text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import magic, { isModuleRegistered, MagicOptions } from '@magic-microservices/magic'; import { renderHtmlTagObjectsToFragment, getHash, IPortalHtmlParserResult, } from '@magic-microservices/portal-utils'; import { Sandbox } from '@garfish/browser-vm'; import { Module } from '@garfish/browser-vm/dist/types'; import md5 from 'blueimp-md5'; import { EventEmitter, EventType } from './EventEmitter'; import { HistoryEventEmitters, HistoryEvents, historySandbox } from './history/sandbox'; import { defaultFetch } from './utils/defaultFetch'; import { PropTypesMap } from '@magic-microservices/magic/dist/src/lib/Heap'; import { LOADING_CONTAINER_ID, loadingStyleCss, loadingDom } from './const/loading'; export interface IPortalManifest extends IPortalHtmlParserResult { renderContent?: string; // for SSR } type ManifestType = string | IPortalManifest; export interface IDefaultPortalProps { manifest?: ManifestType | Promise<ManifestType>; fetch?: (url: string) => Promise<string>; 'initial-path'?: string; 'history-isolation'?: boolean; 'render-dom-id'?: string; overrides?: Record<string, unknown>; } export interface IPortalRegisterOptions< T extends IDefaultPortalProps = IDefaultPortalProps, > { restMagicOptions?: MagicOptions<T>; plugins?: MagicOptions<T>['plugins']; } export interface MagicPortalElement extends HTMLElement, IDefaultPortalProps, EventEmitter { sandbox?: Sandbox; hostEventEmitter: EventEmitter; clientEventEmitter: EventEmitter; historyEventEmitters: HistoryEventEmitters; } export interface IPortalHost { shadowRoot: ShadowRoot; postMessage: EventEmitter['postMessage']; emitEvent: EventEmitter['emitEvent']; addEventListener: EventEmitter['addPortalEventListener']; removeEventListener: EventEmitter['removePortalEventListener']; } export interface IClientWindow extends Window { portalHost?: IPortalHost; } export const PORTAL_HTML_TAG = 'magic-portal'; const historyEvents = ['popstate', 'hashchange'] as const; const rawElementAddEventListener = Element.prototype.addEventListener; const rawElementRemoveEventListener = Element.prototype.removeEventListener; interface IBuildPortalContentParams extends IDefaultPortalProps { container: Element; webcomponentsIns: MagicPortalElement; } async function buildPortalContent({ container, manifest, fetch = defaultFetch, overrides, 'history-isolation': historyIsolation, 'initial-path': initialPath, 'render-dom-id': renderDomId, webcomponentsIns, }: IBuildPortalContentParams) { const { hostEventEmitter, clientEventEmitter, sandbox: oldSandbox } = webcomponentsIns; // clear sideEffect container.innerHTML = ''; clientEventEmitter.emitEvent('beforeServiceUmount'); clientEventEmitter.clean(); oldSandbox?.clearEffects(); // mock head const head = document.createElement('head'); container.appendChild(head); // mock body const body = document.createElement('body'); const bodyContent = document.createDocumentFragment(); // create loading const loadingContainer = document.createElement('div'); loadingContainer.setAttribute('id', LOADING_CONTAINER_ID); loadingContainer.style.position = 'absolute'; loadingContainer.style.width = '100%'; loadingContainer.style.height = '100%'; const loadingStyleDom = document.createElement('style'); loadingStyleDom.appendChild(document.createTextNode(loadingStyleCss)); head.appendChild(loadingStyleDom); loadingContainer.innerHTML += loadingDom; // create render root const renderContainer = document.createElement('div'); renderContainer.setAttribute('id', renderDomId || 'root'); // generate body DOM bodyContent.appendChild(loadingContainer); bodyContent.appendChild(renderContainer); body.appendChild(bodyContent); container.appendChild(body); let manifestJson = (await manifest) as IPortalManifest; if (!manifestJson) { return; } if (typeof manifest === 'string') { manifestJson = JSON.parse(await fetch(manifest)) as IPortalManifest; } const { scripts, styles, renderContent } = manifestJson; const stylesDOMFragment = renderHtmlTagObjectsToFragment(styles); head.appendChild(stylesDOMFragment); // for SSR renderContent && (renderContainer.innerHTML = renderContent); let sandboxModulesOverrides: Module[] = []; if (historyIsolation) { const { location, history, History, historyEventEmitters } = historySandbox( initialPath || window.location.href, ); webcomponentsIns.historyEventEmitters = historyEventEmitters; sandboxModulesOverrides = sandboxModulesOverrides.concat([ () => ({ override: { history, History, }, }), () => ({ override: { location, }, }), ]); } // create sandbox const sandbox = new Sandbox({ el: () => container, protectVariable: () => ['HTMLElement', 'EventTarget', 'Event'], useStrict: false, strictIsolation: true, namespace: md5(JSON.stringify(manifest)) + getHash(), modules: [ // hack garfish sandbox error ...sandboxModulesOverrides, () => ({ override: { module: {}, }, }), () => ({ override: { portalHost: { shadowRoot: webcomponentsIns.shadowRoot, postMessage: hostEventEmitter.postMessage, emitEvent: hostEventEmitter.emitEvent, addEventListener: clientEventEmitter.addPortalEventListener, removeEventListener: clientEventEmitter.removePortalEventListener, }, }, }), ], }); Object.keys(overrides || {}).forEach((key) => { if (sandbox.global && overrides) { // TODO: garfish will fix this type err sandbox.global[key as unknown as number] = overrides[key] as never; } }); if (historyIsolation && sandbox.global) { const { historyEventEmitters } = webcomponentsIns; const rawAddEventListener = sandbox.global.addEventListener; const rawRemoveEventListener = sandbox.global.removeEventListener; const rawDispatchEvent = sandbox.global.dispatchEvent; sandbox.global.dispatchEvent = (event: Event): boolean => { if (event instanceof PopStateEvent || event instanceof HashChangeEvent) { historyEventEmitters.emit( event instanceof PopStateEvent ? 'popstate' : 'hashchange', event instanceof PopStateEvent ? new PopStateEvent('popstate') : new HashChangeEvent('hashchange'), ); return true; } return rawDispatchEvent(event); }; // 重写 historyIsolation 下的 popstate & hashchange 事件监听,保证和 location 表现一致 sandbox.global.addEventListener = ( type: string, listener: EventListener, options?: boolean | AddEventListenerOptions, ): void => { if (historyEvents.includes(type as HistoryEvents)) { return historyEventEmitters.on(type as HistoryEvents, listener); } return rawAddEventListener.call(sandbox.global, type, listener, options); }; sandbox.global.removeEventListener = ( type: string, listener: EventListener, options?: boolean | AddEventListenerOptions, ): void => { if (historyEvents.includes(type as HistoryEvents)) { return historyEventEmitters.off(type as HistoryEvents, listener); } return rawRemoveEventListener.call(sandbox.global, type, listener, options); }; } webcomponentsIns.sandbox = sandbox; /** * proxy script tags */ // 模拟浏览器串行加载执行所有 JS // TODO: 需要让过程更贴合浏览器实现,比如 async & defer & type="module" await scripts?.reduce(async (acc, script) => { await acc; let scriptContent = script.innerHTML; const scriptSrc = script.attributes?.src; if (scriptSrc) { scriptContent = await fetch(scriptSrc); } scriptContent && sandbox.execScript(scriptContent, {}, scriptSrc); }, Promise.resolve()); // close loading loadingContainer.style.display = 'none'; } export function isPortalRegister(): boolean { return isModuleRegistered(PORTAL_HTML_TAG); } export const customElementCompatibility = Object.prototype.toString.call(window.customElements) === '[object CustomElementRegistry]'; export async function portalRegister<T extends IDefaultPortalProps = IDefaultPortalProps>( options: IPortalRegisterOptions<T> = {}, ): Promise<void> { const { restMagicOptions, plugins } = options; if (!customElementCompatibility) { throw new Error('Browser not support web components'); } // register a service component await magic<T>( PORTAL_HTML_TAG, { bootstrap: (webcomponentsIns: MagicPortalElement) => { // 父子通信能力 const host = new EventEmitter(); const client = new EventEmitter(); webcomponentsIns.hostEventEmitter = host; webcomponentsIns.clientEventEmitter = client; webcomponentsIns.postMessage = client.postMessage; webcomponentsIns.emitEvent = client.emitEvent; webcomponentsIns.addPortalEventListener = host.addPortalEventListener; webcomponentsIns.removePortalEventListener = host.removePortalEventListener; webcomponentsIns.addEventListener = ( type: EventType, listener: EventListener, ...args: unknown[] ) => { if (type === 'message') { return host.addPortalEventListener(type, listener); } return rawElementAddEventListener.call( webcomponentsIns, type, listener, ...args, ); }; webcomponentsIns.removeEventListener = ( type: EventType, listener: EventListener, ...args: unknown[] ) => { if (type === 'message') { return host.removePortalEventListener(type, listener); } return rawElementRemoveEventListener.call( webcomponentsIns, type, listener, ...args, ); }; }, mount: async (container, props, webcomponentsIns: MagicPortalElement) => { await buildPortalContent({ ...props, container, webcomponentsIns, }); }, updated: async (attributeName, _propsValue, container, props, webcomponentsIns) => { if (attributeName === 'manifest' || attributeName === 'history-isolation') { await buildPortalContent({ ...props, container, webcomponentsIns, }); } }, unmount: (webcomponentsIns: MagicPortalElement) => { const { hostEventEmitter, clientEventEmitter, sandbox } = webcomponentsIns; clientEventEmitter.emitEvent('beforeServiceUmount'); clientEventEmitter.clean(); hostEventEmitter.clean(); sandbox?.clearEffects(); }, }, { ...(restMagicOptions || {}), shadow: true, plugins: [...(restMagicOptions?.plugins || []), ...(plugins || [])], propTypes: { ...(restMagicOptions?.propTypes || ({} as PropTypesMap<T>)), manifest: Object, fetch: Function, overrides: Object, 'initial-path': String, 'history-isolation': Boolean, }, }, ); } declare global { interface HTMLElementTagNameMap { [PORTAL_HTML_TAG]: MagicPortalElement; } }
the_stack
import { getTimestampWithProcessHRTime } from '../common/time-util'; import { validateArrayElementsNotNull, validateDuplicateKeys, validateMapElementNotNull, validateNotNull, } from '../common/validations'; import { MeasureUnit } from '../stats/types'; import { Cumulative } from './cumulative/cumulative'; import { DerivedCumulative } from './cumulative/derived-cumulative'; import { BaseMetricProducer } from './export/base-metric-producer'; import { LabelKey, LabelValue, Metric, MetricDescriptorType, MetricProducer, Timestamp, } from './export/types'; import { DerivedGauge } from './gauges/derived-gauge'; import { Gauge } from './gauges/gauge'; import { Meter, MetricOptions } from './types'; /** * Creates and manages application's set of metrics. */ export class MetricRegistry { private registeredMetrics: Map<string, Meter> = new Map(); private metricProducer: MetricProducer; private static readonly NAME = 'name'; private static readonly LABEL_KEY = 'labelKey'; private static readonly CONSTANT_LABELS = 'constantLabels'; private static readonly DEFAULT_DESCRIPTION = ''; private static readonly DEFAULT_UNIT = MeasureUnit.UNIT; private static readonly DEFAULT_LABEL_KEYS = []; private static readonly DEFAULT_CONSTANT_LABEL = new Map(); constructor() { this.metricProducer = new MetricProducerForRegistry(this.registeredMetrics); } /** * Builds a new Int64 gauge to be added to the registry. This is more * convenient form when you want to manually increase and decrease values as * per your service requirements. * * @param name The name of the metric. * @param options The options for the metric. * @returns A Int64 Gauge metric. */ addInt64Gauge(name: string, options?: MetricOptions): Gauge { const description = (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; const constantLabels = (options && options.constantLabels) || MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); const labelKeysCopy = Object.assign([], labelKeys); const int64Gauge = new Gauge( validateNotNull(name, MetricRegistry.NAME), description, unit, MetricDescriptorType.GAUGE_INT64, labelKeysCopy, constantLabels ); this.registerMetric(name, int64Gauge); return int64Gauge; } /** * Builds a new double gauge to be added to the registry. This is more * convenient form when you want to manually increase and decrease values as * per your service requirements. * * @param name The name of the metric. * @param options The options for the metric. * @returns A Double Gauge metric. */ addDoubleGauge(name: string, options?: MetricOptions): Gauge { const description = (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; const constantLabels = (options && options.constantLabels) || MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); const labelKeysCopy = Object.assign([], labelKeys); const doubleGauge = new Gauge( validateNotNull(name, MetricRegistry.NAME), description, unit, MetricDescriptorType.GAUGE_DOUBLE, labelKeysCopy, constantLabels ); this.registerMetric(name, doubleGauge); return doubleGauge; } /** * Builds a new derived Int64 gauge to be added to the registry. This is more * convenient form when you want to manually increase and decrease values as * per your service requirements. * * @param name The name of the metric. * @param options The options for the metric. * @returns A Int64 DerivedGauge metric. */ addDerivedInt64Gauge(name: string, options?: MetricOptions): DerivedGauge { const description = (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; const constantLabels = (options && options.constantLabels) || MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); const labelKeysCopy = Object.assign([], labelKeys); const derivedInt64Gauge = new DerivedGauge( validateNotNull(name, MetricRegistry.NAME), description, unit, MetricDescriptorType.GAUGE_INT64, labelKeysCopy, constantLabels ); this.registerMetric(name, derivedInt64Gauge); return derivedInt64Gauge; } /** * Builds a new derived double gauge to be added to the registry. This is more * convenient form when you want to manually increase and decrease values as * per your service requirements. * * @param name The name of the metric. * @param options The options for the metric. * @returns A Double DerivedGauge metric. */ addDerivedDoubleGauge(name: string, options?: MetricOptions): DerivedGauge { const description = (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; const constantLabels = (options && options.constantLabels) || MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); const labelKeysCopy = Object.assign([], labelKeys); const derivedDoubleGauge = new DerivedGauge( validateNotNull(name, MetricRegistry.NAME), description, unit, MetricDescriptorType.GAUGE_DOUBLE, labelKeysCopy, constantLabels ); this.registerMetric(name, derivedDoubleGauge); return derivedDoubleGauge; } /** * Builds a new Int64 cumulative to be added to the registry. This API is * useful when you want to manually increase and reset values as per service * requirements. * * @param name The name of the metric. * @param options The options for the metric. * @returns A Int64 Cumulative metric. */ addInt64Cumulative(name: string, options?: MetricOptions): Cumulative { const description = (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; const constantLabels = (options && options.constantLabels) || MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); const labelKeysCopy = Object.assign([], labelKeys); const int64Cumulative = new Cumulative( validateNotNull(name, MetricRegistry.NAME), description, unit, MetricDescriptorType.CUMULATIVE_INT64, labelKeysCopy, constantLabels ); this.registerMetric(name, int64Cumulative); return int64Cumulative; } /** * Builds a new double cumulative to be added to the registry. This API is * useful when you want to manually increase and reset values as per service * requirements. * * @param name The name of the metric. * @param options The options for the metric. * @returns A Double Cumulative metric. */ addDoubleCumulative(name: string, options?: MetricOptions): Cumulative { const description = (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; const constantLabels = (options && options.constantLabels) || MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); const labelKeysCopy = Object.assign([], labelKeys); const doubleCumulative = new Cumulative( validateNotNull(name, MetricRegistry.NAME), description, unit, MetricDescriptorType.CUMULATIVE_DOUBLE, labelKeysCopy, constantLabels ); this.registerMetric(name, doubleCumulative); return doubleCumulative; } /** * Builds a new derived Int64 Cumulative to be added to the registry. * * @param name The name of the metric. * @param options The options for the metric. * @returns A Int64 DerivedCumulative metric. */ addDerivedInt64Cumulative( name: string, options?: MetricOptions ): DerivedCumulative { const description = (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; const constantLabels = (options && options.constantLabels) || MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); const labelKeysCopy = Object.assign([], labelKeys); const startTime: Timestamp = getTimestampWithProcessHRTime(); const derivedInt64Cumulative = new DerivedCumulative( validateNotNull(name, MetricRegistry.NAME), description, unit, MetricDescriptorType.CUMULATIVE_INT64, labelKeysCopy, constantLabels, startTime ); this.registerMetric(name, derivedInt64Cumulative); return derivedInt64Cumulative; } /** * Builds a new derived Double Cumulative to be added to the registry. * * @param name The name of the metric. * @param options The options for the metric. * @returns A Double DerivedCumulative metric. */ addDerivedDoubleCumulative( name: string, options?: MetricOptions ): DerivedCumulative { const description = (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; const labelKeys = (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; const constantLabels = (options && options.constantLabels) || MetricRegistry.DEFAULT_CONSTANT_LABEL; // TODO(mayurkale): Add support for resource this.validateLables(labelKeys, constantLabels); const labelKeysCopy = Object.assign([], labelKeys); const startTime: Timestamp = getTimestampWithProcessHRTime(); const derivedDoubleCumulative = new DerivedCumulative( validateNotNull(name, MetricRegistry.NAME), description, unit, MetricDescriptorType.CUMULATIVE_DOUBLE, labelKeysCopy, constantLabels, startTime ); this.registerMetric(name, derivedDoubleCumulative); return derivedDoubleCumulative; } /** * Registers metric to register. * * @param name The name of the metric. * @param meter The metric to register. */ private registerMetric(name: string, meter: Meter): void { if (this.registeredMetrics.has(name)) { throw new Error( `A metric with the name ${name} has already been registered.` ); } this.registeredMetrics.set(name, meter); } /** * Gets a metric producer for registry. * * @returns The metric producer. */ getMetricProducer(): MetricProducer { return this.metricProducer; } /** Validates labelKeys and constantLabels. */ private validateLables( labelKeys: LabelKey[], constantLabels: Map<LabelKey, LabelValue> ) { validateArrayElementsNotNull(labelKeys, MetricRegistry.LABEL_KEY); validateMapElementNotNull(constantLabels, MetricRegistry.CONSTANT_LABELS); validateDuplicateKeys(labelKeys, constantLabels); } } /** * A MetricProducerForRegistry is a producer that can be registered for * exporting using MetricProducerManager. */ class MetricProducerForRegistry extends BaseMetricProducer { private registeredMetrics: Map<string, Meter>; constructor(registeredMetrics: Map<string, Meter>) { super(); this.registeredMetrics = registeredMetrics; } /** * Gets a collection of produced Metric`s to be exported. * * @returns The list of metrics. */ getMetrics(): Metric[] { return Array.from(this.registeredMetrics.values()) .map(meter => meter.getMetric()) .filter(meter => !!meter) as Metric[]; } }
the_stack
import { WebviewTag } from 'electron'; import { useCallback, useEffect, useMemo, useRef } from 'react'; import { TransactionConfig } from 'web3-eth'; import { useRecoilValue } from 'recoil'; import Web3 from 'web3'; import { ethers } from 'ethers'; import { signTypedData_v4 } from 'eth-sig-util'; import { TransactionPrepareService } from '../../../service/TransactionPrepareService'; import { walletService } from '../../../service/WalletService'; import { ChainConfig } from './config'; import { DappBrowserIPC } from '../types'; import { evmTransactionSigner } from '../../../service/signers/EvmTransactionSigner'; import { EVMContractCallUnsigned } from '../../../service/signers/TransactionSupported'; import { walletAllAssetsState } from '../../../recoil/atom'; import { getCronosAsset } from '../../../utils/utils'; import { TransactionDataParser } from './TransactionDataParser'; const { shell } = window.require('electron'); type WebView = WebviewTag & HTMLWebViewElement; export type ErrorHandler = (reason: string) => void; interface IUseIPCProviderProps { webview: WebView | null; onRequestAddress: (onSuccess: (address: string) => void, onError: ErrorHandler) => void; onRequestTokenApproval: ( event: DappBrowserIPC.TokenApprovalEvent, onSuccess: (passphrase: string) => void, onError: ErrorHandler, ) => void; onRequestSendTransaction: ( event: DappBrowserIPC.SendTransactionEvent, onSuccess: (passphrase: string) => void, onError: ErrorHandler, ) => Promise<void>; onRequestSignMessage: ( event: DappBrowserIPC.SignMessageEvent, onSuccess: (passphrase: string) => void, onError: ErrorHandler, ) => Promise<void>; onRequestSignPersonalMessage: ( event: DappBrowserIPC.SignPersonalMessageEvent, onSuccess: (passphrase: string) => void, onError: ErrorHandler, ) => Promise<void>; onRequestSignTypedMessage: ( event: DappBrowserIPC.SignTypedMessageEvent, onSuccess: (passphrase: string) => void, onError: ErrorHandler, ) => Promise<void>; onRequestEcRecover: ( event: DappBrowserIPC.EcrecoverEvent, onSuccess: (address: string) => void, onError: ErrorHandler, ) => Promise<void>; onRequestWatchAsset: ( event: DappBrowserIPC.WatchAssetEvent, onSuccess: () => void, onError: ErrorHandler, ) => Promise<void>; onRequestAddEthereumChain: ( event: DappBrowserIPC.AddEthereumChainEvent, onSuccess: () => void, onError: ErrorHandler, ) => Promise<void>; onFinishTransaction: () => void; } export function useRefCallback(fn: Function) { const fnRef = useRef(fn); fnRef.current = fn; return fnRef; } export const useIPCProvider = (props: IUseIPCProviderProps) => { const { webview, onFinishTransaction } = props; const transactionPrepareService = new TransactionPrepareService(walletService.storageService); const allAssets = useRecoilValue(walletAllAssetsState); const cronosAsset = getCronosAsset(allAssets); const transactionDataParser = useMemo(() => { return new TransactionDataParser(ChainConfig.RpcUrl, ChainConfig.ExplorerAPIUrl); }, []); const executeJavScript = useCallback( (script: string) => { webview?.executeJavaScript( ` (function() { ${script} })(); `, ); }, [webview], ); // const injectDomReadyScript = useCallback(() => { // executeJavScript( // ` // var config = { // chainId: ${ChainConfig.chainId}, // rpcUrl: "${ChainConfig.rpcUrl}", // isDebug: true // }; // window.ethereum = new window.desktopWallet.Provider(config); // window.web3 = new window.desktopWallet.Web3(window.ethereum); // `, // ); // }, [webview]); const sendError = (id: number, error: string) => { executeJavScript(` window.ethereum.sendError(${id}, "${error}") `); }; const sendResponse = (id: number, response: string) => { executeJavScript(` window.ethereum.sendResponse(${id}, "${response}") `); }; const sendResponses = (id: number, responses: string[]) => { const script = responses.map(r => `'${r}'`).join(','); executeJavScript(` window.ethereum.sendResponse(${id}, [${script}]) `); }; const handleRequestAccounts = useRefCallback((id: number, address: string) => { executeJavScript( ` window.ethereum.setAddress("${address}"); `, ); sendResponses(id, [address]); }); const handleTokenApproval = useRefCallback( async (event: DappBrowserIPC.TokenApprovalEvent, passphrase: string) => { const prepareTXConfig: TransactionConfig = { from: event.object.from, to: event.object.to, }; const prepareTxInfo = await transactionPrepareService.prepareEVMTransaction( cronosAsset!, prepareTXConfig, ); const data = evmTransactionSigner.encodeTokenApprovalABI( event.object.tokenData.contractAddress, event.object.spender, ethers.constants.MaxUint256, ); const txConfig: EVMContractCallUnsigned = { from: event.object.from, contractAddress: event.object.to, data, gasLimit: String(event.object.gas), gasPrice: event.object.gasPrice, nonce: prepareTxInfo.nonce, }; try { const result = await evmTransactionSigner.sendContractCallTransaction( txConfig, passphrase, ChainConfig.RpcUrl, ); sendResponse(event.id, result); } catch (error) { sendError(event.id, 'Transaction failed'); } onFinishTransaction(); }, ); const handleSendTransaction = useRefCallback( async (event: DappBrowserIPC.SendTransactionEvent, passphrase: string) => { const prepareTXConfig: TransactionConfig = { from: event.object.from, to: event.object.to, }; const prepareTxInfo = await transactionPrepareService.prepareEVMTransaction( cronosAsset!, prepareTXConfig, ); const txConfig: EVMContractCallUnsigned = { from: event.object.from, contractAddress: event.object.to, data: event.object.data, gasLimit: String(event.object.gas), gasPrice: event.object.gasPrice, value: event.object.value, nonce: prepareTxInfo.nonce, }; try { const result = await evmTransactionSigner.sendContractCallTransaction( txConfig, passphrase, ChainConfig.RpcUrl, ); sendResponse(event.id, result); } catch (error) { sendError(event.id, 'Transaction failed'); } onFinishTransaction(); }, ); const handleSignMessage = useRefCallback( async (eventId: number, data: string, passphrase: string, addPrefix: boolean) => { const wallet = ethers.Wallet.fromMnemonic(passphrase); if (addPrefix) { const result = await wallet.signMessage(ethers.utils.arrayify(data)); sendResponse(eventId, result); } else { // deprecated } }, ); const handleSignTypedMessage = useRefCallback( async (event: DappBrowserIPC.SignTypedMessageEvent, passphrase: string) => { const wallet = ethers.Wallet.fromMnemonic(passphrase); const bufferedKey = Buffer.from(wallet.privateKey.replace(/^(0x)/, ''), 'hex'); const sig = signTypedData_v4(bufferedKey, { data: JSON.parse(event.object.raw) }); sendResponse(event.id, sig); }, ); const listenIPCMessages = () => { if (!webview) { return; } webview.addEventListener('ipc-message', async e => { const { channel, args } = e; if (channel !== DappBrowserIPC.ChannelName) { return; } if (args?.length < 1) { return; } const event: DappBrowserIPC.Event = args[0]; switch (event.name) { case 'requestAccounts': props.onRequestAddress( address => { handleRequestAccounts.current(event.id, address); }, reason => { sendError(event.id, reason); }, ); break; case 'signTransaction': // parse transaction data if (event.object.data.startsWith('0x095ea7b3')) { const response = await transactionDataParser.parseTokenApprovalData( event.object.to, event.object.data, ); const approvalEvent: DappBrowserIPC.TokenApprovalEvent = { name: 'tokenApproval', id: event.id, object: { tokenData: response.tokenData, amount: response.amount, gas: event.object.gas, gasPrice: event.object.gasPrice, from: event.object.from, spender: response.spender, to: event.object.to, }, }; props.onRequestTokenApproval( approvalEvent, passphrase => { handleTokenApproval.current(approvalEvent, passphrase); }, reason => { sendError(event.id, reason); }, ); } else { props.onRequestSendTransaction( event, passphrase => { handleSendTransaction.current(event, passphrase); }, reason => { sendError(event.id, reason); }, ); } break; case 'signMessage': props.onRequestSignMessage( event, passphrase => { handleSignMessage.current(event.id, event.object.data, passphrase, false); }, reason => { sendError(event.id, reason); }, ); break; case 'signPersonalMessage': props.onRequestSignPersonalMessage( event, passphrase => { handleSignMessage.current(event.id, event.object.data, passphrase, true); }, reason => { sendError(event.id, reason); }, ); break; case 'signTypedMessage': props.onRequestSignTypedMessage( event, passphrase => { handleSignTypedMessage.current(event, passphrase); }, reason => { sendError(event.id, reason); }, ); break; case 'ecRecover': props.onRequestEcRecover( event, () => { new Web3('').eth.personal .ecRecover(event.object.message, event.object.signature) .then( result => { sendResponse(event.id, result); }, reason => { sendError(event.id, reason); }, ); }, reason => { sendError(event.id, reason); }, ); break; case 'watchAsset': props.onRequestWatchAsset( event, () => {}, reason => { sendError(event.id, reason); }, ); break; case 'addEthereumChain': props.onRequestAddEthereumChain( event, () => {}, reason => { sendError(event.id, reason); }, ); break; default: break; } }); }; const setupIPC = useCallback(() => { if (!webview) { return; } listenIPCMessages(); webview.addEventListener('new-window', e => { e.preventDefault(); shell.openExternal(e.url); }); webview.addEventListener('did-finish-load', () => { // injectDomReadyScript(); if (process.env.NODE_ENV === 'development') { webview.openDevTools(); } }); }, [webview]); useEffect(() => { setupIPC(); }, [setupIPC]); };
the_stack
import { BorderRadiusPrefix, BoxShadowPrefix, ColorPrefix, FontSizePrefix, FontWeightPrefix, LineHeightPrefix, SizingPrefix, SpacePrefix, normalizeVariable } from "../theming"; import { Breakpoint, useMatchedBreakpoints } from "../BreakpointProvider"; import { CSSProperties, useMemo } from "react"; import { Globals, Property } from "csstype"; import { ResponsiveProp, parseResponsiveValue } from "../useResponsiveValue"; import { LiteralUnion } from "type-fest"; import { isNil } from "../../../shared"; /* SYNTAX: // No breakpoint, no pseudo, known value <Button backgroundColor="warning-10">Toto</Button> // No breakpoint, no pseudo, dynamic value <Button backgroundColor="#fff">Toto</Button> // No breakpoint, pseudo, known value <Button backgroundColorHover="warning-10">Toto</Button> // No breakpoint, pseudo, dynamic value <Button backgroundColorHover="#fff">Toto</Button> // Breakpoint, no pseudo, known value <Button backgroundColor={{ s: "warning-10", md: "accent-10", lg: "black" }}>Toto</Button> // Breakpoint, no pseudo, dynamic value <Button backgroundColor={{ s: "warning-10", md: "#fff", lg: "black" }}>Toto</Button> // Breakpoint, pseudo, known value <Button backgroundColorHover={{ s: "warning-10", md: "accent-10", lg: "black" }}>Toto</Button> // Breakpoint, pseudo, dynamic value <Button backgroundColorHover={{ s: "warning-10", md: "#fff", lg: "black" }}>Toto</Button> */ const GlobalValues = [ "inherit", "initial", "revert", "unset" ]; export const ColorExpressionTypes = [ "#", "rgb", "rgba", "hsl", "hsla" ] as const; const SizingScale = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ] as const; const SpacingScale = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ] as const; const OrbitColors = [ "white", "black", "gray", // Purple "purple-1", "purple-2", "purple-3", "purple-4", "purple-5", "purple-6", "purple-7", "purple-8", "purple-9", "purple-10", // Orange "orange-1", "orange-2", "orange-3", "orange-4", "orange-5", "orange-6", "orange-7", "orange-8", "orange-9", "orange-10", // Green "green-1", "green-2", "green-3", "green-4", "green-5", "green-6", "green-7", "green-8", "green-9", "green-10", // Alert "alert-1", "alert-2", "alert-3", "alert-4", "alert-5", "alert-6", "alert-7", "alert-8", "alert-9", "alert-10", // Warning "warning-1", "warning-2", "warning-3", "warning-4", "warning-5", "warning-6", "warning-7", "warning-8", "warning-9", "warning-10", // Success "success-1", "success-2", "success-3", "success-4", "success-5", "success-6", "success-7", "success-8", "success-9", "success-10", // Neutral "neutral-1", "neutral-2", "neutral-3", "neutral-4", "neutral-5", "neutral-6", "neutral-7", "neutral-8", "neutral-9", "neutral-10", // Accent "accent-1", "accent-2", "accent-3", "accent-4", "accent-5", "accent-6", "accent-7", "accent-8", "accent-9", "accent-10" ] as const; const BackgroundColorAliases = [ "alias-default", "alias-soft-break", "alias-hard-break", "alias-mid-break", "alias-basic", "alias-basic-hover", "alias-basic-active", "alias-basic-transparent", "alias-basic-transparent-hover", "alias-basic-transparent-active", "alias-static-white", "alias-grey-hover", "alias-grey-active", "alias-accent", "alias-accent-hover", "alias-accent-active", "alias-accent-faint", "alias-accent-light", "alias-accent-transparent", "alias-accent-transparent-hover", "alias-accent-transparent-active", "alias-alert", "alias-alert-hover", "alias-alert-active", "alias-alert-faint", "alias-alert-light", "alias-alert-transparent", "alias-alert-transparent-hover", "alias-alert-transparent-active", "alias-warning", "alias-warning-hover", "alias-warning-active", "alias-warning-faint", "alias-warning-light", "alias-success", "alias-success-hover", "alias-success-active", "alias-success-faint", "alias-success-light", "alias-transparent", "alias-input-selection" ] as const; const BorderWidthAndStyle = "1px solid"; const BorderColorAliases = [ "alias-low-break", "alias-mid-break", "alias-high-break", "alias-accent", "alias-accent-hover", "alias-accent-active", "alias-alert", "alias-alert-hover", "alias-alert-active", "alias-warning", "alias-warning-hover", "alias-warning-active", "alias-success", "alias-success-hover", "alias-success-active" ] as const; const IconColorAliases = [ "alias-primary", "alias-primary-hover", "alias-secondary", "alias-tertiary", "alias-faint", "alias-accent", "alias-accent-hover", "alias-alert", "alias-alert-hover", "alias-warning", "alias-success", "alias-static-white", "alias-input-placeholder" ] as const; const TextColorAliases = [ "alias-primary", "alias-primary-hover", "alias-secondary", "alias-tertiary", "alias-faint", "alias-accent", "alias-accent-hover", "alias-alert", "alias-alert-hover", "alias-warning", "alias-success", "alias-static-white", "alias-input-placeholder" ] as const; const BorderRadiusScale = [ 0, 1, 2, 3, 4, "pill" ] as const; const BoxShadowScale = [ 1, 2, 3, 4 ] as const; const BoxShadowAliases = [ "alias-floating", "alias-lifted", "alias-raised", "alias-skim" ] as const; const FontSizeScale = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, "headline", "subheadline" ] as const; const FontWeightScale = [ 1, 2, 3 ] as const; const LineHeightScale = [ 1, 2, 3, 4, 5, 6 ] as const; function createValuesMapping<T extends readonly (string | number)[]>(values: T, template: (value: T[number]) => string) { const mapping = {} as Record<T[number], string>; values.reduce((acc, x) => { acc[x] = template(x); return acc; }, mapping); return mapping; } function composePrefixes(...rest) { return rest.reduce((acc, prefix) => { return !isNil(prefix) ? `${acc}${acc !== "" ? "-" : ""}${prefix}` : acc; }, ""); } function createPrefixedValueTemplate(prefix: string) { return (value: string | number) => `var(${normalizeVariable(value, prefix)})`; } export const SpacingMapping = createValuesMapping(SpacingScale, createPrefixedValueTemplate(SpacePrefix)); export const SizingMapping = createValuesMapping(SizingScale, createPrefixedValueTemplate(SizingPrefix)); export const ColorMapping = createValuesMapping(OrbitColors, createPrefixedValueTemplate(ColorPrefix)); export const BackgroundColorMapping = { ...createValuesMapping(BackgroundColorAliases, createPrefixedValueTemplate(composePrefixes(ColorPrefix, "bg"))), ...ColorMapping }; export const BorderMapping = { ...createValuesMapping(BorderColorAliases, value => `${BorderWidthAndStyle} var(${normalizeVariable(value, composePrefixes(ColorPrefix, "b"))})`), ...createValuesMapping(OrbitColors, value => `${BorderWidthAndStyle} var(${normalizeVariable(value, ColorPrefix)})`) }; export const BorderRadiusMapping = createValuesMapping(BorderRadiusScale, createPrefixedValueTemplate(BorderRadiusPrefix)); export const BoxShadowMapping = { ...createValuesMapping(BoxShadowScale, createPrefixedValueTemplate(BoxShadowPrefix)), ...createValuesMapping(BoxShadowAliases, createPrefixedValueTemplate(BoxShadowPrefix)) }; export const FontSizeMapping = createValuesMapping(FontSizeScale, createPrefixedValueTemplate(FontSizePrefix)); const fontVariationSettingsValueTemplate = (value: string | number) => `'wght' var(${normalizeVariable(value, FontWeightPrefix)})`; export const FontWeightMapping = createValuesMapping(FontWeightScale, fontVariationSettingsValueTemplate); export const IconColorMapping = { ...createValuesMapping(IconColorAliases, createPrefixedValueTemplate(composePrefixes(ColorPrefix, "icon"))), ...ColorMapping }; export const LineHeightMapping = createValuesMapping(LineHeightScale, createPrefixedValueTemplate(LineHeightPrefix)); export const TextColorMapping = { ...createValuesMapping(TextColorAliases, createPrefixedValueTemplate(composePrefixes(ColorPrefix, "text"))), ...ColorMapping }; // Custom CSS color type to use instead of Property.Color to offer less useless values in intellisense and // stop showing too many values in props docs. // eslint-disable-next-line @typescript-eslint/ban-types export type CssColor = Globals | "currentcolor" | (string & {}); // Custom fill type to use instead of Property.Fill to offer less useless values in intellisense and // stop showing too many values in props docs. // eslint-disable-next-line @typescript-eslint/ban-types export type Fill = Globals | "child" | "context-fill" | "context-stroke" | "none" | (string & {}); export type BackgroundColorValue = keyof typeof BackgroundColorMapping | CssColor; export type BorderValue = keyof typeof BorderMapping | Property.Border; export type BorderRadiusValue = keyof typeof BorderRadiusMapping | Property.BorderRadius; export type BoxShadowValue = keyof typeof BoxShadowMapping | Property.BoxShadow; export type ColorValue = keyof typeof TextColorMapping | CssColor; export type ColumnGapValue = keyof typeof SpacingMapping | Property.ColumnGap; export type FillValue = keyof typeof IconColorMapping | Fill; export type FontSizeValue = keyof typeof FontSizeMapping | Property.FontSize; export type FontWeightValue = keyof typeof FontWeightMapping | typeof GlobalValues[number]; export type GapValue = keyof typeof SpacingMapping | Property.Gap; export type GridAutoColumnsValue = keyof typeof SizingMapping | Property.GridAutoColumns; export type GridAutoRowsValue = keyof typeof SizingMapping | Property.GridAutoRows; export type GridTemplateColumnsValue = keyof typeof SizingMapping | Property.GridTemplateColumns; export type GridTemplateRowsValue = keyof typeof SizingMapping | Property.GridTemplateRows; export type HeightValue = keyof typeof SizingMapping | Property.Height; export type LineHeightValue = keyof typeof LineHeightMapping | Property.LineHeight; export type MarginValue = keyof typeof SpacingMapping | Property.Margin; export type PaddingValue = keyof typeof SpacingMapping | Property.Padding; export type RowGapValue = keyof typeof SpacingMapping | Property.RowGap; export type SizingValue = LiteralUnion<keyof typeof SizingMapping, string>; export type SpacingValue = LiteralUnion<keyof typeof SpacingMapping, string>; export type StrokeValue = keyof typeof IconColorMapping | Property.Stroke; export type WidthValue = keyof typeof SizingMapping | Property.Width; export type AlignContentProp = ResponsiveProp<Property.AlignContent>; export type AlignItemsProp = ResponsiveProp<Property.AlignItems>; export type AlignSelfProp = ResponsiveProp<Property.AlignSelf>; export type AspectRatioProp = ResponsiveProp<Property.AspectRatio>; export type BackgroundColorProp = ResponsiveProp<BackgroundColorValue>; export type BackgroundImageProp = ResponsiveProp<Property.BackgroundImage>; export type BackgroundPositionProp = ResponsiveProp<Property.BackgroundPosition>; export type BackgroundRepeatProp = ResponsiveProp<Property.BackgroundRepeat>; export type BackgroundSizeProp = ResponsiveProp<Property.BackgroundSize>; export type BorderProp = ResponsiveProp<BorderValue>; export type BorderBottomProp = BorderProp; export type BorderLeftProp = BorderProp; export type BorderRightProp = BorderProp; export type BorderTopProp = BorderProp; export type BorderRadiusProp = ResponsiveProp<BorderRadiusValue>; export type BorderBottomLeftRadiusProp = BorderRadiusProp; export type BorderBottomRightRadiusProp = BorderRadiusProp; export type BorderTopLeftRadiusProp = BorderRadiusProp; export type BorderTopRightRadiusProp = BorderRadiusProp; export type BottomProp = ResponsiveProp<Property.Bottom>; export type BoxShadowProp = ResponsiveProp<BoxShadowValue>; export type ColorProp = ResponsiveProp<ColorValue>; export type ColumnGapProp = ResponsiveProp<ColumnGapValue>; export type ContentProp = ResponsiveProp<Property.Content>; export type ContentVisibilityProp = ResponsiveProp<Property.ContentVisibility>; export type CursorProp = ResponsiveProp<Property.Cursor>; export type DisplayProp = ResponsiveProp<Property.Display>; export type FillProp = ResponsiveProp<FillValue>; export type FilterProp = ResponsiveProp<Property.Filter>; export type FlexProp = ResponsiveProp<Property.Flex>; export type FlexBasisProp = ResponsiveProp<Property.FlexBasis>; export type FlexDirectionProp = ResponsiveProp<Property.FlexDirection>; export type FlexFlowProp = ResponsiveProp<Property.FlexFlow>; export type FlexGrowProp = ResponsiveProp<Property.FlexGrow>; export type FlexShrinkProp = ResponsiveProp<Property.FlexShrink>; export type FlexWrapProp = ResponsiveProp<Property.FlexWrap>; export type FontSizeProp = ResponsiveProp<FontSizeValue>; export type FontStyleProp = ResponsiveProp<Property.FontStyle>; export type FontWeightProp = ResponsiveProp<FontWeightValue>; export type GapProp = ResponsiveProp<GapValue>; export type GridProp = ResponsiveProp<Property.Grid>; export type GridAreaProp = ResponsiveProp<Property.GridArea>; export type GridAutoColumnsProp = ResponsiveProp<GridAutoColumnsValue>; export type GridAutoFlowProp = ResponsiveProp<Property.GridAutoFlow>; export type GridAutoRowsProp = ResponsiveProp<GridAutoRowsValue>; export type GridColumnProp = ResponsiveProp<Property.GridColumn>; export type GridColumnEndProp = ResponsiveProp<Property.GridColumnEnd>; export type GridColumnSpanProp = ResponsiveProp<number>; export type GridColumnStartProp = ResponsiveProp<Property.GridColumnStart>; export type GridRowProp = ResponsiveProp<Property.GridRow>; export type GridRowEndProp = ResponsiveProp<Property.GridRowEnd>; export type GridRowStartProp = ResponsiveProp<Property.GridRowStart>; export type GridRowSpanProp = ResponsiveProp<number>; export type GridTemplateProp = ResponsiveProp<Property.GridTemplate>; export type GridTemplateAreasProp = ResponsiveProp<Property.GridTemplateAreas>; export type GridTemplateColumnsProp = ResponsiveProp<GridTemplateColumnsValue>; export type GridTemplateRowsProp = ResponsiveProp<GridTemplateRowsValue>; export type HeightProp = ResponsiveProp<HeightValue>; export type JustifyContentProp = ResponsiveProp<Property.JustifyContent>; export type JustifyItemsProp = ResponsiveProp<Property.JustifyItems>; export type JustifySelfProp = ResponsiveProp<Property.JustifySelf>; export type LeftProp = ResponsiveProp<Property.Left>; export type LetterSpacingProp = ResponsiveProp<Property.LetterSpacing>; export type LineHeightProp = ResponsiveProp<LineHeightValue>; export type MarginProp = ResponsiveProp<MarginValue>; export type MarginBottomProp = MarginProp; export type MarginLeftProp = MarginProp; export type MarginRightProp = MarginProp; export type MarginTopProp = MarginProp; export type MarginXProp = MarginProp; export type MarginYProp = MarginProp; export type MaxHeightProp = ResponsiveProp<HeightValue>; export type MaxWidthProp = ResponsiveProp<WidthValue>; export type MinHeightProp = ResponsiveProp<HeightValue>; export type MinWidthProp = ResponsiveProp<WidthValue>; export type ObjectFitProp = ResponsiveProp<Property.ObjectFit>; export type ObjectPositionProp = ResponsiveProp<Property.ObjectPosition>; export type OpacityProp = ResponsiveProp<Property.Opacity>; export type OrderProp = ResponsiveProp<Property.Order>; export type OutlineProp = ResponsiveProp<Property.Outline>; export type OverflowProp = ResponsiveProp<Property.Overflow>; export type OverflowXProp = ResponsiveProp<Property.OverflowX>; export type OverflowYProp = ResponsiveProp<Property.OverflowY>; export type PaddingProp = ResponsiveProp<PaddingValue>; export type PaddingBottomProp = PaddingProp; export type PaddingLeftProp = PaddingProp; export type PaddingRightProp = PaddingProp; export type PaddingTopProp = PaddingProp; export type PaddingXProp = PaddingProp; export type PaddingYProp = PaddingProp; export type PointerEventsProp = ResponsiveProp<Property.PointerEvents>; export type PositionProp = ResponsiveProp<Property.Position>; export type ResizeProp = ResponsiveProp<Property.Resize>; export type RightProp = ResponsiveProp<Property.Right>; export type RowGapProp = ResponsiveProp<RowGapValue>; export type StrokeProp = ResponsiveProp<StrokeValue>; export type TextAlignProp = ResponsiveProp<Property.TextAlign | "justify-all">; export type TextDecorationProp = ResponsiveProp<Property.TextDecoration>; export type TextOverflowProp = ResponsiveProp<Property.TextOverflow>; export type TextTransformProp = ResponsiveProp<Property.TextTransform>; export type TopProp = ResponsiveProp<Property.Top>; export type TransformProp = ResponsiveProp<Property.Transform>; export type TransformOriginProp = ResponsiveProp<Property.TransformOrigin>; export type TransformStyleProp = ResponsiveProp<Property.TransformStyle>; export type VerticalAlignProp = ResponsiveProp<Property.VerticalAlign>; export type VisibilityProp = ResponsiveProp<Property.Visibility>; export type WhiteSpaceProp = ResponsiveProp<Property.WhiteSpace>; export type WidthProp = ResponsiveProp<WidthValue>; export type WillChangeProp = ResponsiveProp<Property.WillChange>; export type WordBreakProp = ResponsiveProp<Property.WordBreak>; export type ZIndexProp = ResponsiveProp<Property.ZIndex>; export interface StyledSystemProps { /** * @ignore */ alignContent?: AlignContentProp; /** * @ignore */ alignItems?: AlignItemsProp; /** * @ignore */ alignSelf?: AlignSelfProp; /** * @ignore */ aspectRatio?: AspectRatioProp; /** * @ignore */ backgroundColor?: BackgroundColorProp; /** * @ignore */ backgroundColorActive?: BackgroundColorProp; /** * @ignore */ backgroundColorFocus?: BackgroundColorProp; /** * @ignore */ backgroundColorHover?: BackgroundColorProp; /** * @ignore */ backgroundImage?: BackgroundImageProp; /** * @ignore */ backgroundPosition?: BackgroundPositionProp; /** * @ignore */ backgroundRepeat?: BackgroundRepeatProp; /** * @ignore */ backgroundSize?: BackgroundSizeProp; /** * @ignore */ border?: BorderProp; /** * @ignore */ borderBottom?: BorderBottomProp; /** * @ignore */ borderBottomActive?: BorderBottomProp; /** * @ignore */ borderBottomFocus?: BorderBottomProp; /** * @ignore */ borderBottomHover?: BorderBottomProp; /** * @ignore */ borderBottomLeftRadius?: BorderRadiusProp; /** * @ignore */ borderBottomRightRadius?: BorderRadiusProp; /** * @ignore */ borderActive?: BorderProp; /** * @ignore */ borderFocus?: BorderProp; /** * @ignore */ borderHover?: BorderProp; /** * @ignore */ borderLeft?: BorderLeftProp; /** * @ignore */ borderLeftActive?: BorderLeftProp; /** * @ignore */ borderLeftFocus?: BorderLeftProp; /** * @ignore */ borderLeftHover?: BorderLeftProp; /** * @ignore */ borderRadius?: BorderRadiusProp; /** * @ignore */ borderRight?: BorderRightProp; /** * @ignore */ borderRightActive?: BorderRightProp; /** * @ignore */ borderRightFocus?: BorderRightProp; /** * @ignore */ borderRightHover?: BorderRightProp; /** * @ignore */ borderTop?: BorderTopProp; /** * @ignore */ borderTopActive?: BorderTopProp; /** * @ignore */ borderTopFocus?: BorderTopProp; /** * @ignore */ borderTopHover?: BorderTopProp; /** * @ignore */ borderTopLeftRadius?: BorderRadiusProp; /** * @ignore */ borderTopRightRadius?: BorderRadiusProp; /** * @ignore */ bottom?: BottomProp; /** * @ignore */ boxShadow?: BoxShadowProp; /** * @ignore */ boxShadowActive?: BoxShadowProp; /** * @ignore */ boxShadowFocus?: BoxShadowProp; /** * @ignore */ boxShadowHover?: BoxShadowProp; /** * @ignore */ color?: ColorProp; /** * @ignore */ colorActive?: ColorProp; /** * @ignore */ colorFocus?: ColorProp; /** * @ignore */ colorHover?: ColorProp; /** * @ignore */ columnGap?: ColumnGapProp; /** * @ignore */ content?: ContentProp; /** * @ignore */ contentVisibility?: ContentVisibilityProp; /** * @ignore */ cursor?: CursorProp; /** * @ignore */ cursorHover?: CursorProp; /** * @ignore */ display?: DisplayProp; /** * @ignore */ fill?: FillProp; /** * @ignore */ fillFocus?: FillProp; /** * @ignore */ fillHover?: FillProp; /** * @ignore */ filter?: FilterProp; /** * @ignore */ flex?: FlexProp; /** * @ignore */ flexBasis?: FlexBasisProp; /** * @ignore */ flexDirection?: FlexDirectionProp; /** * @ignore */ flexFlow?: FlexFlowProp; /** * @ignore */ flexGrow?: FlexGrowProp; /** * @ignore */ flexShrink?: FlexShrinkProp; /** * @ignore */ flexWrap?: FlexWrapProp; /** * @ignore */ fontSize?: FontSizeProp; /** * @ignore */ fontStyle?: FontStyleProp; /** * @ignore */ fontWeight?: FontWeightProp; /** * @ignore */ gap?: GapProp; /** * @ignore */ grid?: GridProp; /** * @ignore */ gridArea?: GridAreaProp; /** * @ignore */ gridAutoColumns?: GridAutoColumnsProp; /** * @ignore */ gridAutoFlow?: GridAutoFlowProp; /** * @ignore */ gridAutoRows?: GridAutoRowsProp; /** * @ignore */ gridColumn?: GridColumnProp; /** * @ignore */ gridColumnEnd?: GridColumnEndProp; /** * @ignore */ gridColumnSpan?: GridColumnSpanProp; /** * @ignore */ gridColumnStart?: GridColumnStartProp; /** * @ignore */ gridRow?: GridRowProp; /** * @ignore */ gridRowEnd?: GridRowEndProp; /** * @ignore */ gridRowSpan?: GridRowSpanProp; /** * @ignore */ gridRowStart?: GridRowStartProp; /** * @ignore */ gridTemplate?: GridTemplateProp; /** * @ignore */ gridTemplateAreas?: GridTemplateAreasProp; /** * @ignore */ gridTemplateColumns?: GridTemplateColumnsProp; /** * @ignore */ gridTemplateRows?: GridTemplateRowsProp; /** * @ignore */ height?: HeightProp; /** * @ignore */ justifyContent?: JustifyContentProp; /** * @ignore */ justifyItems?: JustifyItemsProp; /** * @ignore */ justifySelf?: JustifySelfProp; /** * @ignore */ left?: LeftProp; /** * @ignore */ letterSpacing?: LetterSpacingProp; /** * @ignore */ lineHeight?: LineHeightProp; /** * @ignore */ margin?: MarginProp; /** * @ignore */ marginBottom?: MarginBottomProp; /** * @ignore */ marginLeft?: MarginLeftProp; /** * @ignore */ marginRight?: MarginRightProp; /** * @ignore */ marginTop?: MarginTopProp; /** * @ignore */ marginX?: MarginXProp; /** * @ignore */ marginY?: MarginYProp; /** * @ignore */ maxHeight?: MaxHeightProp; /** * @ignore */ maxWidth?: MaxWidthProp; /** * @ignore */ minHeight?: MinHeightProp; /** * @ignore */ minWidth?: MinWidthProp; /** * @ignore */ objectFit?: ObjectFitProp; /** * @ignore */ objectPosition?: ObjectPositionProp; /** * @ignore */ opacity?: OpacityProp; /** * @ignore */ opacityActive?: OpacityProp; /** * @ignore */ opacityFocus?: OpacityProp; /** * @ignore */ opacityHover?: OpacityProp; /** * @ignore */ order?: OrderProp; /** * @ignore */ outline?: OutlineProp; /** * @ignore */ outlineFocus?: OutlineProp; /** * @ignore */ overflow?: OverflowProp; /** * @ignore */ overflowX?: OverflowXProp; /** * @ignore */ overflowY?: OverflowYProp; /** * @ignore */ padding?: PaddingProp; /** * @ignore */ paddingBottom?: PaddingBottomProp; /** * @ignore */ paddingLeft?: PaddingLeftProp; /** * @ignore */ paddingRight?: PaddingRightProp; /** * @ignore */ paddingTop?: PaddingTopProp; /** * @ignore */ paddingX?: PaddingXProp; /** * @ignore */ paddingY?: PaddingYProp; /** * @ignore */ pointerEvents?: PointerEventsProp; /** * @ignore */ position?: PositionProp; /** * @ignore */ resize?: ResizeProp; /** * @ignore */ right?: RightProp; /** * @ignore */ rowGap?: RowGapProp; /** * @ignore */ stroke?: StrokeProp; /** * @ignore */ textAlign?: TextAlignProp; /** * @ignore */ textDecoration?: TextDecorationProp; /** * @ignore */ textOverflow?: TextOverflowProp; /** * @ignore */ textTransform?: TextTransformProp; /** * @ignore */ top?: TopProp; /** * @ignore */ transform?: TransformProp; /** * @ignore */ transformOrigin?: TransformOriginProp; /** * @ignore */ transformStyle?: TransformStyleProp; /** * @ignore */ verticalAlign?: VerticalAlignProp; /** * @ignore */ visibility?: VisibilityProp; /** * @ignore */ whiteSpace?: WhiteSpaceProp; /** * @ignore */ width?: WidthProp; /** * @ignore */ willChange?: WillChangeProp; /** * @ignore */ wordBreak?: WordBreakProp; /** * @ignore */ zIndex?: ZIndexProp; } class StylingContext { private classes: string[]; private style: Record<string, any>; matchedBreakpoints: Breakpoint[]; constructor(className: string, style: CSSProperties, matchedBreakpoints: Breakpoint[]) { this.classes = !isNil(className) ? [className] : []; this.style = style ?? {}; this.matchedBreakpoints = matchedBreakpoints; } addClass(className: string) { if (!this.classes.includes(className)) { this.classes.push(className); } } addStyleValue(name: string, value: any) { if (isNil(this.style[name])) { this.style[name] = value; } } computeStyling() { const className = this.classes.length !== 0 ? this.classes.join(" ") : undefined; const styleValue = Object.keys(this.style).length !== 0 ? this.style : undefined; return { className, style: styleValue }; } } type PropHandler<TValue> = (name: string, value: TValue, context: StylingContext) => void; function getSystemValue<T extends Record<string | number, string>>(value: keyof T, systemValues: T) { return systemValues[value as keyof typeof systemValues]; } export function getSizingValue(value: string | keyof typeof SizingMapping) { const systemValue = getSystemValue(value as keyof typeof SizingMapping, SizingMapping); return systemValue ?? value; } function parseResponsiveSystemValue<TValue extends string | number>(value: TValue, systemValues: Record<TValue, string>, matchedBreakpoints: Breakpoint[]) { if (isNil(value)) { return value; } // Quick lookup since most values will be a non responsive system value and will not requires to parse for a responsive value. const systemValue = getSystemValue(value, systemValues); if (!isNil(systemValue)) { return systemValue; } const underlyingValue = parseResponsiveValue(value, matchedBreakpoints); if (!isNil(underlyingValue)) { const underlyingSystemValue = getSystemValue(underlyingValue, systemValues); if (!isNil(underlyingSystemValue)) { return underlyingSystemValue; } } return underlyingValue; } function createHandler<TValue extends string | number>(systemValues?: Record<TValue, string>): PropHandler<TValue> { const systemValueHandler: PropHandler<TValue> = (name, value, context) => { const parsedValue = parseResponsiveSystemValue(value, systemValues, context.matchedBreakpoints); if (!isNil(parsedValue)) { context.addStyleValue(name, parsedValue); } }; const passThroughHandler: PropHandler<TValue> = (name, value, context: StylingContext) => { const parsedValue = parseResponsiveValue(value, context.matchedBreakpoints); if (!isNil(parsedValue)) { context.addStyleValue(name, parsedValue); } }; return !isNil(systemValues) ? systemValueHandler : passThroughHandler; } function createPseudoHandler<TValue extends string | number>(pseudoClassName, pseudoVariable, systemValues?: Record<TValue, string>): PropHandler<TValue> { const systemValueHandler: PropHandler<TValue> = (name, value, context) => { const parsedValue = parseResponsiveSystemValue(value, systemValues, context.matchedBreakpoints); if (!isNil(parsedValue)) { context.addClass(pseudoClassName); context.addStyleValue(pseudoVariable, parsedValue); } }; const passThroughHandler: PropHandler<TValue> = (name, value, context) => { const parsedValue = parseResponsiveValue(value, context.matchedBreakpoints); if (!isNil(parsedValue)) { context.addClass(pseudoClassName); context.addStyleValue(pseudoVariable, parsedValue); } }; return !isNil(systemValues) ? systemValueHandler : passThroughHandler; } // Custom handler for borders to allow the following syntax: // - border="warning-10" -> style="1px solid var(--o-ui-warning-10)" // - border="hsla(223, 12%, 87%, 1)" -> style="1px solid hsla(223, 12%, 87%, 1)" function createBorderHandler<TValue extends string>(systemValues: Record<TValue, string>): PropHandler<TValue> { return (name, value, context) => { const parsedValue = parseResponsiveSystemValue(value, systemValues, context.matchedBreakpoints); if (!isNil(parsedValue)) { if (ColorExpressionTypes.some(x => parsedValue.startsWith(x))) { context.addStyleValue(name, `${BorderWidthAndStyle} ${parsedValue}`); } else { context.addStyleValue(name, parsedValue); } } }; } function createBorderPseudoHandler<TValue extends string>(pseudoClassName: string, pseudoVariable: string, systemValues: Record<TValue, string>): PropHandler<TValue> { return (name, value, context) => { const parsedValue = parseResponsiveSystemValue(value, systemValues, context.matchedBreakpoints); if (!isNil(parsedValue)) { context.addClass(pseudoClassName); if (ColorExpressionTypes.some(x => parsedValue.startsWith(x))) { context.addStyleValue(pseudoVariable, `${BorderWidthAndStyle} ${parsedValue}`); } else { context.addStyleValue(pseudoVariable, parsedValue); } } }; } // Custom handler for font-weight because of "fontVariationSettings". const fontWeightHandler: PropHandler<string | number> = (name, value, context) => { const parsedValue = parseResponsiveSystemValue(value, FontWeightMapping, context.matchedBreakpoints); if (!isNil(parsedValue)) { context.addStyleValue("fontVariationSettings", parsedValue); if (!GlobalValues.includes(parsedValue as string)) { context.addStyleValue("fontWeight", "400"); } } }; const gridColumnSpanHandler: PropHandler<string | number> = (name, value, context) => { const parsedValue = parseResponsiveValue(value, context.matchedBreakpoints); if (!isNil(parsedValue)) { context.addStyleValue("gridColumn", `span ${parsedValue} / span ${parsedValue}`); } }; const gridRowSpanHandler: PropHandler<string | number> = (name, value, context) => { const parsedValue = parseResponsiveValue(value, context.matchedBreakpoints); if (!isNil(parsedValue)) { context.addStyleValue("gridRow", `span ${parsedValue} / span ${parsedValue}`); } }; function createAxisHandler<TValue extends string>(firstPropName: string, secondPropName: string, systemValues: Record<TValue, string>): PropHandler<TValue> { const firstHandler = createHandler(systemValues); const secondHandler = createHandler(systemValues); return (name, value, context) => { firstHandler(firstPropName, value, context); secondHandler(secondPropName, value, context); }; } const PropsHandlers: Record<string, PropHandler<unknown>> = { alignContent: createHandler(), alignItems: createHandler(), alignSelf: createHandler(), aspectRatio: createHandler(), backgroundColor: createHandler(BackgroundColorMapping), backgroundColorActive: createPseudoHandler("o-ui-bg-active", "--o-ui-bg-active", BackgroundColorMapping), backgroundColorFocus: createPseudoHandler("o-ui-bg-focus", "--o-ui-bg-focus", BackgroundColorMapping), backgroundColorHover: createPseudoHandler("o-ui-bg-hover", "--o-ui-bg-hover", BackgroundColorMapping), backgroundImage: createHandler(), backgroundPosition: createHandler(), backgroundRepeat: createHandler(), backgroundSize: createHandler(), border: createBorderHandler(BorderMapping), borderBottom: createBorderHandler(BorderMapping), borderBottomActive: createBorderPseudoHandler("o-ui-bb-active", "--o-ui-bb-active", BorderMapping), borderBottomFocus: createBorderPseudoHandler("o-ui-bb-focus", "--o-ui-bb-focus", BorderMapping), borderBottomHover: createBorderPseudoHandler("o-ui-bb-hover", "--o-ui-bb-hover", BorderMapping), borderBottomLeftRadius: createHandler(BorderRadiusMapping), borderBottomRightRadius: createHandler(BorderRadiusMapping), borderActive: createBorderPseudoHandler("o-ui-b-active", "--o-ui-b-active", BorderMapping), borderFocus: createBorderPseudoHandler("o-ui-b-focus", "--o-ui-b-focus", BorderMapping), borderHover: createBorderPseudoHandler("o-ui-b-hover", "--o-ui-b-hover", BorderMapping), borderLeft: createBorderHandler(BorderMapping), borderLeftActive: createBorderPseudoHandler("o-ui-bl-active", "--o-ui-bl-active", BorderMapping), borderLeftFocus: createBorderPseudoHandler("o-ui-bl-focus", "--o-ui-bl-focus", BorderMapping), borderLeftHover: createBorderPseudoHandler("o-ui-bl-hover", "--o-ui-bl-hover", BorderMapping), borderRadius: createHandler(BorderRadiusMapping), borderRight: createBorderHandler(BorderMapping), borderRightActive: createBorderPseudoHandler("o-ui-br-active", "--o-ui-br-active", BorderMapping), borderRightFocus: createBorderPseudoHandler("o-ui-br-focus", "--o-ui-br-focus", BorderMapping), borderRightHover: createBorderPseudoHandler("o-ui-br-hover", "--o-ui-br-hover", BorderMapping), borderTop: createBorderHandler(BorderMapping), borderTopActive: createBorderPseudoHandler("o-ui-bt-active", "--o-ui-bt-active", BorderMapping), borderTopFocus: createBorderPseudoHandler("o-ui-bt-focus", "--o-ui-bt-focus", BorderMapping), borderTopHover: createBorderPseudoHandler("o-ui-bt-hover", "--o-ui-bt-hover", BorderMapping), borderTopLeftRadius: createHandler(BorderRadiusMapping), borderTopRightRadius: createHandler(BorderRadiusMapping), bottom: createHandler(), boxShadow: createHandler(BoxShadowMapping), boxShadowActive: createPseudoHandler("o-ui-bs-active", "--o-ui-bs-active", BoxShadowMapping), boxShadowFocus: createPseudoHandler("o-ui-bs-focus", "--o-ui-bs-focus", BoxShadowMapping), boxShadowHover: createPseudoHandler("o-ui-bs-hover", "--o-ui-bs-hover", BoxShadowMapping), color: createHandler(TextColorMapping), colorActive: createPseudoHandler("o-ui-c-active", "--o-ui-c-active", TextColorMapping), colorFocus: createPseudoHandler("o-ui-c-focus", "--o-ui-c-focus", TextColorMapping), colorHover: createPseudoHandler("o-ui-c-hover", "--o-ui-c-hover", TextColorMapping), columnGap: createHandler(SpacingMapping), content: createHandler(), contentVisibility: createHandler(), cursor: createHandler(), cursorHover: createPseudoHandler("o-ui-cs-hover", "--o-ui-cs-hover"), display: createHandler(), fill: createHandler(IconColorMapping), fillFocus: createPseudoHandler("o-ui-f-focus", "--o-ui-f-focus", IconColorMapping), fillHover: createPseudoHandler("o-ui-f-hover", "--o-ui-f-hover", IconColorMapping), filter: createHandler(), flex: createHandler(), flexBasis: createHandler(), flexDirection: createHandler(), flexFlow: createHandler(), flexGrow: createHandler(), flexShrink: createHandler(), flexWrap: createHandler(), fontSize: createHandler(FontSizeMapping), fontStyle: createHandler(), fontWeight: fontWeightHandler, gap: createHandler(SpacingMapping), grid: createHandler(), gridArea: createHandler(), gridAutoColumns: createHandler(SizingMapping), gridAutoFlow: createHandler(), gridAutoRows: createHandler(SizingMapping), gridColumn: createHandler(), gridColumnEnd: createHandler(), gridColumnSpan: gridColumnSpanHandler, gridColumnStart: createHandler(), gridRow: createHandler(), gridRowEnd: createHandler(), gridRowSpan: gridRowSpanHandler, gridRowStart: createHandler(), gridTemplate: createHandler(), gridTemplateAreas: createHandler(), gridTemplateColumns: createHandler(SizingMapping), gridTemplateRows: createHandler(SizingMapping), height: createHandler(SizingMapping), justifyContent: createHandler(), justifyItems: createHandler(), justifySelf: createHandler(), left: createHandler(), letterSpacing: createHandler(), lineHeight: createHandler(LineHeightMapping), margin: createHandler(SpacingMapping), marginBottom: createHandler(SpacingMapping), marginLeft: createHandler(SpacingMapping), marginRight: createHandler(SpacingMapping), marginTop: createHandler(SpacingMapping), marginX: createAxisHandler("marginLeft", "marginRight", SpacingMapping), marginY: createAxisHandler("marginBottom", "marginTop", SpacingMapping), maxHeight: createHandler(SizingMapping), maxWidth: createHandler(SizingMapping), minHeight: createHandler(SizingMapping), minWidth: createHandler(SizingMapping), objectFit: createHandler(), objectPosition: createHandler(), opacity: createHandler(), opacityActive: createPseudoHandler("o-ui-o-active", "o-ui-o-active"), opacityFocus: createPseudoHandler("o-ui-o-focus", "o-ui-o-focus"), opacityHover: createPseudoHandler("o-ui-o-hover", "o-ui-o-hover"), order: createHandler(), outline: createHandler(), outlineFocus: createPseudoHandler("o-ui-ol-focus", "o-ui-ol-focus"), overflow: createHandler(), overflowX: createHandler(), overflowY: createHandler(), padding: createHandler(SpacingMapping), paddingBottom: createHandler(SpacingMapping), paddingLeft: createHandler(SpacingMapping), paddingRight: createHandler(SpacingMapping), paddingTop: createHandler(SpacingMapping), paddingX: createAxisHandler("paddingLeft", "paddingRight", SpacingMapping), paddingY: createAxisHandler("paddingBottom", "paddingTop", SpacingMapping), pointerEvents: createHandler(), position: createHandler(), resize: createHandler(), right: createHandler(), rowGap: createHandler(SpacingMapping), stroke: createHandler(IconColorMapping), textAlign: createHandler(), textDecoration: createHandler(), textOverflow: createHandler(), textTransform: createHandler(), top: createHandler(), transform: createHandler(), transformOrigin: createHandler(), transformStyle: createHandler(), verticalAlign: createHandler(), visibility: createHandler(), whiteSpace: createHandler(), width: createHandler(SizingMapping), willChange: createHandler(), wordBreak: createHandler(), zIndex: createHandler() }; export function useStyledSystem<TProps extends Record<string, any>>(props: TProps) { const { alignContent, alignItems, alignSelf, aspectRatio, backgroundColor, backgroundColorActive, backgroundColorFocus, backgroundColorHover, backgroundImage, backgroundPosition, backgroundRepeat, backgroundSize, border, borderBottom, borderBottomActive, borderBottomFocus, borderBottomHover, borderBottomLeftRadius, borderBottomRightRadius, borderFocus, borderHover, borderActive, borderLeft, borderLeftActive, borderLeftFocus, borderLeftHover, borderRadius, borderRight, borderRightActive, borderRightFocus, borderRightHover, borderTop, borderTopActive, borderTopFocus, borderTopHover, borderTopLeftRadius, borderTopRightRadius, bottom, boxShadow, boxShadowActive, boxShadowFocus, boxShadowHover, className, color, colorActive, colorFocus, colorHover, columnGap, content, contentVisibility, cursor, cursorHover, display, fill, fillFocus, fillHover, filter, flex, flexBasis, flexDirection, flexFlow, flexGrow, flexShrink, flexWrap, fontSize, fontStyle, fontWeight, gap, grid, gridArea, gridAutoColumns, gridAutoFlow, gridAutoRows, gridColumn, gridColumnEnd, gridColumnSpan, gridColumnStart, gridRow, gridRowEnd, gridRowSpan, gridRowStart, gridTemplate, gridTemplateAreas, gridTemplateColumns, gridTemplateRows, height, justifyContent, justifyItems, justifySelf, left, letterSpacing, lineHeight, margin, marginBottom, marginLeft, marginRight, marginTop, marginX, marginY, maxHeight, maxWidth, minHeight, minWidth, objectFit, objectPosition, opacity, opacityActive, opacityFocus, opacityHover, order, outline, outlineFocus, overflow, overflowX, overflowY, padding, paddingBottom, paddingLeft, paddingRight, paddingTop, paddingX, paddingY, pointerEvents, position, resize, right, rowGap, stroke, style, textAlign, textDecoration, textOverflow, textTransform, top, transform, transformOrigin, transformStyle, verticalAlign, visibility, whiteSpace, width, willChange, wordBreak, zIndex, ...rest } = props; const matchedBreakpoints = useMatchedBreakpoints(); // We don't have to add "props" as a dependency because useStyledSystem return the "rest" which is all the props that are not already a dependency // of this memoization. If we do add props, the memoization will refresh on every render, which is bad, so don't do it. /* eslint-disable react-hooks/exhaustive-deps */ const styling = useMemo(() => { const context = new StylingContext(className, style, matchedBreakpoints); Object.keys(props).forEach(key => { const value = props[key]; if (!isNil(value)) { const handler = PropsHandlers[key]; if (!isNil(handler)) { handler(key, value, context); } } }); return context.computeStyling(); }, [ alignContent, alignItems, alignSelf, aspectRatio, backgroundColor, backgroundColorActive, backgroundColorFocus, backgroundColorHover, backgroundImage, backgroundPosition, backgroundRepeat, backgroundSize, border, borderBottom, borderBottomActive, borderBottomFocus, borderBottomHover, borderLeft, borderLeftActive, borderLeftFocus, borderLeftHover, borderRight, borderRightActive, borderRightFocus, borderRightHover, borderTop, borderTopActive, borderTopFocus, borderTopHover, borderActive, borderFocus, borderHover, borderRadius, borderBottomLeftRadius, borderBottomRightRadius, borderTopLeftRadius, borderTopRightRadius, boxShadow, boxShadowActive, boxShadowFocus, boxShadowHover, bottom, matchedBreakpoints, className, color, colorActive, colorFocus, colorHover, columnGap, content, contentVisibility, cursor, cursorHover, display, fill, fillFocus, fillHover, filter, flex, flexBasis, flexDirection, flexFlow, flexGrow, flexShrink, flexWrap, fontSize, fontStyle, fontWeight, gap, grid, gridArea, gridAutoColumns, gridAutoFlow, gridAutoRows, gridColumn, gridColumnEnd, gridColumnSpan, gridColumnStart, gridRow, gridRowEnd, gridRowSpan, gridRowStart, gridTemplate, gridTemplateAreas, gridTemplateColumns, gridTemplateRows, height, justifyContent, justifyItems, justifySelf, left, letterSpacing, lineHeight, margin, marginBottom, marginLeft, marginRight, marginTop, marginX, marginY, maxHeight, maxWidth, minHeight, minWidth, objectFit, objectPosition, opacity, opacityActive, opacityFocus, opacityHover, order, outline, outlineFocus, overflow, overflowX, overflowY, padding, paddingBottom, paddingLeft, paddingRight, paddingTop, paddingX, paddingY, pointerEvents, position, resize, right, rowGap, stroke, style, textAlign, textDecoration, textOverflow, textTransform, top, transform, transformOrigin, transformStyle, verticalAlign, visibility, whiteSpace, width, willChange, wordBreak, zIndex ]); /* eslint-enable react-hooks/exhaustive-deps */ return { ...rest, className: styling.className, style: styling.style } as Omit<TProps, keyof StyledSystemProps>; }
the_stack
import dedent from "dedent"; import type { ValidTestCase } from "~/tests/helpers/util"; const tests: ReadonlyArray<ValidTestCase> = [ // Should not fail on explicit ReadonlyArray parameter. { code: dedent` function foo(...numbers: ReadonlyArray<number>) { } `, optionsSet: [[]], }, { code: dedent` function foo(...numbers: readonly number[]) { } `, optionsSet: [[]], }, // Should not fail on explicit ReadonlyArray return type. { code: dedent` function foo(): ReadonlyArray<number> { return [1, 2, 3]; } `, optionsSet: [[]], }, { code: dedent` const foo = (): ReadonlyArray<number> => { return [1, 2, 3]; } `, optionsSet: [[]], }, // ReadonlyArray Tuple. { code: dedent` function foo(tuple: readonly [number, string, readonly [number, string]]) { } `, optionsSet: [[]], }, // Should not fail on ReadonlyArray type alias. { code: `type Foo = ReadonlyArray<string>;`, optionsSet: [[]], }, // Should not fail on ReadonlyArray type alias in local type. { code: dedent` function foo() { type Foo = ReadonlyArray<string>; } `, optionsSet: [[]], }, // Should not fail on ReadonlyArray in variable declaration. { code: `const foo: ReadonlyArray<string> = [];`, optionsSet: [[]], }, // Allow return type. { code: dedent` function foo(...numbers: ReadonlyArray<number>): Array<number> {} function bar(...numbers: readonly number[]): number[] {} `, optionsSet: [[{ allowMutableReturnType: true }]], }, // Allow return type. { code: dedent` const foo = function(...numbers: ReadonlyArray<number>): Array<number> {} const bar = function(...numbers: readonly number[]): number[] {} `, optionsSet: [[{ allowMutableReturnType: true }]], }, // Allow return type. { code: dedent` const foo = (...numbers: ReadonlyArray<number>): Array<number> => {} const bar = (...numbers: readonly number[]): number[] => {} `, optionsSet: [[{ allowMutableReturnType: true }]], }, // Allow return type. { code: dedent` class Foo { foo(...numbers: ReadonlyArray<number>): Array<number> { } } class Bar { foo(...numbers: readonly number[]): number[] { } } `, optionsSet: [[{ allowMutableReturnType: true }]], }, // Allow return type with Type Arguments. { code: dedent` function foo(...numbers: ReadonlyArray<number>): Promise<Array<number>> {} function foo(...numbers: ReadonlyArray<number>): Promise<number[]> {} `, optionsSet: [[{ allowMutableReturnType: true }]], }, // Allow return type with deep Type Arguments. { code: dedent` type Foo<T> = { readonly x: T; }; function foo(...numbers: ReadonlyArray<number>): Promise<Foo<Array<number>>> {} function foo(...numbers: ReadonlyArray<number>): Promise<Foo<number[]>> {} `, optionsSet: [[{ allowMutableReturnType: true }]], }, // Allow return type with Type Arguments in a tuple. { code: dedent` function foo(...numbers: ReadonlyArray<number>): readonly [number, Array<number>, number] {} function foo(...numbers: ReadonlyArray<number>): readonly [number, number[], number] {} `, optionsSet: [[{ allowMutableReturnType: true }]], }, // Allow return type with Type Arguments Union. { code: dedent` function foo(...numbers: ReadonlyArray<number>): { readonly a: Array<number> } | { readonly b: string[] } {} `, optionsSet: [[{ allowMutableReturnType: true }]], }, // Allow return type with Type Arguments Intersection. { code: dedent` function foo(...numbers: ReadonlyArray<number>): { readonly a: Array<number> } & { readonly b: string[] } {} `, optionsSet: [[{ allowMutableReturnType: true }]], }, // Allow return type with Type Arguments Conditional. { code: dedent` function foo<T>(x: T): T extends Array<number> ? string : number[] {} `, optionsSet: [[{ allowMutableReturnType: true }]], }, // Allow inline mutable return type. { code: dedent` function foo(bar: string): { baz: number } { return 1 as any; } `, optionsSet: [[{ allowMutableReturnType: true }]], }, // Should not fail on implicit ReadonlyArray type in variable declaration. { code: dedent` const foo = [1, 2, 3] as const `, optionsSet: [[{ checkImplicit: true }]], }, // Should not fail on implicit Array. { code: dedent` const foo = [1, 2, 3] function bar(param = [1, 2, 3]) {} `, optionsSet: [[]], }, // Interface with readonly modifiers should not produce failures. { code: dedent` interface Foo { readonly a: number, readonly b: ReadonlyArray<string>, readonly c: () => string, readonly d: { readonly [key: string]: string }, readonly [key: string]: string, } `, optionsSet: [[]], }, // PropertySignature and IndexSignature members without readonly modifier // should produce failures. Also verify that nested members are checked. { code: dedent` interface Foo { readonly a: number, readonly b: ReadonlyArray<string>, readonly c: () => string, readonly d: { readonly [key: string]: string }, readonly [key: string]: string, readonly e: { readonly a: number, readonly b: ReadonlyArray<string>, readonly c: () => string, readonly d: { readonly [key: string]: string }, readonly [key: string]: string, } } `, optionsSet: [[]], }, // Class with parameter properties. { code: dedent` class Klass { constructor ( nonParameterProp: string, readonly readonlyProp: string, public readonly publicReadonlyProp: string, protected readonly protectedReadonlyProp: string, private readonly privateReadonlyProp: string, ) { } } `, optionsSet: [[]], }, // CallSignature and MethodSignature cannot have readonly modifiers and should // not produce failures. { code: dedent` interface Foo { (): void foo(): void } `, optionsSet: [[]], }, // The literal with indexer with readonly modifier should not produce failures. { code: `let foo: { readonly [key: string]: number };`, optionsSet: [[]], }, // Type literal in array template parameter with readonly should not produce failures. { code: `type foo = ReadonlyArray<{ readonly type: string, readonly code: string }>;`, optionsSet: [[]], }, // Type literal with readonly on members should not produce failures. { code: dedent` let foo: { readonly a: number, readonly b: ReadonlyArray<string>, readonly c: () => string, readonly d: { readonly [key: string]: string } readonly [key: string]: string }; `, optionsSet: [[]], }, // Mapped types with readonly on members should not produce failures. { code: dedent` const func = (x: { readonly [key in string]: number }) => {} `, optionsSet: [[]], }, // Ignore Classes. { code: dedent` class Klass { foo: number; private bar: number; static baz: number; private static qux: number; } `, optionsSet: [[{ ignoreClass: true }]], }, // Ignore Interfaces. { code: dedent` interface Foo { foo: number, bar: ReadonlyArray<string>, baz: () => string, qux: { [key: string]: string } } `, optionsSet: [[{ ignoreInterface: true }]], }, // Allow Local. { code: dedent` function foo() { let foo: { a: number, b: ReadonlyArray<string>, c: () => string, d: { [key: string]: string }, [key: string]: string, readonly d: { a: number, b: ReadonlyArray<string>, c: () => string, d: { [key: string]: string }, [key: string]: string, } } }; `, optionsSet: [[{ allowLocalMutation: true }]], }, // Ignore Prefix. { code: dedent` let mutableFoo: string[] = []; `, optionsSet: [[{ ignorePattern: "^mutable" }]], }, { code: dedent` let foo: { mutableA: number, mutableB: ReadonlyArray<string>, mutableC: () => string, mutableD: { readonly [key: string]: string }, mutableE: { mutableA: number, mutableB: ReadonlyArray<string>, mutableC: () => string, mutableD: { readonly [key: string]: string }, } }; `, optionsSet: [[{ ignorePattern: "^mutable" }]], }, { code: dedent` class Klass { mutableA: string; private mutableB: string; } `, optionsSet: [[{ ignorePattern: "^mutable" }]], }, // Ignore Suffix. { code: dedent` let fooMutable: string[] = []; `, optionsSet: [[{ ignorePattern: "Mutable$" }]], }, { code: dedent` let foo: { aMutable: number, bMutable: ReadonlyArray<string>, cMutable: () => string, dMutable: { readonly [key: string]: string }, eMutable: { aMutable: number, bMutable: ReadonlyArray<string>, cMutable: () => string, dMutable: { readonly [key: string]: string }, } }; `, optionsSet: [[{ ignorePattern: "Mutable$" }]], }, { code: dedent` class Klass { AMutable: string; private BMutable: string; } `, optionsSet: [[{ ignorePattern: "Mutable$" }]], }, // Allow mutable TSIndexSignature. { code: dedent` const mutableResult: { [key: string]: string } = {}; `, optionsSet: [[{ ignorePattern: "^mutable" }]], }, // Ignore Mutable Collections (Array, Tuple, Set, Map) { code: dedent`type Foo = Array<string>;`, optionsSet: [[{ ignoreCollections: true }]], }, { code: dedent`const Foo: number[] = [];`, optionsSet: [[{ ignoreCollections: true }]], }, { code: dedent`const Foo = []`, optionsSet: [[{ ignoreCollections: true, checkImplicit: true }]], }, { code: dedent`type Foo = [string, string];`, optionsSet: [[{ ignoreCollections: true }]], }, { code: dedent`const Foo: [string, string] = ['foo', 'bar'];`, optionsSet: [[{ ignoreCollections: true }]], }, { code: dedent`const Foo = ['foo', 'bar'];`, optionsSet: [[{ ignoreCollections: true, checkImplicit: true }]], }, { code: dedent`type Foo = Set<string, string>;`, optionsSet: [[{ ignoreCollections: true }]], }, { code: dedent`const Foo: Set<string, string> = new Set();`, optionsSet: [[{ ignoreCollections: true }]], }, { code: dedent`type Foo = Map<string, string>;`, optionsSet: [[{ ignoreCollections: true }]], }, { code: dedent`const Foo: Map<string, string> = new Map();`, optionsSet: [[{ ignoreCollections: true }]], }, ]; export default tests;
the_stack
import {expect} from 'chai' import nock from 'nock' // WARN: nock must be imported before NodeHttpTransport, since it modifies node's http import { ClientOptions, HttpError, WriteOptions, Point, WriteApi, InfluxDB, WritePrecisionType, DEFAULT_WriteOptions, PointSettings, } from '../../src' import {collectLogging, CollectedLogs} from '../util' import {Logger} from '../../src/util/logger' import {waitForCondition} from './util/waitForCondition' import zlib from 'zlib' const clientOptions: ClientOptions = { url: 'http://fake:8086', token: 'a', } const ORG = 'org' const BUCKET = 'bucket' const PRECISION: WritePrecisionType = 's' const WRITE_PATH_NS = `/api/v2/write?org=${ORG}&bucket=${BUCKET}&precision=ns` function createApi( org: string, bucket: string, precision: WritePrecisionType, options: Partial<WriteOptions> ): WriteApi { return new InfluxDB({ ...clientOptions, ...{writeOptions: options}, }).getWriteApi(org, bucket, precision) } interface WriteListeners { successLineCount: number failedLineCount: number writeFailed(error: Error, lines: string[]): void writeSuccess(lines: string[]): void } function createWriteCounters(): WriteListeners { const retVal = { successLineCount: 0, failedLineCount: 0, writeFailed(_error: Error, lines: string[]): void { retVal.failedLineCount += lines.length }, writeSuccess(lines: string[]): void { retVal.successLineCount += lines.length }, } return retVal } describe('WriteApi', () => { beforeEach(() => { nock.disableNetConnect() }) afterEach(() => { nock.cleanAll() nock.enableNetConnect() }) describe('simple', () => { let subject: WriteApi let logs: CollectedLogs beforeEach(() => { subject = createApi(ORG, BUCKET, PRECISION, { retryJitter: 0, }) // logs = collectLogging.decorate() logs = collectLogging.replace() }) afterEach(async () => { await subject.close() collectLogging.after() }) it('can be closed and flushed without any data', async () => { await subject.close().catch(e => expect.fail('should not happen', e)) await subject.flush(true).catch(e => expect.fail('should not happen', e)) }) it('fails on close without server connection', async () => { subject.writeRecord('test value=1') subject.writeRecords(['test value=2', 'test value=3']) await subject .close() .then(() => expect.fail('failure expected')) .catch(e => { expect(logs.error).length.greaterThan(0) expect(e).to.be.ok }) }) it('fails on flush without server connection', async () => { subject.writeRecord('test value=1') subject.writeRecords(['test value=2', 'test value=3']) await subject .flush() .then(() => expect.fail('failure expected')) .catch(e => { expect([...logs.error, ...logs.warn]).to.length(1) expect(e).to.be.ok }) }) it('fails on write if it is closed already', async () => { await subject.close() expect(() => subject.writeRecord('text value=1')).to.throw( 'writeApi: already closed!' ) expect(() => subject.writeRecords(['text value=1', 'text value=2']) ).to.throw('writeApi: already closed!') expect(() => subject.writePoint(new Point('test').floatField('value', 1)) ).to.throw('writeApi: already closed!') expect(() => subject.writePoints([new Point('test').floatField('value', 1)]) ).to.throw('writeApi: already closed!') }) }) describe('configuration', () => { let subject: WriteApi let logs: CollectedLogs function useSubject(writeOptions: Partial<WriteOptions>): void { subject = new InfluxDB({ ...clientOptions, }).getWriteApi(ORG, BUCKET, PRECISION, writeOptions) } beforeEach(() => { // logs = collectLogging.decorate() logs = collectLogging.replace() }) afterEach(async () => { await subject.close() collectLogging.after() }) it('flushes the data in specified batchSize', async () => { useSubject({ flushInterval: 0, batchSize: 1, }) subject.writeRecord('test value=1') subject.writeRecords(['test value=2', 'test value=3']) // wait for http calls to finish await waitForCondition(() => logs.warn.length >= 3) await subject.close().then(() => { expect(logs.error).to.length(1) expect(logs.warn).length(3) // 3 warnings about write failure expect(logs.error[0][0]).includes( '3', 'Warning message informs about count of missing lines' ) }) }) it('does not retry write when maxRetries is zero', async () => { useSubject({maxRetries: 0, batchSize: 1}) subject.writeRecord('test value=1') await waitForCondition(() => logs.error.length > 0) await subject.close().then(() => { expect(logs.error).to.length(1) expect(logs.warn).is.deep.equal([]) }) }) it('does not retry write when maxRetryTime exceeds', async () => { useSubject({maxRetryTime: 5, batchSize: 1}) subject.writeRecord('test value=1') // wait for first attempt to fail await waitForCondition(() => logs.warn.length > 0) // wait for retry attempt to fail on timeout await waitForCondition(() => logs.error.length > 0) await subject.close().then(() => { expect(logs.warn).to.length(1) expect(logs.warn[0][0]).contains( 'Write to InfluxDB failed (attempt: 1)' ) expect(logs.error).to.length(1) expect(logs.error[0][0]).contains( 'Write to InfluxDB failed (attempt: 2)' ) expect(logs.error[0][1].toString()).contains('Max retry time exceeded') }) }) it('does not retry write when writeFailed handler returns a Promise', async () => { useSubject({ maxRetries: 3, batchSize: 1, writeFailed: (error: Error, lines: string[], attempts: number) => { Logger.warn( `CUSTOMERRORHANDLING ${!!error} ${lines.length} ${attempts}`, undefined ) return Promise.resolve() }, }) subject.writeRecord('test value=1') await waitForCondition(() => logs.warn.length > 0) await subject.close().then(() => { expect(logs.error).length(0) expect(logs.warn).is.deep.equal([ ['CUSTOMERRORHANDLING true 1 1', undefined], ]) }) }) it('uses the pre-configured batchSize', async () => { useSubject({flushInterval: 0, maxRetries: 0, batchSize: 2}) subject.writeRecords(['test value=1', 'test value=2', 'test value=3']) await waitForCondition(() => logs.error.length > 0) // wait for HTTP call to fail let count = subject.dispose() expect(logs.error).has.length(1) expect(logs.warn).has.length(0) expect(count).equals(1) count = subject.dispose() // dispose is idempotent expect(logs.error).has.length(1) // no more errorrs expect(logs.warn).has.length(0) expect(count).equals(1) }) it('implementation uses expected defaults', () => { useSubject({}) const writeOptions = (subject as any).writeOptions as WriteOptions expect(writeOptions.writeFailed).equals(DEFAULT_WriteOptions.writeFailed) expect(writeOptions.writeSuccess).equals( DEFAULT_WriteOptions.writeSuccess ) expect(writeOptions.writeSuccess).to.not.throw() expect(writeOptions.writeFailed).to.not.throw() expect(writeOptions.randomRetry).equals(true) }) }) describe('convert point time to line protocol', () => { const writeAPI = createApi(ORG, BUCKET, 'ms', { retryJitter: 0, }) as PointSettings it('converts empty string to no timestamp', () => { const p = new Point('a').floatField('b', 1).timestamp('') expect(p.toLineProtocol(writeAPI)).equals('a b=1') }) it('converts number to timestamp', () => { const p = new Point('a').floatField('b', 1).timestamp(1.2) expect(p.toLineProtocol(writeAPI)).equals('a b=1 1') }) it('converts Date to timestamp', () => { const d = new Date() const p = new Point('a').floatField('b', 1).timestamp(d) expect(p.toLineProtocol(writeAPI)).equals(`a b=1 ${d.getTime()}`) }) it('converts undefined to local timestamp', () => { const p = new Point('a').floatField('b', 1) expect(p.toLineProtocol(writeAPI)).satisfies((x: string) => { return x.startsWith('a b=1') }, `does not start with 'a b=1'`) expect(p.toLineProtocol(writeAPI)).satisfies((x: string) => { return Date.now() - Number.parseInt(x.substring('a b=1 '.length)) < 1000 }) }) }) describe('flush on background', () => { let subject: WriteApi let logs: CollectedLogs function useSubject(writeOptions: Partial<WriteOptions>): void { subject = createApi(ORG, BUCKET, PRECISION, { retryJitter: 0, ...writeOptions, }) } beforeEach(() => { // logs = collectLogging.decorate() logs = collectLogging.replace() }) afterEach(async () => { await subject.close() collectLogging.after() }) it('flushes the records automatically in intervals', async () => { useSubject({flushInterval: 5, maxRetries: 0, batchSize: 10}) subject.writeRecord('test value=1') await waitForCondition(() => logs.error.length >= 1) // wait for HTTP call to fail expect(logs.error).has.length(1) subject.writeRecord('test value=2') await waitForCondition(() => logs.error.length >= 2) expect(logs.error).has.length(2) await subject.flush().then(() => { expect(logs.error).has.length(2) }) }) it('flushes the records automatically in batches', async () => { useSubject({flushInterval: 0, maxRetries: 0, batchSize: 1}) subject.writeRecord('test value=1') await waitForCondition(() => logs.error.length >= 1) // wait for HTTP call to fail expect(logs.error).has.length(1) subject.writeRecord('test value=2') await waitForCondition(() => logs.error.length >= 2) expect(logs.error).has.length(2) await subject.flush().then(() => { expect(logs.error).has.length(2) }) }) }) describe('usage of server API', () => { let subject: WriteApi let logs: CollectedLogs function useSubject(writeOptions: Partial<WriteOptions>): void { subject = createApi(ORG, BUCKET, 'ns', { retryJitter: 0, defaultTags: {xtra: '1'}, ...writeOptions, }) } beforeEach(() => { // logs = collectLogging.decorate() logs = collectLogging.replace() }) afterEach(async () => { subject.close() collectLogging.after() }) it('flushes the records without errors', async () => { const writeCounters = createWriteCounters() useSubject({ flushInterval: 5, maxRetries: 1, randomRetry: false, batchSize: 10, writeSuccess: writeCounters.writeSuccess, }) let requests = 0 const messages: string[] = [] nock(clientOptions.url) .post(WRITE_PATH_NS) .reply((_uri, _requestBody) => { requests++ if (requests % 2) { return [429, '', {'retry-after': '1'}] } else { messages.push(_requestBody.toString()) return [204, '', {'retry-after': '1'}] } }) .persist() subject.writePoint( new Point('test') .tag('t', ' ') .floatField('value', 1) .timestamp('') ) await waitForCondition(() => writeCounters.successLineCount == 1) expect(logs.error).has.length(0) expect(logs.warn).has.length(1) // request was retried once subject.writePoint(new Point()) // ignored, since it generates no line subject.writePoints([ new Point('test'), // will be ignored + warning new Point('test').floatField('value', 2), new Point('test').floatField('value', 3), new Point('test').floatField('value', 4).timestamp('1'), new Point('test').floatField('value', 5).timestamp(2.1), new Point('test').floatField('value', 6).timestamp(new Date(3)), new Point('test') .floatField('value', 7) .timestamp((false as any) as string), // server decides what to do with such values ]) await waitForCondition(() => writeCounters.successLineCount == 7) expect(logs.error).to.length(0) expect(logs.warn).to.length(2) expect(messages).to.have.length(2) expect(messages[0]).to.equal('test,t=\\ ,xtra=1 value=1') const lines = messages[1].split('\n') expect(lines).has.length(6) expect(lines[0]).to.satisfy((line: string) => line.startsWith('test,xtra=1 value=2') ) expect(lines[0].substring(lines[0].lastIndexOf(' ') + 1)).to.have.length( String(Date.now()).length + 6 // nanosecond precision ) expect(lines[1]).to.satisfy((line: string) => line.startsWith('test,xtra=1 value=3') ) expect(lines[0].substring(lines[0].lastIndexOf(' ') + 1)).to.have.length( String(Date.now()).length + 6 // nanosecond precision ) expect(lines[2]).to.be.equal('test,xtra=1 value=4 1') expect(lines[3]).to.be.equal('test,xtra=1 value=5 2') expect(lines[4]).to.be.equal('test,xtra=1 value=6 3000000') expect(lines[5]).to.be.equal('test,xtra=1 value=7 false') }) it('flushes gzipped line protocol', async () => { const writeCounters = createWriteCounters() useSubject({ flushInterval: 5, maxRetries: 1, randomRetry: false, batchSize: 10, writeSuccess: writeCounters.writeSuccess, gzipThreshold: 0, }) let requests = 0 const messages: string[] = [] nock(clientOptions.url) .post(WRITE_PATH_NS) .reply(function(_uri, _requestBody) { requests++ if (requests % 2) { return [429, '', {'retry-after': '1'}] } else { if (this.req.headers['content-encoding'] == 'gzip') { const plain = zlib.gunzipSync( Buffer.from(_requestBody as string, 'hex') ) messages.push(plain.toString()) } return [204, '', {'retry-after': '1'}] } }) .persist() subject.writePoint( new Point('test') .tag('t', ' ') .floatField('value', 1) .timestamp('') ) await waitForCondition(() => writeCounters.successLineCount == 1) expect(logs.error).has.length(0) expect(logs.warn).has.length(1) // request was retried once subject.writePoint(new Point()) // ignored, since it generates no line subject.writePoints([ new Point('test'), // will be ignored + warning new Point('test').floatField('value', 2), new Point('test').floatField('value', 3), new Point('test').floatField('value', 4).timestamp('1'), new Point('test').floatField('value', 5).timestamp(2.1), new Point('test').floatField('value', 6).timestamp(new Date(3)), new Point('test') .floatField('value', 7) .timestamp((false as any) as string), // server decides what to do with such values ]) await waitForCondition(() => writeCounters.successLineCount == 7) expect(logs.error).to.length(0) expect(logs.warn).to.length(2) expect(messages).to.have.length(2) expect(messages[0]).to.equal('test,t=\\ ,xtra=1 value=1') const lines = messages[1].split('\n') expect(lines).has.length(6) expect(lines[0]).to.satisfy((line: string) => line.startsWith('test,xtra=1 value=2') ) expect(lines[0].substring(lines[0].lastIndexOf(' ') + 1)).to.have.length( String(Date.now()).length + 6 // nanosecond precision ) expect(lines[1]).to.satisfy((line: string) => line.startsWith('test,xtra=1 value=3') ) expect(lines[0].substring(lines[0].lastIndexOf(' ') + 1)).to.have.length( String(Date.now()).length + 6 // nanosecond precision ) expect(lines[2]).to.be.equal('test,xtra=1 value=4 1') expect(lines[3]).to.be.equal('test,xtra=1 value=5 2') expect(lines[4]).to.be.equal('test,xtra=1 value=6 3000000') expect(lines[5]).to.be.equal('test,xtra=1 value=7 false') }) it('fails on write response status not being exactly 204', async () => { const writeCounters = createWriteCounters() // required because of https://github.com/influxdata/influxdb-client-js/issues/263 useSubject({ flushInterval: 2, maxRetries: 0, batchSize: 10, writeFailed: writeCounters.writeFailed, }) let authorization: any nock(clientOptions.url) .post(WRITE_PATH_NS) .reply(function(_uri, _requestBody) { authorization = this.req.headers.authorization return [200, '', {}] }) .persist() subject.writePoint(new Point('test').floatField('value', 1)) await waitForCondition(() => writeCounters.failedLineCount == 1) expect(logs.error).has.length(1) expect(logs.error[0][0]).equals('Write to InfluxDB failed.') expect(logs.error[0][1]).instanceOf(HttpError) expect(logs.error[0][1].statusCode).equals(200) expect(logs.error[0][1].message).equals( `204 HTTP response status code expected, but 200 returned` ) expect(logs.warn).deep.equals([]) expect(authorization).equals(`Token ${clientOptions.token}`) }) it('sends custom http header', async () => { useSubject({ headers: {authorization: 'Token customToken'}, }) let authorization: any nock(clientOptions.url) .post(WRITE_PATH_NS) .reply(function(_uri, _requestBody) { authorization = this.req.headers.authorization return [204, '', {}] }) .persist() subject.writePoint(new Point('test').floatField('value', 1)) await subject.close() expect(logs.error).has.length(0) expect(logs.warn).deep.equals([]) expect(authorization).equals(`Token customToken`) }) }) })
the_stack
import React, {CSSProperties, useCallback, useEffect, useState} from "react"; import styles from "./Message.module.css"; import * as Blocks from "../../../../data/blocks"; import {StickerItem, TapbackItem} from "../../../../data/blocks"; import { Avatar, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, IconButton, PaletteColor, Typography, useTheme } from "@mui/material"; import {getDeliveryStatusTime, getTimeDivider} from "../../../../util/dateUtils"; import {findPerson} from "../../../../util/peopleUtils"; import {MessageErrorCode, MessageStatusCode} from "../../../../data/stateCodes"; import MessageAttachmentDownloadable from "../attachment/MessageAttachmentDownloadable"; import MessageAttachmentImage from "../attachment/MessageAttachmentImage"; import {downloadArrayBuffer, downloadBlob} from "../../../../util/browserUtils"; import MessageModifierTapbackRow from "../modifier/MessageModifierTapbackRow"; import MessageModifierStickerStack from "../modifier/MessageModifierStickerStack"; import {colorFromContact} from "../../../../util/avatarUtils"; import Linkify from "linkify-react"; import {appleServiceAppleMessage} from "../../../../data/appleConstants"; import FileDownloadResult, {FileDisplayResult} from "shared/data/fileDownloadResult"; import {PersonData} from "../../../../../window"; import {Property} from "csstype"; import {ErrorRounded} from "@mui/icons-material"; const radiusLinked = "4px"; const radiusUnlinked = "16.5px"; const marginLinked = "2px"; const marginUnlinked = "8px"; const opacityUnconfirmed = 0.5; const opacityConfirmed = 1; //A message's position in the thread in accordance with other nearby messages export interface MessageFlow { anchorTop: boolean; anchorBottom: boolean; showDivider: boolean; } export interface MessagePartProps { alignSelf: Property.AlignSelf; //Message alignment color: Property.Color; //Text and action button colors backgroundColor: Property.Color; //Message background color opacity: Property.Opacity; //Content opacity borderRadius: Property.BorderRadius; //Content border radius marginTop: Property.MarginTop; //Message top margin } interface Props { message: Blocks.MessageItem; isGroupChat: boolean; service: string; flow: MessageFlow; showStatus?: boolean; } export default function Message(props: Props) { //State const [attachmentDataArray, setAttachmentDataArray] = useState<FileDownloadResult[]>([]); const [dialogOpen, setDialogOpen] = useState<"error" | "rawError" | undefined>(undefined); function closeDialog() { setDialogOpen(undefined); } function openDialogError() { setDialogOpen("error"); } function openDialogRawError() { setDialogOpen("rawError"); } function copyRawErrorAndClose() { navigator.clipboard.writeText(props.message.error!.detail!); closeDialog(); } //Getting the message information const isOutgoing = props.message.sender === undefined; const displayAvatar = !isOutgoing && !props.flow.anchorTop; const displaySender = props.isGroupChat && displayAvatar; const messageConfirmed = props.message.status !== MessageStatusCode.Unconfirmed; //Building the message style const theme = useTheme(); let colorPalette: PaletteColor; if(isOutgoing) { if(props.service === appleServiceAppleMessage) colorPalette = theme.palette.messageOutgoing; else colorPalette = theme.palette.messageOutgoingTextMessage; } else { colorPalette = theme.palette.messageIncoming; } const messagePartPropsBase: Partial<MessagePartProps> = { alignSelf: isOutgoing ? "flex-end" : "flex-start", color: colorPalette.contrastText, backgroundColor: colorPalette.main, opacity: messageConfirmed ? opacityConfirmed : opacityUnconfirmed }; //Splitting the modifiers for each message part const stickerGroups = props.message.stickers.reduce((accumulator: {[index: number]: StickerItem[]}, item: StickerItem) => { if(accumulator[item.messageIndex]) accumulator[item.messageIndex].push(item); else accumulator[item.messageIndex] = [item]; return accumulator; }, {}); const tapbackGroups = props.message.tapbacks.reduce((accumulator: {[index: number]: TapbackItem[]}, item: TapbackItem) => { if(accumulator[item.messageIndex]) accumulator[item.messageIndex].push(item); else accumulator[item.messageIndex] = [item]; return accumulator; }, {}); //Adding the message text const components: React.ReactNode[] = []; if(props.message.text) { const partProps: MessagePartProps = { ...messagePartPropsBase, borderRadius: getBorderRadius(props.flow.anchorTop, props.flow.anchorBottom || props.message.attachments.length > 0, isOutgoing), marginTop: 0 } as MessagePartProps; const component = <MessageBubble key="messagetext" text={props.message.text!} index={0} partProps={partProps} stickers={stickerGroups[0]} tapbacks={tapbackGroups[0]} />; components.push(component); } function onAttachmentData(attachmentIndex: number, shouldDownload: boolean, result: FileDownloadResult) { if(shouldDownload) { //Downloading the file const attachment = props.message.attachments[attachmentIndex]; downloadArrayBuffer(result.data, result.downloadType ?? attachment.type, result.downloadName ?? attachment.name); } else { //Updating the data const newArray = [...attachmentDataArray]; newArray[attachmentIndex] = result; setAttachmentDataArray(newArray); } } function downloadData(attachmentIndex: number, data: ArrayBuffer | Blob) { const attachment = props.message.attachments[attachmentIndex]; if(data instanceof ArrayBuffer) { downloadArrayBuffer(data, attachment.type, attachment.name); } else { downloadBlob(data, attachment.type, attachment.name); } } /** * Computes the file data to display to the user */ const getComputedFileData = useCallback((attachmentIndex: number): FileDisplayResult => { const attachment = props.message.attachments[attachmentIndex]; const downloadData = attachmentDataArray[attachmentIndex]; if(downloadData === undefined) { return { data: attachment.data, name: attachment.name, type: attachment.type }; } else return { data: downloadData.data, name: downloadData.downloadName ?? attachment.name, type: downloadData.downloadType ?? attachment.type }; }, [props.message.attachments, attachmentDataArray]); //Adding the attachments for(let i = 0; i < props.message.attachments.length; i++) { const index = props.message.text ? i + 1 : i; const attachment = props.message.attachments[i]; const partProps: MessagePartProps = { ...messagePartPropsBase, borderRadius: getBorderRadius(props.flow.anchorTop || index > 0, props.flow.anchorBottom || i + 1 < props.message.attachments.length, isOutgoing), marginTop: index > 0 ? marginLinked : undefined } as MessagePartProps; //Checking if the attachment has data const attachmentData = getComputedFileData(i); if(attachmentData.data !== undefined && isAttachmentPreviewable(attachmentData.type)) { //Custom background color const imagePartProps = { ...partProps, backgroundColor: theme.palette.background.sidebar, }; if(attachmentData.type.startsWith("image/")) { components.push(<MessageAttachmentImage key={attachment.guid ?? attachment.localID} data={attachmentData.data} name={attachmentData.name} type={attachmentData.type} partProps={imagePartProps} stickers={stickerGroups[index]} tapbacks={tapbackGroups[index]} />); } } else { //Adding a generic download attachment components.push(<MessageAttachmentDownloadable key={attachment.guid ?? attachment.localID} data={attachmentData.data} name={attachmentData.name} type={attachmentData.type} size={attachment.size} guid={attachment.guid!} onDataAvailable={(data) => onAttachmentData(i, !isAttachmentPreviewable(data.downloadType ?? attachment.type), data)} onDataClicked={(data) => downloadData(i, data)} partProps={partProps} stickers={stickerGroups[index]} tapbacks={tapbackGroups[index]} />); } } const messageStyle: CSSProperties = { marginTop: props.flow.anchorTop ? marginLinked : marginUnlinked, }; //Initializing state const [personData, setPersonData] = useState<PersonData | undefined>(); useEffect(() => { if(!props.message.sender) return; //Requesting contact data findPerson(props.message.sender).then(setPersonData, console.warn); }, [props.message.sender]); //Building and returning the component return ( <div className={styles.message} style={messageStyle}> {props.flow.showDivider && <Typography className={styles.separator} variant="body2" color="textSecondary">{getTimeDivider(props.message.date)}</Typography>} {displaySender && <Typography className={styles.labelSender} variant="caption" color="textSecondary">{personData?.name ?? props.message.sender}</Typography>} <div className={styles.messageSplit}> {<Avatar className={styles.avatar} src={personData?.avatar} style={displayAvatar ? {visibility: "visible", backgroundColor: colorFromContact(props.message.sender ?? "")} : {visibility: "hidden"}} />} <div className={styles.messageParts}> {components} </div> {props.message.progress && !props.message.error && <CircularProgress className={styles.messageProgress} size={24} variant={props.message.progress === -1 ? "indeterminate" : "determinate"} value={props.message.progress} />} {props.message.error && <IconButton className={styles.messageError} style={{color: theme.palette.error.light}} size="small" onClick={openDialogError}> <ErrorRounded /> </IconButton>} <Dialog open={dialogOpen === "error"} onClose={closeDialog}> <DialogTitle>Your message could not be sent</DialogTitle> {props.message.error !== undefined && <React.Fragment> <DialogContent> <DialogContentText>{messageErrorToUserString(props.message.error!.code)}</DialogContentText> </DialogContent> <DialogActions> {props.message.error!.detail && <Button onClick={openDialogRawError} color="primary"> Error details </Button>} <Button onClick={closeDialog} color="primary" autoFocus> Dismiss </Button> </DialogActions> </React.Fragment>} </Dialog> <Dialog open={dialogOpen === "rawError"} onClose={closeDialog}> <DialogTitle>Error details</DialogTitle> {props.message.error !== undefined && <React.Fragment> <DialogContent> <DialogContentText className={styles.rawErrorText}>{props.message.error.detail!}</DialogContentText> </DialogContent> <DialogActions> <Button onClick={copyRawErrorAndClose} color="primary"> Copy to clipboard </Button> <Button onClick={closeDialog} color="primary" autoFocus> Dismiss </Button> </DialogActions> </React.Fragment>} </Dialog> </div> {props.showStatus && <Typography className={styles.labelStatus} variant="caption" color="textSecondary">{getStatusString(props.message)}</Typography>} </div> ); } //A standard message bubble with text function MessageBubble(props: {text: string, index: number, partProps: MessagePartProps, tapbacks?: TapbackItem[], stickers?: StickerItem[]}) { return ( <DecorativeMessageBubble element="div" className={styles.textBubble} style={props.partProps} tapbacks={props.tapbacks} stickers={props.stickers}> <Linkify options={{target: "_blank"}}>{props.text}</Linkify> </DecorativeMessageBubble> ); /* return <div className={styles.textBubble + (props.tapbacks ? " " + styles.tapbackMargin : "")} style={props.partProps}> {props.stickers && <MessageModifierStickerStack modifiers={props.stickers} />} {props.tapbacks && <MessageModifierTapbackRow modifiers={props.tapbacks} />} {props.text} </div> */ } export function DecorativeMessageBubble(props: {element: React.ElementType, className?: string, style?: React.CSSProperties, tapbacks?: TapbackItem[], stickers?: StickerItem[], children: React.ReactNode, [x: string]: any}) { const {className, style, tapbacks, stickers, children, ...rest} = props; const [isPeeking, setPeeking] = useState(false); function enablePeeking() { setPeeking(true); } function disablePeeking() { setPeeking(false); } return ( <props.element className={(props.className ?? "") + (props.tapbacks ? " " + styles.tapbackMargin : "")} style={props.style} onMouseEnter={enablePeeking} onMouseLeave={disablePeeking} {...rest}> {props.stickers && <MessageModifierStickerStack modifiers={props.stickers} reveal={isPeeking} />} {props.tapbacks && <MessageModifierTapbackRow modifiers={props.tapbacks} />} {props.children} </props.element> ); } function getBorderRadius(anchorTop: boolean, anchorBottom: boolean, isOutgoing: boolean): string { const radiusTop = anchorTop ? radiusLinked : radiusUnlinked; const radiusBottom = anchorBottom ? radiusLinked : radiusUnlinked; if(isOutgoing) { return `${radiusUnlinked} ${radiusTop} ${radiusBottom} ${radiusUnlinked}`; } else { return `${radiusTop} ${radiusUnlinked} ${radiusUnlinked} ${radiusBottom}`; } } function getStatusString(message: Blocks.MessageItem): string | undefined { if(message.status === MessageStatusCode.Delivered) { return "Delivered"; } else if(message.status === MessageStatusCode.Read) { return message.statusDate ? "Read • " + getDeliveryStatusTime(message.statusDate) : "Read"; } else { return undefined; } } function isAttachmentPreviewable(mimeType: string): boolean { //return mimeType.startsWith("image/") || mimeType.startsWith("video/") || mimeType.startsWith("audio/"); return mimeType.startsWith("image/"); } function messageErrorToUserString(error: MessageErrorCode): string { switch(error) { case MessageErrorCode.LocalInvalidContent: return "The selected content is unavailable"; case MessageErrorCode.LocalTooLarge: return "The selected content is too large to send"; case MessageErrorCode.LocalIO: return "Couldn't process selected content"; case MessageErrorCode.LocalNetwork: return "Couldn't connect to AirMessage server"; case MessageErrorCode.LocalInternalError: return "An internal error occurred"; case MessageErrorCode.ServerUnknown: return "An unknown external error occurred"; case MessageErrorCode.ServerExternal: return "An external error occurred"; case MessageErrorCode.ServerBadRequest: return "An error occurred while sending this message"; case MessageErrorCode.ServerUnauthorized: return "AirMessage server isn't allowed to send messages"; case MessageErrorCode.ServerTimeout: return "This message couldn't be delivered properly"; case MessageErrorCode.AppleNoConversation: return "This conversation isn't available"; case MessageErrorCode.AppleNetwork: return "Couldn't connect to iMessage server"; case MessageErrorCode.AppleUnregistered: return "This recipient is not registered with iMessage"; default: return "An unknown error occurred"; } }
the_stack
import * as vscode from 'vscode'; import { JenkinsService } from './jenkinsService'; import { QuickpickSet } from './quickpickSet'; import { ext } from './extensionVariables'; import { ConnectionsTreeItem } from './connectionsTree'; import { JenkinsConnection } from './jenkinsConnection'; import { SelectionFlows } from './selectionFlows'; export class ConnectionsManager implements QuickpickSet { private _host: JenkinsService; public constructor() { ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.connections.select', async (item?: ConnectionsTreeItem) => { await this.selectConnection(item?.connection); })); ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.connections.add', async () => { await this.addConnection(); })); ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.connections.edit', async (item?: ConnectionsTreeItem) => { await this.editConnection(item?.connection); })); ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.connections.delete', async (item?: ConnectionsTreeItem) => { await this.deleteConnection(item?.connection); })); ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.connections.selectFolder', async (item?: ConnectionsTreeItem) => { await this.selectFolder(); })); vscode.workspace.onDidChangeConfiguration(event => { if (event.affectsConfiguration('jenkins-jack.jenkins.connections')) { this.updateSettings(); }} ); } public async initialize() { await this.updateSettings(); } public get commands(): any[] { return [ { label: "$(list-selection) Connections: Select", description: "Select a jenkins host connection to connect to.", target: async () => vscode.commands.executeCommand('extension.jenkins-jack.connections.select') }, { label: "$(add) Connections: Add", description: "Add a jenkins host connection via input prompts.", target: async () => vscode.commands.executeCommand('extension.jenkins-jack.connections.add') }, { label: "$(edit) Connections: Edit", description: "Edit a jenkins host's connection info.", target: async () => vscode.commands.executeCommand('extension.jenkins-jack.connections.edit') }, { label: "$(circle-slash) Connections: Delete", description: "Delete a jenkins host connection from settings.", target: async () => vscode.commands.executeCommand('extension.jenkins-jack.connections.delete') }, { label: "$(list-selection) Connections: Select Folder", description: "Select a folder on the jenkins host for this connection to filter its queries on.", target: async () => vscode.commands.executeCommand('extension.jenkins-jack.connections.selectFolder') }, ]; } /** * The active Jenkins host client service. */ public get host(): JenkinsService { return this._host; } public get connected(): boolean { return (null != this.host); } public async display() { let result = await vscode.window.showQuickPick(this.commands, { placeHolder: 'Jenkins Jack', ignoreFocusOut: true }); if (undefined === result) { return; } return result.target(); } private async updateSettings() { let config = vscode.workspace.getConfiguration('jenkins-jack.jenkins'); let conn: JenkinsConnection | undefined; for (let c of config.connections) { if (c.active) { conn = JenkinsConnection.fromJSON(c); break; } } if (undefined === conn) { vscode.window.showErrorMessage("You must select a host connection to use the extension's features"); return; } if (undefined !== this._host) { this._host.dispose(); } let host = await this.createJenkinsService(conn); if (!host) { return; } this._host = host; } public get activeConnection(): any { let config = vscode.workspace.getConfiguration('jenkins-jack.jenkins'); for (let c of config.connections) { if (c.active) { return c; } } return undefined; } /** * Provides an input flow for adding in a host to the user's settings. */ public async addConnection() { let conn = await this.getConnectionInput(); if (undefined === conn) { return; } let host = await this.createJenkinsService(conn); if (!host) { return; } this._host = host; // Add the connection to the list and make it the active one let config = vscode.workspace.getConfiguration('jenkins-jack.jenkins'); config.connections.forEach((c: any) => c.active = false); config.connections.push({ "name": conn.name, "uri": conn.uri, "username": conn.username, "folderFilter": conn.folderFilter, "crumbIssuer": conn.crumbIssuer, "active": true }); vscode.workspace.getConfiguration().update('jenkins-jack.jenkins.connections', config.connections, vscode.ConfigurationTarget.Global); vscode.window.showInformationMessage(`Jenkins Jack: Host updated to ${conn.name}: ${conn.uri}`); // Refresh the connection tree and it's dependent tree views vscode.commands.executeCommand('extension.jenkins-jack.tree.connections.refresh'); } /** * Provides an input flow for a user to edit a host's connection info. * @param conn Optional connection object edit. */ public async editConnection(conn?: any) { let config = vscode.workspace.getConfiguration('jenkins-jack.jenkins'); if (!conn) { let hosts = []; for (let c of config.connections) { hosts.push({ label: c.name, description: `${c.uri} (${c.username})`, target: c }); } // Select a connection to edit let result = await vscode.window.showQuickPick(hosts, { ignoreFocusOut: true }); if (undefined === result) { return; } conn = result.target; } // Prompt user to edit the connection fields let editedConnection = await this.getConnectionInput(JenkinsConnection.fromJSON(conn)); if (undefined === editedConnection) { return; } // If the name of a connection was changed, ensure we update // references of pipeline tree items to use the new name if (editedConnection.name !== conn.name) { let pipelineConfig = await vscode.workspace.getConfiguration('jenkins-jack.pipeline.tree'); let pipelineTreeItems = []; for (let c of pipelineConfig.items) { if (conn.name === c.hostId) { c.hostId = editedConnection.name; } pipelineTreeItems.push(c); } await vscode.workspace.getConfiguration().update('jenkins-jack.pipeline.tree.items', pipelineTreeItems, vscode.ConfigurationTarget.Global); } // Remake connection list with the modified connection. We do this because // direct updating of config.connections causes undefined behavior. let modifiedConnections = config.connections.filter((c: any) => { return c.name !== conn.name; }); modifiedConnections.push(editedConnection.toJSON()); // If we just edited the active connection, re-connect with the new information. if (conn.name == this.activeConnection.name) { let host = await this.createJenkinsService(editedConnection); if (!host) { return; } this._host = host; } await vscode.workspace.getConfiguration().update('jenkins-jack.jenkins.connections', modifiedConnections, vscode.ConfigurationTarget.Global); vscode.commands.executeCommand('extension.jenkins-jack.tree.connections.refresh'); } /** * User flow for deleting a Jenkins host connection. * @param conn Optional connection object to delete. */ public async deleteConnection(conn?: any) { let config = vscode.workspace.getConfiguration('jenkins-jack.jenkins'); if (!conn) { let hosts = []; for (let c of config.connections) { hosts.push({ label: c.name, description: `${c.uri} (${c.username})`, target: c }); } let result = await vscode.window.showQuickPick(hosts, { ignoreFocusOut: true }); if (undefined === result) { return undefined; } conn = result.target; } // Remove connection and update global config. let modifiedConnections = config.connections.filter((c: any) => { return c.name !== conn.name; }); await vscode.workspace.getConfiguration().update('jenkins-jack.jenkins.connections', modifiedConnections, vscode.ConfigurationTarget.Global); vscode.window.showInformationMessage(`Host "${conn.name} ${conn.uri}" removed`); // Remove password from key-chain let removedConnection = JenkinsConnection.fromJSON(conn); await removedConnection.deletePassword(); // If this host was active, make the first host in the list active. if (conn.active && 0 < modifiedConnections.length) { return await this.selectConnection(modifiedConnections[0]); } // Refresh the connection tree and it's dependent tree views vscode.commands.executeCommand('extension.jenkins-jack.tree.connections.refresh'); } public async selectFolder() { let config = vscode.workspace.getConfiguration('jenkins-jack.jenkins'); let connJson = config.connections.find((c: any) => c.active && c.name === this.activeConnection.name); let folderFilter = await SelectionFlows.folders(false, 'Select a folder to path for filtering job operations on this connection', true); if (undefined === folderFilter) { return undefined; } if ('.' === folderFilter) { folderFilter = undefined; } connJson.folderFilter = folderFilter; let host = await this.createJenkinsService(JenkinsConnection.fromJSON(connJson)); if (!host) { return; } this._host = host; vscode.workspace.getConfiguration().update('jenkins-jack.jenkins.connections', config.connections, vscode.ConfigurationTarget.Global); vscode.window.showInformationMessage(`Jenkins Jack: Host updated to ${connJson.name}: ${connJson.uri}`); // Refresh the connection tree and it's dependent tree views vscode.commands.executeCommand('extension.jenkins-jack.tree.connections.refresh'); } /** * Displays the quick-pick host/connection selection list for the user. * Active connection is updated in the global config upon selection. * If connection already provided, config is just updated and associated * treeViews are refreshed. */ public async selectConnection(conn?: any) { let config = vscode.workspace.getConfiguration('jenkins-jack.jenkins'); if (!conn) { let hosts = []; for (let c of config.connections) { let activeIcon = c.active ? "$(primitive-dot)" : "$(dash)"; hosts.push({ label: `${activeIcon} ${c.name}`, description: `${c.uri} (${c.username})`, target: c }); } let result = await vscode.window.showQuickPick(hosts, { ignoreFocusOut: true }); if (undefined === result) { return; } conn = result.target; } this._host?.dispose(); let host = await this.createJenkinsService(JenkinsConnection.fromJSON(conn)); if (!host) { return; } this._host = host; // Update settings with active host. for (let c of config.connections) { c.active = (conn.name === c.name && conn.uri === c.uri && conn.username === c.username); } vscode.workspace.getConfiguration().update('jenkins-jack.jenkins.connections', config.connections, vscode.ConfigurationTarget.Global); vscode.window.showInformationMessage(`Jenkins Jack: Host updated to ${conn.name}: ${conn.uri}`); // Refresh the connection tree and it's dependent tree views vscode.commands.executeCommand('extension.jenkins-jack.tree.connections.refresh'); } private async getConnectionInput(jenkinsConnection?: JenkinsConnection): Promise<JenkinsConnection | undefined> { let config = vscode.workspace.getConfiguration('jenkins-jack.jenkins'); // Have user enter a unique name for the host. If host name already exists, try again. let hostName: string | undefined = undefined; while (true) { hostName = await vscode.window.showInputBox({ ignoreFocusOut: true, prompt: 'Enter in a unique name for your jenkins connection (e.g. Jenky McJunklets)', value: jenkinsConnection?.name }); if (undefined === hostName) { return undefined; } if (!config.connections.some((c: any) => c.name === hostName) || jenkinsConnection?.name === hostName) { break; } vscode.window.showWarningMessage(`There is already a connection named "${hostName}". Please choose another.`); } let hostUri = await vscode.window.showInputBox({ ignoreFocusOut: true, prompt: 'Enter in your host uri, including protocol (e.g. http://127.0.0.1:8080)', value: (jenkinsConnection) ? jenkinsConnection.uri : 'http://127.0.0.1:8080' }); if (undefined === hostUri) { return undefined; } let folderFilter = await vscode.window.showInputBox({ ignoreFocusOut: true, prompt: '(Optional) Filter only jobs on a specified folder path (e.g. "myfolder", "myfolder/mysubfolder")', value: jenkinsConnection?.folderFilter }); if (undefined === folderFilter) { return undefined; } folderFilter = '' !== folderFilter?.trim() ? folderFilter : undefined; let enableCSRF = await vscode.window.showQuickPick([{ label: 'CSRF Protection Enabled', picked: jenkinsConnection?.crumbIssuer ?? true }], { canPickMany: true, placeHolder: 'CSRF Protection support. Only disable for older Jenkins versions with connection issues.' }); if (undefined === enableCSRF) { return undefined; } let crumbIssuer = enableCSRF.length > 0; let username = await vscode.window.showInputBox({ ignoreFocusOut: true, prompt: 'Enter in a username for authentication', value: jenkinsConnection?.username }); if (undefined === username) { return undefined; } let newConnection = new JenkinsConnection( hostName, hostUri, username, crumbIssuer, jenkinsConnection?.active ?? false, folderFilter); // If no password is found for the passed connection, attempt to retrieve a password for the newly // created connection. let storedPassword = await jenkinsConnection?.getPassword() ?? await newConnection.getPassword(true); let password = await vscode.window.showInputBox({ ignoreFocusOut: true, password: true, prompt: `Enter in the password of "${username}" for authentication. Passwords are stored on the local system's key-chain. `, value: storedPassword ?? '' }); if (undefined === password) { return undefined; } await newConnection.setPassword(password); return newConnection; } private async createJenkinsService(conn: JenkinsConnection): Promise<JenkinsService | undefined> { let jenkinsService = new JenkinsService(conn); let success = await jenkinsService.initialize(); if (!success) { return undefined; } return jenkinsService; } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { Assets } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { AzureMediaServices } from "../azureMediaServices"; import { Asset, AssetsListNextOptionalParams, AssetsListOptionalParams, AssetsListResponse, AssetsGetOptionalParams, AssetsGetResponse, AssetsCreateOrUpdateOptionalParams, AssetsCreateOrUpdateResponse, AssetsDeleteOptionalParams, AssetsUpdateOptionalParams, AssetsUpdateResponse, ListContainerSasInput, AssetsListContainerSasOptionalParams, AssetsListContainerSasResponse, AssetsGetEncryptionKeyOptionalParams, AssetsGetEncryptionKeyResponse, AssetsListStreamingLocatorsOptionalParams, AssetsListStreamingLocatorsResponse, AssetsListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing Assets operations. */ export class AssetsImpl implements Assets { private readonly client: AzureMediaServices; /** * Initialize a new instance of the class Assets class. * @param client Reference to the service client */ constructor(client: AzureMediaServices) { this.client = client; } /** * List Assets in the Media Services account with optional filtering and ordering * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param options The options parameters. */ public list( resourceGroupName: string, accountName: string, options?: AssetsListOptionalParams ): PagedAsyncIterableIterator<Asset> { const iter = this.listPagingAll(resourceGroupName, accountName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(resourceGroupName, accountName, options); } }; } private async *listPagingPage( resourceGroupName: string, accountName: string, options?: AssetsListOptionalParams ): AsyncIterableIterator<Asset[]> { let result = await this._list(resourceGroupName, accountName, options); yield result.value || []; let continuationToken = result.odataNextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, accountName, continuationToken, options ); continuationToken = result.odataNextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, accountName: string, options?: AssetsListOptionalParams ): AsyncIterableIterator<Asset> { for await (const page of this.listPagingPage( resourceGroupName, accountName, options )) { yield* page; } } /** * List Assets in the Media Services account with optional filtering and ordering * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param options The options parameters. */ private _list( resourceGroupName: string, accountName: string, options?: AssetsListOptionalParams ): Promise<AssetsListResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, options }, listOperationSpec ); } /** * Get the details of an Asset in the Media Services account * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param assetName The Asset name. * @param options The options parameters. */ get( resourceGroupName: string, accountName: string, assetName: string, options?: AssetsGetOptionalParams ): Promise<AssetsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, assetName, options }, getOperationSpec ); } /** * Creates or updates an Asset in the Media Services account * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param assetName The Asset name. * @param parameters The request parameters * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, accountName: string, assetName: string, parameters: Asset, options?: AssetsCreateOrUpdateOptionalParams ): Promise<AssetsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, assetName, parameters, options }, createOrUpdateOperationSpec ); } /** * Deletes an Asset in the Media Services account * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param assetName The Asset name. * @param options The options parameters. */ delete( resourceGroupName: string, accountName: string, assetName: string, options?: AssetsDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, accountName, assetName, options }, deleteOperationSpec ); } /** * Updates an existing Asset in the Media Services account * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param assetName The Asset name. * @param parameters The request parameters * @param options The options parameters. */ update( resourceGroupName: string, accountName: string, assetName: string, parameters: Asset, options?: AssetsUpdateOptionalParams ): Promise<AssetsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, assetName, parameters, options }, updateOperationSpec ); } /** * Lists storage container URLs with shared access signatures (SAS) for uploading and downloading Asset * content. The signatures are derived from the storage account keys. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param assetName The Asset name. * @param parameters The request parameters * @param options The options parameters. */ listContainerSas( resourceGroupName: string, accountName: string, assetName: string, parameters: ListContainerSasInput, options?: AssetsListContainerSasOptionalParams ): Promise<AssetsListContainerSasResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, assetName, parameters, options }, listContainerSasOperationSpec ); } /** * Gets the Asset storage encryption keys used to decrypt content created by version 2 of the Media * Services API * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param assetName The Asset name. * @param options The options parameters. */ getEncryptionKey( resourceGroupName: string, accountName: string, assetName: string, options?: AssetsGetEncryptionKeyOptionalParams ): Promise<AssetsGetEncryptionKeyResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, assetName, options }, getEncryptionKeyOperationSpec ); } /** * Lists Streaming Locators which are associated with this asset. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param assetName The Asset name. * @param options The options parameters. */ listStreamingLocators( resourceGroupName: string, accountName: string, assetName: string, options?: AssetsListStreamingLocatorsOptionalParams ): Promise<AssetsListStreamingLocatorsResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, assetName, options }, listStreamingLocatorsOperationSpec ); } /** * ListNext * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, accountName: string, nextLink: string, options?: AssetsListNextOptionalParams ): Promise<AssetsListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AssetCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [ Parameters.apiVersion, Parameters.filter, Parameters.top, Parameters.orderby ], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.Asset }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.assetName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.Asset }, 201: { bodyMapper: Mappers.Asset }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters7, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.assetName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.assetName ], headerParameters: [Parameters.accept], serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.Asset }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters7, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.assetName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listContainerSasOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/listContainerSas", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.AssetContainerSas }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters8, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.assetName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getEncryptionKeyOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/getEncryptionKey", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.StorageEncryptedAssetDecryptionData }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.assetName ], headerParameters: [Parameters.accept], serializer }; const listStreamingLocatorsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/listStreamingLocators", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ListStreamingLocatorsResponse }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.assetName ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AssetCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [ Parameters.apiVersion, Parameters.filter, Parameters.top, Parameters.orderby ], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer };
the_stack
* @module CartesianGeometry */ import { Arc3d } from "../curve/Arc3d"; import { AnnounceNumberNumberCurvePrimitive } from "../curve/CurvePrimitive"; import { AxisOrder, Geometry, PlaneAltitudeEvaluator } from "../Geometry"; import { Angle } from "../geometry3d/Angle"; import { XYZProps } from "../geometry3d/XYZProps"; import { GrowableFloat64Array } from "../geometry3d/GrowableFloat64Array"; import { GrowableXYZArray } from "../geometry3d/GrowableXYZArray"; import { Matrix3d } from "../geometry3d/Matrix3d"; import { Plane3dByOriginAndUnitNormal } from "../geometry3d/Plane3dByOriginAndUnitNormal"; import { Point3d, Vector3d } from "../geometry3d/Point3dVector3d"; import { IndexedXYZCollectionPolygonOps } from "../geometry3d/PolygonOps"; import { Range1d, Range3d } from "../geometry3d/Range"; import { Transform } from "../geometry3d/Transform"; import { Matrix4d } from "../geometry4d/Matrix4d"; import { Point4d } from "../geometry4d/Point4d"; import { AnalyticRoots } from "../numerics/Polynomials"; import { Clipper, ClipUtilities, PolygonClipper } from "./ClipUtils"; import { GrowableXYZArrayCache } from "../geometry3d/ReusableObjectCache"; /** Wire format describing a [[ClipPlane]]. * If either [[normal]] or [[dist]] are omitted, defaults to a normal of [[Vector3d.unitZ]] and a distance of zero. * @public */ export interface ClipPlaneProps { /** The plane's inward normal. */ normal?: XYZProps; /** The plane's distance from the origin. */ dist?: number; /** Defaults to `false`. */ invisible?: boolean; /** Defaults to `false`. */ interior?: boolean; } /** A ClipPlane is a single plane represented as * * An inward unit normal (u,v,w) * * A signedDistance * * Hence * * The halfspace function evaluation for "point" [x,y,z,] is: ([x,y,z] DOT (u,v,w)l - signedDistance) * * POSITIVE values of the halfspace function are "inside" * * ZERO value of the halfspace function is "on" * * NEGATIVE value of the halfspace function is "outside" * * A representative point on the plane is (signedDistance*u, signedDistance * v, signedDistance *w) * * Given a point and inward normal, the signedDistance is (point DOT normal) * @public */ export class ClipPlane implements Clipper, PlaneAltitudeEvaluator, PolygonClipper { private _inwardNormal: Vector3d; /** Construct a parallel plane through the origin. * * Move it to the actual position. * * _distanceFromOrigin is the distance it moved, with the (inward) normal direction as positive */ private _distanceFromOrigin: number; private _invisible: boolean; private _interior: boolean; private constructor(normal: Vector3d, distance: number, invisible: boolean, interior: boolean) { this._invisible = invisible; this._interior = interior; this._inwardNormal = normal; this._distanceFromOrigin = distance; } /* private safeSetXYZDistance(nx: number, ny: number, nz: number, d: number) { this._inwardNormal.set(nx, ny, nz); this._distanceFromOrigin = d; } */ /** * Return true if all members are almostEqual to corresponding members of other. * @param other clip plane to compare */ public isAlmostEqual(other: ClipPlane): boolean { return Geometry.isSameCoordinate(this._distanceFromOrigin, other._distanceFromOrigin) && this._inwardNormal.isAlmostEqual(other._inwardNormal) && this._interior === other._interior && this._invisible === other._invisible; } /** return a cloned plane */ public clone(): ClipPlane { const result = new ClipPlane(this._inwardNormal.clone(), this._distanceFromOrigin, this._invisible, this._interior); return result; } /** return Return a cloned plane with coordinate data negated. */ public cloneNegated(): ClipPlane { const plane = new ClipPlane(this._inwardNormal.clone(), this._distanceFromOrigin, this._invisible, this._interior); plane.negateInPlace(); return plane; } /** Create a ClipPlane from Plane3dByOriginAndUnitNormal. */ public static createPlane(plane: Plane3dByOriginAndUnitNormal, invisible: boolean = false, interior: boolean = false, result?: ClipPlane): ClipPlane { const distance = plane.getNormalRef().dotProduct(plane.getOriginRef()); if (result) { result._invisible = invisible; result._interior = interior; result._inwardNormal = plane.getNormalRef().clone(); result._distanceFromOrigin = distance; return result; } return new ClipPlane(plane.getNormalRef().clone(), distance, invisible, interior); } /** * * Create a ClipPlane with direct normal and signedDistance. * * The vector is normalized for storage. */ public static createNormalAndDistance(normal: Vector3d, distance: number, invisible: boolean = false, interior: boolean = false, result?: ClipPlane): ClipPlane | undefined { const normalized = normal.normalize(); if (normalized) { if (result) { result._invisible = invisible; result._interior = interior; result._inwardNormal = normalized; result._distanceFromOrigin = distance; } return new ClipPlane(normalized, distance, invisible, interior); } return undefined; } /** Create a ClipPlane * * "normal" is the inward normal of the plane. (It is internally normalized) * * "point" is any point of the plane. * * The stored distance for the plane is the dot product of the point with the normal (i.e. treat the point's xyz as a vector from the origin.) */ public static createNormalAndPoint(normal: Vector3d, point: Point3d, invisible: boolean = false, interior: boolean = false, result?: ClipPlane): ClipPlane | undefined { const normalized = normal.normalize(); if (normalized) { const distance = normalized.dotProduct(point); if (result) { result._invisible = invisible; result._interior = interior; result._inwardNormal = normalized; result._distanceFromOrigin = distance; } return new ClipPlane(normalized, distance, invisible, interior); } return undefined; } /** Create a ClipPlane * * "normal" (normalX, normalY, nz) is the inward normal of the plane. * * The given (normalX,normalY,normalZ) * * "point" is any point of the plane. * * The stored distance for the plane is the dot product of the point with the normal (i.e. treat the point's xyz as a vector from the origin.) */ public static createNormalAndPointXYZXYZ(normalX: number, normalY: number, normalZ: number, originX: number, originY: number, originZ: number, invisible: boolean = false, interior: boolean = false, result?: ClipPlane): ClipPlane | undefined { const q = Geometry.hypotenuseXYZ(normalX, normalY, normalZ); const r = Geometry.conditionalDivideFraction(1, q); if (r !== undefined) { if (result) { result._inwardNormal.set(normalX * r, normalY * r, normalZ * r); result._distanceFromOrigin = result._inwardNormal.dotProductXYZ(originX, originY, originZ); result._invisible = invisible; result._interior = interior; return result; } const normal = Vector3d.create(normalX * r, normalY * r, normalZ * r); return new ClipPlane(normal, normal.dotProductXYZ(originX, originY, originZ), invisible, interior); } return undefined; } /** * return a json object of the form * `{"normal":[u,v,w],"dist":signedDistanceValue,"interior":true,"invisible":true}` */ public toJSON(): ClipPlaneProps { const props: ClipPlaneProps = { normal: this.inwardNormalRef.toJSON(), dist: this.distance, }; if (this.interior) props.interior = true; if (this.invisible) props.invisible = true; return props; } /** parse json object to ClipPlane instance */ public static fromJSON(json: ClipPlaneProps, result?: ClipPlane): ClipPlane | undefined { if (json && json.normal && undefined !== json.dist && Number.isFinite(json.dist)) return ClipPlane.createNormalAndDistance(Vector3d.fromJSON(json.normal), json.dist, !!json.invisible, !!json.interior); return ClipPlane.createNormalAndDistance(Vector3d.unitZ(), 0, false, false, result); } /** Set both the invisible and interior flags. */ public setFlags(invisible: boolean, interior: boolean) { this._invisible = invisible; this._interior = interior; } /** * Return the stored distanceFromOrigin property. */ public get distance() { return this._distanceFromOrigin; } /** * Return the stored inward normal property. */ public get inwardNormalRef(): Vector3d { return this._inwardNormal; } /** * Return the "interior" property bit */ public get interior() { return this._interior; } /** * Return the "invisible" property bit. */ public get invisible() { return this._invisible; } /** * Create a plane defined by two points, an up vector, and a tilt angle relative to the up vector. * @param point0 start point of the edge * @param point1 end point of the edge * @param upVector vector perpendicular to the plane * @param tiltAngle angle to tilt the plane around the edge in the direction of the up vector. * @param result optional preallocated plane */ public static createEdgeAndUpVector(point0: Point3d, point1: Point3d, upVector: Vector3d, tiltAngle?: Angle, result?: ClipPlane): ClipPlane | undefined { const edgeVector = Vector3d.createFrom(point1.minus(point0)); let normal = (upVector.crossProduct(edgeVector)).normalize(); if (normal) { if (tiltAngle !== undefined && !tiltAngle.isAlmostZero) { const tiltNormal = Vector3d.createRotateVectorAroundVector(normal, edgeVector, tiltAngle); if (tiltNormal) { normal = tiltNormal.clone(); } } normal.negate(normal); return ClipPlane.createNormalAndPoint(normal, point0, false, false, result); } return undefined; } /** * Create a plane perpendicular to the edge between the xy parts of point0 and point1 */ public static createEdgeXY(point0: Point3d, point1: Point3d, result?: ClipPlane): ClipPlane | undefined { const normal = Vector3d.create(point0.y - point1.y, point1.x - point0.x); if (normal.normalizeInPlace()) return ClipPlane.createNormalAndPoint(normal, point0, false, false, result); return undefined; } /** * Return the Plane3d form of the plane. * * The plane origin is the point `distance * inwardNormal` * * The plane normal is the inward normal of the ClipPlane. */ public getPlane3d(): Plane3dByOriginAndUnitNormal { const d = this._distanceFromOrigin; // Normal should be normalized, will not return undefined return Plane3dByOriginAndUnitNormal.create(Point3d.create(this._inwardNormal.x * d, this._inwardNormal.y * d, this._inwardNormal.z * d), this._inwardNormal)!; } /** * Return the Point4d d form of the plane. * * The homogeneous xyz are the inward normal xyz. * * The homogeneous weight is the negated ClipPlane distance. */ public getPlane4d(): Point4d { return Point4d.create(this._inwardNormal.x, this._inwardNormal.y, this._inwardNormal.z, - this._distanceFromOrigin); } /** * Set the plane from DPoint4d style plane. * * The saved plane has its direction normalized. * * This preserves the plane itself as a zero set but make plane evaluations act as true distances (even if the plane coefficients are scaled otherwise) * @param plane */ public setPlane4d(plane: Point4d) { const a = Math.sqrt(plane.x * plane.x + plane.y * plane.y + plane.z * plane.z); const r = a === 0.0 ? 1.0 : 1.0 / a; this._inwardNormal.x = r * plane.x; this._inwardNormal.y = r * plane.y; this._inwardNormal.z = r * plane.z; this._distanceFromOrigin = -r * plane.w; } /** * Evaluate the altitude in weighted space, i.e. (dot product with inward normal) minus distance, with point.w scale applied to distance) * @param point space point to test */ public weightedAltitude(point: Point4d): number { return point.x * this._inwardNormal.x + point.y * this._inwardNormal.y + point.z * this._inwardNormal.z - point.w * this._distanceFromOrigin; } /** * Evaluate the distance from the plane to a point in space, i.e. (dot product with inward normal) minus distance * @param point space point to test */ public altitude(point: Point3d): number { return point.x * this._inwardNormal.x + point.y * this._inwardNormal.y + point.z * this._inwardNormal.z - this._distanceFromOrigin; } /** * Evaluate the distance from the plane to a point in space with point given as x,y,z, i.e. (dot product with inward normal) minus distance * @param point space point to test */ public altitudeXYZ(x: number, y: number, z: number): number { return x * this._inwardNormal.x + y * this._inwardNormal.y + z * this._inwardNormal.z - this._distanceFromOrigin; } /** * Return the x component of the normal used to evaluate altitude. */ public normalX(): number {return this._inwardNormal.x; } /** * Return the x component of the normal used to evaluate altitude. */ public normalY(): number {return this._inwardNormal.y; } /** * Return the z component of the normal used to evaluate altitude. */ public normalZ(): number {return this._inwardNormal.z; } /** Return the dot product of the plane normal with the vector (NOT using the plane's distanceFromOrigin). */ public velocity(vector: Vector3d): number { return vector.x * this._inwardNormal.x + vector.y * this._inwardNormal.y + vector.z * this._inwardNormal.z; } /** Return the dot product of the plane normal with the x,yz, vector components (NOT using the plane's distanceFromOrigin). */ public velocityXYZ(x: number, y: number, z: number): number { return x * this._inwardNormal.x + y * this._inwardNormal.y + z * this._inwardNormal.z; } /** Return the dot product of the plane normal with the point (treating the point xyz as a vector, and NOT using the plane's distanceFromOrigin). */ public dotProductPlaneNormalPoint(point: Point3d): number { return point.x * this._inwardNormal.x + point.y * this._inwardNormal.y + point.z * this._inwardNormal.z; } /** * Return true if spacePoint is inside or on the plane, with tolerance applied to "on". * @param spacePoint point to test. * @param tolerance tolerance for considering "near plane" to be "on plane" */ public isPointOnOrInside(spacePoint: Point3d, tolerance: number = Geometry.smallMetricDistance): boolean { let value = this.altitude(spacePoint); if (tolerance) { value += tolerance; } return value >= 0.0; } /** * Return true if spacePoint is strictly inside the halfspace, with tolerance applied to "on". * @param spacePoint point to test. * @param tolerance tolerance for considering "near plane" to be "on plane" */ public isPointInside(point: Point3d, tolerance: number = Geometry.smallMetricDistance): boolean { let value = this.altitude(point); if (tolerance) { value -= tolerance; } return value > 0.0; } /** * Return true if spacePoint is strictly on the plane, within tolerance * @param spacePoint point to test. * @param tolerance tolerance for considering "near plane" to be "on plane" */ public isPointOn(point: Point3d, tolerance: number = Geometry.smallMetricDistance): boolean { return Math.abs(this.altitude(point)) <= tolerance; } /** * Compute intersections of an (UNBOUNDED) arc with the plane. Append them (as radians) to a growing array. * @param arc arc to test. The angle limits of the arc are NOT considered. * @param intersectionRadians array to receive results */ public appendIntersectionRadians(arc: Arc3d, intersectionRadians: GrowableFloat64Array) { const arcVectors = arc.toVectors(); const alpha = this.altitude(arc.center); const beta = this.velocity(arcVectors.vector0); const gamma = this.velocity(arcVectors.vector90); AnalyticRoots.appendImplicitLineUnitCircleIntersections(alpha, beta, gamma, undefined, undefined, intersectionRadians); } private static _clipArcFractionArray = new GrowableFloat64Array(); /** Announce fractional intervals of arc clip. * * Each call to `announce(fraction0, fraction1, arc)` announces one interval that is inside the clip plane. */ public announceClippedArcIntervals(arc: Arc3d, announce?: AnnounceNumberNumberCurvePrimitive): boolean { const breaks = ClipPlane._clipArcFractionArray; breaks.clear(); this.appendIntersectionRadians(arc, breaks); arc.sweep.radiansArrayToPositivePeriodicFractions(breaks); return ClipUtilities.selectIntervals01(arc, breaks, this, announce); } /** * * Compute intersection of (unbounded) segment with the plane. * * If the ends are on the same side of the plane, return undefined. * * If the intersection is an endpoint or interior to the segment return the fraction. * * If both ends are on, return undefined. */ public getBoundedSegmentSimpleIntersection(pointA: Point3d, pointB: Point3d): number | undefined { const h0 = this.altitude(pointA); const h1 = this.altitude(pointB); if (h0 * h1 > 0.0) return undefined; if (h0 === 0.0 && h1 === 0.0) { return undefined; } return - h0 / (h1 - h0); } /** Apply transform to the origin. Apply inverse transpose of the matrix part to th normal vector. */ public transformInPlace(transform: Transform): boolean { const plane: Plane3dByOriginAndUnitNormal = this.getPlane3d(); const matrix: Matrix3d = transform.matrix; const newPoint = transform.multiplyPoint3d(plane.getOriginRef()); // Normal transforms as the inverse transpose of the matrix part // BTW: If the matrix is orthogonal, this is a long way to multiply by the matrix part (mumble grumble) const newNormal = matrix.multiplyInverseTranspose(plane.getNormalRef()); if (!newNormal) return false; plane.set(newPoint, newNormal); const normalized = (plane.getNormalRef()).normalize(); if (!normalized) return false; this._inwardNormal = normalized; this._distanceFromOrigin = this._inwardNormal.dotProduct(plane.getOriginRef()); return true; } /** Set the invisible flag. Interpretation of this is up to the use code algorithms. */ public setInvisible(invisible: boolean) { this._invisible = invisible; } /** reverse the sign of all coefficients, so outside and inside reverse */ public negateInPlace() { this._inwardNormal = this._inwardNormal.negate(); this._distanceFromOrigin = - this._distanceFromOrigin; } /** * Move the plane INWARD by given distance * @param offset distance of shift inwards */ public offsetDistance(offset: number) { this._distanceFromOrigin += offset; } /** * Clip a polygon to the inside or outside of the plane. * * Results with 2 or fewer points are ignored. * * Other than ensuring capacity in the arrays, there are no object allocations during execution of this function. * @param xyz input points. * @param work work buffer * @param tolerance tolerance for "on plane" decision. */ public clipConvexPolygonInPlace(xyz: GrowableXYZArray, work: GrowableXYZArray, inside: boolean = true, tolerance: number = Geometry.smallMetricDistance) { return IndexedXYZCollectionPolygonOps.clipConvexPolygonInPlace(this, xyz, work, inside, tolerance); } /** * Multiply the ClipPlane's DPoint4d by matrix. * @param matrix matrix to apply. * @param invert if true, use in verse of the matrix. * @param transpose if true, use the transpose of the matrix (or inverse, per invert parameter) * * Note that if matrixA is applied to all of space, the matrix to send to this method to get a corresponding effect on the plane is the inverse transpose of matrixA * * Callers that will apply the same matrix to many planes should pre-invert the matrix for efficiency. * * Both params default to true to get the full effect of transforming space. * @param matrix matrix to apply * @return false if unable to invert */ public multiplyPlaneByMatrix4d(matrix: Matrix4d, invert: boolean = true, transpose: boolean = true): boolean { const plane: Point4d = this.getPlane4d(); if (invert) { const inverse = matrix.createInverse(); if (inverse) return this.multiplyPlaneByMatrix4d(inverse, false, transpose); return false; } if (transpose) matrix.multiplyTransposePoint4d(plane, plane); else matrix.multiplyPoint4d(plane, plane); this.setPlane4d(plane); return true; } /** announce the interval (if any) where a line is within the clip plane half space. */ public announceClippedSegmentIntervals(f0: number, f1: number, pointA: Point3d, pointB: Point3d, announce?: (fraction0: number, fraction1: number) => void): boolean { if (f1 < f0) return false; const h0 = - this.altitude(pointA); const h1 = - this.altitude(pointB); const delta = h1 - h0; const f = Geometry.conditionalDivideFraction(-h0, delta); if (f === undefined) { // The segment is parallel to the plane. if (h0 <= 0.0) { if (announce) announce(f0, f1); return true; } return false; } if (delta > 0) { // segment aims OUT if (f < f1) f1 = f; } else { // segment aims IN if (f > f0) f0 = f; } if (f1 < f0) return false; if (announce) announce(f0, f1); return true; } /** * Return a coordinate frame with * * origin at closest point to global origin * * z axis points in * x and y are "in plane" */ public getFrame(): Transform { const d = this._distanceFromOrigin; const origin = Point3d.create(this._inwardNormal.x * d, this._inwardNormal.y * d, this._inwardNormal.z * d); const matrix = Matrix3d.createRigidHeadsUp(this._inwardNormal, AxisOrder.ZXY); return Transform.createOriginAndMatrix(origin, matrix); } /** * Return the intersection of the plane with a range cube. * @param range * @param xyzOut intersection polygon. This is convex. */ public intersectRange(range: Range3d, addClosurePoint: boolean = false): GrowableXYZArray | undefined { if (range.isNull) return undefined; const corners = range.corners(); const frameOnPlane = this.getFrame(); frameOnPlane.multiplyInversePoint3dArrayInPlace(corners); const localRange = Range3d.createArray(corners); if (localRange.low.z * localRange.high.z > 0.0) return undefined; // oversized polygon on local z= 0 const xyzOut = new GrowableXYZArray(); xyzOut.pushXYZ(localRange.low.x, localRange.low.y, 0); xyzOut.pushXYZ(localRange.high.x, localRange.low.y, 0); xyzOut.pushXYZ(localRange.high.x, localRange.high.y, 0); xyzOut.pushXYZ(localRange.low.x, localRange.high.y, 0); xyzOut.multiplyTransformInPlace(frameOnPlane); IndexedXYZCollectionPolygonOps.intersectRangeConvexPolygonInPlace(range, xyzOut); if (xyzOut.length === 0) return undefined; if (addClosurePoint) xyzOut.pushWrap(1); return xyzOut; } /** Implement appendPolygonClip, as defined in interface PolygonClipper. /** * * @param xyz input polygon. This is not changed. * @param insideFragments Array to receive "inside" fragments. Each fragment is a GrowableXYZArray grabbed from the cache. This is NOT cleared. * @param outsideFragments Array to receive "outside" fragments. Each fragment is a GrowableXYZArray grabbed from the cache. This is NOT cleared. * @param arrayCache cache for reusable GrowableXYZArray. */ public appendPolygonClip( xyz: GrowableXYZArray, insideFragments: GrowableXYZArray[], outsideFragments: GrowableXYZArray[], arrayCache: GrowableXYZArrayCache): void { const perpendicularRange = Range1d.createNull(); const newInside = arrayCache.grabFromCache(); const newOutside = arrayCache.grabFromCache(); IndexedXYZCollectionPolygonOps.splitConvexPolygonInsideOutsidePlane(this, xyz, newInside, newOutside, perpendicularRange); ClipUtilities.captureOrDrop(newInside, 3, insideFragments, arrayCache); ClipUtilities.captureOrDrop(newOutside, 3, outsideFragments, arrayCache); } }
the_stack
import { promises, readFileSync } from 'fs' import { platform } from 'os' import { join } from 'path' import ava, { TestInterface } from 'ava' import PNG from '@jimp/png' import { GlobalFonts, createCanvas, Canvas, Image, ImageData, Path2D, SKRSContext2D, DOMMatrix } from '../index' import { snapshotImage } from './image-snapshot' const test = ava as TestInterface<{ canvas: Canvas ctx: SKRSContext2D }> const png = PNG() const fontIosevka = readFileSync(join(__dirname, 'fonts', 'iosevka-slab-regular.ttf')) const fontSourceSerifPro = readFileSync(join(__dirname, 'fonts', 'SourceSerifPro-Regular.ttf')) const fontOSRSPath = join(__dirname, 'fonts', 'osrs-font-compact.otf') console.assert(GlobalFonts.register(fontIosevka), 'Register Iosevka font failed') console.assert(GlobalFonts.register(fontSourceSerifPro), 'Register SourceSerifPro font failed') test.beforeEach((t) => { const canvas = createCanvas(512, 512) t.context.canvas = canvas t.context.ctx = canvas.getContext('2d')! }) test('alpha-false', async (t) => { const canvas = createCanvas(512, 512) const ctx = canvas.getContext('2d', { alpha: false }) await snapshotImage(t, { canvas, ctx }) }) test('arc', async (t) => { const { ctx } = t.context ctx.beginPath() ctx.arc(100, 75, 50, 0, 2 * Math.PI) ctx.stroke() await snapshotImage(t) }) test('arcTo', async (t) => { const { ctx } = t.context ctx.beginPath() ctx.moveTo(180, 90) ctx.arcTo(180, 130, 110, 130, 130) ctx.lineTo(110, 130) ctx.stroke() await snapshotImage(t) }) test('arcTo-colorful', async (t) => { const { ctx } = t.context ctx.beginPath() ctx.strokeStyle = 'gray' ctx.moveTo(200, 20) ctx.lineTo(200, 130) ctx.lineTo(50, 20) ctx.stroke() // Arc ctx.beginPath() ctx.strokeStyle = 'black' ctx.lineWidth = 5 ctx.moveTo(200, 20) ctx.arcTo(200, 130, 50, 20, 40) ctx.stroke() // Start point ctx.beginPath() ctx.fillStyle = 'blue' ctx.arc(200, 20, 5, 0, 2 * Math.PI) ctx.fill() // Control points ctx.beginPath() ctx.fillStyle = 'red' ctx.arc(200, 130, 5, 0, 2 * Math.PI) // Control point one ctx.arc(50, 20, 5, 0, 2 * Math.PI) // Control point two ctx.fill() await snapshotImage(t) }) test('beginPath', async (t) => { const { ctx } = t.context ctx.beginPath() ctx.strokeStyle = 'blue' ctx.moveTo(20, 20) ctx.lineTo(200, 20) ctx.stroke() // Second path ctx.beginPath() ctx.strokeStyle = 'green' ctx.moveTo(20, 20) ctx.lineTo(120, 120) ctx.stroke() await snapshotImage(t) }) test('bezierCurveTo', async (t) => { const { ctx } = t.context ctx.beginPath() ctx.moveTo(30, 30) ctx.bezierCurveTo(120, 160, 180, 10, 220, 140) ctx.stroke() await snapshotImage(t) }) test('bezierCurveTo-colorful', async (t) => { const { ctx } = t.context const start = { x: 50, y: 20 } const cp1 = { x: 230, y: 30 } const cp2 = { x: 150, y: 80 } const end = { x: 250, y: 100 } // Cubic Bézier curve ctx.beginPath() ctx.moveTo(start.x, start.y) ctx.bezierCurveTo(cp1.x, cp1.y, cp2.x, cp2.y, end.x, end.y) ctx.stroke() // Start and end points ctx.fillStyle = 'blue' ctx.beginPath() ctx.arc(start.x, start.y, 5, 0, 2 * Math.PI) // Start point ctx.arc(end.x, end.y, 5, 0, 2 * Math.PI) // End point ctx.fill() // Control points ctx.fillStyle = 'red' ctx.beginPath() ctx.arc(cp1.x, cp1.y, 5, 0, 2 * Math.PI) // Control point one ctx.arc(cp2.x, cp2.y, 5, 0, 2 * Math.PI) // Control point two ctx.fill() await snapshotImage(t) }) test('clearRect', async (t) => { const { ctx, canvas } = t.context ctx.beginPath() ctx.fillStyle = '#ff6' ctx.fillRect(0, 0, canvas.width, canvas.height) // Draw blue triangle ctx.beginPath() ctx.fillStyle = 'blue' ctx.moveTo(20, 20) ctx.lineTo(180, 20) ctx.lineTo(130, 130) ctx.closePath() ctx.fill() // Clear part of the canvas ctx.clearRect(10, 10, 120, 100) await snapshotImage(t) }) test('clip', async (t) => { const { ctx, canvas } = t.context // Create circular clipping region ctx.beginPath() ctx.arc(100, 75, 50, 0, Math.PI * 2) ctx.clip() // Draw stuff that gets clipped ctx.fillStyle = 'blue' ctx.fillRect(0, 0, canvas.width, canvas.height) ctx.fillStyle = 'orange' ctx.fillRect(0, 0, 100, 100) await snapshotImage(t) }) test('closePath', async (t) => { const { ctx } = t.context ctx.beginPath() ctx.moveTo(20, 140) // Move pen to bottom-left corner ctx.lineTo(120, 10) // Line to top corner ctx.lineTo(220, 140) // Line to bottom-right corner ctx.closePath() // Line to bottom-left corner ctx.stroke() await snapshotImage(t) }) test('closePath-arc', async (t) => { const { ctx } = t.context ctx.beginPath() ctx.arc(240, 20, 40, 0, Math.PI) ctx.moveTo(100, 20) ctx.arc(60, 20, 40, 0, Math.PI) ctx.moveTo(215, 80) ctx.arc(150, 80, 65, 0, Math.PI) ctx.closePath() ctx.lineWidth = 6 ctx.stroke() await snapshotImage(t) }) test('createImageData', async (t) => { const { ctx } = t.context const imageData = ctx.createImageData(256, 256) // Iterate through every pixel for (let i = 0; i < imageData.data.length; i += 4) { // Modify pixel data imageData.data[i + 0] = 190 // R value imageData.data[i + 1] = 0 // G value imageData.data[i + 2] = 210 // B value imageData.data[i + 3] = 255 // A value } // Draw image data to the canvas ctx.putImageData(imageData, 20, 20) await snapshotImage(t) }) test('createLinearGradient', async (t) => { const { ctx } = t.context const gradient = ctx.createLinearGradient(20, 0, 220, 0) // Add three color stops gradient.addColorStop(0, 'green') gradient.addColorStop(0.5, 'cyan') gradient.addColorStop(1, 'green') // Set the fill style and draw a rectangle ctx.fillStyle = gradient ctx.fillRect(20, 20, 200, 100) await snapshotImage(t) }) test('createPattern-no-transform', async (t) => { const { ctx } = t.context const imageSrc = await promises.readFile(join(__dirname, 'canvas_createpattern.png')) const image = new Image() image.src = imageSrc const pattern = ctx.createPattern(image, 'repeat') ctx.fillStyle = pattern ctx.fillRect(0, 0, 300, 300) await snapshotImage(t) }) test('createPattern-no-transform-imagedata', async (t) => { const { ctx } = t.context const imageSrc = await promises.readFile(join(__dirname, 'canvas_createpattern.png')) const imageMeta = png.decoders['image/png'](imageSrc) const imageData = new ImageData(new Uint8ClampedArray(imageMeta.data), imageMeta.width, imageMeta.height) const pattern = ctx.createPattern(imageData, 'repeat') ctx.fillStyle = pattern ctx.fillRect(0, 0, 300, 300) await snapshotImage(t) }) test('createPattern-with-transform', async (t) => { const { ctx } = t.context const imageSrc = await promises.readFile(join(__dirname, 'canvas_createpattern.png')) const image = new Image() image.src = imageSrc const pattern = ctx.createPattern(image, 'repeat') const matrix = new DOMMatrix() pattern.setTransform(matrix.rotate(-45).scale(1.5)) ctx.fillStyle = pattern ctx.fillRect(0, 0, 300, 300) await snapshotImage(t) }) test('createRadialGradient', async (t) => { const { ctx } = t.context const gradient = ctx.createRadialGradient(110, 90, 30, 100, 100, 70) // Add three color stops gradient.addColorStop(0, 'pink') gradient.addColorStop(0.9, 'white') gradient.addColorStop(1, 'green') // Set the fill style and draw a rectangle ctx.fillStyle = gradient ctx.fillRect(20, 20, 160, 160) await snapshotImage(t) }) test('createConicGradient', async (t) => { const { ctx } = t.context const gradient = ctx.createConicGradient(0, 100, 100) // Add five color stops gradient.addColorStop(0, 'red') gradient.addColorStop(0.25, 'orange') gradient.addColorStop(0.5, 'yellow') gradient.addColorStop(0.75, 'green') gradient.addColorStop(1, 'blue') // Set the fill style and draw a rectangle ctx.fillStyle = gradient ctx.fillRect(20, 20, 200, 200) await snapshotImage(t) }) test('drawImage', async (t) => { const { ctx } = t.context const filePath = './javascript.png' const file = await promises.readFile(join(__dirname, filePath)) const image = new Image() image.src = file ctx.drawImage(image, 0, 0) await snapshotImage(t) }) test('drawImage-svg', async (t) => { const { ctx } = t.context const filePath = './mountain.svg' const file = await promises.readFile(join(__dirname, filePath)) const image = new Image() image.src = file ctx.drawImage(image, 0, 0) await snapshotImage(t) }) test('drawImage-svg-with-only-viewBox', async (t) => { const { ctx } = t.context const filePath = './only-viewbox.svg' const file = await promises.readFile(join(__dirname, filePath)) const image = new Image() image.src = file ctx.drawImage(image, 0, 0) await snapshotImage(t) }) test('drawImage-svg-resize', async (t) => { const { ctx, canvas } = t.context const filePath = './resize.svg' const file = await promises.readFile(join(__dirname, filePath)) const image = new Image() image.src = file image.width = 100 image.height = 100 ctx.drawImage(image, 0, 0) await snapshotImage(t, { canvas, ctx }, 'png', 0.2) }) test.skip('drawImage-svg-with-css', async (t) => { const { ctx } = t.context const filePath = './css-style.svg' const file = await promises.readFile(join(__dirname, filePath)) const image = new Image() image.src = file ctx.drawImage(image, 0, 0) await snapshotImage(t) }) test('drawImage-svg without width height should be empty image', async (t) => { const { ctx, canvas } = t.context const filePath = './mountain.svg' const svgContent = (await promises.readFile(join(__dirname, filePath))).toString('utf-8') const image = new Image() image.src = Buffer.from(svgContent.replace('width="128"', '').replace('height="128"', '')) ctx.drawImage(image, 0, 0) const output = await canvas.encode('png') const outputData = png.decoders['image/png'](output) t.deepEqual(outputData.data, Buffer.alloc(outputData.width * outputData.height * 4, 0)) }) test('draw-image-svg-noto-emoji', async (t) => { const { ctx } = t.context const filePath = './notoemoji-person.svg' const file = await promises.readFile(join(__dirname, filePath)) const image = new Image() image.src = file ctx.drawImage(image, 0, 0) await snapshotImage(t) }) test('drawImage-another-Canvas', async (t) => { const { ctx } = t.context ctx.fillStyle = 'hotpink' ctx.fillRect(10, 10, 100, 100) const anotherCanvas = createCanvas(200, 200) const anotherContext = anotherCanvas.getContext('2d') anotherContext.beginPath() anotherContext.ellipse(80, 80, 50, 75, Math.PI / 4, 0, 2 * Math.PI) anotherContext.stroke() // Draw the ellipse's line of reflection anotherContext.beginPath() anotherContext.setLineDash([5, 5]) anotherContext.moveTo(10, 150) anotherContext.lineTo(150, 10) anotherContext.stroke() ctx.drawImage(anotherCanvas, 150, 150) await snapshotImage(t) }) test('ellipse', async (t) => { const { ctx } = t.context // Draw the ellipse ctx.beginPath() ctx.ellipse(100, 100, 50, 75, Math.PI / 4, 0, 2 * Math.PI) ctx.stroke() // Draw the ellipse's line of reflection ctx.beginPath() ctx.setLineDash([5, 5]) ctx.moveTo(0, 200) ctx.lineTo(200, 0) ctx.stroke() await snapshotImage(t) }) test('fill', async (t) => { const { ctx } = t.context const region = new Path2D() region.moveTo(30, 90) region.lineTo(110, 20) region.lineTo(240, 130) region.lineTo(60, 130) region.lineTo(190, 20) region.lineTo(270, 90) region.closePath() // Fill path ctx.fillStyle = 'green' ctx.fill(region, 'evenodd') await snapshotImage(t) }) test('fillRect', async (t) => { const { ctx } = t.context ctx.fillStyle = 'hotpink' ctx.fillRect(20, 10, 150, 100) await snapshotImage(t) }) test('fillText', async (t) => { const { ctx, canvas } = t.context ctx.fillStyle = 'yellow' ctx.fillRect(0, 0, canvas.width, canvas.height) ctx.fillStyle = 'black' ctx.font = '48px Iosevka Slab' ctx.fillText('skr canvas', 50, 150) const gradient = ctx.createConicGradient(0, 100, 100) // Add five color stops gradient.addColorStop(0, 'red') gradient.addColorStop(0.15, 'orange') gradient.addColorStop(0.25, 'yellow') gradient.addColorStop(0.35, 'orange') gradient.addColorStop(0.5, 'green') gradient.addColorStop(0.75, 'cyan') gradient.addColorStop(1, 'blue') // Set the fill style and draw a rectangle ctx.fillStyle = gradient ctx.fillText('@napi-rs/canvas', 50, 250) await snapshotImage(t, { canvas, ctx }, 'png', 3.2) }) test('fillText-maxWidth', async (t) => { const { ctx, canvas } = t.context ctx.fillStyle = 'white' ctx.fillRect(0, 0, canvas.width, canvas.height) ctx.fillStyle = 'black' ctx.font = '24px Iosevka Slab' ctx.fillText('Hello world', 50, 90, 90) ctx.fillText('Hello world', 160, 90) await snapshotImage(t, { canvas, ctx }, 'png', 0.8) }) test('fillText-AA', async (t) => { GlobalFonts.registerFromPath(fontOSRSPath) const { ctx, canvas } = t.context ctx.imageSmoothingEnabled = false ctx.font = '16px OSRSFontCompact' ctx.fillStyle = 'white' ctx.fillRect(0, 0, 100, 100) ctx.fillStyle = 'black' ctx.fillText('@napi-rs/canvas', 10, 10) ctx.fillText('ABC abc 123', 10, 40) await snapshotImage(t, { canvas, ctx }, 'png', 3.2) }) test('fillText-COLRv1', async (t) => { const { ctx, canvas } = t.context GlobalFonts.registerFromPath(join(__dirname, 'fonts', 'COLRv1.ttf'), 'Colrv1') ctx.font = '100px Colrv1' ctx.fillText('abc', 50, 100) await snapshotImage(t, { canvas, ctx }, 'png', 0.5) }) test('getContextAttributes', (t) => { const defaultCtx = t.context.ctx const defaultAttrs = defaultCtx.getContextAttributes() t.is(defaultAttrs.alpha, true) t.is(defaultAttrs.desynchronized, false) const canvas = createCanvas(512, 512) const ctx = canvas.getContext('2d', { alpha: false }) const customAttrs = ctx.getContextAttributes() t.is(customAttrs.alpha, false) t.is(customAttrs.desynchronized, false) }) test('getImageData', async (t) => { const { ctx } = t.context ctx.rect(10, 10, 100, 100) ctx.fill() const imageData = ctx.getImageData(60, 60, 200, 100) ctx.putImageData(imageData, 150, 10) await snapshotImage(t) }) test('isPointInPath', (t) => { const { ctx } = t.context ctx.rect(0, 0, 100, 100) t.is(ctx.isPointInPath(50, -1), false) // Outside the rect t.is(ctx.isPointInPath(50, 0), true) // On the edge of the rect t.is(ctx.isPointInPath(50, 1), true) // Inside the rect ctx.rect(40, 40, 20, 20) // Overlap the area center t.is(ctx.isPointInPath(50, 50), true) t.is(ctx.isPointInPath(50, 50, 'nonzero'), true) t.is(ctx.isPointInPath(50, 50, 'evenodd'), false) const path = new Path2D() path.rect(0, 0, 100, 100) t.is(ctx.isPointInPath(path, 50, -1), false) t.is(ctx.isPointInPath(path, 50, 1), true) path.rect(40, 40, 20, 20) t.is(ctx.isPointInPath(path, 50, 50), true) t.is(ctx.isPointInPath(path, 50, 50, 'nonzero'), true) t.is(ctx.isPointInPath(path, 50, 50, 'evenodd'), false) }) test('isPointInStroke', (t) => { const { ctx } = t.context ctx.rect(10, 10, 100, 100) ctx.stroke() t.is(ctx.isPointInStroke(50, 9), false) // Outside the rect t.is(ctx.isPointInStroke(50, 10), true) // On the edge of the rect t.is(ctx.isPointInStroke(50, 11), false) // Inside the rect ctx.lineWidth = 3 ctx.stroke() // All points on the edge now t.is(ctx.isPointInStroke(50, 9), true) t.is(ctx.isPointInStroke(50, 10), true) t.is(ctx.isPointInStroke(50, 11), true) ctx.lineWidth = 1 const path = new Path2D() path.rect(10, 10, 100, 100) t.is(ctx.isPointInStroke(path, 50, 9), false) t.is(ctx.isPointInStroke(path, 50, 10), true) t.is(ctx.isPointInStroke(path, 50, 11), false) }) test('lineTo', async (t) => { const { ctx } = t.context ctx.beginPath() // Start a new path ctx.moveTo(30, 50) // Move the pen to (30, 50) ctx.lineTo(150, 100) // Draw a line to (150, 100) ctx.stroke() // Render the path await snapshotImage(t) }) test('measureText', (t) => { const { ctx } = t.context ctx.font = '50px Iosevka Slab' const metrics = ctx.measureText('@napi-rs/canvas') t.is(metrics.actualBoundingBoxLeft, -3) t.true(Math.abs(metrics.actualBoundingBoxRight - 372) < 0.001) }) test('moveTo', async (t) => { const { ctx } = t.context ctx.beginPath() ctx.moveTo(50, 50) // Begin first sub-path ctx.lineTo(200, 50) ctx.moveTo(50, 90) // Begin second sub-path ctx.lineTo(280, 120) ctx.stroke() await snapshotImage(t) }) test('putImageData', async (t) => { const { ctx } = t.context function putImageData( imageData: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number, ) { const data = imageData.data const height = imageData.height const width = imageData.width dirtyX = dirtyX || 0 dirtyY = dirtyY || 0 dirtyWidth = dirtyWidth !== undefined ? dirtyWidth : width dirtyHeight = dirtyHeight !== undefined ? dirtyHeight : height const limitBottom = dirtyY + dirtyHeight const limitRight = dirtyX + dirtyWidth for (let y = dirtyY; y < limitBottom; y++) { for (let x = dirtyX; x < limitRight; x++) { const pos = y * width + x ctx.fillStyle = 'rgba(' + data[pos * 4 + 0] + ',' + data[pos * 4 + 1] + ',' + data[pos * 4 + 2] + ',' + data[pos * 4 + 3] / 255 + ')' ctx.fillRect(x + dx, y + dy, 1, 1) } } } // Draw content onto the canvas ctx.fillRect(0, 0, 100, 100) // Create an ImageData object from it const imagedata = ctx.getImageData(0, 0, 100, 100) // use the putImageData function that illustrates how putImageData works putImageData(imagedata, 150, 0, 50, 50, 25, 25) await snapshotImage(t) }) test('quadraticCurveTo', async (t) => { const { ctx } = t.context // Quadratic Bézier curve ctx.beginPath() ctx.moveTo(50, 20) ctx.quadraticCurveTo(230, 30, 50, 100) ctx.stroke() // Start and end points ctx.fillStyle = 'blue' ctx.beginPath() ctx.arc(50, 20, 5, 0, 2 * Math.PI) // Start point ctx.arc(50, 100, 5, 0, 2 * Math.PI) // End point ctx.fill() // Control point ctx.fillStyle = 'red' ctx.beginPath() ctx.arc(230, 30, 5, 0, 2 * Math.PI) ctx.fill() await snapshotImage(t) }) test('rect', async (t) => { const { ctx } = t.context ctx.fillStyle = 'yellow' ctx.rect(10, 20, 150, 100) ctx.fill() await snapshotImage(t) }) test('resetTransform', async (t) => { const { ctx } = t.context // Skewed rects ctx.transform(1, 0, 1.7, 1, 0, 0) ctx.fillStyle = 'gray' ctx.fillRect(40, 40, 50, 20) ctx.fillRect(40, 90, 50, 20) // Non-skewed rects ctx.resetTransform() ctx.fillStyle = 'red' ctx.fillRect(40, 40, 50, 20) ctx.fillRect(40, 90, 50, 20) await snapshotImage(t) }) test('save-restore', async (t) => { const { ctx } = t.context // Save the default state ctx.save() ctx.fillStyle = 'green' ctx.fillRect(10, 10, 100, 100) // Restore the default state ctx.restore() ctx.fillRect(150, 40, 100, 100) await snapshotImage(t) }) test('rotate', async (t) => { const { ctx } = t.context // Point of transform origin ctx.arc(0, 0, 5, 0, 2 * Math.PI) ctx.fillStyle = 'blue' ctx.fill() // Non-rotated rectangle ctx.fillStyle = 'gray' ctx.fillRect(100, 0, 80, 20) // Rotated rectangle ctx.rotate((45 * Math.PI) / 180) ctx.fillStyle = 'red' ctx.fillRect(100, 0, 80, 20) // Reset transformation matrix to the identity matrix ctx.setTransform(1, 0, 0, 1, 0, 0) ctx.fillStyle = 'hotpink' ctx.fillRect(100, 50, 80, 20) await snapshotImage(t) }) test('scale', async (t) => { const { ctx } = t.context // Scaled rectangle ctx.scale(9, 3) ctx.fillStyle = 'red' ctx.fillRect(10, 10, 8, 20) // Reset current transformation matrix to the identity matrix ctx.setTransform(1, 0, 0, 1, 0, 0) // Non-scaled rectangle ctx.fillStyle = 'gray' ctx.fillRect(10, 10, 8, 20) await snapshotImage(t) }) test('setLineDash', async (t) => { const { ctx } = t.context // Dashed line ctx.beginPath() ctx.setLineDash([5, 15]) ctx.moveTo(0, 50) ctx.lineTo(300, 50) ctx.stroke() // Solid line ctx.beginPath() ctx.setLineDash([]) ctx.moveTo(0, 100) ctx.lineTo(300, 100) ctx.stroke() await snapshotImage(t) }) test('setTransform', async (t) => { const { ctx } = t.context ctx.setTransform(1, 0.2, 0.8, 1, 0, 0) ctx.fillRect(0, 0, 100, 100) await snapshotImage(t) }) test('stroke', async (t) => { const { ctx } = t.context // First sub-path ctx.lineWidth = 26 ctx.strokeStyle = 'orange' ctx.moveTo(20, 20) ctx.lineTo(160, 20) ctx.stroke() // Second sub-path ctx.lineWidth = 14 ctx.strokeStyle = 'green' ctx.moveTo(20, 80) ctx.lineTo(220, 80) ctx.stroke() // Third sub-path ctx.lineWidth = 4 ctx.strokeStyle = 'pink' ctx.moveTo(20, 140) ctx.lineTo(280, 140) ctx.stroke() await snapshotImage(t) }) test('stroke-and-filling', async (t) => { const { ctx } = t.context ctx.lineWidth = 16 ctx.strokeStyle = 'red' // Stroke on top of fill ctx.beginPath() ctx.rect(25, 25, 100, 100) ctx.fill() ctx.stroke() // Fill on top of stroke ctx.beginPath() ctx.rect(175, 25, 100, 100) ctx.stroke() ctx.fill() await snapshotImage(t) }) test('strokeRect', async (t) => { const { ctx } = t.context ctx.shadowColor = '#d53' ctx.shadowBlur = 20 ctx.lineJoin = 'bevel' ctx.lineWidth = 15 ctx.strokeStyle = '#38f' ctx.strokeRect(30, 30, 160, 90) await snapshotImage(t) }) test('strokeText', async (t) => { const { ctx, canvas } = t.context ctx.fillStyle = 'yellow' ctx.fillRect(0, 0, canvas.width, canvas.height) ctx.strokeStyle = 'black' ctx.lineWidth = 3 ctx.font = '50px Iosevka Slab' ctx.strokeText('skr canvas', 50, 150) const gradient = ctx.createConicGradient(0, 100, 100) // Add five color stops gradient.addColorStop(0, 'red') gradient.addColorStop(0.15, 'orange') gradient.addColorStop(0.25, 'yellow') gradient.addColorStop(0.35, 'orange') gradient.addColorStop(0.5, 'green') gradient.addColorStop(0.75, 'cyan') gradient.addColorStop(1, 'blue') // Set the fill style and draw a rectangle ctx.strokeStyle = gradient ctx.strokeText('@napi-rs/canvas', 50, 300) await snapshotImage(t, { canvas, ctx }, 'png', 3.5) }) test('draw-text-emoji', async (t) => { if (platform() === 'darwin') { t.pass('macOS definitely supports emoji') return } const { ctx, canvas } = t.context GlobalFonts.registerFromPath(join(__dirname, 'fonts', 'AppleColorEmoji@2x.ttf')) ctx.font = '50px Apple Color Emoji' ctx.strokeText('😀😃😄😁😆😅', 50, 100) ctx.fillText('😂🤣☺️😊😊😇', 50, 220) await snapshotImage(t, { canvas, ctx }, 'png', 0.05) }) test('transform', async (t) => { const { ctx } = t.context ctx.transform(1, 0.2, 0.8, 1, 0, 0) ctx.fillRect(0, 0, 100, 100) ctx.resetTransform() ctx.fillRect(220, 0, 100, 100) await snapshotImage(t) }) test('translate', async (t) => { const { ctx } = t.context drawTranslate(ctx) await snapshotImage(t) }) test('translate-with-transform', async (t) => { const { ctx } = t.context ctx.translate(110, 30) ctx.transform(1, 0, 0, 1, -20, -10) ctx.transform(1, 0, 0, 1, 0, 0) ctx.fillStyle = 'red' ctx.fillRect(-30, -10, 80, 80) await snapshotImage(t) }) test('webp-output', async (t) => { const { ctx } = t.context drawTranslate(ctx) await snapshotImage(t, t.context, 'webp') }) test('avif-output', async (t) => { const { ctx } = t.context drawTranslate(ctx) await snapshotImage(t, t.context, 'avif') }) test('raw output', async (t) => { const { ctx, canvas } = t.context drawTranslate(ctx) const output = canvas.data() const pngFromCanvas = await canvas.encode('png') const pngOutput = png.decoders['image/png'](pngFromCanvas) t.deepEqual(output, pngOutput.data) }) test('toDataURL', async (t) => { const { ctx, canvas } = t.context drawTranslate(ctx) const output = canvas.toDataURL() const prefix = 'data:image/png;base64,' t.true(output.startsWith(prefix)) const imageBase64 = output.substr(prefix.length) const pngBuffer = Buffer.from(imageBase64, 'base64') t.deepEqual(pngBuffer, await canvas.encode('png')) }) test('JPEG toDataURL with quality', async (t) => { const { ctx, canvas } = t.context drawTranslate(ctx) const output = canvas.toDataURL('image/jpeg', 20) const prefix = 'data:image/jpeg;base64,' t.true(output.startsWith(prefix)) const imageBase64 = output.substr(prefix.length) const pngBuffer = Buffer.from(imageBase64, 'base64') t.deepEqual(pngBuffer, await canvas.encode('jpeg', 20)) }) test('WebP toDataURL with quality', async (t) => { const { ctx, canvas } = t.context drawTranslate(ctx) const output = canvas.toDataURL('image/webp', 100) const prefix = 'data:image/webp;base64,' t.true(output.startsWith(prefix)) const imageBase64 = output.substr(prefix.length) const pngBuffer = Buffer.from(imageBase64, 'base64') t.deepEqual(pngBuffer, await canvas.encode('webp', 100)) }) test('toDataURLAsync', async (t) => { const { ctx, canvas } = t.context drawTranslate(ctx) const output = await canvas.toDataURLAsync() const prefix = 'data:image/png;base64,' t.true(output.startsWith(prefix)) const imageBase64 = output.substr(prefix.length) const pngBuffer = Buffer.from(imageBase64, 'base64') t.deepEqual(pngBuffer, await canvas.encode('png')) }) test('shadowOffsetX', async (t) => { const { ctx } = t.context ctx.shadowColor = 'red' ctx.shadowOffsetX = 25 ctx.shadowBlur = 10 // Rectangle ctx.fillStyle = 'blue' ctx.fillRect(20, 20, 150, 100) await snapshotImage(t) }) test('shadowOffsetY', async (t) => { const { ctx } = t.context ctx.shadowColor = 'red' ctx.shadowOffsetY = 25 ctx.shadowBlur = 10 // Rectangle ctx.fillStyle = 'blue' ctx.fillRect(20, 20, 150, 80) await snapshotImage(t) }) function drawTranslate(ctx: SKRSContext2D) { // Moved square ctx.translate(110, 30) ctx.fillStyle = 'red' ctx.fillRect(0, 0, 80, 80) // Reset current transformation matrix to the identity matrix ctx.setTransform(1, 0, 0, 1, 0, 0) // Unmoved square ctx.fillStyle = 'gray' ctx.fillRect(0, 0, 80, 80) }
the_stack
import delay from 'delay' import { mockProcessExit, mockProcessStderr, mockProcessStdout } from 'jest-mock-process' import { Observable } from 'rxjs' import { Listr } from '@root/index' describe('show output from task', () => { let mockExit: jest.SpyInstance<never, [number?]> // eslint-disable-next-line @typescript-eslint/ban-types let mockStdout: jest.SpyInstance<boolean, [string, string?, Function?]> // eslint-disable-next-line @typescript-eslint/ban-types let mockStderr: jest.SpyInstance<boolean, [string, string?, Function?]> process.stdout.isTTY = true beforeEach(async () => { mockExit = mockProcessExit() mockStdout = mockProcessStdout() mockStderr = mockProcessStderr() }) afterEach(async () => { mockExit.mockRestore() mockStdout.mockRestore() mockStderr.mockRestore() jest.clearAllMocks() }) // rMG224TBrLk3ocYtKidc1D4AyZtEHm11 it('should yield example output', async () => { await new Listr( [ { title: 'This task will execute.', task: async (ctx, task): Promise<void> => { task.output = 'I will push an output. [0]' await delay(5) task.output = 'I will push an output. [1]' await delay(5) task.output = 'I will push an output. [2]' await delay(5) }, options: { persistentOutput: false } } ], { concurrent: false, rendererOptions: { lazy: true } } ).run() expect(mockStdout.mock.calls).toMatchSnapshot('rMG224TBrLk3ocYtKidc1D4AyZtEHm11-out') expect(mockStderr.mock.calls).toMatchSnapshot('rMG224TBrLk3ocYtKidc1D4AyZtEHm11-err') expect(mockExit.mock.calls).toMatchSnapshot('rMG224TBrLk3ocYtKidc1D4AyZtEHm11-exit') }) // oYHBlOYGg8juKRkaqigY617eyLbGMuDd it('should have persistent output', async () => { await new Listr( [ { title: 'This task will execute.', task: async (ctx, task): Promise<void> => { task.output = 'I will push an output. [0]' await delay(5) task.output = 'I will push an output. [1]' await delay(5) task.output = 'I will push an output. [2]' await delay(5) }, options: { persistentOutput: true } } ], { concurrent: false, rendererOptions: { lazy: true } } ).run() expect(mockStdout.mock.calls).toMatchSnapshot('oYHBlOYGg8juKRkaqigY617eyLbGMuDd-out') expect(mockStderr.mock.calls).toMatchSnapshot('oYHBlOYGg8juKRkaqigY617eyLbGMuDd-err') expect(mockExit.mock.calls).toMatchSnapshot('oYHBlOYGg8juKRkaqigY617eyLbGMuDd-exit') }) // 767BkeBTfR1lrS2ANYYH7CLWPATxqyat it('should output to bottom bar', async () => { await new Listr( [ { title: 'This task will execute.', task: async (ctx, task): Promise<void> => { task.output = 'I will push an output. [0]' await delay(5) task.output = 'I will push an output. [1]' await delay(5) task.output = 'I will push an output. [2]' await delay(5) }, options: { bottomBar: Infinity } } ], { concurrent: false, rendererOptions: { lazy: true } } ).run() expect(mockStdout.mock.calls).toMatchSnapshot('767BkeBTfR1lrS2ANYYH7CLWPATxqyat-out') expect(mockStderr.mock.calls).toMatchSnapshot('767BkeBTfR1lrS2ANYYH7CLWPATxqyat-err') expect(mockExit.mock.calls).toMatchSnapshot('767BkeBTfR1lrS2ANYYH7CLWPATxqyat-exit') }) // JMCRBo4OtLm7JB3XbcYoRcCdQRiKfPdP it('should output to bottom bar from task with no title', async () => { await new Listr( [ { task: async (ctx, task): Promise<void> => { task.output = 'I will push an output. [0]' await delay(5) task.output = 'I will push an output. [1]' await delay(5) task.output = 'I will push an output. [2]' await delay(5) }, options: { bottomBar: Infinity } } ], { concurrent: false, rendererOptions: { lazy: true } } ).run() expect(mockStdout.mock.calls).toMatchSnapshot('JMCRBo4OtLm7JB3XbcYoRcCdQRiKfPdP-out') expect(mockStderr.mock.calls).toMatchSnapshot('JMCRBo4OtLm7JB3XbcYoRcCdQRiKfPdP-err') expect(mockExit.mock.calls).toMatchSnapshot('JMCRBo4OtLm7JB3XbcYoRcCdQRiKfPdP-exit') }) // iI52S3WPytorU9EZKPar2AiBrLAZTVut it('should output to bottom bar from task with no title persistently', async () => { await new Listr( [ { task: async (ctx, task): Promise<void> => { task.output = 'I will push an output. [0]' await delay(5) task.output = 'I will push an output. [1]' await delay(5) task.output = 'I will push an output. [2]' await delay(5) }, options: { bottomBar: Infinity, persistentOutput: true } } ], { concurrent: false, rendererOptions: { lazy: true } } ).run() expect(mockStdout.mock.calls).toMatchSnapshot('iI52S3WPytorU9EZKPar2AiBrLAZTVut-out') expect(mockStderr.mock.calls).toMatchSnapshot('iI52S3WPytorU9EZKPar2AiBrLAZTVut-err') expect(mockExit.mock.calls).toMatchSnapshot('iI52S3WPytorU9EZKPar2AiBrLAZTVut-exit') }) // HhZEM7noGNW4xpgxv4ZtXsPMroPWqrEA it('should output to bottom bar persistently', async () => { await new Listr( [ { title: 'This task will execute.', task: async (ctx, task): Promise<void> => { task.output = 'I will push an output. [0]' await delay(5) task.output = 'I will push an output. [1]' await delay(5) task.output = 'I will push an output. [2]' await delay(5) }, options: { bottomBar: Infinity, persistentOutput: true } } ], { concurrent: false, rendererOptions: { lazy: true } } ).run() expect(mockStdout.mock.calls).toMatchSnapshot('HhZEM7noGNW4xpgxv4ZtXsPMroPWqrEA-out') expect(mockStderr.mock.calls).toMatchSnapshot('HhZEM7noGNW4xpgxv4ZtXsPMroPWqrEA-err') expect(mockExit.mock.calls).toMatchSnapshot('HhZEM7noGNW4xpgxv4ZtXsPMroPWqrEA-exit') }) // d4wXg4yGYak09qivTqgKFZaQJ3PvDZm5 it('should limit output to bottom bar persistently', async () => { await new Listr( [ { title: 'This task will execute.', task: async (ctx, task): Promise<void> => { task.output = 'I will push an output. [0]' await delay(5) task.output = 'I will push an output. [1]' await delay(5) task.output = 'I will push an output. [2]' await delay(5) }, options: { bottomBar: 2 } } ], { concurrent: false, rendererOptions: { lazy: true } } ).run() expect(mockStdout.mock.calls).toMatchSnapshot('d4wXg4yGYak09qivTqgKFZaQJ3PvDZm5-out') expect(mockStderr.mock.calls).toMatchSnapshot('d4wXg4yGYak09qivTqgKFZaQJ3PvDZm5-err') expect(mockExit.mock.calls).toMatchSnapshot('d4wXg4yGYak09qivTqgKFZaQJ3PvDZm5-exit') }) // NpGb4ry8b6hlK7VkJ1YcXcVibx0k5Sus it('should output to bottom bar 2 times at most and delete the prior tasks output when finished', async () => { await new Listr( [ { title: 'This task will execute.', task: async (ctx, task): Promise<void> => { task.output = 'I will push an output. [0]' await delay(5) task.output = 'I will push an output. [1]' await delay(5) task.output = 'I will push an output. [2]' await delay(5) }, options: { bottomBar: true, persistentOutput: false } }, { title: 'This task will execute.', task: async (ctx, task): Promise<void> => { task.output = 'I will push an output. [0]' await delay(5) task.output = 'I will push an output. [1]' await delay(5) task.output = 'I will push an output. [2]' await delay(5) }, options: { bottomBar: true, persistentOutput: true } } ], { concurrent: false, rendererOptions: { lazy: true } } ).run() expect(mockStdout.mock.calls).toMatchSnapshot('NpGb4ry8b6hlK7VkJ1YcXcVibx0k5Sus-out') expect(mockStderr.mock.calls).toMatchSnapshot('NpGb4ry8b6hlK7VkJ1YcXcVibx0k5Sus-err') expect(mockExit.mock.calls).toMatchSnapshot('NpGb4ry8b6hlK7VkJ1YcXcVibx0k5Sus-exit') }) // SM8IHVdptzrFs7Qk2bseYbdCwtTf03QT it('should output to from an observable', async () => { await new Listr( [ { title: 'Observable test.', task: (): Observable<string> => new Observable((observer) => { observer.next('test') delay(5) .then(() => { observer.next('changed') return delay(5) }) .then(() => { observer.complete() }) }) } ], { concurrent: false, rendererOptions: { lazy: true } } ).run() expect(mockStdout.mock.calls).toMatchSnapshot('SM8IHVdptzrFs7Qk2bseYbdCwtTf03QT-out') expect(mockStderr.mock.calls).toMatchSnapshot('SM8IHVdptzrFs7Qk2bseYbdCwtTf03QT-err') expect(mockExit.mock.calls).toMatchSnapshot('SM8IHVdptzrFs7Qk2bseYbdCwtTf03QT-exit') }) // j7BqsosH97ffW1SQSdkADSm2HnSZQ9nn it('should indent long multiline output with persistent output', async () => { await new Listr( [ { title: 'This task will execute.', task: async (ctx, task): Promise<void> => { const start = 'This is a' const mid = 'long ' const end = 'multi line output.' task.output = start + mid.repeat(40) + '\n' + mid.repeat(40) + '\n' + mid.repeat(40) + '\n' + mid.repeat(40) + '\n' + mid.repeat(40) + '\n' + end await delay(5) }, options: { persistentOutput: true } } ], { concurrent: false, rendererOptions: { lazy: true } } ).run() expect(mockStdout.mock.calls).toMatchSnapshot('j7BqsosH97ffW1SQSdkADSm2HnSZQ9nn-out') expect(mockStderr.mock.calls).toMatchSnapshot('j7BqsosH97ffW1SQSdkADSm2HnSZQ9nn-err') expect(mockExit.mock.calls).toMatchSnapshot('j7BqsosH97ffW1SQSdkADSm2HnSZQ9nn-exit') }) // MjcoXTjPbNRDsgOIbGzvjt7MEaZcmasv it.each([ true, false ])('should have persistent output on task fail with bottom bar %s', async (input) => { await new Listr( [ { title: 'This task will execute.', task: async (ctx, task): Promise<void> => { task.output = 'I will push an output. [0]' await delay(5) task.output = 'I will push an output. [1]' await delay(5) task.output = 'I will push an output. [2]' await delay(5) throw new Error('This task has failed') }, options: { bottomBar: input, persistentOutput: true } } ], { concurrent: false, rendererOptions: { lazy: true }, exitOnError: false } ).run() expect(mockStdout.mock.calls).toMatchSnapshot('MjcoXTjPbNRDsgOIbGzvjt7MEaZcmasv-out') expect(mockStderr.mock.calls).toMatchSnapshot('MjcoXTjPbNRDsgOIbGzvjt7MEaZcmasv-err') expect(mockExit.mock.calls).toMatchSnapshot('MjcoXTjPbNRDsgOIbGzvjt7MEaZcmasv-exit') }) })
the_stack
import { bytes } from '@chainsafe/libp2p-noise/dist/src/@types/basic'; import { Noise } from '@chainsafe/libp2p-noise/dist/src/noise'; import debug from 'debug'; import Libp2p, { Connection, Libp2pModules, Libp2pOptions } from 'libp2p'; import Bootstrap from 'libp2p-bootstrap'; import { MuxedStream } from 'libp2p-interfaces/dist/src/stream-muxer/types'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: No types available import Mplex from 'libp2p-mplex'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: No types available import Websockets from 'libp2p-websockets'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: No types available import filters from 'libp2p-websockets/src/filters'; import { Peer } from 'libp2p/dist/src/peer-store'; import Ping from 'libp2p/src/ping'; import { Multiaddr, multiaddr } from 'multiaddr'; import PeerId from 'peer-id'; import { getBootstrapNodes } from './discovery'; import { getPeersForProtocol } from './select_peer'; import { LightPushCodec, WakuLightPush } from './waku_light_push'; import { WakuMessage } from './waku_message'; import { RelayCodecs, WakuRelay } from './waku_relay'; import { RelayPingContentTopic } from './waku_relay/constants'; import { StoreCodec, WakuStore } from './waku_store'; const websocketsTransportKey = Websockets.prototype[Symbol.toStringTag]; export const DefaultPingKeepAliveValueSecs = 0; export const DefaultRelayKeepAliveValueSecs = 5 * 60; /** * DefaultPubSubTopic is the default gossipsub topic to use for Waku. */ export const DefaultPubSubTopic = '/waku/2/default-waku/proto'; const dbg = debug('waku:waku'); export interface CreateOptions { /** * The PubSub Topic to use. Defaults to {@link DefaultPubSubTopic}. * * One and only one pubsub topic is used by Waku. This is used by: * - WakuRelay to receive, route and send messages, * - WakuLightPush to send messages, * - WakuStore to retrieve messages. * * The usage of the default pubsub topic is recommended. * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details. * * @default {@link DefaultPubSubTopic} */ pubSubTopic?: string; /** * Set keep alive frequency in seconds: Waku will send a `/ipfs/ping/1.0.0` * request to each peer after the set number of seconds. Set to 0 to disable. * * @default {@link DefaultPingKeepAliveValueSecs} */ pingKeepAlive?: number; /** * Set keep alive frequency in seconds: Waku will send a ping message over * relay to each peer after the set number of seconds. Set to 0 to disable. * * @default {@link DefaultRelayKeepAliveValueSecs} */ relayKeepAlive?: number; /** * You can pass options to the `Libp2p` instance used by {@link Waku} using the {@link CreateOptions.libp2p} property. * This property is the same type than the one passed to [`Libp2p.create`](https://github.com/libp2p/js-libp2p/blob/master/doc/API.md#create) * apart that we made the `modules` property optional and partial, * allowing its omission and letting Waku set good defaults. * Notes that some values are overridden by {@link Waku} to ensure it implements the Waku protocol. */ libp2p?: Omit<Libp2pOptions & import('libp2p').CreateOptions, 'modules'> & { modules?: Partial<Libp2pModules>; }; /** * Byte array used as key for the noise protocol used for connection encryption * by [`Libp2p.create`](https://github.com/libp2p/js-libp2p/blob/master/doc/API.md#create) * This is only used for test purposes to not run out of entropy during CI runs. */ staticNoiseKey?: bytes; /** * Use libp2p-bootstrap to discover and connect to new nodes. * * You can pass: * - `true` to use {@link getBootstrapNodes}, * - an array of multiaddresses, * - a function that returns an array of multiaddresses (or Promise of). * * Note: It overrides any other peerDiscovery modules that may have been set via * {@link CreateOptions.libp2p}. */ bootstrap?: boolean | string[] | (() => string[] | Promise<string[]>); decryptionKeys?: Array<Uint8Array | string>; } export class Waku { public libp2p: Libp2p; public relay: WakuRelay; public store: WakuStore; public lightPush: WakuLightPush; private pingKeepAliveTimers: { [peer: string]: ReturnType<typeof setInterval>; }; private relayKeepAliveTimers: { [peer: string]: ReturnType<typeof setInterval>; }; private constructor( options: CreateOptions, libp2p: Libp2p, store: WakuStore, lightPush: WakuLightPush ) { this.libp2p = libp2p; this.relay = libp2p.pubsub as unknown as WakuRelay; this.store = store; this.lightPush = lightPush; this.pingKeepAliveTimers = {}; this.relayKeepAliveTimers = {}; const pingKeepAlive = options.pingKeepAlive || DefaultPingKeepAliveValueSecs; const relayKeepAlive = options.relayKeepAlive || DefaultRelayKeepAliveValueSecs; libp2p.connectionManager.on('peer:connect', (connection: Connection) => { this.startKeepAlive(connection.remotePeer, pingKeepAlive, relayKeepAlive); }); libp2p.connectionManager.on('peer:disconnect', (connection: Connection) => { this.stopKeepAlive(connection.remotePeer); }); options?.decryptionKeys?.forEach(this.addDecryptionKey); } /** * Create new waku node * * @param options Takes the same options than `Libp2p`. */ static async create(options?: CreateOptions): Promise<Waku> { // Get an object in case options or libp2p are undefined const libp2pOpts = Object.assign({}, options?.libp2p); // Default for Websocket filter is `all`: // Returns all TCP and DNS based addresses, both with ws or wss. libp2pOpts.config = Object.assign( { transport: { [websocketsTransportKey]: { filter: filters.all, }, }, }, options?.libp2p?.config ); // Pass pubsub topic to relay if (options?.pubSubTopic) { libp2pOpts.config.pubsub = Object.assign( { pubSubTopic: options.pubSubTopic }, libp2pOpts.config.pubsub ); } libp2pOpts.modules = Object.assign({}, options?.libp2p?.modules); // Default transport for libp2p is Websockets libp2pOpts.modules = Object.assign( { transport: [Websockets], }, options?.libp2p?.modules ); // streamMuxer, connection encryption and pubsub are overridden // as those are the only ones currently supported by Waku nodes. libp2pOpts.modules = Object.assign(libp2pOpts.modules, { streamMuxer: [Mplex], connEncryption: [new Noise(options?.staticNoiseKey)], pubsub: WakuRelay, }); if (options?.bootstrap) { let bootstrap: undefined | (() => string[] | Promise<string[]>); if (options.bootstrap === true) { bootstrap = getBootstrapNodes; } else if (Array.isArray(options.bootstrap)) { bootstrap = (): string[] => { return options.bootstrap as string[]; }; } else if (typeof options.bootstrap === 'function') { bootstrap = options.bootstrap; } if (bootstrap !== undefined) { try { const list = await bootstrap(); // Note: this overrides any other peer discover libp2pOpts.modules = Object.assign(libp2pOpts.modules, { peerDiscovery: [Bootstrap], }); libp2pOpts.config.peerDiscovery = { [Bootstrap.tag]: { list, enabled: true, }, }; } catch (e) { dbg('Failed to retrieve bootstrap nodes', e); } } } // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: modules property is correctly set thanks to voodoo const libp2p = await Libp2p.create(libp2pOpts); const wakuStore = new WakuStore(libp2p, { pubSubTopic: options?.pubSubTopic, }); const wakuLightPush = new WakuLightPush(libp2p); await libp2p.start(); return new Waku(options ? options : {}, libp2p, wakuStore, wakuLightPush); } /** * Dials to the provided peer. * * @param peer The peer to dial */ async dial(peer: PeerId | Multiaddr | string): Promise<{ stream: MuxedStream; protocol: string; }> { return this.libp2p.dialProtocol(peer, [StoreCodec].concat(RelayCodecs)); } /** * Add peer to address book, it will be auto-dialed in the background. */ addPeerToAddressBook( peerId: PeerId | string, multiaddrs: Multiaddr[] | string[] ): void { let peer; if (typeof peerId === 'string') { peer = PeerId.createFromB58String(peerId); } else { peer = peerId; } const addresses = multiaddrs.map((addr: Multiaddr | string) => { if (typeof addr === 'string') { return multiaddr(addr); } else { return addr; } }); this.libp2p.peerStore.addressBook.set(peer, addresses); } async stop(): Promise<void> { return this.libp2p.stop(); } /** * Register a decryption key to attempt decryption of messages received via * [[WakuRelay]] and [[WakuStore]]. This can either be a private key for * asymmetric encryption or a symmetric key. * * Strings must be in hex format. */ addDecryptionKey(key: Uint8Array | string): void { this.relay.addDecryptionKey(key); this.store.addDecryptionKey(key); } /** * Delete a decryption key that was used to attempt decryption of messages * received via [[WakuRelay]] or [[WakuStore]]. * * Strings must be in hex format. */ deleteDecryptionKey(key: Uint8Array | string): void { this.relay.deleteDecryptionKey(key); this.store.deleteDecryptionKey(key); } /** * Return the local multiaddr with peer id on which libp2p is listening. * @throws if libp2p is not listening on localhost */ getLocalMultiaddrWithID(): string { const localMultiaddr = this.libp2p.multiaddrs.find((addr) => addr.toString().match(/127\.0\.0\.1/) ); if (!localMultiaddr || localMultiaddr.toString() === '') { throw 'Not listening on localhost'; } return localMultiaddr + '/p2p/' + this.libp2p.peerId.toB58String(); } /** * Wait to be connected to a peer. Useful when using the [[CreateOptions.bootstrap]] * with [[Waku.create]]. The Promise resolves only once we are connected to a * Store peer, Relay peer and Light Push peer. */ async waitForConnectedPeer(): Promise<void> { const desiredProtocols = [[StoreCodec], [LightPushCodec], RelayCodecs]; await Promise.all( desiredProtocols.map((desiredProtocolVersions) => { const peers = new Array<Peer>(); desiredProtocolVersions.forEach((proto) => { getPeersForProtocol(this.libp2p, proto).forEach((peer) => peers.push(peer) ); }); if (peers.length > 0) { return Promise.resolve(); } else { // No peer available for this protocol, waiting to connect to one. return new Promise<void>((resolve) => { this.libp2p.peerStore.on( 'change:protocols', ({ protocols: connectedPeerProtocols }) => { desiredProtocolVersions.forEach((desiredProto) => { if (connectedPeerProtocols.includes(desiredProto)) { dbg('Resolving for', desiredProto, connectedPeerProtocols); resolve(); } }); } ); }); } }) ); } private startKeepAlive( peerId: PeerId, pingPeriodSecs: number, relayPeriodSecs: number ): void { // Just in case a timer already exist for this peer this.stopKeepAlive(peerId); const peerIdStr = peerId.toB58String(); if (pingPeriodSecs !== 0) { this.pingKeepAliveTimers[peerIdStr] = setInterval(() => { Ping(this.libp2p, peerId); }, pingPeriodSecs * 1000); } if (relayPeriodSecs !== 0) { this.relayKeepAliveTimers[peerIdStr] = setInterval(() => { WakuMessage.fromBytes(new Uint8Array(), RelayPingContentTopic).then( (wakuMsg) => this.relay.send(wakuMsg) ); }, relayPeriodSecs * 1000); } } private stopKeepAlive(peerId: PeerId): void { const peerIdStr = peerId.toB58String(); if (this.pingKeepAliveTimers[peerIdStr]) { clearInterval(this.pingKeepAliveTimers[peerIdStr]); delete this.pingKeepAliveTimers[peerIdStr]; } if (this.relayKeepAliveTimers[peerIdStr]) { clearInterval(this.relayKeepAliveTimers[peerIdStr]); delete this.relayKeepAliveTimers[peerIdStr]; } } }
the_stack
import type { DataItem } from "../../core/render/Component"; import type { SlicedChart } from "./SlicedChart"; import { PercentSeries, IPercentSeriesSettings, IPercentSeriesDataItem, IPercentSeriesPrivate } from "../percent/PercentSeries"; import { Template } from "../../core/util/Template"; import { ListTemplate } from "../../core/util/List"; import { FunnelSlice } from "./FunnelSlice"; import { Tick } from "../../core/render/Tick"; import { Label } from "../../core/render/Label"; import { percent, p50, p100 } from "../../core/util/Percent"; import * as $array from "../../core/util/Array"; import * as $type from "../../core/util/Type"; import * as $utils from "../../core/util/Utils"; export interface IFunnelSeriesDataItem extends IPercentSeriesDataItem { slice: FunnelSlice; link: FunnelSlice; index: number; } export interface IFunnelSeriesSettings extends IPercentSeriesSettings { /** * Width of the bottom edge of the slice relative to the top edge of the next * slice. * * `1` - means the full width of the slice, resulting in a rectangle. * `0` - means using width of the next slice, resulting in a trapezoid. * * @see {@link https://www.amcharts.com/docs/v5/charts/percent-charts/sliced-chart/funnel-series/#Slice_bottom_width} for more info * @default 1 */ bottomRatio?: number; /** * Orientation of the series. * * @see {@link https://www.amcharts.com/docs/v5/charts/percent-charts/sliced-chart/#Series_orientation} for more info * @default "vertical" */ orientation: "horizontal" | "vertical"; /** * If set to `true`, series will not create slices for data items with zero * value. */ ignoreZeroValues?: boolean; /** * Should labels be aligned into columns/rows? * * @default false */ alignLabels?: boolean; /** * Relative location within area available to series where it should start. * * `0` - beginning, `1` - end, or any intermediate value. * * @see {@link https://www.amcharts.com/docs/v5/charts/percent-charts/sliced-chart/funnel-series/#Start_end_locations} for more info * @default 0 */ startLocation?: number; /** * Relative location within area available to series where it should start. * * `0` - beginning, `1` - end, or any intermediate value. * * @see {@link https://www.amcharts.com/docs/v5/charts/percent-charts/sliced-chart/funnel-series/#Start_end_locations} for more info * @default 0 */ endLocation?: number; } export interface IFunnelSeriesPrivate extends IPercentSeriesPrivate { } /** * Creates a funnel series for use in a [[SlicedChart]]. * * @see {@link https://www.amcharts.com/docs/v5/charts/percent-charts/sliced-chart/funnel-series/} for more info * @important */ export class FunnelSeries extends PercentSeries { /** * A chart series is attached to. */ declare public chart: SlicedChart | undefined; protected _tag = "funnel"; declare public _sliceType: FunnelSlice; declare public _labelType: Label; declare public _tickType: Tick; protected _makeSlices(): ListTemplate<this["_sliceType"]> { return new ListTemplate( Template.new({}), () => FunnelSlice._new(this._root, { themeTags: $utils.mergeTags(this.slices.template.get("themeTags", []), [this._tag, "series", "slice", this.get("orientation")]) }, [this.slices.template]) ); } protected _makeLabels(): ListTemplate<this["_labelType"]> { return new ListTemplate( Template.new({}), () => Label._new(this._root, { themeTags: $utils.mergeTags(this.labels.template.get("themeTags", []), [this._tag, "series", "label", this.get("orientation")]) }, [this.labels.template]) ); } protected _makeTicks(): ListTemplate<this["_tickType"]> { return new ListTemplate( Template.new({}), () => Tick._new(this._root, { themeTags: $utils.mergeTags(this.ticks.template.get("themeTags", []), [this._tag, "series", "tick", this.get("orientation")]) }, [this.ticks.template]) ); } /** * A [[ListTemplate]] of all slice links in series. * * `links.template` can also be used to configure slice links. * * @see {@link https://www.amcharts.com/docs/v5/charts/percent-charts/sliced-chart/funnel-series/#Slice_links} for more info */ public readonly links: ListTemplate<this["_sliceType"]> = this._makeLinks(); protected _makeLinks(): ListTemplate<this["_sliceType"]> { return new ListTemplate( Template.new({}), () => FunnelSlice._new(this._root, { themeTags: $utils.mergeTags(this.links.template.get("themeTags", []), [this._tag, "series", "link", this.get("orientation")]) }, [this.links.template]), ); } /** * @ignore */ public makeLink(dataItem: DataItem<this["_dataItemSettings"]>): this["_sliceType"] { const link = this.slicesContainer.children.push(this.links.make()); link._setDataItem(dataItem); dataItem.set("link", link); this.links.push(link); return link; } public static className: string = "FunnelSeries"; public static classNames: Array<string> = PercentSeries.classNames.concat([FunnelSeries.className]); declare public _settings: IFunnelSeriesSettings; declare public _privateSettings: IFunnelSeriesPrivate; declare public _dataItemSettings: IFunnelSeriesDataItem; protected _total: number = 0; protected _count: number = 0; protected _nextCoord: number = 0; protected _opposite: boolean = false; protected _afterNew() { super._afterNew(); const slicesContainer = this.slicesContainer; slicesContainer.setAll({ isMeasured: true, position: "relative", width: percent(100), height: percent(100) }); slicesContainer.onPrivate("width", () => { this.markDirtySize(); }) slicesContainer.onPrivate("height", () => { this.markDirtySize(); }) if (this.get("orientation") == "vertical") { this.set("layout", this._root.horizontalLayout); } else { this.set("layout", this._root.verticalLayout); } } protected processDataItem(dataItem: DataItem<this["_dataItemSettings"]>) { super.processDataItem(dataItem); const slice = this.makeSlice(dataItem); slice._setDataItem(dataItem); dataItem.set("slice", slice); this.makeLink(dataItem); const label = this.makeLabel(dataItem); label.on("x", () => { this._updateTick(dataItem); }) label.on("y", () => { this._updateTick(dataItem); }) this.makeTick(dataItem); slice.events.on("positionchanged", () => { label.markDirty(); }) slice.events.on("boundschanged", () => { const dataItem = slice.dataItem; if (dataItem) { this._updateTick(dataItem as any); } }) } public _updateChildren() { this._opposite = false; if (this.children.indexOf(this.labelsContainer) == 0) { this._opposite = true; } let total = 0; let count = 0; $array.each(this.dataItems, (dataItem) => { const value = dataItem.get("value"); if ($type.isNumber(value)) { count++; if (value > 0) { total += Math.abs(dataItem.get("valueWorking", value) / value); } else { if (this.get("ignoreZeroValues", false)) { count--; } else { if (dataItem.isHidden()) { count--; } else { total += 1; } } } } }) this._total = 1 / count * total; this._count = count; if (this.isDirty("alignLabels")) { this._fixLayout(); } if (this._total > 0 && (this._valuesDirty || this._sizeDirty)) { const slicesContainer = this.slicesContainer; let h: number; if (this.get("orientation") == "vertical") { h = slicesContainer.innerHeight(); } else { h = slicesContainer.innerWidth(); } this._nextCoord = this.get("startLocation", 0) * h; this.markDirtyBounds(); let i = 0; $array.each(this._dataItems, (dataItem) => { this.updateLegendValue(dataItem); dataItem.set("index", i); i++; const slice = dataItem.get("slice"); const tick = dataItem.get("tick"); const label = dataItem.get("label"); const link = dataItem.get("link"); const color = dataItem.get("fill"); slice._setDefault("fill", color); slice._setDefault("stroke", color); link._setDefault("fill", color); link._setDefault("stroke", color); const value = dataItem.get("value"); if ($type.isNumber(value)) { if (value == 0 && this.get("ignoreZeroValues")) { slice.setPrivate("visible", false); tick.setPrivate("visible", false); label.setPrivate("visible", false); } else { slice.setPrivate("visible", true); tick.setPrivate("visible", true); label.setPrivate("visible", true); this.decorateSlice(dataItem); if (this.isLast(dataItem)) { link.setPrivate("visible", false); } else if (!dataItem.isHidden()) { link.setPrivate("visible", true); } } } }) } super._updateChildren(); } protected _fixLayout() { const orientation = this.get("orientation"); const labelsContainer = this.labelsContainer; const labelsTemplate = this.labels.template; if (this.get("alignLabels")) { labelsContainer.set("position", "relative"); labelsContainer.setAll({ isMeasured: true }); if (orientation == "vertical") { this.set("layout", this._root.horizontalLayout); labelsTemplate.setAll({ centerX: p100, x: p100 }); } else { this.set("layout", this._root.verticalLayout); labelsTemplate.setAll({ centerX: 0, x: 0 }); } } else { labelsContainer.setAll({ isMeasured: false, position: "absolute" }); if (orientation == "vertical") { labelsContainer.setAll({ x: p50 }); labelsTemplate.setAll({ centerX: p50, x: 0 }); } else { labelsContainer.setAll({ y: p50 }); labelsTemplate.setAll({ centerX: p50, y: 0 }); } } this.markDirtySize(); } protected getNextValue(dataItem: DataItem<this["_dataItemSettings"]>): number { let index = dataItem.get("index"); let nextValue = dataItem.get("valueWorking", 0); if (index < this.dataItems.length - 1) { let nextItem = this.dataItems[index + 1]; nextValue = nextItem.get("valueWorking", 0); if (nextItem.isHidden() || (nextItem.get("value") == 0 && this.get("ignoreZeroValues"))) { return this.getNextValue(nextItem); } } return nextValue; } protected isLast(dataItem: DataItem<this["_dataItemSettings"]>): boolean { let index = dataItem.get("index"); if (index == this.dataItems.length - 1) { return true; } else { for (let i = index + 1; i < this.dataItems.length; i++) { if (!this.dataItems[i].isHidden()) { return false; } } } return true; } protected decorateSlice(dataItem: DataItem<this["_dataItemSettings"]>) { const orientation = this.get("orientation"); const slice = dataItem.get("slice"); const label = dataItem.get("label"); const link = dataItem.get("link"); const slicesContainer = this.slicesContainer; let maxWidth = slicesContainer.innerWidth(); let maxHeight = slicesContainer.innerHeight(); let maxSize = maxWidth; if (orientation == "horizontal") { maxSize = maxHeight; } const nextValue = this.getNextValue(dataItem); const value = dataItem.get("value", 0); const workingValue = Math.abs(dataItem.get("valueWorking", value)); const bottomRatio = this.get("bottomRatio", 0); const valueHigh = this.getPrivate("valueHigh", 0); let d = 1; if (value != 0) { d = workingValue / Math.abs(value); } else { if (dataItem.isHidden()) { d = 0.000001; } } if (this._nextCoord == Infinity) { this._nextCoord = 0; } let topWidth = workingValue / valueHigh * maxSize; let bottomWidth = (workingValue - (workingValue - nextValue) * bottomRatio) / valueHigh * maxSize; slice.setAll({ topWidth, bottomWidth, orientation }); link.setAll({ topWidth: bottomWidth, bottomWidth: (workingValue - (workingValue - nextValue)) / valueHigh * maxSize, orientation }); const startLocation = this.get("startLocation", 0); const endLocation = this.get("endLocation", 1); if (orientation == "vertical") { let linkHeight = link.height() * d; maxHeight = maxHeight * (endLocation - startLocation) + linkHeight; slice.set("y", this._nextCoord); let height = Math.min(100000, Math.max(0, maxHeight / this._count * d / this._total - linkHeight)); slice.setAll({ height, x: maxWidth / 2 }); let labelY = this._nextCoord + height / 2; label.set("y", labelY); this._nextCoord += height + linkHeight; link.setAll({ y: this._nextCoord - linkHeight, x: maxWidth / 2 }); } else { let linkHeight = link.width() * d; maxWidth = maxWidth * (endLocation - startLocation) + linkHeight; slice.set("x", this._nextCoord); let width = Math.min(100000, Math.max(0, maxWidth / this._count * d / this._total - linkHeight)); slice.setAll({ width, y: maxHeight / 2 }); const labelX = this._nextCoord + width / 2; label.set("x", labelX); this._nextCoord += width + linkHeight; link.setAll({ x: this._nextCoord - linkHeight, y: maxHeight / 2 }); } } /** * Hides series's data item. * * @param dataItem Data item * @param duration Animation duration in milliseconds * @return Promise */ public async hideDataItem(dataItem: DataItem<this["_dataItemSettings"]>, duration?: number): Promise<void> { dataItem.get("link").hide(duration); return super.hideDataItem(dataItem, duration) } /** * Shows series's data item. * * @param dataItem Data item * @param duration Animation duration in milliseconds * @return Promise */ public async showDataItem(dataItem: DataItem<this["_dataItemSettings"]>, duration?: number): Promise<void> { dataItem.get("link").show(duration); return super.showDataItem(dataItem, duration) } protected _updateTick(dataItem: DataItem<this["_dataItemSettings"]>) { if (this.get("alignLabels")) { const tick = dataItem.get("tick"); const label = dataItem.get("label"); const slice = dataItem.get("slice"); if (tick && slice && label) { const labelsContainer = this.labelsContainer; const slicesContainer = this.slicesContainer; let tickLocation = tick.get("location", 0.5); const lcw = labelsContainer.width(); const lch = labelsContainer.height(); const pl = labelsContainer.get("paddingLeft", 0); const pr = labelsContainer.get("paddingRight", 0); const pt = labelsContainer.get("paddingTop", 0); const pb = labelsContainer.get("paddingBottom", 0); let p0 = { x: 0, y: 0 }; let p1 = { x: 0, y: 0 }; let p2 = { x: 0, y: 0 }; if (this._opposite) { tickLocation = 1 - tickLocation; } if (this.get("orientation") == "vertical") { p0 = slice.getPoint(tickLocation, 0.5); p0.x += slice.x() + slicesContainer.x(); p0.y += slice.y() + slicesContainer.y(); if (this._opposite) { p1.x = lcw; p1.y = label.y(); p2.x = lcw - pl; p2.y = p1.y; } else { p1.x = slicesContainer.x() + slicesContainer.width(); p1.y = label.y(); p2.x = p1.x + lcw - label.width() - pr; p2.y = p1.y; } } else { p0 = slice.getPoint(0.5, tickLocation); p0.x += slice.x() + slicesContainer.x(); p0.y += slice.y() + slicesContainer.y(); if (this._opposite) { p1.y = lch; p1.x = label.x(); p2.y = lch - pt; p2.x = p1.x; } else { p1.y = slicesContainer.y() + slicesContainer.height(); p1.x = label.x(); p2.y = p1.y + lch - label.height() - pb; p2.x = p1.x; } } tick.set("points", [p0, p1, p2]); } } } /** * @ignore */ public disposeDataItem(dataItem: DataItem<this["_dataItemSettings"]>) { super.disposeDataItem(dataItem); let link = dataItem.get("link"); if (link) { this.links.removeValue(link); link.dispose(); } } }
the_stack
export namespace enums { /** * @name PolicyTopicEntryTypeEnum.PolicyTopicEntryType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PolicyTopicEntryTypeEnum.PolicyTopicEntryType */ export enum PolicyTopicEntryType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PROHIBITED = 2, // PROHIBITED LIMITED = 4, // LIMITED FULLY_LIMITED = 8, // FULLY_LIMITED DESCRIPTIVE = 5, // DESCRIPTIVE BROADENING = 6, // BROADENING AREA_OF_INTEREST_ONLY = 7, // AREA_OF_INTEREST_ONLY } /** * @name PolicyTopicEvidenceDestinationMismatchUrlTypeEnum.PolicyTopicEvidenceDestinationMismatchUrlType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PolicyTopicEvidenceDestinationMismatchUrlTypeEnum.PolicyTopicEvidenceDestinationMismatchUrlType */ export enum PolicyTopicEvidenceDestinationMismatchUrlType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN DISPLAY_URL = 2, // DISPLAY_URL FINAL_URL = 3, // FINAL_URL FINAL_MOBILE_URL = 4, // FINAL_MOBILE_URL TRACKING_URL = 5, // TRACKING_URL MOBILE_TRACKING_URL = 6, // MOBILE_TRACKING_URL } /** * @name PolicyTopicEvidenceDestinationNotWorkingDeviceEnum.PolicyTopicEvidenceDestinationNotWorkingDevice * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PolicyTopicEvidenceDestinationNotWorkingDeviceEnum.PolicyTopicEvidenceDestinationNotWorkingDevice */ export enum PolicyTopicEvidenceDestinationNotWorkingDevice { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN DESKTOP = 2, // DESKTOP ANDROID = 3, // ANDROID IOS = 4, // IOS } /** * @name PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum.PolicyTopicEvidenceDestinationNotWorkingDnsErrorType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PolicyTopicEvidenceDestinationNotWorkingDnsErrorTypeEnum.PolicyTopicEvidenceDestinationNotWorkingDnsErrorType */ export enum PolicyTopicEvidenceDestinationNotWorkingDnsErrorType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN HOSTNAME_NOT_FOUND = 2, // HOSTNAME_NOT_FOUND GOOGLE_CRAWLER_DNS_ISSUE = 3, // GOOGLE_CRAWLER_DNS_ISSUE } /** * @name PolicyApprovalStatusEnum.PolicyApprovalStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PolicyApprovalStatusEnum.PolicyApprovalStatus */ export enum PolicyApprovalStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN DISAPPROVED = 2, // DISAPPROVED APPROVED_LIMITED = 3, // APPROVED_LIMITED APPROVED = 4, // APPROVED AREA_OF_INTEREST_ONLY = 5, // AREA_OF_INTEREST_ONLY } /** * @name PolicyReviewStatusEnum.PolicyReviewStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PolicyReviewStatusEnum.PolicyReviewStatus */ export enum PolicyReviewStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN REVIEW_IN_PROGRESS = 2, // REVIEW_IN_PROGRESS REVIEWED = 3, // REVIEWED UNDER_APPEAL = 4, // UNDER_APPEAL ELIGIBLE_MAY_SERVE = 5, // ELIGIBLE_MAY_SERVE } /** * @name AssetPerformanceLabelEnum.AssetPerformanceLabel * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AssetPerformanceLabelEnum.AssetPerformanceLabel */ export enum AssetPerformanceLabel { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PENDING = 2, // PENDING LEARNING = 3, // LEARNING LOW = 4, // LOW GOOD = 5, // GOOD BEST = 6, // BEST } /** * @name ServedAssetFieldTypeEnum.ServedAssetFieldType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ServedAssetFieldTypeEnum.ServedAssetFieldType */ export enum ServedAssetFieldType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN HEADLINE_1 = 2, // HEADLINE_1 HEADLINE_2 = 3, // HEADLINE_2 HEADLINE_3 = 4, // HEADLINE_3 DESCRIPTION_1 = 5, // DESCRIPTION_1 DESCRIPTION_2 = 6, // DESCRIPTION_2 } /** * @name CallConversionReportingStateEnum.CallConversionReportingState * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CallConversionReportingStateEnum.CallConversionReportingState */ export enum CallConversionReportingState { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN DISABLED = 2, // DISABLED USE_ACCOUNT_LEVEL_CALL_CONVERSION_ACTION = 3, // USE_ACCOUNT_LEVEL_CALL_CONVERSION_ACTION USE_RESOURCE_LEVEL_CALL_CONVERSION_ACTION = 4, // USE_RESOURCE_LEVEL_CALL_CONVERSION_ACTION } /** * @name DisplayAdFormatSettingEnum.DisplayAdFormatSetting * @link https://developers.google.com/google-ads/api/reference/rpc/v9/DisplayAdFormatSettingEnum.DisplayAdFormatSetting */ export enum DisplayAdFormatSetting { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ALL_FORMATS = 2, // ALL_FORMATS NON_NATIVE = 3, // NON_NATIVE NATIVE = 4, // NATIVE } /** * @name DisplayUploadProductTypeEnum.DisplayUploadProductType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/DisplayUploadProductTypeEnum.DisplayUploadProductType */ export enum DisplayUploadProductType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN HTML5_UPLOAD_AD = 2, // HTML5_UPLOAD_AD DYNAMIC_HTML5_EDUCATION_AD = 3, // DYNAMIC_HTML5_EDUCATION_AD DYNAMIC_HTML5_FLIGHT_AD = 4, // DYNAMIC_HTML5_FLIGHT_AD DYNAMIC_HTML5_HOTEL_RENTAL_AD = 5, // DYNAMIC_HTML5_HOTEL_RENTAL_AD DYNAMIC_HTML5_JOB_AD = 6, // DYNAMIC_HTML5_JOB_AD DYNAMIC_HTML5_LOCAL_AD = 7, // DYNAMIC_HTML5_LOCAL_AD DYNAMIC_HTML5_REAL_ESTATE_AD = 8, // DYNAMIC_HTML5_REAL_ESTATE_AD DYNAMIC_HTML5_CUSTOM_AD = 9, // DYNAMIC_HTML5_CUSTOM_AD DYNAMIC_HTML5_TRAVEL_AD = 10, // DYNAMIC_HTML5_TRAVEL_AD DYNAMIC_HTML5_HOTEL_AD = 11, // DYNAMIC_HTML5_HOTEL_AD } /** * @name LegacyAppInstallAdAppStoreEnum.LegacyAppInstallAdAppStore * @link https://developers.google.com/google-ads/api/reference/rpc/v9/LegacyAppInstallAdAppStoreEnum.LegacyAppInstallAdAppStore */ export enum LegacyAppInstallAdAppStore { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN APPLE_APP_STORE = 2, // APPLE_APP_STORE GOOGLE_PLAY = 3, // GOOGLE_PLAY WINDOWS_STORE = 4, // WINDOWS_STORE WINDOWS_PHONE_STORE = 5, // WINDOWS_PHONE_STORE CN_APP_STORE = 6, // CN_APP_STORE } /** * @name MimeTypeEnum.MimeType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/MimeTypeEnum.MimeType */ export enum MimeType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN IMAGE_JPEG = 2, // IMAGE_JPEG IMAGE_GIF = 3, // IMAGE_GIF IMAGE_PNG = 4, // IMAGE_PNG FLASH = 5, // FLASH TEXT_HTML = 6, // TEXT_HTML PDF = 7, // PDF MSWORD = 8, // MSWORD MSEXCEL = 9, // MSEXCEL RTF = 10, // RTF AUDIO_WAV = 11, // AUDIO_WAV AUDIO_MP3 = 12, // AUDIO_MP3 HTML5_AD_ZIP = 13, // HTML5_AD_ZIP } /** * @name VideoThumbnailEnum.VideoThumbnail * @link https://developers.google.com/google-ads/api/reference/rpc/v9/VideoThumbnailEnum.VideoThumbnail */ export enum VideoThumbnail { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN DEFAULT_THUMBNAIL = 2, // DEFAULT_THUMBNAIL THUMBNAIL_1 = 3, // THUMBNAIL_1 THUMBNAIL_2 = 4, // THUMBNAIL_2 THUMBNAIL_3 = 5, // THUMBNAIL_3 } /** * @name AgeRangeTypeEnum.AgeRangeType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AgeRangeTypeEnum.AgeRangeType */ export enum AgeRangeType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN AGE_RANGE_18_24 = 503001, // AGE_RANGE_18_24 AGE_RANGE_25_34 = 503002, // AGE_RANGE_25_34 AGE_RANGE_35_44 = 503003, // AGE_RANGE_35_44 AGE_RANGE_45_54 = 503004, // AGE_RANGE_45_54 AGE_RANGE_55_64 = 503005, // AGE_RANGE_55_64 AGE_RANGE_65_UP = 503006, // AGE_RANGE_65_UP AGE_RANGE_UNDETERMINED = 503999, // AGE_RANGE_UNDETERMINED } /** * @name AppPaymentModelTypeEnum.AppPaymentModelType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AppPaymentModelTypeEnum.AppPaymentModelType */ export enum AppPaymentModelType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PAID = 30, // PAID } /** * @name ContentLabelTypeEnum.ContentLabelType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ContentLabelTypeEnum.ContentLabelType */ export enum ContentLabelType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN SEXUALLY_SUGGESTIVE = 2, // SEXUALLY_SUGGESTIVE BELOW_THE_FOLD = 3, // BELOW_THE_FOLD PARKED_DOMAIN = 4, // PARKED_DOMAIN JUVENILE = 6, // JUVENILE PROFANITY = 7, // PROFANITY TRAGEDY = 8, // TRAGEDY VIDEO = 9, // VIDEO VIDEO_RATING_DV_G = 10, // VIDEO_RATING_DV_G VIDEO_RATING_DV_PG = 11, // VIDEO_RATING_DV_PG VIDEO_RATING_DV_T = 12, // VIDEO_RATING_DV_T VIDEO_RATING_DV_MA = 13, // VIDEO_RATING_DV_MA VIDEO_NOT_YET_RATED = 14, // VIDEO_NOT_YET_RATED EMBEDDED_VIDEO = 15, // EMBEDDED_VIDEO LIVE_STREAMING_VIDEO = 16, // LIVE_STREAMING_VIDEO SOCIAL_ISSUES = 17, // SOCIAL_ISSUES } /** * @name DayOfWeekEnum.DayOfWeek * @link https://developers.google.com/google-ads/api/reference/rpc/v9/DayOfWeekEnum.DayOfWeek */ export enum DayOfWeek { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN MONDAY = 2, // MONDAY TUESDAY = 3, // TUESDAY WEDNESDAY = 4, // WEDNESDAY THURSDAY = 5, // THURSDAY FRIDAY = 6, // FRIDAY SATURDAY = 7, // SATURDAY SUNDAY = 8, // SUNDAY } /** * @name DeviceEnum.Device * @link https://developers.google.com/google-ads/api/reference/rpc/v9/DeviceEnum.Device */ export enum Device { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN MOBILE = 2, // MOBILE TABLET = 3, // TABLET DESKTOP = 4, // DESKTOP CONNECTED_TV = 6, // CONNECTED_TV OTHER = 5, // OTHER } /** * @name GenderTypeEnum.GenderType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/GenderTypeEnum.GenderType */ export enum GenderType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN MALE = 10, // MALE FEMALE = 11, // FEMALE UNDETERMINED = 20, // UNDETERMINED } /** * @name HotelDateSelectionTypeEnum.HotelDateSelectionType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/HotelDateSelectionTypeEnum.HotelDateSelectionType */ export enum HotelDateSelectionType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN DEFAULT_SELECTION = 50, // DEFAULT_SELECTION USER_SELECTED = 51, // USER_SELECTED } /** * @name IncomeRangeTypeEnum.IncomeRangeType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/IncomeRangeTypeEnum.IncomeRangeType */ export enum IncomeRangeType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN INCOME_RANGE_0_50 = 510001, // INCOME_RANGE_0_50 INCOME_RANGE_50_60 = 510002, // INCOME_RANGE_50_60 INCOME_RANGE_60_70 = 510003, // INCOME_RANGE_60_70 INCOME_RANGE_70_80 = 510004, // INCOME_RANGE_70_80 INCOME_RANGE_80_90 = 510005, // INCOME_RANGE_80_90 INCOME_RANGE_90_UP = 510006, // INCOME_RANGE_90_UP INCOME_RANGE_UNDETERMINED = 510000, // INCOME_RANGE_UNDETERMINED } /** * @name InteractionTypeEnum.InteractionType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/InteractionTypeEnum.InteractionType */ export enum InteractionType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CALLS = 8000, // CALLS } /** * @name KeywordMatchTypeEnum.KeywordMatchType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/KeywordMatchTypeEnum.KeywordMatchType */ export enum KeywordMatchType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN EXACT = 2, // EXACT PHRASE = 3, // PHRASE BROAD = 4, // BROAD } /** * @name ListingGroupTypeEnum.ListingGroupType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ListingGroupTypeEnum.ListingGroupType */ export enum ListingGroupType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN SUBDIVISION = 2, // SUBDIVISION UNIT = 3, // UNIT } /** * @name LocationGroupRadiusUnitsEnum.LocationGroupRadiusUnits * @link https://developers.google.com/google-ads/api/reference/rpc/v9/LocationGroupRadiusUnitsEnum.LocationGroupRadiusUnits */ export enum LocationGroupRadiusUnits { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN METERS = 2, // METERS MILES = 3, // MILES MILLI_MILES = 4, // MILLI_MILES } /** * @name MinuteOfHourEnum.MinuteOfHour * @link https://developers.google.com/google-ads/api/reference/rpc/v9/MinuteOfHourEnum.MinuteOfHour */ export enum MinuteOfHour { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ZERO = 2, // ZERO FIFTEEN = 3, // FIFTEEN THIRTY = 4, // THIRTY FORTY_FIVE = 5, // FORTY_FIVE } /** * @name ParentalStatusTypeEnum.ParentalStatusType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ParentalStatusTypeEnum.ParentalStatusType */ export enum ParentalStatusType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PARENT = 300, // PARENT NOT_A_PARENT = 301, // NOT_A_PARENT UNDETERMINED = 302, // UNDETERMINED } /** * @name PreferredContentTypeEnum.PreferredContentType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PreferredContentTypeEnum.PreferredContentType */ export enum PreferredContentType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN YOUTUBE_TOP_CONTENT = 400, // YOUTUBE_TOP_CONTENT } /** * @name ProductBiddingCategoryLevelEnum.ProductBiddingCategoryLevel * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ProductBiddingCategoryLevelEnum.ProductBiddingCategoryLevel */ export enum ProductBiddingCategoryLevel { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN LEVEL1 = 2, // LEVEL1 LEVEL2 = 3, // LEVEL2 LEVEL3 = 4, // LEVEL3 LEVEL4 = 5, // LEVEL4 LEVEL5 = 6, // LEVEL5 } /** * @name ProductChannelEnum.ProductChannel * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ProductChannelEnum.ProductChannel */ export enum ProductChannel { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ONLINE = 2, // ONLINE LOCAL = 3, // LOCAL } /** * @name ProductChannelExclusivityEnum.ProductChannelExclusivity * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ProductChannelExclusivityEnum.ProductChannelExclusivity */ export enum ProductChannelExclusivity { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN SINGLE_CHANNEL = 2, // SINGLE_CHANNEL MULTI_CHANNEL = 3, // MULTI_CHANNEL } /** * @name ProductConditionEnum.ProductCondition * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ProductConditionEnum.ProductCondition */ export enum ProductCondition { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN NEW = 3, // NEW REFURBISHED = 4, // REFURBISHED USED = 5, // USED } /** * @name ProductCustomAttributeIndexEnum.ProductCustomAttributeIndex * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ProductCustomAttributeIndexEnum.ProductCustomAttributeIndex */ export enum ProductCustomAttributeIndex { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN INDEX0 = 7, // INDEX0 INDEX1 = 8, // INDEX1 INDEX2 = 9, // INDEX2 INDEX3 = 10, // INDEX3 INDEX4 = 11, // INDEX4 } /** * @name ProductTypeLevelEnum.ProductTypeLevel * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ProductTypeLevelEnum.ProductTypeLevel */ export enum ProductTypeLevel { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN LEVEL1 = 7, // LEVEL1 LEVEL2 = 8, // LEVEL2 LEVEL3 = 9, // LEVEL3 LEVEL4 = 10, // LEVEL4 LEVEL5 = 11, // LEVEL5 } /** * @name ProximityRadiusUnitsEnum.ProximityRadiusUnits * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ProximityRadiusUnitsEnum.ProximityRadiusUnits */ export enum ProximityRadiusUnits { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN MILES = 2, // MILES KILOMETERS = 3, // KILOMETERS } /** * @name WebpageConditionOperandEnum.WebpageConditionOperand * @link https://developers.google.com/google-ads/api/reference/rpc/v9/WebpageConditionOperandEnum.WebpageConditionOperand */ export enum WebpageConditionOperand { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN URL = 2, // URL CATEGORY = 3, // CATEGORY PAGE_TITLE = 4, // PAGE_TITLE PAGE_CONTENT = 5, // PAGE_CONTENT CUSTOM_LABEL = 6, // CUSTOM_LABEL } /** * @name WebpageConditionOperatorEnum.WebpageConditionOperator * @link https://developers.google.com/google-ads/api/reference/rpc/v9/WebpageConditionOperatorEnum.WebpageConditionOperator */ export enum WebpageConditionOperator { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN EQUALS = 2, // EQUALS CONTAINS = 3, // CONTAINS } /** * @name CallToActionTypeEnum.CallToActionType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CallToActionTypeEnum.CallToActionType */ export enum CallToActionType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN LEARN_MORE = 2, // LEARN_MORE GET_QUOTE = 3, // GET_QUOTE APPLY_NOW = 4, // APPLY_NOW SIGN_UP = 5, // SIGN_UP CONTACT_US = 6, // CONTACT_US SUBSCRIBE = 7, // SUBSCRIBE DOWNLOAD = 8, // DOWNLOAD BOOK_NOW = 9, // BOOK_NOW SHOP_NOW = 10, // SHOP_NOW } /** * @name LeadFormCallToActionTypeEnum.LeadFormCallToActionType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/LeadFormCallToActionTypeEnum.LeadFormCallToActionType */ export enum LeadFormCallToActionType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN LEARN_MORE = 2, // LEARN_MORE GET_QUOTE = 3, // GET_QUOTE APPLY_NOW = 4, // APPLY_NOW SIGN_UP = 5, // SIGN_UP CONTACT_US = 6, // CONTACT_US SUBSCRIBE = 7, // SUBSCRIBE DOWNLOAD = 8, // DOWNLOAD BOOK_NOW = 9, // BOOK_NOW GET_OFFER = 10, // GET_OFFER REGISTER = 11, // REGISTER GET_INFO = 12, // GET_INFO REQUEST_DEMO = 13, // REQUEST_DEMO JOIN_NOW = 14, // JOIN_NOW GET_STARTED = 15, // GET_STARTED } /** * @name LeadFormDesiredIntentEnum.LeadFormDesiredIntent * @link https://developers.google.com/google-ads/api/reference/rpc/v9/LeadFormDesiredIntentEnum.LeadFormDesiredIntent */ export enum LeadFormDesiredIntent { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN LOW_INTENT = 2, // LOW_INTENT HIGH_INTENT = 3, // HIGH_INTENT } /** * @name LeadFormFieldUserInputTypeEnum.LeadFormFieldUserInputType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/LeadFormFieldUserInputTypeEnum.LeadFormFieldUserInputType */ export enum LeadFormFieldUserInputType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN FULL_NAME = 2, // FULL_NAME EMAIL = 3, // EMAIL PHONE_NUMBER = 4, // PHONE_NUMBER POSTAL_CODE = 5, // POSTAL_CODE CITY = 9, // CITY REGION = 10, // REGION COUNTRY = 11, // COUNTRY WORK_EMAIL = 12, // WORK_EMAIL COMPANY_NAME = 13, // COMPANY_NAME WORK_PHONE = 14, // WORK_PHONE JOB_TITLE = 15, // JOB_TITLE FIRST_NAME = 23, // FIRST_NAME LAST_NAME = 24, // LAST_NAME VEHICLE_MODEL = 1001, // VEHICLE_MODEL VEHICLE_TYPE = 1002, // VEHICLE_TYPE PREFERRED_DEALERSHIP = 1003, // PREFERRED_DEALERSHIP VEHICLE_PURCHASE_TIMELINE = 1004, // VEHICLE_PURCHASE_TIMELINE VEHICLE_OWNERSHIP = 1005, // VEHICLE_OWNERSHIP VEHICLE_PAYMENT_TYPE = 1009, // VEHICLE_PAYMENT_TYPE VEHICLE_CONDITION = 1010, // VEHICLE_CONDITION COMPANY_SIZE = 1006, // COMPANY_SIZE ANNUAL_SALES = 1007, // ANNUAL_SALES YEARS_IN_BUSINESS = 1008, // YEARS_IN_BUSINESS JOB_DEPARTMENT = 1011, // JOB_DEPARTMENT JOB_ROLE = 1012, // JOB_ROLE EDUCATION_PROGRAM = 1013, // EDUCATION_PROGRAM EDUCATION_COURSE = 1014, // EDUCATION_COURSE PRODUCT = 1016, // PRODUCT SERVICE = 1017, // SERVICE OFFER = 1018, // OFFER CATEGORY = 1019, // CATEGORY PREFERRED_CONTACT_METHOD = 1020, // PREFERRED_CONTACT_METHOD PREFERRED_LOCATION = 1021, // PREFERRED_LOCATION PREFERRED_CONTACT_TIME = 1022, // PREFERRED_CONTACT_TIME PURCHASE_TIMELINE = 1023, // PURCHASE_TIMELINE YEARS_OF_EXPERIENCE = 1048, // YEARS_OF_EXPERIENCE JOB_INDUSTRY = 1049, // JOB_INDUSTRY LEVEL_OF_EDUCATION = 1050, // LEVEL_OF_EDUCATION PROPERTY_TYPE = 1024, // PROPERTY_TYPE REALTOR_HELP_GOAL = 1025, // REALTOR_HELP_GOAL PROPERTY_COMMUNITY = 1026, // PROPERTY_COMMUNITY PRICE_RANGE = 1027, // PRICE_RANGE NUMBER_OF_BEDROOMS = 1028, // NUMBER_OF_BEDROOMS FURNISHED_PROPERTY = 1029, // FURNISHED_PROPERTY PETS_ALLOWED_PROPERTY = 1030, // PETS_ALLOWED_PROPERTY NEXT_PLANNED_PURCHASE = 1031, // NEXT_PLANNED_PURCHASE EVENT_SIGNUP_INTEREST = 1033, // EVENT_SIGNUP_INTEREST PREFERRED_SHOPPING_PLACES = 1034, // PREFERRED_SHOPPING_PLACES FAVORITE_BRAND = 1035, // FAVORITE_BRAND TRANSPORTATION_COMMERCIAL_LICENSE_TYPE = 1036, // TRANSPORTATION_COMMERCIAL_LICENSE_TYPE EVENT_BOOKING_INTEREST = 1038, // EVENT_BOOKING_INTEREST DESTINATION_COUNTRY = 1039, // DESTINATION_COUNTRY DESTINATION_CITY = 1040, // DESTINATION_CITY DEPARTURE_COUNTRY = 1041, // DEPARTURE_COUNTRY DEPARTURE_CITY = 1042, // DEPARTURE_CITY DEPARTURE_DATE = 1043, // DEPARTURE_DATE RETURN_DATE = 1044, // RETURN_DATE NUMBER_OF_TRAVELERS = 1045, // NUMBER_OF_TRAVELERS TRAVEL_BUDGET = 1046, // TRAVEL_BUDGET TRAVEL_ACCOMMODATION = 1047, // TRAVEL_ACCOMMODATION } /** * @name LeadFormPostSubmitCallToActionTypeEnum.LeadFormPostSubmitCallToActionType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/LeadFormPostSubmitCallToActionTypeEnum.LeadFormPostSubmitCallToActionType */ export enum LeadFormPostSubmitCallToActionType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN VISIT_SITE = 2, // VISIT_SITE DOWNLOAD = 3, // DOWNLOAD LEARN_MORE = 4, // LEARN_MORE SHOP_NOW = 5, // SHOP_NOW } /** * @name MobileAppVendorEnum.MobileAppVendor * @link https://developers.google.com/google-ads/api/reference/rpc/v9/MobileAppVendorEnum.MobileAppVendor */ export enum MobileAppVendor { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN APPLE_APP_STORE = 2, // APPLE_APP_STORE GOOGLE_APP_STORE = 3, // GOOGLE_APP_STORE } /** * @name PriceExtensionPriceQualifierEnum.PriceExtensionPriceQualifier * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PriceExtensionPriceQualifierEnum.PriceExtensionPriceQualifier */ export enum PriceExtensionPriceQualifier { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN FROM = 2, // FROM UP_TO = 3, // UP_TO AVERAGE = 4, // AVERAGE } /** * @name PriceExtensionPriceUnitEnum.PriceExtensionPriceUnit * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PriceExtensionPriceUnitEnum.PriceExtensionPriceUnit */ export enum PriceExtensionPriceUnit { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PER_HOUR = 2, // PER_HOUR PER_DAY = 3, // PER_DAY PER_WEEK = 4, // PER_WEEK PER_MONTH = 5, // PER_MONTH PER_YEAR = 6, // PER_YEAR PER_NIGHT = 7, // PER_NIGHT } /** * @name PriceExtensionTypeEnum.PriceExtensionType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PriceExtensionTypeEnum.PriceExtensionType */ export enum PriceExtensionType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN BRANDS = 2, // BRANDS EVENTS = 3, // EVENTS LOCATIONS = 4, // LOCATIONS NEIGHBORHOODS = 5, // NEIGHBORHOODS PRODUCT_CATEGORIES = 6, // PRODUCT_CATEGORIES PRODUCT_TIERS = 7, // PRODUCT_TIERS SERVICES = 8, // SERVICES SERVICE_CATEGORIES = 9, // SERVICE_CATEGORIES SERVICE_TIERS = 10, // SERVICE_TIERS } /** * @name PromotionExtensionDiscountModifierEnum.PromotionExtensionDiscountModifier * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PromotionExtensionDiscountModifierEnum.PromotionExtensionDiscountModifier */ export enum PromotionExtensionDiscountModifier { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN UP_TO = 2, // UP_TO } /** * @name PromotionExtensionOccasionEnum.PromotionExtensionOccasion * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PromotionExtensionOccasionEnum.PromotionExtensionOccasion */ export enum PromotionExtensionOccasion { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN NEW_YEARS = 2, // NEW_YEARS CHINESE_NEW_YEAR = 3, // CHINESE_NEW_YEAR VALENTINES_DAY = 4, // VALENTINES_DAY EASTER = 5, // EASTER MOTHERS_DAY = 6, // MOTHERS_DAY FATHERS_DAY = 7, // FATHERS_DAY LABOR_DAY = 8, // LABOR_DAY BACK_TO_SCHOOL = 9, // BACK_TO_SCHOOL HALLOWEEN = 10, // HALLOWEEN BLACK_FRIDAY = 11, // BLACK_FRIDAY CYBER_MONDAY = 12, // CYBER_MONDAY CHRISTMAS = 13, // CHRISTMAS BOXING_DAY = 14, // BOXING_DAY INDEPENDENCE_DAY = 15, // INDEPENDENCE_DAY NATIONAL_DAY = 16, // NATIONAL_DAY END_OF_SEASON = 17, // END_OF_SEASON WINTER_SALE = 18, // WINTER_SALE SUMMER_SALE = 19, // SUMMER_SALE FALL_SALE = 20, // FALL_SALE SPRING_SALE = 21, // SPRING_SALE RAMADAN = 22, // RAMADAN EID_AL_FITR = 23, // EID_AL_FITR EID_AL_ADHA = 24, // EID_AL_ADHA SINGLES_DAY = 25, // SINGLES_DAY WOMENS_DAY = 26, // WOMENS_DAY HOLI = 27, // HOLI PARENTS_DAY = 28, // PARENTS_DAY ST_NICHOLAS_DAY = 29, // ST_NICHOLAS_DAY CARNIVAL = 30, // CARNIVAL EPIPHANY = 31, // EPIPHANY ROSH_HASHANAH = 32, // ROSH_HASHANAH PASSOVER = 33, // PASSOVER HANUKKAH = 34, // HANUKKAH DIWALI = 35, // DIWALI NAVRATRI = 36, // NAVRATRI SONGKRAN = 37, // SONGKRAN YEAR_END_GIFT = 38, // YEAR_END_GIFT } /** * @name TargetImpressionShareLocationEnum.TargetImpressionShareLocation * @link https://developers.google.com/google-ads/api/reference/rpc/v9/TargetImpressionShareLocationEnum.TargetImpressionShareLocation */ export enum TargetImpressionShareLocation { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ANYWHERE_ON_PAGE = 2, // ANYWHERE_ON_PAGE TOP_OF_PAGE = 3, // TOP_OF_PAGE ABSOLUTE_TOP_OF_PAGE = 4, // ABSOLUTE_TOP_OF_PAGE } /** * @name AdvertisingChannelSubTypeEnum.AdvertisingChannelSubType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AdvertisingChannelSubTypeEnum.AdvertisingChannelSubType */ export enum AdvertisingChannelSubType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN SEARCH_MOBILE_APP = 2, // SEARCH_MOBILE_APP DISPLAY_MOBILE_APP = 3, // DISPLAY_MOBILE_APP SEARCH_EXPRESS = 4, // SEARCH_EXPRESS DISPLAY_EXPRESS = 5, // DISPLAY_EXPRESS SHOPPING_SMART_ADS = 6, // SHOPPING_SMART_ADS DISPLAY_GMAIL_AD = 7, // DISPLAY_GMAIL_AD DISPLAY_SMART_CAMPAIGN = 8, // DISPLAY_SMART_CAMPAIGN VIDEO_OUTSTREAM = 9, // VIDEO_OUTSTREAM VIDEO_ACTION = 10, // VIDEO_ACTION VIDEO_NON_SKIPPABLE = 11, // VIDEO_NON_SKIPPABLE APP_CAMPAIGN = 12, // APP_CAMPAIGN APP_CAMPAIGN_FOR_ENGAGEMENT = 13, // APP_CAMPAIGN_FOR_ENGAGEMENT LOCAL_CAMPAIGN = 14, // LOCAL_CAMPAIGN SHOPPING_COMPARISON_LISTING_ADS = 15, // SHOPPING_COMPARISON_LISTING_ADS SMART_CAMPAIGN = 16, // SMART_CAMPAIGN VIDEO_SEQUENCE = 17, // VIDEO_SEQUENCE APP_CAMPAIGN_FOR_PRE_REGISTRATION = 18, // APP_CAMPAIGN_FOR_PRE_REGISTRATION } /** * @name AdvertisingChannelTypeEnum.AdvertisingChannelType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AdvertisingChannelTypeEnum.AdvertisingChannelType */ export enum AdvertisingChannelType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN SEARCH = 2, // SEARCH DISPLAY = 3, // DISPLAY SHOPPING = 4, // SHOPPING HOTEL = 5, // HOTEL VIDEO = 6, // VIDEO MULTI_CHANNEL = 7, // MULTI_CHANNEL LOCAL = 8, // LOCAL SMART = 9, // SMART PERFORMANCE_MAX = 10, // PERFORMANCE_MAX } /** * @name CriterionCategoryChannelAvailabilityModeEnum.CriterionCategoryChannelAvailabilityMode * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CriterionCategoryChannelAvailabilityModeEnum.CriterionCategoryChannelAvailabilityMode */ export enum CriterionCategoryChannelAvailabilityMode { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ALL_CHANNELS = 2, // ALL_CHANNELS CHANNEL_TYPE_AND_ALL_SUBTYPES = 3, // CHANNEL_TYPE_AND_ALL_SUBTYPES CHANNEL_TYPE_AND_SUBSET_SUBTYPES = 4, // CHANNEL_TYPE_AND_SUBSET_SUBTYPES } /** * @name CriterionCategoryLocaleAvailabilityModeEnum.CriterionCategoryLocaleAvailabilityMode * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CriterionCategoryLocaleAvailabilityModeEnum.CriterionCategoryLocaleAvailabilityMode */ export enum CriterionCategoryLocaleAvailabilityMode { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ALL_LOCALES = 2, // ALL_LOCALES COUNTRY_AND_ALL_LANGUAGES = 3, // COUNTRY_AND_ALL_LANGUAGES LANGUAGE_AND_ALL_COUNTRIES = 4, // LANGUAGE_AND_ALL_COUNTRIES COUNTRY_AND_LANGUAGE = 5, // COUNTRY_AND_LANGUAGE } /** * @name CustomizerAttributeTypeEnum.CustomizerAttributeType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CustomizerAttributeTypeEnum.CustomizerAttributeType */ export enum CustomizerAttributeType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN TEXT = 2, // TEXT NUMBER = 3, // NUMBER PRICE = 4, // PRICE PERCENT = 5, // PERCENT } /** * @name MonthOfYearEnum.MonthOfYear * @link https://developers.google.com/google-ads/api/reference/rpc/v9/MonthOfYearEnum.MonthOfYear */ export enum MonthOfYear { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN JANUARY = 2, // JANUARY FEBRUARY = 3, // FEBRUARY MARCH = 4, // MARCH APRIL = 5, // APRIL MAY = 6, // MAY JUNE = 7, // JUNE JULY = 8, // JULY AUGUST = 9, // AUGUST SEPTEMBER = 10, // SEPTEMBER OCTOBER = 11, // OCTOBER NOVEMBER = 12, // NOVEMBER DECEMBER = 13, // DECEMBER } /** * @name AppStoreEnum.AppStore * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AppStoreEnum.AppStore */ export enum AppStore { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN APPLE_ITUNES = 2, // APPLE_ITUNES GOOGLE_PLAY = 3, // GOOGLE_PLAY } /** * @name FeedItemSetStringFilterTypeEnum.FeedItemSetStringFilterType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedItemSetStringFilterTypeEnum.FeedItemSetStringFilterType */ export enum FeedItemSetStringFilterType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN EXACT = 2, // EXACT } /** * @name AppUrlOperatingSystemTypeEnum.AppUrlOperatingSystemType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AppUrlOperatingSystemTypeEnum.AppUrlOperatingSystemType */ export enum AppUrlOperatingSystemType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN IOS = 2, // IOS ANDROID = 3, // ANDROID } /** * @name FrequencyCapEventTypeEnum.FrequencyCapEventType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FrequencyCapEventTypeEnum.FrequencyCapEventType */ export enum FrequencyCapEventType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN IMPRESSION = 2, // IMPRESSION VIDEO_VIEW = 3, // VIDEO_VIEW } /** * @name FrequencyCapLevelEnum.FrequencyCapLevel * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FrequencyCapLevelEnum.FrequencyCapLevel */ export enum FrequencyCapLevel { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN AD_GROUP_AD = 2, // AD_GROUP_AD AD_GROUP = 3, // AD_GROUP CAMPAIGN = 4, // CAMPAIGN } /** * @name FrequencyCapTimeUnitEnum.FrequencyCapTimeUnit * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FrequencyCapTimeUnitEnum.FrequencyCapTimeUnit */ export enum FrequencyCapTimeUnit { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN DAY = 2, // DAY WEEK = 3, // WEEK MONTH = 4, // MONTH } /** * @name KeywordPlanAggregateMetricTypeEnum.KeywordPlanAggregateMetricType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/KeywordPlanAggregateMetricTypeEnum.KeywordPlanAggregateMetricType */ export enum KeywordPlanAggregateMetricType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN DEVICE = 2, // DEVICE } /** * @name KeywordPlanCompetitionLevelEnum.KeywordPlanCompetitionLevel * @link https://developers.google.com/google-ads/api/reference/rpc/v9/KeywordPlanCompetitionLevelEnum.KeywordPlanCompetitionLevel */ export enum KeywordPlanCompetitionLevel { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN LOW = 2, // LOW MEDIUM = 3, // MEDIUM HIGH = 4, // HIGH } /** * @name KeywordPlanConceptGroupTypeEnum.KeywordPlanConceptGroupType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/KeywordPlanConceptGroupTypeEnum.KeywordPlanConceptGroupType */ export enum KeywordPlanConceptGroupType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN BRAND = 2, // BRAND OTHER_BRANDS = 3, // OTHER_BRANDS NON_BRAND = 4, // NON_BRAND } /** * @name MatchingFunctionContextTypeEnum.MatchingFunctionContextType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/MatchingFunctionContextTypeEnum.MatchingFunctionContextType */ export enum MatchingFunctionContextType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN FEED_ITEM_ID = 2, // FEED_ITEM_ID DEVICE_NAME = 3, // DEVICE_NAME FEED_ITEM_SET_ID = 4, // FEED_ITEM_SET_ID } /** * @name MatchingFunctionOperatorEnum.MatchingFunctionOperator * @link https://developers.google.com/google-ads/api/reference/rpc/v9/MatchingFunctionOperatorEnum.MatchingFunctionOperator */ export enum MatchingFunctionOperator { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN IN = 2, // IN IDENTITY = 3, // IDENTITY EQUALS = 4, // EQUALS AND = 5, // AND CONTAINS_ANY = 6, // CONTAINS_ANY } /** * @name InteractionEventTypeEnum.InteractionEventType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/InteractionEventTypeEnum.InteractionEventType */ export enum InteractionEventType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CLICK = 2, // CLICK ENGAGEMENT = 3, // ENGAGEMENT VIDEO_VIEW = 4, // VIDEO_VIEW NONE = 5, // NONE } /** * @name QualityScoreBucketEnum.QualityScoreBucket * @link https://developers.google.com/google-ads/api/reference/rpc/v9/QualityScoreBucketEnum.QualityScoreBucket */ export enum QualityScoreBucket { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN BELOW_AVERAGE = 2, // BELOW_AVERAGE AVERAGE = 3, // AVERAGE ABOVE_AVERAGE = 4, // ABOVE_AVERAGE } /** * @name UserIdentifierSourceEnum.UserIdentifierSource * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserIdentifierSourceEnum.UserIdentifierSource */ export enum UserIdentifierSource { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN FIRST_PARTY = 2, // FIRST_PARTY THIRD_PARTY = 3, // THIRD_PARTY } /** * @name AdDestinationTypeEnum.AdDestinationType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AdDestinationTypeEnum.AdDestinationType */ export enum AdDestinationType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN NOT_APPLICABLE = 2, // NOT_APPLICABLE WEBSITE = 3, // WEBSITE APP_DEEP_LINK = 4, // APP_DEEP_LINK APP_STORE = 5, // APP_STORE PHONE_CALL = 6, // PHONE_CALL MAP_DIRECTIONS = 7, // MAP_DIRECTIONS LOCATION_LISTING = 8, // LOCATION_LISTING MESSAGE = 9, // MESSAGE LEAD_FORM = 10, // LEAD_FORM YOUTUBE = 11, // YOUTUBE UNMODELED_FOR_CONVERSIONS = 12, // UNMODELED_FOR_CONVERSIONS } /** * @name AdNetworkTypeEnum.AdNetworkType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AdNetworkTypeEnum.AdNetworkType */ export enum AdNetworkType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN SEARCH = 2, // SEARCH SEARCH_PARTNERS = 3, // SEARCH_PARTNERS CONTENT = 4, // CONTENT YOUTUBE_SEARCH = 5, // YOUTUBE_SEARCH YOUTUBE_WATCH = 6, // YOUTUBE_WATCH MIXED = 7, // MIXED } /** * @name BudgetCampaignAssociationStatusEnum.BudgetCampaignAssociationStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/BudgetCampaignAssociationStatusEnum.BudgetCampaignAssociationStatus */ export enum BudgetCampaignAssociationStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name ClickTypeEnum.ClickType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ClickTypeEnum.ClickType */ export enum ClickType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN APP_DEEPLINK = 2, // APP_DEEPLINK BREADCRUMBS = 3, // BREADCRUMBS BROADBAND_PLAN = 4, // BROADBAND_PLAN CALL_TRACKING = 5, // CALL_TRACKING CALLS = 6, // CALLS CLICK_ON_ENGAGEMENT_AD = 7, // CLICK_ON_ENGAGEMENT_AD GET_DIRECTIONS = 8, // GET_DIRECTIONS LOCATION_EXPANSION = 9, // LOCATION_EXPANSION LOCATION_FORMAT_CALL = 10, // LOCATION_FORMAT_CALL LOCATION_FORMAT_DIRECTIONS = 11, // LOCATION_FORMAT_DIRECTIONS LOCATION_FORMAT_IMAGE = 12, // LOCATION_FORMAT_IMAGE LOCATION_FORMAT_LANDING_PAGE = 13, // LOCATION_FORMAT_LANDING_PAGE LOCATION_FORMAT_MAP = 14, // LOCATION_FORMAT_MAP LOCATION_FORMAT_STORE_INFO = 15, // LOCATION_FORMAT_STORE_INFO LOCATION_FORMAT_TEXT = 16, // LOCATION_FORMAT_TEXT MOBILE_CALL_TRACKING = 17, // MOBILE_CALL_TRACKING OFFER_PRINTS = 18, // OFFER_PRINTS OTHER = 19, // OTHER PRODUCT_EXTENSION_CLICKS = 20, // PRODUCT_EXTENSION_CLICKS PRODUCT_LISTING_AD_CLICKS = 21, // PRODUCT_LISTING_AD_CLICKS SITELINKS = 22, // SITELINKS STORE_LOCATOR = 23, // STORE_LOCATOR URL_CLICKS = 25, // URL_CLICKS VIDEO_APP_STORE_CLICKS = 26, // VIDEO_APP_STORE_CLICKS VIDEO_CALL_TO_ACTION_CLICKS = 27, // VIDEO_CALL_TO_ACTION_CLICKS VIDEO_CARD_ACTION_HEADLINE_CLICKS = 28, // VIDEO_CARD_ACTION_HEADLINE_CLICKS VIDEO_END_CAP_CLICKS = 29, // VIDEO_END_CAP_CLICKS VIDEO_WEBSITE_CLICKS = 30, // VIDEO_WEBSITE_CLICKS VISUAL_SITELINKS = 31, // VISUAL_SITELINKS WIRELESS_PLAN = 32, // WIRELESS_PLAN PRODUCT_LISTING_AD_LOCAL = 33, // PRODUCT_LISTING_AD_LOCAL PRODUCT_LISTING_AD_MULTICHANNEL_LOCAL = 34, // PRODUCT_LISTING_AD_MULTICHANNEL_LOCAL PRODUCT_LISTING_AD_MULTICHANNEL_ONLINE = 35, // PRODUCT_LISTING_AD_MULTICHANNEL_ONLINE PRODUCT_LISTING_ADS_COUPON = 36, // PRODUCT_LISTING_ADS_COUPON PRODUCT_LISTING_AD_TRANSACTABLE = 37, // PRODUCT_LISTING_AD_TRANSACTABLE PRODUCT_AD_APP_DEEPLINK = 38, // PRODUCT_AD_APP_DEEPLINK SHOWCASE_AD_CATEGORY_LINK = 39, // SHOWCASE_AD_CATEGORY_LINK SHOWCASE_AD_LOCAL_STOREFRONT_LINK = 40, // SHOWCASE_AD_LOCAL_STOREFRONT_LINK SHOWCASE_AD_ONLINE_PRODUCT_LINK = 42, // SHOWCASE_AD_ONLINE_PRODUCT_LINK SHOWCASE_AD_LOCAL_PRODUCT_LINK = 43, // SHOWCASE_AD_LOCAL_PRODUCT_LINK PROMOTION_EXTENSION = 44, // PROMOTION_EXTENSION SWIPEABLE_GALLERY_AD_HEADLINE = 45, // SWIPEABLE_GALLERY_AD_HEADLINE SWIPEABLE_GALLERY_AD_SWIPES = 46, // SWIPEABLE_GALLERY_AD_SWIPES SWIPEABLE_GALLERY_AD_SEE_MORE = 47, // SWIPEABLE_GALLERY_AD_SEE_MORE SWIPEABLE_GALLERY_AD_SITELINK_ONE = 48, // SWIPEABLE_GALLERY_AD_SITELINK_ONE SWIPEABLE_GALLERY_AD_SITELINK_TWO = 49, // SWIPEABLE_GALLERY_AD_SITELINK_TWO SWIPEABLE_GALLERY_AD_SITELINK_THREE = 50, // SWIPEABLE_GALLERY_AD_SITELINK_THREE SWIPEABLE_GALLERY_AD_SITELINK_FOUR = 51, // SWIPEABLE_GALLERY_AD_SITELINK_FOUR SWIPEABLE_GALLERY_AD_SITELINK_FIVE = 52, // SWIPEABLE_GALLERY_AD_SITELINK_FIVE HOTEL_PRICE = 53, // HOTEL_PRICE PRICE_EXTENSION = 54, // PRICE_EXTENSION HOTEL_BOOK_ON_GOOGLE_ROOM_SELECTION = 55, // HOTEL_BOOK_ON_GOOGLE_ROOM_SELECTION SHOPPING_COMPARISON_LISTING = 56, // SHOPPING_COMPARISON_LISTING } /** * @name ConversionActionCategoryEnum.ConversionActionCategory * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ConversionActionCategoryEnum.ConversionActionCategory */ export enum ConversionActionCategory { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN DEFAULT = 2, // DEFAULT PAGE_VIEW = 3, // PAGE_VIEW PURCHASE = 4, // PURCHASE SIGNUP = 5, // SIGNUP LEAD = 6, // LEAD DOWNLOAD = 7, // DOWNLOAD ADD_TO_CART = 8, // ADD_TO_CART BEGIN_CHECKOUT = 9, // BEGIN_CHECKOUT SUBSCRIBE_PAID = 10, // SUBSCRIBE_PAID PHONE_CALL_LEAD = 11, // PHONE_CALL_LEAD IMPORTED_LEAD = 12, // IMPORTED_LEAD SUBMIT_LEAD_FORM = 13, // SUBMIT_LEAD_FORM BOOK_APPOINTMENT = 14, // BOOK_APPOINTMENT REQUEST_QUOTE = 15, // REQUEST_QUOTE GET_DIRECTIONS = 16, // GET_DIRECTIONS OUTBOUND_CLICK = 17, // OUTBOUND_CLICK CONTACT = 18, // CONTACT ENGAGEMENT = 19, // ENGAGEMENT STORE_VISIT = 20, // STORE_VISIT STORE_SALE = 21, // STORE_SALE } /** * @name ConversionAttributionEventTypeEnum.ConversionAttributionEventType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ConversionAttributionEventTypeEnum.ConversionAttributionEventType */ export enum ConversionAttributionEventType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN IMPRESSION = 2, // IMPRESSION INTERACTION = 3, // INTERACTION } /** * @name ConversionLagBucketEnum.ConversionLagBucket * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ConversionLagBucketEnum.ConversionLagBucket */ export enum ConversionLagBucket { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN LESS_THAN_ONE_DAY = 2, // LESS_THAN_ONE_DAY ONE_TO_TWO_DAYS = 3, // ONE_TO_TWO_DAYS TWO_TO_THREE_DAYS = 4, // TWO_TO_THREE_DAYS THREE_TO_FOUR_DAYS = 5, // THREE_TO_FOUR_DAYS FOUR_TO_FIVE_DAYS = 6, // FOUR_TO_FIVE_DAYS FIVE_TO_SIX_DAYS = 7, // FIVE_TO_SIX_DAYS SIX_TO_SEVEN_DAYS = 8, // SIX_TO_SEVEN_DAYS SEVEN_TO_EIGHT_DAYS = 9, // SEVEN_TO_EIGHT_DAYS EIGHT_TO_NINE_DAYS = 10, // EIGHT_TO_NINE_DAYS NINE_TO_TEN_DAYS = 11, // NINE_TO_TEN_DAYS TEN_TO_ELEVEN_DAYS = 12, // TEN_TO_ELEVEN_DAYS ELEVEN_TO_TWELVE_DAYS = 13, // ELEVEN_TO_TWELVE_DAYS TWELVE_TO_THIRTEEN_DAYS = 14, // TWELVE_TO_THIRTEEN_DAYS THIRTEEN_TO_FOURTEEN_DAYS = 15, // THIRTEEN_TO_FOURTEEN_DAYS FOURTEEN_TO_TWENTY_ONE_DAYS = 16, // FOURTEEN_TO_TWENTY_ONE_DAYS TWENTY_ONE_TO_THIRTY_DAYS = 17, // TWENTY_ONE_TO_THIRTY_DAYS THIRTY_TO_FORTY_FIVE_DAYS = 18, // THIRTY_TO_FORTY_FIVE_DAYS FORTY_FIVE_TO_SIXTY_DAYS = 19, // FORTY_FIVE_TO_SIXTY_DAYS SIXTY_TO_NINETY_DAYS = 20, // SIXTY_TO_NINETY_DAYS } /** * @name ConversionOrAdjustmentLagBucketEnum.ConversionOrAdjustmentLagBucket * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ConversionOrAdjustmentLagBucketEnum.ConversionOrAdjustmentLagBucket */ export enum ConversionOrAdjustmentLagBucket { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CONVERSION_LESS_THAN_ONE_DAY = 2, // CONVERSION_LESS_THAN_ONE_DAY CONVERSION_ONE_TO_TWO_DAYS = 3, // CONVERSION_ONE_TO_TWO_DAYS CONVERSION_TWO_TO_THREE_DAYS = 4, // CONVERSION_TWO_TO_THREE_DAYS CONVERSION_THREE_TO_FOUR_DAYS = 5, // CONVERSION_THREE_TO_FOUR_DAYS CONVERSION_FOUR_TO_FIVE_DAYS = 6, // CONVERSION_FOUR_TO_FIVE_DAYS CONVERSION_FIVE_TO_SIX_DAYS = 7, // CONVERSION_FIVE_TO_SIX_DAYS CONVERSION_SIX_TO_SEVEN_DAYS = 8, // CONVERSION_SIX_TO_SEVEN_DAYS CONVERSION_SEVEN_TO_EIGHT_DAYS = 9, // CONVERSION_SEVEN_TO_EIGHT_DAYS CONVERSION_EIGHT_TO_NINE_DAYS = 10, // CONVERSION_EIGHT_TO_NINE_DAYS CONVERSION_NINE_TO_TEN_DAYS = 11, // CONVERSION_NINE_TO_TEN_DAYS CONVERSION_TEN_TO_ELEVEN_DAYS = 12, // CONVERSION_TEN_TO_ELEVEN_DAYS CONVERSION_ELEVEN_TO_TWELVE_DAYS = 13, // CONVERSION_ELEVEN_TO_TWELVE_DAYS CONVERSION_TWELVE_TO_THIRTEEN_DAYS = 14, // CONVERSION_TWELVE_TO_THIRTEEN_DAYS CONVERSION_THIRTEEN_TO_FOURTEEN_DAYS = 15, // CONVERSION_THIRTEEN_TO_FOURTEEN_DAYS CONVERSION_FOURTEEN_TO_TWENTY_ONE_DAYS = 16, // CONVERSION_FOURTEEN_TO_TWENTY_ONE_DAYS CONVERSION_TWENTY_ONE_TO_THIRTY_DAYS = 17, // CONVERSION_TWENTY_ONE_TO_THIRTY_DAYS CONVERSION_THIRTY_TO_FORTY_FIVE_DAYS = 18, // CONVERSION_THIRTY_TO_FORTY_FIVE_DAYS CONVERSION_FORTY_FIVE_TO_SIXTY_DAYS = 19, // CONVERSION_FORTY_FIVE_TO_SIXTY_DAYS CONVERSION_SIXTY_TO_NINETY_DAYS = 20, // CONVERSION_SIXTY_TO_NINETY_DAYS ADJUSTMENT_LESS_THAN_ONE_DAY = 21, // ADJUSTMENT_LESS_THAN_ONE_DAY ADJUSTMENT_ONE_TO_TWO_DAYS = 22, // ADJUSTMENT_ONE_TO_TWO_DAYS ADJUSTMENT_TWO_TO_THREE_DAYS = 23, // ADJUSTMENT_TWO_TO_THREE_DAYS ADJUSTMENT_THREE_TO_FOUR_DAYS = 24, // ADJUSTMENT_THREE_TO_FOUR_DAYS ADJUSTMENT_FOUR_TO_FIVE_DAYS = 25, // ADJUSTMENT_FOUR_TO_FIVE_DAYS ADJUSTMENT_FIVE_TO_SIX_DAYS = 26, // ADJUSTMENT_FIVE_TO_SIX_DAYS ADJUSTMENT_SIX_TO_SEVEN_DAYS = 27, // ADJUSTMENT_SIX_TO_SEVEN_DAYS ADJUSTMENT_SEVEN_TO_EIGHT_DAYS = 28, // ADJUSTMENT_SEVEN_TO_EIGHT_DAYS ADJUSTMENT_EIGHT_TO_NINE_DAYS = 29, // ADJUSTMENT_EIGHT_TO_NINE_DAYS ADJUSTMENT_NINE_TO_TEN_DAYS = 30, // ADJUSTMENT_NINE_TO_TEN_DAYS ADJUSTMENT_TEN_TO_ELEVEN_DAYS = 31, // ADJUSTMENT_TEN_TO_ELEVEN_DAYS ADJUSTMENT_ELEVEN_TO_TWELVE_DAYS = 32, // ADJUSTMENT_ELEVEN_TO_TWELVE_DAYS ADJUSTMENT_TWELVE_TO_THIRTEEN_DAYS = 33, // ADJUSTMENT_TWELVE_TO_THIRTEEN_DAYS ADJUSTMENT_THIRTEEN_TO_FOURTEEN_DAYS = 34, // ADJUSTMENT_THIRTEEN_TO_FOURTEEN_DAYS ADJUSTMENT_FOURTEEN_TO_TWENTY_ONE_DAYS = 35, // ADJUSTMENT_FOURTEEN_TO_TWENTY_ONE_DAYS ADJUSTMENT_TWENTY_ONE_TO_THIRTY_DAYS = 36, // ADJUSTMENT_TWENTY_ONE_TO_THIRTY_DAYS ADJUSTMENT_THIRTY_TO_FORTY_FIVE_DAYS = 37, // ADJUSTMENT_THIRTY_TO_FORTY_FIVE_DAYS ADJUSTMENT_FORTY_FIVE_TO_SIXTY_DAYS = 38, // ADJUSTMENT_FORTY_FIVE_TO_SIXTY_DAYS ADJUSTMENT_SIXTY_TO_NINETY_DAYS = 39, // ADJUSTMENT_SIXTY_TO_NINETY_DAYS ADJUSTMENT_NINETY_TO_ONE_HUNDRED_AND_FORTY_FIVE_DAYS = 40, // ADJUSTMENT_NINETY_TO_ONE_HUNDRED_AND_FORTY_FIVE_DAYS CONVERSION_UNKNOWN = 41, // CONVERSION_UNKNOWN ADJUSTMENT_UNKNOWN = 42, // ADJUSTMENT_UNKNOWN } /** * @name ConversionValueRulePrimaryDimensionEnum.ConversionValueRulePrimaryDimension * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ConversionValueRulePrimaryDimensionEnum.ConversionValueRulePrimaryDimension */ export enum ConversionValueRulePrimaryDimension { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN NO_RULE_APPLIED = 2, // NO_RULE_APPLIED ORIGINAL = 3, // ORIGINAL NEW_VS_RETURNING_USER = 4, // NEW_VS_RETURNING_USER GEO_LOCATION = 5, // GEO_LOCATION DEVICE = 6, // DEVICE AUDIENCE = 7, // AUDIENCE MULTIPLE = 8, // MULTIPLE } /** * @name ExternalConversionSourceEnum.ExternalConversionSource * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ExternalConversionSourceEnum.ExternalConversionSource */ export enum ExternalConversionSource { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN WEBPAGE = 2, // WEBPAGE ANALYTICS = 3, // ANALYTICS UPLOAD = 4, // UPLOAD AD_CALL_METRICS = 5, // AD_CALL_METRICS WEBSITE_CALL_METRICS = 6, // WEBSITE_CALL_METRICS STORE_VISITS = 7, // STORE_VISITS ANDROID_IN_APP = 8, // ANDROID_IN_APP IOS_IN_APP = 9, // IOS_IN_APP IOS_FIRST_OPEN = 10, // IOS_FIRST_OPEN APP_UNSPECIFIED = 11, // APP_UNSPECIFIED ANDROID_FIRST_OPEN = 12, // ANDROID_FIRST_OPEN UPLOAD_CALLS = 13, // UPLOAD_CALLS FIREBASE = 14, // FIREBASE CLICK_TO_CALL = 15, // CLICK_TO_CALL SALESFORCE = 16, // SALESFORCE STORE_SALES_CRM = 17, // STORE_SALES_CRM STORE_SALES_PAYMENT_NETWORK = 18, // STORE_SALES_PAYMENT_NETWORK GOOGLE_PLAY = 19, // GOOGLE_PLAY THIRD_PARTY_APP_ANALYTICS = 20, // THIRD_PARTY_APP_ANALYTICS GOOGLE_ATTRIBUTION = 21, // GOOGLE_ATTRIBUTION STORE_SALES_DIRECT_UPLOAD = 23, // STORE_SALES_DIRECT_UPLOAD STORE_SALES = 24, // STORE_SALES SEARCH_ADS_360 = 25, // SEARCH_ADS_360 GOOGLE_HOSTED = 27, // GOOGLE_HOSTED FLOODLIGHT = 29, // FLOODLIGHT ANALYTICS_SEARCH_ADS_360 = 31, // ANALYTICS_SEARCH_ADS_360 FIREBASE_SEARCH_ADS_360 = 33, // FIREBASE_SEARCH_ADS_360 } /** * @name HotelPriceBucketEnum.HotelPriceBucket * @link https://developers.google.com/google-ads/api/reference/rpc/v9/HotelPriceBucketEnum.HotelPriceBucket */ export enum HotelPriceBucket { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN LOWEST_UNIQUE = 2, // LOWEST_UNIQUE LOWEST_TIED = 3, // LOWEST_TIED NOT_LOWEST = 4, // NOT_LOWEST ONLY_PARTNER_SHOWN = 5, // ONLY_PARTNER_SHOWN } /** * @name HotelRateTypeEnum.HotelRateType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/HotelRateTypeEnum.HotelRateType */ export enum HotelRateType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN UNAVAILABLE = 2, // UNAVAILABLE PUBLIC_RATE = 3, // PUBLIC_RATE QUALIFIED_RATE = 4, // QUALIFIED_RATE PRIVATE_RATE = 5, // PRIVATE_RATE } /** * @name PlaceholderTypeEnum.PlaceholderType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PlaceholderTypeEnum.PlaceholderType */ export enum PlaceholderType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN SITELINK = 2, // SITELINK CALL = 3, // CALL APP = 4, // APP LOCATION = 5, // LOCATION AFFILIATE_LOCATION = 6, // AFFILIATE_LOCATION CALLOUT = 7, // CALLOUT STRUCTURED_SNIPPET = 8, // STRUCTURED_SNIPPET MESSAGE = 9, // MESSAGE PRICE = 10, // PRICE PROMOTION = 11, // PROMOTION AD_CUSTOMIZER = 12, // AD_CUSTOMIZER DYNAMIC_EDUCATION = 13, // DYNAMIC_EDUCATION DYNAMIC_FLIGHT = 14, // DYNAMIC_FLIGHT DYNAMIC_CUSTOM = 15, // DYNAMIC_CUSTOM DYNAMIC_HOTEL = 16, // DYNAMIC_HOTEL DYNAMIC_REAL_ESTATE = 17, // DYNAMIC_REAL_ESTATE DYNAMIC_TRAVEL = 18, // DYNAMIC_TRAVEL DYNAMIC_LOCAL = 19, // DYNAMIC_LOCAL DYNAMIC_JOB = 20, // DYNAMIC_JOB IMAGE = 21, // IMAGE } /** * @name RecommendationTypeEnum.RecommendationType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/RecommendationTypeEnum.RecommendationType */ export enum RecommendationType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CAMPAIGN_BUDGET = 2, // CAMPAIGN_BUDGET KEYWORD = 3, // KEYWORD TEXT_AD = 4, // TEXT_AD TARGET_CPA_OPT_IN = 5, // TARGET_CPA_OPT_IN MAXIMIZE_CONVERSIONS_OPT_IN = 6, // MAXIMIZE_CONVERSIONS_OPT_IN ENHANCED_CPC_OPT_IN = 7, // ENHANCED_CPC_OPT_IN SEARCH_PARTNERS_OPT_IN = 8, // SEARCH_PARTNERS_OPT_IN MAXIMIZE_CLICKS_OPT_IN = 9, // MAXIMIZE_CLICKS_OPT_IN OPTIMIZE_AD_ROTATION = 10, // OPTIMIZE_AD_ROTATION CALLOUT_EXTENSION = 11, // CALLOUT_EXTENSION SITELINK_EXTENSION = 12, // SITELINK_EXTENSION CALL_EXTENSION = 13, // CALL_EXTENSION KEYWORD_MATCH_TYPE = 14, // KEYWORD_MATCH_TYPE MOVE_UNUSED_BUDGET = 15, // MOVE_UNUSED_BUDGET FORECASTING_CAMPAIGN_BUDGET = 16, // FORECASTING_CAMPAIGN_BUDGET TARGET_ROAS_OPT_IN = 17, // TARGET_ROAS_OPT_IN RESPONSIVE_SEARCH_AD = 18, // RESPONSIVE_SEARCH_AD MARGINAL_ROI_CAMPAIGN_BUDGET = 19, // MARGINAL_ROI_CAMPAIGN_BUDGET } /** * @name SearchEngineResultsPageTypeEnum.SearchEngineResultsPageType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/SearchEngineResultsPageTypeEnum.SearchEngineResultsPageType */ export enum SearchEngineResultsPageType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ADS_ONLY = 2, // ADS_ONLY ORGANIC_ONLY = 3, // ORGANIC_ONLY ADS_AND_ORGANIC = 4, // ADS_AND_ORGANIC } /** * @name SearchTermMatchTypeEnum.SearchTermMatchType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/SearchTermMatchTypeEnum.SearchTermMatchType */ export enum SearchTermMatchType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN BROAD = 2, // BROAD EXACT = 3, // EXACT PHRASE = 4, // PHRASE NEAR_EXACT = 5, // NEAR_EXACT NEAR_PHRASE = 6, // NEAR_PHRASE } /** * @name SlotEnum.Slot * @link https://developers.google.com/google-ads/api/reference/rpc/v9/SlotEnum.Slot */ export enum Slot { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN SEARCH_SIDE = 2, // SEARCH_SIDE SEARCH_TOP = 3, // SEARCH_TOP SEARCH_OTHER = 4, // SEARCH_OTHER CONTENT = 5, // CONTENT SEARCH_PARTNER_TOP = 6, // SEARCH_PARTNER_TOP SEARCH_PARTNER_OTHER = 7, // SEARCH_PARTNER_OTHER MIXED = 8, // MIXED } /** * @name TrackingCodePageFormatEnum.TrackingCodePageFormat * @link https://developers.google.com/google-ads/api/reference/rpc/v9/TrackingCodePageFormatEnum.TrackingCodePageFormat */ export enum TrackingCodePageFormat { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN HTML = 2, // HTML AMP = 3, // AMP } /** * @name TrackingCodeTypeEnum.TrackingCodeType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/TrackingCodeTypeEnum.TrackingCodeType */ export enum TrackingCodeType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN WEBPAGE = 2, // WEBPAGE WEBPAGE_ONCLICK = 3, // WEBPAGE_ONCLICK CLICK_TO_CALL = 4, // CLICK_TO_CALL WEBSITE_CALL = 5, // WEBSITE_CALL } /** * @name TargetingDimensionEnum.TargetingDimension * @link https://developers.google.com/google-ads/api/reference/rpc/v9/TargetingDimensionEnum.TargetingDimension */ export enum TargetingDimension { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN KEYWORD = 2, // KEYWORD AUDIENCE = 3, // AUDIENCE TOPIC = 4, // TOPIC GENDER = 5, // GENDER AGE_RANGE = 6, // AGE_RANGE PLACEMENT = 7, // PLACEMENT PARENTAL_STATUS = 8, // PARENTAL_STATUS INCOME_RANGE = 9, // INCOME_RANGE } /** * @name CustomerMatchUploadKeyTypeEnum.CustomerMatchUploadKeyType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CustomerMatchUploadKeyTypeEnum.CustomerMatchUploadKeyType */ export enum CustomerMatchUploadKeyType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CONTACT_INFO = 2, // CONTACT_INFO CRM_ID = 3, // CRM_ID MOBILE_ADVERTISING_ID = 4, // MOBILE_ADVERTISING_ID } /** * @name UserListCombinedRuleOperatorEnum.UserListCombinedRuleOperator * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserListCombinedRuleOperatorEnum.UserListCombinedRuleOperator */ export enum UserListCombinedRuleOperator { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN AND = 2, // AND AND_NOT = 3, // AND_NOT } /** * @name UserListCrmDataSourceTypeEnum.UserListCrmDataSourceType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserListCrmDataSourceTypeEnum.UserListCrmDataSourceType */ export enum UserListCrmDataSourceType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN FIRST_PARTY = 2, // FIRST_PARTY THIRD_PARTY_CREDIT_BUREAU = 3, // THIRD_PARTY_CREDIT_BUREAU THIRD_PARTY_VOTER_FILE = 4, // THIRD_PARTY_VOTER_FILE } /** * @name UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator */ export enum UserListDateRuleItemOperator { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN EQUALS = 2, // EQUALS NOT_EQUALS = 3, // NOT_EQUALS BEFORE = 4, // BEFORE AFTER = 5, // AFTER } /** * @name UserListLogicalRuleOperatorEnum.UserListLogicalRuleOperator * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserListLogicalRuleOperatorEnum.UserListLogicalRuleOperator */ export enum UserListLogicalRuleOperator { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ALL = 2, // ALL ANY = 3, // ANY NONE = 4, // NONE } /** * @name UserListNumberRuleItemOperatorEnum.UserListNumberRuleItemOperator * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserListNumberRuleItemOperatorEnum.UserListNumberRuleItemOperator */ export enum UserListNumberRuleItemOperator { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN GREATER_THAN = 2, // GREATER_THAN GREATER_THAN_OR_EQUAL = 3, // GREATER_THAN_OR_EQUAL EQUALS = 4, // EQUALS NOT_EQUALS = 5, // NOT_EQUALS LESS_THAN = 6, // LESS_THAN LESS_THAN_OR_EQUAL = 7, // LESS_THAN_OR_EQUAL } /** * @name UserListPrepopulationStatusEnum.UserListPrepopulationStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserListPrepopulationStatusEnum.UserListPrepopulationStatus */ export enum UserListPrepopulationStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN REQUESTED = 2, // REQUESTED FINISHED = 3, // FINISHED FAILED = 4, // FAILED } /** * @name UserListRuleTypeEnum.UserListRuleType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserListRuleTypeEnum.UserListRuleType */ export enum UserListRuleType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN AND_OF_ORS = 2, // AND_OF_ORS OR_OF_ANDS = 3, // OR_OF_ANDS } /** * @name UserListStringRuleItemOperatorEnum.UserListStringRuleItemOperator * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserListStringRuleItemOperatorEnum.UserListStringRuleItemOperator */ export enum UserListStringRuleItemOperator { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CONTAINS = 2, // CONTAINS EQUALS = 3, // EQUALS STARTS_WITH = 4, // STARTS_WITH ENDS_WITH = 5, // ENDS_WITH NOT_EQUALS = 6, // NOT_EQUALS NOT_CONTAINS = 7, // NOT_CONTAINS NOT_STARTS_WITH = 8, // NOT_STARTS_WITH NOT_ENDS_WITH = 9, // NOT_ENDS_WITH } /** * @name AccessInvitationStatusEnum.AccessInvitationStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AccessInvitationStatusEnum.AccessInvitationStatus */ export enum AccessInvitationStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PENDING = 2, // PENDING DECLINED = 3, // DECLINED EXPIRED = 4, // EXPIRED } /** * @name AccessReasonEnum.AccessReason * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AccessReasonEnum.AccessReason */ export enum AccessReason { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN OWNED = 2, // OWNED SHARED = 3, // SHARED LICENSED = 4, // LICENSED SUBSCRIBED = 5, // SUBSCRIBED AFFILIATED = 6, // AFFILIATED } /** * @name AccessRoleEnum.AccessRole * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AccessRoleEnum.AccessRole */ export enum AccessRole { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ADMIN = 2, // ADMIN STANDARD = 3, // STANDARD READ_ONLY = 4, // READ_ONLY EMAIL_ONLY = 5, // EMAIL_ONLY } /** * @name AccountBudgetProposalStatusEnum.AccountBudgetProposalStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AccountBudgetProposalStatusEnum.AccountBudgetProposalStatus */ export enum AccountBudgetProposalStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PENDING = 2, // PENDING APPROVED_HELD = 3, // APPROVED_HELD APPROVED = 4, // APPROVED CANCELLED = 5, // CANCELLED REJECTED = 6, // REJECTED } /** * @name AccountBudgetProposalTypeEnum.AccountBudgetProposalType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AccountBudgetProposalTypeEnum.AccountBudgetProposalType */ export enum AccountBudgetProposalType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CREATE = 2, // CREATE UPDATE = 3, // UPDATE END = 4, // END REMOVE = 5, // REMOVE } /** * @name AccountBudgetStatusEnum.AccountBudgetStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AccountBudgetStatusEnum.AccountBudgetStatus */ export enum AccountBudgetStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PENDING = 2, // PENDING APPROVED = 3, // APPROVED CANCELLED = 4, // CANCELLED } /** * @name AccountLinkStatusEnum.AccountLinkStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AccountLinkStatusEnum.AccountLinkStatus */ export enum AccountLinkStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED REQUESTED = 4, // REQUESTED PENDING_APPROVAL = 5, // PENDING_APPROVAL REJECTED = 6, // REJECTED REVOKED = 7, // REVOKED } /** * @name AdCustomizerPlaceholderFieldEnum.AdCustomizerPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AdCustomizerPlaceholderFieldEnum.AdCustomizerPlaceholderField */ export enum AdCustomizerPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN INTEGER = 2, // INTEGER PRICE = 3, // PRICE DATE = 4, // DATE STRING = 5, // STRING } /** * @name AdGroupAdRotationModeEnum.AdGroupAdRotationMode * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AdGroupAdRotationModeEnum.AdGroupAdRotationMode */ export enum AdGroupAdRotationMode { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN OPTIMIZE = 2, // OPTIMIZE ROTATE_FOREVER = 3, // ROTATE_FOREVER } /** * @name AdGroupAdStatusEnum.AdGroupAdStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AdGroupAdStatusEnum.AdGroupAdStatus */ export enum AdGroupAdStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED PAUSED = 3, // PAUSED REMOVED = 4, // REMOVED } /** * @name AdGroupCriterionApprovalStatusEnum.AdGroupCriterionApprovalStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AdGroupCriterionApprovalStatusEnum.AdGroupCriterionApprovalStatus */ export enum AdGroupCriterionApprovalStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN APPROVED = 2, // APPROVED DISAPPROVED = 3, // DISAPPROVED PENDING_REVIEW = 4, // PENDING_REVIEW UNDER_REVIEW = 5, // UNDER_REVIEW } /** * @name AdGroupCriterionStatusEnum.AdGroupCriterionStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AdGroupCriterionStatusEnum.AdGroupCriterionStatus */ export enum AdGroupCriterionStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED PAUSED = 3, // PAUSED REMOVED = 4, // REMOVED } /** * @name AdGroupStatusEnum.AdGroupStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AdGroupStatusEnum.AdGroupStatus */ export enum AdGroupStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED PAUSED = 3, // PAUSED REMOVED = 4, // REMOVED } /** * @name AdGroupTypeEnum.AdGroupType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AdGroupTypeEnum.AdGroupType */ export enum AdGroupType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN SEARCH_STANDARD = 2, // SEARCH_STANDARD DISPLAY_STANDARD = 3, // DISPLAY_STANDARD SHOPPING_PRODUCT_ADS = 4, // SHOPPING_PRODUCT_ADS HOTEL_ADS = 6, // HOTEL_ADS SHOPPING_SMART_ADS = 7, // SHOPPING_SMART_ADS VIDEO_BUMPER = 8, // VIDEO_BUMPER VIDEO_TRUE_VIEW_IN_STREAM = 9, // VIDEO_TRUE_VIEW_IN_STREAM VIDEO_TRUE_VIEW_IN_DISPLAY = 10, // VIDEO_TRUE_VIEW_IN_DISPLAY VIDEO_NON_SKIPPABLE_IN_STREAM = 11, // VIDEO_NON_SKIPPABLE_IN_STREAM VIDEO_OUTSTREAM = 12, // VIDEO_OUTSTREAM SEARCH_DYNAMIC_ADS = 13, // SEARCH_DYNAMIC_ADS SHOPPING_COMPARISON_LISTING_ADS = 14, // SHOPPING_COMPARISON_LISTING_ADS PROMOTED_HOTEL_ADS = 15, // PROMOTED_HOTEL_ADS VIDEO_RESPONSIVE = 16, // VIDEO_RESPONSIVE VIDEO_EFFICIENT_REACH = 17, // VIDEO_EFFICIENT_REACH SMART_CAMPAIGN_ADS = 18, // SMART_CAMPAIGN_ADS } /** * @name AdServingOptimizationStatusEnum.AdServingOptimizationStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AdServingOptimizationStatusEnum.AdServingOptimizationStatus */ export enum AdServingOptimizationStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN OPTIMIZE = 2, // OPTIMIZE CONVERSION_OPTIMIZE = 3, // CONVERSION_OPTIMIZE ROTATE = 4, // ROTATE ROTATE_INDEFINITELY = 5, // ROTATE_INDEFINITELY UNAVAILABLE = 6, // UNAVAILABLE } /** * @name AdStrengthEnum.AdStrength * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AdStrengthEnum.AdStrength */ export enum AdStrength { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PENDING = 2, // PENDING NO_ADS = 3, // NO_ADS POOR = 4, // POOR AVERAGE = 5, // AVERAGE GOOD = 6, // GOOD EXCELLENT = 7, // EXCELLENT } /** * @name AdTypeEnum.AdType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AdTypeEnum.AdType */ export enum AdType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN TEXT_AD = 2, // TEXT_AD EXPANDED_TEXT_AD = 3, // EXPANDED_TEXT_AD EXPANDED_DYNAMIC_SEARCH_AD = 7, // EXPANDED_DYNAMIC_SEARCH_AD HOTEL_AD = 8, // HOTEL_AD SHOPPING_SMART_AD = 9, // SHOPPING_SMART_AD SHOPPING_PRODUCT_AD = 10, // SHOPPING_PRODUCT_AD VIDEO_AD = 12, // VIDEO_AD GMAIL_AD = 13, // GMAIL_AD IMAGE_AD = 14, // IMAGE_AD RESPONSIVE_SEARCH_AD = 15, // RESPONSIVE_SEARCH_AD LEGACY_RESPONSIVE_DISPLAY_AD = 16, // LEGACY_RESPONSIVE_DISPLAY_AD APP_AD = 17, // APP_AD LEGACY_APP_INSTALL_AD = 18, // LEGACY_APP_INSTALL_AD RESPONSIVE_DISPLAY_AD = 19, // RESPONSIVE_DISPLAY_AD LOCAL_AD = 20, // LOCAL_AD HTML5_UPLOAD_AD = 21, // HTML5_UPLOAD_AD DYNAMIC_HTML5_AD = 22, // DYNAMIC_HTML5_AD APP_ENGAGEMENT_AD = 23, // APP_ENGAGEMENT_AD SHOPPING_COMPARISON_LISTING_AD = 24, // SHOPPING_COMPARISON_LISTING_AD VIDEO_BUMPER_AD = 25, // VIDEO_BUMPER_AD VIDEO_NON_SKIPPABLE_IN_STREAM_AD = 26, // VIDEO_NON_SKIPPABLE_IN_STREAM_AD VIDEO_OUTSTREAM_AD = 27, // VIDEO_OUTSTREAM_AD VIDEO_TRUEVIEW_DISCOVERY_AD = 28, // VIDEO_TRUEVIEW_DISCOVERY_AD VIDEO_TRUEVIEW_IN_STREAM_AD = 29, // VIDEO_TRUEVIEW_IN_STREAM_AD VIDEO_RESPONSIVE_AD = 30, // VIDEO_RESPONSIVE_AD SMART_CAMPAIGN_AD = 31, // SMART_CAMPAIGN_AD CALL_AD = 32, // CALL_AD APP_PRE_REGISTRATION_AD = 33, // APP_PRE_REGISTRATION_AD } /** * @name AffiliateLocationFeedRelationshipTypeEnum.AffiliateLocationFeedRelationshipType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AffiliateLocationFeedRelationshipTypeEnum.AffiliateLocationFeedRelationshipType */ export enum AffiliateLocationFeedRelationshipType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN GENERAL_RETAILER = 2, // GENERAL_RETAILER } /** * @name AffiliateLocationPlaceholderFieldEnum.AffiliateLocationPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AffiliateLocationPlaceholderFieldEnum.AffiliateLocationPlaceholderField */ export enum AffiliateLocationPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN BUSINESS_NAME = 2, // BUSINESS_NAME ADDRESS_LINE_1 = 3, // ADDRESS_LINE_1 ADDRESS_LINE_2 = 4, // ADDRESS_LINE_2 CITY = 5, // CITY PROVINCE = 6, // PROVINCE POSTAL_CODE = 7, // POSTAL_CODE COUNTRY_CODE = 8, // COUNTRY_CODE PHONE_NUMBER = 9, // PHONE_NUMBER LANGUAGE_CODE = 10, // LANGUAGE_CODE CHAIN_ID = 11, // CHAIN_ID CHAIN_NAME = 12, // CHAIN_NAME } /** * @name AppCampaignAppStoreEnum.AppCampaignAppStore * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AppCampaignAppStoreEnum.AppCampaignAppStore */ export enum AppCampaignAppStore { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN APPLE_APP_STORE = 2, // APPLE_APP_STORE GOOGLE_APP_STORE = 3, // GOOGLE_APP_STORE } /** * @name AppCampaignBiddingStrategyGoalTypeEnum.AppCampaignBiddingStrategyGoalType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AppCampaignBiddingStrategyGoalTypeEnum.AppCampaignBiddingStrategyGoalType */ export enum AppCampaignBiddingStrategyGoalType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN OPTIMIZE_INSTALLS_TARGET_INSTALL_COST = 2, // OPTIMIZE_INSTALLS_TARGET_INSTALL_COST OPTIMIZE_IN_APP_CONVERSIONS_TARGET_INSTALL_COST = 3, // OPTIMIZE_IN_APP_CONVERSIONS_TARGET_INSTALL_COST OPTIMIZE_IN_APP_CONVERSIONS_TARGET_CONVERSION_COST = 4, // OPTIMIZE_IN_APP_CONVERSIONS_TARGET_CONVERSION_COST OPTIMIZE_RETURN_ON_ADVERTISING_SPEND = 5, // OPTIMIZE_RETURN_ON_ADVERTISING_SPEND OPTIMIZE_PRE_REGISTRATION_CONVERSION_VOLUME = 6, // OPTIMIZE_PRE_REGISTRATION_CONVERSION_VOLUME OPTIMIZE_INSTALLS_WITHOUT_TARGET_INSTALL_COST = 7, // OPTIMIZE_INSTALLS_WITHOUT_TARGET_INSTALL_COST } /** * @name AppPlaceholderFieldEnum.AppPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AppPlaceholderFieldEnum.AppPlaceholderField */ export enum AppPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN STORE = 2, // STORE ID = 3, // ID LINK_TEXT = 4, // LINK_TEXT URL = 5, // URL FINAL_URLS = 6, // FINAL_URLS FINAL_MOBILE_URLS = 7, // FINAL_MOBILE_URLS TRACKING_URL = 8, // TRACKING_URL FINAL_URL_SUFFIX = 9, // FINAL_URL_SUFFIX } /** * @name AssetFieldTypeEnum.AssetFieldType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AssetFieldTypeEnum.AssetFieldType */ export enum AssetFieldType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN HEADLINE = 2, // HEADLINE DESCRIPTION = 3, // DESCRIPTION MANDATORY_AD_TEXT = 4, // MANDATORY_AD_TEXT MARKETING_IMAGE = 5, // MARKETING_IMAGE MEDIA_BUNDLE = 6, // MEDIA_BUNDLE YOUTUBE_VIDEO = 7, // YOUTUBE_VIDEO BOOK_ON_GOOGLE = 8, // BOOK_ON_GOOGLE LEAD_FORM = 9, // LEAD_FORM PROMOTION = 10, // PROMOTION CALLOUT = 11, // CALLOUT STRUCTURED_SNIPPET = 12, // STRUCTURED_SNIPPET SITELINK = 13, // SITELINK MOBILE_APP = 14, // MOBILE_APP HOTEL_CALLOUT = 15, // HOTEL_CALLOUT CALL = 16, // CALL PRICE = 24, // PRICE LONG_HEADLINE = 17, // LONG_HEADLINE BUSINESS_NAME = 18, // BUSINESS_NAME SQUARE_MARKETING_IMAGE = 19, // SQUARE_MARKETING_IMAGE PORTRAIT_MARKETING_IMAGE = 20, // PORTRAIT_MARKETING_IMAGE LOGO = 21, // LOGO LANDSCAPE_LOGO = 22, // LANDSCAPE_LOGO VIDEO = 23, // VIDEO CALL_TO_ACTION_SELECTION = 25, // CALL_TO_ACTION_SELECTION } /** * @name AssetGroupStatusEnum.AssetGroupStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AssetGroupStatusEnum.AssetGroupStatus */ export enum AssetGroupStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED PAUSED = 3, // PAUSED REMOVED = 4, // REMOVED } /** * @name AssetLinkStatusEnum.AssetLinkStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AssetLinkStatusEnum.AssetLinkStatus */ export enum AssetLinkStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED PAUSED = 4, // PAUSED } /** * @name AssetSetAssetStatusEnum.AssetSetAssetStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AssetSetAssetStatusEnum.AssetSetAssetStatus */ export enum AssetSetAssetStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name AssetSetLinkStatusEnum.AssetSetLinkStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AssetSetLinkStatusEnum.AssetSetLinkStatus */ export enum AssetSetLinkStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name AssetSetStatusEnum.AssetSetStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AssetSetStatusEnum.AssetSetStatus */ export enum AssetSetStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name AssetSetTypeEnum.AssetSetType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AssetSetTypeEnum.AssetSetType */ export enum AssetSetType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PAGE_FEED = 2, // PAGE_FEED DYNAMIC_EDUCATION = 3, // DYNAMIC_EDUCATION MERCHANT_CENTER_FEED = 4, // MERCHANT_CENTER_FEED } /** * @name AssetTypeEnum.AssetType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AssetTypeEnum.AssetType */ export enum AssetType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN YOUTUBE_VIDEO = 2, // YOUTUBE_VIDEO MEDIA_BUNDLE = 3, // MEDIA_BUNDLE IMAGE = 4, // IMAGE TEXT = 5, // TEXT LEAD_FORM = 6, // LEAD_FORM BOOK_ON_GOOGLE = 7, // BOOK_ON_GOOGLE PROMOTION = 8, // PROMOTION CALLOUT = 9, // CALLOUT STRUCTURED_SNIPPET = 10, // STRUCTURED_SNIPPET SITELINK = 11, // SITELINK PAGE_FEED = 12, // PAGE_FEED DYNAMIC_EDUCATION = 13, // DYNAMIC_EDUCATION MOBILE_APP = 14, // MOBILE_APP HOTEL_CALLOUT = 15, // HOTEL_CALLOUT CALL = 16, // CALL PRICE = 17, // PRICE CALL_TO_ACTION = 18, // CALL_TO_ACTION } /** * @name AttributionModelEnum.AttributionModel * @link https://developers.google.com/google-ads/api/reference/rpc/v9/AttributionModelEnum.AttributionModel */ export enum AttributionModel { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN EXTERNAL = 100, // EXTERNAL GOOGLE_ADS_LAST_CLICK = 101, // GOOGLE_ADS_LAST_CLICK GOOGLE_SEARCH_ATTRIBUTION_FIRST_CLICK = 102, // GOOGLE_SEARCH_ATTRIBUTION_FIRST_CLICK GOOGLE_SEARCH_ATTRIBUTION_LINEAR = 103, // GOOGLE_SEARCH_ATTRIBUTION_LINEAR GOOGLE_SEARCH_ATTRIBUTION_TIME_DECAY = 104, // GOOGLE_SEARCH_ATTRIBUTION_TIME_DECAY GOOGLE_SEARCH_ATTRIBUTION_POSITION_BASED = 105, // GOOGLE_SEARCH_ATTRIBUTION_POSITION_BASED GOOGLE_SEARCH_ATTRIBUTION_DATA_DRIVEN = 106, // GOOGLE_SEARCH_ATTRIBUTION_DATA_DRIVEN } /** * @name BatchJobStatusEnum.BatchJobStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/BatchJobStatusEnum.BatchJobStatus */ export enum BatchJobStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PENDING = 2, // PENDING RUNNING = 3, // RUNNING DONE = 4, // DONE } /** * @name BidModifierSourceEnum.BidModifierSource * @link https://developers.google.com/google-ads/api/reference/rpc/v9/BidModifierSourceEnum.BidModifierSource */ export enum BidModifierSource { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CAMPAIGN = 2, // CAMPAIGN AD_GROUP = 3, // AD_GROUP } /** * @name BiddingSourceEnum.BiddingSource * @link https://developers.google.com/google-ads/api/reference/rpc/v9/BiddingSourceEnum.BiddingSource */ export enum BiddingSource { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CAMPAIGN_BIDDING_STRATEGY = 5, // CAMPAIGN_BIDDING_STRATEGY AD_GROUP = 6, // AD_GROUP AD_GROUP_CRITERION = 7, // AD_GROUP_CRITERION } /** * @name BiddingStrategyStatusEnum.BiddingStrategyStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/BiddingStrategyStatusEnum.BiddingStrategyStatus */ export enum BiddingStrategyStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 4, // REMOVED } /** * @name BiddingStrategyTypeEnum.BiddingStrategyType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/BiddingStrategyTypeEnum.BiddingStrategyType */ export enum BiddingStrategyType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN COMMISSION = 16, // COMMISSION ENHANCED_CPC = 2, // ENHANCED_CPC INVALID = 17, // INVALID MANUAL_CPC = 3, // MANUAL_CPC MANUAL_CPM = 4, // MANUAL_CPM MANUAL_CPV = 13, // MANUAL_CPV MAXIMIZE_CONVERSIONS = 10, // MAXIMIZE_CONVERSIONS MAXIMIZE_CONVERSION_VALUE = 11, // MAXIMIZE_CONVERSION_VALUE PAGE_ONE_PROMOTED = 5, // PAGE_ONE_PROMOTED PERCENT_CPC = 12, // PERCENT_CPC TARGET_CPA = 6, // TARGET_CPA TARGET_CPM = 14, // TARGET_CPM TARGET_IMPRESSION_SHARE = 15, // TARGET_IMPRESSION_SHARE TARGET_OUTRANK_SHARE = 7, // TARGET_OUTRANK_SHARE TARGET_ROAS = 8, // TARGET_ROAS TARGET_SPEND = 9, // TARGET_SPEND } /** * @name BillingSetupStatusEnum.BillingSetupStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/BillingSetupStatusEnum.BillingSetupStatus */ export enum BillingSetupStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PENDING = 2, // PENDING APPROVED_HELD = 3, // APPROVED_HELD APPROVED = 4, // APPROVED CANCELLED = 5, // CANCELLED } /** * @name BrandSafetySuitabilityEnum.BrandSafetySuitability * @link https://developers.google.com/google-ads/api/reference/rpc/v9/BrandSafetySuitabilityEnum.BrandSafetySuitability */ export enum BrandSafetySuitability { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN EXPANDED_INVENTORY = 2, // EXPANDED_INVENTORY STANDARD_INVENTORY = 3, // STANDARD_INVENTORY LIMITED_INVENTORY = 4, // LIMITED_INVENTORY } /** * @name BudgetDeliveryMethodEnum.BudgetDeliveryMethod * @link https://developers.google.com/google-ads/api/reference/rpc/v9/BudgetDeliveryMethodEnum.BudgetDeliveryMethod */ export enum BudgetDeliveryMethod { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN STANDARD = 2, // STANDARD ACCELERATED = 3, // ACCELERATED } /** * @name BudgetPeriodEnum.BudgetPeriod * @link https://developers.google.com/google-ads/api/reference/rpc/v9/BudgetPeriodEnum.BudgetPeriod */ export enum BudgetPeriod { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN DAILY = 2, // DAILY CUSTOM_PERIOD = 5, // CUSTOM_PERIOD } /** * @name BudgetStatusEnum.BudgetStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/BudgetStatusEnum.BudgetStatus */ export enum BudgetStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name BudgetTypeEnum.BudgetType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/BudgetTypeEnum.BudgetType */ export enum BudgetType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN STANDARD = 2, // STANDARD FIXED_CPA = 4, // FIXED_CPA SMART_CAMPAIGN = 5, // SMART_CAMPAIGN } /** * @name CallPlaceholderFieldEnum.CallPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CallPlaceholderFieldEnum.CallPlaceholderField */ export enum CallPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PHONE_NUMBER = 2, // PHONE_NUMBER COUNTRY_CODE = 3, // COUNTRY_CODE TRACKED = 4, // TRACKED CONVERSION_TYPE_ID = 5, // CONVERSION_TYPE_ID CONVERSION_REPORTING_STATE = 6, // CONVERSION_REPORTING_STATE } /** * @name CallTrackingDisplayLocationEnum.CallTrackingDisplayLocation * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CallTrackingDisplayLocationEnum.CallTrackingDisplayLocation */ export enum CallTrackingDisplayLocation { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN AD = 2, // AD LANDING_PAGE = 3, // LANDING_PAGE } /** * @name CallTypeEnum.CallType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CallTypeEnum.CallType */ export enum CallType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN MANUALLY_DIALED = 2, // MANUALLY_DIALED HIGH_END_MOBILE_SEARCH = 3, // HIGH_END_MOBILE_SEARCH } /** * @name CalloutPlaceholderFieldEnum.CalloutPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CalloutPlaceholderFieldEnum.CalloutPlaceholderField */ export enum CalloutPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CALLOUT_TEXT = 2, // CALLOUT_TEXT } /** * @name CampaignCriterionStatusEnum.CampaignCriterionStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CampaignCriterionStatusEnum.CampaignCriterionStatus */ export enum CampaignCriterionStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED PAUSED = 3, // PAUSED REMOVED = 4, // REMOVED } /** * @name CampaignDraftStatusEnum.CampaignDraftStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CampaignDraftStatusEnum.CampaignDraftStatus */ export enum CampaignDraftStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PROPOSED = 2, // PROPOSED REMOVED = 3, // REMOVED PROMOTING = 5, // PROMOTING PROMOTED = 4, // PROMOTED PROMOTE_FAILED = 6, // PROMOTE_FAILED } /** * @name CampaignExperimentStatusEnum.CampaignExperimentStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CampaignExperimentStatusEnum.CampaignExperimentStatus */ export enum CampaignExperimentStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN INITIALIZING = 2, // INITIALIZING INITIALIZATION_FAILED = 8, // INITIALIZATION_FAILED ENABLED = 3, // ENABLED GRADUATED = 4, // GRADUATED REMOVED = 5, // REMOVED PROMOTING = 6, // PROMOTING PROMOTION_FAILED = 9, // PROMOTION_FAILED PROMOTED = 7, // PROMOTED ENDED_MANUALLY = 10, // ENDED_MANUALLY } /** * @name CampaignExperimentTrafficSplitTypeEnum.CampaignExperimentTrafficSplitType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CampaignExperimentTrafficSplitTypeEnum.CampaignExperimentTrafficSplitType */ export enum CampaignExperimentTrafficSplitType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN RANDOM_QUERY = 2, // RANDOM_QUERY COOKIE = 3, // COOKIE } /** * @name CampaignExperimentTypeEnum.CampaignExperimentType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CampaignExperimentTypeEnum.CampaignExperimentType */ export enum CampaignExperimentType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN BASE = 2, // BASE DRAFT = 3, // DRAFT EXPERIMENT = 4, // EXPERIMENT } /** * @name CampaignServingStatusEnum.CampaignServingStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CampaignServingStatusEnum.CampaignServingStatus */ export enum CampaignServingStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN SERVING = 2, // SERVING NONE = 3, // NONE ENDED = 4, // ENDED PENDING = 5, // PENDING SUSPENDED = 6, // SUSPENDED } /** * @name CampaignSharedSetStatusEnum.CampaignSharedSetStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CampaignSharedSetStatusEnum.CampaignSharedSetStatus */ export enum CampaignSharedSetStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name CampaignStatusEnum.CampaignStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CampaignStatusEnum.CampaignStatus */ export enum CampaignStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED PAUSED = 3, // PAUSED REMOVED = 4, // REMOVED } /** * @name ChangeClientTypeEnum.ChangeClientType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ChangeClientTypeEnum.ChangeClientType */ export enum ChangeClientType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN GOOGLE_ADS_WEB_CLIENT = 2, // GOOGLE_ADS_WEB_CLIENT GOOGLE_ADS_AUTOMATED_RULE = 3, // GOOGLE_ADS_AUTOMATED_RULE GOOGLE_ADS_SCRIPTS = 4, // GOOGLE_ADS_SCRIPTS GOOGLE_ADS_BULK_UPLOAD = 5, // GOOGLE_ADS_BULK_UPLOAD GOOGLE_ADS_API = 6, // GOOGLE_ADS_API GOOGLE_ADS_EDITOR = 7, // GOOGLE_ADS_EDITOR GOOGLE_ADS_MOBILE_APP = 8, // GOOGLE_ADS_MOBILE_APP GOOGLE_ADS_RECOMMENDATIONS = 9, // GOOGLE_ADS_RECOMMENDATIONS SEARCH_ADS_360_SYNC = 10, // SEARCH_ADS_360_SYNC SEARCH_ADS_360_POST = 11, // SEARCH_ADS_360_POST INTERNAL_TOOL = 12, // INTERNAL_TOOL OTHER = 13, // OTHER } /** * @name ChangeEventResourceTypeEnum.ChangeEventResourceType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ChangeEventResourceTypeEnum.ChangeEventResourceType */ export enum ChangeEventResourceType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN AD = 2, // AD AD_GROUP = 3, // AD_GROUP AD_GROUP_CRITERION = 4, // AD_GROUP_CRITERION CAMPAIGN = 5, // CAMPAIGN CAMPAIGN_BUDGET = 6, // CAMPAIGN_BUDGET AD_GROUP_BID_MODIFIER = 7, // AD_GROUP_BID_MODIFIER CAMPAIGN_CRITERION = 8, // CAMPAIGN_CRITERION FEED = 9, // FEED FEED_ITEM = 10, // FEED_ITEM CAMPAIGN_FEED = 11, // CAMPAIGN_FEED AD_GROUP_FEED = 12, // AD_GROUP_FEED AD_GROUP_AD = 13, // AD_GROUP_AD ASSET = 14, // ASSET CUSTOMER_ASSET = 15, // CUSTOMER_ASSET CAMPAIGN_ASSET = 16, // CAMPAIGN_ASSET AD_GROUP_ASSET = 17, // AD_GROUP_ASSET } /** * @name ChangeStatusOperationEnum.ChangeStatusOperation * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ChangeStatusOperationEnum.ChangeStatusOperation */ export enum ChangeStatusOperation { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ADDED = 2, // ADDED CHANGED = 3, // CHANGED REMOVED = 4, // REMOVED } /** * @name ChangeStatusResourceTypeEnum.ChangeStatusResourceType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ChangeStatusResourceTypeEnum.ChangeStatusResourceType */ export enum ChangeStatusResourceType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN AD_GROUP = 3, // AD_GROUP AD_GROUP_AD = 4, // AD_GROUP_AD AD_GROUP_CRITERION = 5, // AD_GROUP_CRITERION CAMPAIGN = 6, // CAMPAIGN CAMPAIGN_CRITERION = 7, // CAMPAIGN_CRITERION FEED = 9, // FEED FEED_ITEM = 10, // FEED_ITEM AD_GROUP_FEED = 11, // AD_GROUP_FEED CAMPAIGN_FEED = 12, // CAMPAIGN_FEED AD_GROUP_BID_MODIFIER = 13, // AD_GROUP_BID_MODIFIER SHARED_SET = 14, // SHARED_SET CAMPAIGN_SHARED_SET = 15, // CAMPAIGN_SHARED_SET ASSET = 16, // ASSET CUSTOMER_ASSET = 17, // CUSTOMER_ASSET CAMPAIGN_ASSET = 18, // CAMPAIGN_ASSET AD_GROUP_ASSET = 19, // AD_GROUP_ASSET } /** * @name CombinedAudienceStatusEnum.CombinedAudienceStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CombinedAudienceStatusEnum.CombinedAudienceStatus */ export enum CombinedAudienceStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name ConversionActionCountingTypeEnum.ConversionActionCountingType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ConversionActionCountingTypeEnum.ConversionActionCountingType */ export enum ConversionActionCountingType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ONE_PER_CLICK = 2, // ONE_PER_CLICK MANY_PER_CLICK = 3, // MANY_PER_CLICK } /** * @name ConversionActionStatusEnum.ConversionActionStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ConversionActionStatusEnum.ConversionActionStatus */ export enum ConversionActionStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED HIDDEN = 4, // HIDDEN } /** * @name ConversionActionTypeEnum.ConversionActionType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ConversionActionTypeEnum.ConversionActionType */ export enum ConversionActionType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN AD_CALL = 2, // AD_CALL CLICK_TO_CALL = 3, // CLICK_TO_CALL GOOGLE_PLAY_DOWNLOAD = 4, // GOOGLE_PLAY_DOWNLOAD GOOGLE_PLAY_IN_APP_PURCHASE = 5, // GOOGLE_PLAY_IN_APP_PURCHASE UPLOAD_CALLS = 6, // UPLOAD_CALLS UPLOAD_CLICKS = 7, // UPLOAD_CLICKS WEBPAGE = 8, // WEBPAGE WEBSITE_CALL = 9, // WEBSITE_CALL STORE_SALES_DIRECT_UPLOAD = 10, // STORE_SALES_DIRECT_UPLOAD STORE_SALES = 11, // STORE_SALES FIREBASE_ANDROID_FIRST_OPEN = 12, // FIREBASE_ANDROID_FIRST_OPEN FIREBASE_ANDROID_IN_APP_PURCHASE = 13, // FIREBASE_ANDROID_IN_APP_PURCHASE FIREBASE_ANDROID_CUSTOM = 14, // FIREBASE_ANDROID_CUSTOM FIREBASE_IOS_FIRST_OPEN = 15, // FIREBASE_IOS_FIRST_OPEN FIREBASE_IOS_IN_APP_PURCHASE = 16, // FIREBASE_IOS_IN_APP_PURCHASE FIREBASE_IOS_CUSTOM = 17, // FIREBASE_IOS_CUSTOM THIRD_PARTY_APP_ANALYTICS_ANDROID_FIRST_OPEN = 18, // THIRD_PARTY_APP_ANALYTICS_ANDROID_FIRST_OPEN THIRD_PARTY_APP_ANALYTICS_ANDROID_IN_APP_PURCHASE = 19, // THIRD_PARTY_APP_ANALYTICS_ANDROID_IN_APP_PURCHASE THIRD_PARTY_APP_ANALYTICS_ANDROID_CUSTOM = 20, // THIRD_PARTY_APP_ANALYTICS_ANDROID_CUSTOM THIRD_PARTY_APP_ANALYTICS_IOS_FIRST_OPEN = 21, // THIRD_PARTY_APP_ANALYTICS_IOS_FIRST_OPEN THIRD_PARTY_APP_ANALYTICS_IOS_IN_APP_PURCHASE = 22, // THIRD_PARTY_APP_ANALYTICS_IOS_IN_APP_PURCHASE THIRD_PARTY_APP_ANALYTICS_IOS_CUSTOM = 23, // THIRD_PARTY_APP_ANALYTICS_IOS_CUSTOM ANDROID_APP_PRE_REGISTRATION = 24, // ANDROID_APP_PRE_REGISTRATION ANDROID_INSTALLS_ALL_OTHER_APPS = 25, // ANDROID_INSTALLS_ALL_OTHER_APPS FLOODLIGHT_ACTION = 26, // FLOODLIGHT_ACTION FLOODLIGHT_TRANSACTION = 27, // FLOODLIGHT_TRANSACTION GOOGLE_HOSTED = 28, // GOOGLE_HOSTED LEAD_FORM_SUBMIT = 29, // LEAD_FORM_SUBMIT SALESFORCE = 30, // SALESFORCE SEARCH_ADS_360 = 31, // SEARCH_ADS_360 SMART_CAMPAIGN_AD_CLICKS_TO_CALL = 32, // SMART_CAMPAIGN_AD_CLICKS_TO_CALL SMART_CAMPAIGN_MAP_CLICKS_TO_CALL = 33, // SMART_CAMPAIGN_MAP_CLICKS_TO_CALL SMART_CAMPAIGN_MAP_DIRECTIONS = 34, // SMART_CAMPAIGN_MAP_DIRECTIONS SMART_CAMPAIGN_TRACKED_CALLS = 35, // SMART_CAMPAIGN_TRACKED_CALLS STORE_VISITS = 36, // STORE_VISITS } /** * @name ConversionAdjustmentTypeEnum.ConversionAdjustmentType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ConversionAdjustmentTypeEnum.ConversionAdjustmentType */ export enum ConversionAdjustmentType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN RETRACTION = 2, // RETRACTION RESTATEMENT = 3, // RESTATEMENT ENHANCEMENT = 4, // ENHANCEMENT } /** * @name ConversionCustomVariableStatusEnum.ConversionCustomVariableStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ConversionCustomVariableStatusEnum.ConversionCustomVariableStatus */ export enum ConversionCustomVariableStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ACTIVATION_NEEDED = 2, // ACTIVATION_NEEDED ENABLED = 3, // ENABLED PAUSED = 4, // PAUSED } /** * @name ConversionOriginEnum.ConversionOrigin * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ConversionOriginEnum.ConversionOrigin */ export enum ConversionOrigin { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN WEBSITE = 2, // WEBSITE GOOGLE_HOSTED = 3, // GOOGLE_HOSTED APP = 4, // APP CALL_FROM_ADS = 5, // CALL_FROM_ADS STORE = 6, // STORE YOUTUBE_HOSTED = 7, // YOUTUBE_HOSTED } /** * @name ConversionValueRuleSetStatusEnum.ConversionValueRuleSetStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ConversionValueRuleSetStatusEnum.ConversionValueRuleSetStatus */ export enum ConversionValueRuleSetStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED PAUSED = 4, // PAUSED } /** * @name ConversionValueRuleStatusEnum.ConversionValueRuleStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ConversionValueRuleStatusEnum.ConversionValueRuleStatus */ export enum ConversionValueRuleStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED PAUSED = 4, // PAUSED } /** * @name CriterionSystemServingStatusEnum.CriterionSystemServingStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CriterionSystemServingStatusEnum.CriterionSystemServingStatus */ export enum CriterionSystemServingStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ELIGIBLE = 2, // ELIGIBLE RARELY_SERVED = 3, // RARELY_SERVED } /** * @name CriterionTypeEnum.CriterionType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CriterionTypeEnum.CriterionType */ export enum CriterionType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN KEYWORD = 2, // KEYWORD PLACEMENT = 3, // PLACEMENT MOBILE_APP_CATEGORY = 4, // MOBILE_APP_CATEGORY MOBILE_APPLICATION = 5, // MOBILE_APPLICATION DEVICE = 6, // DEVICE LOCATION = 7, // LOCATION LISTING_GROUP = 8, // LISTING_GROUP AD_SCHEDULE = 9, // AD_SCHEDULE AGE_RANGE = 10, // AGE_RANGE GENDER = 11, // GENDER INCOME_RANGE = 12, // INCOME_RANGE PARENTAL_STATUS = 13, // PARENTAL_STATUS YOUTUBE_VIDEO = 14, // YOUTUBE_VIDEO YOUTUBE_CHANNEL = 15, // YOUTUBE_CHANNEL USER_LIST = 16, // USER_LIST PROXIMITY = 17, // PROXIMITY TOPIC = 18, // TOPIC LISTING_SCOPE = 19, // LISTING_SCOPE LANGUAGE = 20, // LANGUAGE IP_BLOCK = 21, // IP_BLOCK CONTENT_LABEL = 22, // CONTENT_LABEL CARRIER = 23, // CARRIER USER_INTEREST = 24, // USER_INTEREST WEBPAGE = 25, // WEBPAGE OPERATING_SYSTEM_VERSION = 26, // OPERATING_SYSTEM_VERSION APP_PAYMENT_MODEL = 27, // APP_PAYMENT_MODEL MOBILE_DEVICE = 28, // MOBILE_DEVICE CUSTOM_AFFINITY = 29, // CUSTOM_AFFINITY CUSTOM_INTENT = 30, // CUSTOM_INTENT LOCATION_GROUP = 31, // LOCATION_GROUP CUSTOM_AUDIENCE = 32, // CUSTOM_AUDIENCE COMBINED_AUDIENCE = 33, // COMBINED_AUDIENCE KEYWORD_THEME = 34, // KEYWORD_THEME } /** * @name CustomAudienceMemberTypeEnum.CustomAudienceMemberType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CustomAudienceMemberTypeEnum.CustomAudienceMemberType */ export enum CustomAudienceMemberType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN KEYWORD = 2, // KEYWORD URL = 3, // URL PLACE_CATEGORY = 4, // PLACE_CATEGORY APP = 5, // APP } /** * @name CustomAudienceStatusEnum.CustomAudienceStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CustomAudienceStatusEnum.CustomAudienceStatus */ export enum CustomAudienceStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name CustomAudienceTypeEnum.CustomAudienceType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CustomAudienceTypeEnum.CustomAudienceType */ export enum CustomAudienceType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN AUTO = 2, // AUTO INTEREST = 3, // INTEREST PURCHASE_INTENT = 4, // PURCHASE_INTENT SEARCH = 5, // SEARCH } /** * @name CustomConversionGoalStatusEnum.CustomConversionGoalStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CustomConversionGoalStatusEnum.CustomConversionGoalStatus */ export enum CustomConversionGoalStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name CustomInterestMemberTypeEnum.CustomInterestMemberType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CustomInterestMemberTypeEnum.CustomInterestMemberType */ export enum CustomInterestMemberType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN KEYWORD = 2, // KEYWORD URL = 3, // URL } /** * @name CustomInterestStatusEnum.CustomInterestStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CustomInterestStatusEnum.CustomInterestStatus */ export enum CustomInterestStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name CustomInterestTypeEnum.CustomInterestType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CustomInterestTypeEnum.CustomInterestType */ export enum CustomInterestType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CUSTOM_AFFINITY = 2, // CUSTOM_AFFINITY CUSTOM_INTENT = 3, // CUSTOM_INTENT } /** * @name CustomPlaceholderFieldEnum.CustomPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CustomPlaceholderFieldEnum.CustomPlaceholderField */ export enum CustomPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ID = 2, // ID ID2 = 3, // ID2 ITEM_TITLE = 4, // ITEM_TITLE ITEM_SUBTITLE = 5, // ITEM_SUBTITLE ITEM_DESCRIPTION = 6, // ITEM_DESCRIPTION ITEM_ADDRESS = 7, // ITEM_ADDRESS PRICE = 8, // PRICE FORMATTED_PRICE = 9, // FORMATTED_PRICE SALE_PRICE = 10, // SALE_PRICE FORMATTED_SALE_PRICE = 11, // FORMATTED_SALE_PRICE IMAGE_URL = 12, // IMAGE_URL ITEM_CATEGORY = 13, // ITEM_CATEGORY FINAL_URLS = 14, // FINAL_URLS FINAL_MOBILE_URLS = 15, // FINAL_MOBILE_URLS TRACKING_URL = 16, // TRACKING_URL CONTEXTUAL_KEYWORDS = 17, // CONTEXTUAL_KEYWORDS ANDROID_APP_LINK = 18, // ANDROID_APP_LINK SIMILAR_IDS = 19, // SIMILAR_IDS IOS_APP_LINK = 20, // IOS_APP_LINK IOS_APP_STORE_ID = 21, // IOS_APP_STORE_ID } /** * @name CustomerPayPerConversionEligibilityFailureReasonEnum.CustomerPayPerConversionEligibilityFailureReason * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CustomerPayPerConversionEligibilityFailureReasonEnum.CustomerPayPerConversionEligibilityFailureReason */ export enum CustomerPayPerConversionEligibilityFailureReason { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN NOT_ENOUGH_CONVERSIONS = 2, // NOT_ENOUGH_CONVERSIONS CONVERSION_LAG_TOO_HIGH = 3, // CONVERSION_LAG_TOO_HIGH HAS_CAMPAIGN_WITH_SHARED_BUDGET = 4, // HAS_CAMPAIGN_WITH_SHARED_BUDGET HAS_UPLOAD_CLICKS_CONVERSION = 5, // HAS_UPLOAD_CLICKS_CONVERSION AVERAGE_DAILY_SPEND_TOO_HIGH = 6, // AVERAGE_DAILY_SPEND_TOO_HIGH ANALYSIS_NOT_COMPLETE = 7, // ANALYSIS_NOT_COMPLETE OTHER = 8, // OTHER } /** * @name CustomizerAttributeStatusEnum.CustomizerAttributeStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CustomizerAttributeStatusEnum.CustomizerAttributeStatus */ export enum CustomizerAttributeStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name CustomizerValueStatusEnum.CustomizerValueStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/CustomizerValueStatusEnum.CustomizerValueStatus */ export enum CustomizerValueStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name DataDrivenModelStatusEnum.DataDrivenModelStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/DataDrivenModelStatusEnum.DataDrivenModelStatus */ export enum DataDrivenModelStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN AVAILABLE = 2, // AVAILABLE STALE = 3, // STALE EXPIRED = 4, // EXPIRED NEVER_GENERATED = 5, // NEVER_GENERATED } /** * @name DistanceBucketEnum.DistanceBucket * @link https://developers.google.com/google-ads/api/reference/rpc/v9/DistanceBucketEnum.DistanceBucket */ export enum DistanceBucket { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN WITHIN_700M = 2, // WITHIN_700M WITHIN_1KM = 3, // WITHIN_1KM WITHIN_5KM = 4, // WITHIN_5KM WITHIN_10KM = 5, // WITHIN_10KM WITHIN_15KM = 6, // WITHIN_15KM WITHIN_20KM = 7, // WITHIN_20KM WITHIN_25KM = 8, // WITHIN_25KM WITHIN_30KM = 9, // WITHIN_30KM WITHIN_35KM = 10, // WITHIN_35KM WITHIN_40KM = 11, // WITHIN_40KM WITHIN_45KM = 12, // WITHIN_45KM WITHIN_50KM = 13, // WITHIN_50KM WITHIN_55KM = 14, // WITHIN_55KM WITHIN_60KM = 15, // WITHIN_60KM WITHIN_65KM = 16, // WITHIN_65KM BEYOND_65KM = 17, // BEYOND_65KM WITHIN_0_7MILES = 18, // WITHIN_0_7MILES WITHIN_1MILE = 19, // WITHIN_1MILE WITHIN_5MILES = 20, // WITHIN_5MILES WITHIN_10MILES = 21, // WITHIN_10MILES WITHIN_15MILES = 22, // WITHIN_15MILES WITHIN_20MILES = 23, // WITHIN_20MILES WITHIN_25MILES = 24, // WITHIN_25MILES WITHIN_30MILES = 25, // WITHIN_30MILES WITHIN_35MILES = 26, // WITHIN_35MILES WITHIN_40MILES = 27, // WITHIN_40MILES BEYOND_40MILES = 28, // BEYOND_40MILES } /** * @name DsaPageFeedCriterionFieldEnum.DsaPageFeedCriterionField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/DsaPageFeedCriterionFieldEnum.DsaPageFeedCriterionField */ export enum DsaPageFeedCriterionField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PAGE_URL = 2, // PAGE_URL LABEL = 3, // LABEL } /** * @name EducationPlaceholderFieldEnum.EducationPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/EducationPlaceholderFieldEnum.EducationPlaceholderField */ export enum EducationPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PROGRAM_ID = 2, // PROGRAM_ID LOCATION_ID = 3, // LOCATION_ID PROGRAM_NAME = 4, // PROGRAM_NAME AREA_OF_STUDY = 5, // AREA_OF_STUDY PROGRAM_DESCRIPTION = 6, // PROGRAM_DESCRIPTION SCHOOL_NAME = 7, // SCHOOL_NAME ADDRESS = 8, // ADDRESS THUMBNAIL_IMAGE_URL = 9, // THUMBNAIL_IMAGE_URL ALTERNATIVE_THUMBNAIL_IMAGE_URL = 10, // ALTERNATIVE_THUMBNAIL_IMAGE_URL FINAL_URLS = 11, // FINAL_URLS FINAL_MOBILE_URLS = 12, // FINAL_MOBILE_URLS TRACKING_URL = 13, // TRACKING_URL CONTEXTUAL_KEYWORDS = 14, // CONTEXTUAL_KEYWORDS ANDROID_APP_LINK = 15, // ANDROID_APP_LINK SIMILAR_PROGRAM_IDS = 16, // SIMILAR_PROGRAM_IDS IOS_APP_LINK = 17, // IOS_APP_LINK IOS_APP_STORE_ID = 18, // IOS_APP_STORE_ID } /** * @name ExtensionSettingDeviceEnum.ExtensionSettingDevice * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ExtensionSettingDeviceEnum.ExtensionSettingDevice */ export enum ExtensionSettingDevice { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN MOBILE = 2, // MOBILE DESKTOP = 3, // DESKTOP } /** * @name ExtensionTypeEnum.ExtensionType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ExtensionTypeEnum.ExtensionType */ export enum ExtensionType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN NONE = 2, // NONE APP = 3, // APP CALL = 4, // CALL CALLOUT = 5, // CALLOUT MESSAGE = 6, // MESSAGE PRICE = 7, // PRICE PROMOTION = 8, // PROMOTION SITELINK = 10, // SITELINK STRUCTURED_SNIPPET = 11, // STRUCTURED_SNIPPET LOCATION = 12, // LOCATION AFFILIATE_LOCATION = 13, // AFFILIATE_LOCATION HOTEL_CALLOUT = 15, // HOTEL_CALLOUT IMAGE = 16, // IMAGE } /** * @name FeedAttributeTypeEnum.FeedAttributeType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedAttributeTypeEnum.FeedAttributeType */ export enum FeedAttributeType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN INT64 = 2, // INT64 DOUBLE = 3, // DOUBLE STRING = 4, // STRING BOOLEAN = 5, // BOOLEAN URL = 6, // URL DATE_TIME = 7, // DATE_TIME INT64_LIST = 8, // INT64_LIST DOUBLE_LIST = 9, // DOUBLE_LIST STRING_LIST = 10, // STRING_LIST BOOLEAN_LIST = 11, // BOOLEAN_LIST URL_LIST = 12, // URL_LIST DATE_TIME_LIST = 13, // DATE_TIME_LIST PRICE = 14, // PRICE } /** * @name FeedItemQualityApprovalStatusEnum.FeedItemQualityApprovalStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedItemQualityApprovalStatusEnum.FeedItemQualityApprovalStatus */ export enum FeedItemQualityApprovalStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN APPROVED = 2, // APPROVED DISAPPROVED = 3, // DISAPPROVED } /** * @name FeedItemQualityDisapprovalReasonEnum.FeedItemQualityDisapprovalReason * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedItemQualityDisapprovalReasonEnum.FeedItemQualityDisapprovalReason */ export enum FeedItemQualityDisapprovalReason { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PRICE_TABLE_REPETITIVE_HEADERS = 2, // PRICE_TABLE_REPETITIVE_HEADERS PRICE_TABLE_REPETITIVE_DESCRIPTION = 3, // PRICE_TABLE_REPETITIVE_DESCRIPTION PRICE_TABLE_INCONSISTENT_ROWS = 4, // PRICE_TABLE_INCONSISTENT_ROWS PRICE_DESCRIPTION_HAS_PRICE_QUALIFIERS = 5, // PRICE_DESCRIPTION_HAS_PRICE_QUALIFIERS PRICE_UNSUPPORTED_LANGUAGE = 6, // PRICE_UNSUPPORTED_LANGUAGE PRICE_TABLE_ROW_HEADER_TABLE_TYPE_MISMATCH = 7, // PRICE_TABLE_ROW_HEADER_TABLE_TYPE_MISMATCH PRICE_TABLE_ROW_HEADER_HAS_PROMOTIONAL_TEXT = 8, // PRICE_TABLE_ROW_HEADER_HAS_PROMOTIONAL_TEXT PRICE_TABLE_ROW_DESCRIPTION_NOT_RELEVANT = 9, // PRICE_TABLE_ROW_DESCRIPTION_NOT_RELEVANT PRICE_TABLE_ROW_DESCRIPTION_HAS_PROMOTIONAL_TEXT = 10, // PRICE_TABLE_ROW_DESCRIPTION_HAS_PROMOTIONAL_TEXT PRICE_TABLE_ROW_HEADER_DESCRIPTION_REPETITIVE = 11, // PRICE_TABLE_ROW_HEADER_DESCRIPTION_REPETITIVE PRICE_TABLE_ROW_UNRATEABLE = 12, // PRICE_TABLE_ROW_UNRATEABLE PRICE_TABLE_ROW_PRICE_INVALID = 13, // PRICE_TABLE_ROW_PRICE_INVALID PRICE_TABLE_ROW_URL_INVALID = 14, // PRICE_TABLE_ROW_URL_INVALID PRICE_HEADER_OR_DESCRIPTION_HAS_PRICE = 15, // PRICE_HEADER_OR_DESCRIPTION_HAS_PRICE STRUCTURED_SNIPPETS_HEADER_POLICY_VIOLATED = 16, // STRUCTURED_SNIPPETS_HEADER_POLICY_VIOLATED STRUCTURED_SNIPPETS_REPEATED_VALUES = 17, // STRUCTURED_SNIPPETS_REPEATED_VALUES STRUCTURED_SNIPPETS_EDITORIAL_GUIDELINES = 18, // STRUCTURED_SNIPPETS_EDITORIAL_GUIDELINES STRUCTURED_SNIPPETS_HAS_PROMOTIONAL_TEXT = 19, // STRUCTURED_SNIPPETS_HAS_PROMOTIONAL_TEXT } /** * @name FeedItemSetStatusEnum.FeedItemSetStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedItemSetStatusEnum.FeedItemSetStatus */ export enum FeedItemSetStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name FeedItemStatusEnum.FeedItemStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedItemStatusEnum.FeedItemStatus */ export enum FeedItemStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name FeedItemTargetDeviceEnum.FeedItemTargetDevice * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedItemTargetDeviceEnum.FeedItemTargetDevice */ export enum FeedItemTargetDevice { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN MOBILE = 2, // MOBILE } /** * @name FeedItemTargetStatusEnum.FeedItemTargetStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedItemTargetStatusEnum.FeedItemTargetStatus */ export enum FeedItemTargetStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name FeedItemTargetTypeEnum.FeedItemTargetType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedItemTargetTypeEnum.FeedItemTargetType */ export enum FeedItemTargetType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CAMPAIGN = 2, // CAMPAIGN AD_GROUP = 3, // AD_GROUP CRITERION = 4, // CRITERION } /** * @name FeedItemValidationStatusEnum.FeedItemValidationStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedItemValidationStatusEnum.FeedItemValidationStatus */ export enum FeedItemValidationStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PENDING = 2, // PENDING INVALID = 3, // INVALID VALID = 4, // VALID } /** * @name FeedLinkStatusEnum.FeedLinkStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedLinkStatusEnum.FeedLinkStatus */ export enum FeedLinkStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name FeedMappingCriterionTypeEnum.FeedMappingCriterionType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedMappingCriterionTypeEnum.FeedMappingCriterionType */ export enum FeedMappingCriterionType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN LOCATION_EXTENSION_TARGETING = 4, // LOCATION_EXTENSION_TARGETING DSA_PAGE_FEED = 3, // DSA_PAGE_FEED } /** * @name FeedMappingStatusEnum.FeedMappingStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedMappingStatusEnum.FeedMappingStatus */ export enum FeedMappingStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name FeedOriginEnum.FeedOrigin * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedOriginEnum.FeedOrigin */ export enum FeedOrigin { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN USER = 2, // USER GOOGLE = 3, // GOOGLE } /** * @name FeedStatusEnum.FeedStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FeedStatusEnum.FeedStatus */ export enum FeedStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name FlightPlaceholderFieldEnum.FlightPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/FlightPlaceholderFieldEnum.FlightPlaceholderField */ export enum FlightPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN DESTINATION_ID = 2, // DESTINATION_ID ORIGIN_ID = 3, // ORIGIN_ID FLIGHT_DESCRIPTION = 4, // FLIGHT_DESCRIPTION ORIGIN_NAME = 5, // ORIGIN_NAME DESTINATION_NAME = 6, // DESTINATION_NAME FLIGHT_PRICE = 7, // FLIGHT_PRICE FORMATTED_PRICE = 8, // FORMATTED_PRICE FLIGHT_SALE_PRICE = 9, // FLIGHT_SALE_PRICE FORMATTED_SALE_PRICE = 10, // FORMATTED_SALE_PRICE IMAGE_URL = 11, // IMAGE_URL FINAL_URLS = 12, // FINAL_URLS FINAL_MOBILE_URLS = 13, // FINAL_MOBILE_URLS TRACKING_URL = 14, // TRACKING_URL ANDROID_APP_LINK = 15, // ANDROID_APP_LINK SIMILAR_DESTINATION_IDS = 16, // SIMILAR_DESTINATION_IDS IOS_APP_LINK = 17, // IOS_APP_LINK IOS_APP_STORE_ID = 18, // IOS_APP_STORE_ID } /** * @name GeoTargetConstantStatusEnum.GeoTargetConstantStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/GeoTargetConstantStatusEnum.GeoTargetConstantStatus */ export enum GeoTargetConstantStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVAL_PLANNED = 3, // REMOVAL_PLANNED } /** * @name GeoTargetingRestrictionEnum.GeoTargetingRestriction * @link https://developers.google.com/google-ads/api/reference/rpc/v9/GeoTargetingRestrictionEnum.GeoTargetingRestriction */ export enum GeoTargetingRestriction { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN LOCATION_OF_PRESENCE = 2, // LOCATION_OF_PRESENCE } /** * @name GeoTargetingTypeEnum.GeoTargetingType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/GeoTargetingTypeEnum.GeoTargetingType */ export enum GeoTargetingType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN AREA_OF_INTEREST = 2, // AREA_OF_INTEREST LOCATION_OF_PRESENCE = 3, // LOCATION_OF_PRESENCE } /** * @name GoalConfigLevelEnum.GoalConfigLevel * @link https://developers.google.com/google-ads/api/reference/rpc/v9/GoalConfigLevelEnum.GoalConfigLevel */ export enum GoalConfigLevel { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CUSTOMER = 2, // CUSTOMER CAMPAIGN = 3, // CAMPAIGN } /** * @name GoogleAdsFieldCategoryEnum.GoogleAdsFieldCategory * @link https://developers.google.com/google-ads/api/reference/rpc/v9/GoogleAdsFieldCategoryEnum.GoogleAdsFieldCategory */ export enum GoogleAdsFieldCategory { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN RESOURCE = 2, // RESOURCE ATTRIBUTE = 3, // ATTRIBUTE SEGMENT = 5, // SEGMENT METRIC = 6, // METRIC } /** * @name GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType */ export enum GoogleAdsFieldDataType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN BOOLEAN = 2, // BOOLEAN DATE = 3, // DATE DOUBLE = 4, // DOUBLE ENUM = 5, // ENUM FLOAT = 6, // FLOAT INT32 = 7, // INT32 INT64 = 8, // INT64 MESSAGE = 9, // MESSAGE RESOURCE_NAME = 10, // RESOURCE_NAME STRING = 11, // STRING UINT64 = 12, // UINT64 } /** * @name GoogleVoiceCallStatusEnum.GoogleVoiceCallStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/GoogleVoiceCallStatusEnum.GoogleVoiceCallStatus */ export enum GoogleVoiceCallStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN MISSED = 2, // MISSED RECEIVED = 3, // RECEIVED } /** * @name HotelPlaceholderFieldEnum.HotelPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/HotelPlaceholderFieldEnum.HotelPlaceholderField */ export enum HotelPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PROPERTY_ID = 2, // PROPERTY_ID PROPERTY_NAME = 3, // PROPERTY_NAME DESTINATION_NAME = 4, // DESTINATION_NAME DESCRIPTION = 5, // DESCRIPTION ADDRESS = 6, // ADDRESS PRICE = 7, // PRICE FORMATTED_PRICE = 8, // FORMATTED_PRICE SALE_PRICE = 9, // SALE_PRICE FORMATTED_SALE_PRICE = 10, // FORMATTED_SALE_PRICE IMAGE_URL = 11, // IMAGE_URL CATEGORY = 12, // CATEGORY STAR_RATING = 13, // STAR_RATING CONTEXTUAL_KEYWORDS = 14, // CONTEXTUAL_KEYWORDS FINAL_URLS = 15, // FINAL_URLS FINAL_MOBILE_URLS = 16, // FINAL_MOBILE_URLS TRACKING_URL = 17, // TRACKING_URL ANDROID_APP_LINK = 18, // ANDROID_APP_LINK SIMILAR_PROPERTY_IDS = 19, // SIMILAR_PROPERTY_IDS IOS_APP_LINK = 20, // IOS_APP_LINK IOS_APP_STORE_ID = 21, // IOS_APP_STORE_ID } /** * @name HotelReconciliationStatusEnum.HotelReconciliationStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/HotelReconciliationStatusEnum.HotelReconciliationStatus */ export enum HotelReconciliationStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN RESERVATION_ENABLED = 2, // RESERVATION_ENABLED RECONCILIATION_NEEDED = 3, // RECONCILIATION_NEEDED RECONCILED = 4, // RECONCILED CANCELED = 5, // CANCELED } /** * @name ImagePlaceholderFieldEnum.ImagePlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ImagePlaceholderFieldEnum.ImagePlaceholderField */ export enum ImagePlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ASSET_ID = 2, // ASSET_ID } /** * @name InvoiceTypeEnum.InvoiceType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/InvoiceTypeEnum.InvoiceType */ export enum InvoiceType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CREDIT_MEMO = 2, // CREDIT_MEMO INVOICE = 3, // INVOICE } /** * @name JobPlaceholderFieldEnum.JobPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/JobPlaceholderFieldEnum.JobPlaceholderField */ export enum JobPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN JOB_ID = 2, // JOB_ID LOCATION_ID = 3, // LOCATION_ID TITLE = 4, // TITLE SUBTITLE = 5, // SUBTITLE DESCRIPTION = 6, // DESCRIPTION IMAGE_URL = 7, // IMAGE_URL CATEGORY = 8, // CATEGORY CONTEXTUAL_KEYWORDS = 9, // CONTEXTUAL_KEYWORDS ADDRESS = 10, // ADDRESS SALARY = 11, // SALARY FINAL_URLS = 12, // FINAL_URLS FINAL_MOBILE_URLS = 14, // FINAL_MOBILE_URLS TRACKING_URL = 15, // TRACKING_URL ANDROID_APP_LINK = 16, // ANDROID_APP_LINK SIMILAR_JOB_IDS = 17, // SIMILAR_JOB_IDS IOS_APP_LINK = 18, // IOS_APP_LINK IOS_APP_STORE_ID = 19, // IOS_APP_STORE_ID } /** * @name KeywordPlanForecastIntervalEnum.KeywordPlanForecastInterval * @link https://developers.google.com/google-ads/api/reference/rpc/v9/KeywordPlanForecastIntervalEnum.KeywordPlanForecastInterval */ export enum KeywordPlanForecastInterval { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN NEXT_WEEK = 3, // NEXT_WEEK NEXT_MONTH = 4, // NEXT_MONTH NEXT_QUARTER = 5, // NEXT_QUARTER } /** * @name KeywordPlanKeywordAnnotationEnum.KeywordPlanKeywordAnnotation * @link https://developers.google.com/google-ads/api/reference/rpc/v9/KeywordPlanKeywordAnnotationEnum.KeywordPlanKeywordAnnotation */ export enum KeywordPlanKeywordAnnotation { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN KEYWORD_CONCEPT = 2, // KEYWORD_CONCEPT } /** * @name KeywordPlanNetworkEnum.KeywordPlanNetwork * @link https://developers.google.com/google-ads/api/reference/rpc/v9/KeywordPlanNetworkEnum.KeywordPlanNetwork */ export enum KeywordPlanNetwork { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN GOOGLE_SEARCH = 2, // GOOGLE_SEARCH GOOGLE_SEARCH_AND_PARTNERS = 3, // GOOGLE_SEARCH_AND_PARTNERS } /** * @name LabelStatusEnum.LabelStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/LabelStatusEnum.LabelStatus */ export enum LabelStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name LinkedAccountTypeEnum.LinkedAccountType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/LinkedAccountTypeEnum.LinkedAccountType */ export enum LinkedAccountType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN THIRD_PARTY_APP_ANALYTICS = 2, // THIRD_PARTY_APP_ANALYTICS DATA_PARTNER = 3, // DATA_PARTNER GOOGLE_ADS = 4, // GOOGLE_ADS } /** * @name ListingGroupFilterBiddingCategoryLevelEnum.ListingGroupFilterBiddingCategoryLevel * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ListingGroupFilterBiddingCategoryLevelEnum.ListingGroupFilterBiddingCategoryLevel */ export enum ListingGroupFilterBiddingCategoryLevel { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN LEVEL1 = 2, // LEVEL1 LEVEL2 = 3, // LEVEL2 LEVEL3 = 4, // LEVEL3 LEVEL4 = 5, // LEVEL4 LEVEL5 = 6, // LEVEL5 } /** * @name ListingGroupFilterCustomAttributeIndexEnum.ListingGroupFilterCustomAttributeIndex * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ListingGroupFilterCustomAttributeIndexEnum.ListingGroupFilterCustomAttributeIndex */ export enum ListingGroupFilterCustomAttributeIndex { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN INDEX0 = 2, // INDEX0 INDEX1 = 3, // INDEX1 INDEX2 = 4, // INDEX2 INDEX3 = 5, // INDEX3 INDEX4 = 6, // INDEX4 } /** * @name ListingGroupFilterProductChannelEnum.ListingGroupFilterProductChannel * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ListingGroupFilterProductChannelEnum.ListingGroupFilterProductChannel */ export enum ListingGroupFilterProductChannel { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ONLINE = 2, // ONLINE LOCAL = 3, // LOCAL } /** * @name ListingGroupFilterProductConditionEnum.ListingGroupFilterProductCondition * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ListingGroupFilterProductConditionEnum.ListingGroupFilterProductCondition */ export enum ListingGroupFilterProductCondition { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN NEW = 2, // NEW REFURBISHED = 3, // REFURBISHED USED = 4, // USED } /** * @name ListingGroupFilterProductTypeLevelEnum.ListingGroupFilterProductTypeLevel * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ListingGroupFilterProductTypeLevelEnum.ListingGroupFilterProductTypeLevel */ export enum ListingGroupFilterProductTypeLevel { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN LEVEL1 = 2, // LEVEL1 LEVEL2 = 3, // LEVEL2 LEVEL3 = 4, // LEVEL3 LEVEL4 = 5, // LEVEL4 LEVEL5 = 6, // LEVEL5 } /** * @name ListingGroupFilterTypeEnum.ListingGroupFilterType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ListingGroupFilterTypeEnum.ListingGroupFilterType */ export enum ListingGroupFilterType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN SUBDIVISION = 2, // SUBDIVISION UNIT_INCLUDED = 3, // UNIT_INCLUDED UNIT_EXCLUDED = 4, // UNIT_EXCLUDED } /** * @name ListingGroupFilterVerticalEnum.ListingGroupFilterVertical * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ListingGroupFilterVerticalEnum.ListingGroupFilterVertical */ export enum ListingGroupFilterVertical { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN SHOPPING = 2, // SHOPPING } /** * @name LocalPlaceholderFieldEnum.LocalPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/LocalPlaceholderFieldEnum.LocalPlaceholderField */ export enum LocalPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN DEAL_ID = 2, // DEAL_ID DEAL_NAME = 3, // DEAL_NAME SUBTITLE = 4, // SUBTITLE DESCRIPTION = 5, // DESCRIPTION PRICE = 6, // PRICE FORMATTED_PRICE = 7, // FORMATTED_PRICE SALE_PRICE = 8, // SALE_PRICE FORMATTED_SALE_PRICE = 9, // FORMATTED_SALE_PRICE IMAGE_URL = 10, // IMAGE_URL ADDRESS = 11, // ADDRESS CATEGORY = 12, // CATEGORY CONTEXTUAL_KEYWORDS = 13, // CONTEXTUAL_KEYWORDS FINAL_URLS = 14, // FINAL_URLS FINAL_MOBILE_URLS = 15, // FINAL_MOBILE_URLS TRACKING_URL = 16, // TRACKING_URL ANDROID_APP_LINK = 17, // ANDROID_APP_LINK SIMILAR_DEAL_IDS = 18, // SIMILAR_DEAL_IDS IOS_APP_LINK = 19, // IOS_APP_LINK IOS_APP_STORE_ID = 20, // IOS_APP_STORE_ID } /** * @name LocationExtensionTargetingCriterionFieldEnum.LocationExtensionTargetingCriterionField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/LocationExtensionTargetingCriterionFieldEnum.LocationExtensionTargetingCriterionField */ export enum LocationExtensionTargetingCriterionField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ADDRESS_LINE_1 = 2, // ADDRESS_LINE_1 ADDRESS_LINE_2 = 3, // ADDRESS_LINE_2 CITY = 4, // CITY PROVINCE = 5, // PROVINCE POSTAL_CODE = 6, // POSTAL_CODE COUNTRY_CODE = 7, // COUNTRY_CODE } /** * @name LocationPlaceholderFieldEnum.LocationPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/LocationPlaceholderFieldEnum.LocationPlaceholderField */ export enum LocationPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN BUSINESS_NAME = 2, // BUSINESS_NAME ADDRESS_LINE_1 = 3, // ADDRESS_LINE_1 ADDRESS_LINE_2 = 4, // ADDRESS_LINE_2 CITY = 5, // CITY PROVINCE = 6, // PROVINCE POSTAL_CODE = 7, // POSTAL_CODE COUNTRY_CODE = 8, // COUNTRY_CODE PHONE_NUMBER = 9, // PHONE_NUMBER } /** * @name LocationSourceTypeEnum.LocationSourceType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/LocationSourceTypeEnum.LocationSourceType */ export enum LocationSourceType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN GOOGLE_MY_BUSINESS = 2, // GOOGLE_MY_BUSINESS AFFILIATE = 3, // AFFILIATE } /** * @name ManagerLinkStatusEnum.ManagerLinkStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ManagerLinkStatusEnum.ManagerLinkStatus */ export enum ManagerLinkStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ACTIVE = 2, // ACTIVE INACTIVE = 3, // INACTIVE PENDING = 4, // PENDING REFUSED = 5, // REFUSED CANCELED = 6, // CANCELED } /** * @name MediaTypeEnum.MediaType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/MediaTypeEnum.MediaType */ export enum MediaType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN IMAGE = 2, // IMAGE ICON = 3, // ICON MEDIA_BUNDLE = 4, // MEDIA_BUNDLE AUDIO = 5, // AUDIO VIDEO = 6, // VIDEO DYNAMIC_IMAGE = 7, // DYNAMIC_IMAGE } /** * @name MerchantCenterLinkStatusEnum.MerchantCenterLinkStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/MerchantCenterLinkStatusEnum.MerchantCenterLinkStatus */ export enum MerchantCenterLinkStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED PENDING = 3, // PENDING } /** * @name MessagePlaceholderFieldEnum.MessagePlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/MessagePlaceholderFieldEnum.MessagePlaceholderField */ export enum MessagePlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN BUSINESS_NAME = 2, // BUSINESS_NAME COUNTRY_CODE = 3, // COUNTRY_CODE PHONE_NUMBER = 4, // PHONE_NUMBER MESSAGE_EXTENSION_TEXT = 5, // MESSAGE_EXTENSION_TEXT MESSAGE_TEXT = 6, // MESSAGE_TEXT } /** * @name MobileDeviceTypeEnum.MobileDeviceType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/MobileDeviceTypeEnum.MobileDeviceType */ export enum MobileDeviceType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN MOBILE = 2, // MOBILE TABLET = 3, // TABLET } /** * @name NegativeGeoTargetTypeEnum.NegativeGeoTargetType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/NegativeGeoTargetTypeEnum.NegativeGeoTargetType */ export enum NegativeGeoTargetType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PRESENCE_OR_INTEREST = 4, // PRESENCE_OR_INTEREST PRESENCE = 5, // PRESENCE } /** * @name OfflineUserDataJobFailureReasonEnum.OfflineUserDataJobFailureReason * @link https://developers.google.com/google-ads/api/reference/rpc/v9/OfflineUserDataJobFailureReasonEnum.OfflineUserDataJobFailureReason */ export enum OfflineUserDataJobFailureReason { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN INSUFFICIENT_MATCHED_TRANSACTIONS = 2, // INSUFFICIENT_MATCHED_TRANSACTIONS INSUFFICIENT_TRANSACTIONS = 3, // INSUFFICIENT_TRANSACTIONS } /** * @name OfflineUserDataJobMatchRateRangeEnum.OfflineUserDataJobMatchRateRange * @link https://developers.google.com/google-ads/api/reference/rpc/v9/OfflineUserDataJobMatchRateRangeEnum.OfflineUserDataJobMatchRateRange */ export enum OfflineUserDataJobMatchRateRange { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN MATCH_RANGE_LESS_THAN_20 = 2, // MATCH_RANGE_LESS_THAN_20 MATCH_RANGE_20_TO_30 = 3, // MATCH_RANGE_20_TO_30 MATCH_RANGE_31_TO_40 = 4, // MATCH_RANGE_31_TO_40 MATCH_RANGE_41_TO_50 = 5, // MATCH_RANGE_41_TO_50 MATCH_RANGE_51_TO_60 = 6, // MATCH_RANGE_51_TO_60 MATCH_RANGE_61_TO_70 = 7, // MATCH_RANGE_61_TO_70 MATCH_RANGE_71_TO_80 = 8, // MATCH_RANGE_71_TO_80 MATCH_RANGE_81_TO_90 = 9, // MATCH_RANGE_81_TO_90 MATCH_RANGE_91_TO_100 = 10, // MATCH_RANGE_91_TO_100 } /** * @name OfflineUserDataJobStatusEnum.OfflineUserDataJobStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/OfflineUserDataJobStatusEnum.OfflineUserDataJobStatus */ export enum OfflineUserDataJobStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PENDING = 2, // PENDING RUNNING = 3, // RUNNING SUCCESS = 4, // SUCCESS FAILED = 5, // FAILED } /** * @name OfflineUserDataJobTypeEnum.OfflineUserDataJobType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/OfflineUserDataJobTypeEnum.OfflineUserDataJobType */ export enum OfflineUserDataJobType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN STORE_SALES_UPLOAD_FIRST_PARTY = 2, // STORE_SALES_UPLOAD_FIRST_PARTY STORE_SALES_UPLOAD_THIRD_PARTY = 3, // STORE_SALES_UPLOAD_THIRD_PARTY CUSTOMER_MATCH_USER_LIST = 4, // CUSTOMER_MATCH_USER_LIST CUSTOMER_MATCH_WITH_ATTRIBUTES = 5, // CUSTOMER_MATCH_WITH_ATTRIBUTES } /** * @name OperatingSystemVersionOperatorTypeEnum.OperatingSystemVersionOperatorType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/OperatingSystemVersionOperatorTypeEnum.OperatingSystemVersionOperatorType */ export enum OperatingSystemVersionOperatorType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN EQUALS_TO = 2, // EQUALS_TO GREATER_THAN_EQUALS_TO = 4, // GREATER_THAN_EQUALS_TO } /** * @name OptimizationGoalTypeEnum.OptimizationGoalType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/OptimizationGoalTypeEnum.OptimizationGoalType */ export enum OptimizationGoalType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CALL_CLICKS = 2, // CALL_CLICKS DRIVING_DIRECTIONS = 3, // DRIVING_DIRECTIONS APP_PRE_REGISTRATION = 4, // APP_PRE_REGISTRATION } /** * @name PaymentModeEnum.PaymentMode * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PaymentModeEnum.PaymentMode */ export enum PaymentMode { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CLICKS = 4, // CLICKS CONVERSION_VALUE = 5, // CONVERSION_VALUE CONVERSIONS = 6, // CONVERSIONS GUEST_STAY = 7, // GUEST_STAY } /** * @name PlacementTypeEnum.PlacementType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PlacementTypeEnum.PlacementType */ export enum PlacementType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN WEBSITE = 2, // WEBSITE MOBILE_APP_CATEGORY = 3, // MOBILE_APP_CATEGORY MOBILE_APPLICATION = 4, // MOBILE_APPLICATION YOUTUBE_VIDEO = 5, // YOUTUBE_VIDEO YOUTUBE_CHANNEL = 6, // YOUTUBE_CHANNEL } /** * @name PositiveGeoTargetTypeEnum.PositiveGeoTargetType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PositiveGeoTargetTypeEnum.PositiveGeoTargetType */ export enum PositiveGeoTargetType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PRESENCE_OR_INTEREST = 5, // PRESENCE_OR_INTEREST SEARCH_INTEREST = 6, // SEARCH_INTEREST PRESENCE = 7, // PRESENCE } /** * @name PricePlaceholderFieldEnum.PricePlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PricePlaceholderFieldEnum.PricePlaceholderField */ export enum PricePlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN TYPE = 2, // TYPE PRICE_QUALIFIER = 3, // PRICE_QUALIFIER TRACKING_TEMPLATE = 4, // TRACKING_TEMPLATE LANGUAGE = 5, // LANGUAGE FINAL_URL_SUFFIX = 6, // FINAL_URL_SUFFIX ITEM_1_HEADER = 100, // ITEM_1_HEADER ITEM_1_DESCRIPTION = 101, // ITEM_1_DESCRIPTION ITEM_1_PRICE = 102, // ITEM_1_PRICE ITEM_1_UNIT = 103, // ITEM_1_UNIT ITEM_1_FINAL_URLS = 104, // ITEM_1_FINAL_URLS ITEM_1_FINAL_MOBILE_URLS = 105, // ITEM_1_FINAL_MOBILE_URLS ITEM_2_HEADER = 200, // ITEM_2_HEADER ITEM_2_DESCRIPTION = 201, // ITEM_2_DESCRIPTION ITEM_2_PRICE = 202, // ITEM_2_PRICE ITEM_2_UNIT = 203, // ITEM_2_UNIT ITEM_2_FINAL_URLS = 204, // ITEM_2_FINAL_URLS ITEM_2_FINAL_MOBILE_URLS = 205, // ITEM_2_FINAL_MOBILE_URLS ITEM_3_HEADER = 300, // ITEM_3_HEADER ITEM_3_DESCRIPTION = 301, // ITEM_3_DESCRIPTION ITEM_3_PRICE = 302, // ITEM_3_PRICE ITEM_3_UNIT = 303, // ITEM_3_UNIT ITEM_3_FINAL_URLS = 304, // ITEM_3_FINAL_URLS ITEM_3_FINAL_MOBILE_URLS = 305, // ITEM_3_FINAL_MOBILE_URLS ITEM_4_HEADER = 400, // ITEM_4_HEADER ITEM_4_DESCRIPTION = 401, // ITEM_4_DESCRIPTION ITEM_4_PRICE = 402, // ITEM_4_PRICE ITEM_4_UNIT = 403, // ITEM_4_UNIT ITEM_4_FINAL_URLS = 404, // ITEM_4_FINAL_URLS ITEM_4_FINAL_MOBILE_URLS = 405, // ITEM_4_FINAL_MOBILE_URLS ITEM_5_HEADER = 500, // ITEM_5_HEADER ITEM_5_DESCRIPTION = 501, // ITEM_5_DESCRIPTION ITEM_5_PRICE = 502, // ITEM_5_PRICE ITEM_5_UNIT = 503, // ITEM_5_UNIT ITEM_5_FINAL_URLS = 504, // ITEM_5_FINAL_URLS ITEM_5_FINAL_MOBILE_URLS = 505, // ITEM_5_FINAL_MOBILE_URLS ITEM_6_HEADER = 600, // ITEM_6_HEADER ITEM_6_DESCRIPTION = 601, // ITEM_6_DESCRIPTION ITEM_6_PRICE = 602, // ITEM_6_PRICE ITEM_6_UNIT = 603, // ITEM_6_UNIT ITEM_6_FINAL_URLS = 604, // ITEM_6_FINAL_URLS ITEM_6_FINAL_MOBILE_URLS = 605, // ITEM_6_FINAL_MOBILE_URLS ITEM_7_HEADER = 700, // ITEM_7_HEADER ITEM_7_DESCRIPTION = 701, // ITEM_7_DESCRIPTION ITEM_7_PRICE = 702, // ITEM_7_PRICE ITEM_7_UNIT = 703, // ITEM_7_UNIT ITEM_7_FINAL_URLS = 704, // ITEM_7_FINAL_URLS ITEM_7_FINAL_MOBILE_URLS = 705, // ITEM_7_FINAL_MOBILE_URLS ITEM_8_HEADER = 800, // ITEM_8_HEADER ITEM_8_DESCRIPTION = 801, // ITEM_8_DESCRIPTION ITEM_8_PRICE = 802, // ITEM_8_PRICE ITEM_8_UNIT = 803, // ITEM_8_UNIT ITEM_8_FINAL_URLS = 804, // ITEM_8_FINAL_URLS ITEM_8_FINAL_MOBILE_URLS = 805, // ITEM_8_FINAL_MOBILE_URLS } /** * @name ProductBiddingCategoryStatusEnum.ProductBiddingCategoryStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ProductBiddingCategoryStatusEnum.ProductBiddingCategoryStatus */ export enum ProductBiddingCategoryStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ACTIVE = 2, // ACTIVE OBSOLETE = 3, // OBSOLETE } /** * @name PromotionPlaceholderFieldEnum.PromotionPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/PromotionPlaceholderFieldEnum.PromotionPlaceholderField */ export enum PromotionPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PROMOTION_TARGET = 2, // PROMOTION_TARGET DISCOUNT_MODIFIER = 3, // DISCOUNT_MODIFIER PERCENT_OFF = 4, // PERCENT_OFF MONEY_AMOUNT_OFF = 5, // MONEY_AMOUNT_OFF PROMOTION_CODE = 6, // PROMOTION_CODE ORDERS_OVER_AMOUNT = 7, // ORDERS_OVER_AMOUNT PROMOTION_START = 8, // PROMOTION_START PROMOTION_END = 9, // PROMOTION_END OCCASION = 10, // OCCASION FINAL_URLS = 11, // FINAL_URLS FINAL_MOBILE_URLS = 12, // FINAL_MOBILE_URLS TRACKING_URL = 13, // TRACKING_URL LANGUAGE = 14, // LANGUAGE FINAL_URL_SUFFIX = 15, // FINAL_URL_SUFFIX } /** * @name ReachPlanAdLengthEnum.ReachPlanAdLength * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ReachPlanAdLengthEnum.ReachPlanAdLength */ export enum ReachPlanAdLength { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN SIX_SECONDS = 2, // SIX_SECONDS FIFTEEN_OR_TWENTY_SECONDS = 3, // FIFTEEN_OR_TWENTY_SECONDS TWENTY_SECONDS_OR_MORE = 4, // TWENTY_SECONDS_OR_MORE } /** * @name ReachPlanAgeRangeEnum.ReachPlanAgeRange * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ReachPlanAgeRangeEnum.ReachPlanAgeRange */ export enum ReachPlanAgeRange { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN AGE_RANGE_18_24 = 503001, // AGE_RANGE_18_24 AGE_RANGE_18_34 = 2, // AGE_RANGE_18_34 AGE_RANGE_18_44 = 3, // AGE_RANGE_18_44 AGE_RANGE_18_49 = 4, // AGE_RANGE_18_49 AGE_RANGE_18_54 = 5, // AGE_RANGE_18_54 AGE_RANGE_18_64 = 6, // AGE_RANGE_18_64 AGE_RANGE_18_65_UP = 7, // AGE_RANGE_18_65_UP AGE_RANGE_21_34 = 8, // AGE_RANGE_21_34 AGE_RANGE_25_34 = 503002, // AGE_RANGE_25_34 AGE_RANGE_25_44 = 9, // AGE_RANGE_25_44 AGE_RANGE_25_49 = 10, // AGE_RANGE_25_49 AGE_RANGE_25_54 = 11, // AGE_RANGE_25_54 AGE_RANGE_25_64 = 12, // AGE_RANGE_25_64 AGE_RANGE_25_65_UP = 13, // AGE_RANGE_25_65_UP AGE_RANGE_35_44 = 503003, // AGE_RANGE_35_44 AGE_RANGE_35_49 = 14, // AGE_RANGE_35_49 AGE_RANGE_35_54 = 15, // AGE_RANGE_35_54 AGE_RANGE_35_64 = 16, // AGE_RANGE_35_64 AGE_RANGE_35_65_UP = 17, // AGE_RANGE_35_65_UP AGE_RANGE_45_54 = 503004, // AGE_RANGE_45_54 AGE_RANGE_45_64 = 18, // AGE_RANGE_45_64 AGE_RANGE_45_65_UP = 19, // AGE_RANGE_45_65_UP AGE_RANGE_50_65_UP = 20, // AGE_RANGE_50_65_UP AGE_RANGE_55_64 = 503005, // AGE_RANGE_55_64 AGE_RANGE_55_65_UP = 21, // AGE_RANGE_55_65_UP AGE_RANGE_65_UP = 503006, // AGE_RANGE_65_UP } /** * @name ReachPlanNetworkEnum.ReachPlanNetwork * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ReachPlanNetworkEnum.ReachPlanNetwork */ export enum ReachPlanNetwork { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN YOUTUBE = 2, // YOUTUBE GOOGLE_VIDEO_PARTNERS = 3, // GOOGLE_VIDEO_PARTNERS YOUTUBE_AND_GOOGLE_VIDEO_PARTNERS = 4, // YOUTUBE_AND_GOOGLE_VIDEO_PARTNERS } /** * @name RealEstatePlaceholderFieldEnum.RealEstatePlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/RealEstatePlaceholderFieldEnum.RealEstatePlaceholderField */ export enum RealEstatePlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN LISTING_ID = 2, // LISTING_ID LISTING_NAME = 3, // LISTING_NAME CITY_NAME = 4, // CITY_NAME DESCRIPTION = 5, // DESCRIPTION ADDRESS = 6, // ADDRESS PRICE = 7, // PRICE FORMATTED_PRICE = 8, // FORMATTED_PRICE IMAGE_URL = 9, // IMAGE_URL PROPERTY_TYPE = 10, // PROPERTY_TYPE LISTING_TYPE = 11, // LISTING_TYPE CONTEXTUAL_KEYWORDS = 12, // CONTEXTUAL_KEYWORDS FINAL_URLS = 13, // FINAL_URLS FINAL_MOBILE_URLS = 14, // FINAL_MOBILE_URLS TRACKING_URL = 15, // TRACKING_URL ANDROID_APP_LINK = 16, // ANDROID_APP_LINK SIMILAR_LISTING_IDS = 17, // SIMILAR_LISTING_IDS IOS_APP_LINK = 18, // IOS_APP_LINK IOS_APP_STORE_ID = 19, // IOS_APP_STORE_ID } /** * @name ResourceChangeOperationEnum.ResourceChangeOperation * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ResourceChangeOperationEnum.ResourceChangeOperation */ export enum ResourceChangeOperation { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CREATE = 2, // CREATE UPDATE = 3, // UPDATE REMOVE = 4, // REMOVE } /** * @name ResourceLimitTypeEnum.ResourceLimitType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ResourceLimitTypeEnum.ResourceLimitType */ export enum ResourceLimitType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CAMPAIGNS_PER_CUSTOMER = 2, // CAMPAIGNS_PER_CUSTOMER BASE_CAMPAIGNS_PER_CUSTOMER = 3, // BASE_CAMPAIGNS_PER_CUSTOMER EXPERIMENT_CAMPAIGNS_PER_CUSTOMER = 105, // EXPERIMENT_CAMPAIGNS_PER_CUSTOMER HOTEL_CAMPAIGNS_PER_CUSTOMER = 4, // HOTEL_CAMPAIGNS_PER_CUSTOMER SMART_SHOPPING_CAMPAIGNS_PER_CUSTOMER = 5, // SMART_SHOPPING_CAMPAIGNS_PER_CUSTOMER AD_GROUPS_PER_CAMPAIGN = 6, // AD_GROUPS_PER_CAMPAIGN AD_GROUPS_PER_SHOPPING_CAMPAIGN = 8, // AD_GROUPS_PER_SHOPPING_CAMPAIGN AD_GROUPS_PER_HOTEL_CAMPAIGN = 9, // AD_GROUPS_PER_HOTEL_CAMPAIGN REPORTING_AD_GROUPS_PER_LOCAL_CAMPAIGN = 10, // REPORTING_AD_GROUPS_PER_LOCAL_CAMPAIGN REPORTING_AD_GROUPS_PER_APP_CAMPAIGN = 11, // REPORTING_AD_GROUPS_PER_APP_CAMPAIGN MANAGED_AD_GROUPS_PER_SMART_CAMPAIGN = 52, // MANAGED_AD_GROUPS_PER_SMART_CAMPAIGN AD_GROUP_CRITERIA_PER_CUSTOMER = 12, // AD_GROUP_CRITERIA_PER_CUSTOMER BASE_AD_GROUP_CRITERIA_PER_CUSTOMER = 13, // BASE_AD_GROUP_CRITERIA_PER_CUSTOMER EXPERIMENT_AD_GROUP_CRITERIA_PER_CUSTOMER = 107, // EXPERIMENT_AD_GROUP_CRITERIA_PER_CUSTOMER AD_GROUP_CRITERIA_PER_CAMPAIGN = 14, // AD_GROUP_CRITERIA_PER_CAMPAIGN CAMPAIGN_CRITERIA_PER_CUSTOMER = 15, // CAMPAIGN_CRITERIA_PER_CUSTOMER BASE_CAMPAIGN_CRITERIA_PER_CUSTOMER = 16, // BASE_CAMPAIGN_CRITERIA_PER_CUSTOMER EXPERIMENT_CAMPAIGN_CRITERIA_PER_CUSTOMER = 108, // EXPERIMENT_CAMPAIGN_CRITERIA_PER_CUSTOMER WEBPAGE_CRITERIA_PER_CUSTOMER = 17, // WEBPAGE_CRITERIA_PER_CUSTOMER BASE_WEBPAGE_CRITERIA_PER_CUSTOMER = 18, // BASE_WEBPAGE_CRITERIA_PER_CUSTOMER EXPERIMENT_WEBPAGE_CRITERIA_PER_CUSTOMER = 19, // EXPERIMENT_WEBPAGE_CRITERIA_PER_CUSTOMER COMBINED_AUDIENCE_CRITERIA_PER_AD_GROUP = 20, // COMBINED_AUDIENCE_CRITERIA_PER_AD_GROUP CUSTOMER_NEGATIVE_PLACEMENT_CRITERIA_PER_CUSTOMER = 21, // CUSTOMER_NEGATIVE_PLACEMENT_CRITERIA_PER_CUSTOMER CUSTOMER_NEGATIVE_YOUTUBE_CHANNEL_CRITERIA_PER_CUSTOMER = 22, // CUSTOMER_NEGATIVE_YOUTUBE_CHANNEL_CRITERIA_PER_CUSTOMER CRITERIA_PER_AD_GROUP = 23, // CRITERIA_PER_AD_GROUP LISTING_GROUPS_PER_AD_GROUP = 24, // LISTING_GROUPS_PER_AD_GROUP EXPLICITLY_SHARED_BUDGETS_PER_CUSTOMER = 25, // EXPLICITLY_SHARED_BUDGETS_PER_CUSTOMER IMPLICITLY_SHARED_BUDGETS_PER_CUSTOMER = 26, // IMPLICITLY_SHARED_BUDGETS_PER_CUSTOMER COMBINED_AUDIENCE_CRITERIA_PER_CAMPAIGN = 27, // COMBINED_AUDIENCE_CRITERIA_PER_CAMPAIGN NEGATIVE_KEYWORDS_PER_CAMPAIGN = 28, // NEGATIVE_KEYWORDS_PER_CAMPAIGN NEGATIVE_PLACEMENTS_PER_CAMPAIGN = 29, // NEGATIVE_PLACEMENTS_PER_CAMPAIGN GEO_TARGETS_PER_CAMPAIGN = 30, // GEO_TARGETS_PER_CAMPAIGN NEGATIVE_IP_BLOCKS_PER_CAMPAIGN = 32, // NEGATIVE_IP_BLOCKS_PER_CAMPAIGN PROXIMITIES_PER_CAMPAIGN = 33, // PROXIMITIES_PER_CAMPAIGN LISTING_SCOPES_PER_SHOPPING_CAMPAIGN = 34, // LISTING_SCOPES_PER_SHOPPING_CAMPAIGN LISTING_SCOPES_PER_NON_SHOPPING_CAMPAIGN = 35, // LISTING_SCOPES_PER_NON_SHOPPING_CAMPAIGN NEGATIVE_KEYWORDS_PER_SHARED_SET = 36, // NEGATIVE_KEYWORDS_PER_SHARED_SET NEGATIVE_PLACEMENTS_PER_SHARED_SET = 37, // NEGATIVE_PLACEMENTS_PER_SHARED_SET SHARED_SETS_PER_CUSTOMER_FOR_TYPE_DEFAULT = 40, // SHARED_SETS_PER_CUSTOMER_FOR_TYPE_DEFAULT SHARED_SETS_PER_CUSTOMER_FOR_NEGATIVE_PLACEMENT_LIST_LOWER = 41, // SHARED_SETS_PER_CUSTOMER_FOR_NEGATIVE_PLACEMENT_LIST_LOWER HOTEL_ADVANCE_BOOKING_WINDOW_BID_MODIFIERS_PER_AD_GROUP = 44, // HOTEL_ADVANCE_BOOKING_WINDOW_BID_MODIFIERS_PER_AD_GROUP BIDDING_STRATEGIES_PER_CUSTOMER = 45, // BIDDING_STRATEGIES_PER_CUSTOMER BASIC_USER_LISTS_PER_CUSTOMER = 47, // BASIC_USER_LISTS_PER_CUSTOMER LOGICAL_USER_LISTS_PER_CUSTOMER = 48, // LOGICAL_USER_LISTS_PER_CUSTOMER BASE_AD_GROUP_ADS_PER_CUSTOMER = 53, // BASE_AD_GROUP_ADS_PER_CUSTOMER EXPERIMENT_AD_GROUP_ADS_PER_CUSTOMER = 54, // EXPERIMENT_AD_GROUP_ADS_PER_CUSTOMER AD_GROUP_ADS_PER_CAMPAIGN = 55, // AD_GROUP_ADS_PER_CAMPAIGN TEXT_AND_OTHER_ADS_PER_AD_GROUP = 56, // TEXT_AND_OTHER_ADS_PER_AD_GROUP IMAGE_ADS_PER_AD_GROUP = 57, // IMAGE_ADS_PER_AD_GROUP SHOPPING_SMART_ADS_PER_AD_GROUP = 58, // SHOPPING_SMART_ADS_PER_AD_GROUP RESPONSIVE_SEARCH_ADS_PER_AD_GROUP = 59, // RESPONSIVE_SEARCH_ADS_PER_AD_GROUP APP_ADS_PER_AD_GROUP = 60, // APP_ADS_PER_AD_GROUP APP_ENGAGEMENT_ADS_PER_AD_GROUP = 61, // APP_ENGAGEMENT_ADS_PER_AD_GROUP LOCAL_ADS_PER_AD_GROUP = 62, // LOCAL_ADS_PER_AD_GROUP VIDEO_ADS_PER_AD_GROUP = 63, // VIDEO_ADS_PER_AD_GROUP LEAD_FORM_CAMPAIGN_ASSETS_PER_CAMPAIGN = 143, // LEAD_FORM_CAMPAIGN_ASSETS_PER_CAMPAIGN PROMOTION_CUSTOMER_ASSETS_PER_CUSTOMER = 79, // PROMOTION_CUSTOMER_ASSETS_PER_CUSTOMER PROMOTION_CAMPAIGN_ASSETS_PER_CAMPAIGN = 80, // PROMOTION_CAMPAIGN_ASSETS_PER_CAMPAIGN PROMOTION_AD_GROUP_ASSETS_PER_AD_GROUP = 81, // PROMOTION_AD_GROUP_ASSETS_PER_AD_GROUP CALLOUT_CUSTOMER_ASSETS_PER_CUSTOMER = 134, // CALLOUT_CUSTOMER_ASSETS_PER_CUSTOMER CALLOUT_CAMPAIGN_ASSETS_PER_CAMPAIGN = 135, // CALLOUT_CAMPAIGN_ASSETS_PER_CAMPAIGN CALLOUT_AD_GROUP_ASSETS_PER_AD_GROUP = 136, // CALLOUT_AD_GROUP_ASSETS_PER_AD_GROUP SITELINK_CUSTOMER_ASSETS_PER_CUSTOMER = 137, // SITELINK_CUSTOMER_ASSETS_PER_CUSTOMER SITELINK_CAMPAIGN_ASSETS_PER_CAMPAIGN = 138, // SITELINK_CAMPAIGN_ASSETS_PER_CAMPAIGN SITELINK_AD_GROUP_ASSETS_PER_AD_GROUP = 139, // SITELINK_AD_GROUP_ASSETS_PER_AD_GROUP STRUCTURED_SNIPPET_CUSTOMER_ASSETS_PER_CUSTOMER = 140, // STRUCTURED_SNIPPET_CUSTOMER_ASSETS_PER_CUSTOMER STRUCTURED_SNIPPET_CAMPAIGN_ASSETS_PER_CAMPAIGN = 141, // STRUCTURED_SNIPPET_CAMPAIGN_ASSETS_PER_CAMPAIGN STRUCTURED_SNIPPET_AD_GROUP_ASSETS_PER_AD_GROUP = 142, // STRUCTURED_SNIPPET_AD_GROUP_ASSETS_PER_AD_GROUP MOBILE_APP_CUSTOMER_ASSETS_PER_CUSTOMER = 144, // MOBILE_APP_CUSTOMER_ASSETS_PER_CUSTOMER MOBILE_APP_CAMPAIGN_ASSETS_PER_CAMPAIGN = 145, // MOBILE_APP_CAMPAIGN_ASSETS_PER_CAMPAIGN MOBILE_APP_AD_GROUP_ASSETS_PER_AD_GROUP = 146, // MOBILE_APP_AD_GROUP_ASSETS_PER_AD_GROUP HOTEL_CALLOUT_CUSTOMER_ASSETS_PER_CUSTOMER = 147, // HOTEL_CALLOUT_CUSTOMER_ASSETS_PER_CUSTOMER HOTEL_CALLOUT_CAMPAIGN_ASSETS_PER_CAMPAIGN = 148, // HOTEL_CALLOUT_CAMPAIGN_ASSETS_PER_CAMPAIGN HOTEL_CALLOUT_AD_GROUP_ASSETS_PER_AD_GROUP = 149, // HOTEL_CALLOUT_AD_GROUP_ASSETS_PER_AD_GROUP CALL_CUSTOMER_ASSETS_PER_CUSTOMER = 150, // CALL_CUSTOMER_ASSETS_PER_CUSTOMER CALL_CAMPAIGN_ASSETS_PER_CAMPAIGN = 151, // CALL_CAMPAIGN_ASSETS_PER_CAMPAIGN CALL_AD_GROUP_ASSETS_PER_AD_GROUP = 152, // CALL_AD_GROUP_ASSETS_PER_AD_GROUP PRICE_CUSTOMER_ASSETS_PER_CUSTOMER = 154, // PRICE_CUSTOMER_ASSETS_PER_CUSTOMER PRICE_CAMPAIGN_ASSETS_PER_CAMPAIGN = 155, // PRICE_CAMPAIGN_ASSETS_PER_CAMPAIGN PRICE_AD_GROUP_ASSETS_PER_AD_GROUP = 156, // PRICE_AD_GROUP_ASSETS_PER_AD_GROUP VERSIONS_PER_AD = 82, // VERSIONS_PER_AD USER_FEEDS_PER_CUSTOMER = 90, // USER_FEEDS_PER_CUSTOMER SYSTEM_FEEDS_PER_CUSTOMER = 91, // SYSTEM_FEEDS_PER_CUSTOMER FEED_ATTRIBUTES_PER_FEED = 92, // FEED_ATTRIBUTES_PER_FEED FEED_ITEMS_PER_CUSTOMER = 94, // FEED_ITEMS_PER_CUSTOMER CAMPAIGN_FEEDS_PER_CUSTOMER = 95, // CAMPAIGN_FEEDS_PER_CUSTOMER BASE_CAMPAIGN_FEEDS_PER_CUSTOMER = 96, // BASE_CAMPAIGN_FEEDS_PER_CUSTOMER EXPERIMENT_CAMPAIGN_FEEDS_PER_CUSTOMER = 109, // EXPERIMENT_CAMPAIGN_FEEDS_PER_CUSTOMER AD_GROUP_FEEDS_PER_CUSTOMER = 97, // AD_GROUP_FEEDS_PER_CUSTOMER BASE_AD_GROUP_FEEDS_PER_CUSTOMER = 98, // BASE_AD_GROUP_FEEDS_PER_CUSTOMER EXPERIMENT_AD_GROUP_FEEDS_PER_CUSTOMER = 110, // EXPERIMENT_AD_GROUP_FEEDS_PER_CUSTOMER AD_GROUP_FEEDS_PER_CAMPAIGN = 99, // AD_GROUP_FEEDS_PER_CAMPAIGN FEED_ITEM_SETS_PER_CUSTOMER = 100, // FEED_ITEM_SETS_PER_CUSTOMER FEED_ITEMS_PER_FEED_ITEM_SET = 101, // FEED_ITEMS_PER_FEED_ITEM_SET CAMPAIGN_EXPERIMENTS_PER_CUSTOMER = 112, // CAMPAIGN_EXPERIMENTS_PER_CUSTOMER EXPERIMENT_ARMS_PER_VIDEO_EXPERIMENT = 113, // EXPERIMENT_ARMS_PER_VIDEO_EXPERIMENT OWNED_LABELS_PER_CUSTOMER = 115, // OWNED_LABELS_PER_CUSTOMER LABELS_PER_CAMPAIGN = 117, // LABELS_PER_CAMPAIGN LABELS_PER_AD_GROUP = 118, // LABELS_PER_AD_GROUP LABELS_PER_AD_GROUP_AD = 119, // LABELS_PER_AD_GROUP_AD LABELS_PER_AD_GROUP_CRITERION = 120, // LABELS_PER_AD_GROUP_CRITERION TARGET_CUSTOMERS_PER_LABEL = 121, // TARGET_CUSTOMERS_PER_LABEL KEYWORD_PLANS_PER_USER_PER_CUSTOMER = 122, // KEYWORD_PLANS_PER_USER_PER_CUSTOMER KEYWORD_PLAN_AD_GROUP_KEYWORDS_PER_KEYWORD_PLAN = 123, // KEYWORD_PLAN_AD_GROUP_KEYWORDS_PER_KEYWORD_PLAN KEYWORD_PLAN_AD_GROUPS_PER_KEYWORD_PLAN = 124, // KEYWORD_PLAN_AD_GROUPS_PER_KEYWORD_PLAN KEYWORD_PLAN_NEGATIVE_KEYWORDS_PER_KEYWORD_PLAN = 125, // KEYWORD_PLAN_NEGATIVE_KEYWORDS_PER_KEYWORD_PLAN KEYWORD_PLAN_CAMPAIGNS_PER_KEYWORD_PLAN = 126, // KEYWORD_PLAN_CAMPAIGNS_PER_KEYWORD_PLAN CONVERSION_ACTIONS_PER_CUSTOMER = 128, // CONVERSION_ACTIONS_PER_CUSTOMER BATCH_JOB_OPERATIONS_PER_JOB = 130, // BATCH_JOB_OPERATIONS_PER_JOB BATCH_JOBS_PER_CUSTOMER = 131, // BATCH_JOBS_PER_CUSTOMER HOTEL_CHECK_IN_DATE_RANGE_BID_MODIFIERS_PER_AD_GROUP = 132, // HOTEL_CHECK_IN_DATE_RANGE_BID_MODIFIERS_PER_AD_GROUP } /** * @name ResponseContentTypeEnum.ResponseContentType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ResponseContentTypeEnum.ResponseContentType */ export enum ResponseContentType { UNSPECIFIED = 0, // UNSPECIFIED RESOURCE_NAME_ONLY = 1, // RESOURCE_NAME_ONLY MUTABLE_RESOURCE = 2, // MUTABLE_RESOURCE } /** * @name SearchTermTargetingStatusEnum.SearchTermTargetingStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/SearchTermTargetingStatusEnum.SearchTermTargetingStatus */ export enum SearchTermTargetingStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ADDED = 2, // ADDED EXCLUDED = 3, // EXCLUDED ADDED_EXCLUDED = 4, // ADDED_EXCLUDED NONE = 5, // NONE } /** * @name SeasonalityEventScopeEnum.SeasonalityEventScope * @link https://developers.google.com/google-ads/api/reference/rpc/v9/SeasonalityEventScopeEnum.SeasonalityEventScope */ export enum SeasonalityEventScope { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CUSTOMER = 2, // CUSTOMER CAMPAIGN = 4, // CAMPAIGN CHANNEL = 5, // CHANNEL } /** * @name SeasonalityEventStatusEnum.SeasonalityEventStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/SeasonalityEventStatusEnum.SeasonalityEventStatus */ export enum SeasonalityEventStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 4, // REMOVED } /** * @name SharedSetStatusEnum.SharedSetStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/SharedSetStatusEnum.SharedSetStatus */ export enum SharedSetStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED REMOVED = 3, // REMOVED } /** * @name SharedSetTypeEnum.SharedSetType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/SharedSetTypeEnum.SharedSetType */ export enum SharedSetType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN NEGATIVE_KEYWORDS = 2, // NEGATIVE_KEYWORDS NEGATIVE_PLACEMENTS = 3, // NEGATIVE_PLACEMENTS } /** * @name SimulationModificationMethodEnum.SimulationModificationMethod * @link https://developers.google.com/google-ads/api/reference/rpc/v9/SimulationModificationMethodEnum.SimulationModificationMethod */ export enum SimulationModificationMethod { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN UNIFORM = 2, // UNIFORM DEFAULT = 3, // DEFAULT SCALING = 4, // SCALING } /** * @name SimulationTypeEnum.SimulationType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/SimulationTypeEnum.SimulationType */ export enum SimulationType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CPC_BID = 2, // CPC_BID CPV_BID = 3, // CPV_BID TARGET_CPA = 4, // TARGET_CPA BID_MODIFIER = 5, // BID_MODIFIER TARGET_ROAS = 6, // TARGET_ROAS PERCENT_CPC_BID = 7, // PERCENT_CPC_BID TARGET_IMPRESSION_SHARE = 8, // TARGET_IMPRESSION_SHARE BUDGET = 9, // BUDGET } /** * @name SitelinkPlaceholderFieldEnum.SitelinkPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/SitelinkPlaceholderFieldEnum.SitelinkPlaceholderField */ export enum SitelinkPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN TEXT = 2, // TEXT LINE_1 = 3, // LINE_1 LINE_2 = 4, // LINE_2 FINAL_URLS = 5, // FINAL_URLS FINAL_MOBILE_URLS = 6, // FINAL_MOBILE_URLS TRACKING_URL = 7, // TRACKING_URL FINAL_URL_SUFFIX = 8, // FINAL_URL_SUFFIX } /** * @name SpendingLimitTypeEnum.SpendingLimitType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/SpendingLimitTypeEnum.SpendingLimitType */ export enum SpendingLimitType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN INFINITE = 2, // INFINITE } /** * @name StructuredSnippetPlaceholderFieldEnum.StructuredSnippetPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/StructuredSnippetPlaceholderFieldEnum.StructuredSnippetPlaceholderField */ export enum StructuredSnippetPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN HEADER = 2, // HEADER SNIPPETS = 3, // SNIPPETS } /** * @name SummaryRowSettingEnum.SummaryRowSetting * @link https://developers.google.com/google-ads/api/reference/rpc/v9/SummaryRowSettingEnum.SummaryRowSetting */ export enum SummaryRowSetting { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN NO_SUMMARY_ROW = 2, // NO_SUMMARY_ROW SUMMARY_ROW_WITH_RESULTS = 3, // SUMMARY_ROW_WITH_RESULTS SUMMARY_ROW_ONLY = 4, // SUMMARY_ROW_ONLY } /** * @name SystemManagedResourceSourceEnum.SystemManagedResourceSource * @link https://developers.google.com/google-ads/api/reference/rpc/v9/SystemManagedResourceSourceEnum.SystemManagedResourceSource */ export enum SystemManagedResourceSource { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN AD_VARIATIONS = 2, // AD_VARIATIONS } /** * @name TargetCpaOptInRecommendationGoalEnum.TargetCpaOptInRecommendationGoal * @link https://developers.google.com/google-ads/api/reference/rpc/v9/TargetCpaOptInRecommendationGoalEnum.TargetCpaOptInRecommendationGoal */ export enum TargetCpaOptInRecommendationGoal { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN SAME_COST = 2, // SAME_COST SAME_CONVERSIONS = 3, // SAME_CONVERSIONS SAME_CPA = 4, // SAME_CPA CLOSEST_CPA = 5, // CLOSEST_CPA } /** * @name TimeTypeEnum.TimeType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/TimeTypeEnum.TimeType */ export enum TimeType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN NOW = 2, // NOW FOREVER = 3, // FOREVER } /** * @name TravelPlaceholderFieldEnum.TravelPlaceholderField * @link https://developers.google.com/google-ads/api/reference/rpc/v9/TravelPlaceholderFieldEnum.TravelPlaceholderField */ export enum TravelPlaceholderField { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN DESTINATION_ID = 2, // DESTINATION_ID ORIGIN_ID = 3, // ORIGIN_ID TITLE = 4, // TITLE DESTINATION_NAME = 5, // DESTINATION_NAME ORIGIN_NAME = 6, // ORIGIN_NAME PRICE = 7, // PRICE FORMATTED_PRICE = 8, // FORMATTED_PRICE SALE_PRICE = 9, // SALE_PRICE FORMATTED_SALE_PRICE = 10, // FORMATTED_SALE_PRICE IMAGE_URL = 11, // IMAGE_URL CATEGORY = 12, // CATEGORY CONTEXTUAL_KEYWORDS = 13, // CONTEXTUAL_KEYWORDS DESTINATION_ADDRESS = 14, // DESTINATION_ADDRESS FINAL_URL = 15, // FINAL_URL FINAL_MOBILE_URLS = 16, // FINAL_MOBILE_URLS TRACKING_URL = 17, // TRACKING_URL ANDROID_APP_LINK = 18, // ANDROID_APP_LINK SIMILAR_DESTINATION_IDS = 19, // SIMILAR_DESTINATION_IDS IOS_APP_LINK = 20, // IOS_APP_LINK IOS_APP_STORE_ID = 21, // IOS_APP_STORE_ID } /** * @name UserInterestTaxonomyTypeEnum.UserInterestTaxonomyType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserInterestTaxonomyTypeEnum.UserInterestTaxonomyType */ export enum UserInterestTaxonomyType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN AFFINITY = 2, // AFFINITY IN_MARKET = 3, // IN_MARKET MOBILE_APP_INSTALL_USER = 4, // MOBILE_APP_INSTALL_USER VERTICAL_GEO = 5, // VERTICAL_GEO NEW_SMART_PHONE_USER = 6, // NEW_SMART_PHONE_USER } /** * @name UserListAccessStatusEnum.UserListAccessStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserListAccessStatusEnum.UserListAccessStatus */ export enum UserListAccessStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ENABLED = 2, // ENABLED DISABLED = 3, // DISABLED } /** * @name UserListClosingReasonEnum.UserListClosingReason * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserListClosingReasonEnum.UserListClosingReason */ export enum UserListClosingReason { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN UNUSED = 2, // UNUSED } /** * @name UserListMembershipStatusEnum.UserListMembershipStatus * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserListMembershipStatusEnum.UserListMembershipStatus */ export enum UserListMembershipStatus { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN OPEN = 2, // OPEN CLOSED = 3, // CLOSED } /** * @name UserListSizeRangeEnum.UserListSizeRange * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserListSizeRangeEnum.UserListSizeRange */ export enum UserListSizeRange { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN LESS_THAN_FIVE_HUNDRED = 2, // LESS_THAN_FIVE_HUNDRED LESS_THAN_ONE_THOUSAND = 3, // LESS_THAN_ONE_THOUSAND ONE_THOUSAND_TO_TEN_THOUSAND = 4, // ONE_THOUSAND_TO_TEN_THOUSAND TEN_THOUSAND_TO_FIFTY_THOUSAND = 5, // TEN_THOUSAND_TO_FIFTY_THOUSAND FIFTY_THOUSAND_TO_ONE_HUNDRED_THOUSAND = 6, // FIFTY_THOUSAND_TO_ONE_HUNDRED_THOUSAND ONE_HUNDRED_THOUSAND_TO_THREE_HUNDRED_THOUSAND = 7, // ONE_HUNDRED_THOUSAND_TO_THREE_HUNDRED_THOUSAND THREE_HUNDRED_THOUSAND_TO_FIVE_HUNDRED_THOUSAND = 8, // THREE_HUNDRED_THOUSAND_TO_FIVE_HUNDRED_THOUSAND FIVE_HUNDRED_THOUSAND_TO_ONE_MILLION = 9, // FIVE_HUNDRED_THOUSAND_TO_ONE_MILLION ONE_MILLION_TO_TWO_MILLION = 10, // ONE_MILLION_TO_TWO_MILLION TWO_MILLION_TO_THREE_MILLION = 11, // TWO_MILLION_TO_THREE_MILLION THREE_MILLION_TO_FIVE_MILLION = 12, // THREE_MILLION_TO_FIVE_MILLION FIVE_MILLION_TO_TEN_MILLION = 13, // FIVE_MILLION_TO_TEN_MILLION TEN_MILLION_TO_TWENTY_MILLION = 14, // TEN_MILLION_TO_TWENTY_MILLION TWENTY_MILLION_TO_THIRTY_MILLION = 15, // TWENTY_MILLION_TO_THIRTY_MILLION THIRTY_MILLION_TO_FIFTY_MILLION = 16, // THIRTY_MILLION_TO_FIFTY_MILLION OVER_FIFTY_MILLION = 17, // OVER_FIFTY_MILLION } /** * @name UserListTypeEnum.UserListType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/UserListTypeEnum.UserListType */ export enum UserListType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN REMARKETING = 2, // REMARKETING LOGICAL = 3, // LOGICAL EXTERNAL_REMARKETING = 4, // EXTERNAL_REMARKETING RULE_BASED = 5, // RULE_BASED SIMILAR = 6, // SIMILAR CRM_BASED = 7, // CRM_BASED } /** * @name ValueRuleDeviceTypeEnum.ValueRuleDeviceType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ValueRuleDeviceTypeEnum.ValueRuleDeviceType */ export enum ValueRuleDeviceType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN MOBILE = 2, // MOBILE DESKTOP = 3, // DESKTOP TABLET = 4, // TABLET } /** * @name ValueRuleGeoLocationMatchTypeEnum.ValueRuleGeoLocationMatchType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ValueRuleGeoLocationMatchTypeEnum.ValueRuleGeoLocationMatchType */ export enum ValueRuleGeoLocationMatchType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ANY = 2, // ANY LOCATION_OF_PRESENCE = 3, // LOCATION_OF_PRESENCE } /** * @name ValueRuleOperationEnum.ValueRuleOperation * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ValueRuleOperationEnum.ValueRuleOperation */ export enum ValueRuleOperation { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN ADD = 2, // ADD MULTIPLY = 3, // MULTIPLY SET = 4, // SET } /** * @name ValueRuleSetAttachmentTypeEnum.ValueRuleSetAttachmentType * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ValueRuleSetAttachmentTypeEnum.ValueRuleSetAttachmentType */ export enum ValueRuleSetAttachmentType { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN CUSTOMER = 2, // CUSTOMER CAMPAIGN = 3, // CAMPAIGN } /** * @name ValueRuleSetDimensionEnum.ValueRuleSetDimension * @link https://developers.google.com/google-ads/api/reference/rpc/v9/ValueRuleSetDimensionEnum.ValueRuleSetDimension */ export enum ValueRuleSetDimension { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN GEO_LOCATION = 2, // GEO_LOCATION DEVICE = 3, // DEVICE AUDIENCE = 4, // AUDIENCE } /** * @name VanityPharmaDisplayUrlModeEnum.VanityPharmaDisplayUrlMode * @link https://developers.google.com/google-ads/api/reference/rpc/v9/VanityPharmaDisplayUrlModeEnum.VanityPharmaDisplayUrlMode */ export enum VanityPharmaDisplayUrlMode { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN MANUFACTURER_WEBSITE_URL = 2, // MANUFACTURER_WEBSITE_URL WEBSITE_DESCRIPTION = 3, // WEBSITE_DESCRIPTION } /** * @name VanityPharmaTextEnum.VanityPharmaText * @link https://developers.google.com/google-ads/api/reference/rpc/v9/VanityPharmaTextEnum.VanityPharmaText */ export enum VanityPharmaText { UNSPECIFIED = 0, // UNSPECIFIED UNKNOWN = 1, // UNKNOWN PRESCRIPTION_TREATMENT_WEBSITE_EN = 2, // PRESCRIPTION_TREATMENT_WEBSITE_EN PRESCRIPTION_TREATMENT_WEBSITE_ES = 3, // PRESCRIPTION_TREATMENT_WEBSITE_ES PRESCRIPTION_DEVICE_WEBSITE_EN = 4, // PRESCRIPTION_DEVICE_WEBSITE_EN PRESCRIPTION_DEVICE_WEBSITE_ES = 5, // PRESCRIPTION_DEVICE_WEBSITE_ES MEDICAL_DEVICE_WEBSITE_EN = 6, // MEDICAL_DEVICE_WEBSITE_EN MEDICAL_DEVICE_WEBSITE_ES = 7, // MEDICAL_DEVICE_WEBSITE_ES PREVENTATIVE_TREATMENT_WEBSITE_EN = 8, // PREVENTATIVE_TREATMENT_WEBSITE_EN PREVENTATIVE_TREATMENT_WEBSITE_ES = 9, // PREVENTATIVE_TREATMENT_WEBSITE_ES PRESCRIPTION_CONTRACEPTION_WEBSITE_EN = 10, // PRESCRIPTION_CONTRACEPTION_WEBSITE_EN PRESCRIPTION_CONTRACEPTION_WEBSITE_ES = 11, // PRESCRIPTION_CONTRACEPTION_WEBSITE_ES PRESCRIPTION_VACCINE_WEBSITE_EN = 12, // PRESCRIPTION_VACCINE_WEBSITE_EN PRESCRIPTION_VACCINE_WEBSITE_ES = 13, // PRESCRIPTION_VACCINE_WEBSITE_ES } }
the_stack
* @module HyperModeling */ import { assert } from "@itwin/core-bentley"; import { SectionType } from "@itwin/core-common"; import { IModelApp, IModelConnection, ScreenViewport, tryImageElementFromUrl, ViewManip } from "@itwin/core-frontend"; import { registerTools } from "./Tools"; import { HyperModelingDecorator } from "./HyperModelingDecorator"; import { HyperModelingConfig, SectionGraphicsConfig, SectionMarkerConfig } from "./HyperModelingConfig"; import { SectionMarkerHandler } from "./SectionMarkerHandler"; /** @internal */ export interface MarkerData { readonly label: string; readonly image: HTMLImageElement | undefined; } interface Resources { readonly namespace?: string; readonly markers: { readonly section: MarkerData; readonly plan: MarkerData; readonly elevation: MarkerData; readonly detail: MarkerData; }; } interface MaybeInitialized { resources?: Resources; } interface Initialized { resources: Resources; } function assertInitialized(maybe: MaybeInitialized): asserts maybe is Initialized { if (undefined === maybe.resources) throw new Error("You must call HyperModeling.initialize before using the hypermodeling package"); } /** The API entry point for the hypermodeling package. Applications must call [[initialize]] and await the result before using the package. * The behavior of the package can be customized via a [[HyperModelingConfig]] supplied to [[initialize]], [[updateConfiguration]], or [[replaceConfiguration]]. * Hypermodeling mode can be enabled or disabled via [[startOrStop]], which returns a [[HyperModelingDecorator]] when enabling hypermodeling. * Consult the package's `README.md` for a description of the available functionality. * @public */ export class HyperModeling { /** @internal */ public static resources?: Resources; private static _markerHandler?: SectionMarkerHandler; private static _markerConfig: SectionMarkerConfig = {}; private static _graphicsConfig: SectionGraphicsConfig = {}; private static shutdown() { this.resources = undefined; this._markerHandler = undefined; this._markerConfig = {}; this._graphicsConfig = {}; } /** Returns whether the hypermodeling package is initialized. * @see [[HyperModeling.initialize]] to initialize the package. */ public static get isInitialized(): boolean { return undefined !== this.resources; } /** Invoke this method to initialize the hypermodeling package for use. You *must* await the result before using any of this package's APIs. * Typically an application would invoke this after [IModelApp.startup]($frontend), e.g., * ```ts * await IModelApp.startup(); * await HyperModeling.initialize(); * ``` * Calling this method again after the first initialization behaves the same as calling [[HyperModeling.replaceConfiguration]]. * @note The hypermodeling package will be reset to uninitialized after [IModelApp.shutdown]($frontend) is invoked. * @see [[replaceConfiguration]] and [[updateConfiguration]] to modify the configuration after initialization. */ public static async initialize(config?: HyperModelingConfig): Promise<void> { if (undefined !== this.resources) { this.replaceConfiguration(config); return; } // clean up if we're being shut down IModelApp.onBeforeShutdown.addListener(() => this.shutdown()); const namespace = "HyperModeling"; await IModelApp.localization.registerNamespace(namespace); const loadImages = [ tryImageElementFromUrl("section-marker.svg"), tryImageElementFromUrl("detail-marker.svg"), tryImageElementFromUrl("elevation-marker.svg"), tryImageElementFromUrl("plan-marker.svg"), ]; const images = await Promise.all(loadImages); this.resources = { namespace, markers: { section: { image: images[0], label: IModelApp.localization.getLocalizedString("HyperModeling:Message.SectionCallout") }, detail: { image: images[1], label: IModelApp.localization.getLocalizedString("HyperModeling:Message.DetailCallout") }, elevation: { image: images[2], label: IModelApp.localization.getLocalizedString("HyperModeling:Message.ElevationCallout") }, plan: { image: images[3], label: IModelApp.localization.getLocalizedString("HyperModeling:Message.PlanCallout") }, }, }; registerTools(namespace); this.replaceConfiguration(config); } private static async ensureInitialized(): Promise<void> { if (undefined === this.resources) await this.initialize(); assertInitialized(this); } /** Replaces the current package configuration, overwriting all previous settings. Passing `undefined` resets all settings to defaults. * @see [[HyperModeling.updateConfiguration]] for overriding specific aspects of the configuration. */ public static replaceConfiguration(config?: HyperModelingConfig): void { config = config ?? {}; this._markerHandler = config.markerHandler ?? new SectionMarkerHandler(); this._markerConfig = config.markers ? { ...config.markers } : {}; this._graphicsConfig = config.graphics ? { ...config.graphics } : {}; } /** Overrides specific aspects of the current package configuration. Any field that is not `undefined` will be replaced in the current configuration; * the rest will retain their current values. * @see [[HyperModeling.replaceConfiguration]]. */ public static updateConfiguration(config: HyperModelingConfig): void { this._markerHandler = config.markerHandler ?? this._markerHandler; if (config.markers) { this._markerConfig = { ignoreModelSelector: config.markers.ignoreModelSelector ?? this._markerConfig.ignoreModelSelector, ignoreCategorySelector: config.markers.ignoreCategorySelector ?? this._markerConfig.ignoreCategorySelector, hiddenSectionTypes: config.markers.hiddenSectionTypes ?? this._markerConfig.hiddenSectionTypes, }; } if (config.graphics) { this._graphicsConfig = { ignoreClip: config.graphics.ignoreClip ?? this._graphicsConfig.ignoreClip, debugClipVolumes: config.graphics.debugClipVolumes ?? this._graphicsConfig.debugClipVolumes, hideSectionGraphics: config.graphics.hideSectionGraphics ?? this._graphicsConfig.hideSectionGraphics, hideSheetAnnotations: config.graphics.hideSheetAnnotations ?? this._graphicsConfig.hideSheetAnnotations, }; IModelApp.viewManager.invalidateViewportScenes(); } } /** The handler that defines interactions with [[SectionMarker]]s. * @see [[initialize]] to override the default handler at package initialization. * @see [[updateConfiguration]] or [[replaceConfiguration]] to change the current handler. */ public static get markerHandler(): SectionMarkerHandler { assertInitialized(this); assert(undefined !== this._markerHandler); return this._markerHandler; } /** The current marker display configuration applied to any newly-created [[HyperModelingDecorator]]s. * @see [[initialize]] to override the default configuration at package initialization. * @see [[updateConfiguration]] or [[replaceConfiguration]] to change the current configuration. * @see [[HyperModelingDecorator.replaceConfiguration]] or [[HyperModelingDecorator.updateConfiguration]] to change the configuration for an existing decorator. */ public static get markerConfig(): SectionMarkerConfig { return this._markerConfig; } /** This graphics options applied to graphics displayed by all [[HyperModelingDecorator]]s. * @see [[updateConfiguration]] or [[replaceConfiguration]] to change the current configuration. */ public static get graphicsConfig(): SectionGraphicsConfig { return this._graphicsConfig; } /** Returns true if the specified iModel contains any [SectionDrawingLocation]($backend)s. Hypermodeling is based on section drawing locations, * so if none are present, hypermodeling features are not relevant to the iModel. Attempting to use those features with such an iModel is fine, * but probably not useful. */ public static async isSupportedForIModel(imodel: IModelConnection): Promise<boolean> { try { const nRows = await imodel.queryRowCount("SELECT ECInstanceId FROM bis.SectionDrawingLocation LIMIT 1"); return nRows > 0; } catch { // An iModel with a version of BisCore older than 1.0.11 will produce an expected "table not found" on the SectionDrawingLocation ECClass. return false; } } /** Returns whether hypermodeling is currently enabled for the specified viewport. * @see [[startOrStop]] to enable or disable hypermodeling for a viewport. */ public static isEnabledForViewport(viewport: ScreenViewport): boolean { return undefined !== HyperModelingDecorator.getForViewport(viewport); } /** Start or stop hypermodeling mode for the specified viewport. * Enabling hypermodeling registers and returns a [[HyperModelingDecorator]] to display [[SectionMarker]]s within the viewport. * Disabling hypermodeling removes that decorator. * @param viewport The hypermodeling viewport * @param start `true` to enter hypermodeling mode, `false` to exit, or `undefined` to toggle the current mode. * @returns The new decorator is hypermodeling was successfully enabled. * @note Enabling hypermodeling may fail if the viewport is not viewing a spatial model or if the viewport's iModel does not support hypermodeling. * @see [[start]] and [[stop]]. * @see [[isSupportedForIModel]]. */ public static async startOrStop(viewport: ScreenViewport, start?: boolean): Promise<HyperModelingDecorator | undefined> { // Help out the caller since we're async anyway... await this.ensureInitialized(); const decorator = HyperModelingDecorator.getForViewport(viewport); if (undefined === start) start = undefined === decorator; if (start) { return this._start(viewport); } else { decorator?.dispose(); return undefined; } } /** Start hypermodeling mode for the specified viewport if it is not currently enabled. * If hypermodeling is already enabled for the viewport, the existing decorator is returned; otherwise, a new decorator is created. * @param viewport The viewport for which to enable hypermodeling * @returns The decorator that implements hypermodeling features for the viewport, or `undefined` if hypermodeling could not be enabled. * @note Enabling hypermodeling may fail if the viewport is not viewing a spatial model or if the viewport's iModel does not support hypermodeling. */ public static async start(viewport: ScreenViewport): Promise<HyperModelingDecorator | undefined> { await this.ensureInitialized(); return this._start(viewport); } private static async _start(viewport: ScreenViewport): Promise<HyperModelingDecorator | undefined> { assertInitialized(this); if (!viewport.view.isSpatialView()) return undefined; let decorator = HyperModelingDecorator.getForViewport(viewport); if (!decorator) decorator = await HyperModelingDecorator.create(viewport, this._markerConfig); if (undefined !== decorator && viewport.view.isCameraOn) { // We want the 2d graphics to align with the 3d geometry. Perspective ruins that. viewport.view.turnCameraOff(); ViewManip.fitView(viewport, false, { noSaveInUndo: true }); viewport.clearViewUndo(); } return decorator; } /** Stop hypermodeling mode for the specified viewport if it is currently enabled. This disposes of the [[HyperModelingDecorator]] associated with the viewport. * @see [[start]] to enable hypermodeling for a viewport. * @see [[startOrStop]] to toggle hypermodeling mode. */ public static stop(viewport: ScreenViewport): void { const decorator = HyperModelingDecorator.getForViewport(viewport); decorator?.dispose(); } /** @internal */ public static get namespace(): string | undefined { assertInitialized(this); return this.resources.namespace; } /** @internal */ public static getMarkerData(type: SectionType): MarkerData { assertInitialized(this); switch (type) { case SectionType.Plan: return this.resources.markers.plan; case SectionType.Elevation: return this.resources.markers.elevation; case SectionType.Detail: return this.resources.markers.detail; default: return this.resources.markers.section; } } }
the_stack
import {TextEditor, TextDocument, Range, Position, Selection, window} from 'vscode'; // Functions based on editor utils in proto-repl https://github.com/jasongilman/proto-repl export namespace EditorUtils { export class Scope { type: string; range: Range; constructor(t: string, r: Range) { this.type = t; this.range = r; } containsPosition(position: Position) : boolean { return this.range.start.isBeforeOrEqual(position) && this.range.end.isAfterOrEqual(position); } } // Escapes the Clojure code and places it in quotations export function escapeClojureCodeInString(code: string): string { let escaped = code.replace(/\\/g,"\\\\").replace(/"/g, "\\\""); return `\"${escaped}\"`; } export function getTopLevelForms(document: TextDocument): Range[] { var forms: Range[]; for (var i=0; i < document.lineCount; i++) { let line = document.lineAt(i); if (!line.isEmptyOrWhitespace) { // look for open or close parens/brackets or ; var inString = false; for (var j=0; j < line.text.length; j++) { let c = line.text.charAt(j); //if (c) if (["(", "[", "{"].indexOf(c) != -1) { } } } } return forms; } // Returns true if the position is in a comment // export function inComment(editor: TextEditor, position: Position) { // let text = editor.document.getText(); // let lines = text.split("\n"); // let offset = editor.document.offsetAt(position); // } // Returns true if the given position is in a string // export function isInString(editor: TextEditor, position: Position) { // let offset = editor.document.offsetAt(position); // let text = editor.document.getText(); // // find the position of all the quotation marks // var start = 0; // var inQuotes = false; // while (start != -1 && start < offset) { // start = text.indexOf("\""); // if (start != -1 && start < offset && text[start - 1] != "\\") { // inQuotes = !inQuotes; // } // } // return inQuotes; // } function makeRange(document: TextDocument, start: number, end: number) { let startPos = document.positionAt(start); let endPos = document.positionAt(end); return new Range(startPos, endPos); } // Returns the various scopes (comment, string) for a document and their ranges export function getScopes(document: TextDocument): Scope[] { var rval: Scope[] = new Array<Scope>(); var inString = false; var inComment = false; var rangeStart: number; let text = document.getText(); // iterate over all the characters in the document for (var i = 0; i < text.length; i++) { let currentChar = text[i]; if (inString) { if (currentChar == "\"") { inString = false; rval.push(new Scope("string", makeRange(document, rangeStart, i))); } } else if (inComment) { if (currentChar == "\n") { inComment = false; rval.push(new Scope("comment", makeRange(document, rangeStart, i))); } } else if (currentChar == "\"") { inString = true; rangeStart = i; } else if (currentChar == ";") { inComment = true; rangeStart = i; } } return rval; } function scopesContainPosition(scopes: Scope[], position: Position) { for (var scope of scopes) { if (scope.containsPosition(position)) { return true; } } return false; } //Find the innermost form containing the cursor export function getInnermostFormRange(document: TextDocument, position: Position) { if (!document) { return; // No open document } let scopes = getScopes(document); let offset = document.offsetAt(position); // find the form containing the offset let text = document.getText(); var start = -1; var end = -1; // find opening brace/paren for (var i = offset; i >= 0; i--) { let position = document.positionAt(i); if (!scopesContainPosition(scopes, position)) { let currentChar = text[i]; if (currentChar == "{") { if (i - 1 >= 0 && text[i-1] == "#") { start = i - 1; } else { start = i; } break; } else if (currentChar == "(") { if (i - 1 >= 0 && text[i-1] == "#") { start = i - 1; } else { start = i; } break; } else if (currentChar == "[") { start = i; break; } } } // find ending brace/paren for (var i=offset; i < text.length; i++) { let position = document.positionAt(i); if(!scopesContainPosition(scopes, position)) { let currentChar = text[i]; if (currentChar == "}" || currentChar == "]" || currentChar == ")") { end = i; break; } } } let startPos = document.positionAt(start); let endPos = document.positionAt(end); return new Range(startPos, endPos); } export function getInnermostForm(document: TextDocument, position: Position) { if (!document) { return; // No open document } const range = getInnermostFormRange(document, position); if (!range) { return } return document.getText(range); } // Find the argument position of the current document position and the function name export function getArgumentSignature(document: TextDocument, position: Position): [string, number] { let posIndex = document.offsetAt(position); const formOffsets = findContainingBracketPositions(document.getText(), posIndex); if (!formOffsets) { return; } const startPos = document.positionAt(formOffsets[0]); const endPos = document.positionAt(formOffsets[1]); const formRange = new Range(startPos, endPos); const form = document.getText(formRange); // only return args for function forms if(form && form.match(/\(.*/)) { // char index in form of position const posCharIndex = document.offsetAt(position) - formOffsets[0]; // the part of the form to the left of the position const leftPart = form.substr(0, posCharIndex); const innerElementsStr = leftPart.replace("(", "").replace("\n", " "); // split the string on whitespace or comma and remove any empty strings const innerElements = innerElementsStr.split(/\s|,/).filter((val) => { return val.length != 0; }); if (innerElements.length < 1) { return; } const func = innerElements[0]; let argIndex = innerElements.length - 2; // if the character leftmost of the position is whitespace (or a comma) then // we have moved on to the next argument position if (innerElementsStr.match(/^.*(\s|,)$/)) { argIndex = argIndex + 1; } return [func, argIndex]; } } // Find the symbol under the cursor export function getSymobleUnderCursor(editor: TextEditor){ if (!editor) { return; // No open text editor } var position = editor.selection.active; let wordRange = editor.document.getWordRangeAtPosition(position); var sym = editor.document.getText(wordRange); return sym; } // Find the top level form containing the cursor export function getTopLevelFormForCursor(editor: TextEditor) { if (!editor) { return; // No open text editor } var position = editor.selection.active; } // Finds a Clojure Namespace declaration in the editor and returns the name // of the namespace. export function findNSDeclaration(code: string) { let regex = /\(ns(\s+\^\{[\s\S]*?\})?\s+([\w\.\-_\d\*\+!\?]+)/; var ns = null; let match = regex.exec(code); if (match) { ns = match[2]; } return ns; } // Find the namespace for the currently open file export function findNSForCurrentEditor(editor: TextEditor): string { // get the contents of the current edtior if (!editor) { return; // No open text editor } const text = editor.document.getText(); return findNSDeclaration(text); } // Find the positions of the brackets that contain the given start and optional end positions. // Bracket in this context means parenthesis, square bracket, or squiggly bracket. export function findContainingBracketPositions(text: string, startPosition: number, endPosition?: number) : Array<number> { var startPos = startPosition; var endPos:number= startPosition; if (endPosition) { endPos = endPosition; } // find opening bracket var closingParenCount = 0; var closingSquareBracketCount = 0; var closingSquigglyBracketcount = 0; var pOpen; var pClose; for (pOpen = startPosition - 1; pOpen > -1; pOpen--) { let pChar = text[pOpen]; if (pChar == '(') { if (closingParenCount == 0) { break; } else { closingParenCount -= 1; } } if (pChar == ')') { closingParenCount += 1; } if (pChar == '[') { if (closingSquareBracketCount == 0) { break; } else { closingSquareBracketCount -= 1; } } if (pChar == ']') { closingSquareBracketCount += 1; } if (pChar == '{') { if (closingSquigglyBracketcount == 0) { break; } else { closingSquigglyBracketcount -= 1; } } if (pChar == '}') { closingSquigglyBracketcount += 1; } } // Look for the closing matching bracket if we found an opening bracket if (pOpen != -1) { var openingParenCount = 0; var openingSquareBracketCount = 0; var openingSquigglyBracketCount = 0; for (pClose = endPos; pClose < text.length; pClose++) { let eChar = text[pClose]; if (eChar == ')') { if (openingParenCount == 0) { break; } else { openingParenCount -= 1; } } if (eChar == '(') { openingParenCount += 1; } if (eChar == ']') { if (openingSquareBracketCount == 0) { break; } else { openingSquareBracketCount -= 1; } } if (eChar == '[') { openingSquareBracketCount += 1; } if (eChar == '}') { if (openingSquigglyBracketCount == 0) { break; } else { openingSquigglyBracketCount -= 1; } } if (eChar == '{') { openingSquigglyBracketCount += 1; } } // Sanity check to make sure bracket types match let oChar = text[pOpen]; let eChar = text[pClose]; if ((oChar == '(' && eChar == ')') || (oChar == '[' && eChar == ']') || (oChar == '{' && eChar == '}')) { startPos = pOpen; endPos = pClose + 1; } } return [startPos, endPos]; } // Finds the Range occupied by the namespace declaration export function findNSDeclarationRange(editor: TextEditor): Range { if (!editor) { return; } const text = editor.document.getText(); let nsDeclare = "(ns"; let charPos = text.indexOf(nsDeclare); if (charPos != -1) { const positions = findContainingBracketPositions(text, charPos + 1); const editStart = editor.document.positionAt(positions[0]); const editEnd = editor.document.positionAt(positions[1]); return new Range(editStart, editEnd); } return; } // Expand selection to the next-outermost brackets containing the cursor. // Repeated invocations will expand selection to increasingly outer brackets. export function selectBrackets(editor: TextEditor) { if (!editor) { return; // no open text editor } let document = editor.document; var startIndex = -1; var endIndex = document.getText().length; let selection = editor.selection; var newSelectionIndices; // If we have a selection and the cursor is not outside it, use it to find brackets if (selection.contains(selection.active)) { startIndex = document.offsetAt(selection.start); endIndex = document.offsetAt(selection.end); newSelectionIndices = findContainingBracketPositions(document.getText(), startIndex, endIndex); } else { startIndex = document.offsetAt(selection.active); newSelectionIndices = findContainingBracketPositions(document.getText(), startIndex); } let anchor = document.positionAt(newSelectionIndices[0]); let active = document.positionAt(newSelectionIndices[1]); let newSelection = new Selection(anchor, active); editor.selection = newSelection; } // Get the file path for the given editor export function getFilePath(editor: TextEditor): string { if (!editor) { return; // no open text editor } return editor.document.fileName; } }
the_stack
import { SqrlInstance } from "../function/Instance"; import SqrlAst from "./SqrlAst"; import invariant from "../jslib/invariant"; import sqrlErrorWrap from "../compile/sqrlErrorWrap"; import { sqrlInvariant } from "../api/parse"; import { Ast, jsonAst } from "./Ast"; import { Expr, ConstantExpr, walkExpr, Slot, CallExpr } from "../expr/Expr"; import { SqrlSlot } from "../slot/SqrlSlot"; import { SqrlObject } from "../object/SqrlObject"; import { SqrlCompiledOutput } from "../compile/SqrlCompiledOutput"; const binaryOperatorToFunction = { "=": "_cmpE", "!=": "_cmpNE", ">": "_cmpG", ">=": "_cmpGE", "<": "_cmpL", "<=": "_cmpLE", "-": "_subtract", "+": "_add", "*": "_multiply", "%": "_modulo", or: "_or", and: "_and", contains: "_contains", }; class AstExprState { currentIterator: string | null = null; constructor( public instance: SqrlInstance, private compiledSqrl: SqrlCompiledOutput ) {} costForExpr(expr: Expr): number { if (expr.type === "value") { return this.compiledSqrl.getSlotCost(expr.slot.name).recursiveCost; } else if (expr.type === "call") { return this.instance.getCost(expr.func); } return 1; } sortExprsByCostAsc(exprs: Expr[]): Expr[] { return exprs.sort((left, right): number => { return this.costForExpr(left) - this.costForExpr(right); }); } hasSlot(name: string): boolean { return this.compiledSqrl.slots.hasOwnProperty(name); } getSlot(name: string): SqrlSlot { invariant( this.compiledSqrl.slots.hasOwnProperty(name), "Could not find slot with given name" ); return this.compiledSqrl.slots[name]; } exprForSlot(name: string): Expr { return this.compiledSqrl.exprForSlot(name); } wrapIterator<T>(iterator: string, callback: () => T): T { invariant( this.currentIterator === null, "Multiple levels of iterators are not supported." ); this.currentIterator = iterator; const result: T = callback(); this.currentIterator = null; return result; } } function constantExpr(value): ConstantExpr { return { type: "constant", value, }; } function ifExpr(exprs: Expr[]): Expr { const condition = exprs[0]; if (condition.type === "constant") { if (SqrlObject.isTruthy(condition.value)) { return exprs[1]; } else { return exprs[2]; } } return { type: "if", exprs, // We can safely load the condition upfront, but be lazy on the other expressions load: condition.load, }; } function _astToExprList( exprAsts: Ast[], state: AstExprState, props: Expr, lazy = false ) { const exprs = exprAsts.map((exprAst) => _astToExpr(exprAst, state)); return { load: lazy ? [] : exprLoad(exprs), exprs, ...props, }; } function slotExpr(state: AstExprState, name: string): Expr { const slot = state.getSlot(name); // Reduce references to a constant slot to just that slot (if the value is simple) const slotExpr = state.exprForSlot(name); if ( slotExpr.type === "constant" && (slotExpr.value === null || typeof slotExpr.value === "boolean" || typeof slotExpr.value === "string" || typeof slotExpr.value === "number" || (Array.isArray(slotExpr.value) && !slotExpr.value.length)) ) { return slotExpr; } return { type: "value", load: [slot], slot, }; } function boolExpr(state: AstExprState, expr: Expr): Expr { return { load: expr.load, type: "call", func: "bool", exprs: [expr], }; } function exprLoad(exprs: Expr[]): Slot[] { const load: Set<Slot> = new Set(); for (const expr of exprs) { if (expr.load) { expr.load.forEach((slot) => load.add(slot)); } } return Array.from(load); } function exprOrderedMinimalLoad(exprs: Expr[]): Slot[] { /** * For and/or we only want to preload the first part of the expression, *but* * in the case of an iterator, the code (currently) cannot handle a load/execute * so instead we load everything. */ let hasIterator = false; for (const expr of exprs) { walkExpr(expr, (node) => { hasIterator = hasIterator || node.type === "iterator"; }); } if (hasIterator) { const set: Set<Slot> = new Set(); exprs.forEach((expr) => { expr.load.forEach((slot) => set.add(slot)); }); return Array.from(set); } else { return exprs[0].load || []; } } function andExpr(state: AstExprState, args: Ast[]): Expr { let hadFalse = false; let hadNull = false; const exprs = args .map((arg) => _astToExpr(arg, state)) .filter((expr) => { if (expr.type === "constant") { if (SqrlObject.isTruthy(expr.value)) { // Filter out truthy values return false; } else if (expr.value === null) { hadNull = true; } else { hadFalse = true; } } return true; }); if (hadFalse) { return constantExpr(false); } else if (hadNull) { return constantExpr(null); } else if (exprs.length === 0) { return constantExpr(true); } else if (exprs.length === 1) { return boolExpr(state, exprs[0]); } const sortedExprs = state.sortExprsByCostAsc(exprs); return { type: "call", func: "_andSequential", exprs: [{ type: "state" }, ...sortedExprs], load: exprOrderedMinimalLoad(sortedExprs), }; } function orExpr(state: AstExprState, args: Ast[]): Expr { let hadTrue = false; let hadNull = false; const exprs = args .map((arg) => _astToExpr(arg, state)) .filter((expr) => { if (expr.type === "constant") { if (SqrlObject.isTruthy(expr.value)) { hadTrue = true; } else if (expr.value === null) { hadNull = true; return false; } else { return false; } } return true; }); if (hadTrue) { return constantExpr(true); } else if (exprs.length === 0) { return constantExpr(hadNull ? null : false); } else if (hadNull) { // If we saw a null but still have other values, add it back exprs.push(constantExpr(null)); } else if (exprs.length === 1) { return boolExpr(state, exprs[0]); } const sortedExprs = state.sortExprsByCostAsc(exprs); return makeCall( "_orSequential", [{ type: "state" }, ...sortedExprs], exprOrderedMinimalLoad(sortedExprs) ); } function makeCall(func: string, exprs: Expr[], load?: Slot[]): CallExpr { if (!load) { load = exprLoad(exprs); } return { type: "call", func, exprs, load, }; } function callExpr(state: AstExprState, func: string, args: Ast[]): Expr { const { instance } = state; const props = instance.getProps(func); if (props.pure) { const argExprs = args.map((arg) => _astToExpr(arg, state)); const allConstant = argExprs.every((expr) => expr.type === "constant"); if (allConstant) { const constantExprs: ConstantExpr[] = argExprs.map((expr) => { // @TODO: This is an unfortunate hack to make typescript happy if (expr.type !== "constant") { throw new Error("expected constant"); } return expr; }); const rv = state.instance.pureFunction[func]( ...constantExprs.map((expr) => expr.value) ); return constantExpr(rv); } } if (func === "_slotWait") { return Object.assign(constantExpr(true), { load: args .filter((arg) => { // Filter out wait for anything that is constant const expr = _astToExpr(arg, state); return expr.type !== "constant"; }) .map((arg) => { if (arg.type !== "slot") { throw new Error("Expected slot ast for wait call"); } return state.getSlot(arg.slotName); }), }); } // If the function takes a promise const lazy = !!props.lazyArguments; return _astToExprList(args, state, { type: "call", func }, lazy); } function _astToExpr(ast: Ast, state: AstExprState): Expr { return sqrlErrorWrap( { location: ast.location, }, (): Expr => { if (ast.type === "iterator") { invariant( state.currentIterator === ast.name, `Expected currentIterator to be %s was %s`, ast.name, state.currentIterator ); return { type: "iterator", name: ast.name, }; } else if (ast.type === "feature") { sqrlInvariant( ast, state.hasSlot(ast.value), "Feature was not defined: %s", ast.value ); return slotExpr(state, ast.value); } else if (ast.type === "slot") { return slotExpr(state, ast.slotName); } else if (ast.type === "state") { return { type: "state" }; } else if (ast.type === "whenCause") { if (ast.slotName) { return slotExpr(state, ast.slotName); } else { return constantExpr(null); } } else if (ast.type === "if") { const exprAsts: Ast[] = [ ast.condition, ast.trueBranch, ast.falseBranch, ]; return ifExpr(exprAsts.map((ast) => _astToExpr(ast, state))); } else if (ast.type === "switch") { let result = ast.defaultCase ? _astToExpr(ast.defaultCase, state) : constantExpr(null); for (const { expr, where } of ast.cases) { // @TODO: Investigate old code if tests are failing due to where clauses: // const trueExpr = state.wrapWhere(truthTableWhere, () => _astToExpr(expr, state)); const trueExpr = _astToExpr(expr, state); if (SqrlAst.isConstantTrue(where)) { result = trueExpr; } else { result = ifExpr([_astToExpr(where, state), trueExpr, result]); } } return result; } else if (ast.type === "call" || ast.type === "registeredCall") { const func = ast.func; const location = ast.location || null; return sqrlErrorWrap({ location }, () => { return callExpr(state, func, ast.args); }); } else if (ast.type === "listComprehension") { // The value might still appear as a feature, so make sure to ignore it return state.wrapIterator(ast.iterator.name, () => { return _astToExprList([ast.input, ast.output, ast.where], state, { type: "listComprehension", iterator: ast.iterator.name, }); }); } else if (ast.type === "not") { return callExpr(state, "_not", [ast.expr]); } else if (ast.type === "constant") { return constantExpr(ast.value); } else if (ast.type === "binary_expr" || ast.type === "boolean_expr") { let func: string; let args = [ast.left, ast.right]; if (ast.operator === "or" || ast.operator === "and") { let nextAst = args[args.length - 1]; while ( nextAst.type === "boolean_expr" && nextAst.operator === ast.operator ) { args = [ ...args.slice(0, args.length - 1), nextAst.left, nextAst.right, ]; nextAst = args[args.length - 1]; } } if (ast.operator === "in") { func = "_contains"; args.reverse(); } else if (ast.operator === "/") { args.unshift({ type: "state" }); func = "_divide"; } else if (ast.operator === "%") { args.unshift({ type: "state" }); func = "_modulo"; } else if (ast.operator === "or") { return orExpr(state, args); } else if (ast.operator === "and") { return andExpr(state, args); } else if (ast.operator === "is" || ast.operator === "is not") { invariant( args.length === 2 && SqrlAst.isConstantNull(args[1]), "Expected `null` value for right-hand side of IS" ); let expr = callExpr(state, "_isNull", [args[0]]); if (ast.operator === "is not") { expr = makeCall("_not", [expr]); } return expr; } else { invariant( binaryOperatorToFunction.hasOwnProperty(ast.operator), "Could not find function for binary operator:: %s", ast.operator ); func = binaryOperatorToFunction[ast.operator]; } return callExpr(state, func, args); } else if (ast.type === "list") { return _astToExprList(ast.exprs, state, { type: "list", }); } else { throw new Error("Unhandled ast: " + jsonAst(ast)); } } ); } function _exprExtractLoad(expr: Expr, loaded: Set<Slot> = new Set()): Expr { const load: Set<Slot> = new Set(); (expr.load || []).forEach((slot) => { if (!loaded.has(slot)) { load.add(slot); } }); // @TODO: reduce copying? expr = Object.assign({}, expr); delete expr.load; if (load.size) { return { type: "load", load: Array.from(load), exprs: [_exprExtractLoad(expr, new Set([...load, ...loaded]))], }; } if (expr.exprs) { expr.exprs = expr.exprs.map((e) => _exprExtractLoad(e, loaded)); } return expr; } export function processExprAst( ast: Ast, compiledSqrl: SqrlCompiledOutput, instance: SqrlInstance ): Expr { const astExprState = new AstExprState(instance, compiledSqrl); return _exprExtractLoad(_astToExpr(ast, astExprState)); }
the_stack
import * as angular from 'angular'; import * as _ from "underscore"; import {moduleName} from "../../module-name"; import {AccessControlService} from '../../../../services/AccessControlService'; import {StateService} from '@uirouter/core'; import {RegisterTemplateServiceFactory} from '../../../services/RegisterTemplateServiceFactory'; import {BroadcastService} from '../../../../services/broadcast-service'; import {UiComponentsService} from '../../../services/UiComponentsService'; export class RegisterSelectTemplateController { templates: any = []; model: any; stepNumber: any; stepIndex: any; template: any = null; stepperController: any = null; registeredTemplateId: any; nifiTemplateId: any; isValid: any; isNew: boolean; /** * Error message to be displayed if {@code isValid} is false * @type {null} */ errorMessage: any = null; /** * Indicates if admin operations are allowed. * @type {boolean} */ allowAdmin: any = false; /** * Indicates if edit operations are allowed. * @type {boolean} */ allowEdit: any = false; /** * Flag to indicate the template is loading * Used for PRogress * @type {boolean} */ loadingTemplate: boolean = false; /** * Flag to indicate the select template list is loading * @type {boolean} */ fetchingTemplateList: boolean = false; templateTableOptions: any; allowAccessControl: any; allowExport: any; templateNavigationLinks: any; static readonly $inject = ["$scope", "$http", "$mdDialog", "$mdToast", "$timeout", "$q", "$state", "RestUrlService", "RegisterTemplateService", "StateService", "AccessControlService", "EntityAccessControlService", "UiComponentsService", "AngularModuleExtensionService", "BroadcastService"]; constructor(private $scope: any, private $http: angular.IHttpService, private $mdDialog: angular.material.IDialogService, private $mdToast: angular.material.IToastService, private $timeout: angular.ITimeoutService , private $q: angular.IQService, private $state: StateService, private RestUrlService: any, private registerTemplateService: RegisterTemplateServiceFactory, private StateService: any , private accessControlService: AccessControlService, private EntityAccesControlService: any, private uiComponentsService: UiComponentsService , private AngularModuleExtensionService: any, private broadcastService: BroadcastService) { this.model = this.registerTemplateService.model; this.registeredTemplateId = this.model.id; this.isNew = (this.model.nifiTemplateId == undefined); this.nifiTemplateId = this.model.nifiTemplateId; this.isValid = this.registeredTemplateId !== null; this.templateNavigationLinks = AngularModuleExtensionService.getTemplateNavigation(); /** * The possible options to choose how this template should be displayed in the Feed Stepper * @type {Array.<TemplateTableOption>} */ this.templateTableOptions = [{type: 'NO_TABLE', displayName: 'No table customization', description: 'User will not be given option to customize destination table'}]; this.uiComponentsService.getTemplateTableOptions() .then((templateTableOptions: any) => { Array.prototype.push.apply(this.templateTableOptions, templateTableOptions); }); /** * Get notified when a already registered template is selected and loaded from the previous screen */ this.broadcastService.subscribe($scope, "REGISTERED_TEMPLATE_LOADED", () => this.onRegisteredTemplateLoaded()); $scope.$watch(() => { return this.model.loading; }, (newVal: any) => { if (newVal === false) { this.initTemplateTableOptions(); this.hideProgress(); } }); this.getTemplates(); accessControlService.getUserAllowedActions() .then((actionSet: any) => { this.allowEdit = accessControlService.hasAction(AccessControlService.TEMPLATES_EDIT, actionSet.actions); this.allowAdmin = accessControlService.hasAction(AccessControlService.TEMPLATES_ADMIN, actionSet.actions); this.allowExport = accessControlService.hasAction(AccessControlService.TEMPLATES_EXPORT, actionSet.actions); }); }; // setup the Stepper types initTemplateTableOptions = () => { if (this.model.templateTableOption == null) { if (this.model.defineTable) { this.model.templateTableOption = 'DEFINE_TABLE' } else if (this.model.dataTransformation) { this.model.templateTableOption = 'DATA_TRANSFORMATION' } else if (this.model.reusableTemplate) { this.model.templateTableOption = 'COMMON_REUSABLE_TEMPLATE' } else { this.model.templateTableOption = 'NO_TABLE' } } }; changeTemplate = () => { this.errorMessage = null; this.loadingTemplate = true; this.showProgress(); //Wait for the properties to come back before allowing hte user to go to the next step var selectedTemplate = this.findSelectedTemplate(); var templateName = null; if (selectedTemplate != null && selectedTemplate != undefined) { templateName = selectedTemplate.name; } this.registerTemplateService.loadTemplateWithProperties(null, this.nifiTemplateId, templateName).then((response: any) => { this.registerTemplateService.warnInvalidProcessorNames(); this.$q.when(this.registerTemplateService.checkTemplateAccess()).then((accessResponse: any) => { this.isValid = accessResponse.isValid; this.allowAdmin = accessResponse.allowAdmin; this.allowEdit = accessResponse.allowEdit; this.allowAccessControl = accessResponse.allowAccessControl; if (!accessResponse.isValid) { //PREVENT access this.errorMessage = "Access Denied. You are unable to edit the template. "; } else { if (!this.allowAccessControl) { //deactivate the access control step this.stepperController.deactivateStep(3); } else { this.stepperController.activateStep(3); } } this.loadingTemplate = false; this.hideProgress(); }); }, (err: any) => { this.registerTemplateService.resetModel(); this.errorMessage = (angular.isDefined(err.data) && angular.isDefined(err.data.message)) ? err.data.message : "An Error was found loading this template. Please ensure you have access to edit this template." this.loadingTemplate = false; this.hideProgress(); }); } disableTemplate = () => { if (this.model.id) { this.registerTemplateService.disableTemplate(this.model.id) } } enableTemplate = () => { if (this.model.id) { this.registerTemplateService.enableTemplate(this.model.id) } } deleteTemplateError = (errorMsg: any) => { // Display error message var msg = "<p>The template cannot be deleted at this time.</p><p>"; msg += angular.isString(errorMsg) ? _.escape(errorMsg) : "Please try again later."; msg += "</p>"; this.$mdDialog.hide(); this.$mdDialog.show( this.$mdDialog.alert() .ariaLabel("Error deleting the template") .clickOutsideToClose(true) .htmlContent(msg) .ok("Got it!") .parent(document.body) .title("Error deleting the template")); } deleteTemplate = () => { if (this.model.id) { this.registerTemplateService.deleteTemplate(this.model.id).then((response: any) => { if (response.data && response.data.status == 'success') { this.model.state = "DELETED"; this.$mdToast.show( this.$mdToast.simple() .textContent('Successfully deleted the template ') .hideDelay(3000) ); this.registerTemplateService.resetModel(); this.StateService.FeedManager().Template().navigateToRegisteredTemplates(); } else { this.deleteTemplateError(response.data.message) } }, (response: any) => { this.deleteTemplateError(response.data.message) }); } } /** * Displays a confirmation dialog for deleting the feed. */ confirmDeleteTemplate = () => { var $dialogScope = this.$scope.$new(); $dialogScope.dialog = this.$mdDialog; $dialogScope.vm = this; this.$mdDialog.show({ escapeToClose: false, fullscreen: true, parent: angular.element(document.body), scope: $dialogScope, templateUrl: "./template-delete-dialog.html" }); }; publishTemplate = (overwriteParam: boolean) => { if (this.model.id) { this.$http.get("/proxy/v1/repository/templates/publish/" + this.model.id + "?overwrite=" + overwriteParam).then((response: any) => { this.$mdToast.show( this.$mdToast.simple() .textContent('Successfully published template to repository.') .hideDelay(3000) ); this.StateService.FeedManager().Template().navigateToRegisteredTemplates(); }, (response: any) => { this.publishTemplateError(response.data.message) }); } } publishTemplateError = (errorMsg: any) => { // Display error message var msg = "<p>Template could not be published.</p><p>"; msg += angular.isString(errorMsg) ? _.escape(errorMsg) : "Please try again later."; msg += "</p>"; this.$mdDialog.hide(); this.$mdDialog.show( this.$mdDialog.alert() .ariaLabel("Error publishing the template to repository") .clickOutsideToClose(true) .htmlContent(msg) .ok("Got it!") .parent(document.body) .title("Error publishing the template to repository")); } /** * Called when the user changes the radio buttons */ onTableOptionChange = () => { if (this.model.templateTableOption === 'DEFINE_TABLE') { this.model.defineTable = true; this.model.dataTransformation = false; } else if (this.model.templateTableOption === 'DATA_TRANSFORMATION') { this.model.defineTable = false; this.model.dataTransformation = true; } else { this.model.defineTable = false; this.model.dataTransformation = false; } }; showProgress() { if (this.stepperController) { this.stepperController.showProgress = true; } } hideProgress() { if (this.stepperController && !this.isLoading()) { this.stepperController.showProgress = false; } } findSelectedTemplate() { if (this.nifiTemplateId != undefined) { return _.find(this.templates, (template: any) => { return template.id == this.nifiTemplateId; }); } else { return null; } } isLoading = () => { return this.loadingTemplate || this.fetchingTemplateList || this.model.loading; } /** * Navigate the user to the state * @param link */ templateNavigationLink = (link: any) => { var templateId = this.registeredTemplateId; var templateName = this.model.templateName; this.$state.go(link.sref, {templateId: templateId, templateName: templateName, model: this.model}); } /** * Gets the templates for the select dropdown * @returns {HttpPromise} */ getTemplates = () => { this.fetchingTemplateList = true; this.showProgress(); this.registerTemplateService.getTemplates().then((response: any) => { this.templates = response.data; this.fetchingTemplateList = false; this.matchNiFiTemplateIdWithModel(); this.hideProgress(); }); }; /** * Ensure that the value for the select list matches the model(if a model is selected) */ matchNiFiTemplateIdWithModel() { if (!this.isLoading() && this.model.nifiTemplateId != this.nifiTemplateId) { var matchingTemplate = this.templates.find((template: any) => { var found = angular.isDefined(template.templateDto) ? template.templateDto.id == this.model.nifiTemplateId : template.id == this.model.nifiTemplateId; if (!found) { //check on template name found = this.model.templateName == template.name; } return found; }); if (angular.isDefined(matchingTemplate)) { this.nifiTemplateId = matchingTemplate.templateDto.id; } } } /** * Called either after the the template has been selected from the previous screen, or after the template select list is loaded */ onRegisteredTemplateLoaded() { this.matchNiFiTemplateIdWithModel(); } $onInit() { this.ngOnInit(); } ngOnInit() { this.stepNumber = parseInt(this.stepIndex) + 1; if (this.isLoading()) { this.stepperController.showProgress = true; } } } angular.module(moduleName).component('thinkbigRegisterSelectTemplate', { bindings: { stepIndex: '@', nifiTemplateId: '=?', registeredTemplateId: "=?" }, controllerAs: 'vm', templateUrl: './select-template.html', controller: RegisterSelectTemplateController, require: { stepperController: "^thinkbigStepper" } });
the_stack
type TMtpVectorSubType = 'User' | 'Message' | 'Chat' | 'Dialog' type TMtpVector = 'Vector' type TMtpMessagesSlice = 'messages.MessagesSlice' type TMtpDialogsSlice = 'messages.DialogsSlice' type TMtpMessage = 'Message' type TMtpUser = 'User' type TMtpChat = 'Chat' type TMtpChannel = 'Channel' type TMtpDialog = 'Dialog' type TMtpPhoto = 'UserProfilePhoto' type TMtpDocument = 'document' type TMtpFileLocation = 'FileLocation' type TMtpDcOption = 'DcOption' export type TMtpType = TMtpVector | TMtpMessagesSlice | TMtpMessage | TMtpUser | TMtpChat | TMtpChannel | TMtpDialog | TMtpDcOption | TMtpPhoto | TMtpFileLocation | TMtpDialogsSlice | TMtpGetDialogs | TMtpDocument | TMtpDocumentAttributeType | TMtpGeoPoint type TMtpNearestDc = 'NearestDc' type TMtpConfig = 'Config' type TMtpGetDialogs = 'messages.Dialogs' type TMtpHelpType = TMtpConfig | TMtpNearestDc type TMtpPeerUser = 'PeerUser' type TMtpPeerChat = 'PeerChat' type TMtpPeerChannel = 'PeerChannel' type TMtpInputPeerUser = 'inputPeerUser' type TMtpInputPeerChat = 'inputPeerChat' type TMtpInputPeerChannel = 'inputPeerChannel' type TMtpPeerType = TMtpPeerUser | TMtpInputPeerUser | TMtpPeerChat | TMtpInputPeerChat | TMtpPeerChannel | TMtpInputPeerChannel type TMtpGeoPoint = 'geoPoint' type TMtpFile = 'upload.File' type TMtpUploadType = TMtpFile type TMtpFileUnknown = 'storage.FileUnknown' type TMtpFileJpeg = 'storage.FileJpeg' type TMtpFileGif = 'storage.FileGif' type TMtpFilePng = 'storage.FilePng' type TMtpFilePdf = 'storage.FilePdf' type TMtpFileMp3 = 'storage.FileMp3' type TMtpFileMov = 'storage.FileMov' type TMtpFilePartial = 'storage.FilePartial' type TMtpFileMp4 = 'storage.FileMp4' type TMtpFileWebp = 'storage.FileWebp' type TMtpStorageType = | TMtpFileUnknown | TMtpFileJpeg | TMtpFileGif | TMtpFilePng | TMtpFilePdf | TMtpFileMp3 | TMtpFileMov | TMtpFilePartial | TMtpFileMp4 | TMtpFileWebp // TODO: where is my TL parser??? type TMtpMessageMediaEmpty = 'messageMediaEmpty' type TMtpMessageMediaGeo = 'messageMediaGeo' type TMtpMessageMediaContact = 'messageMediaContact' type TMtpMessageMediaUnsupported = 'messageMediaUnsupported' type TMtpMessageMediaVenue = 'messageMediaVenue' type TMtpMessageMediaPhoto = 'messageMediaPhoto' type TMtpMessageMediaDocument = 'messageMediaDocument' type TMtpMessageMediaWebPage = 'messageMediaWebPage' type TMtpMessageMediaGame = 'messageMediaGame' type TMtpMessageMediaInvoice = 'messageMediaInvoice' export type TMtpMessageMediaType = | TMtpMessageMediaEmpty | TMtpMessageMediaGeo | TMtpMessageMediaContact | TMtpMessageMediaUnsupported | TMtpMessageMediaVenue | TMtpMessageMediaPhoto | TMtpMessageMediaDocument | TMtpMessageMediaWebPage | TMtpMessageMediaGame | TMtpMessageMediaInvoice export type TMtpMessageMediaRecord = { messageMediaEmpty: MtpMessageMediaEmpty, messageMediaGeo: MtpMessageMediaGeo, messageMediaContact: MtpMessageMediaContact, messageMediaUnsupported: MtpMessageMediaUnsupported, messageMediaVenue: MtpMessageMediaVenue, messageMediaPhoto: MtpMessageMediaPhoto, messageMediaDocument: MtpMessageMediaDocument, messageMediaWebPage: MtpMessageMediaWebPage, messageMediaGame: MtpMessageMediaGame, messageMediaInvoice: MtpMessageMediaInvoice, } type TMtpDocumentAttributeImageSize = 'documentAttributeImageSize' type TMtpDocumentAttributeAnimated = 'documentAttributeAnimated' type TMtpDocumentAttributeSticker = 'documentAttributeSticker' type TMtpDocumentAttributeVideo = 'documentAttributeVideo' type TMtpDocumentAttributeAudio = 'documentAttributeAudio' type TMtpDocumentAttributeFilename = 'documentAttributeFilename' type TMtpDocumentAttributeHasStickers = 'documentAttributeHasStickers' export type TMtpDocumentAttributeType = | TMtpDocumentAttributeImageSize | TMtpDocumentAttributeAnimated | TMtpDocumentAttributeSticker | TMtpDocumentAttributeVideo | TMtpDocumentAttributeAudio | TMtpDocumentAttributeFilename | TMtpDocumentAttributeHasStickers export type TMtpDocumentAttributeRecord = { documentAttributeImageSize: MtpDocumentAttributeImageSize, documentAttributeAnimated: MtpDocumentAttributeAnimated, documentAttributeSticker: MtpDocumentAttributeSticker, documentAttributeVideo: MtpDocumentAttributeVideo, documentAttributeAudio: MtpDocumentAttributeAudio, documentAttributeFilename: MtpDocumentAttributeFilename, documentAttributeHasStickers: MtpDocumentAttributeHasStickers, } interface MtpPrimitive<T> { _: T } type Bytes = Uint8Array export interface MtpHelpObject<T extends TMtpHelpType> extends MtpPrimitive<T> { } export interface MtpPeerObject<T extends TMtpPeerType> extends MtpPrimitive<T> { } export interface MtpUploadObject<T extends TMtpUploadType> extends MtpPrimitive<T> { } export interface MtpStorageObject<T extends TMtpStorageType> extends MtpPrimitive<T> { } export interface MtpMessageMediaObject<T extends TMtpMessageMediaType> extends MtpPrimitive<T> { } export interface MtpDocumentAttributeObject<T extends TMtpDocumentAttributeType> extends MtpPrimitive<T> { } export interface MtpObject<T extends TMtpType> extends MtpPrimitive<T> { id: number flags: number // NOTE: I'm not shure thats any object has it } export type MtpVector<T extends MtpPrimitive<TMtpType>> = T[] // STANDART OBJECTS export interface MtpDcOption extends MtpObject<TMtpDcOption> { ipv6?: true tcpo_only?: true ip_address: string port: number } // TODO: generate from TL // tslint:disable-next-line type MtpMessageEntity = any; export interface MtpGeoPoint extends MtpObject<TMtpGeoPoint> { long: number lat: number } export interface MtpMessage extends MtpObject<TMtpMessage> { from_id: number date: number // Unix time message: string to_id: MtpPeer mentioned?: true via_bot_id?: number entities?: MtpVector<MtpMessageEntity> // Vector of message markdown if any // tslint:disable-next-line media: MtpMessageMedia; unread?: true peerID?: true post?: true out?: true } export interface MtpDialog extends MtpObject<TMtpDialog> { read_inbox_max_id: number read_outbox_max_id: number top_message: number unread_count: number } export interface MtpFileLocation extends MtpObject<TMtpFileLocation> { dc_id: number volume_id: string local_id: number secret: string } export interface MtpPhoto extends MtpObject<TMtpPhoto> { photo_id: string photo_small: MtpFileLocation photo_big: MtpFileLocation } export interface MtpDocument extends MtpObject<TMtpDocument> { id: number access_hash: number date: number mime_type: string size: number thumb: any dc_id: number version: number attributes: MtpVector<MtpDocumentAttribute> } export interface MtpUser extends MtpObject<TMtpUser> { access_hash: string first_name?: string last_name?: string phone: string username?: string contact: boolean verifed: boolean bot?: true } export interface MtpChat extends MtpObject<TMtpChat> { title: string access_hash: string } export interface MtpMessagesSlice extends MtpObject<TMtpMessagesSlice> { chats: MtpVector<MtpChat> messages: MtpVector<MtpMessage> users: MtpVector<MtpUser> count: number } export interface MtpGetDialogs extends MtpObject<TMtpGetDialogs> { chats: MtpVector<MtpChat> messages: MtpVector<MtpMessage> users: MtpVector<MtpUser> dialogs: MtpVector<MtpDialog> count: number } export type MtpObjectGeneric = MtpDcOption | MtpMessage | MtpDialog | MtpFileLocation | MtpPhoto | MtpUser | MtpChat | MtpMessagesSlice | MtpGetDialogs // DOCUMENT ATTRIBUTE export type MtpDocumentAttribute = | MtpDocumentAttributeImageSize | MtpDocumentAttributeAnimated | MtpDocumentAttributeSticker | MtpDocumentAttributeVideo | MtpDocumentAttributeAudio | MtpDocumentAttributeFilename | MtpDocumentAttributeHasStickers export interface MtpDocumentAttributeImageSize extends MtpDocumentAttributeObject<TMtpDocumentAttributeImageSize> { w: number h: number } export interface MtpDocumentAttributeAnimated extends MtpDocumentAttributeObject<TMtpDocumentAttributeAnimated> { } export interface MtpDocumentAttributeSticker extends MtpDocumentAttributeObject<TMtpDocumentAttributeSticker> { mask?: true alt: string stickerset: any mask_coords?: any } export interface MtpDocumentAttributeVideo extends MtpDocumentAttributeObject<TMtpDocumentAttributeVideo> { round_message?: true duration: number w: number h: number } export interface MtpDocumentAttributeAudio extends MtpDocumentAttributeObject<TMtpDocumentAttributeAudio> { voice?: true duration: number title?: string performer?: string waveform?: Bytes } export interface MtpDocumentAttributeFilename extends MtpDocumentAttributeObject<TMtpDocumentAttributeFilename> { file_name: string } export interface MtpDocumentAttributeHasStickers extends MtpDocumentAttributeObject<TMtpDocumentAttributeHasStickers> { } // MESSAGE MEDIA export type MtpMessageMedia = | MtpMessageMediaEmpty | MtpMessageMediaGeo | MtpMessageMediaContact | MtpMessageMediaUnsupported | MtpMessageMediaVenue | MtpMessageMediaPhoto | MtpMessageMediaDocument | MtpMessageMediaWebPage | MtpMessageMediaGame | MtpMessageMediaInvoice export interface MtpMessageMediaEmpty extends MtpMessageMediaObject<TMtpMessageMediaEmpty> { } export interface MtpMessageMediaGeo extends MtpMessageMediaObject<TMtpMessageMediaGeo> { geo: MtpGeoPoint } export interface MtpMessageMediaContact extends MtpMessageMediaObject<TMtpMessageMediaContact> { phone_number: string first_name: string last_name: string user_id: number } export interface MtpMessageMediaUnsupported extends MtpMessageMediaObject<TMtpMessageMediaUnsupported> { } export interface MtpMessageMediaVenue extends MtpMessageMediaObject<TMtpMessageMediaVenue> { geo: MtpGeoPoint title: string address: string provider: string venue_id: string } export interface MtpMessageMediaPhoto extends MtpMessageMediaObject<TMtpMessageMediaPhoto> { photo: any caption: string } export interface MtpMessageMediaDocument extends MtpMessageMediaObject<TMtpMessageMediaDocument> { document: MtpDocument caption: string } export interface MtpMessageMediaWebPage extends MtpMessageMediaObject<TMtpMessageMediaWebPage> { webpage: any } export interface MtpMessageMediaGame extends MtpMessageMediaObject<TMtpMessageMediaGame> { game: any } export interface MtpMessageMediaInvoice extends MtpMessageMediaObject<TMtpMessageMediaInvoice> { shipping_address_requested?: true test?: true title: string description: string photo?: any receipt_msg_id?: number currency: string total_amount: number start_param: string } // PEER OBJECTS export type MtpPeer = MtpPeerUser | MtpPeerChat | MtpPeerChannel export interface MtpPeerUser extends MtpPeerObject<TMtpPeerUser | TMtpInputPeerUser> { user_id: number } export interface MtpPeerChat extends MtpPeerObject<TMtpPeerChat | TMtpInputPeerChat> { chat_id: number } export interface MtpPeerChannel extends MtpPeerObject<TMtpPeerChannel | TMtpInputPeerChannel> { channel_id: number } // HELP OBJECTS export interface MtpHelpNearestDc extends MtpHelpObject<TMtpNearestDc> { country: string nearest_dc: number this_dc: number } export interface MtpHelpGetConfig extends MtpHelpObject<TMtpNearestDc> { chat_big_size: number chat_size_max: number date: number dc_options: MtpVector<MtpDcOption> edit_time_limit: number expires: number flags: number forwarded_count_max: number megagroup_size_max: number notify_cloud_delay_ms: number notify_default_delay_ms: number offline_blur_timeout_ms: number offline_idle_timeout_ms: number online_cloud_timeout_ms: number online_update_period_ms: number push_chat_limit: number push_chat_period_ms: number rating_e_decay: number saved_gifs_limit: number stickers_recent_limit: number test_mode: boolean this_dc: number } // UPLOAD OBJECTS export interface MtpUploadFile extends MtpUploadObject<TMtpFile> { type: MtpStorageObject<TMtpStorageType> mtime: number bytes: Bytes } export type TById<T> = { [id: number]: T }
the_stack
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; let info: JamInfo; let startDate: number; let endDate: number; function initTelemetry() { // Watch on mixer button document.getElementById("stream")?.addEventListener("click", () => { (window as any).pxtTickEvent("gamejam.stream") }) // Submit on itch.io button document.querySelector(".submit .button:nth-child(1)").addEventListener("click", () => { (window as any).pxtTickEvent("gamejam.submit.itchio") }) // Submit with office forms button document.querySelector(".submit .button:nth-child(2)").addEventListener("click", () => { (window as any).pxtTickEvent("gamejam.submit.forms") }) } function initRulesTelemetry(id: string,) { // Try one of our tutorials text link document.querySelector(`#${id} + ul li:nth-child(1) a`)?.addEventListener("click", () => { (window as any).pxtTickEvent("gamejam.link.tutorial") }) // How to import images text link document.querySelector(`#${id} + ul li:nth-child(3) a`)?.addEventListener("click", () => { (window as any).pxtTickEvent("gamejam.link.images") }) // Developer documentation text link document.querySelector(`#${id}+ ul li:nth-child(4) a`)?.addEventListener("click", () => { (window as any).pxtTickEvent("gamejam.link.developer") }) } function getInfo(path: string) { let infoRequest = new XMLHttpRequest(); infoRequest.addEventListener("load", onLoad); infoRequest.open("GET", path); infoRequest.send(); function onLoad() { info = JSON.parse(this.responseText) as JamInfo; startDate = new Date(info.start).getTime(); endDate = new Date(info.end).getTime(); const judged = info.featured.some(el => !!el.description); makeTimer(); makeRules(); if (judged) makeWinners(); makeGallery(); makeSchedule(); initTelemetry(); } } function makeTimer() { const now = Date.now(); if (now < endDate) { const parent = document.getElementById("timer"); const label = document.createElement("div"); const labelText = document.createElement("h3"); label.className = "label"; label.appendChild(labelText); parent.appendChild(label); const timer = document.createElement("div"); timer.appendChild(makeTimeCounter("days")); timer.appendChild(makeTimeCounter("hours")); timer.appendChild(makeTimeCounter("minutes")); timer.appendChild(makeTimeCounter("seconds")); parent.appendChild(timer); if (now < startDate) { labelText.innerText = "Starts in:"; } else { labelText.innerText = "Ends in:"; } setTimer(); setInterval(setTimer, 1000); } } function makeTimeCounter(id: string) { const counter = document.createElement("div"); counter.id = id; counter.className = "counter"; const count = document.createElement("div"); count.className = "number"; counter.appendChild(count); const label = document.createElement("div"); label.textContent = id; counter.appendChild(label); return counter; } function setTimer() { const now = Date.now(); let delta = Math.floor((now < startDate ? startDate - now : endDate - now) / 1000); let dayCounter = document.querySelector("#days .number") as HTMLElement; dayCounter.innerText = Math.floor(delta / 86400).toString(); delta = delta % 86400; let hourCounter = document.querySelector("#hours .number") as HTMLElement; hourCounter.innerText = Math.floor(delta / 3600).toString(); delta = delta % 3600; let minuteCounter = document.querySelector("#minutes .number") as HTMLElement; minuteCounter.innerText = Math.floor(delta / 60).toString(); delta = delta % 60; let secondCounter = document.querySelector("#seconds .number") as HTMLElement; secondCounter.innerText = delta.toString(); } function makeRules() { if (info?.rules) { let rulesRequest = new XMLHttpRequest(); rulesRequest.addEventListener("load", onLoad); rulesRequest.open("GET", info.rules.path); rulesRequest.send(); function onLoad() { marked.setOptions({ // @ts-ignore sanitizer: DOMPurify.sanitizer, }); let markdown = marked(this.responseText); const parent = document.getElementById("rules"); parent.innerHTML = markdown; // insert schedule of events after rules const collaborateNode = document.getElementById(info.rules.collaborateId); if (collaborateNode) { collaborateNode.parentElement.insertBefore(document.getElementById("events"), collaborateNode); } // move submit section if submitPositionId exists if (info.rules.submitPositionId) { const beforeNode = document.getElementById(info.rules.submitPositionId); const submitNode = document.getElementById("submit"); if (beforeNode && submitNode) { beforeNode.parentElement.insertBefore(submitNode, beforeNode); } } initRulesTelemetry(info.rules.tipsId); } } } function makeWinners() { const content = document.querySelector(".content"); content.className += " winners"; const gallery = document.querySelector(".gallery"); const parent = document.createElement("div"); parent.id = "highlighted"; parent.className += "segment"; const title = document.createElement("h2"); title.innerText = "Honorable Mentions"; parent.appendChild(title); const description = document.createElement("p"); description.innerText = "These are some games that the judges also loved! Give them a play, we're sure you'll enjoy yourself."; parent.appendChild(description); const highlighted = info.featured.filter(el => !!el.description); let row = document.createElement("div"); for (let i = 0; i < highlighted.length; i++) { row.appendChild(makeGameCard(highlighted[i])); if (i % 2 == 1) { parent.appendChild(row); row = document.createElement("div") } } if (highlighted.length % 2 != 0) { parent.appendChild(row); } content.insertBefore(parent, gallery); } function makeGallery() { const container = document.querySelector(".gallery") as HTMLElement; const parent = document.getElementById("gallery"); if (container && parent) { if (!info?.featured.length) { const description = document.querySelector(".gallery .description") as HTMLElement; description.innerText = "Check back later to play some submitted games!" } else { let hint = document.createElement("div"); hint.className = "hint" hint.innerText = "If you see blocks overlapping each other in the editor workspace, you can \ reformat them by selecting \"Format Code\" from the menu when you right-click \ on the workspace background." container.insertBefore(hint, parent); } let selected = randomize(info.featured); // show all the games let row = document.createElement("div"); for (let i = 0; i < selected.length; i++) { row.appendChild(makeGameCard(selected[i])); if (i % 3 == 2) { parent.appendChild(row); row = document.createElement("div") } } if (selected.length % 3 != 0) { parent.appendChild(row); } } } function makeGameCard(game: Game) { let card = document.createElement("div"); card.className = "game"; let link = document.createElement("a"); link.href = game.url || `https://arcade.makecode.com/${game.id}`; let textLink = link.cloneNode() as HTMLElement; let img = document.createElement("img"); img.src = `https://pxt.azureedge.net/api/${game.id}/thumb`; link.appendChild(img); card.appendChild(link); let label = document.createElement("div"); textLink.innerText = game.title; label.appendChild(textLink); if (game.author) { let author = document.createElement("div"); author.innerText = `by ${game.author}`; label.appendChild(author); } card.appendChild(label); if (game.description) { let description = document.createElement("div"); description.innerText = game.description; label.appendChild(description); } return card; } function makeSchedule() { const sorted = info?.sessions?.sort((a, b) => a.date < b.date ? -1 : 1) || []; const parent = document.getElementById("schedule"); for (const session of sorted) { const row = document.createElement("div"); row.className = "event"; const text = document.createElement("div"); text.className = "text"; const title = document.createElement("div"); title.className = "title"; title.innerText = session.title; const ics = document.createElement("a"); ics.className = "ics"; ics.href = session.ics; const icon = document.createElement("i"); icon.className = "icon calendar"; ics.appendChild(icon); title.appendChild(ics); row.appendChild(title) const details = document.createElement("div"); details.className = "details"; const imgContainer = document.createElement("div"); imgContainer.className = "image" const img = document.createElement("img"); img.src = session.imgSrc; imgContainer.appendChild(img) details.appendChild(imgContainer) const sessionDate = new Date(session.date); const date = document.createElement("div"); date.className = "date"; date.innerText = `${formatDate(sessionDate)}, ${formatTime(session.time)}`; text.appendChild(date); const description = document.createElement("div"); description.innerText = session.description; text.appendChild(description) details.appendChild(text) row.appendChild(details) parent.appendChild(row); } } function formatTime(time: number): string { const EST = time + 3; return `${time % 12 || 12} ${time < 12 ? "AM" : "PM"} PDT / ${EST % 12 || 12} ${EST < 12 ? "AM" : "PM"} EDT`; } function formatDate(date: Date): string { return `${MONTHS[date.getMonth()]} ${date.getDate()}` } function randomize(arr) { const randomized = arr.slice(); for (let i = randomized.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); [randomized[i], randomized[j]] = [randomized[j], randomized[i]]; } return randomized; }
the_stack
import { Headers, Params, RequestOptions } from "./connection"; import { Database } from "./database"; import { ArangojsResponse } from "./lib/request"; /** * Represents an arbitrary route relative to an ArangoDB database. */ export class Route { protected _db: Database; protected _path: string; protected _headers: Headers; /** * @internal * @hidden */ constructor(db: Database, path: string = "", headers: Headers = {}) { if (!path) path = ""; else if (path.charAt(0) !== "/") path = `/${path}`; this._db = db; this._path = path; this._headers = headers; } /** * Creates a new route relative to this route that inherits any of its default * HTTP headers. * * @param path - Path relative to this route. * @param headers - Additional headers that will be sent with each request. * * @example * ```js * const db = new Database(); * const foxx = db.route("/my-foxx-service"); * const users = foxx.route("/users"); * ``` */ route(path: string, headers?: Headers) { if (!path) path = ""; else if (path.charAt(0) !== "/") path = `/${path}`; return new Route(this._db, this._path + path, { ...this._headers, ...headers, }); } /** * Performs an arbitrary HTTP request relative to this route and returns the * server response. * * @param options - Options for performing the request. * * @example * ```js * const db = new Database(); * const foxx = db.route("/my-foxx-service"); * const res = await foxx.request({ * method: "POST", * path: "/users", * body: { * username: "admin", * password: "hunter2" * } * }); * ``` */ request(options?: RequestOptions) { const opts = { ...options }; if (!opts.path || opts.path === "/") opts.path = ""; else if (!this._path || opts.path.charAt(0) === "/") opts.path = opts.path; else opts.path = `/${opts.path}`; opts.basePath = this._path; opts.headers = { ...this._headers, ...opts.headers }; opts.method = opts.method ? opts.method.toUpperCase() : "GET"; return this._db.request(opts); } /** * Performs a DELETE request against the given path relative to this route * and returns the server response. * * @param path - Path relative to this route. * @param qs - Query string parameters for this request. * @param headers - Additional headers to send with this request. * * @example * ```js * const db = new Database(); * const foxx = db.route("/my-foxx-service"); * const res = await foxx.delete("/users/admin"); * ``` */ delete( path: string, qs?: string | Params, headers?: Headers ): Promise<ArangojsResponse>; /** * Performs a DELETE request against the given path relative to this route * and returns the server response. * * @param qs - Query string parameters for this request. * @param headers - Additional headers to send with this request. * * @example * ```js * const db = new Database(); * const foxx = db.route("/my-foxx-service"); * const user = foxx.roue("/users/admin"); * const res = await user.delete(); * ``` */ delete(qs?: Params, headers?: Headers): Promise<ArangojsResponse>; delete(...args: any[]): Promise<ArangojsResponse> { const path = typeof args[0] === "string" ? args.shift() : undefined; const [qs, headers] = args; return this.request({ method: "DELETE", path, qs, headers }); } /** * Performs a GET request against the given path relative to this route * and returns the server response. * * @param path - Path relative to this route. * @param qs - Query string parameters for this request. * @param headers - Additional headers to send with this request. * * @example * ```js * const db = new Database(); * const foxx = db.route("/my-foxx-service"); * const res = await foxx.get("/users", { offset: 10, limit: 5 }); * ``` */ get( path: string, qs?: string | Params, headers?: Headers ): Promise<ArangojsResponse>; /** * Performs a GET request against the given path relative to this route * and returns the server response. * * @param qs - Query string parameters for this request. * @param headers - Additional headers to send with this request. * * @example * ```js * const db = new Database(); * const foxx = db.route("/my-foxx-service"); * const users = foxx.route("/users"); * const res = await users.get({ offset: 10, limit: 5 }); * ``` */ get(qs?: Params, headers?: Headers): Promise<ArangojsResponse>; get(...args: any[]): Promise<ArangojsResponse> { const path = typeof args[0] === "string" ? args.shift() : undefined; const [qs, headers] = args; return this.request({ method: "GET", path, qs, headers }); } /** * Performs a HEAD request against the given path relative to this route * and returns the server response. * * @param path - Path relative to this route. * @param qs - Query string parameters for this request. * @param headers - Additional headers to send with this request. * * @example * ```js * const db = new Database(); * const foxx = db.route("/my-foxx-service"); * const res = await foxx.head("/users", { offset: 10, limit: 5 }); * ``` */ head( path: string, qs?: string | Params, headers?: Headers ): Promise<ArangojsResponse>; /** * Performs a HEAD request against the given path relative to this route * and returns the server response. * * @param qs - Query string parameters for this request. * @param headers - Additional headers to send with this request. * * @example * ```js * const db = new Database(); * const foxx = db.route("/my-foxx-service"); * const users = foxx.route("/users"); * const res = await users.head({ offset: 10, limit: 5 }); * ``` */ head(qs?: Params, headers?: Headers): Promise<ArangojsResponse>; head(...args: any[]): Promise<ArangojsResponse> { const path = typeof args[0] === "string" ? args.shift() : undefined; const [qs, headers] = args; return this.request({ method: "HEAD", path, qs, headers }); } /** * Performs a PATCH request against the given path relative to this route * and returns the server response. * * @param path - Path relative to this route. * @param body - Body of the request object. * @param qs - Query string parameters for this request. * @param headers - Additional headers to send with this request. * * @example * ```js * const db = new Database(); * const foxx = db.route("/my-foxx-service"); * const res = await foxx.patch("/users/admin", { password: "admin" }); * ``` */ patch( path: string, body?: any, qs?: string | Params, headers?: Headers ): Promise<ArangojsResponse>; /** * Performs a PATCH request against the given path relative to this route * and returns the server response. * * **Note**: `body` must not be a `string`. * * @param body - Body of the request object. Must not be a string. * @param qs - Query string parameters for this request. * @param headers - Additional headers to send with this request. * * @example * ```js * const db = new Database(); * const foxx = db.route("/my-foxx-service"); * const user = foxx.route("/users/admin") * const res = await user.patch({ password: "admin" }); * ``` */ patch( body?: any, qs?: string | Params, headers?: Headers ): Promise<ArangojsResponse>; patch(...args: any[]): Promise<ArangojsResponse> { const path = typeof args[0] === "string" ? args.shift() : undefined; const [body, qs, headers] = args; return this.request({ method: "PATCH", path, body, qs, headers }); } /** * Performs a POST request against the given path relative to this route * and returns the server response. * * @param path - Path relative to this route. * @param body - Body of the request object. * @param qs - Query string parameters for this request. * @param headers - Additional headers to send with this request. * * @example * ```js * const db = new Database(); * const foxx = db.route("/my-foxx-service"); * const res = await foxx.post("/users", { * username: "admin", * password: "hunter2" * }); * ``` */ post( path: string, body?: any, qs?: string | Params, headers?: Headers ): Promise<ArangojsResponse>; /** * Performs a POST request against the given path relative to this route * and returns the server response. * * **Note**: `body` must not be a `string`. * * @param body - Body of the request object. Must not be a string. * @param qs - Query string parameters for this request. * @param headers - Additional headers to send with this request. * * @example * ```js * const db = new Database(); * const foxx = db.route("/my-foxx-service"); * const users = foxx.route("/users"); * const res = await users.post({ * username: "admin", * password: "hunter2" * }); * ``` */ post( body?: any, qs?: string | Params, headers?: Headers ): Promise<ArangojsResponse>; post(...args: any[]): Promise<ArangojsResponse> { const path = typeof args[0] === "string" ? args.shift() : undefined; const [body, qs, headers] = args; return this.request({ method: "POST", path, body, qs, headers }); } /** * Performs a PUT request against the given path relative to this route * and returns the server response. * * @param path - Path relative to this route. * @param body - Body of the request object. * @param qs - Query string parameters for this request. * @param headers - Additional headers to send with this request. * * @example * ```js * const db = new Database(); * const foxx = db.route("/my-foxx-service"); * const res = await foxx.put("/users/admin/password", { password: "admin" }); * ``` */ put( path: string, body?: any, qs?: string | Params, headers?: Headers ): Promise<ArangojsResponse>; /** * Performs a PUT request against the given path relative to this route * and returns the server response. * * **Note**: `body` must not be a `string`. * * @param body - Body of the request object. Must not be a string. * @param qs - Query string parameters for this request. * @param headers - Additional headers to send with this request. * * @example * ```js * const db = new Database(); * const foxx = db.route("/my-foxx-service"); * const password = foxx.route("/users/admin/password"); * const res = await password.put({ password: "admin" }); * ``` */ put( body?: any, qs?: string | Params, headers?: Headers ): Promise<ArangojsResponse>; put(...args: any[]): Promise<ArangojsResponse> { const path = typeof args[0] === "string" ? args.shift() : undefined; const [body, qs, headers] = args; return this.request({ method: "PUT", path, body, qs, headers }); } }
the_stack
import { promises as fspromises } from 'fs'; import md5file from 'md5-file'; import * as mkdirp from 'mkdirp'; import { assertIsError } from '../../__tests__/testUtils/test_utils'; import { DryMongoBinary } from '../DryMongoBinary'; import { Md5CheckFailedError } from '../errors'; import { MongoBinaryOpts } from '../MongoBinary'; import MongoBinaryDownload from '../MongoBinaryDownload'; import MongoBinaryDownloadUrl from '../MongoBinaryDownloadUrl'; import { envName, ResolveConfigVariables } from '../resolveConfig'; import * as utils from '../utils'; jest.mock('md5-file'); jest.mock('mkdirp'); describe('MongoBinaryDownload', () => { afterEach(() => { delete process.env[envName(ResolveConfigVariables.MD5_CHECK)]; jest.restoreAllMocks(); }); it('checkMD5 attribute can be set via constructor parameter', () => { expect(new MongoBinaryDownload({ checkMD5: true, downloadDir: '/' }).checkMD5).toBe(true); expect(new MongoBinaryDownload({ checkMD5: false, downloadDir: '/' }).checkMD5).toBe(false); }); it('if checkMD5 input parameter is missing, then it checks "MONGOMS_MD5_CHECK" environment variable', () => { expect(new MongoBinaryDownload({ downloadDir: '/' }).checkMD5).toBe(false); process.env[envName(ResolveConfigVariables.MD5_CHECK)] = '1'; expect(new MongoBinaryDownload({ downloadDir: '/' }).checkMD5).toBe(true); }); it('should use direct download', async () => { process.env['yarn_https-proxy'] = ''; process.env['yarn_proxy'] = ''; process.env['npm_config_https-proxy'] = ''; process.env['npm_config_proxy'] = ''; process.env['https_proxy'] = ''; process.env['http_proxy'] = ''; const du = new MongoBinaryDownload({ downloadDir: '/' }); jest.spyOn(du, 'httpDownload').mockResolvedValue('/tmp/someFile.tgz'); jest.spyOn(utils, 'pathExists').mockResolvedValue(false); await du.download('https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-3.6.3.tgz'); expect(du.httpDownload).toHaveBeenCalledTimes(1); const callArg1 = ( (du.httpDownload as jest.Mock).mock.calls[0] as Parameters< MongoBinaryDownload['httpDownload'] > )[1]; expect(callArg1.agent).toBeUndefined(); }); it('should skip download if binary tar exists', async () => { const du = new MongoBinaryDownload({ downloadDir: '/' }); jest.spyOn(du, 'httpDownload').mockResolvedValue('/tmp/someFile.tgz'); jest.spyOn(utils, 'pathExists').mockResolvedValue(true); await du.download('https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-3.6.3.tgz'); expect(du.httpDownload).not.toHaveBeenCalled(); }); it('should pick up proxy from env vars', async () => { process.env['yarn_https-proxy'] = 'http://user:pass@proxy:8080'; const du = new MongoBinaryDownload({ downloadDir: '/' }); jest.spyOn(du, 'httpDownload').mockResolvedValue('/tmp/someFile.tgz'); jest.spyOn(utils, 'pathExists').mockResolvedValue(false); await du.download('https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-3.6.3.tgz'); expect(du.httpDownload).toHaveBeenCalledTimes(1); const callArg1 = ( (du.httpDownload as jest.Mock).mock.calls[0] as Parameters< MongoBinaryDownload['httpDownload'] > )[1]; utils.assertion( !utils.isNullOrUndefined(callArg1.agent), new Error('Expected "callArg1.agent" to be defined') ); // @ts-expect-error because "proxy" if soft-private expect(callArg1.agent.proxy.href).toBe('http://user:pass@proxy:8080/'); }); it('should not reject unauthorized when npm strict-ssl config is false', async () => { // npm sets false config value as empty string in env vars process.env['npm_config_strict_ssl'] = ''; const du = new MongoBinaryDownload({ downloadDir: '/' }); jest.spyOn(du, 'httpDownload').mockResolvedValue('/tmp/someFile.tgz'); jest.spyOn(utils, 'pathExists').mockResolvedValue(false); await du.download('https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-3.6.3.tgz'); expect(du.httpDownload).toHaveBeenCalledTimes(1); const callArg1 = ( (du.httpDownload as jest.Mock).mock.calls[0] as Parameters< MongoBinaryDownload['httpDownload'] > )[1]; expect(callArg1.rejectUnauthorized).toEqual(false); }); it('should reject unauthorized when npm strict-ssl config is true', async () => { // npm sets true config value as string 'true' in env vars process.env['npm_config_strict_ssl'] = 'true'; const du = new MongoBinaryDownload({ downloadDir: '/' }); jest.spyOn(du, 'httpDownload').mockResolvedValue('/tmp/someFile.tgz'); jest.spyOn(utils, 'pathExists').mockResolvedValue(false); await du.download('https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-3.6.3.tgz'); expect(du.httpDownload).toHaveBeenCalledTimes(1); const callArg1 = ( (du.httpDownload as jest.Mock).mock.calls[0] as Parameters< MongoBinaryDownload['httpDownload'] > )[1]; expect(callArg1.rejectUnauthorized).toEqual(true); }); it('makeMD5check returns true if md5 of downloaded mongoDBArchive is the same as in the reference result', async () => { const someMd5 = 'md5'; const mongoDBArchivePath = '/some/path'; const fileWithReferenceMd5 = '/another/path'; jest.spyOn(fspromises, 'readFile').mockResolvedValueOnce(`${someMd5} fileName`); jest.spyOn(md5file, 'sync').mockImplementationOnce(() => someMd5); jest.spyOn(fspromises, 'unlink').mockResolvedValue(void 0); const du = new MongoBinaryDownload({ downloadDir: '/', checkMD5: true }); jest.spyOn(du, 'download').mockResolvedValue(fileWithReferenceMd5); const urlToMongoDBArchivePath = 'some-url'; const res = await du.makeMD5check(urlToMongoDBArchivePath, mongoDBArchivePath); expect(res).toBe(true); expect(du.download).toBeCalledWith(urlToMongoDBArchivePath); expect(fspromises.readFile).toBeCalledWith(fileWithReferenceMd5); expect(fspromises.unlink).toBeCalledTimes(1); expect(md5file.sync).toBeCalledWith(mongoDBArchivePath); }); it('makeMD5check throws an error if md5 of downloaded mongoDBArchive is NOT the same as in the reference result', async () => { jest.spyOn(fspromises, 'readFile').mockResolvedValueOnce(`someMD5 fileName`); jest.spyOn(md5file, 'sync').mockImplementationOnce(() => 'anotherMD5'); const du = new MongoBinaryDownload({ downloadDir: '/', checkMD5: true }); jest.spyOn(du, 'download').mockResolvedValue(''); try { await du.makeMD5check('', ''); fail('Expected "makeMD5check" to fail'); } catch (err) { expect(err).toBeInstanceOf(Md5CheckFailedError); expect(JSON.stringify(err)).toMatchSnapshot(); // this is to test all the custom values on the error } }); it('false value of checkMD5 attribute disables makeMD5check validation', async () => { jest.spyOn(fspromises, 'readFile').mockResolvedValueOnce(`someMD5 fileName`); jest.spyOn(md5file, 'sync').mockImplementationOnce(() => 'anotherMD5'); const du = new MongoBinaryDownload({ downloadDir: '/', checkMD5: false }); const result = await du.makeMD5check('', ''); expect(result).toEqual(undefined); }); it('should return the correct path to binary name (getPath)', async () => { const downloadDir = '/path/to/downloadDir'; jest.spyOn(DryMongoBinary, 'generateOptions').mockResolvedValue({ arch: 'x64', version: '4.0.25', downloadDir: downloadDir, systemBinary: '', os: { os: 'linux', dist: 'ubuntu', release: '14', }, }); const du = new MongoBinaryDownload({ downloadDir }); // @ts-expect-error because "getPath" is "protected" const path = await du.getPath(); expect(path).toEqual(`${downloadDir}/mongod-x64-ubuntu-4.0.25`); }); it('should print the download progress (printDownloadProgress)', () => { const version = '4.0.25'; process.stdout.isTTY = false; jest.spyOn(console, 'log').mockImplementation(() => void 0); jest.spyOn(process.stdout, 'write').mockImplementation(() => true); const du = new MongoBinaryDownload({ downloadDir: '/', checkMD5: false, version, platform: 'linux', }); expect(du.dlProgress.current).toBe(0); du.dlProgress.length = 5242880; du.dlProgress.totalMb = Math.round((du.dlProgress.length / 1048576) * 10) / 10; du.printDownloadProgress({ length: 1048576 }); expect(console.log).toHaveBeenCalledWith( `Downloading MongoDB "${version}": 20% (1mb / ${du.dlProgress.totalMb}mb)\r` ); expect(console.log).toBeCalledTimes(1); expect(process.stdout.write).not.toHaveBeenCalled(); du.printDownloadProgress({ length: 10 }); expect(console.log).toHaveBeenCalledTimes(1); expect(process.stdout.write).not.toHaveBeenCalled(); expect(du.dlProgress.current).toBe(1048576 + 10); process.stdout.isTTY = true; du.printDownloadProgress({ length: 0 }, true); expect(console.log).toHaveBeenCalledTimes(1); expect(process.stdout.write).toHaveBeenCalledWith( // its still "20" and "1" because of rounding `Downloading MongoDB "${version}": 20% (1mb / ${du.dlProgress.totalMb}mb)\r` ); expect(process.stdout.write).toHaveBeenCalledTimes(2); // once for clearing the line and once for the actual line }); it('should directly return the path if already exists', async () => { const binaryPath = '/path/to/binary'; jest.spyOn(utils, 'pathExists').mockResolvedValue(true); const du = new MongoBinaryDownload({ downloadDir: '/' }); jest .spyOn(du, 'startDownload') .mockImplementation(() => fail('Expected this function not to be called')); // @ts-expect-error because "getPath" is "protected" jest.spyOn(du, 'getPath').mockResolvedValue(binaryPath); const returnValue = await du.getMongodPath(); expect(returnValue).toEqual(binaryPath); expect(du.startDownload).not.toHaveBeenCalled(); expect( // @ts-expect-error because "getPath" is "protected" du.getPath ).toHaveBeenCalledTimes(1); }); it('should return the mongodb archive path (startDownload)', async () => { const downloadUrl = 'https://fastdl.mongodb.org/linux/mongod-something-something.tgz'; const archivePath = '/path/to/archive.tgz'; jest.spyOn(mkdirp, 'default').mockResolvedValue(void 0); jest.spyOn(fspromises, 'access').mockResolvedValue(void 0); jest.spyOn(MongoBinaryDownloadUrl.prototype, 'getDownloadUrl').mockResolvedValue(downloadUrl); const du = new MongoBinaryDownload({ downloadDir: '/' }); jest.spyOn(du, 'download').mockResolvedValue(archivePath); jest.spyOn(du, 'makeMD5check'); const returnValue = await du.startDownload(); expect(returnValue).toEqual(archivePath); expect(du.makeMD5check).toHaveBeenCalledWith(`${downloadUrl}.md5`, archivePath); expect(du.download).toHaveBeenCalledWith(downloadUrl); }); it('should return the mongodb archive path (startDownload)', async () => { const customError = new Error('custom fs error'); jest.spyOn(mkdirp, 'default').mockResolvedValue(void 0); jest.spyOn(fspromises, 'access').mockRejectedValue(customError); jest.spyOn(console, 'error').mockImplementation(() => void 0); const du = new MongoBinaryDownload({ downloadDir: '/' }); try { await du.startDownload(); fail('Expected "startDownload" to fail'); } catch (err) { assertIsError(err); expect(err.message).toEqual(customError.message); expect(console.error).toHaveBeenCalledTimes(1); } }); it('should passthrough options to MongoBinaryDownloadUrl', async () => { const options: MongoBinaryOpts = { arch: 'x64', downloadDir: '/path/to/somewhere', os: { os: 'linux', dist: 'custom', release: '100.0', }, version: '4.0.0', }; const mbd = new MongoBinaryDownload(options); jest.spyOn(DryMongoBinary, 'generateOptions'); // @ts-expect-error "getPath" is protected const path = await mbd.getPath(); expect(DryMongoBinary.generateOptions).toBeCalledWith(expect.objectContaining(options)); expect(path).toMatchSnapshot(); }); });
the_stack
class cmappClass { public authCallBack:any; // 对应 以下参数 func,当类型function时授权之后返回到上一页执行一次func public authType:number; // 对应authTypeObj public authTypeObj:Array<any>; // 微信授权 public environmentInfo: any = { userAgent: null, isMiniprogram: !window, // 是否为小程序环境 isElectron: 0, // 是否为electron环境 isWeixin: 0, // 微信环境 isWechat: 0, // 公众号环境 isWxwork: 0, // 企业微信环境 isDevtools: 0, // 微信开发者工具环境 isApp: 0, // app环境 isHvoi: 0, // 特定手机或系统 isWebview: 0, // 是否为内嵌的webview appType: 0 }; // 环境详情参数 public innerAudioContext: any; constructor() { this.authType = 0; this.authTypeObj = [ { type: 'scope.userLocation', title: '温馨提示', content: '需要获取您的位置信息', ts: '未授权微信获取位置', }, { type: 'scope.werun', title: '温馨提示', content: '需要获取您的运动信息', ts: '未授权微信获取步数', }, { type: 'scope.camera', title: '温馨提示', content: '需要获取您的系统相机', ts: '未授权微信获取相机', }, ]; } getUniApi(uniApi: any, config = {}) { let isSuccess = 0; return new Promise((resolve: any, reject: any) => { const callback = { ...config, success(res: any) { isSuccess = 1; resolve({ isSuccess, res, }); }, fail(res: any) { reject({ isSuccess, res, }); }, } uniApi(callback); }); } isApp() { return window && window.plus || false; } setStorage(key: string, value: any, type = 'uni') { if (type === 'plus') { this.isApp() && window.plus.storage.setItem(key, value) || window.localStorage.setItem(key, value); return; } uni.setStorageSync(key, value); } getStorage(key: string, type = 'uni') { if (type === 'plus') { return this.isApp() && window.plus.storage.getItem(key) || window.localStorage.getItem(key) || ''; } return uni.getStorageSync(key) || ''; } removeStorage(key: string, type = 'uni') { if (key) { if (type === 'plus') { this.isApp() && window.plus.storage.removeItem(key) || window.localStorage.removeItem(key); return; } uni.removeStorageSync(key); } else { window && window.localStorage.clear(); uni.clearStorageSync(); } } updateLS(k:string, timeKey:string, s:number, func:any) { // k值的timeKey超过s分钟为过期,过期(id=0)则清除k值 const cmapp:any = this; const nd:any = new Date().valueOf(); const kid:any = cmapp.getStorage(k); const time:any = cmapp.getStorage(timeKey); let id:number = 1; if (kid && time && nd - time >= 1000 * 60 * s) { cmapp.removeStorage(k); id = 0; } if (typeof func === 'function') { func(id); } } getSearchValue(name: string, path = '') { let reg: any = new RegExp(name + '=([^&]*)(&|$)', 'i'); const params = path || (!this.environmentInfo.isMiniprogram && window.location.href || ''); reg = params.substr(1).match(reg); const value = reg != null ? reg[1] : null; return value; } getQuery($vue: any, key: string) { const route = '_route'; let query = $vue.$mp && $vue.$mp.query || null; const query2 = $vue[route] && $vue[route].query || null; const query3 = $vue.__page__ && $vue.__page__.options || null; query = query || query2 || query3; if (key === 'query') { return query || ''; } const value2 = !this.environmentInfo.isMiniprogram && window.location.href.includes(`${key}=`) && this.getSearchValue(key) || ''; return query && query[key] || value2 || ''; } getSelectorInfo(selector: string) { return new Promise((resolve: any) => { const query: any = uni.createSelectorQuery(); query.select(selector).boundingClientRect(); query.selectViewport().scrollOffset(); query.exec((res: any) => { resolve(res); }); }); } getDivMatrix(m:any) { // 获取旋转对象div的matrix转换为角度 const d1:number = 180; const d2:number = 360; const aa:any = Math.round(d1 * Math.asin(m[0]) / Math.PI); const bb:any = Math.round(d1 * Math.acos(m[1]) / Math.PI); const cc:any = Math.round(d1 * Math.asin(m[2]) / Math.PI); const dd:any = Math.round(d1 * Math.acos(m[3]) / Math.PI); let deg:any = 0; if (aa === bb || -aa === bb) { deg = dd; } else if (-aa + bb === d1) { deg = d1 + cc; } else if (aa + bb === d1) { deg = d2 - cc || d2 - dd; } return deg >= d2 ? 0 : deg; } /** * 获取旋转对象div的matrix * @param selector */ getDivDeg(selector: string) { const $cmapp: any = this; return new Promise((resolve: any, reject: any) => { uni.createSelectorQuery().select(selector).fields({ dataset: true, size: true, scrollOffset: true, properties: ['scrollX', 'scrollY'], computedStyle: ['animation', 'transform'], context: true, }, async function (res: any) { if (res.transform) { const transform: any = res.transform; const matrix: any = transform.split(','); if (matrix && matrix.length > 0) { matrix[0] = matrix[0].split('(').pop(); const deg: any = await $cmapp.getDivMatrix(matrix); resolve(deg); } else { reject(0); } } else { reject(0); } }).exec(); }); } update() {// 升级 const cmapp:any = this; const updateManager:any = uni.getUpdateManager(); updateManager.onCheckForUpdate((res:any) => { // 请求完新版本信息的回调 console.log(res.hasUpdate); }); updateManager.onUpdateReady(function () { cmapp.removeStorage(''); const a:object = { title: '新版本更新中..', icon: 'none', }; uni.showToast(a); updateManager.applyUpdate(); }); updateManager.onUpdateFailed(() => { // 新版本下载失败 }); } /** * 打开页面 只用于 cmapp.isToAuth 中转(所有点击都必须经过cmapp.isToAuth) * @param url 路由 * @param navigateType 类型 switchTab、reLaunch、navigateTo、redirectTo、navigateBack */ jumpTo(url:string, navigateType:string, isAuth = 'no') { if (!url && navigateType !== 'navigateBack') { console.log(isAuth); return; } switch (navigateType) { case 'switchTab': uni.switchTab({ url: url }); break; case 'reLaunch': uni.reLaunch({ url: url }); break; case 'navigateBack': uni.navigateBack(); break; case 'navigateTo': uni.navigateTo({ url: url }); break; case 'redirectTo': uni.redirectTo({ url: url }); break; case 'yes': uni.redirectTo({ url: url }); break;// 同redirectTo default: uni.navigateTo({ url: url }); break; } } /** * 统一点击方法 cmapp.isToAuth // 对应 以下参数 func,当类型function时授权之后返回到上一页执行一次func */ isToAuth(page:any, navigateType:any, func:any) { const cmapp:any = this; const wxinfo = cmapp.getStorage('userInfo'); const nb = 'navigateBack'; let nt = navigateType; if (wxinfo && wxinfo.openid) { if (nt === nb && typeof func === 'function') { func(); return; } cmapp.jumpTo(page, navigateType); } else { if (nt === nb && typeof func === 'function') { cmapp.authCallBack = func; } if (!nt) { nt = 'redirectTo'; } const shareUrl = encodeURIComponent(page); const authUrl = `/pages/index?shareUrl=${shareUrl}&navigateType=${nt}`; cmapp.jumpTo(authUrl, 'navigateTo'); } } /** * 执行cmapp.isToAuth中参数func的方法 * 需要在执行了cmapp.isToAuth方法时的页面onShow中加 this.$cmapp.getAuthCallBack(); */ getAuthCallBack() { const cmapp:any = this; const isCallBack:any = cmapp.getStorage('isCallBack'); if (typeof cmapp.authCallBack === 'function' && isCallBack && isCallBack === 'yes') { cmapp.authCallBack(); cmapp.authCallBack = ''; cmapp.removeStorage('isCallBack'); } else if (isCallBack === 'yes') { cmapp.authCallBack = ''; cmapp.removeStorage('isCallBack'); } } /** 小程序登录获取code */ getCode() { let code:any = null; return new Promise((resolve, reject) => { uni.login({ success: async (res:any) => { if (res.code) { code = res.code; } resolve(code); }, fail: async () => { reject(code); }, }); }); } /** * 检测是否授权 * @param key 是否存在的Stroage的key * @param func1 * @param func2 * @returns {Promise<void>} */ async checkLogin(key:any, func1:any, func2:any) { const cmapp:any = this; const storageValue = cmapp.getStorage(key); if (storageValue) { await func1(); } else { await func2(); } } /** * 获取openid * @param t * @param code * @param func * @returns {Promise<void>} */ async getOpenid($vue:any, code:any) { const cmapp:any = this; return new Promise(async (resolve) => { const responseData = await $vue.$uniAjax.http($vue.$api.sign.getUserId, { apptype: $vue.$config.project.type, plat: $vue.$config.platform, code: code, }, { method: 'POST', }); const openid = responseData.isSuccess && responseData.data && responseData.data.list && responseData.data.list.openid || null; openid && cmapp.setStorage('openid', openid); !openid && cmapp.removeStorage('openid'); resolve(openid); }); } /** * 保存用户信息 * @param t * @param info * @param func * @returns {Promise<void>} */ saveUserInfo(t:any, info:any, func:any) { const cmapp:any = this; info.platform = t.$config.platform; info.apptype = t.$config.project.type; info.openid = info.openid ? info.openid : t.$cmapp.getStorage('openid'); t.$uniAjax.http(t.$api.sign.saveUserInfo, info, { method: 'POST', }, (isSuc:number, res:any) => { t.$store.dispatch('setUserInfo', info); cmapp.setStorage('userInfo', info); let d:any = null; if (isSuc) { d = res.data; } if (typeof func === 'function') { func(d); } }, 'no'); } /** * 已授权 直接到对应的shareUrl页面 * @param t * @param isTs */ authToPage(t:any, isTs = 'no', time:any) { const cmapp:any = this; let url = `/pages/${t.$config.project.type}/index`; const shareUrl = cmapp.getStorage('shareUrl'); if (shareUrl) { url = decodeURIComponent(shareUrl); } if (t.navigateType === 'navigateBack') { cmapp.setStorage('isCallBack', 'yes'); } if (isTs === 'no') { cmapp.jumpTo(url, t.navigateType); return; } let timeOut = 2000; if (time) { timeOut = time; } setTimeout(() => { cmapp.jumpTo(url, t.navigateType); }, timeOut); } /** * 获取分享路由所带的参数 * @param query * @param k * @returns {Promise<void>} */ getUrlParams(t:any, query:any, k:any) { const cmapp:any = this; if (query && query[k]) { cmapp.setStorage(k, decodeURIComponent(query[k])); } else { cmapp.removeStorage(k); } } /** * 入口页面 * @param t * @param isAuth 有tabs并且当前页面是tabs中一页时必为yes * @param query * @param func * @returns {Promise<void>} */ async noAuthIndex(t:any, isAuth = 'no', query:any, func:any) { const cmapp:any = this; uni.showLoading({ title: '数据加载中..' }); await cmapp.getUrlParams(t, query, 'scene'); await cmapp.getUrlParams(t, query, 'shareId'); await cmapp.getUrlParams(t, query, 'shareUrl'); await cmapp.getUrlParams(t, query, 'returnUrl'); if (query && query.navigateType) { t.navigateType = query.navigateType; } const d = async () => { uni.hideLoading(); t.isLoadEnd = 1; let shareUrl:any = cmapp.getStorage('shareUrl'); const userInfo:any = cmapp.getStorage('userInfo'); if (userInfo) { t.$store.dispatch('setUserInfo', userInfo); await t.$cmapp.saveUserInfo(t, userInfo); } if (isAuth === 'yes') { if (userInfo && shareUrl) { cmapp.authToPage(t, 'no'); return; } if (typeof func === 'function') { func(); } return; } if (shareUrl) { shareUrl = decodeURIComponent(shareUrl); cmapp.jumpTo(shareUrl, query.navigateType || ''); } if (typeof func === 'function') { func(); } }; cmapp.checkLogin('openid', () => { d(); }, async () => { cmapp.getCode().then((code:any) => { cmapp.getOpenid(t, code).then(() => { d(); }); }); }); } /** * PopWin.vue关闭窗口 */ closePop(t:any, time = 1, func:any) { setTimeout(() => { t.popIsShow = 'no'; if (typeof func === 'function') { func(); } }, time * 1000); } /** * 设置分享信息 * @param t * @param d d参数如下4个: * @param sharePage 已授权后打开的路由 * @param shareIndex 未授权时打开的页面,默认/pages/${t.$config.project.dir}/index * @param shareTitle 分享标题 * @param shareUrl 打开sharePage或shareIndex之后再打开的shareUrl,默认不打开 * @returns {{path: (*|string), title: (string|*)}} */ setShareMessage(t:any, d:any) { const cmapp:any = this; let path = d.sharePage; const userInfo = cmapp.getStorage('userInfo'); if (!userInfo) { path = d.shareIndex ? `${d.shareIndex}` : `/pages/${t.$config.project.dir}/index`; } path += path.includes('?') ? '&' : '?'; path += `shareId=${cmapp.getStorage('openid') ? cmapp.getStorage('openid') : ''}`; path += `&scene=${cmapp.getStorage('scene') ? cmapp.getStorage('scene') : ''}`; if (d.shareUrl) { path += `&shareUrl=${encodeURIComponent(d.shareUrl)}`; } const title = d.shareTitle ? `${d.shareTitle}` : t.$config.project.name; return { title: title, path: path, }; } /** * 支付宝 设置主题颜色 */ setNavigationBarColor() { // #ifdef MP-ALIPAY const bgColor = '#1890FF'; const txtColor = '#FFFFFF'; uni.setNavigationBarColor({ frontColor: txtColor, backgroundColor: bgColor, animation: { duration: 400, timingFunc: 'easeIn', }, }); // #endif } notFound() { // 页面不存在时自动到首页 // @ts-ignore uni.onPageNotFound((res:any) => { uni.showToast({ title: '页面出错,自动到首页', icon: 'none', }); let q:any = ''; if (res.query && res.query.scene) { const scene = decodeURIComponent(res.query.scene); q = `?scene=${scene}`; } setTimeout(() => { uni.redirectTo({ url: `/pages/index${q}` }); }, 2000); }); } /** * 结合h5跳转路由 * @param path * @param url * @param type */ goToWindow(url:any, type:any) { // #ifdef APP-PLUS this.setStorage('h5url', url); this.jumpTo('/pages/common/h5', '', ''); // #endif // #ifndef APP-PLUS // #ifdef H5 const w:any = window; if (type === 'email') { w.location = `mailto:${url}`; return; } w.location = url; // #endif // #ifndef H5 uni.showToast({ title: '请打开aiplat.com查看', icon: 'none', }); // #endif // #endif } tsCity(cityName:string) { // 删除市、区、县 三字 const lastStr:any = cityName.substr(cityName.length - 1); const filterWords:Array<string> = ['市', '区', '县']; if (filterWords.includes(lastStr) && cityName.length > 2) { cityName = cityName.slice(0, -1); } return cityName; } lessThan10(num: any) { // 0~9前加0 return num < 10 ? `0${num}` : num; } /* * 1,当前日期时间戮 cmapp.nowTime(0,0); * 2,日期转时间戮 cmapp.nowTime(0,'2017-01-01'); * 3,时间戮转日期 cmapp.nowTime(1,'1500002222',f);//f为格式 * */ nowTime(type: any, dateTime: any, format: any, isMillisecond: any) { let nowTime: any = null; let value: any = null; if (dateTime) { nowTime = new Date(dateTime); } else { nowTime = new Date(); } if (type === 0) { // 日期转时间戮 const v: any = nowTime.valueOf() / 1000; if (isMillisecond) { return nowTime.valueOf(); } value = parseInt(v, 10); } else { // 时间戮转日期 const y: any = nowTime.getFullYear(); const m: any = this.lessThan10(nowTime.getMonth() + 1); const d: any = this.lessThan10(nowTime.getDate()); const h: any = this.lessThan10(nowTime.getHours()); const m2: any = this.lessThan10(nowTime.getMinutes()); const s: any = this.lessThan10(nowTime.getSeconds()); switch (format) { case 1: value = `${y}-${m}-${d} ${h}:${m2}:${s}`; break; case 2: value = `${y}/${m}/${d} ${h}:${m2}:${s}`; break; case 3: value = `${y}/${m}/${d}`; break; case 4: value = `${y}/${m}`; break; case 5: value = `${m}/${d}`; break; case 6: value = `${y}-${m}-${d}`; break; case 7: value = `${y}-${m}`; break; case 8: value = `${m}-${d}`; break; case 9: value = `${h}:${m2}:${s}`; break; case 10: value = `${y}年${m}月${d}日`; break; case 11: value = `${y}-${m}-${d} ${h}:${m2}`; break; case 12: value = `${y}/${m}/${d} ${h}:${m2}`; break; case 13: value = `${y}年${m}月${d}日 ${h}:${m2}`; break; default: value = `${y}-${m}-${d}`; break; } } return value; } /** * 倒计时(进度条显示的时间) */ countDownTime(time: any, type: any, isFan: any) { let nowTime: any = new Date().valueOf(); let jdt: any = 0; const arr: Array<any> = [3600, 24, 60, 10]; let time2: any = time; if (isFan) { const a: any = nowTime; nowTime = time2; time2 = a; } if (time2 && time2 > nowTime) { const v1: any = (time2 - nowTime) / (arr[3] * arr[3] * arr[3]); const n: number = parseInt(v1, arr[3]); const v2: any = n / (arr[0] * arr[1]); const day: number = parseInt(v2, arr[3]); const v3: any = ((n - day * arr[0] * arr[1]) / arr[0]); const hour: number = parseInt(v3, arr[3]); const v4: any = ((n - day * arr[0] * arr[1] - hour * arr[0]) / arr[2]); const minutes: number = parseInt(v4, arr[3]); const seconds: any = n - day * arr[0] * arr[1] - hour * arr[0] - minutes * arr[2]; jdt = `${day}天${hour}时${minutes}分${seconds}秒`; if (day <= 0) { if (type === 1) { jdt = `${hour}时${minutes}分${seconds}秒`; } if (hour <= 0 && type === 2) { jdt = `${minutes}分${seconds}秒`; } } if (type === 3) { jdt = { day: day, hour: hour, minutes: minutes, seconds: seconds, }; } } return jdt; } checkMobile(value: any) { let reg: string = '^[1][3,4,5,6,7,8,9][0-9]{9}$'; const regExp: any = new RegExp(reg); return regExp.test(value); } isIllegalMobile(value: any, txt = '手机号码') { let message = [`${txt}正确`, `请输入11位${txt}`, `${txt}必须为11位数字`, `${txt}格式为1(3~9)开头`]; let illegalId = 0; if (!value || value.length !== 11) { illegalId = 1; } else if (!this.checkWord(value, 1)) { illegalId = 2; } else if (!this.checkMobile(value)) { illegalId = 3; } return { illegalId, message: message[illegalId], }; } /** * 默认type=0:只限中文、英文 * type=1:只限数字 * type=2:只限数字和小数点 * type=3:只限中文 * type=4:只限英文 * type=5:只限大写英文 * type=6:只限小写英文 * type=7:只限中文、英文、数字和小数点 * @param v * @param type * @returns {*} */ checkWord(value: any, type: any) { let reg: string = '^[A-Za-z\u4e00-\u9fa5]+$'; switch (type) { case 1: reg = '^[0-9]+$'; break; case 2: reg = '^[0-9.]+$'; break; case 3: reg = '^[\u4e00-\u9fa5]+$'; break; case 4: reg = '^[A-Za-z]+$'; break; case 5: reg = '^[A-Z]+$'; break; case 6: reg = '^[a-z]+$'; break; case 7: reg = '^[A-Za-z0-9.\u4e00-\u9fa5]+$'; case 8: reg = '^[0-9-]+$'; break; default: break; } const regExp: any = new RegExp(reg); return regExp.test(value); } openWxSetting(func:any, func2:any) {// 打开设置 const cmapp:any = this; const a:any = { success() { cmapp.openWxAuth(0, func, func2); }, fail() { func2(func); }, }; uni.openSetting(a); } openWxAuth(type:any, func:any, func2:any) {// 提示授权的操作 const cmapp:any = this; uni.authorize({ scope: cmapp.authTypeObj[cmapp.authType].type, success(res:any) { // data: {scope.userInfo: "ok"} // res.data[cmapp.authTypeObj[cmapp.authType].type] === 'ok' // #ifdef MP-TOUTIAO if (res.data[cmapp.authTypeObj[cmapp.authType].type] === 'ok') { func(0, func); } else { func2(func); } // #endif // #ifndef MP-TOUTIAO func2(func); // #endif }, fail() { if (type === 1) { uni.hideLoading(); uni.showModal({ title: cmapp.authTypeObj[cmapp.authType].title, content: cmapp.authTypeObj[cmapp.authType].content, success(res:any) { if (res.confirm) { cmapp.openWxSetting(func, func2); } else if (res.cancel) { if (typeof func === 'function') { func(1); } } }, }); } else { func2(func); } }, }); } /** *是否授权过 * @param func 如(id, authData) => {} , id=0已授权,id=1取消授权 * @param func2 */ checkWxUserAuth(func:any, func2:any) { const cmapp:any = this; uni.getSetting({ success(res:any) { const a = res.authSetting[cmapp.authTypeObj[cmapp.authType].type] !== undefined && res.authSetting[cmapp.authTypeObj[cmapp.authType].type] !== true; const b = res.authSetting[cmapp.authTypeObj[cmapp.authType].type] === undefined; const c = JSON.stringify(res.authSetting) === '{}'; let aa = a; // #ifdef MP-TOUTIAO aa = aa || c; // #endif if (aa) { cmapp.openWxAuth(1, func, func2); } else if (b) { func2(func); } else { func(0, func); } }, }); } getWebGeo(t:any, localGeo:any, func:any) {// 经纬度转为地址信息 const cmapp:any = this; const keyId:any = Math.round(Math.random() * (t.$config.map.keys.length - 1)); const d:object = { location: `${localGeo.latitude},${localGeo.longitude}`, ak: t.$config.map.keys[keyId], output: 'json', coordtype: 'gcj02ll', latest_admin: 1, }; uni.request({ url: t.$config.map.host + t.$config.map.apis.geocoder, data: d, method: 'GET', header: { 'content-type': 'application/json', // 默认值 }, success: async function (res:any) { if (res.data && res.data.status === 0) { const result:any = { ...res.data.result }; const lg:any = result.addressComponent; lg.cityName = cmapp.tsCity(lg.city); lg.lng = localGeo.longitude; lg.lat = localGeo.latitude; cmapp.setStorage('localGeo', lg); } if (typeof func === 'function') { func(); } }, fail: async () => { if (typeof func === 'function') { func(); } }, }); } // 获取微信经纬度 getLocation(func:any) { uni.getLocation({ type: 'wgs84', success(res:any) { const localGeo:any = { longitude: res.longitude, latitude: res.latitude, }; if (typeof func === 'function') { func(2, localGeo); } }, fail() { if (typeof func === 'function') { func(1); } }, }); } // 判断是否要显示loading showLoad 为 yes 或者 no showLoad(t:any, type:any) { if (!t.showLoad || t.showLoad !== 'no') { if (type === 1) { uni.showLoading({ title: '数据加载中..', }); return; } if (type === 0) { uni.hideLoading(); } } } // 需要授权地理位置的页面 // const t = this; // cmapp.authType = 0; // cmapp.checkLocalGeo(t, () => { // 授权或取消后页面执行的方法 // }); checkLocalGeo(t:any, func3:any) { const cmapp:any = this; cmapp.showLoad(t, 1); cmapp.authType = 0; cmapp.checkWxUserAuth(function (id:any, authData:any) { if (id === 1) { cmapp.showLoad(t, 0); func3(); } else if (id === 2) { cmapp.getWebGeo(t, authData, () => { cmapp.showLoad(t, 0); func3(); }); } else { const localGeo:any = cmapp.getStorage('localGeo'); if (!localGeo || (localGeo && !localGeo.lng)) { cmapp.getLocation(authData); } else { cmapp.showLoad(t, 0); func3(); } } }, cmapp.getLocation); } /** * 重置动画 * @param $vue */ animationReset($vue: any) { const animation: any = uni.createAnimation({ duration: 100, }); animation.rotate(0).step(); $vue.animationData = animation.export(); } /** * 指定div或图左右摇摆的动画 * @param $vue * @param animationAngle 摇摆角度 * @param maxRun 摇摆次数 * @param duration 每次摇摆的时间 * @param callback * div中必有 :animation='animationData' * data中必有 animationData = {}字段 */ animationShake($vue: any, animationAngle = -10, maxRun = 6, duration = 500, callback: any) { const $cmapp: any = this; const animationRun: any = uni.createAnimation({ duration: duration, timingFunction: 'ease', }); animationRun.rotate(animationAngle).step(); $vue.animationData = animationRun.export(); let num: number = 0; const thisShake = setInterval(() => { num += 1; if (num > maxRun || $vue.animationEnd) { $vue.animationEnd = false; $cmapp.animationReset($vue); clearInterval(thisShake); if (typeof callback === 'function') { callback(); } return; } animationAngle = -animationAngle; animationRun.rotate(animationAngle).step(); $vue.animationData = animationRun.export(); }, duration + 5); } /** * showToast方法封装 * @param title 内容 * @param icon 图标 * @param duration 持续时间 */ showToast(title = '网络出错了', icon = 'none', duration = 2000, position = 'center') { return new Promise((resolve: any) => { const params: any = { title, icon, duration, position, mask: true, complete: (res:any) => { setTimeout(() => { resolve(res); }, duration); } } uni.showToast(params); }); } /** * 内部 audio 音乐播放 * @param audioUrl * @param autoplay */ toPlayAudio(audioUrl: string, autoplay = true) { const $cmapp: any = this; return new Promise((resolve, reject) => { if (this.innerAudioContext) { this.innerAudioContext.destroy(); } this.innerAudioContext = uni.createInnerAudioContext(); this.innerAudioContext.autoplay = autoplay; this.innerAudioContext.src = audioUrl; this.innerAudioContext.play(); this.innerAudioContext.onPlay(() => { this.showToast('播放成功'); resolve({ isSuccess: 1, message: '播放成功', errCode: 0, innerAudioContext: $cmapp.innerAudioContext }); }); this.innerAudioContext.onError((responseData: any) => { this.showToast('播放失败'); reject({ isSuccess: 0, message: responseData, errCode: 0, innerAudioContext: this.innerAudioContext }); }); this.innerAudioContext.onEnded(() => { this.innerAudioContext.destroy(); this.showToast('播放已结束'); }); this.innerAudioContext.onStop((responseData: any) => { this.showToast('播放已停止'); }); }); } /** * 保存图片到手机 * @param isCanvas yes为从canvas保存过去,no为普通保存 * @param id isCanvas=yes时必填 * @param filePath isCanvas=no时必填 * @param callback */ saveImageToPhotosAlbum(isCanvas = 'no', id: any, filePath: any, callback: any) { const $cmapp: any = this; uni.showLoading({ title: '保存中..' }); let toast: string = '保存失败'; const save: any = (path: string) => { uni.saveImageToPhotosAlbum({ filePath: path, success() { uni.hideLoading(); toast = '保存成功'; $cmapp.showToast(toast); setTimeout(() => { if (typeof callback === 'function') { callback(); } }, 2000); }, fail() { uni.hideLoading(); $cmapp.showToast(toast); }, }); }; if (isCanvas === 'no') { save(filePath); return; } uni.canvasToTempFilePath({ canvasId: id, success(responseData: any) { save(responseData.tempFilePath); }, fail() { uni.hideLoading(); $cmapp.showToast(toast); }, }); } /** * canvas内文本自动换行 * @param ctx getContext('2d') 对象 * @param lineheight 行高 * @param bytelength 每行字数 * @param text 文本 * @param startleft 开始x坐标 * @param starttop 开始y坐标 */ canvasTextAutoLine(ctx: any, lineheight: any, bytelength: any, text: any, startleft: any, starttop: any) { const getTrueLength: any = (str: any) => { const length: any = str.length; let truelen: any = 0; for (let x: any = 0; x < length; x++) { if (str.charCodeAt(x) > 128) { truelen += 2; } else { truelen += 1; } } return truelen; }; const cutString: any = (str: any, leng: any) => { const len: any = str.length; let tlen: any = len; let nlen: any = 0; for (let x: any = 0; x < len; x++) { if (str.charCodeAt(x) > 128) { if (nlen + 2 < leng) { nlen += 2; } else { tlen = x; break; } } else { console.log(); if (nlen + 1 < leng) { nlen += 1; } else { tlen = x; break; } } } return tlen; }; for (let i: any = 1; getTrueLength(text) > 0; i++) { const tl: any = cutString(text, bytelength); ctx.fillText(text.substr(0, tl).replace(/^\s+|\s+$/, ''), startleft, (i - 1) * lineheight + starttop); text = text.substr(tl); } } /** * 返回到已打开的某个页面 * @param url 为要返回到的那个页面的路由地址,如pages/aiplat/index * @param url2 如果是要返回到某个页面时并要打开在这个页面才有的入口页面,返回到url时要再进入url2 * @param callback */ backTo(url: string, url2: string) { const currentPages: any = getCurrentPages(); const isCurrentPage: any = currentPages.filter((x: { route: string; }) => x.route === url); return new Promise((resolve: any) => { if (isCurrentPage && isCurrentPage.length > 0) { const page: any = currentPages.length - currentPages.indexOf(isCurrentPage[0]) - 1; uni.navigateBack({ delta: page, }); if (url2) { setTimeout(() => { uni.navigateTo({ url: url2, }); }, 100); } } resolve(); }); } openLocation(latitude: any, longitude: any, name: string, address: string) { latitude = parseFloat(latitude); longitude = parseFloat(longitude); this.getUniApi(uni.openLocation, { latitude, longitude, scale: 18, name, address, }).then((responseData:any) => { console.log(responseData); }).catch((responseData:any) => { console.log(responseData); }); } onAccelerometerChange($vue: any, url:string) { this.getUniApi(uni.getSystemInfo).then(() => { uni.onAccelerometerChange((e: any) => { const pages: any = getCurrentPages(); const currentPage: any = pages[pages.length - 1]; if (currentPage.route === url) { currentPage.$vm.onAccelerometerChange(e); } }); }).catch((responseData:any) => { console.log(responseData); }); } scrollTo(scrollTop: number, duration: number, selector: string) { return new Promise<void>((resolve) => { const params: object = { scrollTop: scrollTop || 0, duration: duration || 999, selector: selector || '', complete: () => { resolve(); } }; uni.pageScrollTo(params); }); } eventListener(type: string, eventName: any, func: any) { if (!eventName) { return; } if (type === 'dispatchEvent') { const event: any = new Event(eventName); event && window.dispatchEvent(event); return; } window.addEventListener(eventName, func); } showInfo(title:any,content:any, showCancel:any, cancelText:any, confirmText:any, confirmColor:any, completeFunction:any) { if (!content) { return; } uni.showModal({ title: title || '温馨提示', content: content, showCancel: showCancel || false, cancelText: cancelText || '取消', confirmText: confirmText || '确定', confirmColor: confirmColor || '#ff8b15', complete: (res:any)=>{ completeFunction && completeFunction(res); } }); } getAppType() { if (!window) { return 'miniprogram'; } const userAgent = window.navigator.userAgent.toLowerCase(); if (userAgent && /(android)/i.test(userAgent)) { return 'android'; } else if (userAgent && /(iphone|ipad|ipod|ios)/i.test(userAgent)) { return 'ios'; } else if (userAgent && /(mobile|micromessenger)/i.test(userAgent)) { return 'mobile'; } return 'pc'; // pc } async setEnvironmentInfo($vue: any) { this.environmentInfo.isMiniprogram = !window; this.environmentInfo.isWebview = this.getQuery($vue, 'isWebview') ? 1 : 0; this.environmentInfo.appType = this.getAppType(); // #ifdef APP-PLUS this.environmentInfo.isApp = 1; // #endif const weixinType = this.getQuery($vue, 'weixinType') || this.getStorage('weixinType'); if (weixinType) { this.setStorage('weixinType', weixinType); } // #ifdef H5 this.environmentInfo.userAgent = window.navigator.userAgent.toLowerCase(); this.environmentInfo.isElectron = this.environmentInfo.userAgent.includes('electron') ? 1 : 0; this.environmentInfo.isWeixin = this.environmentInfo.userAgent.includes('micromessenger') ? 1 : 0; this.environmentInfo.isWxwork = this.environmentInfo.userAgent.includes('wxwork') ? 1 : 0; this.environmentInfo.isWechat = (this.environmentInfo.isWeixin && !this.environmentInfo.isWxwork) || this.environmentInfo.userAgent.includes('wechat') ? 1 : 0; this.environmentInfo.isDevtools = this.environmentInfo.userAgent.includes('wechatdevtools') ? 1 : 0; this.environmentInfo.isApp = this.environmentInfo.userAgent.includes('html5plus') ? 1 : 0; const hvoi = this.environmentInfo.userAgent.includes('huawei') || this.environmentInfo.userAgent.includes('vivo') || this.environmentInfo.userAgent.includes('oppo') || this.environmentInfo.userAgent.includes('iphone'); this.environmentInfo.isHvoi = hvoi ? 1 : 0; // #endif if (weixinType === 'wechat') { this.environmentInfo.isWechat = 1; this.environmentInfo.isWxwork = 0; } if (weixinType === 'wxwork') { this.environmentInfo.isWechat = 0; this.environmentInfo.isWxwork = 1; } $vue.$forceUpdate(); } } export default cmappClass;
the_stack
import axios from 'axios'; import * as React from 'react'; import { Alert } from 'react-bootstrap'; import { RouteComponentProps } from 'react-router-dom'; import { DynamicMix } from '../../models/DynamicMix'; import { SongData } from '../../models/SongData'; import { StaticMix } from '../../models/StaticMix'; import HomeNavBar from '../Nav/HomeNavBar'; import DeleteDynamicMixModal from '../SongTable/Modal/DeleteDynamicMixModal'; import DeleteStaticMixModal from '../SongTable/Modal/DeleteStaticMixModal'; import DeleteTrackModal from '../SongTable/Modal/DeleteTrackModal'; import DynamicMixModal from '../SongTable/Modal/DynamicMixModal'; import StaticMixModal from '../SongTable/Modal/StaticMixModal'; import SongTable from '../SongTable/SongTable'; import UploadModal from '../Upload/UploadModal'; import AutoRefreshButton from './AutoRefreshButton'; import './Home.css'; import MusicPlayer from './MusicPlayer'; interface SeparationTask { srcId: string; id: string; status: string; } interface State { /** * Whether to show delete dynamic mix modal */ showDeleteDynamicMixModal: boolean; /** * Whether to show delete static mix modal */ showDeleteStaticMixModal: boolean; /** * Whether to show delete track modal */ showDeleteTrackModal: boolean; /** * Whether to show mix modal */ showDynamicMixModal: boolean; /** * Whether to show source separation modal */ showStaticMixModal: boolean; /** * Whether to show upload modal */ showUploadModal: boolean; /** * List of songs seen in the song table */ songList: SongData[]; /** * Current song, if it is a source song */ currentSrcSong?: SongData; /** * Current song, if it is a static mix */ currentStaticMix?: StaticMix; /** * Current source song displayed in modal */ currentModalSrcSong?: SongData; /** * Current dynamic mix displayed in modal */ currentModalDynamicMix?: DynamicMix; /** * Current static mix displayed in modal */ currentModalStaticMix?: StaticMix; /** * Whether audio is playing */ isPlaying: boolean; /** * The separation task that was just submitted */ task?: SeparationTask; /** * List of IDs of expanded rows */ expandedIds: string[]; } /** * Home component where main functionality happens, consisting of the main nav bar * and the song table. */ class Home extends React.Component<RouteComponentProps, State> { taskInterval?: number; audioInstance: HTMLMediaElement | null; constructor(props: RouteComponentProps) { super(props); this.state = { showDeleteDynamicMixModal: false, showDeleteStaticMixModal: false, showDeleteTrackModal: false, showDynamicMixModal: false, showStaticMixModal: false, showUploadModal: false, songList: [], currentSrcSong: undefined, currentStaticMix: undefined, currentModalSrcSong: undefined, currentModalDynamicMix: undefined, currentModalStaticMix: undefined, isPlaying: false, task: undefined, expandedIds: [], }; this.audioInstance = null; } getAudioInstance = (instance: HTMLAudioElement): void => { instance.onvolumechange = null; this.audioInstance = instance; }; onAudioPause = (): void => { this.setState({ isPlaying: false, }); }; onAudioPlay = (): void => { this.setState({ isPlaying: true, }); }; onSrcSongPauseClick = (): void => { this.setState({ isPlaying: false, }); (window as any).reactmusicplayer.onTogglePlay(); }; onSrcSongPlayClick = (song: SongData): void => { if (this.state.currentSrcSong && this.state.currentSrcSong.url === song.url) { this.setState({ isPlaying: true, }); (window as any).reactmusicplayer.onTogglePlay(); } else { this.setState({ currentSrcSong: song, currentStaticMix: undefined, isPlaying: true, }); } }; onStaticMixPauseClick = (): void => { this.setState({ isPlaying: false, }); (window as any).reactmusicplayer.onTogglePlay(); }; onStaticMixPlayClick = (staticMix: StaticMix): void => { if (this.state.currentStaticMix && this.state.currentStaticMix.url === staticMix.url) { this.setState({ isPlaying: true, }); (window as any).reactmusicplayer.onTogglePlay(); } else { this.setState({ currentSrcSong: undefined, currentStaticMix: staticMix, isPlaying: true, }); } }; onDynamicMixSubmit = (srcId: string, id: string): void => { this.setState({ expandedIds: [...this.state.expandedIds, srcId], }); // Open Mixer page in new tab const win = window.open(`/mixer/${id}`, '_blank'); win?.focus(); this.loadData(); }; onStaticMixSubmit = (srcId: string, id: string, status: string): void => { this.setState({ task: { srcId, id, status, }, expandedIds: [...this.state.expandedIds, srcId], }); this.loadData(); // Set task state to null after 5 seconds this.taskInterval = setInterval(() => { this.setState({ task: undefined, }); }, 5000); }; /** * Called when single table row is expanded */ onExpandRow = (row: SongData, isExpand: boolean): void => { if (isExpand) { // Row is expanded, add the row ID to expanded row ID list this.setState({ expandedIds: [...this.state.expandedIds, row.id], }); } else { // Row is collapsed, remove current row ID from list this.setState({ expandedIds: this.state.expandedIds.filter(s => s !== row.id), }); } }; /** * Called when the expand-all button is pressed */ onExpandAll = (isExpandAll: boolean, results: SongData[]): void => { if (isExpandAll) { // Update expanded row ID list to contain every row this.setState({ expandedIds: results.map((i: SongData) => i.id), }); } else { // Clear expanded row ID list this.setState({ expandedIds: [], }); } }; onDeleteDynamicMixClick = (mix: DynamicMix): void => { this.setState({ showDeleteDynamicMixModal: true, currentModalDynamicMix: mix }); }; onDeleteStaticMixClick = (mix: StaticMix): void => { this.setState({ showDeleteStaticMixModal: true, currentModalStaticMix: mix }); }; onDeleteTrackClick = (song: SongData): void => { this.setState({ showDeleteTrackModal: true, currentModalSrcSong: song }); }; onDynamicMixClick = (song: SongData): void => { this.setState({ showDynamicMixModal: true, currentModalSrcSong: song }); }; onStaticMixClick = (song: SongData): void => { this.setState({ showStaticMixModal: true, currentModalSrcSong: song }); }; onUploadClick = (): void => { this.setState({ showUploadModal: true }); }; handleDeleteDynamicMixModalHide = (): void => { this.setState({ showDeleteDynamicMixModal: false }); }; handleDeleteDynamicMixModalExited = (): void => { this.setState({ currentModalDynamicMix: undefined }); }; handleDeleteStaticMixModalHide = (): void => { this.setState({ showDeleteStaticMixModal: false }); }; handleDeleteStaticMixModalExited = (): void => { this.setState({ currentModalStaticMix: undefined }); }; handleDeleteTrackModalHide = (): void => { this.setState({ showDeleteTrackModal: false }); }; handleDeleteTrackModalExited = (): void => { this.setState({ currentModalSrcSong: undefined }); }; handleDynamicMixModalHide = (): void => { this.setState({ showDynamicMixModal: false }); }; handleDynamicMixModalExited = (): void => { this.setState({ currentModalSrcSong: undefined }); }; handleStaticMixModalHide = (): void => { this.setState({ showStaticMixModal: false }); }; handleStaticMixModalExited = (): void => { this.setState({ currentModalSrcSong: undefined }); }; handleUploadModalHide = (): void => { this.setState({ showUploadModal: false }); }; /** * Fetch song data from backend */ loadData = async (): Promise<void> => { return axios .get<SongData[]>('/api/source-track/') .then(({ data }) => { if (data) { this.setState({ songList: data }); } }) .catch(error => console.log('API errors:', error)); }; componentDidMount(): void { this.loadData(); } componentWillUnmount(): void { clearInterval(this.taskInterval); } render(): JSX.Element { const { songList, showDeleteDynamicMixModal, showDeleteStaticMixModal, showDeleteTrackModal, showStaticMixModal, showDynamicMixModal, showUploadModal, currentSrcSong, currentStaticMix, currentModalSrcSong, currentModalDynamicMix, currentModalStaticMix, isPlaying, task, expandedIds, } = this.state; const currentSongUrl = currentSrcSong ? currentSrcSong.url : currentStaticMix ? currentStaticMix.url : undefined; return ( <div> <HomeNavBar onUploadClick={this.onUploadClick} /> <div className="jumbotron jumbotron-fluid bg-transparent"> <div className="container secondary-color"> <h2 className="display-5">Track List</h2> <p className="lead">Get started by uploading a song or creating a new mix.</p> <Alert variant="info" style={{ fontSize: '0.9em' }}> <p className="mb-0"> <b>Static mix </b>only keeps the selected parts and completely discards the other parts. No individual volume controls. <br /> <b>Dynamic mix</b> gives you a playback interface with controls to individually adjust the volume levels of all the parts. </p> </Alert> {task && ( <Alert variant="success"> <span> <a target="_blank" rel="noreferrer" href={`/api/mix/static/${task.id}`}> {task.id} </a> : {task.status} </span> </Alert> )} <div className="mb-3 refresher"> <AutoRefreshButton period={10} onRefresh={this.loadData} /> </div> <SongTable data={songList} currentSongUrl={currentSongUrl} isPlaying={isPlaying} expandedIds={expandedIds} onExpandRow={this.onExpandRow} onExpandAll={this.onExpandAll} onDeleteDynamicMixClick={this.onDeleteDynamicMixClick} onDeleteStaticMixClick={this.onDeleteStaticMixClick} onDeleteTrackClick={this.onDeleteTrackClick} onDynamicMixClick={this.onDynamicMixClick} onStaticMixClick={this.onStaticMixClick} onStaticMixPauseClick={this.onStaticMixPauseClick} onStaticMixPlayClick={this.onStaticMixPlayClick} onSrcSongPauseClick={this.onSrcSongPauseClick} onSrcSongPlayClick={this.onSrcSongPlayClick} /> </div> </div> <MusicPlayer getAudioInstance={this.getAudioInstance} songData={currentSrcSong} staticMix={currentStaticMix} onAudioPause={this.onAudioPause} onAudioPlay={this.onAudioPlay} /> <UploadModal show={showUploadModal} hide={this.handleUploadModalHide} refresh={this.loadData} /> <DynamicMixModal show={showDynamicMixModal} hide={this.handleDynamicMixModalHide} exit={this.handleDynamicMixModalExited} submit={this.onDynamicMixSubmit} refresh={this.loadData} song={currentModalSrcSong} /> <StaticMixModal show={showStaticMixModal} hide={this.handleStaticMixModalHide} exit={this.handleStaticMixModalExited} submit={this.onStaticMixSubmit} refresh={this.loadData} song={currentModalSrcSong} /> <DeleteDynamicMixModal show={showDeleteDynamicMixModal} hide={this.handleDeleteDynamicMixModalHide} exit={this.handleDeleteDynamicMixModalExited} refresh={this.loadData} mix={currentModalDynamicMix} /> <DeleteStaticMixModal show={showDeleteStaticMixModal} hide={this.handleDeleteStaticMixModalHide} exit={this.handleDeleteStaticMixModalExited} refresh={this.loadData} mix={currentModalStaticMix} /> <DeleteTrackModal show={showDeleteTrackModal} hide={this.handleDeleteTrackModalHide} exit={this.handleDeleteTrackModalExited} refresh={this.loadData} song={currentModalSrcSong} /> </div> ); } } export default Home;
the_stack
import { ArrayIndexOutOfBoundsError, ArrayStoreError, AuthenticationError, CallerNotMemberError, CancellationError, CannotReplicateError, ClassCastError, ClassNotFoundError, ConcurrentModificationError, ConfigMismatchError, ConsistencyLostError, CPGroupDestroyedError, DistributedObjectDestroyedError, HazelcastError, HazelcastInstanceNotActiveError, IllegalStateError, OperationTimeoutError, IndeterminateOperationStateError, IOError, IllegalArgumentError, IllegalMonitorStateError, IndexOutOfBoundsError, InvalidAddressError, InvalidConfigurationError, InterruptedError, LeaderDemotedError, LockOwnershipLostError, MemberLeftError, NegativeArraySizeError, NoSuchElementError, NoDataMemberInClusterError, NodeIdOutOfRangeError, NotLeaderError, NullPointerError, PartitionMigratingError, QueryError, SessionExpiredError, SplitBrainProtectionError, RetryableHazelcastError, RetryableIOError, StaleAppendRequestError, StaleSequenceError, StaleTaskIdError, TargetDisconnectedError, TargetNotMemberError, TopicOverloadError, TransactionError, TransactionNotActiveError, TransactionTimedOutError, UndefinedErrorCodeError, UnsupportedOperationError, HazelcastSerializationError, ReachedMaxSizeError, WaitKeyCancelledError, } from '../core'; import {ClientProtocolErrorCodes} from './ClientProtocolErrorCodes'; import {ClientMessage} from '../protocol/ClientMessage'; import {ErrorsCodec} from '../codec/builtin/ErrorsCodec'; import {ErrorHolder} from './ErrorHolder'; import {StackTraceElement} from './StackTraceElement'; type ErrorFactory = (msg: string, cause: Error, serverStackTrace: StackTraceElement[]) => Error; /** @internal */ export class ClientErrorFactory { private codeToErrorConstructor: Map<number, ErrorFactory> = new Map(); constructor() { this.register(ClientProtocolErrorCodes.ARRAY_INDEX_OUT_OF_BOUNDS, (m, c, s) => new ArrayIndexOutOfBoundsError(m, c, s)); this.register(ClientProtocolErrorCodes.ARRAY_STORE, (m, c, s) => new ArrayStoreError(m, c, s)); this.register(ClientProtocolErrorCodes.AUTHENTICATION, (m, c, s) => new AuthenticationError(m, c, s)); this.register(ClientProtocolErrorCodes.CALLER_NOT_MEMBER, (m, c, s) => new CallerNotMemberError(m, c, s)); this.register(ClientProtocolErrorCodes.CANCELLATION, (m, c, s) => new CancellationError(m, c, s)); this.register(ClientProtocolErrorCodes.CLASS_CAST, (m, c, s) => new ClassCastError(m, c, s)); this.register(ClientProtocolErrorCodes.CLASS_NOT_FOUND, (m, c, s) => new ClassNotFoundError(m, c, s)); this.register(ClientProtocolErrorCodes.CONCURRENT_MODIFICATION, (m, c, s) => new ConcurrentModificationError(m, c, s)); this.register(ClientProtocolErrorCodes.CONFIG_MISMATCH, (m, c, s) => new ConfigMismatchError(m, c, s)); this.register(ClientProtocolErrorCodes.DISTRIBUTED_OBJECT_DESTROYED, (m, c, s) => new DistributedObjectDestroyedError(m, c, s)); this.register(ClientProtocolErrorCodes.EOF, (m, c, s) => new IOError(m, c, s)); this.register(ClientProtocolErrorCodes.HAZELCAST, (m, c, s) => new HazelcastError(m, c, s)); this.register(ClientProtocolErrorCodes.HAZELCAST_INSTANCE_NOT_ACTIVE, (m, c, s) => new HazelcastInstanceNotActiveError(m, c, s)); this.register(ClientProtocolErrorCodes.HAZELCAST_OVERLOAD, (m, c, s) => new HazelcastError(m, c, s)); this.register(ClientProtocolErrorCodes.HAZELCAST_SERIALIZATION, (m, c, s) => new HazelcastSerializationError(m, c, s)); this.register(ClientProtocolErrorCodes.INDETERMINATE_OPERATION_STATE, (m, c, s) => new IndeterminateOperationStateError(m, c, s)); this.register(ClientProtocolErrorCodes.IO, (m, c, s) => new IOError(m, c, s)); this.register(ClientProtocolErrorCodes.ILLEGAL_ARGUMENT, (m, c, s) => new IllegalArgumentError(m, c, s)); this.register(ClientProtocolErrorCodes.ILLEGAL_STATE, (m, c, s) => new IllegalStateError(m, c, s)); this.register(ClientProtocolErrorCodes.INDEX_OUT_OF_BOUNDS, (m, c, s) => new IndexOutOfBoundsError(m, c, s)); this.register(ClientProtocolErrorCodes.INTERRUPTED, (m, c, s) => new InterruptedError(m, c, s)); this.register(ClientProtocolErrorCodes.INVALID_ADDRESS, (m, c, s) => new InvalidAddressError(m, c, s)); this.register(ClientProtocolErrorCodes.INVALID_CONFIGURATION, (m, c, s) => new InvalidConfigurationError(m, c, s)); this.register(ClientProtocolErrorCodes.MEMBER_LEFT, (m, c, s) => new MemberLeftError(m, c, s)); this.register(ClientProtocolErrorCodes.NEGATIVE_ARRAY_SIZE, (m, c, s) => new NegativeArraySizeError(m, c, s)); this.register(ClientProtocolErrorCodes.NO_SUCH_ELEMENT, (m, c, s) => new NoSuchElementError(m, c, s)); this.register(ClientProtocolErrorCodes.NOT_SERIALIZABLE, (m, c, s) => new IOError(m, c, s)); this.register(ClientProtocolErrorCodes.NULL_POINTER, (m, c, s) => new NullPointerError(m, c, s)); this.register(ClientProtocolErrorCodes.OPERATION_TIMEOUT, (m, c, s) => new OperationTimeoutError(m, c, s)); this.register(ClientProtocolErrorCodes.PARTITION_MIGRATING, (m, c, s) => new PartitionMigratingError(m, c, s)); this.register(ClientProtocolErrorCodes.QUERY, (m, c, s) => new QueryError(m, c, s)); this.register(ClientProtocolErrorCodes.QUERY_RESULT_SIZE_EXCEEDED, (m, c, s) => new QueryError(m, c, s)); this.register(ClientProtocolErrorCodes.SPLIT_BRAIN_PROTECTION, (m, c, s) => new SplitBrainProtectionError(m, c, s)); this.register(ClientProtocolErrorCodes.REACHED_MAX_SIZE, (m, c, s) => new ReachedMaxSizeError(m, c, s)); this.register(ClientProtocolErrorCodes.RETRYABLE_HAZELCAST, (m, c, s) => new RetryableHazelcastError(m, c, s)); this.register(ClientProtocolErrorCodes.RETRYABLE_IO, (m, c, s) => new RetryableIOError(m, c, s)); this.register(ClientProtocolErrorCodes.SOCKET, (m, c, s) => new IOError(m, c, s)); this.register(ClientProtocolErrorCodes.STALE_SEQUENCE, (m, c, s) => new StaleSequenceError(m, c, s)); this.register(ClientProtocolErrorCodes.TARGET_DISCONNECTED, (m, c, s) => new TargetDisconnectedError(m, c, s)); this.register(ClientProtocolErrorCodes.TARGET_NOT_MEMBER, (m, c, s) => new TargetNotMemberError(m, c, s)); this.register(ClientProtocolErrorCodes.TOPIC_OVERLOAD, (m, c, s) => new TopicOverloadError(m, c, s)); this.register(ClientProtocolErrorCodes.TRANSACTION, (m, c, s) => new TransactionError(m, c, s)); this.register(ClientProtocolErrorCodes.TRANSACTION_NOT_ACTIVE, (m, c, s) => new TransactionNotActiveError(m, c, s)); this.register(ClientProtocolErrorCodes.TRANSACTION_TIMED_OUT, (m, c, s) => new TransactionTimedOutError(m, c, s)); this.register(ClientProtocolErrorCodes.UNSUPPORTED_OPERATION, (m, c, s) => new UnsupportedOperationError(m, c, s)); this.register(ClientProtocolErrorCodes.NO_DATA_MEMBER, (m, c, s) => new NoDataMemberInClusterError(m, c, s)); this.register(ClientProtocolErrorCodes.STALE_TASK_ID, (m, c, s) => new StaleTaskIdError(m, c, s)); this.register(ClientProtocolErrorCodes.FLAKE_ID_NODE_ID_OUT_OF_RANGE_EXCEPTION, (m, c, s) => new NodeIdOutOfRangeError(m, c, s)); this.register(ClientProtocolErrorCodes.CONSISTENCY_LOST_EXCEPTION, (m, c, s) => new ConsistencyLostError(m, c, s)); this.register(ClientProtocolErrorCodes.SESSION_EXPIRED_EXCEPTION, (m, c, s) => new SessionExpiredError(m, c, s)); this.register(ClientProtocolErrorCodes.CP_GROUP_DESTROYED_EXCEPTION, (m, c, s) => new CPGroupDestroyedError(m, c, s)); this.register(ClientProtocolErrorCodes.LOCK_OWNERSHIP_LOST_EXCEPTION, (m, c, s) => new LockOwnershipLostError(m, c, s)); this.register(ClientProtocolErrorCodes.ILLEGAL_MONITOR_STATE, (m, c, s) => new IllegalMonitorStateError(m, c, s)); this.register(ClientProtocolErrorCodes.WAIT_KEY_CANCELLED_EXCEPTION, (m, c, s) => new WaitKeyCancelledError(m, c, s)); this.register(ClientProtocolErrorCodes.CANNOT_REPLICATE_EXCEPTION, (m, c, s) => new CannotReplicateError(m, c, s)); this.register(ClientProtocolErrorCodes.LEADER_DEMOTED_EXCEPTION, (m, c, s) => new LeaderDemotedError(m, c, s)); this.register(ClientProtocolErrorCodes.STALE_APPEND_REQUEST_EXCEPTION, (m, c, s) => new StaleAppendRequestError(m, c, s)); this.register(ClientProtocolErrorCodes.NOT_LEADER_EXCEPTION, (m, c, s) => new NotLeaderError(m, c, s)); } createErrorFromClientMessage(clientMessage: ClientMessage): Error { const errorHolders = ErrorsCodec.decode(clientMessage); return this.createError(errorHolders, 0); } private createError(errorHolders: ErrorHolder[], errorHolderIdx: number): Error { if (errorHolderIdx === errorHolders.length) { return null; } const errorHolder = errorHolders[errorHolderIdx]; const factoryFn = this.codeToErrorConstructor.get(errorHolder.errorCode); let error: Error; if (factoryFn != null) { error = factoryFn( errorHolder.message, this.createError(errorHolders, errorHolderIdx + 1), errorHolder.stackTraceElements ); } else { const msg = 'Class name: ' + errorHolder.className + ', Message: ' + errorHolder.message; error = new UndefinedErrorCodeError( msg, this.createError(errorHolders, errorHolderIdx + 1), errorHolder.stackTraceElements ); } return error; } private register(code: number, errorFactory: ErrorFactory): void { this.codeToErrorConstructor.set(code, errorFactory); } }
the_stack
import { AST_NODE_TYPES } from '@typescript-eslint/experimental-utils'; import rule from '../../src/rules/object-curly-spacing'; import { RuleTester } from '../RuleTester'; const ruleTester = new RuleTester({ parser: '@typescript-eslint/parser', }); ruleTester.run('object-curly-spacing', rule, { valid: [ // always - object literals { code: 'var obj = { foo: bar, baz: qux };', options: ['always'] }, { code: 'var obj = { foo: { bar: quxx }, baz: qux };', options: ['always'], }, { code: 'var obj = {\nfoo: bar,\nbaz: qux\n};', options: ['always'] }, { code: 'var obj = { /**/foo:bar/**/ };', options: ['always'] }, { code: 'var obj = { //\nfoo:bar };', options: ['always'] }, // always - destructuring { code: 'var { x } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var { x, y } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var { x,y } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {\nx,y } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {\nx,y\n} = z', options: ['always'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var { /**/x/**/ } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var { //\nx } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var { x = 10, y } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var { x: { z }, y } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {\ny,\n} = x', options: ['always'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var { y, } = x', options: ['always'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var { y: x } = x', options: ['always'], parserOptions: { ecmaVersion: 6 }, }, // always - import / export { code: "import door from 'room'", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import * as door from 'room'", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import { door } from 'room'", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import {\ndoor } from 'room'", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import { /**/door/**/ } from 'room'", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import { //\ndoor } from 'room'", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export { door } from 'room'", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import { house, mouse } from 'caravan'", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import house, { mouse } from 'caravan'", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import door, { house, mouse } from 'caravan'", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: 'var door = 0;export { door }', options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import 'room'", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import { bar as x } from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import { x, } from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import {\nx,\n} from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export { x, } from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export {\nx,\n} from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export { /**/x/**/ } from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export { //\nx } from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: 'var x = 1;\nexport { /**/x/**/ };', options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: 'var x = 1;\nexport { //\nx };', options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, // always - empty object { code: 'var foo = {};', options: ['always'] }, // always - objectsInObjects { code: "var obj = { 'foo': { 'bar': 1, 'baz': 2 }};", options: ['always', { objectsInObjects: false }], }, { code: 'var a = { noop: function () {} };', options: ['always', { objectsInObjects: false }], }, { code: 'var { y: { z }} = x', options: ['always', { objectsInObjects: false }], parserOptions: { ecmaVersion: 6 }, }, // always - arraysInObjects { code: "var obj = { 'foo': [ 1, 2 ]};", options: ['always', { arraysInObjects: false }], }, { code: 'var a = { thingInList: list[0] };', options: ['always', { arraysInObjects: false }], }, // always - arraysInObjects, objectsInObjects { code: "var obj = { 'qux': [ 1, 2 ], 'foo': { 'bar': 1, 'baz': 2 }};", options: ['always', { arraysInObjects: false, objectsInObjects: false }], }, // always - arraysInObjects, objectsInObjects (reverse) { code: "var obj = { 'foo': { 'bar': 1, 'baz': 2 }, 'qux': [ 1, 2 ]};", options: ['always', { arraysInObjects: false, objectsInObjects: false }], }, // never { code: 'var obj = {foo: bar,\nbaz: qux\n};', options: ['never'] }, { code: 'var obj = {\nfoo: bar,\nbaz: qux};', options: ['never'] }, // never - object literals { code: 'var obj = {foo: bar, baz: qux};', options: ['never'] }, { code: 'var obj = {foo: {bar: quxx}, baz: qux};', options: ['never'] }, { code: 'var obj = {foo: {\nbar: quxx}, baz: qux\n};', options: ['never'] }, { code: 'var obj = {foo: {\nbar: quxx\n}, baz: qux};', options: ['never'] }, { code: 'var obj = {\nfoo: bar,\nbaz: qux\n};', options: ['never'] }, { code: 'var obj = {foo: bar, baz: qux /* */};', options: ['never'] }, { code: 'var obj = {/* */ foo: bar, baz: qux};', options: ['never'] }, { code: 'var obj = {//\n foo: bar};', options: ['never'] }, { code: 'var obj = { // line comment exception\n foo: bar};', options: ['never'], }, // never - destructuring { code: 'var {x} = y', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {x, y} = y', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {x,y} = y', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {\nx,y\n} = y', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {x = 10} = y', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {x = 10, y} = y', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {x: {z}, y} = y', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {\nx: {z\n}, y} = y', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {\ny,\n} = x', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {y,} = x', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {y:x} = x', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {/* */ y} = x', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {y /* */} = x', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {//\n y} = x', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var { // line comment exception\n y} = x', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, // never - import / export { code: "import door from 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import * as door from 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import {door} from 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export {door} from 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import {/* */ door} from 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export {/* */ door} from 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import {door /* */} from 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export {door /* */} from 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import {//\n door} from 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export {//\n door} from 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: 'var door = foo;\nexport {//\n door}', options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import { // line comment exception\n door} from 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export { // line comment exception\n door} from 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: 'var door = foo; export { // line comment exception\n door}', options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import {\ndoor} from 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export {\ndoor\n} from 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import {house,mouse} from 'caravan'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import {house, mouse} from 'caravan'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: 'var door = 0;export {door}', options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import 'room'", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import x, {bar} from 'foo';", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import x, {bar, baz} from 'foo';", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import {bar as y} from 'foo';", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import {x,} from 'foo';", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "import {\nx,\n} from 'foo';", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export {x,} from 'foo';", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export {\nx,\n} from 'foo';", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, // never - empty object { code: 'var foo = {};', options: ['never'] }, // never - objectsInObjects { code: "var obj = {'foo': {'bar': 1, 'baz': 2} };", options: ['never', { objectsInObjects: true }], }, /* * https://github.com/eslint/eslint/issues/3658 * Empty cases. */ { code: 'var {} = foo;', parserOptions: { ecmaVersion: 6 } }, { code: 'var [] = foo;', parserOptions: { ecmaVersion: 6 } }, { code: 'var {a: {}} = foo;', parserOptions: { ecmaVersion: 6 } }, { code: 'var {a: []} = foo;', parserOptions: { ecmaVersion: 6 } }, { code: "import {} from 'foo';", parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export {} from 'foo';", parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: 'export {};', parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: 'var {} = foo;', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var [] = foo;', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {a: {}} = foo;', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: 'var {a: []} = foo;', options: ['never'], parserOptions: { ecmaVersion: 6 }, }, { code: "import {} from 'foo';", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: "export {} from 'foo';", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, { code: 'export {};', options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, }, // https://github.com/eslint/eslint/issues/6940 { code: 'function foo ({a, b}: Props) {\n}', options: ['never'], }, // default - object literal types { code: 'const x:{}', }, { code: 'const x:{ }', }, { code: 'const x:{f: number}', }, { code: 'const x:{ // line-comment\nf: number\n}', }, { code: 'const x:{// line-comment\nf: number\n}', }, { code: 'const x:{/* inline-comment */f: number/* inline-comment */}', }, { code: 'const x:{\nf: number\n}', }, { code: 'const x:{f: {g: number}}', }, { code: 'const x:{f: [number]}', }, { code: 'const x:{[key: string]: value}', }, { code: 'const x:{[key: string]: [number]}', }, // default - mapped types { code: "const x:{[k in 'union']: number}", }, { code: "const x:{ // line-comment\n[k in 'union']: number\n}", }, { code: "const x:{// line-comment\n[k in 'union']: number\n}", }, { code: "const x:{/* inline-comment */[k in 'union']: number/* inline-comment */}", }, { code: "const x:{\n[k in 'union']: number\n}", }, { code: "const x:{[k in 'union']: {[k in 'union']: number}}", }, { code: "const x:{[k in 'union']: [number]}", }, { code: "const x:{[k in 'union']: value}", }, // never - mapped types { code: "const x:{[k in 'union']: {[k in 'union']: number} }", options: ['never', { objectsInObjects: true }], }, { code: "const x:{[k in 'union']: {[k in 'union']: number}}", options: ['never', { objectsInObjects: false }], }, { code: "const x:{[k in 'union']: () => {[k in 'union']: number} }", options: ['never', { objectsInObjects: true }], }, { code: "const x:{[k in 'union']: () => {[k in 'union']: number}}", options: ['never', { objectsInObjects: false }], }, { code: "const x:{[k in 'union']: [ number ]}", options: ['never', { arraysInObjects: false }], }, { code: "const x:{ [k in 'union']: value}", options: ['never', { arraysInObjects: true }], }, { code: "const x:{[k in 'union']: value}", options: ['never', { arraysInObjects: false }], }, { code: "const x:{ [k in 'union']: [number] }", options: ['never', { arraysInObjects: true }], }, { code: "const x:{[k in 'union']: [number]}", options: ['never', { arraysInObjects: false }], }, // never - object literal types { code: 'const x:{f: {g: number} }', options: ['never', { objectsInObjects: true }], }, { code: 'const x:{f: {g: number}}', options: ['never', { objectsInObjects: false }], }, { code: 'const x:{f: () => {g: number} }', options: ['never', { objectsInObjects: true }], }, { code: 'const x:{f: () => {g: number}}', options: ['never', { objectsInObjects: false }], }, { code: 'const x:{f: [number] }', options: ['never', { arraysInObjects: true }], }, { code: 'const x:{f: [ number ]}', options: ['never', { arraysInObjects: false }], }, { code: 'const x:{ [key: string]: value}', options: ['never', { arraysInObjects: true }], }, { code: 'const x:{[key: string]: value}', options: ['never', { arraysInObjects: false }], }, { code: 'const x:{ [key: string]: [number] }', options: ['never', { arraysInObjects: true }], }, { code: 'const x:{[key: string]: [number]}', options: ['never', { arraysInObjects: false }], }, // always - mapped types { code: "const x:{ [k in 'union']: number }", options: ['always'], }, { code: "const x:{ // line-comment\n[k in 'union']: number\n}", options: ['always'], }, { code: "const x:{ /* inline-comment */ [k in 'union']: number /* inline-comment */ }", options: ['always'], }, { code: "const x:{\n[k in 'union']: number\n}", options: ['always'], }, { code: "const x:{ [k in 'union']: [number] }", options: ['always'], }, // always - mapped types - objectsInObjects { code: "const x:{ [k in 'union']: { [k in 'union']: number } }", options: ['always', { objectsInObjects: true }], }, { code: "const x:{ [k in 'union']: { [k in 'union']: number }}", options: ['always', { objectsInObjects: false }], }, { code: "const x:{ [k in 'union']: () => { [k in 'union']: number } }", options: ['always', { objectsInObjects: true }], }, { code: "const x:{ [k in 'union']: () => { [k in 'union']: number }}", options: ['always', { objectsInObjects: false }], }, // always - mapped types - arraysInObjects { code: "type x = { [k in 'union']: number }", options: ['always'], }, { code: "const x:{ [k in 'union']: [number] }", options: ['always', { arraysInObjects: true }], }, { code: "const x:{ [k in 'union']: value }", options: ['always', { arraysInObjects: true }], }, { code: "const x:{[k in 'union']: value }", options: ['always', { arraysInObjects: false }], }, { code: "const x:{[k in 'union']: [number]}", options: ['always', { arraysInObjects: false }], }, // always - object literal types { code: 'const x:{}', options: ['always'], }, { code: 'const x:{ }', options: ['always'], }, { code: 'const x:{ f: number }', options: ['always'], }, { code: 'const x:{ // line-comment\nf: number\n}', options: ['always'], }, { code: 'const x:{ /* inline-comment */ f: number /* inline-comment */ }', options: ['always'], }, { code: 'const x:{\nf: number\n}', options: ['always'], }, { code: 'const x:{ f: [number] }', options: ['always'], }, // always - literal types - objectsInObjects { code: 'const x:{ f: { g: number } }', options: ['always', { objectsInObjects: true }], }, { code: 'const x:{ f: { g: number }}', options: ['always', { objectsInObjects: false }], }, { code: 'const x:{ f: () => { g: number } }', options: ['always', { objectsInObjects: true }], }, { code: 'const x:{ f: () => { g: number }}', options: ['always', { objectsInObjects: false }], }, // always - literal types - arraysInObjects { code: 'const x:{ f: [number] }', options: ['always', { arraysInObjects: true }], }, { code: 'const x:{ f: [ number ]}', options: ['always', { arraysInObjects: false }], }, { code: 'const x:{ [key: string]: value }', options: ['always', { arraysInObjects: true }], }, { code: 'const x:{[key: string]: value }', options: ['always', { arraysInObjects: false }], }, { code: 'const x:{ [key: string]: [number] }', options: ['always', { arraysInObjects: true }], }, { code: 'const x:{[key: string]: [number]}', options: ['always', { arraysInObjects: false }], }, ], invalid: [ { code: "import {bar} from 'foo.js';", output: "import { bar } from 'foo.js';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 8, endLine: 1, endColumn: 9, }, { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 12, endLine: 1, endColumn: 13, }, ], }, { code: "import { bar as y} from 'foo.js';", output: "import { bar as y } from 'foo.js';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 18, endLine: 1, endColumn: 19, }, ], }, { code: "import {bar as y} from 'foo.js';", output: "import { bar as y } from 'foo.js';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 8, endLine: 1, endColumn: 9, }, { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 17, endLine: 1, endColumn: 18, }, ], }, { code: "import { bar} from 'foo.js';", output: "import { bar } from 'foo.js';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 13, endLine: 1, endColumn: 14, }, ], }, { code: "import x, { bar} from 'foo';", output: "import x, { bar } from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 16, endLine: 1, endColumn: 17, }, ], }, { code: "import x, { bar/* */} from 'foo';", output: "import x, { bar/* */ } from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 21, endLine: 1, endColumn: 22, }, ], }, { code: "import x, {/* */bar } from 'foo';", output: "import x, { /* */bar } from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 11, endLine: 1, endColumn: 12, }, ], }, { code: "import x, {//\n bar } from 'foo';", output: "import x, { //\n bar } from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 11, endLine: 1, endColumn: 12, }, ], }, { code: "import x, { bar, baz} from 'foo';", output: "import x, { bar, baz } from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 21, endLine: 1, endColumn: 22, }, ], }, { code: "import x, {bar} from 'foo';", output: "import x, { bar } from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 11, endLine: 1, endColumn: 12, }, { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 15, endLine: 1, endColumn: 16, }, ], }, { code: "import x, {bar, baz} from 'foo';", output: "import x, { bar, baz } from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 11, endLine: 1, endColumn: 12, }, { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 20, endLine: 1, endColumn: 21, }, ], }, { code: "import {bar,} from 'foo';", output: "import { bar, } from 'foo';", options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 8, endLine: 1, endColumn: 9, }, { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 13, endLine: 1, endColumn: 14, }, ], }, { code: "import { bar, } from 'foo';", output: "import {bar,} from 'foo';", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 9, endLine: 1, endColumn: 10, }, { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 14, endLine: 1, endColumn: 15, }, ], }, { code: "import { /* */ bar, /* */ } from 'foo';", output: "import {/* */ bar, /* */} from 'foo';", options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 9, endLine: 1, endColumn: 10, }, { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ImportDeclaration, line: 1, column: 26, endLine: 1, endColumn: 27, }, ], }, { code: 'var bar = 0;\nexport {bar};', output: 'var bar = 0;\nexport { bar };', options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ExportNamedDeclaration, line: 2, column: 8, endLine: 2, endColumn: 9, }, { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ExportNamedDeclaration, line: 2, column: 12, }, ], }, { code: 'var bar = 0;\nexport {/* */ bar /* */};', output: 'var bar = 0;\nexport { /* */ bar /* */ };', options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ExportNamedDeclaration, line: 2, column: 8, endLine: 2, endColumn: 9, }, { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ExportNamedDeclaration, line: 2, column: 24, endLine: 2, endColumn: 25, }, ], }, { code: 'var bar = 0;\nexport {//\n bar };', output: 'var bar = 0;\nexport { //\n bar };', options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ExportNamedDeclaration, line: 2, column: 8, endLine: 2, endColumn: 9, }, ], }, { code: 'var bar = 0;\nexport { /* */ bar /* */ };', output: 'var bar = 0;\nexport {/* */ bar /* */};', options: ['never'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ExportNamedDeclaration, line: 2, column: 9, endLine: 2, endColumn: 10, }, { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ExportNamedDeclaration, line: 2, column: 25, endLine: 2, endColumn: 26, }, ], }, // always - arraysInObjects { code: "var obj = { 'foo': [ 1, 2 ] };", output: "var obj = { 'foo': [ 1, 2 ]};", options: ['always', { arraysInObjects: false }], errors: [ { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 28, endLine: 1, endColumn: 29, }, ], }, { code: "var obj = { 'foo': [ 1, 2 ] , 'bar': [ 'baz', 'qux' ] };", output: "var obj = { 'foo': [ 1, 2 ] , 'bar': [ 'baz', 'qux' ]};", options: ['always', { arraysInObjects: false }], errors: [ { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 54, endLine: 1, endColumn: 55, }, ], }, // always-objectsInObjects { code: "var obj = { 'foo': { 'bar': 1, 'baz': 2 } };", output: "var obj = { 'foo': { 'bar': 1, 'baz': 2 }};", options: ['always', { objectsInObjects: false }], errors: [ { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 42, endLine: 1, endColumn: 43, }, ], }, { code: "var obj = { 'foo': [ 1, 2 ] , 'bar': { 'baz': 1, 'qux': 2 } };", output: "var obj = { 'foo': [ 1, 2 ] , 'bar': { 'baz': 1, 'qux': 2 }};", options: ['always', { objectsInObjects: false }], errors: [ { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 60, endLine: 1, endColumn: 61, }, ], }, // always-destructuring trailing comma { code: 'var { a,} = x;', output: 'var { a, } = x;', options: ['always'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 9, endLine: 1, endColumn: 10, }, ], }, { code: 'var {a, } = x;', output: 'var {a,} = x;', options: ['never'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 8, endLine: 1, endColumn: 9, }, ], }, { code: 'var {a:b } = x;', output: 'var {a:b} = x;', options: ['never'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 9, endLine: 1, endColumn: 10, }, ], }, { code: 'var { a:b } = x;', output: 'var {a:b} = x;', options: ['never'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 6, endLine: 1, endColumn: 7, }, { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 10, endLine: 1, endColumn: 11, }, ], }, { code: 'var { a:b } = x;', output: 'var {a:b} = x;', options: ['never'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 6, endLine: 1, endColumn: 8, }, { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 11, endLine: 1, endColumn: 13, }, ], }, { code: 'var { a:b } = x;', output: 'var {a:b} = x;', options: ['never'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 6, endLine: 1, endColumn: 9, }, { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 12, endLine: 1, endColumn: 16, }, ], }, // never-objectsInObjects { code: "var obj = {'foo': {'bar': 1, 'baz': 2}};", output: "var obj = {'foo': {'bar': 1, 'baz': 2} };", options: ['never', { objectsInObjects: true }], errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 39, endLine: 1, endColumn: 40, }, ], }, { code: "var obj = {'foo': [1, 2] , 'bar': {'baz': 1, 'qux': 2}};", output: "var obj = {'foo': [1, 2] , 'bar': {'baz': 1, 'qux': 2} };", options: ['never', { objectsInObjects: true }], errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 55, endLine: 1, endColumn: 56, }, ], }, // always & never { code: 'var obj = {foo: bar, baz: qux};', output: 'var obj = { foo: bar, baz: qux };', options: ['always'], errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 11, endLine: 1, endColumn: 12, }, { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 30, endLine: 1, endColumn: 31, }, ], }, { code: 'var obj = {foo: bar, baz: qux };', output: 'var obj = { foo: bar, baz: qux };', options: ['always'], errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 11, endLine: 1, endColumn: 12, }, ], }, { code: 'var obj = {/* */foo: bar, baz: qux };', output: 'var obj = { /* */foo: bar, baz: qux };', options: ['always'], errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 11, endLine: 1, endColumn: 12, }, ], }, { code: 'var obj = {//\n foo: bar };', output: 'var obj = { //\n foo: bar };', options: ['always'], errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 11, endLine: 1, endColumn: 12, }, ], }, { code: 'var obj = { foo: bar, baz: qux};', output: 'var obj = { foo: bar, baz: qux };', options: ['always'], errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 31, endLine: 1, endColumn: 32, }, ], }, { code: 'var obj = { foo: bar, baz: qux/* */};', output: 'var obj = { foo: bar, baz: qux/* */ };', options: ['always'], errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 36, endLine: 1, endColumn: 37, }, ], }, { code: 'var obj = { foo: bar, baz: qux };', output: 'var obj = {foo: bar, baz: qux};', options: ['never'], errors: [ { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 12, endLine: 1, endColumn: 13, }, { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 31, endLine: 1, endColumn: 32, }, ], }, { code: 'var obj = { foo: bar, baz: qux };', output: 'var obj = {foo: bar, baz: qux};', options: ['never'], errors: [ { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 12, endLine: 1, endColumn: 14, }, { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 32, endLine: 1, endColumn: 33, }, ], }, { code: 'var obj = {foo: bar, baz: qux };', output: 'var obj = {foo: bar, baz: qux};', options: ['never'], errors: [ { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 30, endLine: 1, endColumn: 31, }, ], }, { code: 'var obj = {foo: bar, baz: qux };', output: 'var obj = {foo: bar, baz: qux};', options: ['never'], errors: [ { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 30, endLine: 1, endColumn: 32, }, ], }, { code: 'var obj = {foo: bar, baz: qux /* */ };', output: 'var obj = {foo: bar, baz: qux /* */};', options: ['never'], errors: [ { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 36, endLine: 1, endColumn: 37, }, ], }, { code: 'var obj = { foo: bar, baz: qux};', output: 'var obj = {foo: bar, baz: qux};', options: ['never'], errors: [ { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 12, endLine: 1, endColumn: 13, }, ], }, { code: 'var obj = { foo: bar, baz: qux};', output: 'var obj = {foo: bar, baz: qux};', options: ['never'], errors: [ { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 12, endLine: 1, endColumn: 14, }, ], }, { code: 'var obj = { /* */ foo: bar, baz: qux};', output: 'var obj = {/* */ foo: bar, baz: qux};', options: ['never'], errors: [ { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 12, endLine: 1, endColumn: 13, }, ], }, { code: 'var obj = { // line comment exception\n foo: bar };', output: 'var obj = { // line comment exception\n foo: bar};', options: ['never'], errors: [ { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 2, column: 10, endLine: 2, endColumn: 11, }, ], }, { code: 'var obj = { foo: { bar: quxx}, baz: qux};', output: 'var obj = {foo: {bar: quxx}, baz: qux};', options: ['never'], errors: [ { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 12, endLine: 1, endColumn: 13, }, { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 19, endLine: 1, endColumn: 20, }, ], }, { code: 'var obj = {foo: {bar: quxx }, baz: qux };', output: 'var obj = {foo: {bar: quxx}, baz: qux};', options: ['never'], errors: [ { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 27, endLine: 1, endColumn: 28, }, { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 39, endLine: 1, endColumn: 40, }, ], }, { code: 'export const thing = {value: 1 };', output: 'export const thing = { value: 1 };', options: ['always'], parserOptions: { ecmaVersion: 6, sourceType: 'module' }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 22, endLine: 1, endColumn: 23, }, ], }, // destructuring { code: 'var {x, y} = y', output: 'var { x, y } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 5, endLine: 1, endColumn: 6, }, { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 10, endLine: 1, endColumn: 11, }, ], }, { code: 'var { x, y} = y', output: 'var { x, y } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 11, endLine: 1, endColumn: 12, }, ], }, { code: 'var { x, y/* */} = y', output: 'var { x, y/* */ } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 16, endLine: 1, endColumn: 17, }, ], }, { code: 'var {/* */x, y } = y', output: 'var { /* */x, y } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 5, endLine: 1, endColumn: 6, }, ], }, { code: 'var {//\n x } = y', output: 'var { //\n x } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 5, endLine: 1, endColumn: 6, }, ], }, { code: 'var { x, y } = y', output: 'var {x, y} = y', options: ['never'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 6, endLine: 1, endColumn: 7, }, { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 11, endLine: 1, endColumn: 12, }, ], }, { code: 'var {x, y } = y', output: 'var {x, y} = y', options: ['never'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 10, endLine: 1, endColumn: 11, }, ], }, { code: 'var {x, y/* */ } = y', output: 'var {x, y/* */} = y', options: ['never'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 15, endLine: 1, endColumn: 16, }, ], }, { code: 'var { /* */x, y} = y', output: 'var {/* */x, y} = y', options: ['never'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'unexpectedSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 6, endLine: 1, endColumn: 7, }, ], }, { code: 'var { x=10} = y', output: 'var { x=10 } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 11, endLine: 1, endColumn: 12, }, ], }, { code: 'var {x=10 } = y', output: 'var { x=10 } = y', options: ['always'], parserOptions: { ecmaVersion: 6 }, errors: [ { messageId: 'requireSpaceAfter', data: { token: '{' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 5, endLine: 1, endColumn: 6, }, ], }, // never - arraysInObjects { code: "var obj = {'foo': [1, 2]};", output: "var obj = {'foo': [1, 2] };", options: ['never', { arraysInObjects: true }], errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 25, endLine: 1, endColumn: 26, }, ], }, { code: "var obj = {'foo': [1, 2] , 'bar': ['baz', 'qux']};", output: "var obj = {'foo': [1, 2] , 'bar': ['baz', 'qux'] };", options: ['never', { arraysInObjects: true }], errors: [ { messageId: 'requireSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectExpression, line: 1, column: 49, endLine: 1, endColumn: 50, }, ], }, // https://github.com/eslint/eslint/issues/6940 { code: 'function foo ({a, b }: Props) {\n}', output: 'function foo ({a, b}: Props) {\n}', options: ['never'], errors: [ { messageId: 'unexpectedSpaceBefore', data: { token: '}' }, type: AST_NODE_TYPES.ObjectPattern, line: 1, column: 20, endLine: 1, endColumn: 21, }, ], }, // object literal types // never - literal types { code: 'type x = { f: number }', output: 'type x = {f: number}', errors: [ { messageId: 'unexpectedSpaceAfter' }, { messageId: 'unexpectedSpaceBefore' }, ], }, { code: 'type x = { f: number}', output: 'type x = {f: number}', errors: [{ messageId: 'unexpectedSpaceAfter' }], }, { code: 'type x = {f: number }', output: 'type x = {f: number}', errors: [{ messageId: 'unexpectedSpaceBefore' }], }, // always - literal types { code: 'type x = {f: number}', output: 'type x = { f: number }', options: ['always'], errors: [ { messageId: 'requireSpaceAfter' }, { messageId: 'requireSpaceBefore' }, ], }, { code: 'type x = {f: number }', output: 'type x = { f: number }', options: ['always'], errors: [{ messageId: 'requireSpaceAfter' }], }, { code: 'type x = { f: number}', output: 'type x = { f: number }', options: ['always'], errors: [{ messageId: 'requireSpaceBefore' }], }, // never - mapped types { code: "type x = { [k in 'union']: number }", output: "type x = {[k in 'union']: number}", errors: [ { messageId: 'unexpectedSpaceAfter' }, { messageId: 'unexpectedSpaceBefore' }, ], }, { code: "type x = { [k in 'union']: number}", output: "type x = {[k in 'union']: number}", errors: [{ messageId: 'unexpectedSpaceAfter' }], }, { code: "type x = {[k in 'union']: number }", output: "type x = {[k in 'union']: number}", errors: [{ messageId: 'unexpectedSpaceBefore' }], }, // always - mapped types { code: "type x = {[k in 'union']: number}", output: "type x = { [k in 'union']: number }", options: ['always'], errors: [ { messageId: 'requireSpaceAfter' }, { messageId: 'requireSpaceBefore' }, ], }, { code: "type x = {[k in 'union']: number }", output: "type x = { [k in 'union']: number }", options: ['always'], errors: [{ messageId: 'requireSpaceAfter' }], }, { code: "type x = { [k in 'union']: number}", output: "type x = { [k in 'union']: number }", options: ['always'], errors: [{ messageId: 'requireSpaceBefore' }], }, // Mapped and literal types mix { code: "type x = { [k in 'union']: { [k: string]: number } }", output: "type x = {[k in 'union']: {[k: string]: number}}", errors: [ { messageId: 'unexpectedSpaceAfter' }, { messageId: 'unexpectedSpaceAfter' }, { messageId: 'unexpectedSpaceBefore' }, { messageId: 'unexpectedSpaceBefore' }, ], }, ], });
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_fact_Information { interface Tabs { } interface Body { /** The name of the custom entity. */ msdyn_name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } } class Formmsdyn_fact_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_fact_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyn_fact_Information */ Body: DevKit.Formmsdyn_fact_Information.Body; } class msdyn_factApi { /** * DynamicsCrm.DevKit msdyn_factApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; msdyn_AccountCustomer: DevKit.WebApi.LookupValue; msdyn_AccountVendor: DevKit.WebApi.LookupValue; msdyn_ActChargeableBilledSalesAmount: DevKit.WebApi.MoneyValue; /** Value of the Actual Chargeable Billed Sales Amount in base currency. */ msdyn_actchargeablebilledsalesamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_ActChargeableBilledSalesQuantity: DevKit.WebApi.DecimalValue; msdyn_ActChargeableCostAmount: DevKit.WebApi.MoneyValue; /** Value of the Actual Chargeable Cost Amount in base currency. */ msdyn_actchargeablecostamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_ActChargeableCostQuantity: DevKit.WebApi.DecimalValue; msdyn_ActChargeableUnbilledSalesAmount: DevKit.WebApi.MoneyValue; /** Value of the Actual Chargeable Unbilled Sales Amount in base currency. */ msdyn_actchargeableunbilledsalesamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_ActChargeableUnbilledSalesQuantity: DevKit.WebApi.DecimalValue; msdyn_ActNoChargeBilledSalesAmount: DevKit.WebApi.MoneyValue; /** Value of the Actual No Charge Billed Sales Amount in base currency. */ msdyn_actnochargebilledsalesamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_ActNoChargeBilledSalesQuantity: DevKit.WebApi.DecimalValue; msdyn_ActNoChargeCostAmount: DevKit.WebApi.MoneyValue; /** Value of the Actual No Charge Cost Amount in base currency. */ msdyn_actnochargecostamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_ActNoChargeCostQuantity: DevKit.WebApi.DecimalValue; msdyn_ActNoChargeUnbilledSalesAmount: DevKit.WebApi.MoneyValue; /** Value of the Actual No Charge Unbilled Sales Amount in base currency. */ msdyn_actnochargeunbilledsalesamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_ActNoChargeUnbilledSalesQuantity: DevKit.WebApi.DecimalValue; msdyn_ActNonChargeableCostAmount: DevKit.WebApi.MoneyValue; /** Value of the Actual Non Chargeable Cost Amount in base currency. */ msdyn_actnonchargeablecostamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_ActNonChargeableCostQuantity: DevKit.WebApi.DecimalValue; msdyn_ActNonChargeableUnbilledSalesAmount: DevKit.WebApi.MoneyValue; /** Value of the Actual Non Chargeable Unbilled Sales Amount in base currency. */ msdyn_actnonchargeableunbilledsalesamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_ActNonChargeableUnbilledSalesQuantity: DevKit.WebApi.DecimalValue; msdyn_bookableresource: DevKit.WebApi.LookupValue; msdyn_ContactCustomer: DevKit.WebApi.LookupValue; msdyn_ContactVendor: DevKit.WebApi.LookupValue; msdyn_CustomerType: DevKit.WebApi.OptionSetValue; /** Enter the transaction date of the business event. */ msdyn_DocumentDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; msdyn_earnedrevenue: DevKit.WebApi.MoneyValueReadonly; /** Value of the Earned Revenue in base currency. */ msdyn_earnedrevenue_Base: DevKit.WebApi.MoneyValueReadonly; /** Enter the end date for this transaction. */ msdyn_EndDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; msdyn_EstChargeableBilledSalesAmount: DevKit.WebApi.MoneyValue; /** Value of the Estimated Chargeable Billed Sales Amount in base currency. */ msdyn_estchargeablebilledsalesamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_EstChargeableBilledSalesQuantity: DevKit.WebApi.DecimalValue; msdyn_EstChargeableCostAmount: DevKit.WebApi.MoneyValue; /** Value of the Estimated Chargeable Cost Amount in base currency. */ msdyn_estchargeablecostamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_EstChargeableCostQuantity: DevKit.WebApi.DecimalValue; msdyn_EstChargeableUnbilledSalesAmount: DevKit.WebApi.MoneyValue; /** Value of the Estimated Chargeable Unbilled Sales Amount in base currency. */ msdyn_estchargeableunbilledsalesamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_EstChargeableUnbilledSalesQuantity: DevKit.WebApi.DecimalValue; msdyn_Estimate: DevKit.WebApi.LookupValue; msdyn_estimatelineid: DevKit.WebApi.LookupValue; msdyn_EstNoChargeBilledSalesAmount: DevKit.WebApi.MoneyValue; /** Value of the Estimated No Charge Billed Sales Amount in base currency. */ msdyn_estnochargebilledsalesamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_EstNoChargeBilledSalesQuantity: DevKit.WebApi.DecimalValue; msdyn_EstNoChargeCostAmount: DevKit.WebApi.MoneyValue; /** Value of the Estimated No Charge Cost Amount in base currency. */ msdyn_estnochargecostamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_EstNoChargeCostQuantity: DevKit.WebApi.DecimalValue; msdyn_EstNoChargeUnbilledSalesAmount: DevKit.WebApi.MoneyValue; /** Value of the Estimated No Charge Unbilled Sales Amount in base currency. */ msdyn_estnochargeunbilledsalesamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_EstNoChargeUnbilledSalesQuantity: DevKit.WebApi.DecimalValue; msdyn_EstNonChargeableCostAmount: DevKit.WebApi.MoneyValue; /** Value of the Estimated Non Chargeable Cost Amount in base currency. */ msdyn_estnonchargeablecostamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_EstNonChargeableCostQuantity: DevKit.WebApi.DecimalValue; msdyn_EstNonChargeableUnbilledSalesAmount: DevKit.WebApi.MoneyValue; /** Value of the Estimated Non Chargeable Unbilled Sales Amount in base currency. */ msdyn_estnonchargeableunbilledsalesamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_EstNonChargeableUnbilledSalesQuantity: DevKit.WebApi.DecimalValue; /** Unique identifier for entity instances */ msdyn_factId: DevKit.WebApi.GuidValue; msdyn_FactType: DevKit.WebApi.OptionSetValue; msdyn_grossmargin: DevKit.WebApi.MoneyValueReadonly; /** Value of the Gross Margin in base currency. */ msdyn_grossmargin_Base: DevKit.WebApi.MoneyValueReadonly; /** The name of the custom entity. */ msdyn_name: DevKit.WebApi.StringValue; msdyn_Product: DevKit.WebApi.LookupValue; msdyn_Project: DevKit.WebApi.LookupValue; msdyn_ResourceCategory: DevKit.WebApi.LookupValue; msdyn_SalesContract: DevKit.WebApi.LookupValue; /** (Deprecated) */ msdyn_SalesContractLine: DevKit.WebApi.StringValue; /** Unique identifier for Project Contract Line associated with Fact. */ msdyn_SalesContractLineId: DevKit.WebApi.LookupValue; /** Enter the start date. */ msdyn_StartDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; msdyn_Task: DevKit.WebApi.LookupValue; msdyn_totalcost: DevKit.WebApi.MoneyValueReadonly; /** Value of the Total Cost in base currency. */ msdyn_totalcost_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_totalhours: DevKit.WebApi.DecimalValueReadonly; msdyn_TransactionCategory: DevKit.WebApi.LookupValue; msdyn_TransactionClassification: DevKit.WebApi.OptionSetValue; msdyn_VendorType: DevKit.WebApi.OptionSetValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Status of the Fact */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Fact */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Shows the currency associated with the entity. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_fact { enum msdyn_CustomerType { /** 192350001 */ Account, /** 192350002 */ Contact } enum msdyn_FactType { /** 192350000 */ Actual, /** 192350001 */ Estimate } enum msdyn_TransactionClassification { /** 690970001 */ Additional, /** 690970000 */ Commission, /** 192350001 */ Expense, /** 192350004 */ Fee, /** 192350002 */ Material, /** 192350003 */ Milestone, /** 690970002 */ Tax, /** 192350000 */ Time } enum msdyn_VendorType { /** 192350001 */ Account, /** 192350002 */ Contact } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
* @packageDocumentation * @module particle2d */ import { Vec2, Color } from '../core/math'; import Pool from '../core/utils/pool'; import { clampf, degreesToRadians, radiansToDegrees } from '../core/utils/misc'; import { vfmtPosUvColor, getComponentPerVertex } from '../2d/renderer/vertex-format'; import { PositionType, EmitterMode, START_SIZE_EQUAL_TO_END_SIZE, START_RADIUS_EQUAL_TO_END_RADIUS } from './define'; import { ParticleSystem2D } from './particle-system-2d'; const ZERO_VEC2 = new Vec2(0, 0); const _pos = new Vec2(); const _tpa = new Vec2(); const _tpb = new Vec2(); const _tpc = new Vec2(); const formatBytes = getComponentPerVertex(vfmtPosUvColor); // In the Free mode to get emit real rotation in the world coordinate. function getWorldRotation (node) { let rotation = 0; let tempNode = node; while (tempNode) { rotation += tempNode.eulerAngles.z; tempNode = tempNode.parent; } return rotation; } class Particle { public pos = new Vec2(0, 0); public startPos = new Vec2(0, 0); public color = new Color(0, 0, 0, 255); public deltaColor = { r: 0, g: 0, b: 0, a: 255 }; public size = 0; public deltaSize = 0; public rotation = 0; public deltaRotation = 0; public timeToLive = 0; public drawPos = new Vec2(0, 0); public aspectRatio = 1; // Mode A public dir = new Vec2(0, 0); public radialAccel = 0; public tangentialAccel = 0; // Mode B public angle = 0; public degreesPerSecond = 0; public radius = 0; public deltaRadius = 0; } class ParticlePool extends Pool<Particle> { public get (): Particle { return this._get() || new Particle(); } } const pool = new ParticlePool((par: Particle) => { par.pos.set(ZERO_VEC2); par.startPos.set(ZERO_VEC2); par.color._val = 0xFF000000; par.deltaColor.r = par.deltaColor.g = par.deltaColor.b = 0; par.deltaColor.a = 255; par.size = 0; par.deltaSize = 0; par.rotation = 0; par.deltaRotation = 0; par.timeToLive = 0; par.drawPos.set(ZERO_VEC2); par.aspectRatio = 1; // Mode A par.dir.set(ZERO_VEC2); par.radialAccel = 0; par.tangentialAccel = 0; // Mode B par.angle = 0; par.degreesPerSecond = 0; par.radius = 0; par.deltaRadius = 0; }, 1024); export class Simulator { public particles: Particle[] = []; public active = false; public uvFilled = 0; public finished = false; public declare renderData; private readyToPlay = true; private elapsed = 0; private emitCounter = 0; private _worldRotation = 0; private declare sys: ParticleSystem2D; constructor (system) { this.sys = system; this.particles = []; this.active = false; this.readyToPlay = true; this.finished = false; this.elapsed = 0; this.emitCounter = 0; this.uvFilled = 0; this._worldRotation = 0; } public stop () { this.active = false; this.readyToPlay = false; this.elapsed = this.sys.duration; this.emitCounter = 0; } public reset () { this.active = true; this.readyToPlay = true; this.elapsed = 0; this.emitCounter = 0; this.finished = false; const particles = this.particles; for (let id = 0; id < particles.length; ++id) pool.put(particles[id]); particles.length = 0; } public emitParticle (pos) { const psys = this.sys; const particle = pool.get(); this.particles.push(particle); // Init particle // timeToLive // no negative life. prevent division by 0 particle.timeToLive = psys.life + psys.lifeVar * (Math.random() - 0.5) * 2; const timeToLive = particle.timeToLive = Math.max(0, particle.timeToLive); // position particle.pos.x = psys.sourcePos.x + psys.posVar.x * (Math.random() - 0.5) * 2; particle.pos.y = psys.sourcePos.y + psys.posVar.y * (Math.random() - 0.5) * 2; // Color let sr = 0; let sg = 0; let sb = 0; let sa = 0; const startColor = psys.startColor; const startColorVar = psys.startColorVar; const endColor = psys.endColor; const endColorVar = psys.endColorVar; particle.color.r = sr = clampf(startColor.r + startColorVar.r * (Math.random() - 0.5) * 2, 0, 255); particle.color.g = sg = clampf(startColor.g + startColorVar.g * (Math.random() - 0.5) * 2, 0, 255); particle.color.b = sb = clampf(startColor.b + startColorVar.b * (Math.random() - 0.5) * 2, 0, 255); particle.color.a = sa = clampf(startColor.a + startColorVar.a * (Math.random() - 0.5) * 2, 0, 255); particle.deltaColor.r = (clampf(endColor.r + endColorVar.r * (Math.random() - 0.5) * 2, 0, 255) - sr) / timeToLive; particle.deltaColor.g = (clampf(endColor.g + endColorVar.g * (Math.random() - 0.5) * 2, 0, 255) - sg) / timeToLive; particle.deltaColor.b = (clampf(endColor.b + endColorVar.b * (Math.random() - 0.5) * 2, 0, 255) - sb) / timeToLive; particle.deltaColor.a = (clampf(endColor.a + endColorVar.a * (Math.random() - 0.5) * 2, 0, 255) - sa) / timeToLive; // size let startS = psys.startSize + psys.startSizeVar * (Math.random() - 0.5) * 2; startS = Math.max(0, startS); // No negative value particle.size = startS; if (psys.endSize === START_SIZE_EQUAL_TO_END_SIZE) { particle.deltaSize = 0; } else { let endS = psys.endSize + psys.endSizeVar * (Math.random() - 0.5) * 2; endS = Math.max(0, endS); // No negative values particle.deltaSize = (endS - startS) / timeToLive; } // rotation const startA = psys.startSpin + psys.startSpinVar * (Math.random() - 0.5) * 2; const endA = psys.endSpin + psys.endSpinVar * (Math.random() - 0.5) * 2; particle.rotation = startA; particle.deltaRotation = (endA - startA) / timeToLive; // position particle.startPos.x = pos.x; particle.startPos.y = pos.y; // aspect ratio particle.aspectRatio = psys.aspectRatio || 1; // direction const a = degreesToRadians(psys.angle + this._worldRotation + psys.angleVar * (Math.random() - 0.5) * 2); // Mode Gravity: A if (psys.emitterMode === EmitterMode.GRAVITY) { const s = psys.speed + psys.speedVar * (Math.random() - 0.5) * 2; // direction particle.dir.x = Math.cos(a); particle.dir.y = Math.sin(a); particle.dir.multiplyScalar(s); // radial accel particle.radialAccel = psys.radialAccel + psys.radialAccelVar * (Math.random() - 0.5) * 2; // tangential accel particle.tangentialAccel = psys.tangentialAccel + psys.tangentialAccelVar * (Math.random() - 0.5) * 2; // rotation is dir if (psys.rotationIsDir) { particle.rotation = -radiansToDegrees(Math.atan2(particle.dir.y, particle.dir.x)); } } else { // Mode Radius: B // Set the default diameter of the particle from the source position const startRadius = psys.startRadius + psys.startRadiusVar * (Math.random() - 0.5) * 2; const endRadius = psys.endRadius + psys.endRadiusVar * (Math.random() - 0.5) * 2; particle.radius = startRadius; particle.deltaRadius = (psys.endRadius === START_RADIUS_EQUAL_TO_END_RADIUS) ? 0 : (endRadius - startRadius) / timeToLive; particle.angle = a; particle.degreesPerSecond = degreesToRadians(psys.rotatePerS + psys.rotatePerSVar * (Math.random() - 0.5) * 2); } } public updateUVs (force?: boolean) { const renderData = this.renderData; if (renderData && this.sys._renderSpriteFrame) { const vbuf = renderData.vData; const uv = this.sys._renderSpriteFrame.uv; const start = force ? 0 : this.uvFilled; const particleCount = this.particles.length; for (let i = start; i < particleCount; i++) { const offset = i * formatBytes * 4; vbuf[offset + 3] = uv[0]; vbuf[offset + 4] = uv[1]; vbuf[offset + 12] = uv[2]; vbuf[offset + 13] = uv[3]; vbuf[offset + 21] = uv[4]; vbuf[offset + 22] = uv[5]; vbuf[offset + 30] = uv[6]; vbuf[offset + 31] = uv[7]; } this.uvFilled = particleCount; } } public updateParticleBuffer (particle, pos, buffer, offset: number) { const vbuf = buffer.vData; // const uintbuf = buffer._uintVData; const x: number = pos.x; const y: number = pos.y; let width = particle.size; let height = width; const aspectRatio = particle.aspectRatio; if (aspectRatio > 1) { height = width / aspectRatio; } else { width = height * aspectRatio; } const halfWidth = width / 2; const halfHeight = height / 2; // pos if (particle.rotation) { const x1 = -halfWidth; const y1 = -halfHeight; const x2 = halfWidth; const y2 = halfHeight; const rad = -degreesToRadians(particle.rotation); const cr = Math.cos(rad); const sr = Math.sin(rad); // bl vbuf[offset] = x1 * cr - y1 * sr + x; vbuf[offset + 1] = x1 * sr + y1 * cr + y; vbuf[offset + 2] = 0; // br vbuf[offset + 9] = x2 * cr - y1 * sr + x; vbuf[offset + 10] = x2 * sr + y1 * cr + y; vbuf[offset + 11] = 0; // tl vbuf[offset + 18] = x1 * cr - y2 * sr + x; vbuf[offset + 19] = x1 * sr + y2 * cr + y; vbuf[offset + 20] = 0; // tr vbuf[offset + 27] = x2 * cr - y2 * sr + x; vbuf[offset + 28] = x2 * sr + y2 * cr + y; vbuf[offset + 29] = 0; } else { // bl vbuf[offset] = x - halfWidth; vbuf[offset + 1] = y - halfHeight; vbuf[offset + 2] = 0; // br vbuf[offset + 9] = x + halfWidth; vbuf[offset + 10] = y - halfHeight; vbuf[offset + 11] = 0; // tl vbuf[offset + 18] = x - halfWidth; vbuf[offset + 19] = y + halfHeight; vbuf[offset + 20] = 0; // tr vbuf[offset + 27] = x + halfWidth; vbuf[offset + 28] = y + halfHeight; vbuf[offset + 29] = 0; } // color Color.toArray(vbuf, particle.color, offset + 5); Color.toArray(vbuf, particle.color, offset + 14); Color.toArray(vbuf, particle.color, offset + 23); Color.toArray(vbuf, particle.color, offset + 32); } public step (dt) { const assembler = this.sys.assembler!; const psys = this.sys; const node = psys.node; const particles = this.particles; dt = dt > assembler.maxParticleDeltaTime ? assembler.maxParticleDeltaTime : dt; // Calculate pos node.updateWorldTransform(); if (psys.positionType === PositionType.FREE) { this._worldRotation = getWorldRotation(node); const m = node.worldMatrix; _pos.x = m.m12; _pos.y = m.m13; } else if (psys.positionType === PositionType.RELATIVE) { this._worldRotation = node.eulerAngles.z; _pos.x = node.position.x; _pos.y = node.position.y; } else { this._worldRotation = 0; } // Emission if (this.active && psys.emissionRate) { const rate = 1.0 / psys.emissionRate; // issue #1201, prevent bursts of particles, due to too high emitCounter if (particles.length < psys.totalParticles) this.emitCounter += dt; while ((particles.length < psys.totalParticles) && (this.emitCounter > rate)) { this.emitParticle(_pos); this.emitCounter -= rate; } this.elapsed += dt; if (psys.duration !== -1 && psys.duration < this.elapsed) { psys.stopSystem(); } } // Request buffer for particles const renderData = this.renderData; const particleCount = particles.length; renderData.reset(); this.requestData(particleCount * 4, particleCount * 6); // Fill up uvs if (particleCount > this.uvFilled) { this.updateUVs(); } // Used to reduce memory allocation / creation within the loop let particleIdx = 0; while (particleIdx < particles.length) { // Reset temporary vectors _tpa.x = _tpa.y = _tpb.x = _tpb.y = _tpc.x = _tpc.y = 0; const particle = particles[particleIdx]; // life particle.timeToLive -= dt; if (particle.timeToLive > 0) { // Mode A: gravity, direction, tangential accel & radial accel if (psys.emitterMode === EmitterMode.GRAVITY) { const tmp = _tpc; const radial = _tpa; const tangential = _tpb; // radial acceleration if (particle.pos.x || particle.pos.y) { radial.set(particle.pos); radial.normalize(); } tangential.set(radial); radial.multiplyScalar(particle.radialAccel); // tangential acceleration const newy = tangential.x; tangential.x = -tangential.y; tangential.y = newy; tangential.multiplyScalar(particle.tangentialAccel); tmp.set(radial); tmp.add(tangential); tmp.add(psys.gravity); tmp.multiplyScalar(dt); particle.dir.add(tmp); tmp.set(particle.dir); tmp.multiplyScalar(dt); particle.pos.add(tmp); } else { // Mode B: radius movement // Update the angle and radius of the particle. particle.angle += particle.degreesPerSecond * dt; particle.radius += particle.deltaRadius * dt; particle.pos.x = -Math.cos(particle.angle) * particle.radius; particle.pos.y = -Math.sin(particle.angle) * particle.radius; } // color particle.color.r += particle.deltaColor.r * dt; particle.color.g += particle.deltaColor.g * dt; particle.color.b += particle.deltaColor.b * dt; particle.color.a += particle.deltaColor.a * dt; // size particle.size += particle.deltaSize * dt; if (particle.size < 0) { particle.size = 0; } // angle particle.rotation += particle.deltaRotation * dt; // update values in quad buffer const newPos = _tpa; newPos.set(particle.pos); if (psys.positionType !== PositionType.GROUPED) { newPos.add(particle.startPos); } const offset = formatBytes * particleIdx * 4; this.updateParticleBuffer(particle, newPos, renderData, offset); // update particle counter ++particleIdx; } else { // life < 0 const deadParticle = particles[particleIdx]; if (particleIdx !== particles.length - 1) { particles[particleIdx] = particles[particles.length - 1]; } pool.put(deadParticle); particles.length--; renderData.indicesCount -= 6; renderData.vertexCount -= 4; } } if (particles.length === 0 && !this.active && !this.readyToPlay) { this.finished = true; psys._finishedSimulation(); } } requestData (vertexCount: number, indicesCount: number) { let offset = this.renderData.indicesCount; this.renderData.request(vertexCount, indicesCount); const count = this.renderData.indicesCount / 6; const buffer = this.renderData.iData; for (let i = offset; i < count; i++) { const vId = i * 4; buffer[offset++] = vId; buffer[offset++] = vId + 1; buffer[offset++] = vId + 2; buffer[offset++] = vId + 1; buffer[offset++] = vId + 3; buffer[offset++] = vId + 2; } } }
the_stack
import * as fs from "fs"; import * as path from "path"; import { expect } from "chai"; import { Schema, SchemaContext } from "../../ecschema-metadata"; import { deserializeXmlSync } from "../TestUtils/DeserializationHelpers"; import { SchemaUnitProvider } from "../../UnitProvider/SchemaUnitProvider"; import { UNIT_EXTRA_DATA } from "./UnitData"; import { UnitProps } from "@itwin/core-quantity"; import { ISchemaLocater } from "../../Context"; import { SchemaMatchType } from "../../ECObjects"; import { SchemaKey } from "../../SchemaKey"; class TestSchemaLocater implements ISchemaLocater { public async getSchema<T extends Schema>(schemaKey: SchemaKey, matchType: SchemaMatchType, context?: SchemaContext): Promise<T | undefined> { return this.getSchemaSync(schemaKey, matchType, context) as T; } public getSchemaSync<T extends Schema>(schemaKey: SchemaKey, _matchType: SchemaMatchType, context?: SchemaContext): T | undefined { if (schemaKey.name !== "Units") return undefined; const schemaFile = path.join(__dirname, "..", "..", "..", "..", "node_modules", "@bentley", "units-schema", "Units.ecschema.xml"); const schemaXml = fs.readFileSync(schemaFile, "utf-8"); const schema = deserializeXmlSync(schemaXml, context || new SchemaContext()); if (schema !== undefined) return schema as T; return undefined; } } describe("Unit Provider tests", () => { let context: SchemaContext; let provider: SchemaUnitProvider; describe("Initialized with SchemaContext", () => { before(() => { context = new SchemaContext(); const schemaFile = path.join(__dirname, "..", "..", "..", "..", "node_modules", "@bentley", "units-schema", "Units.ecschema.xml"); const schemaXml = fs.readFileSync(schemaFile, "utf-8"); deserializeXmlSync(schemaXml, context); const siSchemaFile = path.join(__dirname, "..", "assets", "SIUnits.ecschema.xml"); const siSchemaXml = fs.readFileSync(siSchemaFile, "utf-8"); deserializeXmlSync(siSchemaXml, context); const metricSchemaFile = path.join(__dirname, "..", "assets", "MetricUnits.ecschema.xml"); const metricSchemaXml = fs.readFileSync(metricSchemaFile, "utf-8"); deserializeXmlSync(metricSchemaXml, context); const usSchemaFile = path.join(__dirname, "..", "assets", "USUnits.ecschema.xml"); const usSchemaXml = fs.readFileSync(usSchemaFile, "utf-8"); deserializeXmlSync(usSchemaXml, context); provider = new SchemaUnitProvider(context, UNIT_EXTRA_DATA); }); // Tests for findUnitByName it("should find units by unit names in Units schema", async () => { const unit1 = await provider.findUnitByName("Units.KM"); expect(unit1.name === "Units.KM", `Unit name should be Units.KM and not ${unit1.name}`).to.be.true; const unit2 = await provider.findUnitByName("Units.KM_PER_HR"); expect(unit2.name === "Units.KM_PER_HR", `Unit name should be Units.KM_PER_HR and not ${unit2.name}`).to.be.true; }); it("should find units by unit names in MetricUnits schema", async () => { const unit1 = await provider.findUnitByName("MetricUnits.KM"); expect(unit1.name === "MetricUnits.KM", `Unit name should be MetricUnits.KM and not ${unit1.name}`).to.be.true; const unit2 = await provider.findUnitByName("MetricUnits.M_PER_KM"); expect(unit2.name === "MetricUnits.M_PER_KM", `Unit name should be MetricUnits.M_PER_KM and not ${unit2.name}`).to.be.true; }); it("should throw when schema is not found", async () => { try { await provider.findUnitByName("MockSchema.KM"); } catch (err: any) { expect(err).to.be.an("error"); expect(err.message).to.equal("Cannot find schema for unit"); } }); it("should throw when phenomenon is not found", async () => { try { await provider.findUnitByName("Units.MOCKUNIT"); } catch (err: any) { expect(err).to.be.an("error"); expect(err.message).to.equal("Cannot find schema item/unit"); } }); // Tests for findUnitsByPhenomenon it("should find units that belong to Units.LENGTH phenomenon", async () => { const filteredUnits: UnitProps[] = await provider.getUnitsByFamily("Units.LENGTH"); for (const unit of filteredUnits) { expect(unit.phenomenon === "Units.LENGTH", `Phenomenon name should be Units.LENGTH and not ${unit.phenomenon}`).to.be.true; } }); it("should find units that belong to Units.VELOCITY phenomenon", async () => { const filteredUnits: UnitProps[] = await provider.getUnitsByFamily("Units.VELOCITY"); for (const unit of filteredUnits) { expect(unit.phenomenon === "Units.VELOCITY", `Phenomenon name should be Units.LENGTH and not ${unit.phenomenon}`).to.be.true; } }); it("should find units that belong to SIUnits.LENGTH phenomenon across multiple schemas", async () => { const filteredUnits: UnitProps[] = await provider.getUnitsByFamily("SIUnits.LENGTH"); for (const unit of filteredUnits) { expect(unit.phenomenon === "SIUnits.LENGTH", `Phenomenon name should be SIUnits.LENGTH and not ${unit.phenomenon}`).to.be.true; } expect(filteredUnits).to.have.lengthOf(19); }); it("should find units that belong to SIUnits.SLOPE phenomenon across multiple schemas", async () => { const filteredUnits: UnitProps[] = await provider.getUnitsByFamily("SIUnits.SLOPE"); for (const unit of filteredUnits) { expect(unit.phenomenon === "SIUnits.SLOPE", `Phenomenon name should be SIUnits.SLOPE and not ${unit.phenomenon}`).to.be.true; } expect(filteredUnits).to.have.lengthOf(9); }); it("should throw when schema is not found", async () => { try { await provider.getUnitsByFamily("MockSchema.VELOCITY"); } catch (err: any) { expect(err).to.be.an("error"); expect(err.message).to.equal("Cannot find schema for phenomenon"); } }); it("should throw when phenomenon is not found", async () => { try { await provider.getUnitsByFamily("SIUnits.VELOCITY"); } catch (err: any) { expect(err).to.be.an("error"); expect(err.message).to.equal("Cannot find schema item/phenomenon"); } }); // Tests for getAlternateDisplayLabels it("should find alternate display labels of Units.US_SURVEY_FT", () => { const altDisplayLabels = provider.getAlternateDisplayLabels("Units.US_SURVEY_FT"); const expectedLabels = ["ft", "SF", "USF", "ft (US Survey)"]; expect(altDisplayLabels, `Alternate display labels should be ${expectedLabels}`).to.include.members(expectedLabels); expect(altDisplayLabels).to.have.lengthOf(4); }); it("should find alternate display labels of Units.CUB_US_SURVEY_FT", () => { const altDisplayLabels = provider.getAlternateDisplayLabels("Units.CUB_US_SURVEY_FT"); const expectedLabels = ["cf"]; expect(altDisplayLabels, `Alternate display labels should be ${expectedLabels}`).to.include.members(expectedLabels); expect(altDisplayLabels).to.have.lengthOf(1); }); it("should not find any alternate display labels of Unit", () => { const altDisplayLabels = provider.getAlternateDisplayLabels("Units.CELSIUS"); const expectedLabels: string[] = []; expect(altDisplayLabels, `Alternate display labels should be ${expectedLabels}`).to.include.members(expectedLabels); expect(altDisplayLabels).to.have.lengthOf(0); }); // Tests for findUnitsByDisplayLabel of findUnit it("should find Units.DELTA_RANKINE with display label 'Δ°R'", async () => { const unit = await provider.findUnit("Δ°R"); expect(unit.name === "Units.DELTA_RANKINE", `Unit name should be Units.DELTA_RANKINE and not ${unit.name}`).to.be.true; }); it("should find Units.MICROMOL_PER_CUB_DM with display label 'µmol/dm³'", async () => { const unit = await provider.findUnit("µmol/dm³"); expect(unit.name === "Units.MICROMOL_PER_CUB_DM", `Unit name should be Units.MICROMOL_PER_CUB_DM and not ${unit.name}`).to.be.true; }); it("should find Units.FT with display label 'ft'", async () => { const unit = await provider.findUnit("ft"); expect(unit.name === "Units.FT", `Unit name should be Units.FT and not ${unit.name}`).to.be.true; }); it("should find USUnits.FT with display label 'ft' with schemaName 'USUnits'",async () => { const unit = await provider.findUnit("ft", "USUnits"); expect(unit.name === "USUnits.FT", `Unit name should be USUnits.FT and not ${unit.name}`).to.be.true; }); it("should find USUnits.FT with display label 'ft' and SIUnits.LENGTH phenomena", async () => { const unit = await provider.findUnit("ft", undefined, "SIUnits.LENGTH"); expect(unit.name === "USUnits.FT", `Unit name should be USUnits.FT and not ${unit.name}`).to.be.true; }); it("should find Units.FT with display label 'ft' and Units.LENGTH phenomena", async () => { const unit = await provider.findUnit("ft", undefined, "Units.LENGTH"); expect(unit.name === "Units.FT", `Unit name should be Units.FT and not ${unit.name}`).to.be.true; }); it("should only find USUnits.FT for USUnits.USCUSTOM unitSystem", async () => { const unit = await provider.findUnit("ft", undefined, undefined, "USUnits.USCUSTOM"); expect(unit.name === "USUnits.FT", `Unit name should be USUnits.FT and not ${unit.name}`).to.be.true; }); it("should only find Units.FT with display label 'ft' for Units.USCUSTOM unitSystem", async () => { const unit = await provider.findUnit("ft", undefined, undefined, "Units.USCUSTOM"); expect(unit.name === "Units.FT", `Unit name should be Units.FT and not ${unit.name}`).to.be.true; }); // Tests for findUnitsByAltDisplayLabel of findUnit it("should find Units.YRD by corresponding alternate display labels", async () => { const unit1 = await provider.findUnit("YRD"); expect(unit1.name === "Units.YRD", `Unit name should be Units.YRD and not ${unit1.name}`).to.be.true; const unit2 = await provider.findUnit("yrd"); expect(unit2.name === "Units.YRD", `Unit name should be Units.YRD and not ${unit2.name}`).to.be.true; }); it("should find Units.ARC_SECOND with alternate display label 'sec'", async () => { const unit = await provider.findUnit("sec"); expect(unit.name === "Units.ARC_SECOND", `Unit name should be Units.ARC_SECOND and not ${unit.name}`).to.be.true; }); it("should find Units.S with alternate display label 'sec' and phenomenon Units.TIME", async () => { const unit = await provider.findUnit("sec", undefined, "Units.TIME"); expect(unit.name === "Units.S", `Unit name should be Units.S and not ${unit.name}`).to.be.true; }); it("should find Units.S with alternate display label 'sec' and unitSystem Units.SI", async () => { const unit = await provider.findUnit("sec", undefined, undefined, "Units.SI"); expect(unit.name === "Units.S", `Unit name should be Units.S and not ${unit.name}`).to.be.true; }); it("should find Units.ARC_MINUTE with display label ''' ", async () => { const unit = await provider.findUnit("'"); expect(unit.name === "Units.ARC_MINUTE", `Unit name should be Units.ARC_MINUTE and not ${unit.name}`).to.be.true; }); it("should find Units.FT with alternate display label ''' and phenomenon Units.LENGTH", async () => { const unit = await provider.findUnit("'", undefined, "Units.LENGTH"); expect(unit.name === "Units.FT", `Unit name should be Units.FT and not ${unit.name}`).to.be.true; }); it("should find Units.FT with alternate display label ''' and unitSystem Units.USCUSTOM", async () => { const unit = await provider.findUnit("'", undefined, undefined, "Units.USCUSTOM"); expect(unit.name === "Units.FT", `Unit name should be Units.FT and not ${unit.name}`).to.be.true; }); // Tests for invalid cases it("should not find any units when unitLabel does not match any display labels or alternate display labels", async () => { try { await provider.findUnit("MockUnitLabel"); } catch (err: any) { expect(err).to.be.an("error"); expect(err.message).to.equal("Cannot find unit with label"); } }); it("should not find any units when schemaName does not exist within context", async () => { try { await provider.findUnit("ft", "MockSchema"); } catch (err: any) { expect(err).to.be.an("error"); expect(err.message).to.equal("Cannot find unit with label"); } try { await provider.findUnit("sec", "MockSchema"); } catch (err: any) { expect(err).to.be.an("error"); expect(err.message).to.equal("Cannot find unit with label"); } }); it("should not find any units when phenomenon does not match any unit", async () => { try { await provider.findUnit("ft", undefined, "MockPhenomenon"); } catch (err: any) { expect(err).to.be.an("error"); expect(err.message).to.equal("Cannot find unit with label"); } try { await provider.findUnit("sec", undefined, "MockPhenomenon"); } catch (err: any) { expect(err).to.be.an("error"); expect(err.message).to.equal("Cannot find unit with label"); } }); it("should not find any units when unitSystem does not match any unit", async () => { try { await provider.findUnit("ft", undefined, undefined, "MockUnitSystem"); } catch (err: any) { expect(err).to.be.an("error"); expect(err.message).to.equal("Cannot find unit with label"); } try { await provider.findUnit("sec", undefined, undefined, "MockUnitSystem"); } catch (err: any) { expect(err).to.be.an("error"); expect(err.message).to.equal("Cannot find unit with label"); } }); }); describe("Initialized with ISchemaLocater", () => { before(() => { const locater = new TestSchemaLocater(); provider = new SchemaUnitProvider(locater, UNIT_EXTRA_DATA); }); it("should find units by unit names in Units schema", async () => { const unit1 = await provider.findUnitByName("Units.KM"); expect(unit1.name === "Units.KM", `Unit name should be Units.KM and not ${unit1.name}`).to.be.true; const unit2 = await provider.findUnitByName("Units.KM_PER_HR"); expect(unit2.name === "Units.KM_PER_HR", `Unit name should be Units.KM_PER_HR and not ${unit2.name}`).to.be.true; }); }); });
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/devicesMappers"; import * as Parameters from "../models/parameters"; import { StorSimpleManagementClientContext } from "../storSimpleManagementClientContext"; /** Class representing a Devices. */ export class Devices { private readonly client: StorSimpleManagementClientContext; /** * Create a Devices. * @param {StorSimpleManagementClientContext} client Reference to the service client. */ constructor(client: StorSimpleManagementClientContext) { this.client = client; } /** * Retrieves all the devices in a manager. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.DevicesListByManagerResponse> */ listByManager(resourceGroupName: string, managerName: string, options?: Models.DevicesListByManagerOptionalParams): Promise<Models.DevicesListByManagerResponse>; /** * @param resourceGroupName The resource group name * @param managerName The manager name * @param callback The callback */ listByManager(resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.DeviceList>): void; /** * @param resourceGroupName The resource group name * @param managerName The manager name * @param options The optional parameters * @param callback The callback */ listByManager(resourceGroupName: string, managerName: string, options: Models.DevicesListByManagerOptionalParams, callback: msRest.ServiceCallback<Models.DeviceList>): void; listByManager(resourceGroupName: string, managerName: string, options?: Models.DevicesListByManagerOptionalParams | msRest.ServiceCallback<Models.DeviceList>, callback?: msRest.ServiceCallback<Models.DeviceList>): Promise<Models.DevicesListByManagerResponse> { return this.client.sendOperationRequest( { resourceGroupName, managerName, options }, listByManagerOperationSpec, callback) as Promise<Models.DevicesListByManagerResponse>; } /** * Returns the properties of the specified device name. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.DevicesGetResponse> */ get(deviceName: string, resourceGroupName: string, managerName: string, options?: Models.DevicesGetOptionalParams): Promise<Models.DevicesGetResponse>; /** * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param callback The callback */ get(deviceName: string, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.Device>): void; /** * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param options The optional parameters * @param callback The callback */ get(deviceName: string, resourceGroupName: string, managerName: string, options: Models.DevicesGetOptionalParams, callback: msRest.ServiceCallback<Models.Device>): void; get(deviceName: string, resourceGroupName: string, managerName: string, options?: Models.DevicesGetOptionalParams | msRest.ServiceCallback<Models.Device>, callback?: msRest.ServiceCallback<Models.Device>): Promise<Models.DevicesGetResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, managerName, options }, getOperationSpec, callback) as Promise<Models.DevicesGetResponse>; } /** * Deletes the device. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(deviceName,resourceGroupName,managerName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Patches the device. * @param deviceName The device Name. * @param devicePatch Patch representation of the device. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.DevicesPatchResponse> */ patch(deviceName: string, devicePatch: Models.DevicePatch, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.DevicesPatchResponse> { return this.beginPatch(deviceName,devicePatch,resourceGroupName,managerName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.DevicesPatchResponse>; } /** * Returns the alert settings of the specified device name. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.DevicesGetAlertSettingsResponse> */ getAlertSettings(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.DevicesGetAlertSettingsResponse>; /** * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param callback The callback */ getAlertSettings(deviceName: string, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.AlertSettings>): void; /** * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param options The optional parameters * @param callback The callback */ getAlertSettings(deviceName: string, resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AlertSettings>): void; getAlertSettings(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AlertSettings>, callback?: msRest.ServiceCallback<Models.AlertSettings>): Promise<Models.DevicesGetAlertSettingsResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, managerName, options }, getAlertSettingsOperationSpec, callback) as Promise<Models.DevicesGetAlertSettingsResponse>; } /** * Creates or updates the alert settings * @param deviceName The device name. * @param alertSettings The alert settings. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.DevicesCreateOrUpdateAlertSettingsResponse> */ createOrUpdateAlertSettings(deviceName: string, alertSettings: Models.AlertSettings, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.DevicesCreateOrUpdateAlertSettingsResponse> { return this.beginCreateOrUpdateAlertSettings(deviceName,alertSettings,resourceGroupName,managerName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.DevicesCreateOrUpdateAlertSettingsResponse>; } /** * Deactivates the device. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deactivate(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeactivate(deviceName,resourceGroupName,managerName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Downloads udpates on the device. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ downloadUpdates(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDownloadUpdates(deviceName,resourceGroupName,managerName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Fails over the device to another device. * @param deviceName The device name. * @param failoverRequest The failover request. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ failover(deviceName: string, failoverRequest: Models.FailoverRequest, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginFailover(deviceName,failoverRequest,resourceGroupName,managerName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Retrieves all the devices which can be used as failover targets for the given device. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.DevicesListFailoverTargetResponse> */ listFailoverTarget(deviceName: string, resourceGroupName: string, managerName: string, options?: Models.DevicesListFailoverTargetOptionalParams): Promise<Models.DevicesListFailoverTargetResponse>; /** * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param callback The callback */ listFailoverTarget(deviceName: string, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.DeviceList>): void; /** * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param options The optional parameters * @param callback The callback */ listFailoverTarget(deviceName: string, resourceGroupName: string, managerName: string, options: Models.DevicesListFailoverTargetOptionalParams, callback: msRest.ServiceCallback<Models.DeviceList>): void; listFailoverTarget(deviceName: string, resourceGroupName: string, managerName: string, options?: Models.DevicesListFailoverTargetOptionalParams | msRest.ServiceCallback<Models.DeviceList>, callback?: msRest.ServiceCallback<Models.DeviceList>): Promise<Models.DevicesListFailoverTargetResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, managerName, options }, listFailoverTargetOperationSpec, callback) as Promise<Models.DevicesListFailoverTargetResponse>; } /** * Installs the updates on the device. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ installUpdates(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginInstallUpdates(deviceName,resourceGroupName,managerName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Retrieves the device metrics. * @param deviceName The name of the appliance. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.DevicesListMetricsResponse> */ listMetrics(deviceName: string, resourceGroupName: string, managerName: string, options?: Models.DevicesListMetricsOptionalParams): Promise<Models.DevicesListMetricsResponse>; /** * @param deviceName The name of the appliance. * @param resourceGroupName The resource group name * @param managerName The manager name * @param callback The callback */ listMetrics(deviceName: string, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.MetricList>): void; /** * @param deviceName The name of the appliance. * @param resourceGroupName The resource group name * @param managerName The manager name * @param options The optional parameters * @param callback The callback */ listMetrics(deviceName: string, resourceGroupName: string, managerName: string, options: Models.DevicesListMetricsOptionalParams, callback: msRest.ServiceCallback<Models.MetricList>): void; listMetrics(deviceName: string, resourceGroupName: string, managerName: string, options?: Models.DevicesListMetricsOptionalParams | msRest.ServiceCallback<Models.MetricList>, callback?: msRest.ServiceCallback<Models.MetricList>): Promise<Models.DevicesListMetricsResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, managerName, options }, listMetricsOperationSpec, callback) as Promise<Models.DevicesListMetricsResponse>; } /** * Retrieves metric definition of all metrics aggregated at device. * @param deviceName The name of the appliance. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.DevicesListMetricDefinitionResponse> */ listMetricDefinition(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.DevicesListMetricDefinitionResponse>; /** * @param deviceName The name of the appliance. * @param resourceGroupName The resource group name * @param managerName The manager name * @param callback The callback */ listMetricDefinition(deviceName: string, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.MetricDefinitionList>): void; /** * @param deviceName The name of the appliance. * @param resourceGroupName The resource group name * @param managerName The manager name * @param options The optional parameters * @param callback The callback */ listMetricDefinition(deviceName: string, resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.MetricDefinitionList>): void; listMetricDefinition(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.MetricDefinitionList>, callback?: msRest.ServiceCallback<Models.MetricDefinitionList>): Promise<Models.DevicesListMetricDefinitionResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, managerName, options }, listMetricDefinitionOperationSpec, callback) as Promise<Models.DevicesListMetricDefinitionResponse>; } /** * Returns the network settings of the specified device name. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.DevicesGetNetworkSettingsResponse> */ getNetworkSettings(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.DevicesGetNetworkSettingsResponse>; /** * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param callback The callback */ getNetworkSettings(deviceName: string, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.NetworkSettings>): void; /** * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param options The optional parameters * @param callback The callback */ getNetworkSettings(deviceName: string, resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.NetworkSettings>): void; getNetworkSettings(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.NetworkSettings>, callback?: msRest.ServiceCallback<Models.NetworkSettings>): Promise<Models.DevicesGetNetworkSettingsResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, managerName, options }, getNetworkSettingsOperationSpec, callback) as Promise<Models.DevicesGetNetworkSettingsResponse>; } /** * Scans for updates on the device. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ scanForUpdates(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginScanForUpdates(deviceName,resourceGroupName,managerName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Creates or updates the security settings. * @param deviceName The device name. * @param securitySettings The security settings. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ createOrUpdateSecuritySettings(deviceName: string, securitySettings: Models.SecuritySettings, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginCreateOrUpdateSecuritySettings(deviceName,securitySettings,resourceGroupName,managerName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Returns the time settings of the specified device name. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.DevicesGetTimeSettingsResponse> */ getTimeSettings(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.DevicesGetTimeSettingsResponse>; /** * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param callback The callback */ getTimeSettings(deviceName: string, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.TimeSettings>): void; /** * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param options The optional parameters * @param callback The callback */ getTimeSettings(deviceName: string, resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TimeSettings>): void; getTimeSettings(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TimeSettings>, callback?: msRest.ServiceCallback<Models.TimeSettings>): Promise<Models.DevicesGetTimeSettingsResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, managerName, options }, getTimeSettingsOperationSpec, callback) as Promise<Models.DevicesGetTimeSettingsResponse>; } /** * Returns the update summary of the specified device name. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.DevicesGetUpdateSummaryResponse> */ getUpdateSummary(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.DevicesGetUpdateSummaryResponse>; /** * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param callback The callback */ getUpdateSummary(deviceName: string, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.Updates>): void; /** * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param options The optional parameters * @param callback The callback */ getUpdateSummary(deviceName: string, resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Updates>): void; getUpdateSummary(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Updates>, callback?: msRest.ServiceCallback<Models.Updates>): Promise<Models.DevicesGetUpdateSummaryResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, managerName, options }, getUpdateSummaryOperationSpec, callback) as Promise<Models.DevicesGetUpdateSummaryResponse>; } /** * Deletes the device. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, resourceGroupName, managerName, options }, beginDeleteMethodOperationSpec, options); } /** * Patches the device. * @param deviceName The device Name. * @param devicePatch Patch representation of the device. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginPatch(deviceName: string, devicePatch: Models.DevicePatch, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, devicePatch, resourceGroupName, managerName, options }, beginPatchOperationSpec, options); } /** * Creates or updates the alert settings * @param deviceName The device name. * @param alertSettings The alert settings. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdateAlertSettings(deviceName: string, alertSettings: Models.AlertSettings, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, alertSettings, resourceGroupName, managerName, options }, beginCreateOrUpdateAlertSettingsOperationSpec, options); } /** * Deactivates the device. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeactivate(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, resourceGroupName, managerName, options }, beginDeactivateOperationSpec, options); } /** * Downloads udpates on the device. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDownloadUpdates(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, resourceGroupName, managerName, options }, beginDownloadUpdatesOperationSpec, options); } /** * Fails over the device to another device. * @param deviceName The device name. * @param failoverRequest The failover request. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginFailover(deviceName: string, failoverRequest: Models.FailoverRequest, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, failoverRequest, resourceGroupName, managerName, options }, beginFailoverOperationSpec, options); } /** * Installs the updates on the device. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginInstallUpdates(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, resourceGroupName, managerName, options }, beginInstallUpdatesOperationSpec, options); } /** * Scans for updates on the device. * @param deviceName The device name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginScanForUpdates(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, resourceGroupName, managerName, options }, beginScanForUpdatesOperationSpec, options); } /** * Creates or updates the security settings. * @param deviceName The device name. * @param securitySettings The security settings. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdateSecuritySettings(deviceName: string, securitySettings: Models.SecuritySettings, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, securitySettings, resourceGroupName, managerName, options }, beginCreateOrUpdateSecuritySettingsOperationSpec, options); } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listByManagerOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion, Parameters.expand ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeviceList }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion, Parameters.expand ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Device }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const getAlertSettingsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/alertSettings/default", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.AlertSettings }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const listFailoverTargetOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/failoverTargets", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion, Parameters.expand ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeviceList }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const listMetricsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/metrics", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion, Parameters.filter ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.MetricList }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const listMetricDefinitionOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/metricsDefinitions", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.MetricDefinitionList }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const getNetworkSettingsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/networkSettings/default", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.NetworkSettings }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const getTimeSettingsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/timeSettings/default", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.TimeSettings }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const getUpdateSummaryOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/updateSummary/default", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Updates }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const beginPatchOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "devicePatch", mapper: { ...Mappers.DevicePatch, required: true } }, responses: { 200: { bodyMapper: Mappers.Device }, 202: {}, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const beginCreateOrUpdateAlertSettingsOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/alertSettings/default", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "alertSettings", mapper: { ...Mappers.AlertSettings, required: true } }, responses: { 200: { bodyMapper: Mappers.AlertSettings }, 202: {}, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const beginDeactivateOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/deactivate", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const beginDownloadUpdatesOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/download", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const beginFailoverOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/failover", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "failoverRequest", mapper: { ...Mappers.FailoverRequest, required: true } }, responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const beginInstallUpdatesOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/install", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const beginScanForUpdatesOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/scanForUpdates", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const beginCreateOrUpdateSecuritySettingsOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/securitySettings/default/update", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "securitySettings", mapper: { ...Mappers.SecuritySettings, required: true } }, responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, serializer };
the_stack
import React, { useState, useRef, useEffect } from 'react'; import { Drawer, Form, ButtonToolbar, Button, Whisper, Tooltip, InputGroup, Input, toaster, Message, Avatar, Popover, Dropdown, } from 'rsuite'; import { axios } from 'api'; import { UserStore } from 'stores'; import { useNavigate } from 'react-router-dom'; import config from 'config'; const MenuPopover = React.forwardRef(({ onSelect, ...rest }: any, ref: any) => { const { me } = UserStore; return ( <Popover ref={ref} {...rest} full> <div style={{ padding: 15, paddingBottom: 0 }}> <p> <b>{me?.name}</b> 账号已登陆 </p> <p style={{ margin: 0, color: '#0005' }}>{me?.email}</p> </div> <Dropdown.Menu onSelect={onSelect}> <Dropdown.Item divider /> <Dropdown.Item eventKey={1}>控制中心</Dropdown.Item> <Dropdown.Item eventKey={2}>开发文档</Dropdown.Item> <Dropdown.Item eventKey={3}>退出登陆</Dropdown.Item> </Dropdown.Menu> </Popover> ); }); export default function AppHead() { const [loginDrawer, setloginDrawer] = useState(false); const [isRegister, setisRegister] = useState(false); const navigate = useNavigate(); const __tooltip = (msg: string) => <Tooltip>{msg}</Tooltip>; const [loginConfig, setloginConfig] = useState<any>({}); const __APILogin = (account: string, password: string) => { if (loginConfig?.netLoading) { return; } if (!account || !password) { toaster.push(<Message>账号或密码不得为空。</Message>); return; } setloginConfig({ ...loginConfig, netLoading: true, }); const msgTitle = '登陆'; const params = { email: account, password, }; axios .post('/api/auth/login', params, {}) .then((res: any) => { setloginConfig({ ...loginConfig, netLoading: false, }); const { data: callback } = res; if (callback?.code !== 200 || !callback?.data) { toaster.push(<Message>{callback?.msg || msgTitle + '失败,请稍后重试!'}</Message>); } else { const { data } = callback; // console.log('成功', callback); toaster.push(<Message>{msgTitle + '成功。'}</Message>); setloginDrawer(false); UserStore.login(data); // 成功,关闭弹窗,刷新列表数据,清空编辑框数据 setloginConfig({ netLoading: false, }); } }) .catch((error: any) => { setloginConfig({ ...loginConfig, netLoading: false, }); toaster.push(<Message>{error + '' || msgTitle + '失败,请稍后重试!'}</Message>); }); }; const [registerConfig, setregisterConfig] = useState<any>({ netLoading: false }); const __APIRegister = (name: string, email: string, code: string, password: string) => { if (registerConfig?.netLoading) { return; } if (!name || !email || !code || !password) { toaster.push(<Message>数据填写不完整。</Message>); return; } setregisterConfig({ ...registerConfig, netLoading: true, }); const msgTitle = '注册账号'; const params = { email, name, code, password, }; axios .post('/api/auth/reg', params, {}) .then((res: any) => { setregisterConfig({ ...registerConfig, netLoading: false, }); const { data } = res; if (data?.code !== 200 || !data?.data) { toaster.push(<Message>{data?.msg || msgTitle + '失败,请稍后重试!'}</Message>); } else { // console.log('成功', data); toaster.push(<Message>{msgTitle + '成功。'}</Message>); // 成功,关闭弹窗,刷新列表数据,清空编辑框数据 setregisterConfig({ netLoading: false, }); } }) .catch((error: any) => { setregisterConfig({ ...registerConfig, netLoading: false, }); toaster.push(<Message>{error + '' || msgTitle + '失败,请稍后重试!'}</Message>); }); }; const [getCodeConfig, setgetCodeConfig] = useState<any>({ netLoading: false }); const __APIGetCode = (email: string) => { if (getCodeConfig?.netLoading || codeRetryStateConfig?.isLoading) { return; } if (!email) { toaster.push(<Message>邮箱地址未输入。</Message>); return; } setgetCodeConfig({ ...getCodeConfig, netLoading: true, }); const msgTitle = '获取验证码'; const params = { email, type: 0, }; axios .post('/api/auth/send', params, {}) .then((res: any) => { setgetCodeConfig({ ...getCodeConfig, netLoading: false, }); const { data } = res; if (data?.code !== 200) { toaster.push(<Message>{data?.msg || msgTitle + '失败,请稍后重试!'}</Message>); } else { // console.log('成功', data); toaster.push(<Message>{msgTitle + '成功。'}</Message>); // 启动重新获取验证码倒计时 getCodeRetryState(); // 成功,关闭弹窗,刷新列表数据,清空编辑框数据 setgetCodeConfig({ netLoading: false, }); } }) .catch((error: any) => { setgetCodeConfig({ ...getCodeConfig, netLoading: false, }); toaster.push(<Message>{error + '' || msgTitle + '失败,请稍后重试!'}</Message>); }); }; const [codeRetryStateConfig, setcodeRetryStateConfig] = useState<any>({ isLoading: false, }); const codeRetryTime = 60; const refCodeRetryStateConfig = useRef<any>({ endTime: codeRetryTime, timer: null, }); const getCodeRetryState = () => { setcodeRetryStateConfig({ isLoading: true, }); // 设置倒计时定时 refCodeRetryStateConfig.current = { ...refCodeRetryStateConfig.current, timer: setInterval(() => { let time = codeRetryTime; if (refCodeRetryStateConfig.current.endTime <= 1) { setcodeRetryStateConfig({ isLoading: false, }); time = codeRetryTime; clearInterval(refCodeRetryStateConfig.current.timer); } else { time = --refCodeRetryStateConfig.current.endTime; setcodeRetryStateConfig({ isLoading: true, }); } refCodeRetryStateConfig.current = { ...refCodeRetryStateConfig.current, endTime: time, }; }, 1000), }; }; useEffect(() => { return () => { // 卸载定时器 if (refCodeRetryStateConfig.current.timer) { clearInterval(refCodeRetryStateConfig.current.timer); } }; }, []); const refUserWhisper = useRef<any>(); let operateUserControl = false; const onUserControl = (key: number) => { if (operateUserControl) return; operateUserControl = true; // 关闭用户操作选项 refUserWhisper?.current?.close(); switch (key) { case 1: // 加载控制台 navigate('/control', { replace: true, }); break; case 2: // 新窗口打开开发文档 window.open(config.docsURL, '_blank'); break; case 3: // 用户退出登陆 setTimeout(() => { UserStore.loginOut(); }, 500); // Bin: 这里为啥要延迟呢?因为退出登陆执行太快,动画还没执行完可能会导致用户感觉 UI 卡一下 break; } setTimeout(() => { operateUserControl = false; }, 500); }; return ( <> <header className="header"> <div className="layout"> <h1 className="logo" onClick={() => { navigate('/', { replace: true, }); }} > 全能搜题 </h1> <div style={{ flex: 1 }}></div> <Whisper placement="bottomEnd" trigger="contextMenu" ref={refUserWhisper} speaker={<MenuPopover onSelect={onUserControl} />} > <Avatar circle onClick={() => { if (UserStore.me) { refUserWhisper?.current?.open(); } else { setloginDrawer(true); } }} > U </Avatar> </Whisper> </div> </header> <Drawer open={loginDrawer} onClose={() => setloginDrawer(false)}> <Drawer.Body> <div style={{ display: 'flex', flexDirection: 'column', height: '100%', justifyContent: 'center', }} > <h3>登陆全能搜题开放平台</h3> <p style={{ marginTop: 5, marginBottom: 45 }}>登陆后可以上传题库,添加题目,调用搜题接口</p> {!isRegister ? ( <Form onChange={(data) => { setloginConfig({ ...loginConfig, ...data }); }} fluid > <Form.Group> <Form.ControlLabel>账号/邮箱</Form.ControlLabel> <Form.Control name="account" autoComplete="off" /> </Form.Group> <Form.Group> <Form.ControlLabel>密码</Form.ControlLabel> <Form.Control name="password" type="password" autoComplete="off" onKeyUp={(e: any) => { if (e.keyCode === 13) { // 响应回车点击事件,立即登陆 } }} /> </Form.Group> <Form.Group> <ButtonToolbar style={{ paddingTop: 20, display: 'flex' }}> <Button appearance="primary" loading={loginConfig?.netLoading} onClick={() => { __APILogin(loginConfig?.account, loginConfig?.password); // console.log('账号', loginConfig); }} > 立即登陆 </Button> <Whisper placement="top" trigger="hover" speaker={__tooltip('如需重置密码请登陆服务器或联系超级管理员操作!')} > <Button appearance="link">忘记密码?</Button> </Whisper> <div style={{ flex: 1 }}></div> <Button onClick={() => setisRegister(true)}>注册账号</Button> </ButtonToolbar> </Form.Group> </Form> ) : ( <Form onChange={(data) => { setregisterConfig({ ...registerConfig, ...data, }); }} fluid > <Form.Group> <Form.ControlLabel>昵称</Form.ControlLabel> <Form.Control name="name" type="name" autoComplete="off" /> </Form.Group> <Form.Group> <Form.ControlLabel>邮箱地址</Form.ControlLabel> <Form.Control name="email" type="email" autoComplete="off" /> </Form.Group> <Form.Group> <Form.ControlLabel>验证码</Form.ControlLabel> <InputGroup inside style={{ width: '100%' }}> <Input name="code" onChange={(value) => { setregisterConfig({ ...registerConfig, code: value, }); }} /> <InputGroup.Button loading={getCodeConfig?.netLoading} disabled={codeRetryStateConfig?.isLoading} onClick={() => { __APIGetCode(registerConfig?.email); }} > {codeRetryStateConfig?.isLoading ? `${refCodeRetryStateConfig?.current?.endTime} 秒后重试` : '获取验证码'} </InputGroup.Button> </InputGroup> </Form.Group> <Form.Group> <Form.ControlLabel>密码</Form.ControlLabel> <Form.Control name="password" type="password" autoComplete="off" /> </Form.Group> <Form.Group> <ButtonToolbar style={{ paddingTop: 20, display: 'flex' }}> <Button appearance="primary" loading={registerConfig?.netLoading} onClick={() => { __APIRegister( registerConfig?.name, registerConfig?.email, registerConfig?.code, registerConfig?.password ); // console.log('注册数据', registerConfig); }} > 立即注册 </Button> <div style={{ flex: 1 }}></div> <Button onClick={() => setisRegister(false)}>已经有账号,登陆</Button> </ButtonToolbar> </Form.Group> </Form> )} </div> </Drawer.Body> </Drawer> </> ); }
the_stack
import * as R from 'ramda'; import {Result, err, ok} from '@compiler/core/monads/Result'; import {CompilerError} from '@compiler/core/shared/CompilerError'; import {NumberToken, Token} from '@compiler/lexer/tokens'; import { MIN_COMPILER_REG_LENGTH, MAX_COMPILER_REG_LENGTH, } from '../../constants'; import {isReservedKeyword} from '../utils/isReservedKeyword'; import {rpnTokens} from './utils/rpnTokens'; import {ParserError, ParserErrorCode} from '../../shared/ParserError'; import {InstructionArgSize, X86TargetCPU} from '../../types'; import {ASTAsmNode} from '../ast/ASTAsmNode'; import {ASTCompilerOption, CompilerOptions} from '../ast/def/ASTCompilerOption'; import {ASTLabelAddrResolver} from '../ast/instruction/ASTResolvableArg'; import {ASTAsmTree} from '../ast/ASTAsmParser'; import {ASTNodeKind} from '../ast/types'; import {ASTInstruction} from '../ast/instruction/ASTInstruction'; import {ASTDef} from '../ast/def/ASTDef'; import {ASTEqu} from '../ast/critical/ASTEqu'; import {ASTTimes} from '../ast/critical/ASTTimes'; import { ASTLabel, isLocalLabel, resolveLocalTokenAbsName, } from '../ast/critical/ASTLabel'; import {BinaryInstruction} from './types/BinaryInstruction'; import {BinaryDefinition} from './types/BinaryDefinition'; import {BinaryRepeatedNode} from './types/BinaryRepeatedNode'; import {BinaryEqu} from './types/BinaryEqu'; import {BinaryBlob} from './BinaryBlob'; import { FirstPassResult, SecondPassResult, BinaryBlobsMap, } from './BinaryPassResults'; export const MAGIC_LABELS = { CURRENT_LINE: '$', SECTION_START: '$$', }; /** * Transforms AST tree into binary set of data * * @see * Output may contain unresolved ASTInstruction (like jmps) for second pass! * They should be erased after second pass * * @export * @class X86Compiler */ export class X86Compiler { private _mode: InstructionArgSize = InstructionArgSize.WORD; private _origin: number = 0x0; private _target: X86TargetCPU = X86TargetCPU.I_486; constructor( public readonly tree: ASTAsmTree, public readonly maxPasses: number = 7, ) {} get origin() { return this._origin; } get mode() { return this._mode; } get target() { return this._target; } /** * Set origin which is absolute address * used to generated absolute offsets * * @param {number} origin * @memberof X86Compiler */ setOrigin(origin: number): void { this._origin = origin; } /** * Change bits mode * * @param {number} mode * @memberof X86Compiler */ setMode(mode: number): void { if (mode < MIN_COMPILER_REG_LENGTH || mode > MAX_COMPILER_REG_LENGTH) throw new ParserError(ParserErrorCode.UNSUPPORTED_COMPILER_MODE); this._mode = mode; } /** * Set cpu target * * @param {X86TargetCPU} target * @memberof X86Compiler */ setTarget(target: X86TargetCPU): void { if (R.isNil(target)) throw new ParserError(ParserErrorCode.UNSUPPORTED_COMPILER_TARGET); this._target = target; } /** * First pass compiler, omit labels and split into multiple chunks * * @param {ASTAsmTree} [tree=this.tree] * @param {boolean} [noAbstractInstructions=false] * @param {number} [initialOffset=0] * @returns {FirstPassResult} * @memberof X86Compiler */ firstPass( tree: ASTAsmTree = this.tree, noAbstractInstructions: boolean = false, initialOffset: number = 0, ): FirstPassResult { const result = new FirstPassResult(tree); const {target} = this; const {astNodes} = tree; const {labels, equ, nodesOffsets} = result; let offset = initialOffset; let originDefined = false; /** * Simplified version of keywordResolver but returns only * first phase labels values or * * @param {string} name * @returns {number} */ function criticalKeywordResolver(name: string): number { if (equ.has(name)) return equ.get(name).val ?? 0; return undefined; } /** * Resolves token value * * @param {Token[]} tokens * @returns {number} */ function criticalMathTokensEvaluate(tokens: Token[]): number { return rpnTokens( tokens, { keywordResolver: criticalKeywordResolver, }, ); } const isRedefinedKeyword = (keyword: string): boolean => ( equ.has(keyword) || labels.has(keyword) ); /** * Emits binary set of data for instruction * * @param {BinaryBlob} blob * @param {number} size */ const emitBlob = (blob: BinaryBlob, size?: number): void => { const addr = this._origin + offset; const prevBlob = nodesOffsets.get(addr); // EQU has size = 0, it can overlap if (size === 0) { // some instructions has 0 bytes, chain them to existing to // preserve order of execution, maybe there will be better solution? if (prevBlob) { prevBlob.slaveBlobs = prevBlob.slaveBlobs || []; prevBlob.slaveBlobs.push(blob); return; } } nodesOffsets.set(addr, blob); if (prevBlob) { blob.slaveBlobs = blob.slaveBlobs || []; // prevent nesting slaves if (prevBlob.slaveBlobs) { blob.slaveBlobs.push(...prevBlob.slaveBlobs); prevBlob.slaveBlobs = null; } blob.slaveBlobs.push(prevBlob); } offset += size ?? blob.binary?.length ?? 1; }; /** * Emits bytes for node from ASTnode, * performs initial compilation of instruction * with known size schemas * * @param {ASTAsmNode} node */ const processNode = (node: ASTAsmNode): void => { const absoluteAddress = this._origin + offset; if (noAbstractInstructions && node.kind !== ASTNodeKind.INSTRUCTION && node.kind !== ASTNodeKind.DEFINE) { throw new ParserError( ParserErrorCode.UNPERMITTED_NODE_IN_POSTPROCESS_MODE, node.loc.start, { node: node.toString(), }, ); } switch (node.kind) { /** [org 0x1] */ case ASTNodeKind.COMPILER_OPTION: { const compilerOption = <ASTCompilerOption> node; // origin set if (compilerOption.option === CompilerOptions.ORG) { if (originDefined) throw new ParserError(ParserErrorCode.ORIGIN_REDEFINED, node.loc.start); this.setOrigin( criticalMathTokensEvaluate(compilerOption.args), ); offset = 0; originDefined = true; // mode set } else if (compilerOption.option === CompilerOptions.BITS) { this.setMode( criticalMathTokensEvaluate(compilerOption.args) / 8, ); // target set } else if (compilerOption.option === CompilerOptions.TARGET) { const arg = <NumberToken> compilerOption.args[0]; this.setTarget( X86TargetCPU[`I_${arg.upperText}`], ); } } break; /** times 10 db nop */ case ASTNodeKind.TIMES: emitBlob( new BinaryRepeatedNode(<ASTTimes> node), 1, ); break; /** xor ax, ax */ case ASTNodeKind.INSTRUCTION: { const astInstruction = <ASTInstruction> node; const resolved = astInstruction.tryResolveSchema(null, null, target); if (!resolved) { throw new ParserError( ParserErrorCode.UNKNOWN_COMPILER_INSTRUCTION, node.loc.start, { instruction: astInstruction.toString(), }, ); } emitBlob( new BinaryInstruction(astInstruction).compile(this, absoluteAddress), ); } break; /** db 0x0 */ case ASTNodeKind.DEFINE: emitBlob( new BinaryDefinition(<ASTDef> node).compile(), ); break; /** test equ 0x0 */ case ASTNodeKind.EQU: { const equNode = (<ASTEqu> node); const blob = new BinaryEqu(equNode); if (isReservedKeyword(equNode.name)) { throw new ParserError( ParserErrorCode.USED_RESERVED_NAME, node.loc.start, { name: equNode.name, }, ); } if (isRedefinedKeyword(equNode.name)) { throw new ParserError( ParserErrorCode.EQU_ALREADY_DEFINED, node.loc.start, { name: equNode.name, }, ); } equ.set(equNode.name, blob); emitBlob(blob, 0); } break; /** test: */ case ASTNodeKind.LABEL: { const labelName = (<ASTLabel> node).name; if (isReservedKeyword(labelName)) { throw new ParserError( ParserErrorCode.USED_RESERVED_NAME, node.loc.start, { name: labelName, }, ); } if (isRedefinedKeyword(labelName)) { throw new ParserError( ParserErrorCode.LABEL_ALREADY_DEFINED, node.loc.start, { label: labelName, }, ); } labels.set(labelName, absoluteAddress); } break; default: throw new ParserError( ParserErrorCode.UNKNOWN_COMPILER_INSTRUCTION, node.loc.start, { instruction: node.toString(), }, ); } }; R.forEach( (node: ASTAsmNode) => { try { processNode(node); } catch (e) { e.loc = e.loc ?? node.loc.start; throw e; } }, astNodes, ); return result; } /** * Find unresolved instructions, try resolve them and emit binaries * * @private * @param {FirstPassResult} firstPassResult * @returns {SecondPassResult} * @memberof X86Compiler */ private secondPass(firstPassResult: FirstPassResult): SecondPassResult { const {target} = this; const {tree} = firstPassResult; const {labels, nodesOffsets, equ} = firstPassResult; const result = new SecondPassResult(0x0, labels); let success = false; let needSort = false; const sectionStartOffset = this._origin; // todo: add multiple sections support? /** * Lookups into tree and resolves nested label args * * @see * instructionIndex must be equal count of instructions in first phase! * * @param {ASTAsmNode} astNode * @param {number} instructionOffset * @returns {ASTLabelAddrResolver} */ function labelResolver(astNode: ASTAsmNode, instructionOffset: number): ASTLabelAddrResolver { return (name: string): number => { // handle case mov ax, [b] where [b] is unknown during compile time if (astNode instanceof ASTInstruction) astNode.labeledInstruction = true; if (sectionStartOffset !== null && name === MAGIC_LABELS.SECTION_START) return sectionStartOffset; if (name === MAGIC_LABELS.CURRENT_LINE) return instructionOffset; if (equ.has(name)) return equ.get(name).val ?? 0; if (isLocalLabel(name)) { name = resolveLocalTokenAbsName( tree, name, R.indexOf(astNode, tree.astNodes), ); } return labels.get(name); }; } /** * Resizes all block after offset which is enlarged * * @param {number} offset * @param {number} enlarge */ function resizeBlockAtOffset(offset: number, enlarge: number): void { // if so decrement precceding instruction offsets and label offsets for (const [label, labelOffset] of labels) { if (labelOffset > offset) labels.set(label, labelOffset + enlarge); } // if so decrement precceding instruction offsets and label offsets const offsetsArray = Array.from(nodesOffsets); for (const [instructionOffset] of offsetsArray) { if (instructionOffset > offset) nodesOffsets.delete(instructionOffset); } for (const [instructionOffset, nextInstruction] of offsetsArray) { if (instructionOffset > offset) nodesOffsets.set(instructionOffset + enlarge, nextInstruction); } } /** * Appends blobs map at current offset to nodesOffsets * * @param {number} offset * @param {BinaryBlobsMap} blobs */ function appendBlobsAtOffset(offset: number, blobs: BinaryBlobsMap): void { needSort = true; for (const [blobOffset, blob] of blobs) nodesOffsets.set(offset + blobOffset, blob); } /** * Process EQU, returns true if value changed * * @param {number} offset * @param {BinaryEqu} blob * @returns {boolean} */ function passEqu(offset: number, blob: BinaryEqu): boolean { const { ast, labeled, val: prevValue, } = blob; // ignore, it is propably already resolved if (!labeled) return false; blob.pass( labelResolver(ast, offset), ); return prevValue !== blob.val || R.isNil(prevValue); } /** * Definition might contain something like it: * db 0xFF, (label+2), 0xFE * its tries to resolve second arg * * @param {number} offset * @param {BinaryDefinition} blob * @returns {boolean} True if need to repeat pass */ function passDefinition(offset: number, blob: BinaryDefinition): boolean { return blob.hasUnresolvedDefinitions() && !blob.tryResolveOffsets(labelResolver(blob.ast, offset)); } // proper resolve labels for (let pass = 0; pass < this.maxPasses; ++pass) { let needPass = false; // eslint-disable-next-line prefer-const for (let [offset, blob] of nodesOffsets) { try { // check for slave blobs (0 bytes instructions, EQU) if (blob.slaveBlobs) { const {slaveBlobs: slaves} = blob; for (let slaveIndex = 0; slaveIndex < slaves.length; ++slaveIndex) { const slave = slaves[slaveIndex]; if (slave instanceof BinaryEqu) { if (passEqu(offset, slave)) needPass = true; } else throw new ParserError(ParserErrorCode.INCORRECT_SLAVE_BLOBS, blob.ast.loc.start); } } if (blob instanceof BinaryDefinition) { if (passDefinition(offset, blob)) needPass = true; else continue; } else if (blob instanceof BinaryEqu) { // ignore, it is propably already resolved if (passEqu(offset, blob)) needPass = true; else continue; } else if (blob instanceof BinaryRepeatedNode) { // repeats instruction nth times const blobResult = blob.pass(this, offset - this._origin, labelResolver(blob.ast, offset)); const blobSize = blobResult.getByteSize(); // prevent loop, kill times nodesOffsets.delete(offset); resizeBlockAtOffset(offset, blobSize - 1); if (blobSize) { appendBlobsAtOffset(0, blobResult.nodesOffsets); needPass = true; break; } } else if (blob instanceof BinaryInstruction) { const {ast, binary} = blob; const pessimisticSize = binary.length; // generally check for JMP/CALL etc instructions // and all args have defined values if (ast.isConstantSize()) continue; // matcher must choose which instruction to match // based on origin it must choose between short relative // jump and long ast.tryResolveSchema( labelResolver(ast, offset), offset, target, ); // single instruction might contain multiple schemas but never 0 const {schemas} = ast; if (!schemas.length) { throw new ParserError( ParserErrorCode.UNKNOWN_COMPILER_INSTRUCTION, ast.loc.start, { instruction: ast.toString(), }, ); } // check if instruction after replacing labels has been shrinked // if so - force rewrite precceding instrutions and labels const recompiled = new BinaryInstruction(ast).compile(this, offset); const shrinkBytes = pessimisticSize - recompiled.byteSize; if (shrinkBytes) { needPass = true; ast.unresolvedArgs = true; nodesOffsets.set(offset, recompiled); resizeBlockAtOffset(offset, -shrinkBytes); } // select first schema, it will be discarded if next instruction have label ast.schemas = [ ast.schemas[0], ]; } } catch (e) { e.loc = e.loc ?? blob.ast?.loc?.start; throw e; } } if (!needPass) { success = true; break; } else result.totalPasses = pass + 1; } // exhaust tries count if (!success) throw new ParserError(ParserErrorCode.UNABLE_TO_COMPILE_FILE); // produce binaries const orderedOffsets = ( needSort ? ( Array .from(nodesOffsets) .sort((a, b) => a[0] - b[0]) ) : nodesOffsets ); for (const [offset, blob] of orderedOffsets) { let compiled = blob; if (blob instanceof BinaryInstruction) compiled = blob.compile(this, offset); if (blob.binary) { result.byteSize = Math.max(result.byteSize, offset + blob.byteSize - this._origin); result.blobs.set(offset, compiled); } } return result; } /** * Transform provided AST nodes array into binary blobs * * @returns {Result<SecondPassResult, CompilerError[]>} * @memberof X86Compiler */ compile(): Result<SecondPassResult, CompilerError[]> { if (!this.tree) return null; try { return ok( this.secondPass( this.firstPass(), ), ); } catch (e) { return err( [ e, ], ); } } }
the_stack
module BABYLONX { export interface IVertexPoint { x: any, y: any, z: any, } export interface IUV { u: any, v: any, } export interface IGeometry { faces: any[], vertices: any[], normals: any[], positions: any[], uvs: any[], uvs2: any[], name: string } export interface IVertexPushOption { faceUVMap: string, pointIndex1: any, pointIndex2: any, pointIndex3: any, pointIndex4: any, uvStart: IUV, uvEnd: IUV, Face3Point: boolean, flip: boolean, onlyPush: boolean } export interface SVGPointSetting { step: any, } export interface IFaceVertices { point1: IVertexPoint, point2: IVertexPoint, point3: IVertexPoint, point4: IVertexPoint } export interface IImportGeoOption { x: any, y: any, z: any, checkFace: boolean, face: any } export class GeometryBuilder { static isInOption = null; static face3UV012 = "012"; static face3UV021 = "021"; static face3UV201 = "201"; static face3UV210 = "210"; static face4UV0123 = "0123"; static face4UV0132 = "0132"; static face4UV1023 = "1023"; static face4UV1032 = "1032"; static _null = 'set null anyway'; static GetTotalLength(path: any) { return null; } static Dim(v: any, u: any) { return Math.sqrt(Math.pow(u.x - v.x, 2.) + Math.pow(u.y - v.y, 2.) + (GeometryBuilder.Def(u.z, GeometryBuilder._null) ? Math.pow(u.z - v.z, 2.) : 0)); } static Def(a: any, d: any) { if (a != undefined && a != null) return (d != undefined && d != null ? a : true); else if (d != GeometryBuilder._null) return (d != undefined && d != null ? d : false); return null; } static Replace(s: string, t: string, d: string) { var ignore = null; return s.replace(new RegExp(t.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof (d) == "string") ? d.replace(/\$/g, "$$$$") : d); } static AddUv(faceUV: string, geo: IGeometry, index: number, uvs: IUV, uve: IUV) { if (!faceUV || faceUV.length == 0 || faceUV.length < index) { geo.uvs.push(uvs.u, uvs.v); return; } if (faceUV[index].toString() == "0") geo.uvs.push(uvs.u, uvs.v); if (faceUV[index].toString() == "1") geo.uvs.push(uvs.u, uve.v); if (faceUV[index].toString() == "2") geo.uvs.push(uve.u, uvs.v); if (faceUV[index].toString() == "3") geo.uvs.push(uve.u, uve.v); }; static Exchange(p: IVertexPoint) { if (!GeometryBuilder.Def(p, GeometryBuilder._null)) return false; return (p.x || p.x == 0.0); } static PushVertex(geo: IGeometry, p1: IVertexPoint, uv: IUV) { if (uv) uv = { u: 0., v: 0. }; geo.vertices.push({ x: p1.x, y: p1.y, z: p1.z }); geo.positions.push(p1.x, p1.y, p1.z); if (uv) geo.uvs.push(uv.u, uv.v); return geo.vertices.length - 1; } static MakeFace(geo: IGeometry, _points: IVertexPoint[], option: IVertexPushOption) { if (!option) option = { faceUVMap: "", pointIndex1: null, pointIndex2: null, pointIndex3: null, pointIndex4: null, uvStart: null, uvEnd: null, Face3Point: false, flip: false, onlyPush: false }; var points = { point1: _points[0], point2: _points[1], point3: _points[2], point4: _points[3] }; if (!option.uvStart) option.uvStart = { u: 0., v: 0. }; if (!option.uvEnd) option.uvEnd = { u: 1., v: 1. }; if (option.onlyPush || GeometryBuilder.Exchange(points.point1)) { geo.vertices.push({ x: points.point1.x, y: points.point1.y, z: points.point1.z }); geo.positions.push(points.point1.x, points.point1.y, points.point1.z); GeometryBuilder.AddUv(option.faceUVMap, geo, 0, option.uvStart, option.uvEnd); option.pointIndex1 = geo.vertices.length - 1; } if (option.onlyPush || GeometryBuilder.Exchange(points.point2)) { geo.vertices.push({ x: points.point2.x, y: points.point2.y, z: points.point2.z }); geo.positions.push(points.point2.x, points.point2.y, points.point2.z); GeometryBuilder.AddUv(option.faceUVMap, geo, 1, option.uvStart, option.uvEnd); option.pointIndex2 = geo.vertices.length - 1; } if (option.onlyPush || GeometryBuilder.Exchange(points.point3)) { geo.vertices.push({ x: points.point3.x, y: points.point3.y, z: points.point3.z }); geo.positions.push(points.point3.x, points.point3.y, points.point3.z); GeometryBuilder.AddUv(option.faceUVMap, geo, 2, option.uvStart, option.uvEnd); option.pointIndex3 = geo.vertices.length - 1; } if (!option.Face3Point) { if (option.onlyPush || GeometryBuilder.Exchange(points.point4)) { geo.vertices.push({ x: points.point4.x, y: points.point4.y, z: points.point4.z }); geo.positions.push(points.point4.x, points.point4.y, points.point4.z); GeometryBuilder.AddUv(option.faceUVMap, geo, 3, option.uvStart, option.uvEnd); option.pointIndex4 = geo.vertices.length - 1; } } if (!option.onlyPush) { if (option.pointIndex1 == null || option.pointIndex1 == undefined) option.pointIndex1 = points.point1; if (option.pointIndex2 == null || option.pointIndex2 == undefined) option.pointIndex2 = points.point2; if (option.pointIndex3 == null || option.pointIndex3 == undefined) option.pointIndex3 = points.point3; if (!option.Face3Point) { if (option.pointIndex4 == null || option.pointIndex4 == undefined) option.pointIndex4 = points.point4; } if (!GeometryBuilder.Def(GeometryBuilder.isInOption, GeometryBuilder._null)) { if (option.flip) { geo.faces.push(option.pointIndex1, option.pointIndex2, option.pointIndex3); if (!option.Face3Point) geo.faces.push(option.pointIndex2, option.pointIndex4, option.pointIndex3); } else { geo.faces.push(option.pointIndex1, option.pointIndex3, option.pointIndex2); if (!option.Face3Point) geo.faces.push(option.pointIndex2, option.pointIndex3, option.pointIndex4); } } else { if (option.flip) { if (GeometryBuilder.isInOption.a && GeometryBuilder.isInOption.b && GeometryBuilder.isInOption.c) geo.faces.push(option.pointIndex1, option.pointIndex2, option.pointIndex3); if (GeometryBuilder.isInOption.b && GeometryBuilder.isInOption.d && GeometryBuilder.isInOption.c && !option.Face3Point) geo.faces.push(option.pointIndex2, option.pointIndex4, option.pointIndex3); } else { if (GeometryBuilder.isInOption.a && GeometryBuilder.isInOption.c && GeometryBuilder.isInOption.b) geo.faces.push(option.pointIndex1, option.pointIndex3, option.pointIndex2); if (GeometryBuilder.isInOption.b && GeometryBuilder.isInOption.c && GeometryBuilder.isInOption.d && !option.Face3Point) geo.faces.push(option.pointIndex2, option.pointIndex3, option.pointIndex4); } } } if (!option.onlyPush) GeometryBuilder.isInOption = null; return [option.pointIndex1, option.pointIndex2, option.pointIndex3, option.pointIndex4]; } static ImportGeometry(geo: IGeometry, v: any[], f: any[], ts: IImportGeoOption) { var st = geo.vertices.length; for (var i = 0; i < v.length; i++) { geo.vertices.push({ x: v[i].x + (ts.x), y: v[i].y + (ts.y), z: v[i].z + (ts.z) }); geo.positions.push(v[i].x + (ts.x), v[i].y + (ts.y), v[i].z + (ts.z)); } for (var i = 0; i < f.length; i++) { if (!ts || !ts.checkFace || ts.face(i, f[i])) geo.faces.push(f[i].a + st, f[i].b + st, f[i].c + st); } } static GeometryBase(firstp: any, builder: any, exGeo: IGeometry, custom: any) { var geo = { faces: [], vertices: [], normals: [], positions: [], uvs: [], uvs2: [], name: "" }; if (!exGeo) exGeo = geo; if (builder) { builder(firstp, exGeo); } if (custom) { exGeo = custom(exGeo); } return exGeo; } static GetGeometryFromBabylon(geo: any, to: IGeometry) { to.faces = geo.indices; to.positions = geo.positions; to.normals = geo.normals; to.uvs = geo.uvs; return to; } static SvgCalibration = 0.00001; static GetPoints(op) { var h1 = 1; function getLenRounded(pat, i) { var i = pat.getPointAtLength(i); return i;//{ x: round(i.x * ik) / ik, y: round(i.y * ik) / ik }; } op.step = GeometryBuilder.Def(op.step, 0.5); var path = document.createElementNS("http://www.w3.org/2000/svg", "path"); path.setAttribute("d", op.path); var result = []; var len = GeometryBuilder.GetTotalLength(path);//path.getTotalLength(); if (GeometryBuilder.Def(op.inLine, GeometryBuilder._null) && (!GeometryBuilder.Def(op.pointLength, GeometryBuilder._null) || op.pointLength < 1000)) { op.step = 0.3; } if (GeometryBuilder.Def(op.pointLength, GeometryBuilder._null)) { op.min = len / op.pointLength; } var plen = 0.0 var s = getLenRounded(path, 0); op.density = GeometryBuilder.Def(op.density, [1]); function getDensityMapStep(index) { var ps = Math.floor(op.density.length * (index / len)); return op.step / op.density[ps]; } var p = s; var c = getLenRounded(path, op.step); plen += op.step; op.push(result, s); var p_o = 0; var oo_p = { x: 0, y: 0 }; for (var i = op.step * 2; i < len; i += getDensityMapStep(i)) { h1++; var n = getLenRounded(path, i); plen += op.step; if (GeometryBuilder.Def(op.inLine, true)) { if (i == op.step * 2) op.push(result, c); if (plen > GeometryBuilder.Def(op.min, 10.)) { op.push(result, n); plen = 0.0; } } else { var d1 = GeometryBuilder.Dim(p, c); var d2 = GeometryBuilder.Dim(c, n); var d3 = GeometryBuilder.Dim(p, n); var d4 = 0; var d5 = 0; if (GeometryBuilder.Def(p_o, GeometryBuilder._null)) { d4 = GeometryBuilder.Dim(p_o, c); d5 = GeometryBuilder.Dim(p_o, n); } var iilen = Math.abs(d3 - (d2 + d1)); var lll = GeometryBuilder.SvgCalibration; if (iilen > lll || p_o > lll) { if (GeometryBuilder.Dim(n, oo_p) > 4.0) { op.push(result, n); oo_p = n; } plen = 0.0; p_o = 0; } else { p_o += iilen; } } p = c; c = n; } result = op.push(result, getLenRounded(path, len), true); var sr = []; var i = 0; for (i = GeometryBuilder.Def(op.start, 0); i < result.length - GeometryBuilder.Def(op.end, 0); i++) { sr.push(result[i]); } return sr; } static BuildBabylonMesh(scene: any, geo: any) { return null; } static ToBabylonGeometry(geo: any) { return null; } static InitializeEngine() { eval("BABYLONX.GeometryBuilder.ToBabylonGeometry = function(op) { var vertexData = new BABYLON.VertexData(); vertexData.indices = op.faces; vertexData.positions = op.positions; vertexData.normals = op.normals; vertexData.uvs = op.uvs; if (BABYLONX.GeometryBuilder.Def(op.uv2s , GeometryBuilder._null)) vertexData.uv2s = op.uv2s; else vertexData.uv2s = []; return vertexData; } "); eval('BABYLONX.GeometryBuilder.GetTotalLength = function(path){return path.getTotalLength();}'); eval("BABYLONX.GeometryBuilder.BuildBabylonMesh = function(opscene,opgeo){ var geo = BABYLONX.GeometryBuilder.ToBabylonGeometry(opgeo); var mesh = new BABYLON.Mesh( opgeo.name, opscene); geo.normals = BABYLONX.GeometryBuilder.Def(geo.normals, []); try { BABYLON.VertexData.ComputeNormals(geo.positions, geo.indices, geo.normals); } catch (e) { } geo.applyToMesh(mesh, false); var center = { x: 0, y: 0, z: 0 }; for (i = 0; i < geo.positions.length; i += 3.0) { center.x += geo.positions[i]; center.y += geo.positions[i + 1]; center.z += geo.positions[i + 2]; } center = { x: center.x * 3.0 / geo.positions.length, y: center.y * 3.0 / geo.positions.length, z: center.z * 3.0 / geo.positions.length }; mesh.center = center; return mesh; }"); } } export class Geometry { faces: any; positions: any; vertices: any; normals: any; uvs: any; uvs2: {}; name: string; toMesh(scene: any) { var mesh = GeometryBuilder.BuildBabylonMesh(scene, this); return mesh; } constructor(geo: IGeometry) { if (geo == null) { geo = { faces: [], vertices: [], normals: [], positions: [], uvs: [], uvs2: [], name: "" }; } this.faces = GeometryBuilder.Def(geo.faces, []); this.positions = GeometryBuilder.Def(geo.positions, []); this.vertices = GeometryBuilder.Def(geo.vertices, []); this.normals = GeometryBuilder.Def(geo.normals, []); this.uvs = GeometryBuilder.Def(geo.uvs, []); this.uvs2 = GeometryBuilder.Def(geo.uvs2, []); this.name = geo.name; } } export class GeometryParser { Objects: any; NewVtx: number; Uvs_helper1: any; Uv_helper2: any; Geometry: Geometry; Flip: boolean; Index_helper: number; static OldIndex = 0; static Vertices = []; static Normals = []; Uv_update: boolean; static _null = "null all time"; static def(a: any, d: any) { if (a != undefined && a != null) return (d != undefined && d != null ? a : true); else if (d != GeometryParser._null) return (d != undefined && d != null ? d : false); return null; } static n_1(ar: any[]) { ar = GeometryParser.def(ar, []); if (!GeometryParser.def(ar.length, null)) return null; return ar[ar.length - 1]; } Vector(x: any, y: any, z: any) { return { x: x, y: y, z: z }; } Face3(a: any, b: any, c: any, normals: any) { return { x: a - GeometryParser.OldIndex, y: b - GeometryParser.OldIndex, z: c - GeometryParser.OldIndex }; } ParseVertexIndex(index: any) { index = parseInt(index); return index >= 0 ? index - 1 : index + GeometryParser.Vertices.length; } ParseNormalIndex(index) { index = parseInt(index); return index >= 0 ? index - 1 : index + GeometryParser.Normals.length; } ParseUVIndex(index) { index = parseInt(index); return index >= 0 ? index - 1 : 1.0; } Add_face(a: any, b: any, c: any, uvs: any) { var GP = GeometryParser; a = this.ParseVertexIndex(a - GP.OldIndex); b = this.ParseVertexIndex(b - GP.OldIndex); c = this.ParseVertexIndex(c - GP.OldIndex); if (this.Uv_update) { if (GP.def(GP.n_1(this.Objects).uvs[a * 2], null) && GP.n_1(this.Objects).uvs[a * 2] != this.Uvs_helper1[this.ParseUVIndex(uvs[0])].x && GP.n_1(this.Objects).uvs[a * 2 + 1] != this.Uvs_helper1[this.ParseUVIndex(uvs[0])].y) { this.NewVtx++; a = GeometryBuilder.PushVertex(GP.n_1(this.Objects), { x: parseFloat(GP.n_1(this.Objects).positions[a * 3]), y: parseFloat(GP.n_1(this.Objects).positions[a * 3 + 1]), z: parseFloat(GP.n_1(this.Objects).positions[a * 3 + 2]) }, null); // uv !uc } if (GP.def(GP.n_1(this.Objects).uvs[b * 2], null) && GP.n_1(this.Objects).uvs[b * 2] != this.Uvs_helper1[this.ParseUVIndex(uvs[1])].x && GP.n_1(this.Objects).uvs[b * 2 + 1] != this.Uvs_helper1[this.ParseUVIndex(uvs[1])].y) { b = GeometryBuilder.PushVertex(GP.n_1(this.Objects), { x: parseFloat(GP.n_1(this.Objects).positions[b * 3]), y: parseFloat(GP.n_1(this.Objects).positions[b * 3 + 1]), z: parseFloat(GP.n_1(this.Objects).positions[b * 3 + 2]) }, null); // uv !uc this.NewVtx++; } if (GP.def(GP.n_1(this.Objects).uvs[c * 2], null) && GP.n_1(this.Objects).uvs[c * 2] != this.Uvs_helper1[this.ParseUVIndex(uvs[2])].x && GP.n_1(this.Objects).uvs[c * 2 + 1] != this.Uvs_helper1[this.ParseUVIndex(uvs[2])].y) { c = GeometryBuilder.PushVertex(GP.n_1(this.Objects), { x: parseFloat(GP.n_1(this.Objects).positions[c * 3]), y: parseFloat(GP.n_1(this.Objects).positions[c * 3 + 1]), z: parseFloat(GP.n_1(this.Objects).positions[c * 3 + 2]) }, null); // uv !uc this.NewVtx++; } } GeometryBuilder.MakeFace(GP.n_1(this.Objects), [a, b, c], { faceUVMap: GeometryBuilder.face3UV012, Face3Point: true, pointIndex1: null, pointIndex2: null, pointIndex3: null, pointIndex4: null, uvStart: null, uvEnd: null, flip: this.Flip, onlyPush: false }); var faceIndex = GP.n_1(this.Objects).faces.length; try { if (!GP.def(GP.n_1(this.Objects).uvs[a * 2], null)) GP.n_1(this.Objects).uvs[a * 2] = this.Uvs_helper1[this.ParseUVIndex(uvs[0])].x; if (!GP.def(GP.n_1(this.Objects).uvs[a * 2 + 1], null)) GP.n_1(this.Objects).uvs[a * 2 + 1] = this.Uvs_helper1[this.ParseUVIndex(uvs[0])].y; if (!GP.def(GP.n_1(this.Objects).uvs[b * 2], null)) GP.n_1(this.Objects).uvs[b * 2] = this.Uvs_helper1[this.ParseUVIndex(uvs[1])].x; if (!GP.def(GP.n_1(this.Objects).uvs[b * 2 + 1], null)) GP.n_1(this.Objects).uvs[b * 2 + 1] = this.Uvs_helper1[this.ParseUVIndex(uvs[1])].y; if (!GP.def(GP.n_1(this.Objects).uvs[c * 2], null)) GP.n_1(this.Objects).uvs[c * 2] = this.Uvs_helper1[this.ParseUVIndex(uvs[2])].x; if (!GP.def(GP.n_1(this.Objects).uvs[c * 2 + 1], null)) GP.n_1(this.Objects).uvs[c * 2 + 1] = this.Uvs_helper1[this.ParseUVIndex(uvs[2])].y; GP.n_1(this.Objects).uvh = GP.def(GP.n_1(this.Objects).uvh, []); GP.n_1(this.Objects).uvf = GP.def(GP.n_1(this.Objects).uvf, []); GP.n_1(this.Objects).uvh[a] = GP.def(GP.n_1(this.Objects).uvh[a], []); GP.n_1(this.Objects).uvh[b] = GP.def(GP.n_1(this.Objects).uvh[b], []); GP.n_1(this.Objects).uvh[c] = GP.def(GP.n_1(this.Objects).uvh[c], []); GP.n_1(this.Objects).uvh[a * 2] = (this.Uvs_helper1[this.ParseUVIndex(uvs[0])].x); GP.n_1(this.Objects).uvh[a * 2 + 1] = (this.Uvs_helper1[this.ParseUVIndex(uvs[0])].y); GP.n_1(this.Objects).uvf[a] = faceIndex; GP.n_1(this.Objects).uvh[b * 2] = (this.Uvs_helper1[this.ParseUVIndex(uvs[1])].x); GP.n_1(this.Objects).uvh[b * 2 + 1] = (this.Uvs_helper1[this.ParseUVIndex(uvs[1])].y); GP.n_1(this.Objects).uvf[b] = faceIndex; GP.n_1(this.Objects).uvh[c * 2] = (this.Uvs_helper1[this.ParseUVIndex(uvs[2])].x); GP.n_1(this.Objects).uvh[c * 2 + 1] = (this.Uvs_helper1[this.ParseUVIndex(uvs[2])].y); GP.n_1(this.Objects).uvf[c] = faceIndex; } catch (e) { } } Handle_face_line(faces: any[], uvs: any[], normals_inds: any) { var GP = GeometryParser; uvs = GP.def(uvs, [0, 0, 0, 0]); if (faces[3] === undefined) { this.Add_face(faces[0], faces[1], faces[2], uvs); } else { this.Add_face(faces[0], faces[1], faces[3], [uvs[0], uvs[1], uvs[3]]); this.Add_face(faces[1], faces[2], faces[3], [uvs[1], uvs[2], uvs[3]]); } } // v float float float static VertexPattern = /v( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/; // vn float float float static NormalPattern = /vn( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/; // vt float float static UVPattern = /vt( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/; // f vertex vertex vertex ... static FacePattern1 = /f( +-?\d+)( +-?\d+)( +-?\d+)( +-?\d+)?/; // f vertex/uv vertex/uv vertex/uv ... static FacePattern2 = /f( +(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+))?/; // f vertex/uv/normal vertex/uv/normal vertex/uv/normal ... static FacePattern3 = /f( +(-?\d+)\/(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+)\/(-?\d+))?/; // f vertex//normal vertex//normal vertex//normal ... static FacePattern4 = /f( +(-?\d+)\/\/(-?\d+))( +(-?\d+)\/\/(-?\d+))( +(-?\d+)\/\/(-?\d+))( +(-?\d+)\/\/(-?\d+))?/; // NewGeo() { var GP = GeometryParser; if (this.Objects.length == 0 || GP.n_1(this.Objects).vertices.length > 0) { GP.OldIndex += GP.n_1(this.Objects).length > 0 ? GP.n_1(this.Objects).vertices.length - this.NewVtx : 0; this.NewVtx = 0; this.Geometry = new Geometry(null); this.Objects.push(this.Geometry); } } constructor(data: any, lastUV: boolean, flip: boolean) { var GP = GeometryParser; this.Objects = GP.def(this.Objects, []); this.Uv_update = lastUV; this.Uvs_helper1 = []; this.Flip = flip; if (/^o /gm.test(data) === false) { this.Geometry = new Geometry(null); this.Objects.push(this.Geometry); } var lines = data.split('\n'); var oldIndex = 0; var oldLine = ''; var lastchar = ''; for (var i = 0; i < lines.length; i++) { var line = lines[i]; line = line.trim(); var result; if (line.length === 0 || line.charAt(0) === '#') { continue; } else if ((result = GP.VertexPattern.exec(line)) !== null) { // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"] if (lastchar == 'g') this.NewGeo(); GeometryBuilder.PushVertex(GP.n_1(this.Objects), { x: -1 * result[1], y: result[2] * 1.0, z: result[3] * 1.0 }, null); // un !uc lastchar = 'v'; } else if ((result = GP.NormalPattern.exec(line)) !== null) { lastchar = 'n'; } else if ((result = GP.UVPattern.exec(line)) !== null) { // ["vt 0.1 0.2", "0.1", "0.2"] this.Uvs_helper1.push({ x: parseFloat(result[1]), y: parseFloat(result[2]) }); // uvs.push({ x: result[1], y: result[2] }); lastchar = 't'; } else if ((result = GP.FacePattern1.exec(line)) !== null) { // ["f 1 2 3", "1", "2", "3", undefined] this.Handle_face_line( [result[1], result[2], result[3], result[4]], null, null ); lastchar = 'f'; } else if ((result = GP.FacePattern2.exec(line)) !== null) { // ["f 1/1 2/2 3/3", " 1/1", "1", "1", " 2/2", "2", "2", " 3/3", "3", "3", undefined, undefined, undefined] this.Handle_face_line( [result[2], result[5], result[8], result[11]], //faces [result[3], result[6], result[9], result[12]], null //uv ); lastchar = 'f'; } else if ((result = GP.FacePattern3.exec(line)) !== null) { // ["f 1/1/1 2/2/2 3/3/3", " 1/1/1", "1", "1", "1", " 2/2/2", "2", "2", "2", " 3/3/3", "3", "3", "3", undefined, undefined, undefined, undefined] this.Handle_face_line( [result[2], result[6], result[10], result[14]], //faces [result[3], result[7], result[11], result[15]], //uv [result[4], result[8], result[12], result[16]] //normal ); lastchar = 'f'; } else if ((result = GP.FacePattern4.exec(line)) !== null) { // ["f 1//1 2//2 3//3", " 1//1", "1", "1", " 2//2", "2", "2", " 3//3", "3", "3", undefined, undefined, undefined] this.Handle_face_line( [result[2], result[5], result[8], result[11]], //faces [], //uv [result[3], result[6], result[9], result[12]] //normal ); lastchar = 'f'; } else if (/^o /.test(line)) { // || /^g /.test(line)) { if (line.replace('o', '').trim() != 'default') { oldLine = line.replace('o', '').trim(); if (oldLine != '' && this.Objects.length > 0) GP.n_1(this.Objects).refname = oldLine; } else oldLine = ''; this.NewGeo(); lastchar = 'o'; } else if (/^g /.test(line)) { if (line.replace('g', '').trim() != 'default') { oldLine = line.replace('g', '').trim(); if (oldLine != '' && this.Objects.length > 0) GP.n_1(this.Objects).refname = oldLine; } else oldLine = ''; lastchar = 'g'; } else if (/^usemtl /.test(line)) { // material // material.name = line.substring( 7 ).trim(); lastchar = 'u'; } else if (/^mtllib /.test(line)) { // mtl file lastchar = 'm'; } else if (/^s /.test(line)) { // smooth shading lastchar = 's'; } } } } }
the_stack
import * as assert from "assert"; import { testContext, disposeTestDocumentStore } from "../../Utils/TestUtil"; import DocumentStore, { IDocumentStore, BulkInsertOperation, IMetadataDictionary, } from "../../../src"; import { createMetadataDictionary } from "../../../src/Mapping/MetadataAsDictionary"; import { CONSTANTS } from "../../../src/Constants"; import * as BluebirdPromise from "bluebird"; import { DateUtil } from "../../../src/Utility/DateUtil"; describe("bulk insert", function () { let store: IDocumentStore; beforeEach(async function () { store = await testContext.getDocumentStore(); }); afterEach(async () => await disposeTestDocumentStore(store)); it("simple bulk insert should work", async () => { const fooBar1 = new FooBar(); fooBar1.name = "John Doe"; const fooBar2 = new FooBar(); fooBar2.name = "Jane Doe"; const fooBar3 = new FooBar(); fooBar3.name = "Mega John"; const fooBar4 = new FooBar(); fooBar4.name = "Mega Jane"; const bulkInsert = store.bulkInsert(); await bulkInsert.store(fooBar1); await bulkInsert.store(fooBar2); await bulkInsert.store(fooBar3); await bulkInsert.store(fooBar4); await bulkInsert.finish(); const session = store.openSession(); try { const doc1 = await session.load<FooBar>("FooBars/1-A"); const doc2 = await session.load<FooBar>("FooBars/2-A"); const doc3 = await session.load<FooBar>("FooBars/3-A"); const doc4 = await session.load<FooBar>("FooBars/4-A"); assert.ok(doc1); assert.ok(doc2); assert.ok(doc3); assert.ok(doc4); assert.strictEqual(doc1.name, "John Doe"); assert.strictEqual(doc2.name, "Jane Doe"); assert.strictEqual(doc3.name, "Mega John"); assert.strictEqual(doc4.name, "Mega Jane"); const docsInsertedCount = await session .query({ collection: "fooBars" }) .count(); assert.strictEqual(docsInsertedCount, 4); } finally { session.dispose(); } }); it("can be killed early before making connection", async () => { try { const bulkInsert = store.bulkInsert(); await bulkInsert.store(new FooBar()); await bulkInsert.abort(); await bulkInsert.store(new FooBar()); assert.fail("Should have thrown."); } catch (error) { assert.strictEqual(error.name, "BulkInsertAbortedException", error.message); const bulkInsertCanceled = /TaskCanceledException/i.test(error.message); const bulkInsertNotRegisteredYet = /Unable to kill bulk insert operation, because it was not found on the server./i.test(error.message); const bulkInsertSuccessfullyKilled = /Bulk insert was aborted by the user./i.test(error.message); // this one's racy, so it's one or the other assert.ok( bulkInsertCanceled || bulkInsertNotRegisteredYet || bulkInsertSuccessfullyKilled, "Unexpected error message:" + error.message); } }); it("can be aborted after a while", async () => { try { const bulkInsert = store.bulkInsert(); await bulkInsert.store(new FooBar()); await bulkInsert.store(new FooBar()); await bulkInsert.store(new FooBar()); await bulkInsert.store(new FooBar()); await BluebirdPromise.delay(500); await bulkInsert.abort(); await bulkInsert.store(new FooBar()); assert.fail("Should have thrown."); } catch (error) { assert.strictEqual(error.name, "BulkInsertAbortedException", error.message); const bulkInsertCanceled = /TaskCanceledException/i.test(error.message); const bulkInsertNotRegisteredYet = /Unable to kill bulk insert operation, because it was not found on the server./i.test(error.message); const bulkInsertSuccessfullyKilled = /Bulk insert was aborted by the user./i.test(error.message); // this one's racy, so it's one or the other assert.ok( bulkInsertCanceled || bulkInsertNotRegisteredYet || bulkInsertSuccessfullyKilled, "Unexpected error message:" + error.message); } }); it("should not accept ids ending with pipeline", async () => { try { const bulkInsert = store.bulkInsert(); await bulkInsert.store(new FooBar(), "foobars|"); assert.fail("Should have thrown."); } catch (error) { assert.strictEqual(error.name, "NotSupportedException"); assert.strictEqual(error.message, "Document ids cannot end with '|', but was called with foobars|"); } }); it("can modify metadata with bulk insert", async () => { const date = DateUtil.default.stringify(new Date()); const fooBar = new FooBar(); fooBar.name = "John Snow"; const metadata = createMetadataDictionary({ raw: {} }); metadata[CONSTANTS.Documents.Metadata.EXPIRES] = date; const bulkInsert = store.bulkInsert(); await bulkInsert.store(fooBar, metadata); await bulkInsert.finish(); const session = store.openSession(); try { const entity = await session.load<FooBar>("FooBars/1-A"); const metadataExpirationDate = session.advanced.getMetadataFor(entity)[CONSTANTS.Documents.Metadata.EXPIRES]; assert.strictEqual(date, metadataExpirationDate); } finally { session.dispose(); } }); it("can handle nested types properly", async () => { class BulkTestItem { public name: string; public created: Date; public constructor(name: string) { this.name = name; this.created = new Date(); } } class BulkTestItemCollection { public id: string; public items: BulkTestItem[]; public constructor(...names: string[]) { this.items = names.map(name => { return new BulkTestItem(name); }); } } store.conventions.registerEntityType(BulkTestItem); store.conventions.registerEntityType(BulkTestItemCollection); const entity = new BulkTestItemCollection("jon", "dany", "imp"); { const bulk = store.bulkInsert(); await bulk.store(entity); await bulk.finish(); } { const session = store.openSession(); const loaded = await session.load(entity["id"]); assert.ok(loaded); const metadata = loaded["@metadata"]; assert.ok(metadata["@id"], entity["id"]); const nestedObjectTypes = metadata[CONSTANTS.Documents.Metadata.NESTED_OBJECT_TYPES]; assert.ok(nestedObjectTypes); assert.strictEqual(Object.keys(nestedObjectTypes).length, 2); assert.strictEqual(nestedObjectTypes["items[]"], BulkTestItem.name); assert.strictEqual(nestedObjectTypes["items[].created"], "date"); } }); it.skip("[RDBC-226] can insert object literals with default conventions", async () => { const bulk = store.bulkInsert(); const obj = { id: null, name: "blabli" }; await bulk.store(obj); await bulk.finish(); assert.ok(obj["id"]); }); // tslint:disable-next-line:max-line-length it("can handle custom entity naming conventions + object literals when findCollectionNameForObjectLiteral is specified", async () => { const store2 = new DocumentStore(store.urls, store.database); store2.conventions.entityFieldNameConvention = "camel"; store2.conventions.remoteEntityFieldNameConvention = "pascal"; store2.conventions.findCollectionNameForObjectLiteral = () => "test"; store2.initialize(); const registeredAt = new Date(); const camelCasedObj = { id: null, name: "Jon", job: "white walker killer", fathersName: "Rhaegar", canUseSword: true, equipment: ["sword", "bow", "direwolf"], registeredAt }; try { const bulk = store2.bulkInsert(); await bulk.store(camelCasedObj); await bulk.finish(); } finally { store2.dispose(); } { // use case transformless store to verify doc const session = store.openSession(); const loaded = await session.load(camelCasedObj["id"]); assert.ok(loaded); assert.ok("Name" in loaded); assert.strictEqual(loaded["Name"], camelCasedObj.name); assert.ok("Job" in loaded); assert.ok("CanUseSword" in loaded); assert.ok("Equipment" in loaded); assert.ok("RegisteredAt" in loaded); assert.ok("FathersName" in loaded); assert.strictEqual(loaded["Equipment"].length, 3); assert.ok("Raven-Node-Type" in loaded["@metadata"]); assert.ok("@nested-object-types" in loaded["@metadata"]); assert.ok("@collection" in loaded["@metadata"]); } }); }); describe("BulkInsertOperation._typeCheckStoreArgs() properly parses arguments", () => { const typeCheckStoreArgs = BulkInsertOperation["_typeCheckStoreArgs"]; // tslint:disable-next-line:no-empty const expectedCallback = () => { }; const expectedId = "id"; const expectedMetadata = {} as IMetadataDictionary; const expectedNullId = null; it("accepts id", () => { const { id, getId } = typeCheckStoreArgs(expectedId); assert.strictEqual(id, expectedId); assert.ok(!getId); }); it("accepts metadata", () => { const { id, getId, metadata } = typeCheckStoreArgs(expectedMetadata); assert.strictEqual(metadata, expectedMetadata); assert.ok(!id); assert.ok(getId); }); it("accepts id, metadata", () => { const { id, getId, metadata } = typeCheckStoreArgs(expectedId, expectedMetadata); assert.strictEqual(metadata, expectedMetadata); assert.strictEqual(id, expectedId); assert.ok(!getId); }); it("accepts null id, metadata returns getId true", () => { const { id, getId, metadata } = typeCheckStoreArgs(expectedNullId, expectedMetadata); assert.strictEqual(metadata, expectedMetadata); assert.ok(!id); assert.ok(getId); }); }); export class FooBar { public name: string; }
the_stack
require('./router.css'); import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { $, Expression, Executor, Dataset } from 'plywood'; import { Stage, Clicker, Essence, DataCube, Filter, Dimension, Measure } from '../../../common/models/index'; import { replaceHash } from '../../utils/url/url'; import { extend } from '../../../common/utils/object/object'; import { SvgIcon } from '../svg-icon/svg-icon'; export type Inflater = (key: string, value: string) => {key: string, value: any}; export interface RouteProps extends React.Props<any> { fragment: string; alwaysShowOrphans?: boolean; transmit?: string[]; inflate?: Inflater; } export interface RouteState {} export class Route extends React.Component<RouteProps, RouteState> {} export interface QualifiedPath { route: JSX.Element; fragment: string; crumbs: string[]; wasDefaultChoice?: boolean; properties?: any; orphans?: JSX.Element[]; parentRoutes: JSX.Element[]; } export interface RouterProps extends React.Props<any> { // this callback is mandatory because the outer parent needs to react (lulz) // to a change and update its state so it rerenders. The router can't trigger // the rerendering by itself, nor should it. onURLChange: (breadCrumbs: string[]) => void; rootFragment?: string; } export interface RouterState { hash?: string; } const HASH_SEPARATOR = /\/+/; export class Router extends React.Component<RouterProps, RouterState> { public mounted: boolean; constructor() { super(); this.state = {}; this.globalHashChangeListener = this.globalHashChangeListener.bind(this); } componentDidMount() { window.addEventListener('hashchange', this.globalHashChangeListener); // Timeout to avoid race conditions between renders window.setTimeout(() => this.onHashChange(window.location.hash), 1); } componentWillUnmount() { window.removeEventListener('hashchange', this.globalHashChangeListener); } globalHashChangeListener(): void { var newHash = window.location.hash; // Means we're going somewhere unknown and this specific router shouldn't // interfer if (this.removeRootFragmentFromHash(newHash) === newHash) return; if (this.state.hash !== newHash) this.onHashChange(newHash); } removeRootFragmentFromHash(hash: string): string { const { rootFragment } = this.props; if (!rootFragment) return hash; return hash.replace(new RegExp('^#' + rootFragment, 'gi'), ''); } componentWillReceiveProps(nextProps: RouterProps) { this.globalHashChangeListener(); } parseHash(hash: string): string[] { if (!hash) return []; var fragments = this.removeRootFragmentFromHash(hash).split(HASH_SEPARATOR); return fragments.filter(Boolean); } sanitizeHash(hash: string): string { const { rootFragment } = this.props; const fragments = this.parseHash(hash); if (fragments.length === 0) return '#' + rootFragment; return `#${rootFragment}/${fragments.join('/')}`; } replaceHash(newHash: string) { replaceHash(newHash); this.onHashChange(newHash); } hasExtraFragments(path: QualifiedPath): boolean { return path.crumbs.length > path.fragment.split(HASH_SEPARATOR).length; } stripUnnecessaryFragments(path: QualifiedPath, crumbs: string[]) { const { rootFragment } = this.props; const fragments = path.fragment.split(HASH_SEPARATOR); const parentFragment = crumbs.join('/').replace(path.crumbs.join('/'), '').replace(/\/$/, ''); const strippedRouteCrumbs = path.crumbs.slice(0, path.fragment.split(HASH_SEPARATOR).length); const strippedCrumbs = [ rootFragment, parentFragment, strippedRouteCrumbs.join('/') ].filter(Boolean); this.replaceHash('#' + strippedCrumbs.join('/')); } onHashChange(hash: string) { const { rootFragment } = this.props; var safeHash = this.sanitizeHash(hash); if (hash !== safeHash) { this.replaceHash(safeHash); return; } var crumbs = this.parseHash(hash); var children = this.props.children as JSX.Element[]; // Default path if (crumbs.length === 0) { let defaultFragment = this.getDefaultFragment(children); if (defaultFragment) { this.replaceHash(hash + '/' + defaultFragment); return; } } var path = this.getQualifiedPath(children, crumbs); if (path.wasDefaultChoice) { crumbs.pop(); crumbs.push(path.fragment); this.replaceHash('#' + [rootFragment].concat(crumbs).join('/')); return; } // Unnecessary fragments if (this.hasExtraFragments(path)) { this.stripUnnecessaryFragments(path, crumbs); return; } // Default child for this path if (this.canDefaultDeeper(path.fragment, path.crumbs)) { crumbs = crumbs.concat(this.getDefaultDeeperCrumbs(path.fragment, path.crumbs)); this.replaceHash('#' + [rootFragment].concat(crumbs).join('/')); } if (this.props.onURLChange) { this.props.onURLChange(crumbs); } this.setState({hash: window.location.hash}); } getDefaultDeeperCrumbs(fragment: string, crumbs: string[]): string[] { var bits = fragment.split(HASH_SEPARATOR); bits.splice(0, crumbs.length); return bits.map((bit) => bit.match(/^:[^=]+=(\w+)$/)[1]); } canDefaultDeeper(fragment: string, crumbs: string[]): boolean { var bits = fragment.split(HASH_SEPARATOR); if (bits.length === crumbs.length) return false; bits.splice(0, crumbs.length); return bits.every((bit) => /^:[^=]+=\w+$/.test(bit)); } getDefaultFragment(children: JSX.Element[]): string { for (let i = 0; i < children.length; i++) { let child = children[i]; if (child.type === Route) { return child.props.fragment; } } return undefined; } getQualifiedPath(candidates: JSX.Element[], crumbs: string[], properties = {}, orphans: JSX.Element[] = [], parentRoutes: JSX.Element[] = []): QualifiedPath { // In case there's only one route if (this.isRoute(candidates as any)) { candidates = ([candidates as any]) as JSX.Element[]; } for (let i = 0; i < candidates.length; i++) { let candidate = candidates[i]; if (!candidate) continue; if (this.isAComment(candidate)) continue; let fragment = candidate.props.fragment; if (!fragment) continue; properties = extend(this.getPropertiesFromCrumbs(crumbs, fragment), properties); if (crumbs[0] === fragment || fragment.charAt(0) === ':') { let children = candidate.props.children; let parents = parentRoutes.concat([candidate]); if (!(Array.isArray(children)) || crumbs.length === 1) { return {fragment, route: candidate, crumbs, properties, orphans, parentRoutes: parents}; } else { if (candidate.props.alwaysShowOrphans === true) { orphans = orphans.concat(children.filter(this.isSimpleChild, this)); } return this.getQualifiedPath(children, crumbs.slice(1), properties, orphans, parents); } } } // If we are here, it means no route has been found and we should // return a default one. var route = candidates.filter(this.isRoute)[0]; var fragment = route.props.fragment; properties = extend(this.getPropertiesFromCrumbs(crumbs, fragment), properties); return {fragment, route, crumbs, wasDefaultChoice: true, properties, orphans, parentRoutes}; } hasSingleChild(route: JSX.Element): boolean { if (!route) return false; return !(Array.isArray(route.props.children)); } isRoute(candidate: JSX.Element): boolean { if (!candidate) return false; return candidate.type === Route; } // Those pesky <!-- react-empty: 14 --> thingies... isAComment(candidate: JSX.Element): boolean { if (!candidate) return false; return candidate.type === undefined; } isSimpleChild(candidate: JSX.Element): boolean { if (!candidate) return false; return !this.isAComment(candidate) && !this.isRoute(candidate); } getSimpleChildren(parent: JSX.Element): JSX.Element[] { if (!parent) return null; return parent.props.children.filter(this.isSimpleChild, this); } getPropertiesFromCrumbs(crumbs: string[], fragment: string, props: any = {}): any { let fragmentToKey = (f: string) => f.slice(1).replace(/=.*$/, ''); let myCrumbs = crumbs.concat(); fragment.split(HASH_SEPARATOR).forEach((bit, i) => { if (bit.charAt(0) !== ':') return; props[fragmentToKey(bit)] = myCrumbs.shift(); }); return props; } inflate(pump: Inflater, properties: any): any { if (!pump) return properties; let newProperties: any = {}; for (let originalKey in properties) { let {key, value} = pump(originalKey, properties[originalKey]); newProperties[key] = value; } return newProperties; } fillProperties(child: JSX.Element, path: QualifiedPath, i = 0): JSX.Element { if (!(child.type instanceof Function)) return child; var propsToTransmit = this.getPropertiesFromCrumbs(path.crumbs, path.route.props.fragment); path.parentRoutes.forEach(route => { if (route.props.transmit) { route.props.transmit.forEach((key: string) => propsToTransmit[key] = path.properties[key]); } }); propsToTransmit = this.inflate(path.route.props.inflate, propsToTransmit); return React.cloneElement(child, extend(propsToTransmit, {key: i})); } getQualifiedChild(candidates: JSX.Element[], crumbs: string[]): JSX.Element | JSX.Element[] { var elements: JSX.Element[]; var path = this.getQualifiedPath(candidates, crumbs); if (this.hasSingleChild(path.route)) { elements = path.orphans.map((orphan, i) => this.fillProperties(orphan, path, i)) .concat([this.fillProperties(path.route.props.children, path, path.orphans.length)]) ; } else { var children = this.getSimpleChildren(path.route); if (children.length === 0) return null; elements = children .map((child, i) => this.fillProperties(child, path, i)) .concat(path.orphans.map((orphan, i) => this.fillProperties(orphan, path, children.length + i))) ; } if (!elements) return null; if (elements.length === 1) return elements[0]; return elements; } render() { const { children } = this.props; const { hash } = this.state; if (hash === undefined) return null; const crumbs = this.parseHash(hash); if (!crumbs || !crumbs.length) return null; const qualifiedChildren = this.getQualifiedChild(children as JSX.Element[], crumbs) as any; // I wish it wouldn't need an enclosing element but... // https://github.com/facebook/react/issues/2127 return <div className="route-wrapper" style={{width: '100%', height: '100%'}}>{qualifiedChildren}</div>; } }
the_stack
* A packed-value, sparse array context used for storing 64 bit signed values. * * An array context is optimised for tracking sparsely set (as in mostly zeros) values that tend to not make * use pof the full 64 bit value range even when they are non-zero. The array context's internal representation * is such that the packed value at each virtual array index may be represented by 0-8 bytes of actual storage. * * An array context encodes the packed values in 8 "set trees" with each set tree representing one byte of the * packed value at the virtual index in question. The {@link #getPackedIndex(int, int, boolean)} method is used * to look up the byte-index corresponding to the given (set tree) value byte of the given virtual index, and can * be used to add entries to represent that byte as needed. As a succesful {@link #getPackedIndex(int, int, boolean)} * may require a resizing of the array, it can throw a {@link ResizeException} to indicate that the requested * packed index cannot be found or added without a resize of the physical storage. * */ export const MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY = 16; const MAX_SUPPORTED_PACKED_COUNTS_ARRAY_LENGTH = Math.pow(2, 13) - 1; //(Short.MAX_VALUE / 4); TODO ALEX why ??? const SET_0_START_INDEX = 0; const NUMBER_OF_SETS = 8; const LEAF_LEVEL_SHIFT = 3; const NON_LEAF_ENTRY_SLOT_INDICATORS_OFFSET = 0; const NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS = 1; const PACKED_ARRAY_GROWTH_INCREMENT = 16; const PACKED_ARRAY_GROWTH_FRACTION_POW2 = 4; const { pow, ceil, log2, max } = Math; const bitCount = (n: number) => { var bits = 0; while (n !== 0) { bits += bitCount32(n | 0); n /= 0x100000000; } return bits; }; const bitCount32 = (n: number) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return (((n + (n >> 4)) & 0xf0f0f0f) * 0x1010101) >> 24; }; export class PackedArrayContext { public readonly isPacked: boolean; physicalLength: number; private array: ArrayBuffer; private byteArray: Uint8Array; private shortArray: Uint16Array; private longArray: Float64Array; private populatedShortLength: number = 0; private virtualLength: number; private topLevelShift: number = Number.MAX_VALUE; // Make it non-sensical until properly initialized. constructor(virtualLength: number, initialPhysicalLength: number) { this.physicalLength = Math.max( initialPhysicalLength, MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY ); this.isPacked = this.physicalLength <= MAX_SUPPORTED_PACKED_COUNTS_ARRAY_LENGTH; if (!this.isPacked) { this.physicalLength = virtualLength; } this.array = new ArrayBuffer(this.physicalLength * 8); this.initArrayViews(this.array); this.init(virtualLength); } private initArrayViews(array: ArrayBuffer) { this.byteArray = new Uint8Array(array); this.shortArray = new Uint16Array(array); this.longArray = new Float64Array(array); } private init(virtualLength: number) { if (!this.isPacked) { // Deal with non-packed context init: this.virtualLength = virtualLength; return; } this.populatedShortLength = SET_0_START_INDEX + 8; // Populate empty root entries, and point to them from the root indexes: for (let i = 0; i < NUMBER_OF_SETS; i++) { this.setAtShortIndex(SET_0_START_INDEX + i, 0); } this.setVirtualLength(virtualLength); } public clear() { this.byteArray.fill(0); this.init(this.virtualLength); } public copyAndIncreaseSize( newPhysicalArrayLength: number, newVirtualArrayLength: number ) { const ctx = new PackedArrayContext( newVirtualArrayLength, newPhysicalArrayLength ); if (this.isPacked) { ctx.populateEquivalentEntriesWithEntriesFromOther(this); } return ctx; } public getPopulatedShortLength() { return this.populatedShortLength; } public getPopulatedLongLength() { return (this.getPopulatedShortLength() + 3) >> 2; // round up } public setAtByteIndex(byteIndex: number, value: number) { this.byteArray[byteIndex] = value; } public getAtByteIndex(byteIndex: number) { return this.byteArray[byteIndex]; } /** * add a byte value to a current byte value in the array * @param byteIndex index of byte value to add to * @param valueToAdd byte value to add * @return the afterAddValue. ((afterAddValue & 0x100) != 0) indicates a carry. */ public addAtByteIndex(byteIndex: number, valueToAdd: number) { const newValue = this.byteArray[byteIndex] + valueToAdd; this.byteArray[byteIndex] = newValue; return newValue; } setPopulatedLongLength(newPopulatedLongLength: number) { this.populatedShortLength = newPopulatedLongLength << 2; } public getVirtualLength() { return this.virtualLength; } public length() { return this.physicalLength; } setAtShortIndex(shortIndex: number, value: number) { this.shortArray[shortIndex] = value; } setAtLongIndex(longIndex: number, value: number) { this.longArray[longIndex] = value; } getAtShortIndex(shortIndex: number) { return this.shortArray[shortIndex]; } getIndexAtShortIndex(shortIndex: number) { return this.shortArray[shortIndex]; } setPackedSlotIndicators(entryIndex: number, newPackedSlotIndicators: number) { this.setAtShortIndex( entryIndex + NON_LEAF_ENTRY_SLOT_INDICATORS_OFFSET, newPackedSlotIndicators ); } getPackedSlotIndicators(entryIndex: number) { return ( this.shortArray[entryIndex + NON_LEAF_ENTRY_SLOT_INDICATORS_OFFSET] & 0xffff ); } private getIndexAtEntrySlot(entryIndex: number, slot: number) { return this.getAtShortIndex( entryIndex + NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + slot ); } setIndexAtEntrySlot(entryIndex: number, slot: number, newIndexValue: number) { this.setAtShortIndex( entryIndex + NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + slot, newIndexValue ); } private expandArrayIfNeeded(entryLengthInLongs: number) { const currentLength = this.length(); if (currentLength < this.getPopulatedLongLength() + entryLengthInLongs) { const growthIncrement = max( entryLengthInLongs, PACKED_ARRAY_GROWTH_INCREMENT, this.getPopulatedLongLength() >> PACKED_ARRAY_GROWTH_FRACTION_POW2 ); this.resizeArray(currentLength + growthIncrement); } } private newEntry(entryLengthInShorts: number) { // Add entry at the end of the array: const newEntryIndex = this.populatedShortLength; this.expandArrayIfNeeded((entryLengthInShorts >> 2) + 1); this.populatedShortLength = newEntryIndex + entryLengthInShorts; for (let i = 0; i < entryLengthInShorts; i++) { this.setAtShortIndex(newEntryIndex + i, -1); // Poison value -1. Must be overriden before reads } return newEntryIndex; } private newLeafEntry() { // Add entry at the end of the array: let newEntryIndex; newEntryIndex = this.getPopulatedLongLength(); this.expandArrayIfNeeded(1); this.setPopulatedLongLength(newEntryIndex + 1); this.setAtLongIndex(newEntryIndex, 0); return newEntryIndex; } /** * Consolidate entry with previous entry verison if one exists * * @param entryIndex The shortIndex of the entry to be consolidated * @param previousVersionIndex the index of the previous version of the entry */ private consolidateEntry(entryIndex: number, previousVersionIndex: number) { const previousVersionPackedSlotsIndicators = this.getPackedSlotIndicators( previousVersionIndex ); // Previous version exists, needs consolidation const packedSlotsIndicators = this.getPackedSlotIndicators(entryIndex); const insertedSlotMask = packedSlotsIndicators ^ previousVersionPackedSlotsIndicators; // the only bit that differs const slotsBelowBitNumber = packedSlotsIndicators & (insertedSlotMask - 1); const insertedSlotIndex = bitCount(slotsBelowBitNumber); const numberOfSlotsInEntry = bitCount(packedSlotsIndicators); // Copy the entry slots from previous version, skipping the newly inserted slot in the target: let sourceSlot = 0; for (let targetSlot = 0; targetSlot < numberOfSlotsInEntry; targetSlot++) { if (targetSlot !== insertedSlotIndex) { const indexAtSlot = this.getIndexAtEntrySlot( previousVersionIndex, sourceSlot ); if (indexAtSlot !== 0) { this.setIndexAtEntrySlot(entryIndex, targetSlot, indexAtSlot); } sourceSlot++; } } } /** * Expand entry as indicated. * * @param existingEntryIndex the index of the entry * @param entryPointerIndex index to the slot pointing to the entry (needs to be fixed up) * @param insertedSlotIndex realtive [packed] index of slot being inserted into entry * @param insertedSlotMask mask value fo slot being inserted * @param nextLevelIsLeaf the level below this one is a leaf level * @return the updated index of the entry (-1 if epansion failed due to conflict) * @throws RetryException if expansion fails due to concurrent conflict, and caller should try again. */ expandEntry( existingEntryIndex: number, entryPointerIndex: number, insertedSlotIndex: number, insertedSlotMask: number, nextLevelIsLeaf: boolean ): number { let packedSlotIndicators = this.getAtShortIndex(existingEntryIndex) & 0xffff; packedSlotIndicators |= insertedSlotMask; const numberOfslotsInExpandedEntry = bitCount(packedSlotIndicators); if (insertedSlotIndex >= numberOfslotsInExpandedEntry) { throw new Error( "inserted slot index is out of range given provided masks" ); } const expandedEntryLength = numberOfslotsInExpandedEntry + NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS; // Create new next-level entry to refer to from slot at this level: let indexOfNewNextLevelEntry = 0; if (nextLevelIsLeaf) { indexOfNewNextLevelEntry = this.newLeafEntry(); // Establish long-index to new leaf entry } else { // TODO: Optimize this by creating the whole sub-tree here, rather than a step that will immediaterly expand // Create a new 1 word (empty, no slots set) entry for the next level: indexOfNewNextLevelEntry = this.newEntry( NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS ); // Establish short-index to new leaf entry this.setPackedSlotIndicators(indexOfNewNextLevelEntry, 0); } const insertedSlotValue = indexOfNewNextLevelEntry; const expandedEntryIndex = this.newEntry(expandedEntryLength); // populate the packed indicators word: this.setPackedSlotIndicators(expandedEntryIndex, packedSlotIndicators); // Populate the inserted slot with the index of the new next level entry: this.setIndexAtEntrySlot( expandedEntryIndex, insertedSlotIndex, insertedSlotValue ); this.setAtShortIndex(entryPointerIndex, expandedEntryIndex); this.consolidateEntry(expandedEntryIndex, existingEntryIndex); return expandedEntryIndex; } // // ###### ######## ######## ## ## ### ## ## #### ## ## ######## ######## ## ## // ## ## ## ## ## ## ## ## ## ## ## ### ## ## ## ## ## ## // ## ## ## ## ## ## ## ## ## ## #### ## ## ## ## ## ## // ## #### ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ### // ## ## ## ## ## ## ######### ## ## ## ## #### ## ## ## ## ## // ## ## ## ## ## ## ## ## ## ## ## ## ### ## ## ## ## ## // ###### ######## ## ### ## ## ######## ## #### ## ## ######## ######## ## ## // getRootEntry(setNumber: number, insertAsNeeded: boolean = false) { const entryPointerIndex = SET_0_START_INDEX + setNumber; let entryIndex = this.getIndexAtShortIndex(entryPointerIndex); if (entryIndex == 0) { if (!insertAsNeeded) { return 0; // Index does not currently exist in packed array; } entryIndex = this.newEntry(NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS); // Create a new empty (no slots set) entry for the next level: this.setPackedSlotIndicators(entryIndex, 0); this.setAtShortIndex(entryPointerIndex, entryIndex); } return entryIndex; } /** * Get the byte-index (into the packed array) corresponding to a given (set tree) value byte of given virtual index. * Inserts new set tree nodes as needed if indicated. * * @param setNumber The set tree number (0-7, 0 corresponding with the LSByte set tree) * @param virtualIndex The virtual index into the PackedArray * @param insertAsNeeded If true, will insert new set tree nodes as needed if they do not already exist * @return the byte-index corresponding to the given (set tree) value byte of the given virtual index */ getPackedIndex( setNumber: number, virtualIndex: number, insertAsNeeded: boolean ) { if (virtualIndex >= this.virtualLength) { throw new Error( `Attempting access at index ${virtualIndex}, beyond virtualLength ${this.virtualLength}` ); } let entryPointerIndex = SET_0_START_INDEX + setNumber; // TODO init needed ? let entryIndex = this.getRootEntry(setNumber, insertAsNeeded); if (entryIndex == 0) { return -1; // Index does not currently exist in packed array; } // Work down the levels of non-leaf entries: for ( let indexShift = this.topLevelShift; indexShift >= LEAF_LEVEL_SHIFT; indexShift -= 4 ) { const nextLevelIsLeaf = indexShift === LEAF_LEVEL_SHIFT; // Target is a packedSlotIndicators entry const packedSlotIndicators = this.getPackedSlotIndicators(entryIndex); const slotBitNumber = (virtualIndex / pow(2, indexShift)) & 0xf; //(virtualIndex >>> indexShift) & 0xf; const slotMask = 1 << slotBitNumber; const slotsBelowBitNumber = packedSlotIndicators & (slotMask - 1); const slotNumber = bitCount(slotsBelowBitNumber); if ((packedSlotIndicators & slotMask) === 0) { // The entryIndex slot does not have the contents we want if (!insertAsNeeded) { return -1; // Index does not currently exist in packed array; } // Expand the entry, adding the index to new entry at the proper slot: entryIndex = this.expandEntry( entryIndex, entryPointerIndex, slotNumber, slotMask, nextLevelIsLeaf ); } // Next level's entry pointer index is in the appropriate slot in in the entries array in this entry: entryPointerIndex = entryIndex + NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + slotNumber; entryIndex = this.getIndexAtShortIndex(entryPointerIndex); } // entryIndex is the long-index of a leaf entry that contains the value byte for the given set const byteIndex = (entryIndex << 3) + (virtualIndex & 0x7); // Determine byte index offset within leaf entry return byteIndex; } determineTopLevelShiftForVirtualLength(virtualLength: number) { const sizeMagnitude = ceil(log2(virtualLength)); const eightsSizeMagnitude = sizeMagnitude - 3; let multipleOfFourSizeMagnitude = ceil(eightsSizeMagnitude / 4) * 4; multipleOfFourSizeMagnitude = max(multipleOfFourSizeMagnitude, 8); const topLevelShiftNeeded = multipleOfFourSizeMagnitude - 4 + 3; return topLevelShiftNeeded; } setVirtualLength(virtualLength: number) { if (!this.isPacked) { throw new Error( "Should never be adjusting the virtual size of a non-packed context" ); } this.topLevelShift = this.determineTopLevelShiftForVirtualLength( virtualLength ); this.virtualLength = virtualLength; } getTopLevelShift() { return this.topLevelShift; } // // ## ## ######## ####### ######## ## ## ## ### ######## ######## // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## // ### ####### ######## ## ## ######## ## ## ## ## ## ## ###### // ## ## ## ## ## ## ## ## ## ######### ## ## // ## ## ## ## ## ## ## ## ## ## ## ## ## // ## ## ## ####### ## ####### ######## ## ## ## ######## // public resizeArray(newLength: number) { const tmp = new Uint8Array(newLength * 8); tmp.set(this.byteArray); this.array = tmp.buffer; this.initArrayViews(this.array); this.physicalLength = newLength; } private populateEquivalentEntriesWithEntriesFromOther( other: PackedArrayContext ) { if (this.virtualLength < other.getVirtualLength()) { throw new Error("Cannot populate array of smaller virtual length"); } for (let i = 0; i < NUMBER_OF_SETS; i++) { const otherEntryIndex = other.getAtShortIndex(SET_0_START_INDEX + i); if (otherEntryIndex == 0) continue; // No tree to duplicate let entryIndexPointer = SET_0_START_INDEX + i; for (let i = this.topLevelShift; i > other.topLevelShift; i -= 4) { // for each inserted level: // Allocate entry in other: const sizeOfEntry = NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + 1; const newEntryIndex = this.newEntry(sizeOfEntry); // Link new level in. this.setAtShortIndex(entryIndexPointer, newEntryIndex); // Populate new level entry, use pointer to slot 0 as place to populate under: this.setPackedSlotIndicators(newEntryIndex, 0x1); // Slot 0 populated entryIndexPointer = newEntryIndex + NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS; // Where the slot 0 index goes. } this.copyEntriesAtLevelFromOther( other, otherEntryIndex, entryIndexPointer, other.topLevelShift ); } } private copyEntriesAtLevelFromOther( other: PackedArrayContext, otherLevelEntryIndex: number, levelEntryIndexPointer: number, otherIndexShift: number ) { const nextLevelIsLeaf = otherIndexShift == LEAF_LEVEL_SHIFT; const packedSlotIndicators = other.getPackedSlotIndicators( otherLevelEntryIndex ); const numberOfSlots = bitCount(packedSlotIndicators); const sizeOfEntry = NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + numberOfSlots; const entryIndex = this.newEntry(sizeOfEntry); this.setAtShortIndex(levelEntryIndexPointer, entryIndex); this.setAtShortIndex( entryIndex + NON_LEAF_ENTRY_SLOT_INDICATORS_OFFSET, packedSlotIndicators ); for (let i = 0; i < numberOfSlots; i++) { if (nextLevelIsLeaf) { // Make leaf in other: const leafEntryIndex = this.newLeafEntry(); this.setIndexAtEntrySlot(entryIndex, i, leafEntryIndex); // OPTIM // avoid iteration on all the values of the source ctx const otherNextLevelEntryIndex = other.getIndexAtEntrySlot( otherLevelEntryIndex, i ); this.longArray[leafEntryIndex] = other.longArray[otherNextLevelEntryIndex]; } else { const otherNextLevelEntryIndex = other.getIndexAtEntrySlot( otherLevelEntryIndex, i ); this.copyEntriesAtLevelFromOther( other, otherNextLevelEntryIndex, entryIndex + NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + i, otherIndexShift - 4 ); } } } getAtUnpackedIndex(index: number) { return this.longArray[index]; } setAtUnpackedIndex(index: number, newValue: number) { this.longArray[index] = newValue; } lazysetAtUnpackedIndex(index: number, newValue: number) { this.longArray[index] = newValue; } incrementAndGetAtUnpackedIndex(index: number) { this.longArray[index]++; return this.longArray[index]; } addAndGetAtUnpackedIndex(index: number, valueToAdd: number) { this.longArray[index] += valueToAdd; return this.longArray[index]; } // // ######## ####### ###### ######## ######## #### ## ## ###### // ## ## ## ## ## ## ## ## ## ### ## ## ## // ## ## ## ## ## ## ## ## #### ## ## // ## ## ## ####### ###### ## ######## ## ## ## ## ## #### // ## ## ## ## ## ## ## ## ## #### ## ## // ## ## ## ## ## ## ## ## ## ## ### ## ## // ## ####### ###### ## ## ## #### ## ## ###### // private nonLeafEntryToString( entryIndex: number, indexShift: number, indentLevel: number ) { let output = ""; for (let i = 0; i < indentLevel; i++) { output += " "; } try { const packedSlotIndicators = this.getPackedSlotIndicators(entryIndex); output += `slotIndiators: 0x${toHex( packedSlotIndicators )}, prevVersionIndex: 0: [ `; const numberOfslotsInEntry = bitCount(packedSlotIndicators); for (let i = 0; i < numberOfslotsInEntry; i++) { output += this.getIndexAtEntrySlot(entryIndex, i); if (i < numberOfslotsInEntry - 1) { output += ", "; } } output += ` ] (indexShift = ${indexShift})\n`; const nextLevelIsLeaf = indexShift == LEAF_LEVEL_SHIFT; for (let i = 0; i < numberOfslotsInEntry; i++) { const nextLevelEntryIndex = this.getIndexAtEntrySlot(entryIndex, i); if (nextLevelIsLeaf) { output += this.leafEntryToString( nextLevelEntryIndex, indentLevel + 4 ); } else { output += this.nonLeafEntryToString( nextLevelEntryIndex, indexShift - 4, indentLevel + 4 ); } } } catch (ex) { output += `Exception thrown at nonLeafEnty at index ${entryIndex} with indexShift ${indexShift}\n`; } return output; } private leafEntryToString(entryIndex: number, indentLevel: number) { let output = ""; for (let i = 0; i < indentLevel; i++) { output += " "; } try { output += "Leaf bytes : "; for (let i = 0; i < 8; i++) { output += `0x${toHex(this.byteArray[entryIndex * 8 + i])} `; } output += "\n"; } catch (ex) { output += `Exception thrown at leafEnty at index ${entryIndex}\n`; } return output; } public toString() { let output = "PackedArrayContext:\n"; if (!this.isPacked) { return output + "Context is unpacked:\n"; // unpackedToString(); } for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { try { const entryPointerIndex = SET_0_START_INDEX + setNumber; const entryIndex = this.getIndexAtShortIndex(entryPointerIndex); output += `Set ${setNumber}: root = ${entryIndex} \n`; if (entryIndex == 0) continue; output += this.nonLeafEntryToString(entryIndex, this.topLevelShift, 4); } catch (ex) { output += `Exception thrown in set ${setNumber}%d\n`; } } //output += recordedValuesToString(); return output; } } const toHex = (n: number) => { return Number(n) .toString(16) .padStart(2, "0"); };
the_stack
import * as React from 'react'; import { Card, Button, Form, Icon, Col, Row, DatePicker, TimePicker, Input, Select, Popover, } from 'antd'; import FooterToolbar from '../../components/FooterToolbar'; import PageHeaderLayout from '../../components/PageHeaderLayout'; import TableForm from './TableForm'; import './style.less'; const { Option } = Select; const { RangePicker } = DatePicker; const fieldLabels = { name: '仓库名', url: '仓库域名', owner: '仓库管理员', approver: '审批人', dateRange: '生效日期', type: '仓库类型', name2: '任务名', url2: '任务描述', owner2: '执行人', approver2: '责任人', dateRange2: '生效日期', type2: '任务类型', }; const tableData = [ { key: '1', workId: '00001', name: 'John Brown', department: 'New York No. 1 Lake Park', }, { key: '2', workId: '00002', name: 'Jim Green', department: 'London No. 1 Lake Park', }, { key: '3', workId: '00003', name: 'Joe Black', department: 'Sidney No. 1 Lake Park', }, ]; class AdvancedForm extends React.Component<{form:any, submitting: boolean}, {width: string}> { constructor(props) { super(props) this.state={ width: '100%', } } public componentDidMount() { window.addEventListener('resize', this.resizeFooterToolbar); } public componentWillUnmount() { window.removeEventListener('resize', this.resizeFooterToolbar); } private resizeFooterToolbar = () => { const siders = document.querySelectorAll('.ant-layout-sider') as NodeListOf<HTMLElement>; const width = `calc(100% - ${siders[0].style.width})`; if (this.state.width !== width) { this.setState({ width }); } }; public render() { const { form, submitting } = this.props; const { getFieldDecorator, validateFieldsAndScroll, getFieldsError } = form; const validate = () => { validateFieldsAndScroll((error, values) => { if (!error) { // submit the values // dispatch({ // type: 'form/submitAdvancedForm', // payload: values, // }); } }); }; const errors = getFieldsError(); const getErrorInfo = () => { const errorCount = Object.keys(errors).filter(key => errors[key]).length; if (!errors || errorCount === 0) { return null; } const scrollToField = fieldKey => { const labelNode = document.querySelector(`label[for="${fieldKey}"]`); if (labelNode) { labelNode.scrollIntoView(true); } }; const errorList = Object.keys(errors).map(key => { if (!errors[key]) { return null; } return ( <li key={key} className={'errorListItem'} onClick={() => scrollToField(key)}> <Icon type="cross-circle-o" className={'errorIcon'} /> <div className={'errorMessage'}>{errors[key][0]}</div> <div className={'errorField'}>{fieldLabels[key]}</div> </li> ); }); return ( <span className={'errorIcon'}> <Popover title="表单校验信息" content={errorList} overlayClassName={'errorPopover'} trigger="click" getPopupContainer={(trigger) => trigger.parentNode as HTMLElement} > <Icon type="exclamation-circle" /> </Popover> {errorCount} </span> ); }; return ( <PageHeaderLayout title="高级表单" content="高级表单常见于一次性输入和提交大批量数据的场景。" wrapperClassName={'advancedForm'} > <Card title="仓库管理" className={'card'} bordered={false}> <Form layout="vertical" hideRequiredMark={true}> <Row gutter={16}> <Col lg={6} md={12} sm={24}> <Form.Item label={fieldLabels.name}> {getFieldDecorator('name', { rules: [{ required: true, message: '请输入仓库名称' }], })(<Input placeholder="请输入仓库名称" />)} </Form.Item> </Col> <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}> <Form.Item label={fieldLabels.url}> {getFieldDecorator('url', { rules: [{ required: true, message: '请选择' }], })( <Input style={{ width: '100%' }} addonBefore="http://" addonAfter=".com" placeholder="请输入" /> )} </Form.Item> </Col> <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}> <Form.Item label={fieldLabels.owner}> {getFieldDecorator('owner', { rules: [{ required: true, message: '请选择管理员' }], })( <Select placeholder="请选择管理员"> <Option value="xiao">付晓晓</Option> <Option value="mao">周毛毛</Option> </Select> )} </Form.Item> </Col> </Row> <Row gutter={16}> <Col lg={6} md={12} sm={24}> <Form.Item label={fieldLabels.approver}> {getFieldDecorator('approver', { rules: [{ required: true, message: '请选择审批员' }], })( <Select placeholder="请选择审批员"> <Option value="xiao">付晓晓</Option> <Option value="mao">周毛毛</Option> </Select> )} </Form.Item> </Col> <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}> <Form.Item label={fieldLabels.dateRange}> {getFieldDecorator('dateRange', { rules: [{ required: true, message: '请选择生效日期' }], })( <RangePicker placeholder={['开始日期', '结束日期']} style={{ width: '100%' }} /> )} </Form.Item> </Col> <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}> <Form.Item label={fieldLabels.type}> {getFieldDecorator('type', { rules: [{ required: true, message: '请选择仓库类型' }], })( <Select placeholder="请选择仓库类型"> <Option value="private">私密</Option> <Option value="public">公开</Option> </Select> )} </Form.Item> </Col> </Row> </Form> </Card> <Card title="任务管理" className={'card'} bordered={false}> <Form layout="vertical" hideRequiredMark={true}> <Row gutter={16}> <Col lg={6} md={12} sm={24}> <Form.Item label={fieldLabels.name2}> {getFieldDecorator('name2', { rules: [{ required: true, message: '请输入' }], })(<Input placeholder="请输入" />)} </Form.Item> </Col> <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}> <Form.Item label={fieldLabels.url2}> {getFieldDecorator('url2', { rules: [{ required: true, message: '请选择' }], })(<Input placeholder="请输入" />)} </Form.Item> </Col> <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}> <Form.Item label={fieldLabels.owner2}> {getFieldDecorator('owner2', { rules: [{ required: true, message: '请选择管理员' }], })( <Select placeholder="请选择管理员"> <Option value="xiao">付晓晓</Option> <Option value="mao">周毛毛</Option> </Select> )} </Form.Item> </Col> </Row> <Row gutter={16}> <Col lg={6} md={12} sm={24}> <Form.Item label={fieldLabels.approver2}> {getFieldDecorator('approver2', { rules: [{ required: true, message: '请选择审批员' }], })( <Select placeholder="请选择审批员"> <Option value="xiao">付晓晓</Option> <Option value="mao">周毛毛</Option> </Select> )} </Form.Item> </Col> <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}> <Form.Item label={fieldLabels.dateRange2}> {getFieldDecorator('dateRange2', { rules: [{ required: true, message: '请输入' }], })( <TimePicker placeholder="提醒时间" style={{ width: '100%' }} getPopupContainer={trigger => trigger.parentNode as HTMLElement} /> )} </Form.Item> </Col> <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}> <Form.Item label={fieldLabels.type2}> {getFieldDecorator('type2', { rules: [{ required: true, message: '请选择仓库类型' }], })( <Select placeholder="请选择仓库类型"> <Option value="private">私密</Option> <Option value="public">公开</Option> </Select> )} </Form.Item> </Col> </Row> </Form> </Card> <Card title="成员管理" bordered={false}> {getFieldDecorator('members', { initialValue: tableData, })(<TableForm />)} </Card> <FooterToolbar style={{ width: this.state.width }}> {getErrorInfo()} <Button type="primary" onClick={validate} loading={submitting}> 提交 </Button> </FooterToolbar> </PageHeaderLayout> ); } } // export default connect(({ global, loading }) => ({ // collapsed: global.collapsed, // submitting: loading.effects['form/submitAdvancedForm'], // }))(Form.create()(AdvancedForm)); export default Form.create()(AdvancedForm);
the_stack
"use strict"; import { SocketCallbackHandler } from "../../common/comms/socketCallbackHandler"; import { Commands, ResponseCommands } from "./commands"; import { SocketServer } from '../../common/comms/socketServer'; import { IdDispenser } from '../../common/idDispenser'; import { createDeferred, Deferred } from '../../common/helpers'; import { KernelCommand } from './contracts'; import { JupyterMessage, ParsedIOMessage } from '../contracts'; import { Helpers } from '../common/helpers'; import * as Rx from 'rx'; import { KernelRestartedError, KernelShutdownError } from '../common/errors'; import { OutputChannel } from 'vscode'; import { Kernel, KernelMessage } from '@jupyterlab/services'; export class JupyterSocketClient extends SocketCallbackHandler { private isDebugging: boolean; constructor(socketServer: SocketServer, private outputChannel: OutputChannel) { super(socketServer); this.isDebugging = process.env['DEBUG_DJAYAMANNE_IPYTHON'] === '1'; this.registerCommandHandler(ResponseCommands.Pong, this.onPong.bind(this)); this.registerCommandHandler(ResponseCommands.ListKernelsSpecs, this.onKernelsListed.bind(this)); this.registerCommandHandler(ResponseCommands.Error, this.onError.bind(this)); this.registerCommandHandler(ResponseCommands.KernelStarted, this.onKernelStarted.bind(this)); this.registerCommandHandler(ResponseCommands.KernelInterrupted, this.onKernelCommandComplete.bind(this)); this.registerCommandHandler(ResponseCommands.KernelRestarted, this.onKernelCommandComplete.bind(this)); this.registerCommandHandler(ResponseCommands.KernelShutdown, this.onKernelCommandComplete.bind(this)); this.registerCommandHandler(ResponseCommands.RunCode, this.onCodeSentForExecution.bind(this)); this.registerCommandHandler(ResponseCommands.ShellResult, this.onShellResult.bind(this)); this.registerCommandHandler(ResponseCommands.IOPUBMessage, this.onIOPUBMessage.bind(this)); this.idDispenser = new IdDispenser(); } private idDispenser: IdDispenser; private pid: number; private guid: string; private writeToDebugLog(message: string) { if (!this.isDebugging) { return; } this.outputChannel.appendLine(message); } public dispose() { super.dispose(); } protected handleHandshake(): boolean { if (typeof this.guid !== 'string') { this.guid = this.stream.readStringInTransaction(); if (typeof this.guid !== 'string') { return false; } } if (typeof this.pid !== 'number') { this.pid = this.stream.readInt32InTransaction(); if (typeof this.pid !== 'number') { return false; } } this.emit('handshake'); return true; } private pendingCommands = new Map<string, Deferred<any>>(); private createId<T>(): [Deferred<T>, string] { const def = createDeferred<T>(); const id = this.idDispenser.Allocate().toString(); this.pendingCommands.set(id, def); return [def, id]; } private releaseId(id: string) { this.pendingCommands.delete(id); this.idDispenser.Free(parseInt(id)); } public listKernelSpecs(): Promise<any> { const [def, id] = this.createId<any>(); this.SendRawCommand(Commands.ListKernelSpecsBytes); this.stream.WriteString(id); return def.promise; } private onKernelsListed() { const id = this.stream.readStringInTransaction(); const kernels = this.stream.readStringInTransaction(); if (typeof kernels !== 'string') { return; } const def = this.pendingCommands.get(id); this.releaseId(id); let kernelList: any; try { kernelList = JSON.parse(kernels); } catch (ex) { def.reject(ex); return; } def.resolve(kernelList); } public startKernel(kernelName: string): Promise<[string, any, string]> { const [def, id] = this.createId<any>(); this.SendRawCommand(Commands.StartKernelBytes); this.stream.WriteString(id); this.stream.WriteString(kernelName); return def.promise; } private onKernelStarted() { const id = this.stream.readStringInTransaction(); const kernelUUID = this.stream.readStringInTransaction(); const configStr = this.stream.readStringInTransaction(); const connectionFile = this.stream.readStringInTransaction(); if (typeof connectionFile !== 'string') { return; } const def = this.pendingCommands.get(id); let config = {}; try { config = JSON.parse(configStr); } catch (ex) { def.reject(ex); return; } this.releaseId(id); def.resolve([kernelUUID, config, connectionFile]); } public sendKernelCommand(kernelUUID: string, command: KernelCommand): Promise<any> { const [def, id] = this.createId<any>(); let commandBytes: Buffer; let error; switch (command) { case KernelCommand.interrupt: { commandBytes = Commands.InterruptKernelBytes; break; } case KernelCommand.restart: { commandBytes = Commands.RestartKernelBytes; error = new KernelRestartedError(); break; } case KernelCommand.shutdown: { commandBytes = Commands.ShutdownKernelBytes; error = new KernelShutdownError(); break; } default: { throw new Error('Unrecognized Kernel Command'); } } this.SendRawCommand(commandBytes); this.stream.WriteString(id); this.stream.WriteString(kernelUUID); if (error) { // Throw errors for pending commands this.pendingCommands.forEach((pendingDef, key) => { if (id !== key) { this.pendingCommands.delete(id); pendingDef.reject(error); } }); this.msgSubject.forEach((subject, key) => { subject.onError(error); }); this.msgSubject.clear(); this.unhandledMessages.clear(); this.finalMessage.clear(); } return def.promise; } private onKernelCommandComplete() { const id = this.stream.readStringInTransaction(); if (typeof id !== 'string') { return; } const def = this.pendingCommands.get(id); this.releaseId(id); def.resolve(); } public ping(message: string) { const [def, id] = this.createId<string>(); this.SendRawCommand(Commands.PingBytes); this.stream.WriteString(id); this.stream.WriteString(message); return def.promise; } private onPong() { const id = this.stream.readStringInTransaction(); const message = this.stream.readStringInTransaction(); if (typeof message !== 'string') { return; } const def = this.pendingCommands.get(id); this.releaseId(id); def.resolve(message); } private msgSubject = new Map<string, Rx.Subject<ParsedIOMessage>>(); private msgSubjectIndexedWithRunId = new Map<string, Rx.Subject<ParsedIOMessage>>(); private unhandledMessages = new Map<string, ParsedIOMessage[]>(); private finalMessage = new Map<string, { shellMessage?: ParsedIOMessage, ioStatusSent: boolean }>(); runCode(code: string): Rx.IObservable<ParsedIOMessage> { const [def, id] = this.createId<string>(); const observable = new Rx.Subject<ParsedIOMessage>(); this.msgSubjectIndexedWithRunId.set(id, observable); this.writeToDebugLog(`Send Code with Id = ${id}`); this.SendRawCommand(Commands.RunCodeBytes); this.stream.WriteString(id); this.stream.WriteString(code); def.promise.then(msg_id => { // Do nothing, code moved to // onCodeSentForExecution (so we have synchronous processing) }).catch(reason => { observable.onError(reason); }); return observable; } private onCodeSentForExecution() { const id = this.stream.readStringInTransaction(); const msg_id = this.stream.readStringInTransaction(); if (typeof msg_id !== 'string') { return; } this.writeToDebugLog(`Code with Id = ${id} has msg_id = ${msg_id}`); const def = this.pendingCommands.get(id); this.releaseId(id); def.resolve(msg_id); const observable = this.msgSubjectIndexedWithRunId.get(id); this.msgSubjectIndexedWithRunId.delete(id); this.msgSubject.set(msg_id, observable); } private onShellResult() { const jsonResult = this.stream.readStringInTransaction(); if (typeof jsonResult !== 'string') { return; } try { const message = JSON.parse(jsonResult) as KernelMessage.IMessage; if (!Helpers.isValidMessag(message)) { return; } const msg_type = message.header.msg_type; if (msg_type === 'status') { this.writeToDebugLog(`Kernel Status = ${message.content.execution_state}`); this.emit('status', message.content.execution_state); } const msg_id = (message.parent_header as KernelMessage.IHeader).msg_id; if (!msg_id) { return; } const status = message.content.status; let parsedMesage: ParsedIOMessage; switch (status) { case 'abort': case 'aborted': case 'error': { // http://jupyter-client.readthedocs.io/en/latest/messaging.html#request-reply if (msg_type !== 'complete_reply' && msg_type !== 'inspect_reply') { parsedMesage = { data: 'error', type: 'text', stream: 'status' }; } break; } case 'ok': { // http://jupyter-client.readthedocs.io/en/latest/messaging.html#request-reply if (msg_type !== 'complete_reply' && msg_type !== 'inspect_reply') { parsedMesage = { data: 'ok', type: 'text', stream: 'status' }; } } } this.writeToDebugLog(`Shell Result with msg_id = ${msg_id} with status = ${status}`); if (!parsedMesage) { this.writeToDebugLog(`Shell Result with msg_id = ${msg_id} with status = ${status} ignored`); return; } this.writeToDebugLog(`Shell Result with msg_id = ${msg_id} has message of: '\n${jsonResult}`); if (this.finalMessage.has(msg_id) && this.msgSubject.has(msg_id)) { const subject = this.msgSubject.get(msg_id); const info = this.finalMessage.get(msg_id); this.writeToDebugLog(`Shell Result with msg_id = ${msg_id} found in finalMessage and msgSubject`); // If th io message with status='idle' has been received, that means message execution is deemed complete if (info.ioStatusSent) { this.writeToDebugLog(`Shell Result with msg_id = ${msg_id} found in finalMessage and msgSubject, and ioStatusSent = true`); this.finalMessage.delete(msg_id); this.msgSubject.delete(msg_id); subject.onNext(parsedMesage); subject.onCompleted(); } else { this.writeToDebugLog(`Shell Result with msg_id = ${msg_id} found in finalMessage and msgSubject, and ioStatusSent = false`); } } else { this.writeToDebugLog(`Shell Result with msg_id = ${msg_id} not found in finalMessage or not found in msgSubject`); // Wait for the io message with status='idle' to arrive const info = this.finalMessage.has(msg_id) ? this.finalMessage.get(msg_id) : { ioStatusSent: false }; info.shellMessage = parsedMesage; this.finalMessage.set(msg_id, info); } } catch (ex) { this.emit('shellmessagepareerror', ex, jsonResult); } } private onIOPUBMessage() { const jsonResult = this.stream.readStringInTransaction(); if (typeof jsonResult !== 'string') { return; } try { const message = JSON.parse(jsonResult) as KernelMessage.IIOPubMessage; if (!Helpers.isValidMessag(message)) { return; } const msg_type = message.header.msg_type; if (msg_type === 'status') { this.writeToDebugLog(`io Kernel Status = ${message.content.execution_state}`); this.emit('status', message.content.execution_state); } const msg_id = (message.parent_header as KernelMessage.IHeader).msg_id; if (!msg_id) { return; } this.writeToDebugLog(`iopub with msg_id = ${msg_id}`); // Ok, if we have received a status of 'idle' this means the execution has completed if (msg_type === 'status' && message.content.execution_state === 'idle') { this.writeToDebugLog(`iopub with msg_id = ${msg_id} and msg_type == status and execution_state == idle`); let timesWaited = 0; const waitForFinalIOMessage = () => { timesWaited += 1; // The Shell message handler has processed the message if (!this.msgSubject.has(msg_id)) { this.writeToDebugLog(`iopub with msg_id = ${msg_id} and msg_type == status and execution_state == idle, not yet in msgSubject`); return; } // Last message sent on shell channel (status='ok' or status='error') // and now we have a status message, this means the exection is deemed complete if (this.finalMessage.has(msg_id)) { this.writeToDebugLog(`iopub with msg_id = ${msg_id} and msg_type == status and execution_state == idle, found in finalMessage`); const subject = this.msgSubject.get(msg_id); const info = this.finalMessage.get(msg_id); if (!info.shellMessage && timesWaited < 10) { this.writeToDebugLog(`iopub with msg_id = ${msg_id} and msg_type == status and execution_state == idle, found in finalMessage and info.shellMessage = ` + typeof (info.shellMessage)); this.writeToDebugLog(`iopub with msg_id = ${msg_id} and msg_type == status and execution_state == idle, found in finalMessage and timesWaited = ` + timesWaited.toString()); setTimeout(() => { waitForFinalIOMessage(); }, 10); return; } this.finalMessage.delete(msg_id); this.msgSubject.delete(msg_id); this.writeToDebugLog(`iopub with msg_id = ${msg_id} and msg_type == status and execution_state == idle almost done`); if (info.shellMessage) { this.writeToDebugLog(`iopub with msg_id = ${msg_id} and msg_type == status and execution_state == idle, and shell message being sent out`); subject.onNext(info.shellMessage); } this.writeToDebugLog(`iopub with msg_id = ${msg_id} and msg_type == status and execution_state == idle, done`); subject.onCompleted(); } else { this.writeToDebugLog(`iopub with msg_id = ${msg_id} and msg_type == status and execution_state == idle, inserted into finalMessage`); this.finalMessage.set(msg_id, { ioStatusSent: true }); } }; // Wait for the shell message to come through setTimeout(() => { waitForFinalIOMessage(); }, 10); } const parsedMesage = Helpers.parseIOMessage(message); if (!parsedMesage) { return; } if (this.msgSubject.has(msg_id)) { this.writeToDebugLog(`iopub with msg_id = ${msg_id} found in msgSubject`); this.msgSubject.get(msg_id).onNext(parsedMesage); } else { this.writeToDebugLog(`iopub with msg_id = ${msg_id} not found in msgSubject and inserted into unhandledMessages`); let data = []; if (this.unhandledMessages.has(msg_id)) { data = this.unhandledMessages.get(msg_id); } data.push(parsedMesage); this.unhandledMessages.set(msg_id, data); return; } } catch (ex) { this.emit('iopubmessagepareerror', ex, jsonResult); } } private onError() { const cmd = this.stream.readStringInTransaction(); const id = this.stream.readStringInTransaction(); const trace = this.stream.readStringInTransaction(); if (typeof trace !== 'string') { return; } if (cmd === 'exit') { return; } if (id.length > 0 && this.pendingCommands.has(id)) { const def = this.pendingCommands.get(id); this.pendingCommands.delete(id); def.reject(new Error(`Command: ${cmd}, Id: ${id}, Python Trace: ${trace}`)); return; } this.emit("commanderror", { command: cmd, id: id, trace: trace }); } }
the_stack
import { connect } from '@tarojs/redux'; import Taro, { Component } from '@tarojs/taro' import { View, Text, ScrollView, Image, Checkbox, CheckboxGroup } from '@tarojs/components' import { AtInputNumber } from 'taro-ui' import shoppingScan from '../../img/shoppingScan.png' import { invitedUsers, singleItem } from '../home/service' import { userInfo } from "../orderDetails/service" import './index.less' @connect(({ common }) => ({ common })) export default class Buy extends Component<any>{ //点击修改加减数量 handleNumberChange(itemId, number) { this.setState({ discount: 0, activiId: 0, }) const { dispatch } = this.props; dispatch({ type: 'common/changeCartItemNumer', payload: { itemId, number } }); } config = { navigationBarTitleText: '购物车' } state = { editable: false, modal: 'none', discount: 0, couponId: '', cartChecked: true, deleteItem: [], userMsg: [], } async componentWillMount() { const { cartItems } = this.props.common; console.log('shoppingCart cartItems', cartItems); const userResult = await userInfo(); const { deleteItem } = this.state; for (const iterator of cartItems) { if (iterator.checked) { deleteItem.push(iterator); } } this.setState({ deleteItem, userMsg: userResult.data.userInfo, }) } //下拉刷新 async onPullDownRefresh() { const { cartItems } = this.props.common; console.log('shoppingCart cartItems', cartItems); const userResult = await userInfo(); const { deleteItem } = this.state; for (const iterator of cartItems) { if (iterator.checked) { deleteItem.push(iterator); } } this.setState({ deleteItem, userMsg: userResult.data.userInfo, }) } //点击编辑与完成 editor() { const { editable } = this.state; this.setState({ editable: !editable }); } choose(activiId, amount, require, totalPrice) { if (totalPrice >= require) { this.setState({ discount: amount, couponId: activiId }) } else { this.setState({ discount: 0, couponId: '' }) } this.setState({ activiId, }) } open() { this.setState({ modal: 'block' }) } prompt() { Taro.showToast({ title: '敬请期待', icon: 'none' }) } //跳转确认订单 async handlePay() { const token = Taro.getStorageSync('accessToken'); if (token) { // Taro.hideTabBarRedDot({ // index: 2 // }) // Taro.setTabBarBadge({ // index: 2, // text: '18', // }) Taro.navigateTo({ url: "../orderDetails/index" }); } else { Taro.switchTab({ url: "../mine/index" }); } } onCheckboxGroupChange(e) { this.setState({ discount: 0, activiId: 0, }) const { dispatch } = this.props; dispatch({ type: 'common/changeCartItemsChecked', payload: e.detail.value }) } deleteCart(deleteItem) { const { dispatch } = this.props; dispatch({ type: 'common/delete', payload: deleteItem }) Taro.showToast({ title: '删除完成', icon: 'succes', duration: 1000, }); } changeCheck() { const { dispatch } = this.props; const { cartChecked } = this.state; dispatch({ type: 'common/changeAllCheckedCartItems', payload: cartChecked }) this.setState({ cartChecked: !cartChecked }) } // 扫码加入购物车 async lookForward() { const { dispatch } = this.props; const { result } = await Taro.scanCode(); console.log('扫码result', result); const obj = JSON.parse(result); if (obj.userId) { console.log('扫码邀请'); await invitedUsers(obj.userId); } else { console.log('扫码加购'); const itemResult = await singleItem(result); console.log('扫码加入购物车itemResult', itemResult); const data: any = {}; data.itemId = itemResult.data.item.code; data.name = itemResult.data.item.name; data.number = 1; data.price = itemResult.data.item.price; data.unit = itemResult.data.item.unit; data.imageUrl = itemResult.data.item.imageUrl; data.pointDiscountPrice = itemResult.data.item.pointDiscountPrice; data.originalPrice = itemResult.data.item.originalPrice; data.memberPrice = itemResult.data.item.memberPrice; await dispatch({ type: 'common/addToCartByCode', payload: data }); } } // } render() { const { cartItems } = this.props.common; const { userMsg } = this.state; console.log('render cartItems', cartItems); // 购物车右上角图标 if (cartItems.length === 0) { // Taro.hideTabBarRedDot({ // index: 2 // }) Taro.removeTabBarBadge({ index: 2 }) }else{ let sum = 0; let i; for( i in cartItems){ if(cartItems[i].checked){ sum += parseInt(cartItems[i].number); } } Taro.setTabBarBadge({ index: 2, text: "" + sum + "" , }) } const { couponId, deleteItem } = this.state; const check = cartItems.every(item => item.checked === true); const totalPrice = {}; if (userMsg.role === 'member') { const total = cartItems.reduce((total, currentValue) => { if (currentValue.checked) { return total + (currentValue.memberPrice * currentValue.number); } return total; }, 0) totalPrice.total = total; }else{ const total = cartItems.reduce((total, currentValue) => { if (currentValue.checked) { return total + (currentValue.price * currentValue.number); } return total; }, 0) totalPrice.total = total; } const { editable } = this.state; return ( <ScrollView className='buy'> {cartItems.length > 0 ? ( <View> <View className='topLine'> <Text className='total'>共计{cartItems.length}件商品</Text> <View className='editor' onClick={this.editor}> <Text className='total'>{editable ? '完成' : '管理'}</Text> </View> </View> {/*中间商品*/} <View className='page-body'> <CheckboxGroup onChange={this.onCheckboxGroupChange}> <View className='quanbu'> {cartItems.map((item) => ( <View key={item.itemId} className='Framework'> {/*按钮*/} <Checkbox value={item.itemId} checked={item.checked}></Checkbox> {/*按钮右边的图片文字等*/} <View className='framework'> {/*物品图片*/} <Image src={item.imageUrl} className='goodsOne' /> <View className='frame'> {/*物品名称*/} <Text className='name'>{item.name}</Text> <View className='work'> {/*价格*/} <View style="display:flex;flex-direction:column;"> <Text className='memberPrice'>¥{(item.memberPrice / 100).toFixed(2)}/{item.unit}</Text> <Text className='price'>¥{(item.price / 100).toFixed(2)}/{item.unit}</Text> <Text className='originalPrice'>¥{(item.originalPrice / 100).toFixed(2)}/{item.unit}</Text> </View> {/*数量选择*/} <AtInputNumber min={1} max={99} step={1} width={100} value={item.number} onChange={this.handleNumberChange.bind(this, item.itemId)} style="margin-top:4PX;" /> </View> {/*价格小计*/} <View className='xj'> <Text className='xiaoj'>小计:</Text> { userMsg.role === 'member'?( <Text className='ji'>¥{(item.memberPrice * item.number) / 100}/{item.unit}</Text> ):( <Text className='ji'>¥{(item.price * item.number) / 100}/{item.unit}</Text> ) } </View> </View> </View> </View> ))} </View> </CheckboxGroup> {cartItems.length !== 0 ? (<View className='boTo'> <View className='qx'> <Checkbox value='all' checked={check} onClick={this.changeCheck}>全选</Checkbox> </View> <View className='rightfk'> <View className='YH'> <Text className='yh'>合计:</Text> <Text className='hj'>¥{(totalPrice.total || 0) / 100 - (this.state.discount)}/元</Text> </View> {!editable ? ( <View className='doubleButtonBox'> <View className='fk' onClick={this.handlePay.bind(this, couponId)}> <Text className='payment'>付款</Text> </View> </View> ) : ( <View className='fk' onClick={this.deleteCart.bind(this, deleteItem)}> <Text className='delete'>删除</Text> </View> )} </View> </View>) : ''} </View> </View> ) : ( <View className="nullBox"> {/* <Image src='https://mengmao-qingying-files.oss-cn-hangzhou.aliyuncs.com/takenGoods.png' className="empty" /> */} <Text className="orederNullText">购物车暂无商品</Text> </View> )} <View className='shoppingScan' onClick={this.lookForward}> <Image src={shoppingScan} /> <Text className='shoppingScanTxt1'>扫一扫</Text> <Text className='shoppingScanTxt2'>商品条形码</Text> </View> </ScrollView> ) } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace LuckyStar { namespace FormLocation { interface Header extends DevKit.Controls.IHeader { devkit_AccountId: DevKit.Controls.Lookup; devkit_ContactId: DevKit.Controls.Lookup; } interface tab_tab1_Sections { tab1sec1: DevKit.Controls.Section; tab1sec2: DevKit.Controls.Section; ref_pan_tab1_section_3: DevKit.Controls.Section; } interface tab_tab2_Sections { tab2sec1: DevKit.Controls.Section; } interface tab_tab3_Sections { tab3sec1: DevKit.Controls.Section; } interface tab_tab1 extends DevKit.Controls.ITab { Section: tab_tab1_Sections; } interface tab_tab2 extends DevKit.Controls.ITab { Section: tab_tab2_Sections; } interface tab_tab3 extends DevKit.Controls.ITab { Section: tab_tab3_Sections; } interface Tabs { tab1: tab_tab1; tab2: tab_tab2; tab3: tab_tab3; } interface Body { Tab: Tabs; WebResource_HelloWorld: DevKit.Controls.WebResource; IFRAME_google: DevKit.Controls.IFrame; timerControl: DevKit.Controls.Timer; notescontrol: DevKit.Controls.Note; /** Date and time when the record was created. */ CreatedOn: DevKit.Controls.DateTime; devkit_AccountId: DevKit.Controls.Lookup; devkit_ContactId: DevKit.Controls.Lookup; devkit_CustomerId: DevKit.Controls.Lookup; devkit_file: DevKit.Controls.File; devkit_image: DevKit.Controls.Image; devkit_Image_URL: DevKit.Controls.String; /** The name of the custom entity. */ devkit_Name: DevKit.Controls.String; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.Controls.Lookup; /** Date and time when the record was modified. */ ModifiedOn: DevKit.Controls.DateTime; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface Footer extends DevKit.Controls.IFooter { /** Date and time when the record was created. */ CreatedOn: DevKit.Controls.DateTime; /** Date and time when the record was modified. */ ModifiedOn: DevKit.Controls.DateTime; /** Status of the Location */ statecode: DevKit.Controls.OptionSet; /** Reason for the status of the Location */ statuscode: DevKit.Controls.OptionSet; } interface Navigation { navAudit: DevKit.Controls.NavigationItem, nav_devkit_devkit_location_account_LocationId: DevKit.Controls.NavigationItem, nav_devkit_devkit_location_contact_LocationId: DevKit.Controls.NavigationItem } interface quickForm_qwAccount_Body { AccountCategoryCode: DevKit.Controls.QuickView; AccountNumber: DevKit.Controls.QuickView; } interface quickForm_quickViewContact_Body { EMailAddress1: DevKit.Controls.QuickView; FirstName: DevKit.Controls.QuickView; LastName: DevKit.Controls.QuickView; MobilePhone: DevKit.Controls.QuickView; ParentCustomerId: DevKit.Controls.QuickView; } interface quickForm_qwAccount extends DevKit.Controls.IQuickView { Body: quickForm_qwAccount_Body; } interface quickForm_quickViewContact extends DevKit.Controls.IQuickView { Body: quickForm_quickViewContact_Body; } interface QuickForm { qwAccount: quickForm_qwAccount; quickViewContact: quickForm_quickViewContact; } interface ProcessBPF_Location_2 { devkit_AccountId: DevKit.Controls.Lookup; devkit_ContactId: DevKit.Controls.Lookup; devkit_CustomerId: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface ProcessBPF_Location_1 { devkit_AccountId: DevKit.Controls.Lookup; devkit_ContactId: DevKit.Controls.Lookup; devkit_CustomerId: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { BPF_Location_2: ProcessBPF_Location_2; BPF_Location_1: ProcessBPF_Location_1; } interface Grid { chartAccount: DevKit.Controls.Grid; panelContact: DevKit.Controls.Grid; panelAccount: DevKit.Controls.Grid; gridAccount: DevKit.Controls.Grid; } } class FormLocation extends DevKit.IForm { /** * DynamicsCrm.DevKit form Location * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Location */ Body: LuckyStar.FormLocation.Body; /** The Footer section of form Location */ Footer: LuckyStar.FormLocation.Footer; /** The Header section of form Location */ Header: LuckyStar.FormLocation.Header; /** The Navigation of form Location */ Navigation: LuckyStar.FormLocation.Navigation; /** The QuickForm of form Location */ QuickForm: LuckyStar.FormLocation.QuickForm; /** The Process of form Location */ Process: LuckyStar.FormLocation.Process; /** The Grid of form Location */ Grid: LuckyStar.FormLocation.Grid; } namespace FormQuick_Create_Location { interface tab_tab_1_Sections { tab1sec1: DevKit.Controls.Section; tab1sec2: DevKit.Controls.Section; tab1sec3: DevKit.Controls.Section; } interface tab_tab_1 extends DevKit.Controls.ITab { Section: tab_tab_1_Sections; } interface Tabs { tab_1: tab_tab_1; } interface Body { Tab: Tabs; devkit_AccountId: DevKit.Controls.Lookup; devkit_ContactId: DevKit.Controls.Lookup; devkit_CustomerId: DevKit.Controls.Lookup; /** The name of the custom entity. */ devkit_Name: DevKit.Controls.String; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Reason for the status of the Location */ statuscode: DevKit.Controls.OptionSet; } } class FormQuick_Create_Location extends DevKit.IForm { /** * DynamicsCrm.DevKit form Quick_Create_Location * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** Provides properties and methods to use Web API to create and manage records and execute Web API actions and functions in Customer Engagement */ WebApi: DevKit.WebApi; /** The Body section of form Quick_Create_Location */ Body: LuckyStar.FormQuick_Create_Location.Body; } class devkit_LocationApi { /** * DynamicsCrm.DevKit devkit_LocationApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; devkit_AccountId: DevKit.WebApi.LookupValue; devkit_ContactId: DevKit.WebApi.LookupValue; devkit_CustomerId_account: DevKit.WebApi.LookupValue; devkit_CustomerId_contact: DevKit.WebApi.LookupValue; devkit_File_Name: DevKit.WebApi.StringValueReadonly; devkit_Image_Timestamp: DevKit.WebApi.BigIntValueReadonly; devkit_Image_URL: DevKit.WebApi.StringValueReadonly; devkit_ImageId: DevKit.WebApi.GuidValueReadonly; /** Unique identifier for entity instances */ devkit_LocationId: DevKit.WebApi.GuidValue; /** The name of the custom entity. */ devkit_Name: DevKit.WebApi.StringValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Contains the id of the process associated with the entity. */ processid: DevKit.WebApi.GuidValue; /** Contains the id of the stage where the entity is located. */ stageid: DevKit.WebApi.GuidValue; /** Status of the Location */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Location */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */ traversedpath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace devkit_Location { enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Location','Quick Create Location'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':false,'Version':'2.10.31','JsFormVersion':'v2'}
the_stack
import * as vscode from "vscode"; import { EventEmitter } from "events"; import { assert } from "console"; function NaN_safe_max(a:number,b:number):number { if (isNaN(a)) { return b; } if (isNaN(b)) { return a; } return Math.max(a,b); } /* profile data total time in all lua modname -> mod data total time in lua state filename -> file data linedefined -> function data timer count line -> line data timer count query for: */ class TimerAndCount { constructor(public readonly timer:number = 0,public readonly count:number = 0) {} public add(other:TimerAndCount|undefined):TimerAndCount { if(!other) { return this; } return new TimerAndCount(this.timer+other.timer, this.count+other.count); } public avg() { return this.timer/this.count; } } class ProfileFileData { functions = new Map<number,TimerAndCount>(); lines = new Map<number,TimerAndCount>(); add(file:ProfileFileData):void { file.functions.forEach((fn,line)=>{ this.functions.set(line,fn.add(this.functions.get(line))); }); file.lines.forEach((ln,line)=>{ this.lines.set(line,ln.add(this.lines.get(line))); }); } max() { const max = { func: {timer:0.0,count:0,average:0.0}, line: {timer:0.0,count:0,average:0.0}, }; this.functions.forEach(fn=>{ max.func.timer = NaN_safe_max(max.func.timer,fn.timer); max.func.count = NaN_safe_max(max.func.count,fn.count); max.func.average = NaN_safe_max(max.func.average,fn.avg()); }); this.lines.forEach(ln=>{ max.line.timer = NaN_safe_max(max.line.timer,ln.timer); max.line.count = NaN_safe_max(max.line.count,ln.count); max.line.average = NaN_safe_max(max.line.average,ln.avg()); }); return max; } } class ProfileModData { totalTime:number = 0; file = new Map<string,ProfileFileData>(); } class ProfileTreeNode { readonly children:ProfileTreeNode[] = []; constructor( public readonly name:string, // modname or file:line public value:number, // time public readonly filename?:string, public readonly line?:number) {} private ToStringInner(pad:string):string { return `${pad}${this.name} : ${this.value}\n${this.children.map(ptn=>ptn.ToStringInner(pad+" ")).join("\n")}`; } ToString():string { return this.ToStringInner(""); } AddToChild(name:string,value:number,filename?:string,line?:number):ProfileTreeNode { let childnode = this.children.find(n=>n.name === name); if (childnode) { childnode.value += value; } else { childnode = new ProfileTreeNode(name,value,filename,line); this.children.push(childnode); } return childnode; } Merge(other:ProfileTreeNode) { this.value += other.value; other.children.forEach(otherchild=>{ const thischild = this.children.find(ptn=>ptn.name === otherchild.name); if (thischild) { thischild.Merge(otherchild); } else { this.children.push(otherchild); } }); } } class ProfileData { private totalTime:number = 0; private readonly mod = new Map<string,ProfileModData>(); private getMod(modname:string) { let mod = this.mod.get(modname); if (!mod) { mod = new ProfileModData(); this.mod.set(modname,mod); } return mod; } private getFile(modname:string,filename:string) { const mod = this.getMod(modname); let file = mod.file.get(filename); if (!file) { file = new ProfileFileData(); mod.file.set(filename,file); } return file; } AddModTime(modname:string,modtime:number) { this.totalTime += modtime; this.getMod(modname).totalTime+=modtime; } AddLineTime(modname:string,filename:string,line:number,time:number,count:number) { const file = this.getFile(modname,filename); const change = new TimerAndCount(time,count); const linedata = file.lines.get(line); file.lines.set(line,change.add(linedata)); } AddFuncTime(modname:string,filename:string,linedefined:number,time:number,count:number) { const file = this.getFile(modname,filename); const change = new TimerAndCount(time,count); const funcdata = file.functions.get(linedefined); file.functions.set(linedefined,change.add(funcdata)); } Report(filename:string) { const filedata = new ProfileFileData(); this.mod.forEach(mod=>{ const file = mod.file.get(filename); if (file) { filedata.add(file); } }); return { totalTime: this.totalTime, fileData: filedata, // line[int] -> count,time // function[int] -> count,time // max -> // line -> count,time // func -> count,time }; } } export class Profile extends EventEmitter implements vscode.Disposable { private readonly profileData = new ProfileData(); private readonly profileTreeRoot = new ProfileTreeNode("root",0); private profileOverhead = new TimerAndCount(0,0); private timeDecorationType: vscode.TextEditorDecorationType; private funcDecorationType: vscode.TextEditorDecorationType; private rulerDecorationTypes: {type:vscode.TextEditorDecorationType;threshold:number}[]; private statusBar: vscode.StatusBarItem; private flamePanel?: vscode.WebviewPanel; constructor(withTree:boolean, private readonly context: vscode.ExtensionContext) { super(); this.timeDecorationType = vscode.window.createTextEditorDecorationType({ before: { contentText:"", color: new vscode.ThemeColor("factorio.ProfileTimerForeground"), } }); this.funcDecorationType = vscode.window.createTextEditorDecorationType({ after: { contentText: "", color: new vscode.ThemeColor("factorio.ProfileFunctionTimerForeground"), borderColor: new vscode.ThemeColor("factorio.ProfileFunctionTimerForeground"), border: "1px solid", margin: "0 0 0 3ch", }, }); const rulers = vscode.workspace.getConfiguration().get<{color?:string;themeColor?:string;threshold:number;lane?:string}[]>("factorio.profile.rulers",[]); this.rulerDecorationTypes = rulers.filter(ruler=>{return ruler.color || ruler.themeColor;}).map(ruler=>{ let lane = vscode.OverviewRulerLane.Right; switch (ruler.lane) { case "Right": lane = vscode.OverviewRulerLane.Right; break; case "Center": lane = vscode.OverviewRulerLane.Center; break; case "Left": lane = vscode.OverviewRulerLane.Left; break; case "Full": lane = vscode.OverviewRulerLane.Full; break; default: break; } return { type: vscode.window.createTextEditorDecorationType({ overviewRulerColor: ruler.color ?? new vscode.ThemeColor(ruler.themeColor!), overviewRulerLane: lane, }), threshold: ruler.threshold }; }); this.statusBar = vscode.window.createStatusBarItem(); if (withTree) { this.createFlamePanel(); } } dispose() { this.timeDecorationType.dispose(); this.funcDecorationType.dispose(); this.rulerDecorationTypes.forEach(ruler=>{ruler.type.dispose();}); this.statusBar.dispose(); if (this.flamePanel){ this.flamePanel.dispose(); } } private async createFlamePanel() { if (this.flamePanel) { return; } this.flamePanel = vscode.window.createWebviewPanel( 'factorioProfile', 'Factorio Profile', vscode.ViewColumn.Two, { enableScripts: true, localResourceRoots: [ this.context.extensionUri ], } ); const flameview = this.flamePanel.webview; flameview.html = (await vscode.workspace.fs.readFile( vscode.Uri.joinPath(this.context.extensionUri,"profile_flamegraph.html"))).toString().replace( /(src|href)="([^"]+)"/g,(_,attr,value)=>{ return `${attr}="${flameview.asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri,value))}"`; } ); flameview.onDidReceiveMessage( (mesg:{command:"init"}|{command:"click";name:string;filename?:string;line?:number})=>{ switch (mesg.command) { case "init": flameview.postMessage({command:"update",data:this.profileTreeRoot}); break; case "click": if(mesg.line && mesg.line > 0) { this.emit("flameclick", mesg); } break; default: break; } }); this.flamePanel.onDidDispose(()=>this.flamePanel=undefined); } public parse(profile:string) { const lines = profile.split("\n"); let currmod:string; let currfile:string; const profileTreeStack = [new ProfileTreeNode("root",0)]; let currnode:ProfileTreeNode|undefined; lines.forEach(line => { const parts = line.split(":"); switch(parts[0]) { case "PROFILE": // nothing break; case "PMN": // PMN:modname:label: time { currmod = parts[1].replace(/[\r\n]*/g,""); const time = parseFloat(parts[3]); this.profileData.AddModTime(currmod,time); } break; case "PFN": // PFN:filename if (currmod) { currfile = parts[1].replace(/[\r\n]*/g,""); } break; case "PLN": // PLN:line:label: time:count if (currmod && currfile) { const line = parseInt(parts[1]); const time = parseFloat(parts[3]); const count = parseInt(parts[4]); this.profileData.AddLineTime(currmod,currfile,line,time,count); } break; case "PFT": // PFT:line:label: time:count if (currmod && currfile) { const line = parseInt(parts[1]); const time = parseFloat(parts[3]); const count = parseInt(parts[4]); this.profileData.AddFuncTime(currmod,currfile,line,time,count); } break; case "POV": //POV:label: time { const time = parseFloat(parts[2]); this.profileOverhead = this.profileOverhead.add(new TimerAndCount(time,1)); } break; case "PROOT": if (currmod) { assert(profileTreeStack.length === 1); currnode = profileTreeStack[0].AddToChild(currmod,0); } break; case "PTREE": // PTREE:funcname:filename:line:label: time if (currnode) { const funcname = parts[1]; const filename = parts[2]; const line = parts[3]; const nodename = funcname + ":" + filename + ":" + line; const time = parseFloat(parts[5]); profileTreeStack.push(currnode); currnode = currnode.AddToChild(nodename,time,filename,parseInt(line)); } break; case "PTEND": if (currnode) { if (profileTreeStack.length === 1){ currnode = undefined; } else { currnode = profileTreeStack.pop(); } } break; } }); assert(profileTreeStack.length === 1); if (this.flamePanel && this.flamePanel.visible) { this.flamePanel.webview.postMessage({command:"merge",data:profileTreeStack[0]}); } this.profileTreeRoot.Merge(profileTreeStack[0]); } public render(editor:vscode.TextEditor,filename:string) { const report = this.profileData.Report(filename); const reportmax = report.fileData.max(); const maxtime = reportmax.line.timer; const maxavg = reportmax.line.average; const maxcount = reportmax.line.count; const linedecs = new Array<vscode.DecorationOptions>(); const funcdecs = new Array<vscode.DecorationOptions>(); const rulerthresholds = this.rulerDecorationTypes.map((ruler,i)=>{ return { type: ruler.type, threshold: ruler.threshold, decs: new Array<vscode.DecorationOptions>() }; }); const displayAverageTime = vscode.workspace.getConfiguration().get("factorio.profile.displayAverageTime"); const colorBy = vscode.workspace.getConfiguration().get<"count"|"totaltime"|"averagetime">("factorio.profile.colorBy","totaltime"); const highlightColor = vscode.workspace.getConfiguration().get("factorio.profile.timerHighlightColor"); const scalemax = {"count": maxcount, "totaltime":maxtime, "averagetime":maxavg }[colorBy]; const colorScaleFactor = Math.max(Number.MIN_VALUE, vscode.workspace.getConfiguration().get<number>("factorio.profile.colorScaleFactor",1)); const scale = { "boost": (x:number)=>{return Math.log1p(x*colorScaleFactor)/Math.log1p(scalemax*colorScaleFactor);}, "linear": (x:number)=>{return x/scalemax;}, "mute": (x:number)=>{return (Math.pow(1+scalemax,(x*colorScaleFactor)/scalemax)-1)/(scalemax*colorScaleFactor);}, }[vscode.workspace.getConfiguration().get<"boost"|"linear"|"mute">("factorio.profile.colorScaleMode","boost")]; const countwidth = maxcount.toFixed(0).length+1; const timeprecision = displayAverageTime ? 6 : 3; const timewidth = maxtime.toFixed(timeprecision).length+1; const width = countwidth+timewidth+3; const haslines = report.fileData.lines.size > 0; const hasfuncs = report.fileData.functions.size > 0; for (let line = 1; line <= editor.document.lineCount; line++) { if (haslines) { const linetc = report.fileData.lines.get(line); if (linetc) { const time = linetc.timer; const count = linetc.count; const displayTime = displayAverageTime ? linetc.avg() : time; const t = scale({"count": count, "totaltime":time, "averagetime":linetc.avg() }[colorBy]); const range = editor.document.validateRange(new vscode.Range(line-1,0,line-1,1/0)); linedecs.push({ range: range, hoverMessage: displayAverageTime ? `total: ${time}` : `avg: ${linetc.avg()}`, renderOptions: { before: { backgroundColor: `${highlightColor}${Math.floor(255*t).toString(16)}`, contentText: `${count.toFixed(0).padStart(countwidth,"\u00A0")}${displayTime.toFixed(timeprecision).padStart(timewidth,"\u00A0")}\u00A0ms`, width: `${width+1}ch`, } } }); const ruler = rulerthresholds.find(ruler=>{return t >= ruler.threshold;}); if (ruler) { ruler.decs.push({ range: range, }); } } else { linedecs.push({ range: editor.document.validateRange(new vscode.Range(line-1,0,line-1,1/0)), renderOptions: { before: { width: `${width+1}ch`, } } }); } } if (hasfuncs) { const functc = report.fileData.functions.get(line); if (functc) { const time = functc.timer; const count = functc.count; const displayTime = displayAverageTime ? functc.avg() : time; const range = editor.document.validateRange(new vscode.Range(line-1,0,line-1,1/0)); funcdecs.push({ range: range, renderOptions: { after: { contentText: `\u00A0${count.toFixed(0)}\u00A0|\u00A0${displayTime.toFixed(timeprecision)}\u00A0ms\u00A0`, // have to repeat some properties here or gitlens will win when we both try to render on the same line color: new vscode.ThemeColor("factorio.ProfileFunctionTimerForeground"), borderColor: new vscode.ThemeColor("factorio.ProfileFunctionTimerForeground"), margin: "0 0 0 3ch", } } }); } } } editor.setDecorations(this.timeDecorationType,linedecs); editor.setDecorations(this.funcDecorationType,funcdecs); rulerthresholds.forEach((ruler)=>{ editor.setDecorations(ruler.type,ruler.decs); }); this.statusBar.text = `Profile Dump Avg ${this.profileOverhead.avg().toFixed(3)} ms`; this.statusBar.show(); } public clear() { vscode.window.visibleTextEditors.forEach(editor => { editor.setDecorations(this.timeDecorationType,[]); editor.setDecorations(this.funcDecorationType,[]); this.rulerDecorationTypes.forEach(ruler=>{ editor.setDecorations(ruler.type,[]); }); }); this.statusBar.hide(); } }
the_stack
import { TestBed } from '@angular/core/testing'; import { StateEditorService } from // eslint-disable-next-line max-len 'components/state-editor/state-editor-properties-services/state-editor.service'; import { AnswerGroupObjectFactory } from 'domain/exploration/AnswerGroupObjectFactory'; import { HintObjectFactory } from 'domain/exploration/HintObjectFactory'; import { Interaction, InteractionObjectFactory } from 'domain/exploration/InteractionObjectFactory'; import { OutcomeObjectFactory } from 'domain/exploration/OutcomeObjectFactory'; import { SolutionObjectFactory } from 'domain/exploration/SolutionObjectFactory'; import { SubtitledHtml } from 'domain/exploration/subtitled-html.model'; import { SubtitledUnicodeObjectFactory } from 'domain/exploration/SubtitledUnicodeObjectFactory'; import { SolutionValidityService } from 'pages/exploration-editor-page/editor-tab/services/solution-validity.service'; import { Subscription } from 'rxjs'; describe('Editor state service', () => { let ecs: StateEditorService; let suof: SubtitledUnicodeObjectFactory; let sof: SolutionObjectFactory; let hof: HintObjectFactory; let interactionObjectFactory: InteractionObjectFactory; let answerGroupObjectFactory: AnswerGroupObjectFactory; let outcomeObjectFactory: OutcomeObjectFactory; let solutionValidityService: SolutionValidityService; let mockInteraction: Interaction; let stateEditorInitializedSpy: jasmine.Spy<jasmine.Func>; let stateEditorDirectiveInitializedSpy: jasmine.Spy<jasmine.Func>; let interactionEditorInitializedSpy: jasmine.Spy<jasmine.Func>; let showTranslationTabBusyModalSpy: jasmine.Spy<jasmine.Func>; let refreshStateTranslationSpy: jasmine.Spy<jasmine.Func>; let updateAnswerChoicesSpy: jasmine.Spy<jasmine.Func>; let saveOutcomeDestDetailsSpy: jasmine.Spy<jasmine.Func>; let handleCustomArgsUpdateSpy: jasmine.Spy<jasmine.Func>; let objectFormValidityChangeSpy: jasmine.Spy<jasmine.Func>; let testSubscriptions: Subscription; beforeEach(() => { TestBed.configureTestingModule({ providers: [StateEditorService] }); ecs = TestBed.inject(StateEditorService); suof = TestBed.inject(SubtitledUnicodeObjectFactory); sof = TestBed.inject(SolutionObjectFactory); hof = TestBed.inject(HintObjectFactory); interactionObjectFactory = TestBed.inject(InteractionObjectFactory); answerGroupObjectFactory = TestBed.inject(AnswerGroupObjectFactory); outcomeObjectFactory = TestBed.inject(OutcomeObjectFactory); solutionValidityService = TestBed.inject(SolutionValidityService); // Here, mockInteraction consists of an TextInput interaction with an // answer group leading to 'State' state and a default outcome leading to // 'Hola' state. mockInteraction = interactionObjectFactory.createFromBackendDict({ id: 'TextInput', answer_groups: [ { outcome: { dest: 'State', feedback: { html: '', content_id: 'This is a new feedback text', }, refresher_exploration_id: null, missing_prerequisite_skill_id: null, labelled_as_correct: false, param_changes: [], }, rule_specs: [], training_data: [], tagged_skill_misconception_id: '', }, ], default_outcome: { dest: 'Hola', feedback: { content_id: '', html: '', }, labelled_as_correct: false, param_changes: [], refresher_exploration_id: null, missing_prerequisite_skill_id: null, }, confirmed_unclassified_answers: [], customization_args: { placeholder: { value: { content_id: 'cid', unicode_str: '1' } }, rows: { value: 1 } }, hints: [], solution: { answer_is_exclusive: true, correct_answer: 'test_answer', explanation: { content_id: '2', html: 'test_explanation1', }, }, }); }); beforeEach(() => { stateEditorInitializedSpy = jasmine.createSpy('stateEditorInitialized'); stateEditorDirectiveInitializedSpy = jasmine.createSpy( 'stateEditorDirectiveInitialized'); interactionEditorInitializedSpy = jasmine.createSpy( 'interactionEditorInitialized'); showTranslationTabBusyModalSpy = jasmine.createSpy( 'showTranslationTabBusyModal'); refreshStateTranslationSpy = jasmine.createSpy('refreshStateTranslation'); updateAnswerChoicesSpy = jasmine.createSpy('updateAnswerChoices'); saveOutcomeDestDetailsSpy = jasmine.createSpy('saveOutcomeDestDetails'); handleCustomArgsUpdateSpy = jasmine.createSpy('handleCustomArgsUpdate'); objectFormValidityChangeSpy = jasmine.createSpy('objectFormValidityChange'); testSubscriptions = new Subscription(); testSubscriptions.add(ecs.onStateEditorInitialized.subscribe( stateEditorInitializedSpy)); testSubscriptions.add(ecs.onStateEditorDirectiveInitialized.subscribe( stateEditorDirectiveInitializedSpy)); testSubscriptions.add(ecs.onInteractionEditorInitialized.subscribe( interactionEditorInitializedSpy)); testSubscriptions.add(ecs.onShowTranslationTabBusyModal.subscribe( showTranslationTabBusyModalSpy)); testSubscriptions.add(ecs.onRefreshStateTranslation.subscribe( refreshStateTranslationSpy)); testSubscriptions.add(ecs.onUpdateAnswerChoices.subscribe( updateAnswerChoicesSpy)); testSubscriptions.add(ecs.onSaveOutcomeDestDetails.subscribe( saveOutcomeDestDetailsSpy)); testSubscriptions.add(ecs.onHandleCustomArgsUpdate.subscribe( handleCustomArgsUpdateSpy)); testSubscriptions.add(ecs.onObjectFormValidityChange.subscribe( objectFormValidityChangeSpy)); }); afterAll(() => { testSubscriptions.unsubscribe(); }); it('should correctly set and get state names', () => { ecs.setActiveStateName('A State'); expect(ecs.getActiveStateName()).toBe('A State'); }); it('should not allow invalid state names to be set', () => { ecs.setActiveStateName(''); expect(ecs.getActiveStateName()).toBeNull(); }); it('should correctly set and get solicitAnswerDetails', () => { expect(ecs.getSolicitAnswerDetails()).toBeFalse(); ecs.setSolicitAnswerDetails(false); expect(ecs.getSolicitAnswerDetails()).toBeFalse(); ecs.setSolicitAnswerDetails(true); expect(ecs.getSolicitAnswerDetails()).toEqual(true); }); it('should correctly set and get cardIsCheckpoint', () => { expect(ecs.getCardIsCheckpoint()).toBeFalse(); expect(ecs.setCardIsCheckpoint(false)); expect(ecs.getCardIsCheckpoint()).toBeFalse(); expect(ecs.setCardIsCheckpoint(true)); expect(ecs.getCardIsCheckpoint()).toBeTrue(); }); it('should correctly set and get misconceptionsBySkill', () => { const misconceptionsBySkill = { skillId1: [0], skillId2: [1, 2] }; expect(ecs.getMisconceptionsBySkill()).toEqual({}); ecs.setMisconceptionsBySkill(misconceptionsBySkill); expect(ecs.getMisconceptionsBySkill()).toEqual(misconceptionsBySkill); }); it('should correctly set and get linkedSkillId', () => { const linkedSkillId = 'skill_id1'; ecs.setLinkedSkillId(linkedSkillId); expect(ecs.getLinkedSkillId()).toEqual(linkedSkillId); }); it('should correctly return answer choices for interaction', () => { const customizationArgsForMultipleChoiceInput = { choices: { value: [ new SubtitledHtml('Choice 1', ''), new SubtitledHtml('Choice 2', '') ] } }; expect( ecs.getAnswerChoices( 'MultipleChoiceInput', customizationArgsForMultipleChoiceInput) ).toEqual([{ val: 0, label: 'Choice 1', }, { val: 1, label: 'Choice 2', }]); const customizationArgsForImageClickInput = { imageAndRegions: { value: { labeledRegions: [{ label: 'Label 1' }, { label: 'Label 2' }] } } }; expect( ecs.getAnswerChoices( 'ImageClickInput', customizationArgsForImageClickInput) ).toEqual([{ val: 'Label 1', label: 'Label 1', }, { val: 'Label 2', label: 'Label 2', }]); const customizationArgsForItemSelectionAndDragAndDropInput = { choices: { value: [ new SubtitledHtml('Choice 1', 'ca_choices_0'), new SubtitledHtml('Choice 2', 'ca_choices_1') ] } }; expect( ecs.getAnswerChoices( 'ItemSelectionInput', customizationArgsForItemSelectionAndDragAndDropInput) ).toEqual([{ val: 'ca_choices_0', label: 'Choice 1', }, { val: 'ca_choices_1', label: 'Choice 2', }]); expect( ecs.getAnswerChoices( 'DragAndDropSortInput', customizationArgsForItemSelectionAndDragAndDropInput) ).toEqual([{ val: 'ca_choices_0', label: 'Choice 1', }, { val: 'ca_choices_1', label: 'Choice 2', }]); expect( ecs.getAnswerChoices( 'NotDragAndDropSortInput', customizationArgsForItemSelectionAndDragAndDropInput) ).toEqual(null); }); it('should return null when getting answer choices' + ' if interactionID is empty', () => { expect(ecs.getAnswerChoices('', { choices: { value: [ new SubtitledHtml('Choice 1', ''), new SubtitledHtml('Choice 2', '') ] } })).toBeNull(); }); it('should return if exploration is whitelisted or not', () => { expect(ecs.isExplorationWhitelisted()).toBeFalse(); ecs.explorationIsWhitelisted = true; expect(ecs.isExplorationWhitelisted()).toBeTrue(); ecs.explorationIsWhitelisted = false; expect(ecs.isExplorationWhitelisted()).toBeFalse(); }); it('should initialise state content editor', () => { expect(ecs.stateContentEditorInitialised).toBeFalse(); ecs.updateStateContentEditorInitialised(); expect(ecs.stateContentEditorInitialised).toBeTrue(); }); it('should initialise state interaction editor', () => { expect(ecs.stateInteractionEditorInitialised).toBeFalse(); ecs.updateStateInteractionEditorInitialised(); expect(ecs.stateInteractionEditorInitialised).toBeTrue(); }); it('should initialise state responses initialised', () => { expect(ecs.stateResponsesInitialised).toBeFalse(); ecs.updateStateResponsesInitialised(); expect(ecs.stateResponsesInitialised).toBeTrue(); }); it('should initialise state hints editor', () => { expect(ecs.stateHintsEditorInitialised).toBeFalse(); ecs.updateStateHintsEditorInitialised(); expect(ecs.stateHintsEditorInitialised).toBeTrue(); }); it('should initialise state solution editor', () => { expect(ecs.stateSolutionEditorInitialised).toBeFalse(); ecs.updateStateSolutionEditorInitialised(); expect(ecs.stateSolutionEditorInitialised).toBeTrue(); }); it('should initialise state editor', () => { expect(ecs.stateEditorDirectiveInitialised).toBeFalse(); ecs.updateStateEditorDirectiveInitialised(); expect(ecs.stateEditorDirectiveInitialised).toBeTrue(); }); it('should update current rule input is valid', () => { expect(ecs.checkCurrentRuleInputIsValid()).toBeFalse(); ecs.updateCurrentRuleInputIsValid(true); expect(ecs.checkCurrentRuleInputIsValid()).toBeTrue(); ecs.updateCurrentRuleInputIsValid(false); expect(ecs.checkCurrentRuleInputIsValid()).toBeFalse(); }); it('should get and set state names', () => { expect(ecs.getStateNames()).toEqual([]); ecs.setStateNames(['Introduction', 'State1']); expect(ecs.getStateNames()).toEqual(['Introduction', 'State1']); ecs.setStateNames(['Introduction', 'End']); expect(ecs.getStateNames()).toEqual(['Introduction', 'End']); }); it('should check event listener registration status', () => { // Registration status is true only when, // stateInteractionEditorInitialised, stateResponsesInitialised and // stateEditorDirectiveInitialised are true. expect(ecs.stateInteractionEditorInitialised).toBeFalse(); expect(ecs.stateResponsesInitialised).toBeFalse(); expect(ecs.stateEditorDirectiveInitialised).toBeFalse(); expect(ecs.checkEventListenerRegistrationStatus()).toBeFalse(); // Set stateInteractionEditorInitialised as true. ecs.updateStateInteractionEditorInitialised(); expect(ecs.stateInteractionEditorInitialised).toBeTrue(); expect(ecs.stateResponsesInitialised).toBeFalse(); expect(ecs.stateEditorDirectiveInitialised).toBeFalse(); expect(ecs.checkEventListenerRegistrationStatus()).toBeFalse(); // Set stateResponsesInitialised as true. ecs.updateStateResponsesInitialised(); expect(ecs.stateInteractionEditorInitialised).toBeTrue(); expect(ecs.stateResponsesInitialised).toBeTrue(); expect(ecs.stateEditorDirectiveInitialised).toBeFalse(); expect(ecs.checkEventListenerRegistrationStatus()).toBeFalse(); // Set stateEditorDirectiveInitialised as true. ecs.updateStateEditorDirectiveInitialised(); expect(ecs.stateInteractionEditorInitialised).toBeTrue(); expect(ecs.stateResponsesInitialised).toBeTrue(); expect(ecs.stateEditorDirectiveInitialised).toBeTrue(); expect(ecs.checkEventListenerRegistrationStatus()).toBeTrue(); }); it('should update exploration whitelisted status', () => { expect(ecs.isExplorationWhitelisted()).toBeFalse(); ecs.updateExplorationWhitelistedStatus(true); expect(ecs.isExplorationWhitelisted()).toBeTrue(); ecs.updateExplorationWhitelistedStatus(false); expect(ecs.isExplorationWhitelisted()).toBeFalse(); }); it('should set interaction', () => { expect(ecs.getInteraction()).toBeUndefined(); ecs.setInteraction(mockInteraction); expect(ecs.getInteraction()).toEqual(mockInteraction); }); it('should get event emitter for change in state names', () => { spyOn(ecs.onStateNamesChanged, 'subscribe'); ecs.onStateNamesChanged.subscribe(); ecs.setStateNames(['State1']); expect(ecs.onStateNamesChanged.subscribe).toHaveBeenCalled(); }); it('should set interaction ID', () => { ecs.setInteraction(mockInteraction); expect(ecs.interaction.id).toBe('TextInput'); ecs.setInteractionId('ChangedTextInput'); expect(ecs.interaction.id).toBe('ChangedTextInput'); }); it('should set interaction answer groups', () => { let newAnswerGroups = [ answerGroupObjectFactory.createNew( [], outcomeObjectFactory.createNew('Hola', '1', 'Feedback text', []), ['Training data text'], '0' ), ]; ecs.setInteraction(mockInteraction); expect(ecs.interaction.answerGroups).toEqual( [ answerGroupObjectFactory.createNew( [], outcomeObjectFactory.createNew( 'State', 'This is a new feedback text', '', []), [], '' ), ] ); ecs.setInteractionAnswerGroups(newAnswerGroups); expect(ecs.interaction.answerGroups).toEqual(newAnswerGroups); }); it('should set interaction default outcome', () => { let newDefaultOutcome = outcomeObjectFactory.createNew( 'Hola1', '', 'Feedback text', []); ecs.setInteraction(mockInteraction); expect(ecs.interaction.defaultOutcome).toEqual( outcomeObjectFactory.createNew('Hola', '', '', [])); ecs.setInteractionDefaultOutcome(newDefaultOutcome); expect(ecs.interaction.defaultOutcome).toEqual(newDefaultOutcome); }); it('should set interaction customization args', () => { let newCustomizationArgs = { rows: { value: 2, }, placeholder: { value: suof.createDefault('2', ''), }, }; ecs.setInteraction(mockInteraction); expect(ecs.interaction.customizationArgs).toEqual({ placeholder: { value: suof.createDefault('1', 'cid'), }, rows: { value: 1 } }); ecs.setInteractionCustomizationArgs(newCustomizationArgs); expect(ecs.interaction.customizationArgs).toEqual(newCustomizationArgs); }); it('should set interaction solution', () => { let newSolution = sof.createFromBackendDict({ answer_is_exclusive: true, correct_answer: 'test_answer_new', explanation: { content_id: '2', html: 'test_explanation1_new', }, }); ecs.setInteraction(mockInteraction); expect(ecs.interaction.solution).toEqual(sof.createFromBackendDict({ answer_is_exclusive: true, correct_answer: 'test_answer', explanation: { content_id: '2', html: 'test_explanation1', }, })); ecs.setInteractionSolution(newSolution); expect(ecs.interaction.solution).toEqual(newSolution); }); it('should set interaction hints', () => { let newHints = [hof.createFromBackendDict({ hint_content: { content_id: '', html: 'This is a hint' } })]; ecs.setInteraction(mockInteraction); expect(ecs.interaction.hints).toEqual([]); ecs.setInteractionHints(newHints); expect(ecs.interaction.hints).toEqual(newHints); }); it('should set in question mode', () => { expect(ecs.isInQuestionMode()).toBeFalse(); ecs.setInQuestionMode(true); expect(ecs.isInQuestionMode()).toBeTrue(); ecs.setInQuestionMode(false); expect(ecs.isInQuestionMode()).toBeFalse(); }); it('should set correctness feedback enabled', () => { expect(ecs.getCorrectnessFeedbackEnabled()).toBeFalse(); ecs.setCorrectnessFeedbackEnabled(true); expect(ecs.getCorrectnessFeedbackEnabled()).toBeTrue(); ecs.setCorrectnessFeedbackEnabled(false); expect(ecs.getCorrectnessFeedbackEnabled()).toBeFalse(); }); it('should set inapplicable skill misconception ids', () => { expect(ecs.getInapplicableSkillMisconceptionIds()).toEqual([]); ecs.setInapplicableSkillMisconceptionIds(['id1', 'id2']); expect(ecs.getInapplicableSkillMisconceptionIds()).toEqual(['id1', 'id2']); }); it('should check if current solution is valid', () => { // Set 'Hola' as the active state. ecs.activeStateName = 'Hola'; // At present, we are not keeping track of the solution's validity. So, we // initialize the Solution Validity Service with the state. Upon, // initialization the solution validity is set as true. expect(ecs.isCurrentSolutionValid()).toBeFalse(); solutionValidityService.init(['Hola']); expect(ecs.isCurrentSolutionValid()).toBeTrue(); }); it('should delete current solution validity', () => { ecs.activeStateName = 'Hola'; expect(ecs.isCurrentSolutionValid()).toBeFalse(); solutionValidityService.init(['Hola']); expect(ecs.isCurrentSolutionValid()).toBeTrue(); ecs.deleteCurrentSolutionValidity(); expect(ecs.isCurrentSolutionValid()).toBeFalse(); }); it('should throw error on deletion of current solution validity' + ' if activeStateName is null', () => { ecs.activeStateName = null; expect(ecs.isCurrentSolutionValid()).toBeFalse(); expect(() => { ecs.deleteCurrentSolutionValidity(); }).toThrowError('Active State for this solution is not set'); expect(ecs.isCurrentSolutionValid()).toBeFalse(); }); });
the_stack
export interface definitions { /** * Common Modifier properties. */ productModifier_Base: { /** * BigCommerce API, which determines how it will display on the storefront. Acceptable values: `date`, `checkbox`, `file`, `text`, `multi_line_text`, `numbers_only_text`, `radio_buttons`, `rectangles`, `dropdown`, `product_list`, `product_list_with_images`, `swatch`. Required in a /POST. */ type: | 'date' | 'checkbox' | 'file' | 'text' | 'multi_line_text' | 'numbers_only_text' | 'radio_buttons' | 'rectangles' | 'dropdown' | 'product_list' | 'product_list_with_images' | 'swatch' /** * Whether or not this modifer is required or not at checkout. Required in a /POST. */ required: boolean /** * The order the modifiers display on the product detail page. */ sort_order?: number config?: definitions['config_Full'] /** * The name of the option shown on the storefront. */ display_name?: string } /** * Product Modifier */ productModifier_Full: definitions['productModifier_Base'] & { /** * The unique numeric ID of the modifier; increments sequentially. */ id?: number /** * The unique numeric ID of the product to which the option belongs. */ product_id?: number /** * The unique option name. Auto-generated from the display name, a timestamp, and the product ID. */ name?: string option_values?: definitions['productModifierOptionValue_Full'][] } /** * The model for a POST to create a modifier on a product. */ productModifier_Post: { /** * BigCommerce API, which determines how it will display on the storefront. Acceptable values: `date`, `checkbox`, `file`, `text`, `multi_line_text`, `numbers_only_text`, `radio_buttons`, `rectangles`, `dropdown`, `product_list`, `product_list_with_images`, `swatch`. Required in a /POST. */ type: | 'date' | 'checkbox' | 'file' | 'text' | 'multi_line_text' | 'numbers_only_text' | 'radio_buttons' | 'rectangles' | 'dropdown' | 'product_list' | 'product_list_with_images' | 'swatch' /** * Whether or not this modifer is required or not at checkout. Required in a /POST. */ required: boolean /** * The order the modifiers display on the product detail page. */ sort_order?: number /** * The values for option config can vary based on the Modifier created. */ config?: { /** * (date, text, multi_line_text, numbers_only_text) The default value. Shown on a date option as an ISO-8601–formatted string, or on a text option as a string. */ default_value?: string /** * (checkbox) Flag for setting the checkbox to be checked by default. */ checked_by_default?: boolean /** * (checkbox) Label displayed for the checkbox option. */ checkbox_label?: string /** * (date) Flag to limit the dates allowed to be entered on a date option. */ date_limited?: boolean /** * (date) The type of limit that is allowed to be entered on a date option. */ date_limit_mode?: 'earliest' | 'range' | 'latest' /** * (date) The earliest date allowed to be entered on the date option, as an ISO-8601 formatted string. */ date_earliest_value?: string /** * (date) The latest date allowed to be entered on the date option, as an ISO-8601 formatted string. */ date_latest_value?: string /** * (file) The kind of restriction on the file types that can be uploaded with a file upload option. Values: `specific` - restricts uploads to particular file types; `all` - allows all file types. */ file_types_mode?: 'specific' | 'all' /** * (file) The type of files allowed to be uploaded if the `file_type_option` is set to `specific`. Values: * `images` - Allows upload of image MIME types (`bmp`, `gif`, `jpg`, `jpeg`, `jpe`, `jif`, `jfif`, `jfi`, `png`, `wbmp`, `xbm`, `tiff`). `documents` - Allows upload of document MIME types (`txt`, `pdf`, `rtf`, `doc`, `docx`, `xls`, `xlsx`, `accdb`, `mdb`, `one`, `pps`, `ppsx`, `ppt`, `pptx`, `pub`, `odt`, `ods`, `odp`, `odg`, `odf`). * `other` - Allows file types defined in the `file_types_other` array. */ file_types_supported?: string[] /** * (file) A list of other file types allowed with the file upload option. */ file_types_other?: string[] /** * (file) The maximum size for a file that can be used with the file upload option. This will still be limited by the server. */ file_max_size?: number /** * (text, multi_line_text) Flag to validate the length of a text or multi-line text input. */ text_characters_limited?: boolean /** * (text, multi_line_text) The minimum length allowed for a text or multi-line text option. */ text_min_length?: number /** * (text, multi_line_text) The maximum length allowed for a text or multi line text option. */ text_max_length?: number /** * (multi_line_text) Flag to validate the maximum number of lines allowed on a multi-line text input. */ text_lines_limited?: boolean /** * (multi_line_text) The maximum number of lines allowed on a multi-line text input. */ text_max_lines?: number /** * (numbers_only_text) Flag to limit the value of a number option. */ number_limited?: boolean /** * (numbers_only_text) The type of limit on values entered for a number option. */ number_limit_mode?: 'lowest' | 'highest' | 'range' /** * (numbers_only_text) The lowest allowed value for a number option if `number_limited` is true. */ number_lowest_value?: number /** * (numbers_only_text) The highest allowed value for a number option if `number_limited` is true. */ number_highest_value?: number /** * (numbers_only_text) Flag to limit the input on a number option to whole numbers only. */ number_integers_only?: boolean /** * (product_list, product_list_with_images) Flag for automatically adjusting inventory on a product included in the list. */ product_list_adjusts_inventory?: boolean /** * (product_list, product_list_with_images) Flag to add the optional product's price to the main product's price. */ product_list_adjusts_pricing?: boolean /** * (product_list, product_list_with_images) How to factor the optional product's weight and package dimensions into the shipping quote. Values: `none` - don't adjust; `weight` - use shipping weight only; `package` - use weight and dimensions. */ product_list_shipping_calc?: 'none' | 'weight' | 'package' } option_values?: (({ /** * The flag for preselecting a value as the default on the storefront. This field is not supported for swatch options/modifiers. */ is_default?: boolean /** * The text display identifying the value on the storefront. Required in a /POST. */ label: string /** * The order in which the value will be displayed on the product page. Required in a /POST. */ sort_order: number /** * Extra data describing the value, based on the type of option or modifier with which the value is associated. The `swatch` type option can accept an array of `colors`, with up to three hexidecimal color keys; or an `image_url`, which is a full image URL path including protocol. The `product list` type option requires a `product_id`. The `checkbox` type option requires a boolean flag, called `checked_value`, to determine which value is considered to be the checked state. */ value_data?: { [key: string]: any } } & { adjusters?: { /** * Adjuster for Complex Rules. */ price?: { /** * The type of adjuster for either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster?: 'relative' | 'percentage' /** * The numeric amount by which the adjuster will change either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster_value?: number } /** * Adjuster for Complex Rules. */ weight?: { /** * The type of adjuster for either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster?: 'relative' | 'percentage' /** * The numeric amount by which the adjuster will change either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster_value?: number } /** * The URL for an image displayed on the storefront when the modifier value is selected.Limit of 8MB per file. */ image_url?: string purchasing_disabled?: { /** * Flag for whether the modifier value disables purchasing when selected on the storefront. This can be used for temporarily disabling a particular modifier value. */ status?: boolean /** * The message displayed on the storefront when the purchasing disabled status is `true`. */ message?: string } } }) & { /** * The unique numeric ID of the value; increments sequentially. */ id?: number })[] } & { /** * The name of the option shown on the storefront. */ display_name: string } /** * The model for a PUT to update a modifier on a product. */ productModifier_Put: { /** * BigCommerce API, which determines how it will display on the storefront. Acceptable values: `date`, `checkbox`, `file`, `text`, `multi_line_text`, `numbers_only_text`, `radio_buttons`, `rectangles`, `dropdown`, `product_list`, `product_list_with_images`, `swatch`. Required in a /POST. */ type: | 'date' | 'checkbox' | 'file' | 'text' | 'multi_line_text' | 'numbers_only_text' | 'radio_buttons' | 'rectangles' | 'dropdown' | 'product_list' | 'product_list_with_images' | 'swatch' /** * Whether or not this modifer is required or not at checkout. Required in a /POST. */ required: boolean /** * The order the modifiers display on the product detail page. */ sort_order?: number /** * The values for option config can vary based on the Modifier created. */ config?: { /** * (date, text, multi_line_text, numbers_only_text) The default value. Shown on a date option as an ISO-8601–formatted string, or on a text option as a string. */ default_value?: string /** * (checkbox) Flag for setting the checkbox to be checked by default. */ checked_by_default?: boolean /** * (checkbox) Label displayed for the checkbox option. */ checkbox_label?: string /** * (date) Flag to limit the dates allowed to be entered on a date option. */ date_limited?: boolean /** * (date) The type of limit that is allowed to be entered on a date option. */ date_limit_mode?: 'earliest' | 'range' | 'latest' /** * (date) The earliest date allowed to be entered on the date option, as an ISO-8601 formatted string. */ date_earliest_value?: string /** * (date) The latest date allowed to be entered on the date option, as an ISO-8601 formatted string. */ date_latest_value?: string /** * (file) The kind of restriction on the file types that can be uploaded with a file upload option. Values: `specific` - restricts uploads to particular file types; `all` - allows all file types. */ file_types_mode?: 'specific' | 'all' /** * (file) The type of files allowed to be uploaded if the `file_type_option` is set to `specific`. Values: * `images` - Allows upload of image MIME types (`bmp`, `gif`, `jpg`, `jpeg`, `jpe`, `jif`, `jfif`, `jfi`, `png`, `wbmp`, `xbm`, `tiff`). `documents` - Allows upload of document MIME types (`txt`, `pdf`, `rtf`, `doc`, `docx`, `xls`, `xlsx`, `accdb`, `mdb`, `one`, `pps`, `ppsx`, `ppt`, `pptx`, `pub`, `odt`, `ods`, `odp`, `odg`, `odf`). * `other` - Allows file types defined in the `file_types_other` array. */ file_types_supported?: string[] /** * (file) A list of other file types allowed with the file upload option. */ file_types_other?: string[] /** * (file) The maximum size for a file that can be used with the file upload option. This will still be limited by the server. */ file_max_size?: number /** * (text, multi_line_text) Flag to validate the length of a text or multi-line text input. */ text_characters_limited?: boolean /** * (text, multi_line_text) The minimum length allowed for a text or multi-line text option. */ text_min_length?: number /** * (text, multi_line_text) The maximum length allowed for a text or multi line text option. */ text_max_length?: number /** * (multi_line_text) Flag to validate the maximum number of lines allowed on a multi-line text input. */ text_lines_limited?: boolean /** * (multi_line_text) The maximum number of lines allowed on a multi-line text input. */ text_max_lines?: number /** * (numbers_only_text) Flag to limit the value of a number option. */ number_limited?: boolean /** * (numbers_only_text) The type of limit on values entered for a number option. */ number_limit_mode?: 'lowest' | 'highest' | 'range' /** * (numbers_only_text) The lowest allowed value for a number option if `number_limited` is true. */ number_lowest_value?: number /** * (numbers_only_text) The highest allowed value for a number option if `number_limited` is true. */ number_highest_value?: number /** * (numbers_only_text) Flag to limit the input on a number option to whole numbers only. */ number_integers_only?: boolean /** * (product_list, product_list_with_images) Flag for automatically adjusting inventory on a product included in the list. */ product_list_adjusts_inventory?: boolean /** * (product_list, product_list_with_images) Flag to add the optional product's price to the main product's price. */ product_list_adjusts_pricing?: boolean /** * (product_list, product_list_with_images) How to factor the optional product's weight and package dimensions into the shipping quote. Values: `none` - don't adjust; `weight` - use shipping weight only; `package` - use weight and dimensions. */ product_list_shipping_calc?: 'none' | 'weight' | 'package' } option_values?: (({ /** * The flag for preselecting a value as the default on the storefront. This field is not supported for swatch options/modifiers. */ is_default?: boolean /** * The text display identifying the value on the storefront. Required in a /POST. */ label: string /** * The order in which the value will be displayed on the product page. Required in a /POST. */ sort_order: number /** * Extra data describing the value, based on the type of option or modifier with which the value is associated. The `swatch` type option can accept an array of `colors`, with up to three hexidecimal color keys; or an `image_url`, which is a full image URL path including protocol. The `product list` type option requires a `product_id`. The `checkbox` type option requires a boolean flag, called `checked_value`, to determine which value is considered to be the checked state. */ value_data?: { [key: string]: any } } & { adjusters?: { /** * Adjuster for Complex Rules. */ price?: { /** * The type of adjuster for either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster?: 'relative' | 'percentage' /** * The numeric amount by which the adjuster will change either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster_value?: number } /** * Adjuster for Complex Rules. */ weight?: { /** * The type of adjuster for either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster?: 'relative' | 'percentage' /** * The numeric amount by which the adjuster will change either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster_value?: number } /** * The URL for an image displayed on the storefront when the modifier value is selected.Limit of 8MB per file. */ image_url?: string purchasing_disabled?: { /** * Flag for whether the modifier value disables purchasing when selected on the storefront. This can be used for temporarily disabling a particular modifier value. */ status?: boolean /** * The message displayed on the storefront when the purchasing disabled status is `true`. */ message?: string } } }) & { /** * The unique numeric ID of the value; increments sequentially. */ id?: number })[] } /** * Common Product Modifer `option_value` properties. */ productModifierOptionValue_Base: { /** * The flag for preselecting a value as the default on the storefront. This field is not supported for swatch options/modifiers. */ is_default?: boolean /** * The text display identifying the value on the storefront. Required in a /POST. */ label: string /** * The order in which the value will be displayed on the product page. Required in a /POST. */ sort_order: number /** * Extra data describing the value, based on the type of option or modifier with which the value is associated. The `swatch` type option can accept an array of `colors`, with up to three hexidecimal color keys; or an `image_url`, which is a full image URL path including protocol. The `product list` type option requires a `product_id`. The `checkbox` type option requires a boolean flag, called `checked_value`, to determine which value is considered to be the checked state. If no data is available, returns `null`. */ value_data?: { [key: string]: any } adjusters?: definitions['adjusters_Full'] } /** * Product Modifer `option_value`. */ productModifierOptionValue_Full: definitions['productModifierOptionValue_Base'] & { /** * The unique numeric ID of the value; increments sequentially. */ id?: number option_id?: number } /** * The model for a POST to create a modifier value on a product. */ productModifierOptionValue_Post: { /** * The flag for preselecting a value as the default on the storefront. This field is not supported for swatch options/modifiers. */ is_default?: boolean /** * The text display identifying the value on the storefront. Required in a /POST. */ label: string /** * The order in which the value will be displayed on the product page. Required in a /POST. */ sort_order: number /** * Extra data describing the value, based on the type of option or modifier with which the value is associated. The `swatch` type option can accept an array of `colors`, with up to three hexidecimal color keys; or an `image_url`, which is a full image URL path including protocol. The `product list` type option requires a `product_id`. The `checkbox` type option requires a boolean flag, called `checked_value`, to determine which value is considered to be the checked state. */ value_data?: { [key: string]: any } } & { adjusters?: { /** * Adjuster for Complex Rules. */ price?: { /** * The type of adjuster for either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster?: 'relative' | 'percentage' /** * The numeric amount by which the adjuster will change either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster_value?: number } /** * Adjuster for Complex Rules. */ weight?: { /** * The type of adjuster for either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster?: 'relative' | 'percentage' /** * The numeric amount by which the adjuster will change either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster_value?: number } /** * The URL for an image displayed on the storefront when the modifier value is selected.Limit of 8MB per file. */ image_url?: string purchasing_disabled?: { /** * Flag for whether the modifier value disables purchasing when selected on the storefront. This can be used for temporarily disabling a particular modifier value. */ status?: boolean /** * The message displayed on the storefront when the purchasing disabled status is `true`. */ message?: string } } } /** * The model for a PUT to update a modifier value on a product. */ productModifierOptionValue_Put: ({ /** * The flag for preselecting a value as the default on the storefront. This field is not supported for swatch options/modifiers. */ is_default?: boolean /** * The text display identifying the value on the storefront. Required in a /POST. */ label: string /** * The order in which the value will be displayed on the product page. Required in a /POST. */ sort_order: number /** * Extra data describing the value, based on the type of option or modifier with which the value is associated. The `swatch` type option can accept an array of `colors`, with up to three hexidecimal color keys; or an `image_url`, which is a full image URL path including protocol. The `product list` type option requires a `product_id`. The `checkbox` type option requires a boolean flag, called `checked_value`, to determine which value is considered to be the checked state. */ value_data?: { [key: string]: any } } & { adjusters?: { /** * Adjuster for Complex Rules. */ price?: { /** * The type of adjuster for either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster?: 'relative' | 'percentage' /** * The numeric amount by which the adjuster will change either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster_value?: number } /** * Adjuster for Complex Rules. */ weight?: { /** * The type of adjuster for either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster?: 'relative' | 'percentage' /** * The numeric amount by which the adjuster will change either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster_value?: number } /** * The URL for an image displayed on the storefront when the modifier value is selected.Limit of 8MB per file. */ image_url?: string purchasing_disabled?: { /** * Flag for whether the modifier value disables purchasing when selected on the storefront. This can be used for temporarily disabling a particular modifier value. */ status?: boolean /** * The message displayed on the storefront when the purchasing disabled status is `true`. */ message?: string } } }) & { /** * The unique numeric ID of the value; increments sequentially. */ id?: number } resp_productionOption: { data?: definitions['productOption_Full'] /** * Empty meta object; may be used later. */ meta?: { ''?: string } } /** * Common Option properties. */ productOption_Base: { /** * The unique numerical ID of the option, increments sequentially. */ id?: number /** * The unique numerical ID of the product to which the option belongs. */ product_id?: number /** * The name of the option shown on the storefront. */ display_name?: string /** * The type of option, which determines how it will display on the storefront. Acceptable values: `radio_buttons`, `rectangles`, `dropdown`, `product_list`, `product_list_with_images`, `swatch`. For reference, the former v2 API values are: RB = radio_buttons, RT = rectangles, S = dropdown, P = product_list, PI = product_list_with_images, CS = swatch. */ type?: | 'radio_buttons' | 'rectangles' | 'dropdown' | 'product_list' | 'product_list_with_images' | 'swatch' config?: definitions['productOptionConfig_Full'] /** * Order in which the option is displayed on the storefront. */ sort_order?: number option_values?: definitions['productOptionOptionValue_Full'] } productOption_Full: definitions['productOption_Base'] & { /** * The unique option name, auto-generated from the display name, a timestamp, and the product ID. */ name?: string } /** * The model for a POST to create options on a product. */ productOption_Post: { /** * The unique numerical ID of the option, increments sequentially. */ id?: number /** * The unique numerical ID of the product to which the option belongs. */ product_id?: number /** * The name of the option shown on the storefront. */ display_name?: string /** * The type of option, which determines how it will display on the storefront. Acceptable values: `radio_buttons`, `rectangles`, `dropdown`, `product_list`, `product_list_with_images`, `swatch`. For reference, the former v2 API values are: RB = radio_buttons, RT = rectangles, S = dropdown, P = product_list, PI = product_list_with_images, CS = swatch. */ type?: | 'radio_buttons' | 'rectangles' | 'dropdown' | 'product_list' | 'product_list_with_images' | 'swatch' /** * The values for option config can vary based on the Modifier created. */ config?: { /** * (date, text, multi_line_text, numbers_only_text) The default value. Shown on a date option as an ISO-8601–formatted string, or on a text option as a string. */ default_value?: string /** * (checkbox) Flag for setting the checkbox to be checked by default. */ checked_by_default?: boolean /** * (checkbox) Label displayed for the checkbox option. */ checkbox_label?: string /** * (date) Flag to limit the dates allowed to be entered on a date option. */ date_limited?: boolean /** * (date) The type of limit that is allowed to be entered on a date option. */ date_limit_mode?: 'earliest' | 'range' | 'latest' /** * (date) The earliest date allowed to be entered on the date option, as an ISO-8601 formatted string. */ date_earliest_value?: string /** * (date) The latest date allowed to be entered on the date option, as an ISO-8601 formatted string. */ date_latest_value?: string /** * (file) The kind of restriction on the file types that can be uploaded with a file upload option. Values: `specific` - restricts uploads to particular file types; `all` - allows all file types. */ file_types_mode?: 'specific' | 'all' /** * (file) The type of files allowed to be uploaded if the `file_type_option` is set to `specific`. Values: * `images` - Allows upload of image MIME types (`bmp`, `gif`, `jpg`, `jpeg`, `jpe`, `jif`, `jfif`, `jfi`, `png`, `wbmp`, `xbm`, `tiff`). `documents` - Allows upload of document MIME types (`txt`, `pdf`, `rtf`, `doc`, `docx`, `xls`, `xlsx`, `accdb`, `mdb`, `one`, `pps`, `ppsx`, `ppt`, `pptx`, `pub`, `odt`, `ods`, `odp`, `odg`, `odf`). * `other` - Allows file types defined in the `file_types_other` array. */ file_types_supported?: string[] /** * (file) A list of other file types allowed with the file upload option. */ file_types_other?: string[] /** * (file) The maximum size for a file that can be used with the file upload option. This will still be limited by the server. */ file_max_size?: number /** * (text, multi_line_text) Flag to validate the length of a text or multi-line text input. */ text_characters_limited?: boolean /** * (text, multi_line_text) The minimum length allowed for a text or multi-line text option. */ text_min_length?: number /** * (text, multi_line_text) The maximum length allowed for a text or multi line text option. */ text_max_length?: number /** * (multi_line_text) Flag to validate the maximum number of lines allowed on a multi-line text input. */ text_lines_limited?: boolean /** * (multi_line_text) The maximum number of lines allowed on a multi-line text input. */ text_max_lines?: number /** * (numbers_only_text) Flag to limit the value of a number option. */ number_limited?: boolean /** * (numbers_only_text) The type of limit on values entered for a number option. */ number_limit_mode?: 'lowest' | 'highest' | 'range' /** * (numbers_only_text) The lowest allowed value for a number option if `number_limited` is true. */ number_lowest_value?: number /** * (numbers_only_text) The highest allowed value for a number option if `number_limited` is true. */ number_highest_value?: number /** * (numbers_only_text) Flag to limit the input on a number option to whole numbers only. */ number_integers_only?: boolean /** * (product_list, product_list_with_images) Flag for automatically adjusting inventory on a product included in the list. */ product_list_adjusts_inventory?: boolean /** * (product_list, product_list_with_images) Flag to add the optional product's price to the main product's price. */ product_list_adjusts_pricing?: boolean /** * (product_list, product_list_with_images) How to factor the optional product's weight and package dimensions into the shipping quote. Values: `none` - don't adjust; `weight` - use shipping weight only; `package` - use weight and dimensions. */ product_list_shipping_calc?: 'none' | 'weight' | 'package' } /** * Order in which the option is displayed on the storefront. */ sort_order?: number option_values?: ({ /** * The flag for preselecting a value as the default on the storefront. This field is not supported for swatch options/modifiers. */ is_default?: boolean /** * The text display identifying the value on the storefront. Required in a /POST. */ label: string /** * The order in which the value will be displayed on the product page. Required in a /POST. */ sort_order: number /** * Extra data describing the value, based on the type of option or modifier with which the value is associated. The `swatch` type option can accept an array of `colors`, with up to three hexidecimal color keys; or an `image_url`, which is a full image URL path including protocol. The `product list` type option requires a `product_id`. The `checkbox` type option requires a boolean flag, called `checked_value`, to determine which value is considered to be the checked state. */ value_data?: { [key: string]: any } } & { /** * The unique numeric ID of the value; increments sequentially. */ id?: number })[] /** * Publicly available image url */ image_url?: string } /** * The model for a PUT to update options on a product. */ productOption_Put: { /** * The unique numerical ID of the option, increments sequentially. */ id?: number /** * The unique numerical ID of the product to which the option belongs. */ product_id?: number /** * The name of the option shown on the storefront. */ display_name?: string /** * The type of option, which determines how it will display on the storefront. Acceptable values: `radio_buttons`, `rectangles`, `dropdown`, `product_list`, `product_list_with_images`, `swatch`. For reference, the former v2 API values are: RB = radio_buttons, RT = rectangles, S = dropdown, P = product_list, PI = product_list_with_images, CS = swatch. */ type?: | 'radio_buttons' | 'rectangles' | 'dropdown' | 'product_list' | 'product_list_with_images' | 'swatch' /** * The values for option config can vary based on the Modifier created. */ config?: { /** * (date, text, multi_line_text, numbers_only_text) The default value. Shown on a date option as an ISO-8601–formatted string, or on a text option as a string. */ default_value?: string /** * (checkbox) Flag for setting the checkbox to be checked by default. */ checked_by_default?: boolean /** * (checkbox) Label displayed for the checkbox option. */ checkbox_label?: string /** * (date) Flag to limit the dates allowed to be entered on a date option. */ date_limited?: boolean /** * (date) The type of limit that is allowed to be entered on a date option. */ date_limit_mode?: 'earliest' | 'range' | 'latest' /** * (date) The earliest date allowed to be entered on the date option, as an ISO-8601 formatted string. */ date_earliest_value?: string /** * (date) The latest date allowed to be entered on the date option, as an ISO-8601 formatted string. */ date_latest_value?: string /** * (file) The kind of restriction on the file types that can be uploaded with a file upload option. Values: `specific` - restricts uploads to particular file types; `all` - allows all file types. */ file_types_mode?: 'specific' | 'all' /** * (file) The type of files allowed to be uploaded if the `file_type_option` is set to `specific`. Values: * `images` - Allows upload of image MIME types (`bmp`, `gif`, `jpg`, `jpeg`, `jpe`, `jif`, `jfif`, `jfi`, `png`, `wbmp`, `xbm`, `tiff`). `documents` - Allows upload of document MIME types (`txt`, `pdf`, `rtf`, `doc`, `docx`, `xls`, `xlsx`, `accdb`, `mdb`, `one`, `pps`, `ppsx`, `ppt`, `pptx`, `pub`, `odt`, `ods`, `odp`, `odg`, `odf`). * `other` - Allows file types defined in the `file_types_other` array. */ file_types_supported?: string[] /** * (file) A list of other file types allowed with the file upload option. */ file_types_other?: string[] /** * (file) The maximum size for a file that can be used with the file upload option. This will still be limited by the server. */ file_max_size?: number /** * (text, multi_line_text) Flag to validate the length of a text or multi-line text input. */ text_characters_limited?: boolean /** * (text, multi_line_text) The minimum length allowed for a text or multi-line text option. */ text_min_length?: number /** * (text, multi_line_text) The maximum length allowed for a text or multi line text option. */ text_max_length?: number /** * (multi_line_text) Flag to validate the maximum number of lines allowed on a multi-line text input. */ text_lines_limited?: boolean /** * (multi_line_text) The maximum number of lines allowed on a multi-line text input. */ text_max_lines?: number /** * (numbers_only_text) Flag to limit the value of a number option. */ number_limited?: boolean /** * (numbers_only_text) The type of limit on values entered for a number option. */ number_limit_mode?: 'lowest' | 'highest' | 'range' /** * (numbers_only_text) The lowest allowed value for a number option if `number_limited` is true. */ number_lowest_value?: number /** * (numbers_only_text) The highest allowed value for a number option if `number_limited` is true. */ number_highest_value?: number /** * (numbers_only_text) Flag to limit the input on a number option to whole numbers only. */ number_integers_only?: boolean /** * (product_list, product_list_with_images) Flag for automatically adjusting inventory on a product included in the list. */ product_list_adjusts_inventory?: boolean /** * (product_list, product_list_with_images) Flag to add the optional product's price to the main product's price. */ product_list_adjusts_pricing?: boolean /** * (product_list, product_list_with_images) How to factor the optional product's weight and package dimensions into the shipping quote. Values: `none` - don't adjust; `weight` - use shipping weight only; `package` - use weight and dimensions. */ product_list_shipping_calc?: 'none' | 'weight' | 'package' } /** * Order in which the option is displayed on the storefront. */ sort_order?: number option_values?: ({ /** * The flag for preselecting a value as the default on the storefront. This field is not supported for swatch options/modifiers. */ is_default?: boolean /** * The text display identifying the value on the storefront. Required in a /POST. */ label: string /** * The order in which the value will be displayed on the product page. Required in a /POST. */ sort_order: number /** * Extra data describing the value, based on the type of option or modifier with which the value is associated. The `swatch` type option can accept an array of `colors`, with up to three hexidecimal color keys; or an `image_url`, which is a full image URL path including protocol. The `product list` type option requires a `product_id`. The `checkbox` type option requires a boolean flag, called `checked_value`, to determine which value is considered to be the checked state. */ value_data?: { [key: string]: any } } & { /** * The unique numeric ID of the value; increments sequentially. */ id?: number })[] /** * Publicly available image url */ image_url?: string } /** * Returns the categories tree, a nested lineage of the categories with parent->child relationship. The Category objects returned are simplified versions of the category objects returned in the rest of this API. */ categoriesTree_Resp: { data?: definitions['categoriesTreeNode_Full'][] meta?: definitions['metaEmpty_Full'] } /** * Used to reflect parent <> child category relationships. Used by Category Tree. */ categoriesTreeNode_Full: { /** * The unique numeric ID of the category; increments sequentially. */ id?: number /** * The unique numeric ID of the category's parent. This field controls where the category sits in the tree of categories that organize the catalog. */ parent_id?: number /** * The name displayed for the category. Name is unique with respect to the category's siblings. */ name?: string /** * Flag to determine whether the product should be displayed to customers browsing the store. If `true`, the category will be displayed. If `false`, the category will be hidden from view. */ is_visible?: boolean /** * The custom URL for the category on the storefront. */ url?: string /** * The list of children of the category. */ children?: definitions['categoriesTreeNode_Full'][] } /** * Common Category object properties. */ category_Full: { /** * Unique ID of the *Category*. Increments sequentially. * Read-Only. */ id?: number /** * The unique numeric ID of the category's parent. This field controls where the category sits in the tree of categories that organize the catalog. * Required in a POST if creating a child category. */ parent_id: number /** * The name displayed for the category. Name is unique with respect to the category's siblings. * Required in a POST. */ name: string /** * The product description, which can include HTML formatting. */ description?: string /** * Number of views the category has on the storefront. */ views?: number /** * Priority this category will be given when included in the menu and category pages. The lower the number, the closer to the top of the results the category will be. */ sort_order?: number /** * Custom title for the category page. If not defined, the category name will be used as the meta title. */ page_title?: string /** * A comma-separated list of keywords that can be used to locate the category when searching the store. */ search_keywords?: string /** * Custom meta keywords for the category page. If not defined, the store's default keywords will be used. Must post as an array like: ["awesome","sauce"]. */ meta_keywords?: string[] /** * Custom meta description for the category page. If not defined, the store's default meta description will be used. */ meta_description?: string /** * A valid layout file. (Please refer to [this article](https://support.bigcommerce.com/articles/Public/Creating-Custom-Template-Files/) on creating category files.) This field is writable only for stores with a Blueprint theme applied. */ layout_file?: string /** * Flag to determine whether the product should be displayed to customers browsing the store. If `true`, the category will be displayed. If `false`, the category will be hidden from view. */ is_visible?: boolean /** * Determines how the products are sorted on category page load. */ default_product_sort?: | 'use_store_settings' | 'featured' | 'newest' | 'best_selling' | 'alpha_asc' | 'alpha_desc' | 'avg_customer_review' | 'price_asc' | 'price_desc' /** * Image URL used for this category on the storefront. Images can be uploaded via form file post to `/categories/{categoryId}/image`, or by providing a publicly accessible URL in this field. */ image_url?: string custom_url?: definitions['customUrl_Full'] } /** * Common Brand properties. */ brand_Full: { /** * Unique ID of the *Brand*. Read-Only. */ id?: number /** * The name of the brand. Must be unique. * Required in POST. */ name: string /** * The title shown in the browser while viewing the brand. */ page_title?: string /** * Comma-separated list of meta keywords to include in the HTML. */ meta_keywords?: string[] /** * A meta description to include. */ meta_description?: string /** * A comma-separated list of keywords that can be used to locate this brand. */ search_keywords?: string /** * Image URL used for this category on the storefront. Images can be uploaded via form file post to `/brands/{brandId}/image`, or by providing a publicly accessible URL in this field. */ image_url?: string custom_url?: definitions['customUrl_Full'] } /** * Common Variant properties. */ productVariant_Base: { /** * The cost price of the variant. Not affected by Price List prices. */ cost_price?: number /** * This variant's base price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is `null`, the product's default price (set in the Product resource's `price` field) will be used as the base price. */ price?: number /** * This variant's sale price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is null, the product's sale price (set in the Product resource's `price` field) will be used as the sale price. */ sale_price?: number /** * This variant's retail price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is null, the product's retail price (set in the Product resource's `price` field) will be used as the retail price. */ retail_price?: number /** * This variant's base weight on the storefront. If this value is null, the product's default weight (set in the Product resource's weight field) will be used as the base weight. */ weight?: number /** * Width of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default width (set in the Product resource's `width` field) will be used as the base width. */ width?: number /** * Height of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default height (set in the Product resource's `height` field) will be used as the base height. */ height?: number /** * Depth of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default depth (set in the Product resource's `depth` field) will be used as the base depth. */ depth?: number /** * Flag used to indicate whether the variant has free shipping. If `true`, the shipping cost for the variant will be zero. */ is_free_shipping?: boolean /** * A fixed shipping cost for the variant. If defined, this value will be used during checkout instead of normal shipping-cost calculation. */ fixed_cost_shipping_price?: number /** * If `true`, this variant will not be purchasable on the storefront. */ purchasing_disabled?: boolean /** * If `purchasing_disabled` is `true`, this message should show on the storefront when the variant is selected. */ purchasing_disabled_message?: string /** * The UPC code used in feeds for shopping comparison sites and external channel integrations. */ upc?: string /** * Inventory level for the variant, which is used when the product's inventory_tracking is set to `variant`. */ inventory_level?: number /** * When the variant hits this inventory level, it is considered low stock. */ inventory_warning_level?: number /** * Identifies where in a warehouse the variant is located. */ bin_picking_number?: string } productVariant_Full: definitions['productVariant_Base'] & { id?: number product_id?: number sku?: string /** * Read-only reference to v2 API's SKU ID. Null if it is a base variant. */ sku_id?: number /** * Array of option and option values IDs that make up this variant. Will be empty if the variant is the product's base variant. */ option_values?: definitions['productVariantOptionValue_Base'][] /** * The price of the variant as seen on the storefront. This price takes into account `sale_price` and any price adjustment rules that are applicable to this variant. */ calculated_price?: number } /** * The model for a POST to create variants on a product. */ productVariant_Post: { /** * The cost price of the variant. Not affected by Price List prices. */ cost_price?: number /** * This variant's base price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is `null`, the product's default price (set in the Product resource's `price` field) will be used as the base price. */ price?: number /** * This variant's sale price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is null, the product's sale price (set in the Product resource's `price` field) will be used as the sale price. */ sale_price?: number /** * This variant's retail price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is null, the product's retail price (set in the Product resource's `price` field) will be used as the retail price. */ retail_price?: number /** * This variant's base weight on the storefront. If this value is null, the product's default weight (set in the Product resource's weight field) will be used as the base weight. */ weight?: number /** * Width of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default width (set in the Product resource's `width` field) will be used as the base width. */ width?: number /** * Height of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default height (set in the Product resource's `height` field) will be used as the base height. */ height?: number /** * Depth of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default depth (set in the Product resource's `depth` field) will be used as the base depth. */ depth?: number /** * Flag used to indicate whether the variant has free shipping. If `true`, the shipping cost for the variant will be zero. */ is_free_shipping?: boolean /** * A fixed shipping cost for the variant. If defined, this value will be used during checkout instead of normal shipping-cost calculation. */ fixed_cost_shipping_price?: number /** * If `true`, this variant will not be purchasable on the storefront. */ purchasing_disabled?: boolean /** * If `purchasing_disabled` is `true`, this message should show on the storefront when the variant is selected. */ purchasing_disabled_message?: string /** * The UPC code used in feeds for shopping comparison sites and external channel integrations. */ upc?: string /** * Inventory level for the variant, which is used when the product's inventory_tracking is set to `variant`. */ inventory_level?: number /** * When the variant hits this inventory level, it is considered low stock. */ inventory_warning_level?: number /** * Identifies where in a warehouse the variant is located. */ bin_picking_number?: string } & { product_id?: number sku?: string /** * Array of option and option values IDs that make up this variant. Will be empty if the variant is the product's base variant. */ option_values?: { id?: number; option_id?: number }[] } variantCollection_Put: definitions['productVariant_Full'][] /** * The model for a PUT to update variants on a product. */ variant_Put: { /** * The cost price of the variant. Not affected by Price List prices. */ cost_price?: number /** * This variant's base price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is `null`, the product's default price (set in the Product resource's `price` field) will be used as the base price. */ price?: number /** * This variant's sale price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is null, the product's sale price (set in the Product resource's `price` field) will be used as the sale price. */ sale_price?: number /** * This variant's retail price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is null, the product's retail price (set in the Product resource's `price` field) will be used as the retail price. */ retail_price?: number /** * This variant's base weight on the storefront. If this value is null, the product's default weight (set in the Product resource's weight field) will be used as the base weight. */ weight?: number /** * Width of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default width (set in the Product resource's `width` field) will be used as the base width. */ width?: number /** * Height of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default height (set in the Product resource's `height` field) will be used as the base height. */ height?: number /** * Depth of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default depth (set in the Product resource's `depth` field) will be used as the base depth. */ depth?: number /** * Flag used to indicate whether the variant has free shipping. If `true`, the shipping cost for the variant will be zero. */ is_free_shipping?: boolean /** * A fixed shipping cost for the variant. If defined, this value will be used during checkout instead of normal shipping-cost calculation. */ fixed_cost_shipping_price?: number /** * If `true`, this variant will not be purchasable on the storefront. */ purchasing_disabled?: boolean /** * If `purchasing_disabled` is `true`, this message should show on the storefront when the variant is selected. */ purchasing_disabled_message?: string /** * The UPC code used in feeds for shopping comparison sites and external channel integrations. */ upc?: string /** * Inventory level for the variant, which is used when the product's inventory_tracking is set to `variant`. */ inventory_level?: number /** * When the variant hits this inventory level, it is considered low stock. */ inventory_warning_level?: number /** * Identifies where in a warehouse the variant is located. */ bin_picking_number?: string } & { id?: number } /** * The model for a POST to create variants on a product. */ productVariant_Post_Product: definitions['productVariant_Base'] & { sku?: string option_values?: { /** * The name of the option. */ option_display_name?: string /** * The label of the option value. */ label?: string }[] } /** * The model for a PUT to update variants on a product. */ productVariant_Put_Product: { /** * The cost price of the variant. Not affected by Price List prices. */ cost_price?: number /** * This variant's base price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is `null`, the product's default price (set in the Product resource's `price` field) will be used as the base price. */ price?: number /** * This variant's sale price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is null, the product's sale price (set in the Product resource's `price` field) will be used as the sale price. */ sale_price?: number /** * This variant's retail price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is null, the product's retail price (set in the Product resource's `price` field) will be used as the retail price. */ retail_price?: number /** * This variant's base weight on the storefront. If this value is null, the product's default weight (set in the Product resource's weight field) will be used as the base weight. */ weight?: number /** * Width of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default width (set in the Product resource's `width` field) will be used as the base width. */ width?: number /** * Height of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default height (set in the Product resource's `height` field) will be used as the base height. */ height?: number /** * Depth of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default depth (set in the Product resource's `depth` field) will be used as the base depth. */ depth?: number /** * Flag used to indicate whether the variant has free shipping. If `true`, the shipping cost for the variant will be zero. */ is_free_shipping?: boolean /** * A fixed shipping cost for the variant. If defined, this value will be used during checkout instead of normal shipping-cost calculation. */ fixed_cost_shipping_price?: number /** * If `true`, this variant will not be purchasable on the storefront. */ purchasing_disabled?: boolean /** * If `purchasing_disabled` is `true`, this message should show on the storefront when the variant is selected. */ purchasing_disabled_message?: string /** * The UPC code used in feeds for shopping comparison sites and external channel integrations. */ upc?: string /** * Inventory level for the variant, which is used when the product's inventory_tracking is set to `variant`. */ inventory_level?: number /** * When the variant hits this inventory level, it is considered low stock. */ inventory_warning_level?: number /** * Identifies where in a warehouse the variant is located. */ bin_picking_number?: string product_id?: number sku?: string } productVariantOptionValue_Full: { /** * The name of the option. */ option_display_name?: string /** * The label of the option value. */ label?: string } & definitions['productVariantOptionValue_Base'] /** * The model for a POST to create option values on a product. */ productOptionValue_Post_Product: { /** * The name of the option. */ option_display_name?: string /** * The label of the option value. */ label?: string } /** * Common Product Variant Option properties. */ productVariantOptionValue_Base: { id?: number; option_id?: number } /** * The model for a POST to create option values on a variant. */ productVariantOptionValue_Post: { id?: number; option_id?: number } resp_productOptionValue: { data?: definitions['productOptionOptionValue_Full'] /** * Empty meta object; may be used later. */ meta?: { ''?: string } } /** * Common Product Option `option_value` properties. */ productOptionOptionValue_Base: { /** * The flag for preselecting a value as the default on the storefront. This field is not supported for swatch options/modifiers. */ is_default?: boolean /** * The text display identifying the value on the storefront. Required in a /POST. */ label: string /** * The order in which the value will be displayed on the product page. Required in a /POST. */ sort_order: number /** * Extra data describing the value, based on the type of option or modifier with which the value is associated. The `swatch` type option can accept an array of `colors`, with up to three hexidecimal color keys; or an `image_url`, which is a full image URL path including protocol. The `product list` type option requires a `product_id`. The `checkbox` type option requires a boolean flag, called `checked_value`, to determine which value is considered to be the checked state. If no data is available, returns `null`. */ value_data?: { [key: string]: any } } /** * Product Option `option_value`. */ productOptionOptionValue_Full: definitions['productOptionOptionValue_Base'] & { /** * The unique numeric ID of the value; increments sequentially. */ id?: number } /** * The model for a POST to create option values on a product. */ productOptionValue_Post: { /** * The flag for preselecting a value as the default on the storefront. This field is not supported for swatch options/modifiers. */ is_default?: boolean /** * The text display identifying the value on the storefront. Required in a /POST. */ label: string /** * The order in which the value will be displayed on the product page. Required in a /POST. */ sort_order: number /** * Extra data describing the value, based on the type of option or modifier with which the value is associated. The `swatch` type option can accept an array of `colors`, with up to three hexidecimal color keys; or an `image_url`, which is a full image URL path including protocol. The `product list` type option requires a `product_id`. The `checkbox` type option requires a boolean flag, called `checked_value`, to determine which value is considered to be the checked state. */ value_data?: { [key: string]: any } } /** * The model for a PUT to update option values on a product. */ productOptionValue_Put: { /** * The flag for preselecting a value as the default on the storefront. This field is not supported for swatch options/modifiers. */ is_default?: boolean /** * The text display identifying the value on the storefront. Required in a /POST. */ label: string /** * The order in which the value will be displayed on the product page. Required in a /POST. */ sort_order: number /** * Extra data describing the value, based on the type of option or modifier with which the value is associated. The `swatch` type option can accept an array of `colors`, with up to three hexidecimal color keys; or an `image_url`, which is a full image URL path including protocol. The `product list` type option requires a `product_id`. The `checkbox` type option requires a boolean flag, called `checked_value`, to determine which value is considered to be the checked state. */ value_data?: { [key: string]: any } } & { /** * The unique numeric ID of the value; increments sequentially. */ id?: number } /** * Common ProductImage properties. */ productImage_Base: { /** * The local path to the original image file uploaded to BigCommerce. */ image_file?: string /** * Flag for identifying whether the image is used as the product's thumbnail. */ is_thumbnail?: boolean /** * The order in which the image will be displayed on the product page. Higher integers give the image a lower priority. When updating, if the image is given a lower priority, all images with a `sort_order` the same as or greater than the image's new `sort_order` value will have their `sort_order`s reordered. */ sort_order?: number /** * The description for the image. */ description?: string /** * Must be a fully qualified URL path, including protocol. Limit of 8MB per file. */ image_url?: string } /** * The model for a POST to create an image on a product. */ productImage_Post: { /** * The unique numeric ID of the image; increments sequentially. */ id?: number /** * The unique numeric identifier for the product with which the image is associated. */ product_id?: number /** * The local path to the original image file uploaded to BigCommerce. */ image_file?: string /** * The zoom URL for this image. By default, this is used as the zoom image on product pages when zoom images are enabled. */ url_zoom?: string /** * The standard URL for this image. By default, this is used for product-page images. */ url_standard?: string /** * The thumbnail URL for this image. By default, this is the image size used on the category page and in side panels. */ url_thumbnail?: string /** * The tiny URL for this image. By default, this is the image size used for thumbnails beneath the product image on a product page. */ url_tiny?: string /** * The date on which the product image was modified. */ date_modified?: string /** * Flag for identifying whether the image is used as the product's thumbnail. */ is_thumbnail?: boolean /** * The order in which the image will be displayed on the product page. Higher integers give the image a lower priority. When updating, if the image is given a lower priority, all images with a `sort_order` the same as or greater than the image's new `sort_order` value will have their `sort_order`s reordered. */ sort_order?: number /** * The description for the image. */ description?: string } & { /** * Must be a fully qualified URL path, including protocol. Limit of 8MB per file. */ image_url?: string /** * Must be sent as a multipart/form-data field in the request body. */ image_file?: string } /** * The model for a PUT to update applicable Product Image fields. */ productImage_Put: { /** * The unique numeric ID of the image; increments sequentially. */ id?: number /** * The unique numeric identifier for the product with which the image is associated. */ product_id?: number /** * The local path to the original image file uploaded to BigCommerce. */ image_file?: string /** * The zoom URL for this image. By default, this is used as the zoom image on product pages when zoom images are enabled. */ url_zoom?: string /** * The standard URL for this image. By default, this is used for product-page images. */ url_standard?: string /** * The thumbnail URL for this image. By default, this is the image size used on the category page and in side panels. */ url_thumbnail?: string /** * The tiny URL for this image. By default, this is the image size used for thumbnails beneath the product image on a product page. */ url_tiny?: string /** * The date on which the product image was modified. */ date_modified?: string /** * Flag for identifying whether the image is used as the product's thumbnail. */ is_thumbnail?: boolean /** * The order in which the image will be displayed on the product page. Higher integers give the image a lower priority. When updating, if the image is given a lower priority, all images with a `sort_order` the same as or greater than the image's new `sort_order` value will have their `sort_order`s reordered. */ sort_order?: number /** * The description for the image. */ description?: string } /** * The model for a POST to create a video on a product. */ productVideo_Base: { /** * The title for the video. If left blank, this will be filled in according to data on a host site. */ title?: string /** * The description for the video. If left blank, this will be filled in according to data on a host site. */ description?: string /** * The order in which the video will be displayed on the product page. Higher integers give the video a lower priority. When updating, if the video is given a lower priority, all videos with a `sort_order` the same as or greater than the video's new `sort_order` value will have their `sort_order`s reordered. */ sort_order?: number /** * The video type (a short name of a host site). */ type?: 'youtube' /** * The ID of the video on a host site. */ video_id?: string } /** * A product video model. */ productVideo_Full: definitions['productVideo_Base'] & { /** * The unique numeric ID of the product video; increments sequentially. */ id?: number /** * The unique numeric identifier for the product with which the image is associated. */ product_id?: number /** * Length of the video. This will be filled in according to data on a host site. */ length?: string } /** * The model for a POST to create a video on a product. */ productVideo_Post: definitions['productVideo_Base'] /** * The model for a PUT to update a video on a product. */ productVideo_Put: definitions['productVideo_Base'] & { /** * The unique numeric ID of the product video; increments sequentially. */ id?: number } productReview_Base: { /** * The title for the product review. * Required in /POST. */ title: string /** * The text for the product review. */ text?: string /** * The status of the product review. Must be one of `approved`, `disapproved` or `pending`. */ status?: string /** * The rating of the product review. Must be one of 0, 1, 2, 3, 4, 5. */ rating?: number /** * The email of the reviewer. Must be a valid email, or an empty string. */ email?: string /** * The name of the reviewer. */ name?: string /** * Date the product was reviewed. Required in /POST. */ date_reviewed: string } /** * A product review model. */ productReview_Full: definitions['productReview_Base'] & { /** * The unique numeric ID of the product review; increments sequentially. */ id?: number /** * The unique numeric identifier for the product with which the review is associated. */ product_id?: number /** * Date the product review was created. */ date_created?: string /** * Date the product review was modified. */ date_modified?: string } /** * The model for a POST to create a product review. */ productReview_Post: { /** * The title for the product review. * Required in /POST. */ title: string /** * The text for the product review. */ text?: string /** * The status of the product review. Must be one of `approved`, `disapproved` or `pending`. */ status?: string /** * The rating of the product review. Must be one of 0, 1, 2, 3, 4, 5. */ rating?: number /** * The email of the reviewer. Must be a valid email, or an empty string. */ email?: string /** * The name of the reviewer. */ name?: string /** * Date the product was reviewed. Required in /POST. */ date_reviewed: string } /** * The model for a PUT to update a product review. */ productReview_Put: { /** * The title for the product review. * Required in /POST. */ title: string /** * The text for the product review. */ text?: string /** * The status of the product review. Must be one of `approved`, `disapproved` or `pending`. */ status?: string /** * The rating of the product review. Must be one of 0, 1, 2, 3, 4, 5. */ rating?: number /** * The email of the reviewer. Must be a valid email, or an empty string. */ email?: string /** * The name of the reviewer. */ name?: string /** * Date the product was reviewed. Required in /POST. */ date_reviewed: string } /** * Image Response returns for: * * Create Variant Image * * Create Modifier Image * * Create Category Image * * Create Brand Image */ resp_productImage: { data?: definitions['productImage_Full'] /** * Empty meta object; may be used later. */ meta?: { [key: string]: any } } /** * An object containing a publicly accessible image URL, or a form post that contains an image file. */ resourceImage_Full: { /** * A public URL for a GIF, JPEG, or PNG image. Limit of 8MB per file. */ image_url?: string } product_Post: definitions['product_Base'] & { variants?: definitions['productVariant_Post_Product'] } /** * The model for a PUT to update a product. */ product_Put: { /** * The unique numerical ID of the product; increments sequentially. */ id?: number } & definitions['product_Base'] & { variants?: definitions['productVariant_Put_Product'] } /** * Catalog Summary object describes a lightweight summary of the catalog. */ catalogSummary_Full: { /** * A count of all inventory items in the catalog. */ inventory_count?: number /** * Total value of store's inventory. */ inventory_value?: number /** * ID of the category containing the most products. */ primary_category_id?: number /** * Name of the category containing the most products. */ primary_category_name?: string /** * Total number of variants */ variant_count?: number /** * Highest priced variant */ highest_variant_price?: number /** * Average price of all variants */ average_variant_price?: number /** * Lowest priced variant in the store */ lowest_variant_price?: string oldest_variant_date?: string newest_variant_date?: string } /** * Metafield for products, categories, variants, and brands. The max number of metafields allowed on each product, category, variant, or brand is fifty. For more information, see [Platform Limits](https://support.bigcommerce.com/s/article/Platform-Limits) in the Help Center. */ metafield_Base: { /** * Unique ID of the *Metafield*. Read-Only. */ id?: number /** * Determines the visibility and writeability of the field by other API consumers. * * |Value|Description * |-|-| * |`app_only`|Private to the app that owns the field| * |`read`|Visible to other API consumers| * |`write`|Open for reading and writing by other API consumers| * |`read_and_sf_access`|Visible to other API consumers, including on storefront| * |`write_and_sf_access`|Open for reading and writing by other API consumers, including on storefront| */ permission_set: | 'app_only' | 'read' | 'write' | 'read_and_sf_access' | 'write_and_sf_access' /** * Namespace for the metafield, for organizational purposes. This is set set by the developer. Required for POST. */ namespace: string /** * The name of the field, for example: `location_id`, `color`. Required for POST. */ key: string /** * The value of the field, for example: `1`, `blue`. Required for POST. */ value: string /** * Description for the metafields. */ description?: string /** * The type of resource with which the metafield is associated. */ resource_type?: 'category' | 'brand' | 'product' | 'variant' /** * The ID for the resource with which the metafield is associated. */ resource_id?: number /** * Date and time of the metafield's creation. Read-Only. */ date_created?: string /** * Date and time when the metafield was last updated. Read-Only. */ date_modified?: string } /** * Common ComplexRule properties. */ complexRule_Base: { /** * The unique numeric ID of the rule; increments sequentially. * Read-Only */ id?: number /** * The unique numeric ID of the product with which the rule is associated; increments sequentially. */ product_id?: number /** * The priority to give this rule when making adjustments to the product properties. */ sort_order?: number /** * Flag for determining whether the rule is to be used when adjusting a product's price, weight, image, or availabilty. */ enabled?: boolean /** * Flag for determining whether other rules should not be applied after this rule has been applied. */ stop?: boolean /** * Flag for determining whether the rule should disable purchasing of a product when the conditions are applied. */ purchasing_disabled?: boolean /** * Message displayed on the storefront when a rule disables the purchasing of a product. */ purchasing_disabled_message?: string /** * Flag for determining whether the rule should hide purchasing of a product when the conditions are applied. */ purchasing_hidden?: boolean /** * The URL for an image displayed on the storefront when the conditions are applied. Limit of 8MB per file. */ image_url?: string price_adjuster?: definitions['adjuster_Full'] weight_adjuster?: definitions['adjuster_Full'] conditions?: definitions['complexRuleConditionBase'][] } /** * Gets custom fields associated with a product. These allow you to specify additional information that will appear on the product's page, such as a book's ISBN or a DVD's release date. */ productCustomField_Base: { /** * The unique numeric ID of the custom field; increments sequentially. * Read-Only */ id?: number /** * The name of the field, shown on the storefront, orders, etc. Required for /POST */ name: string /** * The name of the field, shown on the storefront, orders, etc. Required for /POST */ value: string } /** * The model for a POST to create a custom field on a product. */ productCustomField_Post: { /** * The unique numeric ID of the custom field; increments sequentially. * Read-Only */ id?: number /** * The name of the field, shown on the storefront, orders, etc. Required for /POST */ name: string /** * The name of the field, shown on the storefront, orders, etc. Required for /POST */ value: string } /** * The model for a PUT to update a custom field on a product. */ productCustomField_Put: { /** * The unique numeric ID of the custom field; increments sequentially. * Read-Only */ id?: number /** * The name of the field, shown on the storefront, orders, etc. Required for /POST */ name: string /** * The name of the field, shown on the storefront, orders, etc. Required for /POST */ value: string } /** * Complex rules may return with conditions that apply to one or more variants, or with a single modifier value (if the rules were created using the v2 API or the control panel). Complex rules created or updated in the v3 API must have conditions that either reference multiple `modifier_value_id`'s, or else reference a `modifier_value_id` and a `variant_id`. */ complexRuleConditionBase: { /** * The unique numeric ID of the rule condition; increments sequentially. Read-Only */ id?: number /** * The unique numeric ID of the rule with which the condition is associated. * Read-Only */ rule_id?: number /** * The unique numeric ID of the modifier with which the rule condition is associated. * Required in /POST. */ modifier_id: number /** * The unique numeric ID of the modifier value with which the rule condition is associated. * Required in /POST. */ modifier_value_id: number /** * The unique numeric ID of the variant with which the rule condition is associated. * Required in /POST. */ variant_id: number /** * (READ-ONLY:) The unique numeric ID of the SKU (v2 API), or Combination, with which the rule condition is associated. This is to maintain cross-compatibility between v2 and v3. */ combination_id?: number } /** * The custom URL for the category on the storefront. */ customUrl_Full: { /** * Category URL on the storefront. */ url?: string /** * Returns `true` if the URL has been changed from its default state (the auto-assigned URL that BigCommerce provides). */ is_customized?: boolean } /** * Common Bulk Pricing Rule properties */ bulkPricingRule_Full: { /** * Unique ID of the *Bulk Pricing Rule*. Read-Only. */ id?: number /** * The minimum inclusive quantity of a product to satisfy this rule. Must be greater than or equal to zero. * Required in /POST. */ quantity_min: number /** * The maximum inclusive quantity of a product to satisfy this rule. Must be greater than the `quantity_min` value – unless this field has a value of 0 (zero), in which case there will be no maximum bound for this rule. * Required in /POST. */ quantity_max: number /** * The type of adjustment that is made. Values: `price` - the adjustment amount per product; `percent` - the adjustment as a percentage of the original price; `fixed` - the adjusted absolute price of the product. * Required in /POST. */ type: 'price' | 'percent' | 'fixed' /** * The discount can be a fixed dollar amount or a percentage. For a fixed dollar amount enter it as an integer and the response will return as an integer. For percentage enter the amount as the percentage divided by 100 using string format. For example 10% percent would be “.10”. The response will return as an integer. * Required in /POST. */ amount: number } /** * The values for option config can vary based on the Modifier created. */ productOptionConfig_Full: { /** * (date, text, multi_line_text, numbers_only_text) The default value. Shown on a date option as an ISO-8601–formatted string, or on a text option as a string. */ default_value?: string /** * (checkbox) Flag for setting the checkbox to be checked by default. */ checked_by_default?: boolean /** * (checkbox) Label displayed for the checkbox option. */ checkbox_label?: string /** * (date) Flag to limit the dates allowed to be entered on a date option. */ date_limited?: boolean /** * (date) The type of limit that is allowed to be entered on a date option. */ date_limit_mode?: 'earliest' | 'range' | 'latest' /** * (date) The earliest date allowed to be entered on the date option, as an ISO-8601 formatted string. */ date_earliest_value?: string /** * (date) The latest date allowed to be entered on the date option, as an ISO-8601 formatted string. */ date_latest_value?: string /** * (file) The kind of restriction on the file types that can be uploaded with a file upload option. Values: `specific` - restricts uploads to particular file types; `all` - allows all file types. */ file_types_mode?: 'specific' | 'all' /** * (file) The type of files allowed to be uploaded if the `file_type_option` is set to `specific`. Values: * `images` - Allows upload of image MIME types (`bmp`, `gif`, `jpg`, `jpeg`, `jpe`, `jif`, `jfif`, `jfi`, `png`, `wbmp`, `xbm`, `tiff`). `documents` - Allows upload of document MIME types (`txt`, `pdf`, `rtf`, `doc`, `docx`, `xls`, `xlsx`, `accdb`, `mdb`, `one`, `pps`, `ppsx`, `ppt`, `pptx`, `pub`, `odt`, `ods`, `odp`, `odg`, `odf`). * `other` - Allows file types defined in the `file_types_other` array. */ file_types_supported?: string[] /** * (file) A list of other file types allowed with the file upload option. */ file_types_other?: string[] /** * (file) The maximum size for a file that can be used with the file upload option. This will still be limited by the server. */ file_max_size?: number /** * (text, multi_line_text) Flag to validate the length of a text or multi-line text input. */ text_characters_limited?: boolean /** * (text, multi_line_text) The minimum length allowed for a text or multi-line text option. */ text_min_length?: number /** * (text, multi_line_text) The maximum length allowed for a text or multi line text option. */ text_max_length?: number /** * (multi_line_text) Flag to validate the maximum number of lines allowed on a multi-line text input. */ text_lines_limited?: boolean /** * (multi_line_text) The maximum number of lines allowed on a multi-line text input. */ text_max_lines?: number /** * (numbers_only_text) Flag to limit the value of a number option. */ number_limited?: boolean /** * (numbers_only_text) The type of limit on values entered for a number option. */ number_limit_mode?: 'lowest' | 'highest' | 'range' /** * (numbers_only_text) The lowest allowed value for a number option if `number_limited` is true. */ number_lowest_value?: number /** * (numbers_only_text) The highest allowed value for a number option if `number_limited` is true. */ number_highest_value?: number /** * (numbers_only_text) Flag to limit the input on a number option to whole numbers only. */ number_integers_only?: boolean /** * (product_list, product_list_with_images) Flag for automatically adjusting inventory on a product included in the list. */ product_list_adjusts_inventory?: boolean /** * (product_list, product_list_with_images) Flag to add the optional product's price to the main product's price. */ product_list_adjusts_pricing?: boolean /** * (product_list, product_list_with_images) How to factor the optional product's weight and package dimensions into the shipping quote. Values: `none` - don't adjust; `weight` - use shipping weight only; `package` - use weight and dimensions. */ product_list_shipping_calc?: 'none' | 'weight' | 'package' } /** * Adjuster for Complex Rules. */ adjuster_Full: { /** * The type of adjuster for either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster?: 'relative' | 'percentage' /** * The numeric amount by which the adjuster will change either the price or the weight of the variant, when the modifier value is selected on the storefront. */ adjuster_value?: number } /** * Errors during batch usage for the BigCommerce API. */ resp_variantBatchError: { batch_errors?: (definitions['error_Base'] & { errors?: { additionalProperties?: string } })[] } /** * Data about the response, including pagination and collection totals. */ metaCollection_Full: { pagination?: definitions['pagination_Full'] } /** * Data about the response, including pagination and collection totals. */ pagination_Full: { /** * Total number of items in the result set. */ total?: number /** * Total number of items in the collection response. */ count?: number /** * The amount of items returned in the collection per page, controlled by the limit parameter. */ per_page?: number /** * The page you are currently on within the collection. */ current_page?: number /** * The total number of pages in the collection. */ total_pages?: number /** * Pagination links for the previous and next parts of the whole collection. */ links?: { /** * Link to the previous page returned in the response. */ previous?: string /** * Link to the current page returned in the response. */ current?: string /** * Link to the next page returned in the response. */ next?: string } } /** * Empty meta object; may be used later. */ metaEmpty_Full: { [key: string]: any } errorResponse_Full: definitions['error_Base'] & { errors?: definitions['detailedErrors'] } /** * Error payload for the BigCommerce API. */ error_Base: { /** * The HTTP status code. */ status?: number /** * The error title describing the particular error. */ title?: string type?: string instance?: string } /** * Error payload for the BigCommerce API. */ errorNotFound: { /** * 404 HTTP status code. */ status?: number /** * The error title describing the particular error. */ title?: string type?: string instance?: string } /** * A gift-certificate model. */ giftCertificate_Full: { /** * The gift-certificate code. */ code?: string /** * The balance on a gift certificate when it was purchased. */ original_balance?: number /** * The balance on a gift certificate at the time of this purchase. */ starting_balance?: number /** * The remaining balance on a gift certificate. */ remaining_balance?: number /** * The status of a gift certificate: `active` - gift certificate is active; `pending` - gift certificate purchase is pending; `disabled` - gift certificate is disabled; `expired` - gift certificate is expired. */ status?: 'active' | 'pending' | 'disabled' | 'expired' } /** * No-content response for the BigCommerce API. */ errorNoContent: { /** * 204 HTTP status code. */ status?: number /** * The error title describing the situation. */ title?: string type?: string instance?: string } detailedErrors: { additionalProperties?: string } product_Full: definitions['product_Base'] & { /** * The date on which the product was created. */ date_created?: string /** * The date on which the product was modified. */ date_modified?: string /** * ID of the product. Read Only. */ id?: number /** * The unique identifier of the base variant associated with a simple product. This value is `null` for complex products. */ base_variant_id?: number /** * The price of the product as seen on the storefront. It will be equal to the `sale_price`, if set, and the `price` if there is not a `sale_price`. */ calculated_price?: number options?: definitions['productOption_Base'][] modifiers?: definitions['productModifier_Full'][] /** * Minimum Advertised Price. */ map_price?: number /** * Indicates that the product is in an Option Set (legacy V2 concept). */ option_set_id?: number /** * Legacy template setting which controls if the option set shows up to the side of or below the product image and description. */ option_set_display?: string } & { variants?: definitions['productVariant_Full'] } /** * Common ProductImage properties. */ productImage_Full: definitions['productImage_Base'] & { /** * The unique numeric ID of the image; increments sequentially. */ id?: number /** * The unique numeric identifier for the product with which the image is associated. */ product_id?: number /** * The zoom URL for this image. By default, this is used as the zoom image on product pages when zoom images are enabled. */ url_zoom?: string /** * The standard URL for this image. By default, this is used for product-page images. */ url_standard?: string /** * The thumbnail URL for this image. By default, this is the image size used on the category page and in side panels. */ url_thumbnail?: string /** * The tiny URL for this image. By default, this is the image size used for thumbnails beneath the product image on a product page. */ url_tiny?: string /** * The date on which the product image was modified. */ date_modified?: string } metafield_Post: definitions['metafield_Base'] /** * The model for batch updating products. */ product_Put_Collection: ({ /** * The unique numerical ID of the product; increments sequentially. Required on batch product `PUT` requests. */ id: number } & definitions['product_Base'])[] /** * The values for option config can vary based on the Modifier created. */ config_Full: { /** * (date, text, multi_line_text, numbers_only_text) The default value. Shown on a date option as an ISO-8601–formatted string, or on a text option as a string. */ default_value?: string /** * (checkbox) Flag for setting the checkbox to be checked by default. */ checked_by_default?: boolean /** * (checkbox) Label displayed for the checkbox option. */ checkbox_label?: string /** * (date) Flag to limit the dates allowed to be entered on a date option. */ date_limited?: boolean /** * (date) The type of limit that is allowed to be entered on a date option. */ date_limit_mode?: 'earliest' | 'range' | 'latest' /** * (date) The earliest date allowed to be entered on the date option, as an ISO-8601 formatted string. */ date_earliest_value?: string /** * (date) The latest date allowed to be entered on the date option, as an ISO-8601 formatted string. */ date_latest_value?: string /** * (file) The kind of restriction on the file types that can be uploaded with a file upload option. Values: `specific` - restricts uploads to particular file types; `all` - allows all file types. */ file_types_mode?: 'specific' | 'all' /** * (file) The type of files allowed to be uploaded if the `file_type_option` is set to `specific`. Values: * `images` - Allows upload of image MIME types (`bmp`, `gif`, `jpg`, `jpeg`, `jpe`, `jif`, `jfif`, `jfi`, `png`, `wbmp`, `xbm`, `tiff`). `documents` - Allows upload of document MIME types (`txt`, `pdf`, `rtf`, `doc`, `docx`, `xls`, `xlsx`, `accdb`, `mdb`, `one`, `pps`, `ppsx`, `ppt`, `pptx`, `pub`, `odt`, `ods`, `odp`, `odg`, `odf`). * `other` - Allows file types defined in the `file_types_other` array. */ file_types_supported?: string[] /** * (file) A list of other file types allowed with the file upload option. */ file_types_other?: string[] /** * (file) The maximum size for a file that can be used with the file upload option. This will still be limited by the server. */ file_max_size?: number /** * (text, multi_line_text) Flag to validate the length of a text or multi-line text input. */ text_characters_limited?: boolean /** * (text, multi_line_text) The minimum length allowed for a text or multi-line text option. */ text_min_length?: number /** * (text, multi_line_text) The maximum length allowed for a text or multi line text option. */ text_max_length?: number /** * (multi_line_text) Flag to validate the maximum number of lines allowed on a multi-line text input. */ text_lines_limited?: boolean /** * (multi_line_text) The maximum number of lines allowed on a multi-line text input. */ text_max_lines?: number /** * (numbers_only_text) Flag to limit the value of a number option. */ number_limited?: boolean /** * (numbers_only_text) The type of limit on values entered for a number option. */ number_limit_mode?: 'lowest' | 'highest' | 'range' /** * (numbers_only_text) The lowest allowed value for a number option if `number_limited` is true. */ number_lowest_value?: number /** * (numbers_only_text) The highest allowed value for a number option if `number_limited` is true. */ number_highest_value?: number /** * (numbers_only_text) Flag to limit the input on a number option to whole numbers only. */ number_integers_only?: boolean /** * (product_list, product_list_with_images) Flag for automatically adjusting inventory on a product included in the list. */ product_list_adjusts_inventory?: boolean /** * (product_list, product_list_with_images) Flag to add the optional product's price to the main product's price. */ product_list_adjusts_pricing?: boolean /** * (product_list, product_list_with_images) How to factor the optional product's weight and package dimensions into the shipping quote. Values: `none` - don't adjust; `weight` - use shipping weight only; `package` - use weight and dimensions. */ product_list_shipping_calc?: 'none' | 'weight' | 'package' } adjusters_Full: { price?: definitions['adjuster_Full'] weight?: definitions['adjuster_Full'] /** * The URL for an image displayed on the storefront when the modifier value is selected.Limit of 8MB per file. */ image_url?: string purchasing_disabled?: { /** * Flag for whether the modifier value disables purchasing when selected on the storefront. This can be used for temporarily disabling a particular modifier value. */ status?: boolean /** * The message displayed on the storefront when the purchasing disabled status is `true`. */ message?: string } } /** * Variant properties used on: * * `/catalog/products/variants` * * `/catalog/variants` */ variant_Base: { /** * The cost price of the variant. Not affected by Price List prices. */ cost_price?: number /** * This variant's base price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is `null`, the product's default price (set in the Product resource's `price` field) will be used as the base price. */ price?: number /** * This variant's sale price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is null, the product's sale price (set in the Product resource's `price` field) will be used as the sale price. */ sale_price?: number /** * This variant's retail price on the storefront. If a Price List ID is used, the Price List value will be used. If a Price List ID is not used, and this value is null, the product's retail price (set in the Product resource's `price` field) will be used as the retail price. */ retail_price?: number /** * This variant's base weight on the storefront. If this value is null, the product's default weight (set in the Product resource's weight field) will be used as the base weight. */ weight?: number /** * Width of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default width (set in the Product resource's `width` field) will be used as the base width. */ width?: number /** * Height of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default height (set in the Product resource's `height` field) will be used as the base height. */ height?: number /** * Depth of the variant, which can be used when calculating shipping costs. If this value is `null`, the product's default depth (set in the Product resource's `depth` field) will be used as the base depth. */ depth?: number /** * Flag used to indicate whether the variant has free shipping. If `true`, the shipping cost for the variant will be zero. */ is_free_shipping?: boolean /** * A fixed shipping cost for the variant. If defined, this value will be used during checkout instead of normal shipping-cost calculation. */ fixed_cost_shipping_price?: number /** * If `true`, this variant will not be purchasable on the storefront. */ purchasing_disabled?: boolean /** * If `purchasing_disabled` is `true`, this message should show on the storefront when the variant is selected. */ purchasing_disabled_message?: string /** * The UPC code used in feeds for shopping comparison sites and external channel integrations. */ upc?: string /** * Inventory level for the variant, which is used when the product's inventory_tracking is set to `variant`. */ inventory_level?: number /** * When the variant hits this inventory level, it is considered low stock. */ inventory_warning_level?: number /** * Identifies where in a warehouse the variant is located. */ bin_picking_number?: string } /** * Shared `Product` properties used in: * * `POST` * * `PUT` * * `GET` */ product_Base: { /** * The product name. */ name?: string /** * The product type. One of: `physical` - a physical stock unit, `digital` - a digital download. */ type?: 'physical' | 'digital' /** * User defined product code/stock keeping unit (SKU). */ sku?: string /** * The product description, which can include HTML formatting. */ description?: string /** * Weight of the product, which can be used when calculating shipping costs. This is based on the unit set on the store */ weight?: number /** * Width of the product, which can be used when calculating shipping costs. */ width?: number /** * Depth of the product, which can be used when calculating shipping costs. */ depth?: number /** * Height of the product, which can be used when calculating shipping costs. */ height?: number /** * The price of the product. The price should include or exclude tax, based on the store settings. */ price?: number /** * The cost price of the product. Stored for reference only; it is not used or displayed anywhere on the store. */ cost_price?: number /** * The retail cost of the product. If entered, the retail cost price will be shown on the product page. */ retail_price?: number /** * If entered, the sale price will be used instead of value in the price field when calculating the product's cost. */ sale_price?: number /** * The ID of the tax class applied to the product. (NOTE: Value ignored if automatic tax is enabled.) */ tax_class_id?: number /** * Accepts AvaTax System Tax Codes, which identify products and services that fall into special sales-tax categories. By using these codes, merchants who subscribe to BigCommerce's Avalara Premium integration can calculate sales taxes more accurately. Stores without Avalara Premium will ignore the code when calculating sales tax. Do not pass more than one code. The codes are case-sensitive. For details, please see Avalara's documentation. */ product_tax_code?: string /** * An array of IDs for the categories to which this product belongs. When updating a product, if an array of categories is supplied, all product categories will be overwritten. Does not accept more than 1,000 ID values. */ categories?: number[] /** * A product can be added to an existing brand during a product /PUT or /POST. */ brand_id?: number /** * Current inventory level of the product. Simple inventory tracking must be enabled (See the `inventory_tracking` field) for this to take any effect. */ inventory_level?: number /** * Inventory warning level for the product. When the product's inventory level drops below the warning level, the store owner will be informed. Simple inventory tracking must be enabled (see the `inventory_tracking` field) for this to take any effect. */ inventory_warning_level?: number /** * The type of inventory tracking for the product. Values are: `none` - inventory levels will not be tracked; `product` - inventory levels will be tracked using the `inventory_level` and `inventory_warning_level` fields; `variant` - inventory levels will be tracked based on variants, which maintain their own warning levels and inventory levels. */ inventory_tracking?: 'none' | 'product' | 'variant' /** * A fixed shipping cost for the product. If defined, this value will be used during checkout instead of normal shipping-cost calculation. */ fixed_cost_shipping_price?: number /** * Flag used to indicate whether the product has free shipping. If `true`, the shipping cost for the product will be zero. */ is_free_shipping?: boolean /** * Flag to determine whether the product should be displayed to customers browsing the store. If `true`, the product will be displayed. If `false`, the product will be hidden from view. */ is_visible?: boolean /** * Flag to determine whether the product should be included in the `featured products` panel when viewing the store. */ is_featured?: boolean /** * An array of IDs for the related products. */ related_products?: number[] /** * Warranty information displayed on the product page. Can include HTML formatting. */ warranty?: string /** * The BIN picking number for the product. */ bin_picking_number?: string /** * The layout template file used to render this product category. This field is writable only for stores with a Blueprint theme applied. */ layout_file?: string /** * The product UPC code, which is used in feeds for shopping comparison sites and external channel integrations. */ upc?: string /** * A comma-separated list of keywords that can be used to locate the product when searching the store. */ search_keywords?: string /** * Availability of the product. Availability options are: `available` - the product can be purchased on the storefront; `disabled` - the product is listed in the storefront, but cannot be purchased; `preorder` - the product is listed for pre-orders. */ availability?: 'available' | 'disabled' | 'preorder' /** * Availability text displayed on the checkout page, under the product title. Tells the customer how long it will normally take to ship this product, such as: 'Usually ships in 24 hours.' */ availability_description?: string /** * Type of gift-wrapping options. Values: `any` - allow any gift-wrapping options in the store; `none` - disallow gift-wrapping on the product; `list` – provide a list of IDs in the `gift_wrapping_options_list` field. */ gift_wrapping_options_type?: 'any' | 'none' | 'list' /** * A list of gift-wrapping option IDs. */ gift_wrapping_options_list?: number[] /** * Priority to give this product when included in product lists on category pages and in search results. Lower integers will place the product closer to the top of the results. */ sort_order?: number /** * The product condition. Will be shown on the product page if the `is_condition_shown` field's value is `true`. Possible values: `New`, `Used`, `Refurbished`. */ condition?: 'New' | 'Used' | 'Refurbished' /** * Flag used to determine whether the product condition is shown to the customer on the product page. */ is_condition_shown?: boolean /** * The minimum quantity an order must contain, to be eligible to purchase this product. */ order_quantity_minimum?: number /** * The maximum quantity an order can contain when purchasing the product. */ order_quantity_maximum?: number /** * Custom title for the product page. If not defined, the product name will be used as the meta title. */ page_title?: string /** * Custom meta keywords for the product page. If not defined, the store's default keywords will be used. */ meta_keywords?: string[] /** * Custom meta description for the product page. If not defined, the store's default meta description will be used. */ meta_description?: string /** * The number of times the product has been viewed. */ view_count?: number /** * Pre-order release date. See the `availability` field for details on setting a product's availability to accept pre-orders. */ preorder_release_date?: string /** * Custom expected-date message to display on the product page. If undefined, the message defaults to the storewide setting. Can contain the `%%DATE%%` placeholder, which will be substituted for the release date. */ preorder_message?: string /** * If set to true then on the preorder release date the preorder status will automatically be removed. * If set to false, then on the release date the preorder status **will not** be removed. It will need to be changed manually either in the * control panel or using the API. Using the API set `availability` to `available`. */ is_preorder_only?: boolean /** * False by default, indicating that this product's price should be shown on the product page. If set to `true`, the price is hidden. (NOTE: To successfully set `is_price_hidden` to `true`, the `availability` value must be `disabled`.) */ is_price_hidden?: boolean /** * By default, an empty string. If `is_price_hidden` is `true`, the value of `price_hidden_label` is displayed instead of the price. (NOTE: To successfully set a non-empty string value with `is_price_hidden` set to `true`, the `availability` value must be `disabled`.) */ price_hidden_label?: string custom_url?: definitions['customUrl_Full'] /** * Type of product, defaults to `product`. */ open_graph_type?: | 'product' | 'album' | 'book' | 'drink' | 'food' | 'game' | 'movie' | 'song' | 'tv_show' /** * Title of the product, if not specified the product name will be used instead. */ open_graph_title?: string /** * Description to use for the product, if not specified then the meta_description will be used instead. */ open_graph_description?: string /** * Flag to determine if product description or open graph description is used. */ open_graph_use_meta_description?: boolean /** * Flag to determine if product name or open graph name is used. */ open_graph_use_product_name?: boolean /** * Flag to determine if product image or open graph image is used. */ open_graph_use_image?: boolean /** * The brand can be created during a product PUT or POST request. If the brand already exists then the product will be added. If not the brand will be created and the product added. If using `brand_name` it performs a fuzzy match and adds the brand. eg. "Common Good" and "Common good" are the same. Brand name does not return as part of a product response. Only the `brand_id`. */ 'brand_name or brand_id'?: string /** * Global Trade Item Number */ gtin?: string /** * Manufacturer Part Number */ mpn?: string /** * The total rating for the product. */ reviews_rating_sum?: number /** * The number of times the product has been rated. */ reviews_count?: number /** * The total quantity of this product sold. */ total_sold?: number custom_fields?: definitions['productCustomField_Put'][] bulk_pricing_rules?: definitions['bulkPricingRule_Full'][] images?: definitions['productImage_Full'][] primary_image?: definitions['productImage_Full'] videos?: definitions['productVideo_Full'][] } /** * Properties for updating metafields. */ metafield_Put: { /** * Unique ID of the *Metafield*. Read-Only. */ id?: number } & definitions['metafield_Base'] metafield_Full: definitions['metafield_Put'] & { /** * Date and time of the metafield's creation. Read-Only. */ date_created?: string /** * Date and time when the metafield was last updated. Read-Only. */ date_modified?: string } /** * The model for a PUT to update variants on a product. */ productVariant_Put: definitions['productVariant_Base'] & { product_id?: number sku?: string } }
the_stack
import View from './progress.view'; import { getTimePercent, getOverallBufferedPercent, getOverallPlayedPercent, } from '../../../../utils/video-data'; import { VideoEvent, UIEvent, EngineState, LiveState, } from '../../../../constants'; import { AMOUNT_TO_SKIP_SECONDS } from '../../../keyboard-control/keyboard-control'; import KeyboardInterceptor, { KEYCODES, } from '../../../../utils/keyboard-interceptor'; import formatTime from '../../core/utils/formatTime'; import playerAPI from '../../../../core/player-api-decorator'; import { IEventEmitter } from '../../../event-emitter/types'; import { ITooltipService } from '../../core/tooltip/types'; import { IProgressControlAPI, IProgressControl, IProgressViewConfig, } from './types'; import { ITextMap } from '../../../text-map/types'; import { IPlaybackEngine } from '../../../playback-engine/types'; import { IPreviewThumbnail } from '../../preview-thumbnail/types'; import { IPreviewFullSize } from '../../preview-full-size/types'; import { IThemeService } from '../../core/theme'; export const UPDATE_PROGRESS_INTERVAL_DELAY = 1000 / 60; class ProgressControl implements IProgressControl { static moduleName = 'progressControl'; static View = View; static dependencies = [ 'engine', 'liveStateEngine', 'eventEmitter', 'textMap', 'tooltipService', 'theme', 'previewThumbnail', 'previewFullSize', ]; private _engine: IPlaybackEngine; private _liveStateEngine: any; private _eventEmitter: IEventEmitter; private _textMap: ITextMap; private _tooltipService: ITooltipService; private _theme: IThemeService; private _previewThumbnail: IPreviewThumbnail; private _previewFullSize: IPreviewFullSize; private _isUserDragging: boolean; private _shouldPlayAfterDragEnd: boolean; private _desiredSeekPosition: number; private _interceptor: KeyboardInterceptor; private _updateControlInterval: number; private _timeIndicatorsToAdd: number[]; private _shouldHidePreviewOnUpdate: boolean; private _showFullScreenPreview: boolean; private _unbindEvents: () => void; view: View; isHidden: boolean; constructor({ engine, liveStateEngine, eventEmitter, textMap, tooltipService, theme, previewThumbnail, previewFullSize, }: { eventEmitter: IEventEmitter; engine: IPlaybackEngine; liveStateEngine: any; textMap: ITextMap; tooltipService: ITooltipService; theme: IThemeService; previewThumbnail: IPreviewThumbnail; previewFullSize: IPreviewFullSize; }) { this._engine = engine; this._liveStateEngine = liveStateEngine; this._eventEmitter = eventEmitter; this._textMap = textMap; this._tooltipService = tooltipService; this._previewThumbnail = previewThumbnail; this._previewFullSize = previewFullSize; this._isUserDragging = false; this._desiredSeekPosition = 0; this._theme = theme; this._timeIndicatorsToAdd = []; this._showFullScreenPreview = false; this._bindCallbacks(); this._initUI(); this._bindEvents(); this.view.setPlayed(0); this.view.setBuffered(0); this._initInterceptor(); } getElement() { return this.view.getElement(); } private _bindEvents() { this._unbindEvents = this._eventEmitter.bindEvents( [ [VideoEvent.STATE_CHANGED, this._processStateChange], [VideoEvent.LIVE_STATE_CHANGED, this._processLiveStateChange], [VideoEvent.CHUNK_LOADED, this._updateBufferIndicator], [VideoEvent.DURATION_UPDATED, this._updateAllIndicators], [UIEvent.RESIZE, this.view.updateOnResize, this.view], ], this, ); } private _initUI() { const config: IProgressViewConfig = { callbacks: { onSyncWithLiveClick: this._syncWithLive, onSyncWithLiveMouseEnter: this._onSyncWithLiveMouseEnter, onSyncWithLiveMouseLeave: this._onSyncWithLiveMouseLeave, onChangePlayedPercent: this._onChangePlayedPercent, onSeekToByMouseStart: this._showTooltipAndPreview, onSeekToByMouseEnd: this._hideTooltip, onDragStart: this._startProcessingUserDrag, onDragEnd: this._stopProcessingUserDrag, }, theme: this._theme, textMap: this._textMap, tooltipService: this._tooltipService, }; this.view = new ProgressControl.View(config); } private _initInterceptor() { this._interceptor = new KeyboardInterceptor(this.view.getElement(), { [KEYCODES.UP_ARROW]: e => { e.stopPropagation(); e.preventDefault(); this._eventEmitter.emitAsync(UIEvent.KEYBOARD_KEYDOWN_INTERCEPTED); this._eventEmitter.emitAsync(UIEvent.GO_FORWARD_WITH_KEYBOARD); this._engine.seekForward(AMOUNT_TO_SKIP_SECONDS); }, [KEYCODES.DOWN_ARROW]: e => { e.stopPropagation(); e.preventDefault(); this._eventEmitter.emitAsync(UIEvent.KEYBOARD_KEYDOWN_INTERCEPTED); this._eventEmitter.emitAsync(UIEvent.GO_BACKWARD_WITH_KEYBOARD); this._engine.seekBackward(AMOUNT_TO_SKIP_SECONDS); }, [KEYCODES.RIGHT_ARROW]: e => { e.stopPropagation(); e.preventDefault(); this._eventEmitter.emitAsync(UIEvent.KEYBOARD_KEYDOWN_INTERCEPTED); this._eventEmitter.emitAsync(UIEvent.GO_FORWARD_WITH_KEYBOARD); this._engine.seekForward(AMOUNT_TO_SKIP_SECONDS); }, [KEYCODES.LEFT_ARROW]: e => { e.stopPropagation(); e.preventDefault(); this._eventEmitter.emitAsync(UIEvent.KEYBOARD_KEYDOWN_INTERCEPTED); this._eventEmitter.emitAsync(UIEvent.GO_BACKWARD_WITH_KEYBOARD); this._engine.seekBackward(AMOUNT_TO_SKIP_SECONDS); }, }); } private _destroyInterceptor() { this._interceptor.destroy(); } private _bindCallbacks() { this._syncWithLive = this._syncWithLive.bind(this); this._onSyncWithLiveMouseEnter = this._onSyncWithLiveMouseEnter.bind(this); this._onSyncWithLiveMouseLeave = this._onSyncWithLiveMouseLeave.bind(this); this._updateAllIndicators = this._updateAllIndicators.bind(this); this._onChangePlayedPercent = this._onChangePlayedPercent.bind(this); this._showTooltipAndPreview = this._showTooltipAndPreview.bind(this); this._hideTooltip = this._hideTooltip.bind(this); this._startProcessingUserDrag = this._startProcessingUserDrag.bind(this); this._stopProcessingUserDrag = this._stopProcessingUserDrag.bind(this); } private _startIntervalUpdates() { if (this._updateControlInterval) { this._stopIntervalUpdates(); } this._updateAllIndicators(); this._updateControlInterval = window.setInterval( this._updateAllIndicators, UPDATE_PROGRESS_INTERVAL_DELAY, ); } private _stopIntervalUpdates() { window.clearInterval(this._updateControlInterval); this._updateControlInterval = null; } private _convertPlayedPercentToTime(percent: number): number { const duration = this._engine.getDuration(); return (duration * percent) / 100; } private _onChangePlayedPercent(percent: number) { const newTime = this._convertPlayedPercentToTime(percent); if (this._showFullScreenPreview) { this._desiredSeekPosition = newTime; this._eventEmitter.emitAsync( UIEvent.PROGRESS_USER_PREVIEWING_FRAME, newTime, ); } else { this._changeCurrentTimeOfVideo(newTime); } if (this._isUserDragging) { this._showTooltipAndPreview(percent); } } private _showTooltipAndPreview(percent: number) { const duration = this._engine.getDuration(); const seekToTime = this._convertPlayedPercentToTime(percent); const timeToShow = this._engine.isDynamicContent ? seekToTime - duration : seekToTime; this._previewThumbnail.setTime(formatTime(timeToShow)); this._previewThumbnail.showAt(seekToTime); this.view.showProgressTimeTooltip( this._previewThumbnail.getElement(), percent, ); if (this._isUserDragging && this._showFullScreenPreview) { this._previewFullSize.showAt(seekToTime); } } private _hideTooltip() { if (!this._isUserDragging) { this.view.hideProgressTimeTooltip(); } } private _startProcessingUserDrag() { if (!this._isUserDragging) { this._isUserDragging = true; this._pauseVideoOnDragStart(); this._eventEmitter.emitAsync(UIEvent.PROGRESS_DRAG_STARTED); this._eventEmitter.emitAsync(UIEvent.CONTROL_DRAG_START); } } private _stopProcessingUserDrag() { if (this._isUserDragging) { this._isUserDragging = false; if (this._showFullScreenPreview) { this._shouldHidePreviewOnUpdate = true; } if (this._showFullScreenPreview) { this._changeCurrentTimeOfVideo(this._desiredSeekPosition); } this._playVideoOnDragEnd(); this.view.hideProgressTimeTooltip(); this._eventEmitter.emitAsync(UIEvent.PROGRESS_DRAG_ENDED); this._eventEmitter.emitAsync(UIEvent.CONTROL_DRAG_END); } } private _hidePreview() { this._shouldHidePreviewOnUpdate = false; this._previewFullSize.hide(); } private _processStateChange({ nextState }: { nextState: EngineState }) { switch (nextState) { case EngineState.SRC_SET: this._reset(); break; case EngineState.METADATA_LOADED: this._initTimeIndicators(); if (this._engine.isSeekAvailable) { this.show(); } else { this.hide(); } break; case EngineState.PLAYING: if (this._shouldHidePreviewOnUpdate) { this._hidePreview(); } if (this._liveStateEngine.state === LiveState.SYNC) { this.view.setPlayed(100); } else { this._startIntervalUpdates(); } break; case EngineState.PAUSED: if (this._shouldHidePreviewOnUpdate) { this._hidePreview(); } this._stopIntervalUpdates(); break; case EngineState.SEEK_IN_PROGRESS: this._updateAllIndicators(); break; default: break; } } private _processLiveStateChange({ nextState }: { nextState: LiveState }) { switch (nextState) { case LiveState.NONE: this.view.setLiveSyncState(false); this.view.setUsualMode(); break; case LiveState.INITIAL: this.view.setLiveMode(); break; case LiveState.SYNC: this.view.setLiveSyncState(true); break; case LiveState.NOT_SYNC: this.view.setLiveSyncState(false); break; case LiveState.ENDED: this.view.setLiveSyncState(false); this.view.hideSyncWithLive(); // ensure progress indicators show latest info if (this._engine.getCurrentState() === EngineState.PLAYING) { this._startIntervalUpdates(); } else { this._updateAllIndicators(); } break; default: break; } } private _changeCurrentTimeOfVideo(newTime: number) { const duration = this._engine.getDuration(); if (this._engine.isDynamicContent && duration === newTime) { this._engine.syncWithLive(); } else { this._engine.seekTo(newTime); } this._eventEmitter.emitAsync(UIEvent.PROGRESS_CHANGE, newTime); } private _pauseVideoOnDragStart() { const currentState = this._engine.getCurrentState(); if ( currentState === EngineState.PLAYING || currentState === EngineState.PLAY_REQUESTED ) { this._shouldPlayAfterDragEnd = true; this._engine.pause(); } this._eventEmitter.emitAsync(UIEvent.PROGRESS_DRAG_STARTED); } private _playVideoOnDragEnd() { if (this._shouldPlayAfterDragEnd) { this._engine.play(); this._shouldPlayAfterDragEnd = false; } } private _updateBufferIndicator() { const currentTime = this._engine.getCurrentTime(); const buffered = this._engine.getBuffered(); const duration = this._engine.getDuration(); this._setBuffered( getOverallBufferedPercent(buffered, currentTime, duration), ); } private _updatePlayedIndicator() { if (this._liveStateEngine.state === LiveState.SYNC) { // TODO: mb use this.updatePlayed(100) here? return; } const currentTime = this._engine.getCurrentTime(); const duration = this._engine.getDuration(); this._setPlayed(getOverallPlayedPercent(currentTime, duration)); } private _updateAllIndicators() { this._updatePlayedIndicator(); this._updateBufferIndicator(); } private _initTimeIndicators() { this._timeIndicatorsToAdd.forEach(time => { this._addTimeIndicator(time); }); this._timeIndicatorsToAdd = []; } private _addTimeIndicator(time: number) { const durationTime = this._engine.getDuration(); if (time > durationTime) { // TODO: log error for developers return; } this.view.addTimeIndicator(getTimePercent(time, durationTime)); } private _syncWithLive() { this._engine.syncWithLive(); } private _onSyncWithLiveMouseEnter() { this._eventEmitter.emitAsync(UIEvent.PROGRESS_SYNC_BUTTON_MOUSE_ENTER); } private _onSyncWithLiveMouseLeave() { this._eventEmitter.emitAsync(UIEvent.PROGRESS_SYNC_BUTTON_MOUSE_LEAVE); } private _setPlayed(percent: number) { this.view.setPlayed(percent); } private _setBuffered(percent: number) { this.view.setBuffered(percent); } private _reset() { this._setPlayed(0); this._setBuffered(0); this.clearTimeIndicators(); } /** * Player will show full screen preview instead of actual seek on video when user drag the progress control * @example * player.showPreviewOnProgressDrag(); */ @playerAPI() showPreviewOnProgressDrag() { this._showFullScreenPreview = true; } /** * Player will seek on video when user drag the progress control * @example * player.seekOnProgressDrag(); */ @playerAPI() seekOnProgressDrag() { this._showFullScreenPreview = false; } /** * Add time indicator to progress bar */ @playerAPI() addTimeIndicator(time: number) { this.addTimeIndicators([time]); } /** * Add time indicators to progress bar */ @playerAPI() addTimeIndicators(times: number[]) { if (!this._engine.isMetadataLoaded) { // NOTE: Add indicator after metadata loaded this._timeIndicatorsToAdd.push(...times); return; } times.forEach(time => { this._addTimeIndicator(time); }); } /** * Delete all time indicators from progress bar */ @playerAPI() clearTimeIndicators() { this.view.clearTimeIndicators(); } hide() { this.isHidden = true; this.view.hide(); } show() { this.isHidden = false; this.view.show(); } destroy() { this._destroyInterceptor(); this._stopIntervalUpdates(); this._unbindEvents(); this.view.destroy(); } } export { IProgressControlAPI }; export default ProgressControl;
the_stack
import { User } from './../../models/User'; import { LicenseScanResultItemService } from './../../services/license-scan-result-item/license-scan-result-item.service'; import { LicenseScanResultItem } from './../../models/LicenseScanResultItem'; import { Index, QueryRunner } from 'typeorm'; import { Project, ProjectScanStatusType, VulnerabilityStatusDeploymentType } from '@app/models'; import { ProjectScanStatusTypeService } from '@app/services/project-scan-status-type/project-scan-status-type.service'; import { ProjectService } from '@app/services/project/project.service'; import { Body, Controller, Get, Header, Param, Res, Post, Query, Request, UseGuards, UseInterceptors, Logger, } from '@nestjs/common'; import { ApiTags, ApiResponse, ApiQuery } from '@nestjs/swagger'; import { Response } from 'express'; import { Swagger } from '@nestjsx/crud/lib/crud'; import { Crud, CrudController, CrudRequest, CrudRequestInterceptor, GetManyDefaultResponse, Override, ParsedBody, ParsedRequest, } from '@nestjsx/crud'; import { makeBadge, ValidationError } from 'badge-maker'; @Crud({ model: { type: Project, }, routes: { only: ['getManyBase'], }, }) @ApiTags('Stats') @Controller('stats') export class StatsController implements CrudController<Project> { constructor(public service: ProjectService, private licenseScanResultItemService: LicenseScanResultItemService) {} get base(): CrudController<Project> { return this; } logger = new Logger('StatsContoller'); @Override() async getMany(@ParsedRequest() req: CrudRequest) { const answer = await this.service.getProjectsMany(req.parsed, req.options, null); return answer; } createFormat(label: string, value: string, status: string) { let color = status; if (status === 'unknown') { color = 'lightgrey'; value = 'unknown'; } const format = { label: label, message: value, color: color, labelColor: '#855', style: 'flat', }; return format; } async rawQuery<T = any[]>(query: string, parameters: object = {}): Promise<T> { const conn = this.service.db.manager.connection; const [escapedQuery, escapedParams] = conn.driver.escapeQueryWithParameters(query, parameters, {}); return conn.query(escapedQuery, escapedParams); } createSVG(format: any) { return makeBadge(format); } async getLatestScanDate(project: Project) { if (project) { const scan = await this.service.latestCompletedScan(project); if (scan) { return scan.createdAt.toDateString(); } } } @Get('/badges/:id/licensestate') @Header('Content-Type', 'image/svg+xml') @Header('Content-Disposition', 'attachment; filename=licensestate.svg') async getLicenseState(@Param('id') id: string, @Res() res: Response) { const project = await this.service.db.findOne(Number(id)); let licenseStatus = await ProjectScanStatusTypeService.Unknown(); let latestScanDate = 'unknown'; if (project) { const checklicenseStatus = await this.service.highestLicenseStatus(project); if (checklicenseStatus) { licenseStatus = checklicenseStatus; } latestScanDate = await this.getLatestScanDate(project); } const svg = this.createSVG(this.createFormat('barista license state', latestScanDate, licenseStatus.code)); return res .status(200) .send(svg) .end(); } @Get('/badges/:id/securitystate') @Header('Content-Type', 'image/svg+xml') @Header('Content-Disposition', 'attachment; filename=securitystate.svg') async getSecurityState(@Param('id') id: string, @Res() res: Response) { const project = await this.service.db.findOne(Number(id)); let securityStatus = await ProjectScanStatusTypeService.Unknown(); let latestScanDate = 'unknown'; if (project) { const checksecurityStatus = await this.service.highestSecurityStatus(project); if (checksecurityStatus) { securityStatus = checksecurityStatus; } latestScanDate = await this.getLatestScanDate(project); } const svg = this.createSVG(this.createFormat('barista security state', latestScanDate, securityStatus.code)); return res .status(200) .send(svg) .end(); } @Get('/badges/:id/vulnerabilities') @Header('Content-Type', 'image/svg+xml') @Header('Content-Disposition', 'attachment; filename=vulnerabilities.svg') async getvulnerabilities(@Param('id') id: string, @Res() res: Response) { const project = await this.service.db.findOne(Number(id)); let securityStatus = await ProjectScanStatusTypeService.Unknown(); let valueString = ''; if (project) { const vulnerabilities = await this.service.distinctSeverities(project); securityStatus = await this.service.highestSecurityStatus(project); if (vulnerabilities.length === 0) { valueString = 'none detected'; } vulnerabilities.forEach(vul => (valueString = valueString + vul.severity + ':' + vul.count + ' ')); } const svg = this.createSVG(this.createFormat('barista vulnerabilities', valueString, securityStatus.code)); return res .status(200) .send(svg) .end(); } @Get('/badges/:id/components') @Header('Content-Type', 'image/svg+xml') @Header('Content-Disposition', 'attachment; filename=components.svg') async getComponentsResults(@Param('id') id: string, @Res() res: Response) { const project = await this.service.db.findOne(Number(id)); let valueString = 'unknown'; let color = 'lightgrey'; if (project) { const scan = await this.service.latestCompletedScan(project); if (scan) { const query = await this.licenseScanResultItemService.db .createQueryBuilder('resultItem') .leftJoin('resultItem.licenseScan', 'licenseScan') .leftJoinAndSelect('resultItem.projectScanStatus', 'projectScanStatus') .leftJoinAndSelect('resultItem.license', 'license') .leftJoin('licenseScan.scan', 'scan') .where('scan.id = :id', { id: scan.id }) .getMany(); valueString = query.length.toString(); color = '#edb'; } } const svg = this.createSVG(this.createFormat('barista open source components', valueString, color)); return res .status(200) .send(svg) .end(); } // What are the top 10 component licenses in use and how many components are using each license? @Get('/components') @ApiQuery({ name: 'filterbyuser', required: false, type: String, }) @ApiResponse({ status: 200 }) async getTopComponents(@Query('filterbyuser') filterbyuser: string) { let userFilter = ''; let usergroups = []; if (filterbyuser) { usergroups = filterbyuser.split(','); userFilter = 'AND p2."userId" in (:...userId)'; } const query = `SELECT l2.name AS "name", COUNT(*) AS "value" FROM license l2, license_scan_result_item lsri, license_scan_result lsr, (SELECT DISTINCT ON (s2."projectId") s2.id, s2."projectId" FROM scan s2, project p2 WHERE p2.id = s2."projectId" AND p2.development_type_code = 'organization' ${userFilter} ORDER BY s2."projectId", s2.completed_at DESC) scan WHERE scan.id = lsr."scanId" AND lsri."licenseScanId" = lsr.id AND l2.id = lsri."licenseId" GROUP BY 1 ORDER BY 2 DESC LIMIT 10`; return await this.rawQuery<any>(query, { userId: usergroups }); } // What are the top 10 components in use and how many times is each used across all projects scanned? @Get('/components/scans') @ApiQuery({ name: 'filterbyuser', required: false, type: String, }) @ApiResponse({ status: 200 }) async getTopComponentScans(@Query('filterbyuser') filterbyuser: string) { let userFilter = ''; let usergroups = []; if (filterbyuser) { usergroups = filterbyuser.split(','); userFilter = 'AND p2."userId" in (:...userId)'; } const query = `SELECT lsri."displayIdentifier" AS name, COUNT(*) AS value FROM license l2, license_scan_result_item lsri, license_scan_result lsr, project p3, (SELECT DISTINCT ON (s2."projectId") s2.id, s2."projectId" FROM scan s2, project p2 WHERE p2.id = s2."projectId" AND p2.development_type_code = 'organization' ${userFilter} ORDER BY s2."projectId", s2.completed_at DESC) scan WHERE scan.id = lsr."scanId" AND lsri."licenseScanId" = lsr.id AND l2.id = lsri."licenseId" AND scan."projectId" = p3.id GROUP BY 1 ORDER BY COUNT(*) DESC, 1 LIMIT 10`; const stats = await this.rawQuery<any>(query, { userId: usergroups }); return stats; } // How many new projects are being added each month? @Get('/projects') @ApiQuery({ name: 'filterbyuser', required: false, type: String, }) @ApiResponse({ status: 200 }) async getMonthlyProjects(@Query('filterbyuser') filterbyuser: string) { let userFilter = ''; let usergroups = []; if (filterbyuser) { usergroups = filterbyuser.split(','); userFilter = 'AND p2."userId" in (:...userId)'; } const query = `SELECT date_trunc('month', p2.created_at::date)::date AS name, COUNT(*) AS value FROM project p2 WHERE p2.created_at > date_trunc('month', CURRENT_DATE) - INTERVAL '1 year' AND p2.development_type_code = 'organization' ${userFilter} GROUP BY 1 ORDER BY 1;`; const stats = await this.rawQuery<any>(query, { userId: usergroups }); return stats; } // How many project scans are being done each month? @Get('/projects/scans') @ApiQuery({ name: 'filterbyuser', required: false, type: String, }) @ApiResponse({ status: 200 }) async getMonthlyScans(@Query('filterbyuser') filterbyuser: string) { let userFilter = ''; let usergroups = []; if (filterbyuser) { usergroups = filterbyuser.split(','); userFilter = 'AND p2."userId" in (:...userId)'; } const query = `SELECT date_trunc('month', ssr.created_at::date)::date AS name, COUNT(*) AS value FROM security_scan_result ssr, project p2 WHERE ssr.created_at > date_trunc('month', CURRENT_DATE) - INTERVAL '1 year' AND p2.development_type_code = 'organization' ${userFilter} GROUP BY 1 ORDER BY 1 LIMIT 12;`; const stats = await this.rawQuery<any>(query, { userId: usergroups }); return stats; } // What are the top 10 critical vulnerabilities discovered across all projects scanned? @Get('/vulnerabilities') @ApiQuery({ name: 'filterbyuser', required: false, type: String, }) @ApiResponse({ status: 200 }) async getTopVulnerabilities(@Query('filterbyuser') filterbyuser: string) { let userFilter = ''; let usergroups = []; if (filterbyuser) { usergroups = filterbyuser.split(','); userFilter = 'AND p2."userId" in (:...userId)'; } const query = `SELECT DISTINCT ssri."path" AS "name", COUNT(*) AS value FROM project p2, security_scan_result_item ssri, security_scan_result ssr, (SELECT DISTINCT ON (s2."projectId" ) s2.id, s2."projectId" FROM scan s2 ORDER BY s2."projectId", s2.completed_at DESC) scan WHERE ssr."scanId" = scan.id AND ssri."securityScanId" = ssr."scanId" AND scan."projectId" = p2.id AND p2.development_type_code = 'organization' AND ssri."severity" IN ('CRITICAL','HIGH') ${userFilter} GROUP BY ssri."path" ORDER BY COUNT(*) DESC LIMIT 10`; const stats = await this.rawQuery<any>(query, { userId: usergroups }); return stats; } // What is our monthly license compliance index as defined by the formula: // total number of not approved licenses detected in scans (i.e. yellow or red status) divided by total number of approved licenses found in scans (i.e. green status) @Get('/licensenoncompliance/index') @ApiQuery({ name: 'filterbyuser', required: false, type: String, }) @ApiResponse({ status: 200 }) async getLicenseComplianceIndex(@Query('filterbyuser') filterbyuser: string) { let userFilter = ''; let usergroups = []; if (filterbyuser) { usergroups = filterbyuser.split(','); userFilter = 'AND p2."userId" in (:...userId)'; } const query1 = `SELECT COUNT(*) FROM license l2, license_scan_result_item lsri, license_scan_result lsr, (SELECT DISTINCT ON (s2."projectId") s2.id, s2."projectId" FROM scan s2, project p2 WHERE p2.id = s2."projectId" AND p2.development_type_code = 'organization' ${userFilter} ORDER BY s2."projectId", s2.completed_at DESC) scan WHERE scan.id = lsr."scanId" AND lsri."licenseScanId" = lsr.id AND l2.id = lsri."licenseId" AND lsri.project_scan_status_type_code <> 'green'`; const licenseProblemCount = await this.rawQuery<any>(query1, { userId: usergroups }); const query2 = `SELECT COUNT(*) FROM license l2, license_scan_result_item lsri, license_scan_result lsr, project p3, (SELECT DISTINCT ON (s2."projectId") s2.id, s2."projectId" FROM scan s2, project p2 WHERE p2.id = s2."projectId" AND p2.development_type_code = 'organization' ${userFilter} ORDER BY s2."projectId", s2.completed_at DESC) scan WHERE scan.id = lsr."scanId" AND lsri."licenseScanId" = lsr.id AND l2.id = lsri."licenseId" AND scan."projectId" = p3.id`; const licenseComponentCount = await this.rawQuery<any>(query2, { userId: usergroups }); if (licenseProblemCount.length > 0 && licenseComponentCount.length > 0 && licenseComponentCount[0].count > 0) { const licenseComplianceIndex = (licenseProblemCount[0].count / licenseComponentCount[0].count) * 100; return licenseComplianceIndex; } return -1; } // What is our monthly severe vulnerability index as defined by the formula: // total number of critical or high vulnerabilities detected in scans divided by total number of packages found in scans @Get('/highvulnerability/index') @ApiQuery({ name: 'filterbyuser', required: false, type: String, }) @ApiResponse({ status: 200 }) async getHighVulnerabilityIndex(@Query('filterbyuser') filterbyuser: string) { let userFilter = ''; let usergroups = []; if (filterbyuser) { usergroups = filterbyuser.split(','); userFilter = 'AND p2."userId" in (:...userId)'; } const query1 = `SELECT COUNT(*) FROM project p2, security_scan_result_item ssri, security_scan_result ssr, (SELECT DISTINCT ON (s2."projectId") s2.id, s2."projectId" FROM scan s2 ORDER BY s2."projectId", s2.completed_at DESC) scan WHERE ssr."scanId" = scan.id AND ssri."securityScanId" = ssr."scanId" AND scan."projectId" = p2.id AND p2.development_type_code = 'organization' AND ssri."severity" IN ('CRITICAL','HIGH') ${userFilter}`; const highVulnerabilityCount = await this.rawQuery<any>(query1, { userId: usergroups }); const query2 = `SELECT COUNT(*) FROM license l2, license_scan_result_item lsri, license_scan_result lsr, project p3, (SELECT DISTINCT ON (s2."projectId") s2.id, s2."projectId" FROM scan s2, project p2 WHERE p2.id = s2."projectId" AND p2.development_type_code = 'organization' ${userFilter} ORDER BY s2."projectId", s2.completed_at DESC) scan WHERE scan.id = lsr."scanId" AND lsri."licenseScanId" = lsr.id AND l2.id = lsri."licenseId" AND scan."projectId" = p3.id`; const licenseComponentCount = await this.rawQuery<any>(query2, { userId: usergroups }); if (highVulnerabilityCount.length > 0 && licenseComponentCount.length > 0 && licenseComponentCount[0].count > 0) { const highVulnerabilityIndex = (highVulnerabilityCount[0].count / licenseComponentCount[0].count) * 100; return highVulnerabilityIndex; } return -1; } }
the_stack
import { Socket } from 'net'; import * as iconv from 'iconv-lite'; import * as debug from 'debug'; import { RosException } from '../RosException'; const info = debug('routeros-api:connector:receiver:info'); const error = debug('routeros-api:connector:receiver:error'); const nullBuffer = Buffer.from([0x00]); export interface ISentence { sentence: string; hadMore: boolean; } /** * Interface of the callback which is stored * the tag readers with their respective callbacks */ export interface IReadCallback { name: string; callback: (data: string[]) => void; } /** * Class responsible for receiving and parsing the socket * data, sending to the readers and listeners */ export class Receiver { /** * The socket which connects to the routerboard */ private socket: Socket; /** * The registered tags to answer data to */ private tags: Map<string, IReadCallback> = new Map(); /** * The length of the current data chain received from * the socket */ private dataLength: number = 0; /** * A pipe of all responses received from the routerboard */ private sentencePipe: ISentence[] = []; /** * Flag if the sentencePipe is being processed to * prevent concurrent sentences breaking the pipe */ private processingSentencePipe: boolean = false; /** * The current line being processed from the data chain */ private currentLine: string = ''; /** * The current reply received for the tag */ private currentReply: string = ''; /** * The current tag which the routerboard responded */ private currentTag: string = ''; /** * The current data chain or packet */ private currentPacket: string[] = []; /** * Used to store a partial segment of the * length descriptor if it gets split * between tcp transmissions. */ private lengthDescriptorSegment: Buffer; /** * Receives the socket so we are able to read * the data sent to it, separating each tag * to the according listener. * * @param socket */ constructor(socket: Socket) { this.socket = socket; } /** * Register the tag as a reader so when * the routerboard respond to the command * related to the tag, we know where to send * the data to * * @param {string} tag * @param {function} callback */ public read(tag: string, callback: (packet: string[]) => void): void { info('Reader of %s tag is being set', tag); this.tags.set(tag, { name: tag, callback: callback, }); } /** * Stop reading from a tag, removing it * from the tag mapping. Usually it is closed * after the command has being !done, since each command * opens a new auto-generated tag * * @param {string} tag */ public stop(tag: string): void { info('Not reading from %s tag anymore', tag); this.tags.delete(tag); } /** * Proccess the raw buffer data received from the routerboard, * decode using win1252 encoded string from the routerboard to * utf-8, so languages with accentuation works out of the box. * * After reading each sentence from the raw packet, sends it * to be parsed * * @param {Buffer} data */ public processRawData(data: Buffer): void { if (this.lengthDescriptorSegment) { data = Buffer.concat([this.lengthDescriptorSegment, data]); this.lengthDescriptorSegment = null; } // Loop through the data we just received while (data.length > 0) { // If this does not contain the beginning of a packet... if (this.dataLength > 0) { // If the length of the data we have in our buffer // is less than or equal to that reported by the // bytes used to dermine length... if (data.length <= this.dataLength) { // Subtract the data we are taking from the length we desire this.dataLength -= data.length; // Add this data to our current line this.currentLine += iconv.decode(data, 'win1252'); // If there is no more desired data we want... if (this.dataLength === 0) { // Push the data to the sentance this.sentencePipe.push({ sentence: this.currentLine, hadMore: data.length !== this.dataLength, }); // process the sentance and clear the line this.processSentence(); this.currentLine = ''; } // Break out of processRawData and wait for the next // set of data from the socket break; // If we have more data than we desire... } else { // slice off the part that we desire const tmpBuffer = data.slice(0, this.dataLength); // decode this segment const tmpStr = iconv.decode(tmpBuffer, 'win1252'); // Add this to our current line this.currentLine += tmpStr; // save our line... const line = this.currentLine; // clear the current line this.currentLine = ''; // cut off the line we just pulled out data = data.slice(this.dataLength); // determine the length of the next word. This method also // returns the number of bytes it took to describe the length const [descriptor_length, length] = this.decodeLength(data); // If we do not have enough data to determine // the length... we wait for the next loop // and store the length descriptor segment if (descriptor_length > data.length) { this.lengthDescriptorSegment = data; } // Save this as our next desired length this.dataLength = length; // slice off the bytes used to describe the length data = data.slice(descriptor_length); // If we only desire one more and its the end of the sentance... if (this.dataLength === 1 && data.equals(nullBuffer)) { this.dataLength = 0; data = data.slice(1); // get rid of excess buffer } this.sentencePipe.push({ sentence: line, hadMore: data.length > 0, }); this.processSentence(); } // This is the beginning of this packet... // This ALWAYS gets run first } else { // returns back the start index of the data and the length const [descriptor_length, length] = this.decodeLength(data); // store how long our data is this.dataLength = length; // slice off the bytes used to describe the length data = data.slice(descriptor_length); if (this.dataLength === 1 && data.equals(nullBuffer)) { this.dataLength = 0; data = data.slice(1); // get rid of excess buffer } } } } /** * Process each sentence from the data packet received. * * Detects the .tag of the packet, sending the data to the * related tag when another reply is detected or if * the packet had no more lines to be processed. * */ private processSentence(): void { if (!this.processingSentencePipe) { info('Got asked to process sentence pipe'); this.processingSentencePipe = true; const process = () => { if (this.sentencePipe.length > 0) { const line = this.sentencePipe.shift(); if (!line.hadMore && this.currentReply === '!fatal') { this.socket.emit('fatal'); return; } info('Processing line %s', line.sentence); if (/^\.tag=/.test(line.sentence)) { this.currentTag = line.sentence.substring(5); } else if (/^!/.test(line.sentence)) { if (this.currentTag) { info( 'Received another response, sending current data to tag %s', this.currentTag, ); this.sendTagData(this.currentTag); } this.currentPacket.push(line.sentence); this.currentReply = line.sentence; } else { this.currentPacket.push(line.sentence); } if ( this.sentencePipe.length === 0 && this.dataLength === 0 ) { if (!line.hadMore && this.currentTag) { info( 'No more sentences to process, will send data to tag %s', this.currentTag, ); this.sendTagData(this.currentTag); } else { info('No more sentences and no data to send'); } this.processingSentencePipe = false; } else { process(); } } else { this.processingSentencePipe = false; } }; process(); } } /** * Send the data collected from the tag to the * tag reader */ private sendTagData(currentTag: string): void { const tag = this.tags.get(currentTag); if (tag) { info( 'Sending to tag %s the packet %O', tag.name, this.currentPacket, ); tag.callback(this.currentPacket); } else { throw new RosException('UNREGISTEREDTAG'); } this.cleanUp(); } /** * Clean the current packet, tag and reply state * to start over */ private cleanUp(): void { this.currentPacket = []; this.currentTag = null; this.currentReply = null; } /** * Decodes the length of the buffer received * * Credits for George Joseph: https://github.com/gtjoseph * and for Brandon Myers: https://github.com/Trakkasure * * @param {Buffer} data */ private decodeLength(data: Buffer): number[] { let len; let idx = 0; const b = data[idx++]; if (b & 128) { if ((b & 192) === 128) { len = ((b & 63) << 8) + data[idx++]; } else { if ((b & 224) === 192) { len = ((b & 31) << 8) + data[idx++]; len = (len << 8) + data[idx++]; } else { if ((b & 240) === 224) { len = ((b & 15) << 8) + data[idx++]; len = (len << 8) + data[idx++]; len = (len << 8) + data[idx++]; } else { len = data[idx++]; len = (len << 8) + data[idx++]; len = (len << 8) + data[idx++]; len = (len << 8) + data[idx++]; } } } } else { len = b; } return [idx, len]; } }
the_stack
import { RotationCorrection } from '../../input/OcrExtractor'; import { findMostCommonFont, isInBox } from '../../utils'; import logger from '../../utils/Logger'; import { BoundingBox } from './BoundingBox'; import { Character } from './Character'; import { Drawing } from './Drawing'; import { Element } from './Element'; import { Font } from './Font'; import { Image } from './Image'; import { Paragraph } from './Paragraph'; import { Text } from './Text'; import { Word } from './Word'; export type directionType = 'horizontal' | 'vertical'; /** * A page in a document is represented by the Page class, which contains a list of elements, vertical and horizontal * occupancy areas, and a page number. */ export class Page { // Syntactic sugars for getters and setters public set left(value: number) { this.box.left = value; } public get left(): number { return this.box.left; } public set top(value: number) { this.box.top = value; } public get top(): number { return this.box.top; } public set width(value: number) { this.box.width = value; } public get width(): number { return this.box.width; } public set height(value: number) { this.box.height = value; } public get height(): number { return this.box.height; } private _pageNumber: number; private _elements: Element[]; private _box: BoundingBox; private _horizontalOccupancy: boolean[]; private _verticalOccupancy: boolean[]; private _pageRotation: RotationCorrection; constructor(pageNumber: number, elements: Element[], boundingBox: BoundingBox) { this.pageNumber = pageNumber; this.elements = elements; this.box = boundingBox; this.horizontalOccupancy = []; this.verticalOccupancy = []; this.pageRotation = null; this.computePageOccupancy(); } public getMainRotationAngle(): number { const rotations = this.getElementsOfType<Word>(Word, true).map(word => { if (Array.isArray(word.content) && word.content.length > 1) { const { left: x1, bottom: y1 } = word.content[0] as Character; const { left: x2, bottom: y2 } = word.content[word.content.length - 1] as Character; const arcTan = Math.round((Math.atan((y1 - y2) / (x1 - x2)) * 180) / Math.PI); return arcTan === 0 ? (x1 < x2 ? 0 : 180) : arcTan; } return 0; }); if (rotations.length === 0) { return 0; } const elementsPerRotation = rotations.reduce((acc, value) => { acc[value] = acc[value] || 0; acc[value] += 1; return acc; }, {}); const highestValue: number = Math.max(...(Object.values(elementsPerRotation) as number[])); const mainRotation = Object.keys(elementsPerRotation).find( k => elementsPerRotation[k] === highestValue, ); return parseInt(mainRotation, 10); } /** * Computes all horizontal and vertical page occupancies */ public computePageOccupancy() { this.horizontalOccupancy = Array<boolean>(Math.floor(this.box.height)).fill(false); this.verticalOccupancy = Array<boolean>(Math.floor(this.box.width)).fill(false); const horizontalBarriers: number[][] = this.getBarriers('horizontal'); horizontalBarriers.forEach(a => { for (let i = Math.floor(a[0]); i <= Math.floor(a[1]) + 1; ++i) { if (!this.horizontalOccupancy[i]) { this.horizontalOccupancy[i] = true; } } }); const verticalBarriers: number[][] = this.getBarriers('vertical'); verticalBarriers.forEach(a => { for (let i = Math.floor(a[0]); i <= Math.floor(a[1]) + 1; ++i) { if (!this.verticalOccupancy[i]) { this.verticalOccupancy[i] = true; } } }); } /** * Return the coordinates of each of the elements in a given list. * @param elements The list of elements for which locations need to be returned. * @param returnCenters Boolean indicating if the centers of the elements should be returned as location. */ public getLocationOfElements(elements: Element[], returnCenters: boolean = false): number[][] { if (returnCenters) { return elements.map((elem: Element) => [ elem.box.left + elem.box.width / 2, elem.box.top + elem.box.height / 2, ]); } else { return elements.map((elem: Element) => [elem.box.left, elem.box.top]); } } /** * Return the subset of all the elements inside a rectangle defining a subset of the given page. * @param box Elements of the subset should be inside this bounding box. * @param textOnly Elements of the subset should only be the textual elements. * @param strict if true, returned elements will be fully inside the box. */ public getElementsSubset(box: BoundingBox, textOnly: boolean = true, strict: boolean = true): Element[] { return this.elements.filter(e => e instanceof Text || !textOnly).filter(e => isInBox(e, box, strict)); } /** * Get first level text elements only * * @return {Text[]} */ public getTexts(): Text[] { return this.elements.filter(e => e instanceof Text) as Text[]; } /** * Get a list of elements of type in the current Page instance. Pre-ordered. * * @param type Type of the Element we want to list * @param deepSearch Allows searching all elements of type even if are placed as content of other element type * @return the list of matching Elements */ public getElementsOfType<T extends Element>( type: new (...args: any[]) => T, deepSearch: boolean = true, ): T[] { const result: T[] = new Array<T>(); this.preOrderTraversal((element: Element) => { if (element instanceof type) { result.push(element); } }, deepSearch); return result; } /** * Get all the elements of this page */ public getAllElements(): Element[] { const result: Element[] = new Array<Element>(); this.preOrderTraversal((element: Element) => { result.push(element); }); return result; } /** * Pre-order traversal, calling back when a node is traversed. * * @param preOrderCallback yield the Element. * @param deepSearch Allows searching all elements of type even if are placed in content of other element type */ public preOrderTraversal( preOrderCallback: (element: Element) => void, deepSearch: boolean = true, ): void { let stack: Element[] = Array.from(this.elements); while (stack.length > 0) { const element = stack.shift(); preOrderCallback(element); if ( deepSearch && element.content && typeof element.content !== 'string' && element.content.length !== 0 ) { stack = stack.concat(element.content); } } } /** * Removes an element from the page * @param e The element which is to be removed */ public removeElement(e: Element) { const index: number = this.elements.indexOf(e, 0); if (index > -1 || e !== undefined) { this.elements.splice(index, 1); } else { logger.debug( `--> Could not remove element id "${e.id}" in first level elements on page \ ${this.pageNumber}; it might be located deeper`, ); } } /** * Getter horizontalOccupancy * @return {boolean[]} */ public get horizontalOccupancy(): boolean[] { return this._horizontalOccupancy; } /** * Setter horizontalOccupancy * @param {boolean[]} value */ public set horizontalOccupancy(value: boolean[]) { this._horizontalOccupancy = value; } /** * Getter verticalOccupancy * @return {boolean[]} */ public get verticalOccupancy(): boolean[] { return this._verticalOccupancy; } /** * Setter verticalOccupancy * @param {boolean[]} value */ public set verticalOccupancy(value: boolean[]) { this._verticalOccupancy = value; } /** * Getter elements * @return {Element[]} */ public get elements(): Element[] { return this._elements; } /** * Getter pageNumber * @return {number} */ public get pageNumber(): number { return this._pageNumber; } /** * Getter box * @return {BoundingBox} */ public get box(): BoundingBox { return this._box; } /** * Setter elements * @param {Element[]} value */ public set elements(value: Element[]) { this._elements = value; } /** * Setter pageNumber * @param {number} value */ public set pageNumber(value: number) { this._pageNumber = value; } /** * Setter box * @param {BoundingBox} value */ public set box(value: BoundingBox) { this._box = value; } /** * Setter PageRotation * @param {RotationCorrection} value */ public set pageRotation(value: RotationCorrection) { this._pageRotation = value; } /** * Getter PageRotation * @return {RotationCorrection} */ public get pageRotation(): RotationCorrection { return this._pageRotation; } /** * Returns the main font of the page using the paragraphs' basket + voting * mechanism. The most used font will be returned as a valid Font object. */ public getMainFont(): Font | undefined { const result: Font = findMostCommonFont( this.getElementsOfType<Paragraph>(Paragraph, false) .map(p => p.getMainFont()) .filter(f => f !== undefined), ); if (result !== undefined) { return result; } else { logger.debug(`no font found for page ${this.pageNumber}`); return undefined; } } /** * Returns an array of type [[start:number, end:number]], representing blocks of occupied space along a * particular direction of the page. * @param direction Direction along which (horizontal or vertical) the barriers should be returned */ private getBarriers(direction: directionType): number[][] { let barriers: number[][] = []; if (direction === 'horizontal') { barriers = this.elements .filter((elem: Element) => !(elem instanceof Image) && !(elem instanceof Drawing)) .map((elem: Element) => elem.box) .map((b: BoundingBox) => { const start: number = b.top; const end: number = b.top + b.height; return [start, end]; }); } else { barriers = this.elements .filter((elem: Element) => !(elem instanceof Image) && !(elem instanceof Drawing)) .map((elem: Element) => elem.box) .map((b: BoundingBox) => { const start: number = b.left; const end: number = b.left + b.width; return [start, end]; }); } return barriers; } }
the_stack
import { mkdirSync, readFileSync } from 'fs'; import * as fse from 'fs-extra'; import path from 'path'; import * as _ from 'lodash'; import kebabCase from 'lodash/kebabCase'; import * as yargs from 'yargs'; import { ReactDocgenApi } from 'react-docgen'; import { findPages, findPagesMarkdown, findComponents } from 'docs/src/modules/utils/find'; import { getHeaders } from '@mui/markdown'; import { Styles } from 'docs/src/modules/utils/parseStyles'; import * as ttp from 'typescript-to-proptypes'; import { getGeneralPathInfo, getMaterialPathInfo, getBasePathInfo } from './buildApiUtils'; import buildComponentApi, { writePrettifiedFile } from './ApiBuilders/ComponentApiBuilder'; const apiDocsTranslationsDirectory = path.resolve('docs', 'translations', 'api-docs'); interface ReactApi extends ReactDocgenApi { /** * list of page pathnames * @example ['/components/Accordion'] */ demos: readonly string[]; EOL: string; filename: string; apiUrl: string; forwardsRefTo: string | undefined; inheritance: { component: string; pathname: string } | null; /** * react component name * @example 'Accordion' */ name: string; description: string; spread: boolean | undefined; /** * result of path.readFileSync from the `filename` in utf-8 */ src: string; styles: Styles; propsTable: _.Dictionary<{ default: string | undefined; required: boolean | undefined; type: { name: string | undefined; description: string | undefined }; deprecated: true | undefined; deprecationInfo: string | undefined; }>; translations: { componentDescription: string; propDescriptions: { [key: string]: string | undefined }; classDescriptions: { [key: string]: { description: string; conditions?: string } }; }; } async function removeOutdatedApiDocsTranslations(components: readonly ReactApi[]): Promise<void> { const componentDirectories = new Set<string>(); const files = await fse.readdir(apiDocsTranslationsDirectory); await Promise.all( files.map(async (filename) => { const filepath = path.join(apiDocsTranslationsDirectory, filename); const stats = await fse.stat(filepath); if (stats.isDirectory()) { componentDirectories.add(filepath); } }), ); const currentComponentDirectories = new Set( components.map((component) => { return path.resolve(apiDocsTranslationsDirectory, kebabCase(component.name)); }), ); const outdatedComponentDirectories = new Set(componentDirectories); currentComponentDirectories.forEach((componentDirectory) => { outdatedComponentDirectories.delete(componentDirectory); }); await Promise.all( Array.from(outdatedComponentDirectories, (outdatedComponentDirectory) => { return fse.remove(outdatedComponentDirectory); }), ); } interface Settings { input: { /** * Component directories to be used to generate API */ libDirectory: string[]; /** * The directory to get api pathnames to generate pagesApi */ pageDirectory: string; /** * The directory that contains markdown files to be used to find demos * related to the processed component */ markdownDirectory: string; }; output: { /** * API page + json content output directory */ pagesDirectory: string; /** * The output path of `pagesApi` generated from `input.pageDirectory` */ apiManifestPath: string; }; productUrlPrefix: string; getPathInfo: (filename: string) => { apiUrl: string; demoUrl: string }; } /** * This is the refactored version of the current API building process, nothing's changed. */ const BEFORE_MIGRATION_SETTINGS: Settings[] = [ { input: { libDirectory: [ path.join(process.cwd(), 'packages/mui-base/src'), path.join(process.cwd(), 'packages/mui-material/src'), path.join(process.cwd(), 'packages/mui-lab/src'), ], pageDirectory: path.join(process.cwd(), 'docs/pages'), markdownDirectory: path.join(process.cwd(), 'docs/src/pages'), }, output: { pagesDirectory: path.join(process.cwd(), 'docs/pages/api-docs'), apiManifestPath: path.join(process.cwd(), 'docs/src/pagesApi.js'), }, productUrlPrefix: '', getPathInfo: getGeneralPathInfo, }, ]; /** * Once the preparation is done (as described in https://github.com/mui-org/material-ui/issues/30091), swithc to this settings. * It will generate API for the current & `/material` paths, then set the redirect to link `/api/*` to `/material/api/*` * At this point, `mui-base` content is still live in with `mui-material`. */ // @ts-ignore // eslint-disable-next-line @typescript-eslint/no-unused-vars const MIGRATION_SETTINGS: Settings[] = [ ...BEFORE_MIGRATION_SETTINGS, { input: { libDirectory: [ path.join(process.cwd(), 'packages/mui-base/src'), path.join(process.cwd(), 'packages/mui-material/src'), path.join(process.cwd(), 'packages/mui-lab/src'), ], pageDirectory: path.join(process.cwd(), 'docs/pages/material'), markdownDirectory: path.join(process.cwd(), 'docs/data'), }, output: { pagesDirectory: path.join(process.cwd(), 'docs/pages/material/api-docs'), apiManifestPath: path.join(process.cwd(), 'docs/data/material/pagesApi.js'), }, productUrlPrefix: '/material', getPathInfo: getMaterialPathInfo, }, ]; /** * Once redirects are stable * - Create `mui-base` content in `docs/pages/base/*` and switch to this settings. * - Remove old content directories, eg. `docs/pages/components/*`, ...etc */ // @ts-ignore // eslint-disable-next-line @typescript-eslint/no-unused-vars const POST_MIGRATION_SETTINGS: Settings[] = [ { input: { libDirectory: [ path.join(process.cwd(), 'packages/mui-material/src'), path.join(process.cwd(), 'packages/mui-lab/src'), ], pageDirectory: path.join(process.cwd(), 'docs/pages/material'), markdownDirectory: path.join(process.cwd(), 'docs/data'), }, output: { pagesDirectory: path.join(process.cwd(), 'docs/pages/material/api-docs'), apiManifestPath: path.join(process.cwd(), 'docs/data/material/pagesApi.js'), }, productUrlPrefix: '/material', getPathInfo: getMaterialPathInfo, }, { input: { libDirectory: [path.join(process.cwd(), 'packages/mui-base/src')], pageDirectory: path.join(process.cwd(), 'docs/pages/base'), markdownDirectory: path.join(process.cwd(), 'docs/data'), }, output: { pagesDirectory: path.join(process.cwd(), 'docs/pages/base/api-docs'), apiManifestPath: path.join(process.cwd(), 'docs/data/base/pagesApi.js'), }, productUrlPrefix: '/base', getPathInfo: getBasePathInfo, }, // add other products, eg. joy, data-grid, ...etc ]; const ACTIVE_SETTINGS = BEFORE_MIGRATION_SETTINGS; async function run(argv: { grep?: string }) { const grep = argv.grep == null ? null : new RegExp(argv.grep); let allBuilds: Array<PromiseSettledResult<ReactApi | null>> = []; await ACTIVE_SETTINGS.reduce(async (resolvedPromise, setting) => { const workspaceRoot = path.resolve(__dirname, '../../'); /** * @type {string[]} */ const componentDirectories = setting.input.libDirectory; const apiPagesManifestPath = setting.output.apiManifestPath; const pagesDirectory = setting.output.pagesDirectory; mkdirSync(pagesDirectory, { mode: 0o777, recursive: true }); const manifestDir = apiPagesManifestPath.match(/(.*)\/[^/]+\./)?.[1]; if (manifestDir) { mkdirSync(manifestDir, { recursive: true }); } /** * pageMarkdown: Array<{ components: string[]; filename: string; pathname: string }> * * e.g.: * [{ * pathname: '/components/accordion', * filename: '/Users/user/Projects/material-ui/docs/src/pages/components/badges/accordion-ja.md', * components: [ 'Accordion', 'AccordionActions', 'AccordionDetails', 'AccordionSummary' ] * }, ...] */ const pagesMarkdown = findPagesMarkdown(setting.input.markdownDirectory) .map((markdown) => { const markdownSource = readFileSync(markdown.filename, 'utf8'); return { ...markdown, pathname: setting.getPathInfo(markdown.filename).demoUrl, components: getHeaders(markdownSource).components, }; }) .filter((markdown) => markdown.components.length > 0); /** * components: Array<{ filename: string }> * e.g. * [{ filename: '/Users/user/Projects/material-ui/packages/mui-material/src/Accordion/Accordion.js'}, ...] */ const components = componentDirectories .reduce((directories, componentDirectory) => { return directories.concat(findComponents(componentDirectory)); }, [] as ReadonlyArray<{ filename: string }>) .filter((component) => { if (component.filename.includes('ThemeProvider')) { return false; } if (grep === null) { return true; } return grep.test(component.filename); }); const tsconfig = ttp.loadConfig(path.resolve(workspaceRoot, './tsconfig.json')); const program = ttp.createTSProgram( components.map((component) => { if (component.filename.endsWith('.tsx')) { return component.filename; } if (component.filename.endsWith('.js')) { return component.filename.replace(/\.js$/, '.d.ts'); } throw new TypeError( `Unexpected component filename '${component.filename}'. Expected either a .tsx or .js file.`, ); }), tsconfig, ); const componentBuilds = components.map(async (component) => { try { const { filename } = component; const pathInfo = setting.getPathInfo(filename); return buildComponentApi(filename, { ttpProgram: program, pagesMarkdown, apiUrl: pathInfo.apiUrl, productUrlPrefix: setting.productUrlPrefix, outputPagesDirectory: setting.output.pagesDirectory, }); } catch (error: any) { error.message = `${path.relative(process.cwd(), component.filename)}: ${error.message}`; throw error; } }); const builds = await Promise.allSettled(componentBuilds); const fails = builds.filter( (promise): promise is PromiseRejectedResult => promise.status === 'rejected', ); fails.forEach((build) => { console.error(build.reason); }); if (fails.length > 0) { process.exit(1); } allBuilds = [...allBuilds, ...builds]; const pages = findPages({ front: true }, setting.input.pageDirectory); const apiPages = pages.find(({ pathname }) => pathname.indexOf('api') !== -1)?.children; if (apiPages === undefined) { throw new TypeError('Unable to find pages under /api'); } const source = `module.exports = ${JSON.stringify(apiPages)}`; writePrettifiedFile(apiPagesManifestPath, source); await resolvedPromise; }, Promise.resolve()); if (grep === null) { const componentApis = allBuilds .filter((build): build is PromiseFulfilledResult<ReactApi> => { return build.status === 'fulfilled' && build.value !== null; }) .map((build) => { return build.value; }); await removeOutdatedApiDocsTranslations(componentApis); } } yargs .command({ command: '$0', describe: 'formats codebase', builder: (command) => { return command.option('grep', { description: 'Only generate files for component filenames matching the pattern. The string is treated as a RegExp.', type: 'string', }); }, handler: run, }) .help() .strict(true) .version(false) .parse();
the_stack
import { CommonModule } from '@angular/common'; import { async, discardPeriodicTasks, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { BrowserTestingModule } from '@angular/platform-browser/testing'; import { buildComponent, MzTestWrapperComponent } from '../../shared/test-wrapper'; import { MzErrorMessageComponent } from '../../validation/error-message/error-message.component'; import { ErrorMessageResource } from '../../validation/error-message/models/error-message'; import { MzValidationComponent } from '../../validation/validation.component'; import { MzSelectDirective } from '../select.directive'; import { MzSelectContainerComponent } from './select-container.component'; describe('MzSelectContainerComponent:view', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ BrowserTestingModule, CommonModule, FormsModule, NoopAnimationsModule, ReactiveFormsModule, ], declarations: [ MzErrorMessageComponent, MzSelectContainerComponent, MzSelectDirective, MzTestWrapperComponent, MzValidationComponent, ], }); TestBed.overrideModule(BrowserDynamicTestingModule, { set: { entryComponents: [MzErrorMessageComponent], }, }); })); describe('input-field', () => { let nativeElement: any; function inputField(): HTMLElement { return nativeElement.querySelector('.input-field'); } it('should have inline css class when inline is true', async(() => { buildComponent<MzSelectContainerComponent>(` <mz-select-container [inline]="true"></mz-select-container> `).then((fixture) => { nativeElement = fixture.nativeElement; fixture.detectChanges(); expect(inputField().classList).toContain('inline'); }); })); it('should not have inline css class when inline is false', async(() => { buildComponent<MzSelectContainerComponent>(` <mz-select-container [inline]="false"></mz-select-container> `).then((fixture) => { nativeElement = fixture.nativeElement; fixture.detectChanges(); expect(inputField().classList).not.toContain('inline'); }); })); it('should transclude correctly', async(() => { buildComponent<MzSelectContainerComponent>(` <mz-select-container> content-x </mz-select-container> `).then((fixture) => { nativeElement = fixture.nativeElement; fixture.detectChanges(); expect(inputField().innerText.trim()).toBe('content-x'); }); })); }); describe('input.select-dropdown', () => { let nativeElement: any; let formBuilder: FormBuilder; let formGroup: FormGroup; function errorMessageElement(): HTMLElement { return nativeElement.querySelector('mz-error-message div'); } function inputElement(): HTMLInputElement { return nativeElement.querySelector('input.select-dropdown'); } function selectElement(): HTMLSelectElement { return nativeElement.querySelector('select'); } it('should be disabled/enabled correctly when control disabled status changes', async(() => { buildComponent<any>(` <form [formGroup]="formGroup"> <mz-select-container> <select mz-select formControlName="formControl"></select> </mz-select-container> </form>`, ).then((fixture) => { formBuilder = TestBed.get(FormBuilder); formGroup = formBuilder.group({ 'formControl': null, }); fixture.componentInstance.formGroup = formGroup; nativeElement = fixture.nativeElement; [true, false].forEach(disabled => { if (disabled) { formGroup.get('formControl').disable(); } else { formGroup.get('formControl').enable(); } fixture.detectChanges(); expect(inputElement().disabled).toBe(disabled); }); }); })); it('should set control as touched and call setValidationState when control is reset', fakeAsync(() => { const errorMessageResource: ErrorMessageResource = { required: 'Required', }; buildComponent<any>(` <form [formGroup]="formGroup"> <mz-select-container> <select mz-select mz-validation required id="select" formControlName="formControl" [errorMessageResource]="errorMessageResource" [label]="'label'" [placeholder]="'placeholder'"> <option>Option 1</option> </select> </mz-select-container> </form>`, { errorMessageResource, }, ).then((fixture) => { formBuilder = TestBed.get(FormBuilder); formGroup = formBuilder.group({ 'formControl': [null, Validators.required], }); fixture.componentInstance.formGroup = formGroup; nativeElement = fixture.nativeElement; fixture.detectChanges(); $(inputElement()).trigger('blur'); tick(400); fixture.detectChanges(); discardPeriodicTasks(); expect(inputElement().classList).toContain('invalid'); expect(errorMessageElement()).toBeTruthy(); expect(errorMessageElement().innerHTML.trim()).toBeTruthy(errorMessageResource.required); }); })); it('should have correctly value when control value changes using string value', fakeAsync(() => { buildComponent<{ value: string }>(` <mz-select-container> <select mz-select id="select" [label]="'label'" [placeholder]="'placeholder'" [(ngModel)]="value"> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </select> </mz-select-container>`, { value: 'Option 1', }, ).then((fixture) => { nativeElement = fixture.nativeElement; const component = fixture.componentInstance; fixture.detectChanges(); tick(); expect(inputElement().value).toBe('Option 1'); component.value = 'Option 2'; fixture.detectChanges(); tick(); expect(inputElement().value).toBe('Option 2'); component.value = null; fixture.detectChanges(); tick(); expect(inputElement().value).toBe('placeholder'); }); })); it('should have correctly value when control value changes using object value', fakeAsync(() => { interface Option { text: string; value: number; } const options = [ { text: 'Option 1', value: 1 }, { text: 'Option 2', value: 2 }, { text: 'Option 3', value: 3 }, ]; const value = options[0]; buildComponent<{ options: Option[], value: Option }>(` <mz-select-container> <select mz-select id="select" [label]="'label'" [placeholder]="'placeholder'" [(ngModel)]="value"> <option *ngFor="let option of options" [ngValue]="option">{{ option.text }}</option> </select> </mz-select-container>`, { options, value, }, ).then((fixture) => { nativeElement = fixture.nativeElement; const component = fixture.componentInstance; fixture.autoDetectChanges(); // couldn't force mutationobserver to execute before the end of the test // therefore options used with *ngFor need to be present for the test to work $('select').material_select(); fixture.detectChanges(); tick(); expect(inputElement().value).toBe('Option 1'); component.value = options[1]; fixture.detectChanges(); tick(); expect(inputElement().value).toBe('Option 2'); component.value = null; fixture.detectChanges(); tick(); expect(inputElement().value).toBe('placeholder'); }); })); describe('multiple select', () => { it('should have correctly value when control value changes using string value', fakeAsync(() => { buildComponent<{ value: string[] }>(` <mz-select-container> <select mz-select multiple id="select" [label]="'label'" [placeholder]="'placeholder'" [(ngModel)]="value"> <option *ngFor="let option of options" [value]="option">{{ option }}</option> </select> </mz-select-container>`, { options: ['Option 1', 'Option 2', 'Option 3'], value: ['Option 2', 'Option 3'], }, ).then((fixture) => { nativeElement = fixture.nativeElement; const component = fixture.componentInstance; fixture.detectChanges(); tick(); expect(inputElement().value).toBe('Option 2, Option 3'); component.value = ['Option 1']; fixture.detectChanges(); tick(); expect(inputElement().value).toBe('Option 1'); component.value = null; fixture.detectChanges(); tick(); expect(inputElement().value).toBe('placeholder'); }); })); it('should have correctly value when control value changes using object value', fakeAsync(() => { interface Option { text: string; value: number; } const options: Option[] = [ { text: 'Option 1', value: 1 }, { text: 'Option 2', value: 2 }, { text: 'Option 3', value: 3 }, ]; const value = options.slice(0, 1); buildComponent<{ options: Option[], value: Option[] }>(` <mz-select-container> <select mz-select multiple id="select" [label]="'label'" [placeholder]="'placeholder'" [(ngModel)]="value"> <option *ngFor="let option of options" [ngValue]="option">{{ option.text }}</option> </select> </mz-select-container>`, { options, value, }, ).then((fixture) => { nativeElement = fixture.nativeElement; const component = fixture.componentInstance; fixture.detectChanges(); // couldn't force mutationobserver to execute before the end of the test // therefore options used with *ngFor need to be present for the test to work $('select').material_select(); fixture.detectChanges(); tick(); expect(inputElement().value).toBe('Option 1'); component.value = options.slice(1, 3); fixture.detectChanges(); tick(); expect(inputElement().value).toBe('Option 2, Option 3'); component.value = null; fixture.detectChanges(); tick(); expect(inputElement().value).toBe('placeholder'); }); })); }); }); });
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * Sample result definition */ export interface Result { /** * Sample property of type string */ sampleProperty?: string; } /** * Error definition. */ export interface ErrorDefinition { /** * Service specific error code which serves as the substatus for the HTTP error code. */ code: string; /** * Description of the error. */ message: string; } /** * Error response. */ export interface ErrorResponse { /** * Error definition. */ error?: ErrorDefinition; } /** * Compliance Status details */ export interface ComplianceStatus { /** * The compliance state of the configuration. Possible values include: 'Pending', 'Compliant', * 'Noncompliant', 'Installed', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly complianceState?: ComplianceStateType; /** * Datetime the configuration was last applied. */ lastConfigApplied?: Date; /** * Message from when the configuration was applied. */ message?: string; /** * Level of the message. Possible values include: 'Error', 'Warning', 'Information' */ messageLevel?: MessageLevelType; } /** * Properties for Helm operator. */ export interface HelmOperatorProperties { /** * Version of the operator Helm chart. */ chartVersion?: string; /** * Values override for the operator Helm chart. */ chartValues?: string; } /** * Metadata pertaining to creation and last modification of the resource. */ export interface SystemData { /** * The identity that created the resource. */ createdBy?: string; /** * The type of identity that created the resource. Possible values include: 'User', * 'Application', 'ManagedIdentity', 'Key' */ createdByType?: CreatedByType; /** * The timestamp of resource creation (UTC). */ createdAt?: Date; /** * The identity that last modified the resource. */ lastModifiedBy?: string; /** * The type of identity that last modified the resource. Possible values include: 'User', * 'Application', 'ManagedIdentity', 'Key' */ lastModifiedByType?: CreatedByType; /** * The type of identity that last modified the resource. */ lastModifiedAt?: Date; } /** * Common fields that are returned in the response for all Azure Resource Manager resources * @summary Resource */ export interface Resource extends BaseResource { /** * Fully qualified resource ID for the resource. Ex - * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The name of the resource * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or * "Microsoft.Storage/storageAccounts" * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * The resource model definition for a Azure Resource Manager proxy resource. It will not have tags * and a location * @summary Proxy Resource */ export interface ProxyResource extends Resource { } /** * The SourceControl Configuration object returned in Get & Put response. */ export interface SourceControlConfiguration extends ProxyResource { /** * Url of the SourceControl Repository. */ repositoryUrl?: string; /** * The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric * characters, hyphen and period only. Default value: 'default'. */ operatorNamespace?: string; /** * Instance name of the operator - identifying the specific configuration. */ operatorInstanceName?: string; /** * Type of the operator. Possible values include: 'Flux' */ operatorType?: OperatorType; /** * Any Parameters for the Operator instance in string format. */ operatorParams?: string; /** * Name-value pairs of protected configuration settings for the configuration */ configurationProtectedSettings?: { [propertyName: string]: string }; /** * Scope at which the operator will be installed. Possible values include: 'cluster', * 'namespace'. Default value: 'cluster'. */ operatorScope?: OperatorScopeType; /** * Public Key associated with this SourceControl configuration (either generated within the * cluster or provided by the user). * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly repositoryPublicKey?: string; /** * Base64-encoded known_hosts contents containing public SSH keys required to access private Git * instances */ sshKnownHostsContents?: string; /** * Option to enable Helm Operator for this git configuration. */ enableHelmOperator?: boolean; /** * Properties for Helm operator. */ helmOperatorProperties?: HelmOperatorProperties; /** * The provisioning state of the resource provider. Possible values include: 'Accepted', * 'Deleting', 'Running', 'Succeeded', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: ProvisioningStateType; /** * Compliance Status of the Configuration * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly complianceStatus?: ComplianceStatus; /** * Top level metadata * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources */ systemData?: SystemData; } /** * Display metadata associated with the operation. */ export interface ResourceProviderOperationDisplay { /** * Resource provider: Microsoft KubernetesConfiguration. */ provider?: string; /** * Resource on which the operation is performed. */ resource?: string; /** * Type of operation: get, read, delete, etc. */ operation?: string; /** * Description of this operation. */ description?: string; } /** * Supported operation of this resource provider. */ export interface ResourceProviderOperation { /** * Operation name, in format of {provider}/{resource}/{operation} */ name?: string; /** * Display metadata associated with the operation. */ display?: ResourceProviderOperationDisplay; /** * The flag that indicates whether the operation applies to data plane. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isDataAction?: boolean; } /** * The resource model definition for an Azure Resource Manager tracked top level resource which has * 'tags' and a 'location' * @summary Tracked Resource */ export interface TrackedResource extends Resource { /** * Resource tags. */ tags?: { [propertyName: string]: string }; /** * The geo-location where the resource lives */ location: string; } /** * The resource model definition for an Azure Resource Manager resource with an etag. * @summary Entity Resource */ export interface AzureEntityResource extends Resource { /** * Resource Etag. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly etag?: string; } /** * An interface representing SourceControlConfigurationClientOptions. */ export interface SourceControlConfigurationClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * Result of the request to list Source Control Configurations. It contains a list of * SourceControlConfiguration objects and a URL link to get the next set of results. * @extends Array<SourceControlConfiguration> */ export interface SourceControlConfigurationList extends Array<SourceControlConfiguration> { /** * URL to get the next set of configuration objects, if any. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * Result of the request to list operations. * @extends Array<ResourceProviderOperation> */ export interface ResourceProviderOperationList extends Array<ResourceProviderOperation> { /** * URL to the next set of results, if any. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * Defines values for ComplianceStateType. * Possible values include: 'Pending', 'Compliant', 'Noncompliant', 'Installed', 'Failed' * @readonly * @enum {string} */ export type ComplianceStateType = 'Pending' | 'Compliant' | 'Noncompliant' | 'Installed' | 'Failed'; /** * Defines values for MessageLevelType. * Possible values include: 'Error', 'Warning', 'Information' * @readonly * @enum {string} */ export type MessageLevelType = 'Error' | 'Warning' | 'Information'; /** * Defines values for OperatorType. * Possible values include: 'Flux' * @readonly * @enum {string} */ export type OperatorType = 'Flux'; /** * Defines values for OperatorScopeType. * Possible values include: 'cluster', 'namespace' * @readonly * @enum {string} */ export type OperatorScopeType = 'cluster' | 'namespace'; /** * Defines values for ProvisioningStateType. * Possible values include: 'Accepted', 'Deleting', 'Running', 'Succeeded', 'Failed' * @readonly * @enum {string} */ export type ProvisioningStateType = 'Accepted' | 'Deleting' | 'Running' | 'Succeeded' | 'Failed'; /** * Defines values for CreatedByType. * Possible values include: 'User', 'Application', 'ManagedIdentity', 'Key' * @readonly * @enum {string} */ export type CreatedByType = 'User' | 'Application' | 'ManagedIdentity' | 'Key'; /** * Defines values for ClusterRp. * Possible values include: 'Microsoft.ContainerService', 'Microsoft.Kubernetes' * @readonly * @enum {string} */ export type ClusterRp = 'Microsoft.ContainerService' | 'Microsoft.Kubernetes'; /** * Defines values for ClusterResourceName. * Possible values include: 'managedClusters', 'connectedClusters' * @readonly * @enum {string} */ export type ClusterResourceName = 'managedClusters' | 'connectedClusters'; /** * Defines values for ClusterRp1. * Possible values include: 'Microsoft.ContainerService', 'Microsoft.Kubernetes' * @readonly * @enum {string} */ export type ClusterRp1 = 'Microsoft.ContainerService' | 'Microsoft.Kubernetes'; /** * Defines values for ClusterResourceName1. * Possible values include: 'managedClusters', 'connectedClusters' * @readonly * @enum {string} */ export type ClusterResourceName1 = 'managedClusters' | 'connectedClusters'; /** * Defines values for ClusterRp2. * Possible values include: 'Microsoft.ContainerService', 'Microsoft.Kubernetes' * @readonly * @enum {string} */ export type ClusterRp2 = 'Microsoft.ContainerService' | 'Microsoft.Kubernetes'; /** * Defines values for ClusterResourceName2. * Possible values include: 'managedClusters', 'connectedClusters' * @readonly * @enum {string} */ export type ClusterResourceName2 = 'managedClusters' | 'connectedClusters'; /** * Defines values for ClusterRp3. * Possible values include: 'Microsoft.ContainerService', 'Microsoft.Kubernetes' * @readonly * @enum {string} */ export type ClusterRp3 = 'Microsoft.ContainerService' | 'Microsoft.Kubernetes'; /** * Defines values for ClusterResourceName3. * Possible values include: 'managedClusters', 'connectedClusters' * @readonly * @enum {string} */ export type ClusterResourceName3 = 'managedClusters' | 'connectedClusters'; /** * Contains response data for the get operation. */ export type SourceControlConfigurationsGetResponse = SourceControlConfiguration & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SourceControlConfiguration; }; }; /** * Contains response data for the createOrUpdate operation. */ export type SourceControlConfigurationsCreateOrUpdateResponse = SourceControlConfiguration & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SourceControlConfiguration; }; }; /** * Contains response data for the list operation. */ export type SourceControlConfigurationsListResponse = SourceControlConfigurationList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SourceControlConfigurationList; }; }; /** * Contains response data for the listNext operation. */ export type SourceControlConfigurationsListNextResponse = SourceControlConfigurationList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SourceControlConfigurationList; }; }; /** * Contains response data for the list operation. */ export type OperationsListResponse = ResourceProviderOperationList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ResourceProviderOperationList; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = ResourceProviderOperationList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ResourceProviderOperationList; }; };
the_stack
import { ApiResource, ApiScope, ApiScopeUserClaim, ApiScopesDTO, IdentityResource, IdentityResourcesDTO, ResourcesService, IdentityResourceUserClaim, ApiResourcesDTO, ApiResourceSecretDTO, ApiResourceSecret, ApiResourceScope, ApiResourceAllowedScopeDTO, ApiResourceUserClaim, UserClaimDTO, ApiScopeGroup, ApiScopeGroupDTO, PagedRowsDto, Domain, DomainDTO, } from '@island.is/auth-api-lib' import { BadRequestException, Body, Controller, Delete, Get, Param, Post, Put, Query, UseGuards, } from '@nestjs/common' import { ApiCreatedResponse, ApiOkResponse, ApiQuery, ApiTags, getSchemaPath, } from '@nestjs/swagger' import type { User } from '@island.is/auth-nest-tools' import { IdsUserGuard, ScopesGuard, Scopes, CurrentUser, } from '@island.is/auth-nest-tools' import { AuthAdminScope } from '@island.is/auth/scopes' import { Audit, AuditService } from '@island.is/nest/audit' import { environment } from '../../../environments/' const namespace = `${environment.audit.defaultNamespace}/resources` @UseGuards(IdsUserGuard, ScopesGuard) @ApiTags('resources') @Controller('backend') @Audit({ namespace }) export class ResourcesController { constructor( private readonly resourcesService: ResourcesService, private readonly auditService: AuditService, ) {} /** Gets all Identity Resources and count of rows */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('identity-resources') @ApiQuery({ name: 'page', required: true }) @ApiQuery({ name: 'count', required: true }) @ApiOkResponse({ schema: { allOf: [ { properties: { count: { type: 'number', example: 1, }, rows: { type: 'array', items: { $ref: getSchemaPath(IdentityResource) }, }, }, }, ], }, }) @Audit<PagedRowsDto<IdentityResource>>({ resources: (result) => result.rows.map((resource) => resource.name), }) async findAndCountAllIdentityResources( @Query('page') page: number, @Query('count') count: number, ): Promise<PagedRowsDto<IdentityResource>> { return this.resourcesService.findAndCountAllIdentityResources(page, count) } /** Gets all Api Scopes and count of rows */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('api-scopes') @ApiQuery({ name: 'page', required: true }) @ApiQuery({ name: 'count', required: true }) @ApiOkResponse({ schema: { allOf: [ { properties: { count: { type: 'number', example: 1, }, rows: { type: 'array', items: { $ref: getSchemaPath(ApiScope) }, }, }, }, ], }, }) @Audit<PagedRowsDto<ApiScope>>({ resources: (result) => result.rows.map((scope) => scope.name), }) async findAndCountAllApiScopes( @Query('page') page: number, @Query('count') count: number, ): Promise<PagedRowsDto<ApiScope>> { return this.resourcesService.findAndCountAllApiScopes(page, count) } /** Finds all access controlled scopes */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('access-controlled-scopes') @ApiOkResponse({ type: [ApiScope] }) @Audit<ApiScope[]>({ resources: (scopes) => scopes.map((scope) => scope.name), }) async findAllAccessControlledApiScopes(): Promise<ApiScope[]> { return this.resourcesService.findAllAccessControlledApiScopes() } /** Get's all Api resources and total count of rows */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('api-resources') @ApiQuery({ name: 'searchString', required: false }) @ApiQuery({ name: 'page', required: true }) @ApiQuery({ name: 'count', required: true }) @ApiOkResponse({ schema: { allOf: [ { properties: { count: { type: 'number', example: 1, }, rows: { type: 'array', items: { $ref: getSchemaPath(ApiResource) }, }, }, }, ], }, }) @Audit<PagedRowsDto<ApiResource>>({ resources: (result) => result.rows.map((resource) => resource.name), }) async findAndCountAllApiResources( @Query('searchString') searchString: string, @Query('page') page: number, @Query('count') count: number, ): Promise<PagedRowsDto<ApiResource>> { if (searchString) { return this.resourcesService.findApiResources(searchString, page, count) } return this.resourcesService.findAndCountAllApiResources(page, count) } /** Get's all Api resources and total count of rows */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('all-api-resources') @ApiOkResponse({ type: [ApiResource] }) @Audit<ApiResource[]>({ resources: (resources) => resources.map((resource) => resource.name), }) async findAllApiResources(): Promise<ApiResource[]> { return this.resourcesService.findAllApiResources() } /** Gets Identity Resources by Scope Names */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('identity-resources/scopenames') @ApiQuery({ name: 'scopeNames', required: false }) @ApiOkResponse({ type: IdentityResource, isArray: true }) @Audit<IdentityResource[]>({ resources: (resources) => resources.map((resource) => resource.name), }) async findIdentityResourcesByScopeName( @Query('scopeNames') scopeNames: string, ): Promise<IdentityResource[]> { return this.resourcesService.findIdentityResourcesByScopeName( scopeNames ? scopeNames.split(',') : null, ) // TODO: Check if we can use ParseArrayPipe from v7 } /** Gets Api Scopes by Scope Names */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('api-scopes/scopenames') @ApiQuery({ name: 'scopeNames', required: false }) @ApiOkResponse({ type: ApiScope, isArray: true }) @Audit<ApiScope[]>({ resources: (scopes) => scopes.map((scope) => scope.name), }) async findApiScopesByNameAsync( @Query('scopeNames') scopeNames: string, ): Promise<ApiScope[]> { return this.resourcesService.findApiScopesByNameAsync( scopeNames ? scopeNames.split(',') : null, ) // TODO: Check if we can use ParseArrayPipe from v7 } /** Gets Api Resources by either Api Resource Names or Api Scope Names */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('api-resources/names') @ApiQuery({ name: 'apiResourceNames', required: false }) @ApiQuery({ name: 'apiScopeNames', required: false }) @ApiOkResponse({ type: ApiResource, isArray: true }) @Audit<ApiResource[]>({ resources: (resources) => resources.map((resource) => resource.name), }) async findApiResourcesByNameAsync( @Query('apiResourceNames') apiResourceNames: string, @Query('apiScopeNames') apiScopeNames: string, ): Promise<ApiResource[]> { if (apiResourceNames && apiScopeNames) { throw new Error( 'Specifying both apiResourceNames and apiScopeNames is not supported.', ) } if (apiResourceNames) { return this.resourcesService.findApiResourcesByNameAsync( apiResourceNames.split(','), ) // TODO: Check if we can use ParseArrayPipe from v7 } return this.resourcesService.findApiResourcesByScopeNameAsync( apiScopeNames ? apiScopeNames.split(',') : null, ) // TODO: Check if we can use ParseArrayPipe from v7 } @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('identity-resource/:id') @Audit<IdentityResource>({ resources: (resource) => resource?.name, }) async getIdentityResourceByName( @Param('id') name: string, ): Promise<IdentityResource> { return this.resourcesService.getIdentityResourceByName(name) } /** Creates a new Identity Resource */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Post('identity-resource') @ApiCreatedResponse({ type: IdentityResource }) @Audit<IdentityResource>({ resources: (resource) => resource.name, }) async createIdentityResource( @Body() identityResource: IdentityResourcesDTO, ): Promise<IdentityResource> { return this.resourcesService.createIdentityResource(identityResource) } /** Updates an existing Identity Resource by it's name */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Put('identity-resource/:name') @ApiOkResponse({ type: IdentityResource }) async updateIdentityResource( @Body() identityResource: IdentityResourcesDTO, @Param('name') name: string, @CurrentUser() user: User, ): Promise<IdentityResource> { if (!name) { throw new BadRequestException('Name must be provided') } return this.auditService.auditPromise( { user, action: 'updateIdentityResource', namespace, resources: name, meta: { fields: Object.keys(identityResource) }, }, this.resourcesService.updateIdentityResource(identityResource, name), ) } /** Deletes an existing Identity Resource by it's name */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Delete('identity-resource/:name') async deleteIdentityResource( @Param('name') name: string, @CurrentUser() user: User, ): Promise<number> { if (!name) { throw new BadRequestException('Name must be provided') } return this.auditService.auditPromise( { user, action: 'deleteIdentityResource', namespace, resources: name, }, this.resourcesService.deleteIdentityResource(name), ) } /** Gets all Identity Resource User Claims */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('identity-resource-user-claim') @ApiOkResponse({ type: [IdentityResourceUserClaim] }) @Audit<IdentityResourceUserClaim[]>({ resources: (resources) => resources.map((resource) => resource.identityResourceName), }) async findAllIdentityResourceUserClaims(): Promise< IdentityResourceUserClaim[] > { return this.resourcesService.findAllIdentityResourceUserClaims() } /** Creates a new Identity Resource User Claim */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Post('identity-resource-user-claim') @ApiCreatedResponse({ type: IdentityResourceUserClaim }) @Audit<IdentityResourceUserClaim>({ resources: (claim) => claim.identityResourceName, }) async createIdentityResourceUserClaim( @Body() claim: UserClaimDTO, ): Promise<IdentityResourceUserClaim> { return this.resourcesService.createIdentityResourceUserClaim(claim) } /** Gets all Api Scope User Claims */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('api-scope-user-claim') @ApiOkResponse({ type: [ApiScopeUserClaim] }) @Audit<ApiScopeUserClaim[]>({ resources: (claims) => claims.map((claim) => claim.apiScopeName), }) async findAllApiScopeUserClaims(): Promise<ApiScopeUserClaim[]> { return this.resourcesService.findAllApiScopeUserClaims() } /** Creates a new Api Resource User Claim */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Post('api-resource-user-claim') @ApiCreatedResponse({ type: ApiResourceUserClaim }) @Audit<ApiResourceUserClaim>({ resources: (claim) => claim.apiResourceName, }) async createApiResourceUserClaim( @Body() claim: UserClaimDTO, ): Promise<ApiResourceUserClaim> { return this.resourcesService.createApiResourceUserClaim(claim) } /** Gets all Api Resource User Claims */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('api-resource-user-claim') @ApiOkResponse({ type: [ApiResourceUserClaim] }) @Audit<ApiResourceUserClaim>({ resources: (claim) => claim.apiResourceName, }) async findAllApiResourceUserClaims(): Promise<ApiResourceUserClaim[]> { return this.resourcesService.findAllApiResourceUserClaims() } /** Creates a new Api Scope User Claim */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Post('api-scope-user-claim') @ApiCreatedResponse({ type: ApiScopeUserClaim }) @Audit<ApiScopeUserClaim>({ resources: (claim) => claim.apiScopeName, }) async createApiScopeUserClaim( @Body() claim: UserClaimDTO, ): Promise<ApiScopeUserClaim> { return this.resourcesService.createApiScopeUserClaim(claim) } /** Creates a new Api Scope */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Post('api-scope') @ApiCreatedResponse({ type: ApiScope }) @Audit<ApiScope>({ resources: (scope) => scope.name, }) async createApiScope(@Body() apiScope: ApiScopesDTO): Promise<ApiScope> { return this.resourcesService.createApiScope(apiScope) } /** Creates a new Api Resource */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Post('api-resource') @ApiCreatedResponse({ type: ApiResource }) @Audit<ApiResource>({ resources: (resource) => resource.name, }) async createApiResource( @Body() apiResource: ApiResourcesDTO, ): Promise<ApiResource> { return this.resourcesService.createApiResource(apiResource) } /** Updates an existing Api Scope */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Put('api-scope/:name') @ApiOkResponse({ type: ApiScope }) async updateApiScope( @Body() apiScope: ApiScopesDTO, @Param('name') name: string, @CurrentUser() user: User, ): Promise<ApiScope> { if (!name) { throw new BadRequestException('Name must be provided') } return this.auditService.auditPromise( { user, action: 'updateApiScope', namespace, resources: name, meta: { fields: Object.keys(apiScope) }, }, this.resourcesService.updateApiScope(apiScope, name), ) } /** Updates an existing Api Scope */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Put('api-resource/:name') @ApiOkResponse({ type: ApiResource }) async updateApiResource( @Body() apiResource: ApiResourcesDTO, @Param('name') name: string, @CurrentUser() user: User, ): Promise<ApiResource> { if (!name) { throw new BadRequestException('Name must be provided') } return this.auditService.auditPromise( { user, action: 'updateApiResource', namespace, resources: name, meta: { fields: Object.keys(apiResource) }, }, this.resourcesService.updateApiResource(apiResource, name), ) } /** Deletes an existing Api Scope by it's name */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Delete('api-scope/:name') @ApiOkResponse() async deleteApiScope( @Param('name') name: string, @CurrentUser() user: User, ): Promise<number> { if (!name) { throw new BadRequestException('Name must be provided') } return this.auditService.auditPromise( { user, action: 'deleteApiScope', namespace, resources: name, }, this.resourcesService.deleteApiScope(name), ) } /** Performs a soft delete on an Api resource by it's name */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Delete('api-resource/:name') @ApiOkResponse() async deleteApiResource( @Param('name') name: string, @CurrentUser() user: User, ): Promise<number> { if (!name) { throw new BadRequestException('Name must be provided') } return this.auditService.auditPromise( { user, action: 'deleteApiResource', namespace, resources: name, }, this.resourcesService.deleteApiResource(name), ) } @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Post('identity-resource-user-claims/:identityResourceName/:claimName') @Audit<IdentityResourceUserClaim>({ resources: (claim) => `${claim.identityResourceName}/${claim.claimName}`, }) async addResourceUserClaim( @Param('identityResourceName') identityResourceName: string, @Param('claimName') claimName: string, ): Promise<IdentityResourceUserClaim> { return this.resourcesService.addResourceUserClaim( identityResourceName, claimName, ) } @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Delete('identity-resource-user-claims/:identityResourceName/:claimName') async removeResourceUserClaim( @Param('identityResourceName') identityResourceName: string, @Param('claimName') claimName: string, @CurrentUser() user: User, ): Promise<number> { return this.auditService.auditPromise( { user, action: 'removeResourceUserClaim', namespace, resources: `${identityResourceName}/${claimName}`, }, this.resourcesService.removeResourceUserClaim( identityResourceName, claimName, ), ) } @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Post('api-scope-user-claims/:apiScopeName/:claimName') @ApiCreatedResponse({ type: ApiScopeUserClaim }) @Audit<ApiScopeUserClaim>({ resources: (claim) => `${claim.apiScopeName}/${claim.claimName}`, }) async addApiScopeUserClaim( @Param('apiScopeName') apiScopeName: string, @Param('claimName') claimName: string, ): Promise<ApiScopeUserClaim> { return this.resourcesService.addApiScopeUserClaim(apiScopeName, claimName) } @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Delete('api-scope-user-claims/:apiScopeName/:claimName') async removeApiScopeUserClaim( @Param('apiScopeName') apiScopeName: string, @Param('claimName') claimName: string, @CurrentUser() user: User, ): Promise<number> { return this.auditService.auditPromise( { user, action: 'removeApiScopeUserClaim', namespace, resources: `${apiScopeName}/${claimName}`, }, this.resourcesService.removeApiScopeUserClaim(apiScopeName, claimName), ) } @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('api-scope/:name') @Audit<ApiScope>({ resources: (scope) => scope?.name, }) async getApiScopeByName(@Param('name') name: string): Promise<ApiScope> { return this.resourcesService.getApiScopeByName(name) } @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('is-scope-name-available/:name') @Audit() async isScopeNameAvailable(@Param('name') name: string): Promise<boolean> { return this.resourcesService.isScopeNameAvailable(name) } @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('api-resource/:name') @Audit<ApiResource>({ resources: (resource) => resource?.name, }) async getApiResourceByName( @Param('name') name: string, ): Promise<ApiResource> { return this.resourcesService.getApiResourceByName(name) } @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Post('api-resource-claims/:apiResourceName/:claimName') @Audit<ApiResourceUserClaim>({ resources: (claim) => `${claim.apiResourceName}/${claim.claimName}`, }) async addApiResourceUserClaim( @Param('apiResourceName') apiResourceName: string, @Param('claimName') claimName: string, ): Promise<ApiResourceUserClaim> { if (!apiResourceName || !claimName) { throw new BadRequestException('Name and apiResourceName must be provided') } return this.resourcesService.addApiResourceUserClaim( apiResourceName, claimName, ) } /** Removes user claim from Api Resource */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Delete('api-resource-claims/:apiResourceName/:claimName') async removeApiResourceUserClaim( @Param('apiResourceName') apiResourceName: string, @Param('claimName') claimName: string, @CurrentUser() user: User, ): Promise<number> { if (!apiResourceName || !claimName) { throw new BadRequestException('Name and apiResourceName must be provided') } return this.auditService.auditPromise( { user, action: 'removeApiResourceUserClaim', namespace, resources: `${apiResourceName}/${claimName}`, }, this.resourcesService.removeApiResourceUserClaim( apiResourceName, claimName, ), ) } /** Add secret to ApiResource */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Post('api-resource-secret') @ApiCreatedResponse({ type: ApiResourceSecret }) @Audit<ApiResourceSecret>({ resources: (secret) => secret.apiResourceName, }) async addApiResourceSecret( @Body() apiSecret: ApiResourceSecretDTO, ): Promise<ApiResourceSecret> { if (!apiSecret) { throw new BadRequestException('The apiSecret object must be provided') } return this.resourcesService.addApiResourceSecret(apiSecret) } /** Remove a secret from Api Resource */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Delete('api-resource-secret') async removeApiResourceSecret( @Body() apiSecret: ApiResourceSecretDTO, @CurrentUser() user: User, ): Promise<number> { if (!apiSecret) { throw new BadRequestException( 'apiSecret object must be provided when deleting', ) } return this.auditService.auditPromise( { user, action: 'removeApiResourceSecret', namespace, resources: apiSecret.apiResourceName, }, this.resourcesService.removeApiResourceSecret(apiSecret), ) } /** Adds an allowed scope to api resource */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Post('api-resources-allowed-scope') @ApiCreatedResponse({ type: ApiResourceScope }) @Audit<ApiResourceScope>({ resources: (scope) => scope.apiResourceName, meta: (scope) => ({ scopeName: scope.scopeName }), }) async addApiResourceAllowedScope( @Body() resourceAllowedScope: ApiResourceAllowedScopeDTO, ): Promise<ApiResourceScope | null> { if (!resourceAllowedScope) { throw new BadRequestException( 'resourceAllowedScope object must be provided', ) } return this.resourcesService.addApiResourceAllowedScope( resourceAllowedScope, ) } /** Removes an allowed scope from api Resource */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Delete('api-resources-allowed-scope/:apiResourceName/:scopeName') async removeApiResourceAllowedScope( @Param('apiResourceName') apiResourceName: string, @Param('scopeName') scopeName: string, @CurrentUser() user: User, ): Promise<number> { if (!apiResourceName || !scopeName) { throw new BadRequestException( 'scopeName and apiResourceName must be provided', ) } return this.auditService.auditPromise( { user, action: 'removeApiResourceAllowedScope', namespace, resources: `${apiResourceName}/${scopeName}`, }, this.resourcesService.removeApiResourceAllowedScope( apiResourceName, scopeName, ), ) } /** Get api Resource from Api Resource Scope by Scope Name */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('api-scope-resource/:scopeName') @Audit<ApiResourceScope>({ resources: (scope) => scope?.scopeName, }) async findApiResourceScopeByScopeName( @Param('scopeName') scopeName: string, ): Promise<ApiResourceScope> { if (!scopeName) { throw new BadRequestException('scopeName must be provided') } return this.resourcesService.findApiResourceScopeByScopeName(scopeName) } /** Removes api scope from Api Resource Scope */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Delete('api-scope-resource/:scopeName') async removeApiScopeFromApiResourceScope( @Param('scopeName') scopeName: string, @CurrentUser() user: User, ): Promise<number> { if (!scopeName) { throw new BadRequestException('scopeName must be provided') } return this.auditService.auditPromise( { user, action: 'removeApiScopeFromApiResourceScope', namespace, resources: scopeName, }, this.resourcesService.removeApiScopeFromApiResourceScope(scopeName), ) } // #region ApiScopeGroup @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('api-scope-group') @Audit<ApiScopeGroup[] | PagedRowsDto<ApiScopeGroup>>({ resources: (result) => { const groups = Array.isArray(result) ? result : result.rows return groups.map((group) => group.id) }, }) async findApiScopeGroups( @Query('searchString') searchString?: string, @Query('page') page?: number, @Query('count') count?: number, ): Promise<ApiScopeGroup[] | PagedRowsDto<ApiScopeGroup>> { if (!page || !count) { return this.resourcesService.findAllApiScopeGroups() } return this.resourcesService.findAndCountAllApiScopeGroups( searchString, page, count, ) } @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('api-scope-group/:id') @Audit<ApiScopeGroup>({ resources: (group) => group?.id, }) async findApiScopeGroup( @Param('id') id: string, ): Promise<ApiScopeGroup | null> { return this.resourcesService.findApiScopeGroupByPk(id) } @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Post('api-scope-group') @Audit<ApiScopeGroup>({ resources: (group) => group.id, }) async createApiScopeGroup( @Body() group: ApiScopeGroupDTO, ): Promise<ApiScopeGroup> { return this.resourcesService.createApiScopeGroup(group) } @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Put('api-scope-group/:id') async updateApiScopeGroup( @Body() group: ApiScopeGroupDTO, @Param('id') id: string, @CurrentUser() user: User, ): Promise<[number, ApiScopeGroup[]]> { return this.auditService.auditPromise( { user, namespace, action: 'updateApiScopeGroup', resources: id, meta: { fields: Object.keys(group) }, }, this.resourcesService.updateApiScopeGroup(group, id), ) } @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Delete('api-scope-group/:id') async deleteApiScopeGroup( @Param('id') id: string, @CurrentUser() user: User, ): Promise<number> { if (!id) { throw new BadRequestException('id must be provided') } return this.auditService.auditPromise( { user, namespace, action: 'deleteApiScopeGroup', resources: id, }, this.resourcesService.deleteApiScopeGroup(id), ) } // #endregion ApiScopeGroup // #region Domain /** Find all domains with or without paging */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('domain') @Audit<Domain[] | PagedRowsDto<Domain>>({ resources: (result) => { const domains = Array.isArray(result) ? result : result.rows return domains.map((domain) => domain.name) }, }) async findAllDomains( @Query('searchString') searchString: string, @Query('page') page: number, @Query('count') count: number, ): Promise<Domain[] | PagedRowsDto<Domain>> { return this.resourcesService.findAllDomains(searchString, page, count) } /** Gets domain by name */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Get('domain/:name') @Audit<Domain>({ resources: (domain) => domain?.name, }) async findDomainsByPk(@Param('name') name: string): Promise<Domain | null> { return this.resourcesService.findDomainByPk(name) } /** Creates a new Domain */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Post('domain') @Audit<ApiScopeGroup>({ resources: (domain) => domain.name, }) async createDomain(@Body() domain: DomainDTO): Promise<Domain> { return this.resourcesService.createDomain(domain) } /** Updates an existing Domain */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Put('domain/:name') async updateDomain( @CurrentUser() user: User, @Body() domain: DomainDTO, @Param('name') name: string, ): Promise<[number, Domain[]]> { return this.auditService.auditPromise( { user, namespace, action: 'updateDomain', resources: name, meta: { fields: Object.keys(domain) }, }, this.resourcesService.updateDomain(domain, name), ) } /** Delete Domain */ @Scopes(AuthAdminScope.root, AuthAdminScope.full) @Delete('domain/:name') async deleteDomain( @CurrentUser() user: User, @Param('name') name: string, ): Promise<number> { if (!name) { throw new BadRequestException('name must be provided') } return this.auditService.auditPromise( { user, namespace, action: 'deleteDomain', resources: name, }, this.resourcesService.deleteDomain(name), ) } // #endregion Domain }
the_stack
import { PdfFontStyle, PdfFontFamily } from './enum'; import { PdfFontMetrics, StandardWidthTable } from './pdf-font-metrics'; /** * @private * `Factory of the standard fonts metrics`. */ export class PdfStandardFontMetricsFactory { /** * `Multiplier` os subscript superscript. * @private */ private static readonly subSuperScriptFactor : number = 1.52; /** * `Ascender` value for the font. * @private */ private static readonly helveticaAscent : number = 931; /** * `Ascender` value for the font. * @private */ private static readonly helveticaDescent : number = -225; /** * `Font type`. * @private */ private static readonly helveticaName : string = 'Helvetica'; /** * `Ascender` value for the font. * @private */ private static readonly helveticaBoldAscent : number = 962; /** * `Ascender` value for the font. * @private */ private static readonly helveticaBoldDescent : number = -228; /** * `Font type`. * @private */ private static readonly helveticaBoldName : string = 'Helvetica-Bold'; /** * `Ascender` value for the font. * @private */ private static readonly helveticaItalicAscent : number = 931; /** * `Ascender` value for the font. * @private */ private static readonly helveticaItalicDescent : number = -225; /** * `Font type`. * @private */ private static readonly helveticaItalicName : string = 'Helvetica-Oblique'; /** * `Ascender` value for the font. * @private */ private static readonly helveticaBoldItalicAscent : number = 962; /** * `Ascender` value for the font. * @private */ private static readonly helveticaBoldItalicDescent : number = -228; /** * `Font type`. * @private */ private static readonly helveticaBoldItalicName : string = 'Helvetica-BoldOblique'; /** * `Ascender` value for the font. * @private */ private static readonly courierAscent : number = 805; /** * `Ascender` value for the font. * @private */ private static readonly courierDescent : number = -250; /** * `Font type`. * @private */ private static readonly courierName : string = 'Courier'; /** * `Ascender` value for the font. * @private */ private static readonly courierBoldAscent : number = 801; /** * `Ascender` value for the font. * @private */ private static readonly courierBoldDescent : number = -250; /** * `Font type`. * @private */ private static readonly courierBoldName : string = 'Courier-Bold'; /** * `Ascender` value for the font. * @private */ private static readonly courierItalicAscent : number = 805; /** * `Ascender` value for the font. * @private */ private static readonly courierItalicDescent : number = -250; /** * `Font type`. * @private */ private static readonly courierItalicName : string = 'Courier-Oblique'; /** * `Ascender` value for the font. * @private */ private static readonly courierBoldItalicAscent : number = 801; /** * `Ascender` value for the font. * @private */ private static readonly courierBoldItalicDescent : number = -250; /** * `Font type`. * @private */ private static readonly courierBoldItalicName : string = 'Courier-BoldOblique'; /** * `Ascender` value for the font. * @private */ private static readonly timesAscent : number = 898; /** * `Ascender` value for the font. * @private */ private static readonly timesDescent : number = -218; /** * `Font type`. * @private */ private static readonly timesName : string = 'Times-Roman'; /** * `Ascender` value for the font. * @private */ private static readonly timesBoldAscent : number = 935; /** * `Ascender` value for the font. * @private */ private static readonly timesBoldDescent : number = -218; /** * `Font type`. * @private */ private static readonly timesBoldName : string = 'Times-Bold'; /** * `Ascender` value for the font. * @private */ private static readonly timesItalicAscent : number = 883; /** * `Ascender` value for the font. * @private */ private static readonly timesItalicDescent : number = -217; /** * `Font type`. * @private */ private static readonly timesItalicName : string = 'Times-Italic'; /** * `Ascender` value for the font. * @private */ private static readonly timesBoldItalicAscent : number = 921; /** * `Ascender` value for the font. * @private */ private static readonly timesBoldItalicDescent : number = -218; /** * `Font type`. * @private */ private static readonly timesBoldItalicName : string = 'Times-BoldItalic'; /** * `Ascender` value for the font. * @private */ private static readonly symbolAscent : number = 1010; /** * `Ascender` value for the font. * @private */ private static readonly symbolDescent : number = -293; /** * `Font type`. * @private */ private static readonly symbolName : string = 'Symbol'; /** * `Ascender` value for the font. * @private */ private static readonly zapfDingbatsAscent : number = 820; /** * `Ascender` value for the font. * @private */ private static readonly zapfDingbatsDescent : number = -143; /** * `Font type`. * @private */ private static readonly zapfDingbatsName : string = 'ZapfDingbats'; /** * `Arial` widths table. * @private */ private static arialWidth : number[] = [ 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 0, 556, 0, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0, 0, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 0, 500, 667, 0, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 0, 737, 333, 400, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611, 667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, 556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278, 556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500, 556, 500 ]; /** * `Arial bold` widths table. * @private */ private static arialBoldWidth : number[] = [ 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 0, 556, 0, 278, 556, 500, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0, 0, 278, 278, 500, 500, 350, 556, 1000, 333, 1000, 556, 333, 944, 0, 500, 667, 0, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 0, 737, 333, 400, 584, 333, 333, 333, 611, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611, 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, 556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278, 611, 611, 611, 611, 611, 611, 611, 584, 611, 611, 611, 611, 611, 556, 611, 556 ]; /** * `Fixed` widths table. * @private */ private static fixedWidth : number[] = [ 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600 ]; /** * `Times` widths table. * @private */ private static timesRomanWidth : number[] = [ 250, 333, 408, 500, 500, 833, 778, 180, 333, 333, 500, 564, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 564, 564, 564, 444, 921, 722, 667, 667, 722, 611, 556, 722, 722, 333, 389, 722, 611, 889, 722, 722, 556, 722, 667, 556, 611, 722, 722, 944, 722, 722, 611, 333, 278, 333, 469, 500, 333, 444, 500, 444, 500, 444, 333, 500, 500, 278, 278, 500, 278, 778, 500, 500, 500, 500, 333, 389, 278, 500, 500, 722, 500, 500, 444, 480, 200, 480, 541, 0, 500, 0, 333, 500, 444, 1000, 500, 500, 333, 1000, 556, 333, 889, 0, 611, 0, 0, 333, 333, 444, 444, 350, 500, 1000, 333, 980, 389, 333, 722, 0, 444, 722, 0, 333, 500, 500, 500, 500, 200, 500, 333, 760, 276, 500, 564, 0, 760, 333, 400, 564, 300, 300, 333, 500, 453, 250, 333, 300, 310, 500, 750, 750, 750, 444, 722, 722, 722, 722, 722, 722, 889, 667, 611, 611, 611, 611, 333, 333, 333, 333, 722, 722, 722, 722, 722, 722, 722, 564, 722, 722, 722, 722, 722, 722, 556, 500, 444, 444, 444, 444, 444, 444, 667, 444, 444, 444, 444, 444, 278, 278, 278, 278, 500, 500, 500, 500, 500, 500, 500, 564, 500, 500, 500, 500, 500, 500, 500, 500 ]; /** * `Times bold` widths table. * @private */ private static timesRomanBoldWidth : number[] = [ 250, 333, 555, 500, 500, 1000, 833, 278, 333, 333, 500, 570, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500, 930, 722, 667, 722, 722, 667, 611, 778, 778, 389, 500, 778, 667, 944, 722, 778, 611, 778, 722, 556, 667, 722, 722, 1000, 722, 722, 667, 333, 278, 333, 581, 500, 333, 500, 556, 444, 556, 444, 333, 500, 556, 278, 333, 556, 278, 833, 556, 500, 556, 556, 444, 389, 333, 556, 500, 722, 500, 500, 444, 394, 220, 394, 520, 0, 500, 0, 333, 500, 500, 1000, 500, 500, 333, 1000, 556, 333, 1000, 0, 667, 0, 0, 333, 333, 500, 500, 350, 500, 1000, 333, 1000, 389, 333, 722, 0, 444, 722, 0, 333, 500, 500, 500, 500, 220, 500, 333, 747, 300, 500, 570, 0, 747, 333, 400, 570, 300, 300, 333, 556, 540, 250, 333, 300, 330, 500, 750, 750, 750, 500, 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 389, 389, 389, 389, 722, 722, 778, 778, 778, 778, 778, 570, 778, 722, 722, 722, 722, 722, 611, 556, 500, 500, 500, 500, 500, 500, 722, 444, 444, 444, 444, 444, 278, 278, 278, 278, 500, 556, 500, 500, 500, 500, 500, 570, 500, 556, 556, 556, 556, 500, 556, 500 ]; /** * `Times italic` widths table. * @private */ private static timesRomanItalicWidth : number[] = [ 250, 333, 420, 500, 500, 833, 778, 214, 333, 333, 500, 675, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 675, 675, 675, 500, 920, 611, 611, 667, 722, 611, 611, 722, 722, 333, 444, 667, 556, 833, 667, 722, 611, 722, 611, 500, 556, 722, 611, 833, 611, 556, 556, 389, 278, 389, 422, 500, 333, 500, 500, 444, 500, 444, 278, 500, 500, 278, 278, 444, 278, 722, 500, 500, 500, 500, 389, 389, 278, 500, 444, 667, 444, 444, 389, 400, 275, 400, 541, 0, 500, 0, 333, 500, 556, 889, 500, 500, 333, 1000, 500, 333, 944, 0, 556, 0, 0, 333, 333, 556, 556, 350, 500, 889, 333, 980, 389, 333, 667, 0, 389, 556, 0, 389, 500, 500, 500, 500, 275, 500, 333, 760, 276, 500, 675, 0, 760, 333, 400, 675, 300, 300, 333, 500, 523, 250, 333, 300, 310, 500, 750, 750, 750, 500, 611, 611, 611, 611, 611, 611, 889, 667, 611, 611, 611, 611, 333, 333, 333, 333, 722, 667, 722, 722, 722, 722, 722, 675, 722, 722, 722, 722, 722, 556, 611, 500, 500, 500, 500, 500, 500, 500, 667, 444, 444, 444, 444, 444, 278, 278, 278, 278, 500, 500, 500, 500, 500, 500, 500, 675, 500, 500, 500, 500, 500, 444, 500, 444 ]; /** * `Times bold italic` widths table. * @private */ public static timesRomanBoldItalicWidths : number[] = [ 250, 389, 555, 500, 500, 833, 778, 278, 333, 333, 500, 570, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500, 832, 667, 667, 667, 722, 667, 667, 722, 778, 389, 500, 667, 611, 889, 722, 722, 611, 722, 667, 556, 611, 722, 667, 889, 667, 611, 611, 333, 278, 333, 570, 500, 333, 500, 500, 444, 500, 444, 333, 500, 556, 278, 278, 500, 278, 778, 556, 500, 500, 500, 389, 389, 278, 556, 444, 667, 500, 444, 389, 348, 220, 348, 570, 0, 500, 0, 333, 500, 500, 1000, 500, 500, 333, 1000, 556, 333, 944, 0, 611, 0, 0, 333, 333, 500, 500, 350, 500, 1000, 333, 1000, 389, 333, 722, 0, 389, 611, 0, 389, 500, 500, 500, 500, 220, 500, 333, 747, 266, 500, 606, 0, 747, 333, 400, 570, 300, 300, 333, 576, 500, 250, 333, 300, 300, 500, 750, 750, 750, 500, 667, 667, 667, 667, 667, 667, 944, 667, 667, 667, 667, 667, 389, 389, 389, 389, 722, 722, 722, 722, 722, 722, 722, 570, 722, 722, 722, 722, 722, 611, 611, 500, 500, 500, 500, 500, 500, 500, 722, 444, 444, 444, 444, 444, 278, 278, 278, 278, 500, 556, 500, 500, 500, 500, 500, 570, 500, 556, 556, 556, 556, 444, 500, 444 ]; /** * `Symbol` widths table. * @private */ private static symbolWidth : number[] = [ 250, 333, 713, 500, 549, 833, 778, 439, 333, 333, 500, 549, 250, 549, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 549, 549, 549, 444, 549, 722, 667, 722, 612, 611, 763, 603, 722, 333, 631, 722, 686, 889, 722, 722, 768, 741, 556, 592, 611, 690, 439, 768, 645, 795, 611, 333, 863, 333, 658, 500, 500, 631, 549, 549, 494, 439, 521, 411, 603, 329, 603, 549, 549, 576, 521, 549, 549, 521, 549, 603, 439, 576, 713, 686, 493, 686, 494, 480, 200, 480, 549, 750, 620, 247, 549, 167, 713, 500, 753, 753, 753, 753, 1042, 987, 603, 987, 603, 400, 549, 411, 549, 549, 713, 494, 460, 549, 549, 549, 549, 1000, 603, 1000, 658, 823, 686, 795, 987, 768, 768, 823, 768, 768, 713, 713, 713, 713, 713, 713, 713, 768, 713, 790, 790, 890, 823, 549, 250, 713, 603, 603, 1042, 987, 603, 987, 603, 494, 329, 790, 790, 786, 713, 384, 384, 384, 384, 384, 384, 494, 494, 494, 494, 329, 274, 686, 686, 686, 384, 384, 384, 384, 384, 384, 494, 494, 494, -1 ]; /** * `Zip dingbats` widths table. * @private */ private static zapfDingbatsWidth : number[] = [ 278, 974, 961, 974, 980, 719, 789, 790, 791, 690, 960, 939, 549, 855, 911, 933, 911, 945, 974, 755, 846, 762, 761, 571, 677, 763, 760, 759, 754, 494, 552, 537, 577, 692, 786, 788, 788, 790, 793, 794, 816, 823, 789, 841, 823, 833, 816, 831, 923, 744, 723, 749, 790, 792, 695, 776, 768, 792, 759, 707, 708, 682, 701, 826, 815, 789, 789, 707, 687, 696, 689, 786, 787, 713, 791, 785, 791, 873, 761, 762, 762, 759, 759, 892, 892, 788, 784, 438, 138, 277, 415, 392, 392, 668, 668, 390, 390, 317, 317, 276, 276, 509, 509, 410, 410, 234, 234, 334, 334, 732, 544, 544, 910, 667, 760, 760, 776, 595, 694, 626, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 894, 838, 1016, 458, 748, 924, 748, 918, 927, 928, 928, 834, 873, 828, 924, 924, 917, 930, 931, 463, 883, 836, 836, 867, 867, 696, 696, 874, 874, 760, 946, 771, 865, 771, 888, 967, 888, 831, 873, 927, 970, 918 ]; /** * Returns `metrics` of the font. * @private */ public static getMetrics(fontFamily : PdfFontFamily, fontStyle : PdfFontStyle, size : number) : PdfFontMetrics { let metrics : PdfFontMetrics = null; switch (fontFamily) { case PdfFontFamily.Helvetica: metrics = this.getHelveticaMetrics(fontFamily, fontStyle, size); break; case PdfFontFamily.Courier: metrics = this.getCourierMetrics(fontFamily, fontStyle, size); break; case PdfFontFamily.TimesRoman: metrics = this.getTimesMetrics(fontFamily, fontStyle, size); break; case PdfFontFamily.Symbol: metrics = this.getSymbolMetrics(fontFamily, fontStyle, size); break; case PdfFontFamily.ZapfDingbats: metrics = this.getZapfDingbatsMetrics(fontFamily, fontStyle, size); break; default: metrics = this.getHelveticaMetrics(PdfFontFamily.Helvetica, fontStyle, size); break; } metrics.name = fontFamily.toString(); metrics.subScriptSizeFactor = this.subSuperScriptFactor; metrics.superscriptSizeFactor = this.subSuperScriptFactor; return metrics; } // Implementation /** * Creates `Helvetica font metrics`. * @private */ private static getHelveticaMetrics(fontFamily : PdfFontFamily, fontStyle : PdfFontStyle, size : number) : PdfFontMetrics { let metrics : PdfFontMetrics = new PdfFontMetrics(); if ((fontStyle & PdfFontStyle.Bold) > 0 && (fontStyle & PdfFontStyle.Italic) > 0) { metrics.ascent = this.helveticaBoldItalicAscent; metrics.descent = this.helveticaBoldItalicDescent; metrics.postScriptName = this.helveticaBoldItalicName; metrics.size = size; metrics.widthTable = new StandardWidthTable(this.arialBoldWidth); metrics.height = metrics.ascent - metrics.descent; } else if ((fontStyle & PdfFontStyle.Bold) > 0) { metrics.ascent = this.helveticaBoldAscent; metrics.descent = this.helveticaBoldDescent; metrics.postScriptName = this.helveticaBoldName; metrics.size = size; metrics.widthTable = new StandardWidthTable(this.arialBoldWidth); metrics.height = metrics.ascent - metrics.descent; } else if ((fontStyle & PdfFontStyle.Italic) > 0) { metrics.ascent = this.helveticaItalicAscent; metrics.descent = this.helveticaItalicDescent; metrics.postScriptName = this.helveticaItalicName; metrics.size = size; metrics.widthTable = new StandardWidthTable(this.arialWidth); metrics.height = metrics.ascent - metrics.descent; } else { metrics.ascent = this.helveticaAscent; metrics.descent = this.helveticaDescent; metrics.postScriptName = this.helveticaName; metrics.size = size; metrics.widthTable = new StandardWidthTable(this.arialWidth); metrics.height = metrics.ascent - metrics.descent; } return metrics; } /** * Creates `Courier font metrics`. * @private */ private static getCourierMetrics(fontFamily : PdfFontFamily, fontStyle : PdfFontStyle, size : number) : PdfFontMetrics { let metrics : PdfFontMetrics = new PdfFontMetrics(); if ((fontStyle & PdfFontStyle.Bold) > 0 && (fontStyle & PdfFontStyle.Italic) > 0) { metrics.ascent = this.courierBoldItalicAscent; metrics.descent = this.courierBoldItalicDescent; metrics.postScriptName = this.courierBoldItalicName; metrics.size = size; metrics.widthTable = new StandardWidthTable(this.fixedWidth); metrics.height = metrics.ascent - metrics.descent; } else if ((fontStyle & PdfFontStyle.Bold) > 0) { metrics.ascent = this.courierBoldAscent; metrics.descent = this.courierBoldDescent; metrics.postScriptName = this.courierBoldName; metrics.size = size; metrics.widthTable = new StandardWidthTable(this.fixedWidth); metrics.height = metrics.ascent - metrics.descent; } else if ((fontStyle & PdfFontStyle.Italic) > 0) { metrics.ascent = this.courierItalicAscent; metrics.descent = this.courierItalicDescent; metrics.postScriptName = this.courierItalicName; metrics.size = size; metrics.widthTable = new StandardWidthTable(this.fixedWidth); metrics.height = metrics.ascent - metrics.descent; } else { metrics.ascent = this.courierAscent; metrics.descent = this.courierDescent; metrics.postScriptName = this.courierName; metrics.size = size; metrics.widthTable = new StandardWidthTable(this.fixedWidth); metrics.height = metrics.ascent - metrics.descent; } return metrics; } /** * Creates `Times font metrics`. * @private */ private static getTimesMetrics(fontFamily : PdfFontFamily, fontStyle : PdfFontStyle, size : number) : PdfFontMetrics { let metrics : PdfFontMetrics = new PdfFontMetrics(); if ((fontStyle & PdfFontStyle.Bold) > 0 && (fontStyle & PdfFontStyle.Italic) > 0) { metrics.ascent = this.timesBoldItalicAscent; metrics.descent = this.timesBoldItalicDescent; metrics.postScriptName = this.timesBoldItalicName; metrics.size = size; metrics.widthTable = new StandardWidthTable(this.timesRomanBoldItalicWidths); metrics.height = metrics.ascent - metrics.descent; } else if ((fontStyle & PdfFontStyle.Bold) > 0) { metrics.ascent = this.timesBoldAscent; metrics.descent = this.timesBoldDescent; metrics.postScriptName = this.timesBoldName; metrics.size = size; metrics.widthTable = new StandardWidthTable(this.timesRomanBoldWidth); metrics.height = metrics.ascent - metrics.descent; } else if ((fontStyle & PdfFontStyle.Italic) > 0) { metrics.ascent = this.timesItalicAscent; metrics.descent = this.timesItalicDescent; metrics.postScriptName = this.timesItalicName; metrics.size = size; metrics.widthTable = new StandardWidthTable(this.timesRomanItalicWidth); metrics.height = metrics.ascent - metrics.descent; } else { metrics.ascent = this.timesAscent; metrics.descent = this.timesDescent; metrics.postScriptName = this.timesName; metrics.size = size; metrics.widthTable = new StandardWidthTable(this.timesRomanWidth); metrics.height = metrics.ascent - metrics.descent; } return metrics; } /** * Creates `Symbol font metrics`. * @private */ private static getSymbolMetrics(fontFamily : PdfFontFamily, fontStyle : PdfFontStyle, size : number) : PdfFontMetrics { let metrics : PdfFontMetrics = new PdfFontMetrics(); metrics.ascent = this.symbolAscent; metrics.descent = this.symbolDescent; metrics.postScriptName = this.symbolName; metrics.size = size; metrics.widthTable = new StandardWidthTable(this.symbolWidth); metrics.height = metrics.ascent - metrics.descent; return metrics; } /** * Creates `ZapfDingbats font metrics`. * @private */ private static getZapfDingbatsMetrics(fontFamily : PdfFontFamily, fontStyle : PdfFontStyle, size : number) : PdfFontMetrics { let metrics : PdfFontMetrics = new PdfFontMetrics(); metrics.ascent = this.zapfDingbatsAscent; metrics.descent = this.zapfDingbatsDescent; metrics.postScriptName = this.zapfDingbatsName; metrics.size = size; metrics.widthTable = new StandardWidthTable(this.zapfDingbatsWidth); metrics.height = metrics.ascent - metrics.descent; return metrics; } }
the_stack
import middleware from "../middleware/middleware-component"; const path = require ("path"); const fs = require("fs"); const LOCAL_ENDPOINT = 'http://localhost:3002'; export const STORAGE_ACTION = { UPLOAD: "UPLOAD", LIST: "LIST" }; const getBucket = () => process.env.BUCKET_ID; const isOffline = () => !(getBucket().startsWith("infrcomp")); const getS3 = () => { //AWS.config.update({region: 'eu-west-1'}); const AWS = require('aws-sdk'); return new AWS.S3(Object.assign({ apiVersion: '2006-03-01' }, isOffline() ? { s3ForcePathStyle: true, accessKeyId: 'S3RVER', // This specific key is required when working offline secretAccessKey: 'S3RVER', endpoint: new AWS.Endpoint(LOCAL_ENDPOINT), } : {} )); }; function prepareLocalFs () { const getTempName = isOffline() ? () => { const targetFolder = ".s3"; //check if folder needs to be created or integrated if ( !fs.existsSync( targetFolder ) ) { fs.mkdirSync( targetFolder, {recursive: true} ); } fs.chmodSync( targetFolder, 0o777); return targetFolder; } : () => "/tmp"; return getTempName(); } export const uploadMiddleware = (storageId) => middleware({ callback: async function (req, res, next) { const parsedBody = JSON.parse(req.body); if (parsedBody.action !== STORAGE_ACTION.UPLOAD) { return next(); } //console.log("this is the storage-service: ", parsedBody.part, " of ", parsedBody.total_parts, ", offline: ", isOffline()); //console.log("data: ", parsedBody.data); const s3 = getS3(); // prepare file data const buffer = Buffer.from(parsedBody.file_data.match(/^data:.+\/(.+);base64,(.*)$/)[2], 'base64'); const tmpName = path.join(prepareLocalFs(),parsedBody.file); await new Promise((resolve, reject) => { fs.writeFile(tmpName, buffer, (err) => { if (err) { //console.log(err); reject(err); } else { //console.log("Successfully Written File to tmp."); resolve(); } }); }); const prefix = parsedBody.prefix !== undefined && parsedBody.prefix.replace(/(^\/)|(\/$)/g, "").length > 0 ? parsedBody.prefix.replace(/(^\/)|(\/$)/g, "") + "/" : ""; const getFilePartKey = (idx) => storageId + "/" + prefix + parsedBody.file + "_ICPART_" + idx; await s3.upload({ Bucket: getBucket(), Key: getFilePartKey(parsedBody.part), Body: fs.createReadStream(tmpName), //Expires:expiryDate }).promise().then( function (data) { //console.log("file uploaded: ", data); }, function (error) { console.log("could not upload to s3 ", error); } ); if (parseInt(parsedBody.part) + 1 == parseInt(parsedBody.total_parts)) { // @ts-ignore const parts = Buffer.concat(await Promise.all(Array.apply(null, Array(parseInt(parsedBody.total_parts))).map( function (part, idx) { return new Promise((resolve, reject) => { const partParams = { Bucket: getBucket(), Key: getFilePartKey(idx) }; return s3.getObject(partParams).promise().then( async function (data) { //console.log("file downloaded: ", data); await s3.deleteObject(partParams).promise().then( ok => ok, err => { console.log("could not delete part ", idx, err); } ); resolve(Buffer.from(data.Body, 'base64')); }, function (error) { console.log("could not load part ", idx, error); reject(error); } ); }); } ))); //console.log("upload to: ", storageId + "/" +prefix + parsedBody.fil); const finalparams = { Bucket: getBucket(), Key: storageId + "/" +prefix + parsedBody.file, Body: parts, //Expires:expiryDate }; await s3.upload(finalparams).promise().then( function (data) { //console.log("file uploaded: ", data); res.status(200) .set({ "Access-Control-Allow-Origin" : "*", // Required for CORS support to work "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS }) .send(JSON.stringify({uri: data.Location })); return; }, function (error) { console.log("could not upload to s3 ", error); res.status(500).set({ "Access-Control-Allow-Origin" : "*", // Required for CORS support to work "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS }).send("error"); return } ); } else { res.status(200).set({ "Access-Control-Allow-Origin" : "*", // Required for CORS support to work "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS }).send(JSON.stringify({part: parsedBody.part, total_parts: parsedBody.total_parts })); } } }); /** * User-function to upload a file from the front-end * * @param storageId * @param file * @param onProgess * @param onComplete * @param onError */ export const uploadFile = ( storageId: string, prefix: string | undefined, file, data, onProgess: (uploaded: number) => Boolean, onComplete: (uri: string) => void, onError: (err: string) => void ) => { if (!file) { onError("not a valid file!"); return; } const slice_size = 100 * 1024; const reader = new FileReader(); function upload_file( start, part ) { const next_slice = start + slice_size + 1; const totalParts = Math.ceil(file.size / slice_size); const blob = file.slice( start, next_slice ); reader.onload = function( event ) { // @ts-ignore if ( event.target.readyState !== FileReader.DONE ) { return; } require("infrastructure-components").callService( storageId, Object.assign({ action: STORAGE_ACTION.UPLOAD, // @ts-ignore file_data: event.target.result, file: file.name, file_type: file.type, prefix: prefix, part: part, total_parts: totalParts, }, part +1 == totalParts ? { data: data } : {}), (data: any) => { data.json().then(parsedBody => { //console.log("parsedBody: ", parsedBody); const size_done = start + slice_size; if ( next_slice < file.size ) { if (onProgess(size_done)) { // More to upload, call function recursively upload_file( next_slice, part+1 ); } else { onError("cancelled"); } } else { // Update upload progress onComplete(parsedBody.uri); } }); }, (error) => { onError(error); } ); }; reader.readAsDataURL( blob ); } upload_file(0, 0); }; export const LISTFILES_MODE = { FILES: "FILES", FOLDERS: "FOLDERS", ALL: "ALL" } /** * User-function to get a list of the files. Call from the front-end * */ export const listFiles = ( storageId: string, prefix: string, listMode: string, data: any, onComplete: (result: any) => void, onError: (err: string) => void, config: any = undefined, isOffline: Boolean = false ) => { //console.log("listFiles") require("infrastructure-components").callService( storageId, { action: STORAGE_ACTION.LIST, prefix: prefix, listMode: listMode, data: data }, (data) => { data.json().then(parsedBody => { //console.log(parsedBody); onComplete({data: parsedBody.data, files: parsedBody.files, folders: parsedBody.folders}) }); }, (error) => { //console.log("error: ", error); onError(error); }, config, isOffline ); } export const listMiddleware = (storageId) => middleware({ callback: async function (req, res, next) { const parsedBody = JSON.parse(req.body); if (parsedBody.action !== STORAGE_ACTION.LIST) { return next(); } const s3 = getS3(); //const getFilePartKey = (idx) => + parsedBody.file + "_ICPART_" + idx; await s3.listObjectsV2({ Bucket: getBucket(), Prefix: storageId + "/" + (parsedBody.prefix ? parsedBody.prefix : "").replace(/(^\/)|(\/$)/g, "") }).promise().then( function (data) { //console.log("parsed Prefix: ", parsedBody.prefix); //console.log("listed: ", data); const rawFilesList = data.Contents.map(item => ({ file: item.Key.substring(item.Key.lastIndexOf("/")+1), url: (isOffline() ? LOCAL_ENDPOINT + "/"+data.Name+"/" : "https://"+data.Name+".s3.amazonaws.com/")+item.Key, lastModified: item.LastModified, itemKey: item.Key.substring(item.Key.indexOf(storageId)+storageId.length), })); const userPrefix = parsedBody.prefix.replace(/(^\/)|(\/$)/g, ""); const baseFolder = userPrefix.length == 0 ? ["."] : []; res.status(200) .set({ "Access-Control-Allow-Origin" : "*", // Required for CORS support to work "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS }) .send(Object.assign( {data: res.locals}, parsedBody.listMode !== LISTFILES_MODE.FOLDERS ? { files: rawFilesList.filter( item => { if (parsedBody.listMode === LISTFILES_MODE.ALL) { return true; } const temp = path.join(storageId, parsedBody.prefix ? parsedBody.prefix : "").replace(/(^\/)|(\/$)/g, ""); const isInThisFolder = item.url.indexOf(temp)+temp.length+1 == item.url.indexOf(item.file); //console.log(temp, " | ", item.url, " | ", item.file); return (parsedBody.listMode === LISTFILES_MODE.FILES && isInThisFolder) /*|| (parsedBody.listMode === LISTFILES_MODE.FOLDERS && !isInThisFolder)*/; } ) } : { folders: Array.from(new Set(baseFolder.concat(rawFilesList.map(item => { const temp = path.join(storageId, parsedBody.prefix ? parsedBody.prefix : "").replace(/(^\/)|(\/$)/g, ""); const isInThisFolder = item.url.indexOf(temp)+temp.length+1 == item.url.indexOf(item.file); // remove files const wf = item.itemKey.substring(0, item.itemKey.lastIndexOf("/")).replace(/(^\/)|(\/$)/g, "")+"/"; //console.log("removed files: ", wf); if (wf == userPrefix+"/") { return "." }; //wf.substring(wf.indexOf(parsedBody.prefix)+parsedBody.prefix.length), //console.log("userPrefix: ", userPrefix); const folder = userPrefix && userPrefix.length > 0 ? ( wf.startsWith(userPrefix+"/")? wf.substring(userPrefix.length).replace(/(^\/)|(\/$)/g, ""):"" ): wf; //console.log("folder: ", folder); // return only direct children return folder.indexOf("/") >= 0 ? folder.substring(0, folder.indexOf("/")) : folder }).filter(item => item.length > 0)))) }/* (result, current) => { // if we want a list of folders, map the result //console.log(current.itemKey); //console.log("key: ", folder); /*const obj = {}; obj[folder] = Object.assign({ folder: folder.indexOf("/") >= 0 ? folder.substring(0,folder.indexOf("/")) : folder }, current); return Object.assign(obj, result)* / }, {} // starting with an empty list*/ //))} )); return; }, function (error) { console.log("could not list s3 ", error); res.status(500).set({ "Access-Control-Allow-Origin" : "*", // Required for CORS support to work "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS }).send("error"); return } ); } });
the_stack
import { EventEmitter } from 'events'; import work from 'webworkify-webpack'; import { abrGetUrl } from '../abr/abr-get-url'; import { AbrManifest } from '../abr/abr-manifest'; import Multirate from '../abr/multirate'; import FlvDemuxerInline from '../demux/flv/flv-demuxer-inline'; import FlvPreprocessor from '../demux/flv/flv-preprocessor'; import Loader from '../io/loader'; import { LasMainConfig, SmoothLevelSwitchInfo } from '../types/core'; import { FlvTag } from '../types/flv-object'; import { ILoader, ILoaderCallback, ILoaderConfig, ILoaderContext } from '../types/io'; import { MP4RemuxResult } from '../types/remux'; import { Log } from '../utils/log'; import { ErrorData, ErrorDetails, ErrorTypes } from './errors'; import LasEvents from './events'; import Media from './media'; import { REPORT_TYPES } from './report-types'; import { WorkerCmd } from './worker-cmd'; const URL_REG = new RegExp('^(http|https)://'); /** * flv视频流处理 */ const tag = 'LasMain'; export default class LasMain extends EventEmitter { private _config: LasMainConfig; private _media: Media; private _w?: Worker; private _flv?: FlvDemuxerInline; private _eventEmitter: EventEmitter; private _loader?: Loader<ILoaderContext>; private _loaderConf: ILoaderConfig; private _loaderCallbacks: ILoaderCallback<ILoaderContext>; private _multirate?: Multirate; private _isContinuous: boolean; private _remuxId: number; private _baseTimeSec: number = 0; private _tagDump: FlvPreprocessor<SmoothLevelSwitchInfo>; private _currentUrl?: any; private _isAbr: boolean = false; private _progressTime: number = 0; private _src: any; private _audioCodec: string = ''; /** * 传入配置并初始化 * @param config 配置信息 * @param media Media */ constructor(config: LasMainConfig, media: Media) { super(); this._config = config; this._media = media; this._loaderConf = { connectionTimeout: this._config.connectionTimeout, transmissionTimeout: this._config.transmissionTimeout, maxRetry: 0, retryDelay: 0, useFetch: true }; this._loaderCallbacks = { onProgress: this._onLoaderProgress, onError: this._onLoaderError, onEnd: this._onLoaderEnd, onAbort: this._onLoaderAbort }; this._isContinuous = false; this._remuxId = 1; const eventEmitter = (this._eventEmitter = new EventEmitter()); eventEmitter.on(LasEvents.MEDIA_INFO, data => { this._onEvent(LasEvents.MEDIA_INFO, data) }); eventEmitter.on(LasEvents.SCRIPT_PARSED, data => { this._onEvent(LasEvents.SCRIPT_PARSED, data) }); eventEmitter.on(LasEvents.MANIFEST_PARSED, data => { this._onEvent(LasEvents.MANIFEST_PARSED, data) }); eventEmitter.on(LasEvents.MP4_SEGMENT, data => { this._onEvent(LasEvents.MP4_SEGMENT, data) }); eventEmitter.on(LasEvents.ERROR, data => { this._onEvent(LasEvents.ERROR, data) }); eventEmitter.on(LasEvents.FLV_HEAD, data => { this._onEvent(LasEvents.FLV_HEAD, data) }); this._tagDump = new FlvPreprocessor(this._eventEmitter, this._flvKeyframeCallback); if (this._config.webWorker) { Log.i(tag, 'webWorker'); this._w = work(require.resolve('../demux/flv/flv-demuxer-worker')); if (this._w) { this._w.addEventListener('message', this._onWorkerEvent); this._w.postMessage({ cmd: WorkerCmd.INIT, config: this._config, data: { remuxId: this._remuxId } }); return; } } this._flv = new FlvDemuxerInline(eventEmitter, this._config, { remuxId: this._remuxId }); this._flv.init(); } /** * 初始化 * @param src manifest/播放url */ public init(src: any, audioCodec: string = ''): void { this._src = src; this._audioCodec = audioCodec; if (typeof src === 'string' && !URL_REG.test(src)) { try { this._src = JSON.parse(src); } catch (e) { this.emit(LasEvents.ERROR, { type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.MANIFEST_ERROR, fatal: true, info: { reason: 'manifest parse error' } }); return; } } if (this._src) { if (AbrManifest.verify(this._src)) { this._isAbr = true; } } else { this.emit(LasEvents.ERROR, { type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.MANIFEST_ERROR, fatal: true, info: { reason: 'src empty' } }); return; } if (this._isAbr && !this._multirate) { this._multirate = new Multirate(this._eventEmitter, this._config, this._media, this._src); this._multirate.init(); } } /** * 开始加载 */ public load(): void { let mr = this._multirate; if (mr) { let data = mr.levels[mr.currentLevel]; if (data) { this._load(abrGetUrl(data.url, this._config.defaultLiveDelay), mr.currentLevel); } else { this.emit(LasEvents.ERROR, { type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.MANIFEST_ERROR, fatal: true, info: { reason: 'manifest parse error' } }); } } else { this._load(this._src); } } /** * 销毁 */ public destroy(): void { this._destroyLoader(); if (this._w) { this._w.postMessage({ cmd: WorkerCmd.DESTROY }); this._w.removeEventListener('message', this._onWorkerEvent); this._w.terminate(); } if (this._flv) { this._flv.destroy(); this._flv = undefined; } if (this._multirate) { this._multirate.destory(); } const eventEmitter = this._eventEmitter; if (eventEmitter) { eventEmitter.removeAllListeners(); } } /** * 自动码率是否是开启状态 */ public get autoLevelEnabled(): boolean { if (this._multirate) { return this._multirate.autoLevelEnabled; } return false; } /** * 返回多路流列表 */ public get levels() { if (this._multirate) { return this._multirate.levels; } return []; } /** * 即将切换的level index */ public get nextLevel(): number { if (this._multirate) { return this._multirate.nextLevel; } return 0; } /** * 平滑切换清晰度,在关键帧位置切换 */ public set nextLevel(value: number) { const mr = this._multirate; if (mr) { mr.nextLevel = value; } } /** * 当前正在加载的level index */ public get currentLevel(): number { if (this._multirate) { return this._multirate.currentLevel; } return 0; } /** * 立即切换清晰度,丢弃现有数据,重新拉指定index的流 */ public set currentLevel(value: number) { const mr = this._multirate; if (mr) { let load = value >= 0 || value !== mr.currentLevel; mr.currentLevel = value; const data = mr.levels[mr.currentLevel]; if (load && data) { this._currentUrl = abrGetUrl(data.url, this._config.defaultLiveDelay); this._refreshRemuxId(); this._isContinuous = false; if (this._tagDump) { this._tagDump.reset(); } this._baseTimeSec = this._media.currentTime; this.emit(LasEvents.LEVEL_SWITCHING, { level: mr.currentLevel, startSec: this._baseTimeSec, smooth: false }); this._load(this._currentUrl, mr.currentLevel); } } } /** * worker通信 * @param ev worker返回数据 */ private _onWorkerEvent = (ev: any) => { const data = ev.data; this._onEvent(data.event, data.data); } /** * 关键帧位置处理 * 自动码率需要在关键帧位置进行切换,返回算法判断结果 */ private _flvKeyframeCallback = (timestamp: number): SmoothLevelSwitchInfo | undefined => { if (!this._media.hasStreamTime) { this._media.updateStreamTime(timestamp / 1000, 0); } return this._multirate ? this._multirate.onKeyFrame(timestamp) : undefined; } /** * 处理message事件 */ private _onEvent = (ev: string, data: any): void => { switch (ev) { case LasEvents.FLV_HEAD: if (this._w) { this._w.postMessage({ cmd: WorkerCmd.FLV_HEAD, hasAudio: data.hasAudio, hasVideo: data.hasVideo }); } else if (this._flv) { this._flv.flvHead(data.hasAudio, data.hasVideo); } break; case LasEvents.MEDIA_INFO: this.emit(LasEvents.MEDIA_INFO, data); break; case LasEvents.MP4_SEGMENT: { let mp4Data = data as MP4RemuxResult; if (mp4Data.extra && mp4Data.extra.remuxId !== this._remuxId) { // 过期,丢弃 break; } mp4Data.segments.forEach(segment => { if (segment.type === 'audio' && segment.startDTS > this._baseTimeSec) { this._media.updateStreamTime(segment.streamDTS, segment.startDTS); } }); this.emit(LasEvents.MP4_SEGMENT, mp4Data); } break; default: // SCRIPT_PARSED ERROR END this.emit(ev, data); break; } } private _destroyLoader() { if (this._loader) { this._loader.destroy(); this._loader = undefined; } } /** * 开始下载流 * @param url flv地址 * @param index level index */ private _load(url: string, index: number = 0): void { this._destroyLoader(); if (this._multirate) { this._multirate.onLevelLoad(index); } this._currentUrl = url; let level = this.levels[index]; if (level) { this._updateCodecs(this._audioCodec || level.audioCodec, level.videoCodec); } this.emit(LasEvents.REPORT, { type: REPORT_TYPES.START_LOAD_STREAM, url, sync: this._baseTimeSec, index: index, bitrate: level ? level.bitrate : 0 }); if (!this._loader) { this._loader = new Loader(); } const context = { url, progress: true, responseType: 'arraybuffer', credentials: this._config.credentials }; if (this._loader instanceof Loader) { this._loader.load(context, this._loaderCallbacks, this._loaderConf); } } /** * 读取的flv tag数据传入worker进行解封装、封装操作 * @param tags 读取的flv tag数据 * @param timeOffset 时间偏移 * @param isContinuous 继续remux的时间戳进行处理 */ private _append( tags: FlvTag[], timeOffset: number, isContinuous: boolean, ): void { if (this._w) { this._w.postMessage({ cmd: WorkerCmd.APPEND_DATA, tags, timeOffset: timeOffset || 0, isContinuous }); } else if (this._flv) { this._flv.append(tags, timeOffset || 0, isContinuous); } } private _updateCodecs(audioCodec: string = '', videoCodec: string = ''): void { if (this._w) { this._w.postMessage({ cmd: WorkerCmd.SET_CODECS, audioCodec, videoCodec }); } else if (this._flv) { this._flv.setCodecs(audioCodec, videoCodec); } } /** * 下载数据progress处理 * @param context 下载器上下文 * @param data 下载数据 * @param stats 下载器状态数据 */ private _onLoaderProgress = (target: ILoader<ILoaderContext>, data: string | ArrayBuffer): void => { if (!(data instanceof ArrayBuffer)) { return; } if (this._multirate) { this._multirate.onLoaderChunk(data.byteLength); } this.emit(LasEvents.REPORT, { type: REPORT_TYPES.LOADER_CHUNK_ARRIVAL, byteLength: data.byteLength, timeCost: performance.now() - this._progressTime || target.stats.requestStartTime, header: target.context.responseHeader }); this._progressTime = performance.now(); const result = this._tagDump.processing(data); this._append(result.list, this._baseTimeSec, this._isContinuous); this._isContinuous = true; // 是否需要切换 if (result.callbackResult) { if (this._tagDump) { this._tagDump.reset(); } this._baseTimeSec = result.callbackResult.timestamp ? this._media.getLocalTime(result.callbackResult.timestamp / 1000) || 0 : 0; // 平滑切换 this.emit(LasEvents.LEVEL_SWITCHING, { level: result.callbackResult.level, startSec: this._baseTimeSec, smooth: true }); this._load(result.callbackResult.url, result.callbackResult.level); } } private _onLoaderAbort = (): void => { } /** * 下载器错误处理 * @param context 下载器上下文 * @param status 下载器状态 */ private _onLoaderError = (target: ILoader<ILoaderContext>): void => { if (!target.stats.fatalError) { return; } const errInfo: ErrorData = { type: ErrorTypes.NETWORK_ERROR, details: target.stats.errorMessage === 'timeout' ? ErrorDetails.LOAD_ERROR_TIMEOUT : ErrorDetails.LOAD_ERROR, fatal: true, info: { url: target.context.url, httpStatusCode: target.stats.httpStatusCode, reason: target.stats.errorMessage } }; this.emit(LasEvents.ERROR, errInfo); } /** * 下载完成处理 */ private _onLoaderEnd = (): void => { if (this._w) { this._w.postMessage({ cmd: WorkerCmd.LOAD_END }); } else if (this._flv) { this._flv.end(); } } /** * 处理worker中的过期数据 */ private _refreshRemuxId(): void { this._remuxId++; const data = { remuxId: this._remuxId }; if (this._w) { this._w.postMessage({ cmd: WorkerCmd.SET_EXTRA, data: data }); } else if (this._flv) { this._flv.setExtra(data); } } }
the_stack
import { Line3, Plane, Triangle, Vector3 } from 'three' /** * Ported from: https://github.com/maurizzzio/quickhull3d/ by Mauricio Poppe (https://github.com/maurizzzio) */ const Visible = 0 const Deleted = 1 const _v1 = new Vector3() const _line3 = new Line3() const _plane = new Plane() const _closestPoint = new Vector3() const _triangle = new Triangle() class ConvexHull { tolerance: number faces: any[] newFaces: any[] assigned: VertexList vertices: any[] unassigned: any constructor() { this.tolerance = -1 this.faces = [] // the generated faces of the convex hull this.newFaces = [] // this array holds the faces that are generated within a single iteration // the vertex lists work as follows: // // let 'a' and 'b' be 'Face' instances // let 'v' be points wrapped as instance of 'Vertex' // // [v, v, ..., v, v, v, ...] // ^ ^ // | | // a.outside b.outside // this.assigned = new VertexList() this.unassigned = new VertexList() this.vertices = [] // vertices of the hull (internal representation of given geometry data) } setFromPoints(points) { if (Array.isArray(points) !== true) { console.error('THREE.ConvexHull: Points parameter is not an array.') } if (points.length < 4) { console.error('THREE.ConvexHull: The algorithm needs at least four points.') } this.makeEmpty() for (let i = 0, l = points.length; i < l; i++) { this.vertices.push(new VertexNode(points[i])) } this.compute() return this } setFromObject(object) { const points = [] object.updateMatrixWorld(true) object.traverse((node) => { const geometry = node.geometry if (geometry !== undefined) { if (geometry.isGeometry) { console.error('THREE.ConvexHull no longer supports Geometry. Use THREE.BufferGeometry instead.') return } else if (geometry.isBufferGeometry) { const attribute = geometry.attributes.position if (attribute !== undefined) { for (let i = 0, l = attribute.count; i < l; i++) { const point = new Vector3() point.fromBufferAttribute(attribute, i).applyMatrix4(node.matrixWorld) points.push(point) } } } } }) return this.setFromPoints(points) } containsPoint(point) { const faces = this.faces for (let i = 0, l = faces.length; i < l; i++) { const face = faces[i] // compute signed distance and check on what half space the point lies if (face.distanceToPoint(point) > this.tolerance) return false } return true } intersectRay(ray, target) { // based on "Fast Ray-Convex Polyhedron Intersection" by Eric Haines, GRAPHICS GEMS II const faces = this.faces let tNear = -Infinity let tFar = Infinity for (let i = 0, l = faces.length; i < l; i++) { const face = faces[i] // interpret faces as planes for the further computation const vN = face.distanceToPoint(ray.origin) const vD = face.normal.dot(ray.direction) // if the origin is on the positive side of a plane (so the plane can "see" the origin) and // the ray is turned away or parallel to the plane, there is no intersection if (vN > 0 && vD >= 0) return null // compute the distance from the ray’s origin to the intersection with the plane const t = vD !== 0 ? -vN / vD : 0 // only proceed if the distance is positive. a negative distance means the intersection point // lies "behind" the origin if (t <= 0) continue // now categorized plane as front-facing or back-facing if (vD > 0) { // plane faces away from the ray, so this plane is a back-face tFar = Math.min(t, tFar) } else { // front-face tNear = Math.max(t, tNear) } if (tNear > tFar) { // if tNear ever is greater than tFar, the ray must miss the convex hull return null } } // evaluate intersection point // always try tNear first since its the closer intersection point if (tNear !== -Infinity) { ray.at(tNear, target) } else { ray.at(tFar, target) } return target } intersectsRay(ray) { return this.intersectRay(ray, _v1) !== null } makeEmpty() { this.faces = [] this.vertices = [] return this } // Adds a vertex to the 'assigned' list of vertices and assigns it to the given face addVertexToFace(vertex, face) { vertex.face = face if (face.outside === null) { this.assigned.append(vertex) } else { this.assigned.insertBefore(face.outside, vertex) } face.outside = vertex return this } // Removes a vertex from the 'assigned' list of vertices and from the given face removeVertexFromFace(vertex, face) { if (vertex === face.outside) { // fix face.outside link if (vertex.next !== null && vertex.next.face === face) { // face has at least 2 outside vertices, move the 'outside' reference face.outside = vertex.next } else { // vertex was the only outside vertex that face had face.outside = null } } this.assigned.remove(vertex) return this } // Removes all the visible vertices that a given face is able to see which are stored in the 'assigned' vertext list removeAllVerticesFromFace(face) { if (face.outside !== null) { // reference to the first and last vertex of this face const start = face.outside let end = face.outside while (end.next !== null && end.next.face === face) { end = end.next } this.assigned.removeSubList(start, end) // fix references start.prev = end.next = null face.outside = null return start } } // Removes all the visible vertices that 'face' is able to see deleteFaceVertices(face, absorbingFace = undefined) { const faceVertices = this.removeAllVerticesFromFace(face) if (faceVertices !== undefined) { if (absorbingFace === undefined) { // mark the vertices to be reassigned to some other face this.unassigned.appendChain(faceVertices) } else { // if there's an absorbing face try to assign as many vertices as possible to it let vertex = faceVertices do { // we need to buffer the subsequent vertex at this point because the 'vertex.next' reference // will be changed by upcoming method calls const nextVertex = vertex.next const distance = absorbingFace.distanceToPoint(vertex.point) // check if 'vertex' is able to see 'absorbingFace' if (distance > this.tolerance) { this.addVertexToFace(vertex, absorbingFace) } else { this.unassigned.append(vertex) } // now assign next vertex vertex = nextVertex } while (vertex !== null) } } return this } // Reassigns as many vertices as possible from the unassigned list to the new faces resolveUnassignedPoints(newFaces) { if (this.unassigned.isEmpty() === false) { let vertex = this.unassigned.first() do { // buffer 'next' reference, see .deleteFaceVertices() const nextVertex = vertex.next let maxDistance = this.tolerance let maxFace = null for (let i = 0; i < newFaces.length; i++) { const face = newFaces[i] if (face.mark === Visible) { const distance = face.distanceToPoint(vertex.point) if (distance > maxDistance) { maxDistance = distance maxFace = face } if (maxDistance > 1000 * this.tolerance) break } } // 'maxFace' can be null e.g. if there are identical vertices if (maxFace !== null) { this.addVertexToFace(vertex, maxFace) } vertex = nextVertex } while (vertex !== null) } return this } // Computes the extremes of a simplex which will be the initial hull computeExtremes() { const min = new Vector3() const max = new Vector3() const minVertices = [] const maxVertices = [] // initially assume that the first vertex is the min/max for (let i = 0; i < 3; i++) { minVertices[i] = maxVertices[i] = this.vertices[0] } min.copy(this.vertices[0].point) max.copy(this.vertices[0].point) // compute the min/max vertex on all six directions for (let i = 0, l = this.vertices.length; i < l; i++) { const vertex = this.vertices[i] const point = vertex.point // update the min coordinates for (let j = 0; j < 3; j++) { if (point.getComponent(j) < min.getComponent(j)) { min.setComponent(j, point.getComponent(j)) minVertices[j] = vertex } } // update the max coordinates for (let j = 0; j < 3; j++) { if (point.getComponent(j) > max.getComponent(j)) { max.setComponent(j, point.getComponent(j)) maxVertices[j] = vertex } } } // use min/max vectors to compute an optimal epsilon this.tolerance = 3 * Number.EPSILON * (Math.max(Math.abs(min.x), Math.abs(max.x)) + Math.max(Math.abs(min.y), Math.abs(max.y)) + Math.max(Math.abs(min.z), Math.abs(max.z))) return { min: minVertices, max: maxVertices } } // Computes the initial simplex assigning to its faces all the points // that are candidates to form part of the hull computeInitialHull() { const vertices = this.vertices const extremes = this.computeExtremes() const min = extremes.min const max = extremes.max // 1. Find the two vertices 'v0' and 'v1' with the greatest 1d separation // (max.x - min.x) // (max.y - min.y) // (max.z - min.z) let maxDistance = 0 let index = 0 for (let i = 0; i < 3; i++) { const distance = max[i].point.getComponent(i) - min[i].point.getComponent(i) if (distance > maxDistance) { maxDistance = distance index = i } } const v0 = min[index] const v1 = max[index] let v2 let v3 // 2. The next vertex 'v2' is the one farthest to the line formed by 'v0' and 'v1' maxDistance = 0 _line3.set(v0.point, v1.point) for (let i = 0, l = this.vertices.length; i < l; i++) { const vertex = vertices[i] if (vertex !== v0 && vertex !== v1) { _line3.closestPointToPoint(vertex.point, true, _closestPoint) const distance = _closestPoint.distanceToSquared(vertex.point) if (distance > maxDistance) { maxDistance = distance v2 = vertex } } } // 3. The next vertex 'v3' is the one farthest to the plane 'v0', 'v1', 'v2' maxDistance = -1 _plane.setFromCoplanarPoints(v0.point, v1.point, v2.point) for (let i = 0, l = this.vertices.length; i < l; i++) { const vertex = vertices[i] if (vertex !== v0 && vertex !== v1 && vertex !== v2) { const distance = Math.abs(_plane.distanceToPoint(vertex.point)) if (distance > maxDistance) { maxDistance = distance v3 = vertex } } } const faces = [] if (_plane.distanceToPoint(v3.point) < 0) { // the face is not able to see the point so 'plane.normal' is pointing outside the tetrahedron faces.push(Face.create(v0, v1, v2), Face.create(v3, v1, v0), Face.create(v3, v2, v1), Face.create(v3, v0, v2)) // set the twin edge for (let i = 0; i < 3; i++) { const j = (i + 1) % 3 // join face[ i ] i > 0, with the first face faces[i + 1].getEdge(2).setTwin(faces[0].getEdge(j)) // join face[ i ] with face[ i + 1 ], 1 <= i <= 3 faces[i + 1].getEdge(1).setTwin(faces[j + 1].getEdge(0)) } } else { // the face is able to see the point so 'plane.normal' is pointing inside the tetrahedron faces.push(Face.create(v0, v2, v1), Face.create(v3, v0, v1), Face.create(v3, v1, v2), Face.create(v3, v2, v0)) // set the twin edge for (let i = 0; i < 3; i++) { const j = (i + 1) % 3 // join face[ i ] i > 0, with the first face faces[i + 1].getEdge(2).setTwin(faces[0].getEdge((3 - i) % 3)) // join face[ i ] with face[ i + 1 ] faces[i + 1].getEdge(0).setTwin(faces[j + 1].getEdge(1)) } } // the initial hull is the tetrahedron for (let i = 0; i < 4; i++) { this.faces.push(faces[i]) } // initial assignment of vertices to the faces of the tetrahedron for (let i = 0, l = vertices.length; i < l; i++) { const vertex = vertices[i] if (vertex !== v0 && vertex !== v1 && vertex !== v2 && vertex !== v3) { maxDistance = this.tolerance let maxFace = null for (let j = 0; j < 4; j++) { const distance = this.faces[j].distanceToPoint(vertex.point) if (distance > maxDistance) { maxDistance = distance maxFace = this.faces[j] } } if (maxFace !== null) { this.addVertexToFace(vertex, maxFace) } } } return this } // Removes inactive faces reindexFaces() { const activeFaces = [] for (let i = 0; i < this.faces.length; i++) { const face = this.faces[i] if (face.mark === Visible) { activeFaces.push(face) } } this.faces = activeFaces return this } // Finds the next vertex to create faces with the current hull nextVertexToAdd() { // if the 'assigned' list of vertices is empty, no vertices are left. return with 'undefined' if (this.assigned.isEmpty() === false) { let eyeVertex, maxDistance = 0 // grap the first available face and start with the first visible vertex of that face const eyeFace = this.assigned.first().face let vertex = eyeFace.outside // now calculate the farthest vertex that face can see do { const distance = eyeFace.distanceToPoint(vertex.point) if (distance > maxDistance) { maxDistance = distance eyeVertex = vertex } vertex = vertex.next } while (vertex !== null && vertex.face === eyeFace) return eyeVertex } } // Computes a chain of half edges in CCW order called the 'horizon'. // For an edge to be part of the horizon it must join a face that can see // 'eyePoint' and a face that cannot see 'eyePoint'. computeHorizon(eyePoint, crossEdge, face, horizon) { // moves face's vertices to the 'unassigned' vertex list this.deleteFaceVertices(face) face.mark = Deleted let edge if (crossEdge === null) { edge = crossEdge = face.getEdge(0) } else { // start from the next edge since 'crossEdge' was already analyzed // (actually 'crossEdge.twin' was the edge who called this method recursively) edge = crossEdge.next } do { const twinEdge = edge.twin const oppositeFace = twinEdge.face if (oppositeFace.mark === Visible) { if (oppositeFace.distanceToPoint(eyePoint) > this.tolerance) { // the opposite face can see the vertex, so proceed with next edge this.computeHorizon(eyePoint, twinEdge, oppositeFace, horizon) } else { // the opposite face can't see the vertex, so this edge is part of the horizon horizon.push(edge) } } edge = edge.next } while (edge !== crossEdge) return this } // Creates a face with the vertices 'eyeVertex.point', 'horizonEdge.tail' and 'horizonEdge.head' in CCW order addAdjoiningFace(eyeVertex, horizonEdge) { // all the half edges are created in ccw order thus the face is always pointing outside the hull const face = Face.create(eyeVertex, horizonEdge.tail(), horizonEdge.head()) this.faces.push(face) // join face.getEdge( - 1 ) with the horizon's opposite edge face.getEdge( - 1 ) = face.getEdge( 2 ) face.getEdge(-1).setTwin(horizonEdge.twin) return face.getEdge(0) // the half edge whose vertex is the eyeVertex } // Adds 'horizon.length' faces to the hull, each face will be linked with the // horizon opposite face and the face on the left/right addNewFaces(eyeVertex, horizon) { this.newFaces = [] let firstSideEdge = null let previousSideEdge = null for (let i = 0; i < horizon.length; i++) { const horizonEdge = horizon[i] // returns the right side edge const sideEdge = this.addAdjoiningFace(eyeVertex, horizonEdge) if (firstSideEdge === null) { firstSideEdge = sideEdge } else { // joins face.getEdge( 1 ) with previousFace.getEdge( 0 ) sideEdge.next.setTwin(previousSideEdge) } this.newFaces.push(sideEdge.face) previousSideEdge = sideEdge } // perform final join of new faces firstSideEdge.next.setTwin(previousSideEdge) return this } // Adds a vertex to the hull addVertexToHull(eyeVertex) { const horizon = [] this.unassigned.clear() // remove 'eyeVertex' from 'eyeVertex.face' so that it can't be added to the 'unassigned' vertex list this.removeVertexFromFace(eyeVertex, eyeVertex.face) this.computeHorizon(eyeVertex.point, null, eyeVertex.face, horizon) this.addNewFaces(eyeVertex, horizon) // reassign 'unassigned' vertices to the new faces this.resolveUnassignedPoints(this.newFaces) return this } cleanup() { this.assigned.clear() this.unassigned.clear() this.newFaces = [] return this } compute() { let vertex this.computeInitialHull() // add all available vertices gradually to the hull while ((vertex = this.nextVertexToAdd()) !== undefined) { this.addVertexToHull(vertex) } this.reindexFaces() this.cleanup() return this } } // class Face { normal: Vector3 midpoint: Vector3 area: number constant: number outside: any mark: number edge: any constructor() { this.normal = new Vector3() this.midpoint = new Vector3() this.area = 0 this.constant = 0 // signed distance from face to the origin this.outside = null // reference to a vertex in a vertex list this face can see this.mark = Visible this.edge = null } static create(a, b, c) { const face = new Face() const e0 = new HalfEdge(a, face) const e1 = new HalfEdge(b, face) const e2 = new HalfEdge(c, face) // join edges e0.next = e2.prev = e1 e1.next = e0.prev = e2 e2.next = e1.prev = e0 // main half edge reference face.edge = e0 return face.compute() } getEdge(i) { let edge = this.edge while (i > 0) { edge = edge.next i-- } while (i < 0) { edge = edge.prev i++ } return edge } compute() { const a = this.edge.tail() const b = this.edge.head() const c = this.edge.next.head() _triangle.set(a.point, b.point, c.point) _triangle.getNormal(this.normal) _triangle.getMidpoint(this.midpoint) this.area = _triangle.getArea() this.constant = this.normal.dot(this.midpoint) return this } distanceToPoint(point) { return this.normal.dot(point) - this.constant } } // Entity for a Doubly-Connected Edge List (DCEL). class HalfEdge { vertex: any prev: any next: any twin: any face: any constructor(vertex, face) { this.vertex = vertex this.prev = null this.next = null this.twin = null this.face = face } head() { return this.vertex } tail() { return this.prev ? this.prev.vertex : null } length() { const head = this.head() const tail = this.tail() if (tail !== null) { return tail.point.distanceTo(head.point) } return -1 } magnitudeSquared() { const head = this.head() const tail = this.tail() if (tail !== null) { return tail.point.distanceToSquared(head.point) } return -1 } setTwin(edge) { this.twin = edge edge.twin = this return this } } // A vertex as a double linked list node. class VertexNode { point: any prev: any next: any face: any constructor(point) { this.point = point this.prev = null this.next = null this.face = null // the face that is able to see this vertex } } // A double linked list that contains vertex nodes. class VertexList { head: any tail: any constructor() { this.head = null this.tail = null } first() { return this.head } last() { return this.tail } clear() { this.head = this.tail = null return this } // Inserts a vertex before the target vertex insertBefore(target, vertex) { vertex.prev = target.prev vertex.next = target if (vertex.prev === null) { this.head = vertex } else { vertex.prev.next = vertex } target.prev = vertex return this } // Inserts a vertex after the target vertex insertAfter(target, vertex) { vertex.prev = target vertex.next = target.next if (vertex.next === null) { this.tail = vertex } else { vertex.next.prev = vertex } target.next = vertex return this } // Appends a vertex to the end of the linked list append(vertex) { if (this.head === null) { this.head = vertex } else { this.tail.next = vertex } vertex.prev = this.tail vertex.next = null // the tail has no subsequent vertex this.tail = vertex return this } // Appends a chain of vertices where 'vertex' is the head. appendChain(vertex) { if (this.head === null) { this.head = vertex } else { this.tail.next = vertex } vertex.prev = this.tail // ensure that the 'tail' reference points to the last vertex of the chain while (vertex.next !== null) { vertex = vertex.next } this.tail = vertex return this } // Removes a vertex from the linked list remove(vertex) { if (vertex.prev === null) { this.head = vertex.next } else { vertex.prev.next = vertex.next } if (vertex.next === null) { this.tail = vertex.prev } else { vertex.next.prev = vertex.prev } return this } // Removes a list of vertices whose 'head' is 'a' and whose 'tail' is b removeSubList(a, b) { if (a.prev === null) { this.head = b.next } else { a.prev.next = b.next } if (b.next === null) { this.tail = a.prev } else { b.next.prev = a.prev } return this } isEmpty() { return this.head === null } } export { ConvexHull }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [xray](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsx-ray.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Xray extends PolicyStatement { public servicePrefix = 'xray'; /** * Statement provider for service [xray](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsx-ray.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 retrieve a list of traces specified by ID. Each trace is a collection of segment documents that originates from a single request. Use GetTraceSummaries to get a list of trace IDs * * Access Level: List * * https://docs.aws.amazon.com/xray/latest/api/API_BatchGetTraces.html */ public toBatchGetTraces() { return this.to('BatchGetTraces'); } /** * Grants permission to create a group resource with a name and a filter expression * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/xray/latest/api/API_CreateGroup.html */ public toCreateGroup() { return this.to('CreateGroup'); } /** * Grants permission to create a rule to control sampling behavior for instrumented applications * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/xray/latest/api/API_CreateSamplingRule.html */ public toCreateSamplingRule() { return this.to('CreateSamplingRule'); } /** * Grants permission to delete a group resource * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/xray/latest/api/API_DeleteGroup.html */ public toDeleteGroup() { return this.to('DeleteGroup'); } /** * Grants permission to delete a sampling rule * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/xray/latest/api/API_DeleteSamplingRule.html */ public toDeleteSamplingRule() { return this.to('DeleteSamplingRule'); } /** * Grants permission to retrieve the current encryption configuration for X-Ray data * * Access Level: Read * * https://docs.aws.amazon.com/xray/latest/api/API_GetEncryptionConfig.html */ public toGetEncryptionConfig() { return this.to('GetEncryptionConfig'); } /** * Grants permission to retrieve group resource details * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/xray/latest/api/API_GetGroup.html */ public toGetGroup() { return this.to('GetGroup'); } /** * Grants permission to retrieve all active group details * * Access Level: Read * * https://docs.aws.amazon.com/xray/latest/api/API_GetGroups.html */ public toGetGroups() { return this.to('GetGroups'); } /** * Grants permission to retrieve the details of a specific insight * * Access Level: Read * * https://docs.aws.amazon.com/xray/latest/api/API_GetInsight.html */ public toGetInsight() { return this.to('GetInsight'); } /** * Grants permission to retrieve the events of a specific insight * * Access Level: Read * * https://docs.aws.amazon.com/xray/latest/api/API_GetInsightEvents.html */ public toGetInsightEvents() { return this.to('GetInsightEvents'); } /** * Grants permission to retrieve the part of the service graph which is impacted for a specific insight * * Access Level: Read * * https://docs.aws.amazon.com/xray/latest/api/API_GetInsightImpactGraph.html */ public toGetInsightImpactGraph() { return this.to('GetInsightImpactGraph'); } /** * Grants permission to retrieve the summary of all insights for a group and time range with optional filters * * Access Level: Read * * https://docs.aws.amazon.com/xray/latest/api/API_GetInsightSummaries.html */ public toGetInsightSummaries() { return this.to('GetInsightSummaries'); } /** * Grants permission to retrieve all sampling rules * * Access Level: Read * * https://docs.aws.amazon.com/xray/latest/api/API_GetSamplingRules.html */ public toGetSamplingRules() { return this.to('GetSamplingRules'); } /** * Grants permission to retrieve information about recent sampling results for all sampling rules * * Access Level: Read * * https://docs.aws.amazon.com/xray/latest/api/API_GetSamplingStatisticSummaries.html */ public toGetSamplingStatisticSummaries() { return this.to('GetSamplingStatisticSummaries'); } /** * Grants permission to request a sampling quota for rules that the service is using to sample requests * * Access Level: Read * * https://docs.aws.amazon.com/xray/latest/api/API_GetSamplingTargets.html */ public toGetSamplingTargets() { return this.to('GetSamplingTargets'); } /** * Grants permission to retrieve a document that describes services that process incoming requests, and downstream services that they call as a result * * Access Level: Read * * https://docs.aws.amazon.com/xray/latest/api/API_GetServiceGraph.html */ public toGetServiceGraph() { return this.to('GetServiceGraph'); } /** * Grants permission to retrieve an aggregation of service statistics defined by a specific time range bucketed into time intervals * * Access Level: Read * * https://docs.aws.amazon.com/xray/latest/api/API_GetTimeSeriesServiceStatistics.html */ public toGetTimeSeriesServiceStatistics() { return this.to('GetTimeSeriesServiceStatistics'); } /** * Grants permission to retrieve a service graph for one or more specific trace IDs * * Access Level: Read * * https://docs.aws.amazon.com/xray/latest/api/API_GetTraceGraph.html */ public toGetTraceGraph() { return this.to('GetTraceGraph'); } /** * Grants permission to retrieve IDs and metadata for traces available for a specified time frame using an optional filter. To get the full traces, pass the trace IDs to BatchGetTraces * * Access Level: Read * * https://docs.aws.amazon.com/xray/latest/api/API_GetTraceSummaries.html */ public toGetTraceSummaries() { return this.to('GetTraceSummaries'); } /** * Grants permission to list tags for an X-Ray resource * * Access Level: List * * https://docs.aws.amazon.com/xray/latest/api/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to update the encryption configuration for X-Ray data * * Access Level: Permissions management * * https://docs.aws.amazon.com/xray/latest/api/API_PutEncryptionConfig.html */ public toPutEncryptionConfig() { return this.to('PutEncryptionConfig'); } /** * Grants permission to send AWS X-Ray daemon telemetry to the service * * Access Level: Write * * https://docs.aws.amazon.com/xray/latest/api/API_PutTelemetryRecords.html */ public toPutTelemetryRecords() { return this.to('PutTelemetryRecords'); } /** * Grants permission to upload segment documents to AWS X-Ray. The X-Ray SDK generates segment documents and sends them to the X-Ray daemon, which uploads them in batches * * Access Level: Write * * https://docs.aws.amazon.com/xray/latest/api/API_PutTraceSegments.html */ public toPutTraceSegments() { return this.to('PutTraceSegments'); } /** * Grants permission to add tags to an X-Ray resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/xray/latest/api/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to remove tags from an X-Ray resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/xray/latest/api/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update a group resource * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/xray/latest/api/API_UpdateGroup.html */ public toUpdateGroup() { return this.to('UpdateGroup'); } /** * Grants permission to modify a sampling rule's configuration * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/xray/latest/api/API_UpdateSamplingRule.html */ public toUpdateSamplingRule() { return this.to('UpdateSamplingRule'); } protected accessLevelList: AccessLevelList = { "List": [ "BatchGetTraces", "ListTagsForResource" ], "Write": [ "CreateGroup", "CreateSamplingRule", "DeleteGroup", "DeleteSamplingRule", "PutTelemetryRecords", "PutTraceSegments", "UpdateGroup", "UpdateSamplingRule" ], "Read": [ "GetEncryptionConfig", "GetGroup", "GetGroups", "GetInsight", "GetInsightEvents", "GetInsightImpactGraph", "GetInsightSummaries", "GetSamplingRules", "GetSamplingStatisticSummaries", "GetSamplingTargets", "GetServiceGraph", "GetTimeSeriesServiceStatistics", "GetTraceGraph", "GetTraceSummaries" ], "Permissions management": [ "PutEncryptionConfig" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type group to the statement * * https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-groups * * @param groupName - Identifier for the groupName. * @param id - Identifier for the id. * @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 onGroup(groupName: string, id: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:xray:${Region}:${Account}:group/${GroupName}/${Id}'; arn = arn.replace('${GroupName}', groupName); arn = arn.replace('${Id}', id); 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 sampling-rule to the statement * * https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-sampling * * @param samplingRuleName - Identifier for the samplingRuleName. * @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 onSamplingRule(samplingRuleName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:xray:${Region}:${Account}:sampling-rule/${SamplingRuleName}'; arn = arn.replace('${SamplingRuleName}', samplingRuleName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import account = require('services/Account'); import app = require('Application'); import site = require('Site'); import shopping = require('services/Shopping'); import shoppingCart = require('services/ShoppingCart'); import coupon = require('services/Coupon'); import ko_val = require('knockout.validation'); import mapping = require('knockout.mapping'); import AvalibleCoupons = require('modules/Shopping/OrderProduct/Coupons'); requirejs(['css!content/Shopping/OrderProducts'], function () { }); var avalibleCoupons = new AvalibleCoupons(); class Order { private _userBalance: number; private BalanceAmount: KnockoutObservable<number>; //= ko.observable<number>(); private Sum: KnockoutObservable<number>; private total: KnockoutComputed<number>; private balance: KnockoutComputed<number>; private isBalancePay: KnockoutComputed<boolean>; actualPaid: KnockoutComputed<number>; Id: KnockoutObservable<string>; Invoice: KnockoutObservable<string>; ReceiptAddress: KnockoutObservable<string>; ReceiptRegionId: KnockoutObservable<string>; OrderDetails: KnockoutObservableArray<{ ProductId: KnockoutObservable<string> }>; isValid: () => boolean; constructor(userBalance, source: any) { this._userBalance = userBalance; for (var key in source) { this[key] = source[key]; } this.total = ko.computed(() => { var total = ko.unwrap(this.Sum); return total; }, this); this.balance = ko.computed(() => { var balanceAmount = ko.unwrap(this.BalanceAmount) || 0; if (balanceAmount) return balanceAmount; var sum = ko.unwrap(this.Sum); if (this._userBalance > sum) { return sum; } return this._userBalance; }, this); this.isBalancePay = ko.pureComputed<boolean>({ read: function () { if (ko.unwrap(this.BalanceAmount)) return true; return false; }, write: function (value) { if (value) { var balanceAmount = this.balance(); return shopping.balancePay(ko.unwrap(this.model.order.Id), balanceAmount).done(function (data) { mapping.fromJS(data, {}, this.model.order); }); } return shopping.balancePay(ko.unwrap(this.model.order.Id), 0).done(function (data) { mapping.fromJS(data, {}, this.model.order); }); } }, this); this.actualPaid = ko.computed(function () { return this.Sum() - this.BalanceAmount(); }, this); } } class Model { private _page: chitu.Page; order: Order; orderSummary = ko.observable() balance = ko.observable() useBalancePay = ko.observable() coupons = ko.observableArray() couponTitle = ko.observable() constructor(page: chitu.Page) { this._page = page; } confirmOrder = () => { //model.order.ReceiptAddress.extend({ required: { message: '请填写收货信息' } }); var validation = ko_val.group(this.order); if (!this.order.isValid()) { validation.showAllMessages(); return $.Deferred().reject(); } var order = this.order; //var regionId = model.receiptRegionId(); var data = { orderId: order.Id(), remark: $(this._page.element).find('[name="remark"]').val(), //order.Remark(), invoice: order.Invoice(), address: order.ReceiptAddress(), regionId: order.ReceiptRegionId() }; return shopping.confirmOrder(data).pipe(() => { var productIds = []; var orderDetails = this.order.OrderDetails(); for (var i = 0; i < orderDetails.length; i++) { productIds.push(orderDetails[i].ProductId()); } return shoppingCart.removeItems(productIds); }) .done(() => { debugger; //=============================================== // 进入后订单列表,按返回键可以进入到个人中心 window.location['skip'] window.location.href = '#User_Index'; //================================================ if (ko.unwrap(order.actualPaid) > 0) { window.location.href = '#Shopping_Purchase_' + ko.unwrap(this.order.Id); } else { window.location.href = '#Shopping_OrderList'; } }); } showInvoice = () => { return app.redirect('#Shopping_Invoice', { order: this.order }); } showReceipts = () => { return app.redirect('#User_ReceiptList', { order: this.order }); } showCoupons = () => { return avalibleCoupons.open(ko.unwrap(this.order.Id)); //return app.redirect('Shopping_AvailableCoupons', { coupons: ko.unwrap(model.coupons), parentModel: model }) } } class OrderProductsPage extends chitu.Page { private validation; private model: Model;// = new Model(page); private orderId; constructor(params) { super(params); this.model = new Model(this); avalibleCoupons.couponCodeSelected = (coupon) => { shopping.useCoupon(ko.unwrap(this.model.order.Id), coupon.Code).done((data) => { debugger; mapping.fromJS(data, {}, this.model.order); }); } var orderId; this.load.add(this.page_load); } private page_load(sender: OrderProductsPage, args) { if (this.orderId == args.id) return; this.orderId = args.id; return $.when(account.getBalance(), shopping.getOrder(args.id), coupon.getAvailableCoupons(args.id)) .done((balance, order, coupons) => { if (order == null) { return app.showPage('Shopping_ShoppingCart', {}); } this.model.orderSummary(ko.unwrap(order.Sum)); this.model.balance(balance); this.model.coupons(coupons); if (coupons.length > 0) { this.model.couponTitle(chitu.Utility.format('{0}可用张优惠', coupons.length)); } // order.total = ko.computed(function () { // var total = ko.unwrap(this.Sum); // return total; // }, order); // order.balance = ko.computed(function () { // var balanceAmount = ko.unwrap(this.BalanceAmount) || 0; // if (balanceAmount) // return balanceAmount; // var sum = ko.unwrap(this.Sum); // if (balance > sum) { // return sum; // } // return balance; // }, order); // order.isBalancePay = ko.pureComputed({ // read: function () { // if (ko.unwrap(this.BalanceAmount)) // return true; // return false; // }, // write: function (value) { // if (value) { // var balanceAmount = this.balance(); // return shopping.balancePay(ko.unwrap(this.model.order.Id), balanceAmount).done(function (data) { // mapping.fromJS(data, {}, this.model.order); // }); // } // return shopping.balancePay(ko.unwrap(this.model.order.Id), 0).done(function (data) { // mapping.fromJS(data, {}, this.model.order); // }); // } // }, order); // order.actualPaid = ko.computed(function () { // return order.Sum() - order.BalanceAmount(); // }); //if (this.model.order == null) { this.model.order = $.extend(order, new Order(balance, order)); ko.applyBindings(this.model, sender.element); // } // else { // for (var key in order) { // if (ko.isWriteableObservable(order[key])) { // var value = order[key](); // sender.model.order[key](value); // } // } // } }); } } export = OrderProductsPage; // export = function (page) { // /// <param name="page" type="chitu.Page"/> // var validation; // var model = new Model(page); // avalibleCoupons.couponCodeSelected = (coupon) => { // shopping.useCoupon(ko.unwrap(model.order.Id), coupon.Code).done((data) => { // debugger; // mapping.fromJS(data, {}, model.order); // }); // } // var orderId; // page.load.add(function (sender, args) { // /// <param name="sender" type="chitu.Page"/> // if (orderId == args.id) // return; // orderId = args.id; // return $.when(account.getBalance(), shopping.getOrder(args.id), coupon.getAvailableCoupons(args.id)) // .done(function (balance, order, coupons) { // if (order == null) { // return app.showPage('Shopping_ShoppingCart', {}); // } // model.orderSummary(ko.unwrap(order.Sum)); // model.balance(balance); // model.coupons(coupons); // if (coupons.length > 0) { // model.couponTitle(chitu.Utility.format('{0}可用张优惠', coupons.length)); // } // order.total = ko.computed(function () { // var total = ko.unwrap(this.Sum); // return total; // }, order); // order.balance = ko.computed(function () { // var balanceAmount = ko.unwrap(this.BalanceAmount) || 0; // if (balanceAmount) // return balanceAmount; // var sum = ko.unwrap(this.Sum); // if (balance > sum) { // return sum; // } // return balance; // }, order); // order.isBalancePay = ko.pureComputed({ // read: function () { // if (ko.unwrap(this.BalanceAmount)) // return true; // return false; // }, // write: function (value) { // if (value) { // var balanceAmount = this.balance(); // return shopping.balancePay(ko.unwrap(model.order.Id), balanceAmount).done(function (data) { // mapping.fromJS(data, {}, model.order); // }); // } // return shopping.balancePay(ko.unwrap(model.order.Id), 0).done(function (data) { // mapping.fromJS(data, {}, model.order); // }); // } // }, order); // order.actualPaid = ko.computed(function () { // return order.Sum() - order.BalanceAmount(); // }); // if (model.order == null) { // model.order = order; // ko.applyBindings(model, page.element); // } // else { // for (var key in order) { // if (ko.isWriteableObservable(order[key])) { // var value = order[key](); // model.order[key](value); // } // } // } // }); // }); // }
the_stack
import { createText } from "../utility/utility"; import { createFigma } from "figma-api-stub"; import { testRun } from "../../run"; describe("#View.frame(_:)", () => { const figma = createFigma({ simulateErrors: true, isWithoutTimeout: false, }); // eslint-disable-next-line // @ts-ignore global.figma = figma; jest.mock( "../../../node_modules/@figma/plugin-typings/plugin-api.d.ts", () => { const originalModule = jest.requireActual( "../../../node_modules/@figma/plugin-typings/plugin-api.d.ts" ); return { __esModule: true, ...originalModule, createFrame: jest.fn(() => { return { id: "id", type: "FRAME", strokes: [], }; }), }; } ); describe("for VStack", () => { describe("with VStack parent", () => { describe("case for primary axis layout grow", () => { describe("layoutGrow is 0", () => { test("child VStack primary axis size is FIXED and counter axis size is AUTO", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const vstack = figma.createFrame(); vstack.name = "Frame 1"; vstack.layoutMode = "VERTICAL"; vstack.primaryAxisSizingMode = "FIXED"; vstack.counterAxisSizingMode = "AUTO"; // Avoid to add `.frame(width:) to VStack vstack.counterAxisAlignItems = "MIN"; vstack.paddingLeft = 0; vstack.paddingTop = 0; vstack.paddingRight = 0; vstack.paddingBottom = 0; vstack.itemSpacing = 10; vstack.resize(100, 200); vstack.appendChild(createText("1")); vstack.appendChild(createText("2")); vstack.appendChild(createText("3")); vstack.layoutGrow = 0; vstack.strokes = []; vstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "VERTICAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(vstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` VStack(alignment: .leading, spacing: 10) { VStack(alignment: .leading, spacing: 10) { Text("1") Text("2") Text("3") } .frame(height: 200) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); describe("layoutGrow is 1", () => { test("child VStack primary axis size is FIXED and counter axis size is AUTO", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const vstack = figma.createFrame(); vstack.name = "Frame 1"; vstack.layoutMode = "VERTICAL"; vstack.primaryAxisSizingMode = "FIXED"; vstack.counterAxisSizingMode = "AUTO"; // Avoid to add .frame(width:) to child VStack vstack.counterAxisAlignItems = "MIN"; vstack.paddingLeft = 0; vstack.paddingTop = 0; vstack.paddingRight = 0; vstack.paddingBottom = 0; vstack.itemSpacing = 10; vstack.resize(100, 200); vstack.appendChild(createText("1")); vstack.appendChild(createText("2")); vstack.appendChild(createText("3")); vstack.layoutGrow = 1; vstack.strokes = []; vstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "VERTICAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(vstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` VStack(alignment: .leading, spacing: 10) { VStack(alignment: .leading, spacing: 10) { Text("1") Text("2") Text("3") } .frame(maxHeight: .infinity) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); }); describe("case for counter axis stretch patern", () => { describe("layoutAlign is INHERIT", () => { test("child VStack primary axis size is AUTO and counter axis size is FIXED", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const vstack = figma.createFrame(); vstack.name = "Frame 1"; vstack.layoutMode = "VERTICAL"; vstack.primaryAxisSizingMode = "AUTO"; // Avoid to add `.frame(height:) to child VStack vstack.counterAxisSizingMode = "FIXED"; vstack.counterAxisAlignItems = "MIN"; vstack.paddingLeft = 0; vstack.paddingTop = 0; vstack.paddingRight = 0; vstack.paddingBottom = 0; vstack.itemSpacing = 10; vstack.resize(100, 200); vstack.appendChild(createText("1")); vstack.appendChild(createText("2")); vstack.appendChild(createText("3")); vstack.layoutGrow = 0; vstack.layoutAlign = "INHERIT"; vstack.strokes = []; vstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "VERTICAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(vstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` VStack(alignment: .leading, spacing: 10) { VStack(alignment: .leading, spacing: 10) { Text("1") Text("2") Text("3") } .frame(width: 100) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); describe("layoutAlign is STRETCH", () => { test("child VStack primary axis size is AUTO and counter axis size is FIXED", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const vstack = figma.createFrame(); vstack.name = "Frame 1"; vstack.layoutMode = "VERTICAL"; vstack.primaryAxisSizingMode = "AUTO"; // Avoid to add `.frame(height:) to child VStack vstack.counterAxisSizingMode = "AUTO"; // Avoid to add `.frame(width:) to child VStack vstack.counterAxisAlignItems = "MIN"; vstack.paddingLeft = 0; vstack.paddingTop = 0; vstack.paddingRight = 0; vstack.paddingBottom = 0; vstack.itemSpacing = 10; vstack.resize(100, 200); vstack.appendChild(createText("1")); vstack.appendChild(createText("2")); vstack.appendChild(createText("3")); vstack.layoutGrow = 0; vstack.layoutAlign = "STRETCH"; vstack.strokes = []; vstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "VERTICAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(vstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` VStack(alignment: .leading, spacing: 10) { VStack(alignment: .leading, spacing: 10) { Text("1") Text("2") Text("3") } .frame(maxWidth: .infinity) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); }); }); describe("with HStack parent", () => { describe("case for primary axis layout grow", () => { describe("layoutGrow is 0", () => { test("child VStack primary axis size is AUTO and counter axis size is FIXED", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const vstack = figma.createFrame(); vstack.name = "Frame 1"; vstack.layoutMode = "VERTICAL"; vstack.primaryAxisSizingMode = "AUTO"; // Avoid to add `.frame(width:) to child VStack vstack.counterAxisSizingMode = "FIXED"; vstack.counterAxisAlignItems = "MIN"; vstack.paddingLeft = 0; vstack.paddingTop = 0; vstack.paddingRight = 0; vstack.paddingBottom = 0; vstack.itemSpacing = 10; vstack.resize(100, 200); vstack.appendChild(createText("1")); vstack.appendChild(createText("2")); vstack.appendChild(createText("3")); vstack.layoutGrow = 0; vstack.strokes = []; vstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "HORIZONTAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(vstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` HStack(alignment: .top, spacing: 10) { VStack(alignment: .leading, spacing: 10) { Text("1") Text("2") Text("3") } .frame(width: 100) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); describe("layoutGrow is 1", () => { test("child VStack primary axis size is AUTO and counter axis size is FIXED", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const vstack = figma.createFrame(); vstack.name = "Frame 1"; vstack.layoutMode = "VERTICAL"; vstack.primaryAxisSizingMode = "AUTO"; // Avoid to add .frame(width:) to child VStack vstack.counterAxisSizingMode = "FIXED"; vstack.counterAxisAlignItems = "MIN"; vstack.paddingLeft = 0; vstack.paddingTop = 0; vstack.paddingRight = 0; vstack.paddingBottom = 0; vstack.itemSpacing = 10; vstack.resize(100, 200); vstack.appendChild(createText("1")); vstack.appendChild(createText("2")); vstack.appendChild(createText("3")); vstack.layoutGrow = 1; vstack.strokes = []; vstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "HORIZONTAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(vstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` HStack(alignment: .top, spacing: 10) { VStack(alignment: .leading, spacing: 10) { Text("1") Text("2") Text("3") } .frame(maxWidth: .infinity) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); }); describe("case for counter axis stretch patern", () => { describe("layoutAlign is INHERIT", () => { test("child VStack primary axis size is FIXED and counter axis size is AUTO", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const vstack = figma.createFrame(); vstack.name = "Frame 1"; vstack.layoutMode = "VERTICAL"; vstack.primaryAxisSizingMode = "FIXED"; vstack.counterAxisSizingMode = "AUTO"; // Avoid to add `.frame(width:) to child VStack vstack.counterAxisAlignItems = "MIN"; vstack.paddingLeft = 0; vstack.paddingTop = 0; vstack.paddingRight = 0; vstack.paddingBottom = 0; vstack.itemSpacing = 10; vstack.resize(100, 200); vstack.appendChild(createText("1")); vstack.appendChild(createText("2")); vstack.appendChild(createText("3")); vstack.layoutGrow = 0; vstack.layoutAlign = "INHERIT"; vstack.strokes = []; vstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "HORIZONTAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(vstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` HStack(alignment: .top, spacing: 10) { VStack(alignment: .leading, spacing: 10) { Text("1") Text("2") Text("3") } .frame(height: 200) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); describe("layoutAlign is STRETCH", () => { test("child VStack primary axis size is FIXED and counter axis size is AUTO", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const vstack = figma.createFrame(); vstack.name = "Frame 1"; vstack.layoutMode = "VERTICAL"; vstack.primaryAxisSizingMode = "AUTO"; // Avoid to add `.frame(height:) to child VStack vstack.counterAxisSizingMode = "AUTO"; // Avoid to add `.frame(width:) to child VStack vstack.counterAxisAlignItems = "MIN"; vstack.paddingLeft = 0; vstack.paddingTop = 0; vstack.paddingRight = 0; vstack.paddingBottom = 0; vstack.itemSpacing = 10; vstack.resize(100, 200); vstack.appendChild(createText("1")); vstack.appendChild(createText("2")); vstack.appendChild(createText("3")); vstack.layoutGrow = 0; vstack.layoutAlign = "STRETCH"; vstack.strokes = []; vstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "HORIZONTAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(vstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` HStack(alignment: .top, spacing: 10) { VStack(alignment: .leading, spacing: 10) { Text("1") Text("2") Text("3") } .frame(maxHeight: .infinity) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); }); }); describe("without parent", () => { test("VStack primary axis size is FIXED and counter axis size is FIXED", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const vstack = figma.createFrame(); vstack.name = "Frame 1"; vstack.layoutMode = "VERTICAL"; vstack.primaryAxisSizingMode = "FIXED"; vstack.counterAxisSizingMode = "FIXED"; vstack.counterAxisAlignItems = "MIN"; vstack.paddingLeft = 0; vstack.paddingTop = 0; vstack.paddingRight = 0; vstack.paddingBottom = 0; vstack.itemSpacing = 10; vstack.resize(100, 200); vstack.appendChild(createText("1")); vstack.appendChild(createText("2")); vstack.appendChild(createText("3")); vstack.strokes = []; vstack.effects = []; const code = ` VStack(alignment: .leading, spacing: 10) { Text("1") Text("2") Text("3") } .frame(width: 100, height: 200) `; expect(testRun(vstack)).toEqual(code.slice("\n".length)); }); test("VStack primary axis size is AUTO and counter axis size is FIXED", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const vstack = figma.createFrame(); vstack.name = "Frame 1"; vstack.layoutMode = "VERTICAL"; vstack.primaryAxisSizingMode = "AUTO"; vstack.counterAxisSizingMode = "FIXED"; vstack.counterAxisAlignItems = "MIN"; vstack.paddingLeft = 0; vstack.paddingTop = 0; vstack.paddingRight = 0; vstack.paddingBottom = 0; vstack.itemSpacing = 10; vstack.resize(100, 200); vstack.appendChild(createText("1")); vstack.appendChild(createText("2")); vstack.appendChild(createText("3")); vstack.strokes = []; vstack.effects = []; const code = ` VStack(alignment: .leading, spacing: 10) { Text("1") Text("2") Text("3") } .frame(width: 100) `; expect(testRun(vstack)).toEqual(code.slice("\n".length)); }); test("VStack primary axis size is AUTO and counter axis size is AUTO", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const vstack = figma.createFrame(); vstack.name = "Frame 1"; vstack.layoutMode = "VERTICAL"; vstack.primaryAxisSizingMode = "AUTO"; vstack.counterAxisSizingMode = "AUTO"; vstack.counterAxisAlignItems = "MIN"; vstack.paddingLeft = 0; vstack.paddingTop = 0; vstack.paddingRight = 0; vstack.paddingBottom = 0; vstack.itemSpacing = 10; vstack.resize(100, 200); vstack.appendChild(createText("1")); vstack.appendChild(createText("2")); vstack.appendChild(createText("3")); vstack.strokes = []; vstack.effects = []; const code = ` VStack(alignment: .leading, spacing: 10) { Text("1") Text("2") Text("3") } `; expect(testRun(vstack)).toEqual(code.slice("\n".length)); }); }); }); describe("for HStack", () => { describe("with VStack parent", () => { describe("case for primary axis layout grow", () => { describe("layoutGrow is 0", () => { test("child HStack primary axis size is FIXED and counter axis size is AUTO", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const hstack = figma.createFrame(); hstack.name = "Frame 1"; hstack.layoutMode = "HORIZONTAL"; hstack.primaryAxisSizingMode = "FIXED"; hstack.counterAxisSizingMode = "AUTO"; // Avoid to add `.frame(height:) to child HStack hstack.counterAxisAlignItems = "MIN"; hstack.paddingLeft = 0; hstack.paddingTop = 0; hstack.paddingRight = 0; hstack.paddingBottom = 0; hstack.itemSpacing = 10; hstack.resize(100, 200); hstack.appendChild(createText("1")); hstack.appendChild(createText("2")); hstack.appendChild(createText("3")); hstack.layoutGrow = 0; hstack.strokes = []; hstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "VERTICAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(hstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` VStack(alignment: .leading, spacing: 10) { HStack(alignment: .top, spacing: 10) { Text("1") Text("2") Text("3") } .frame(width: 100) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); describe("layoutGrow is 1", () => { test("child HStack primary axis size is FIXED and counter axis size is AUTO", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const hstack = figma.createFrame(); hstack.name = "Frame 1"; hstack.layoutMode = "HORIZONTAL"; hstack.primaryAxisSizingMode = "AUTO"; // Avoid to add .frame(width:) to child VStack hstack.counterAxisSizingMode = "FIXED"; hstack.counterAxisAlignItems = "MIN"; hstack.paddingLeft = 0; hstack.paddingTop = 0; hstack.paddingRight = 0; hstack.paddingBottom = 0; hstack.itemSpacing = 10; hstack.resize(100, 200); hstack.appendChild(createText("1")); hstack.appendChild(createText("2")); hstack.appendChild(createText("3")); hstack.layoutGrow = 1; hstack.strokes = []; hstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "VERTICAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(hstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` VStack(alignment: .leading, spacing: 10) { HStack(alignment: .top, spacing: 10) { Text("1") Text("2") Text("3") } .frame(maxHeight: .infinity) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); }); describe("case for counter axis stretch patern", () => { describe("layoutAlign is INHERIT", () => { test("child HStack primary axis size is AUTO and counter axis size is FIXED", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const hstack = figma.createFrame(); hstack.name = "Frame 1"; hstack.layoutMode = "HORIZONTAL"; hstack.primaryAxisSizingMode = "AUTO"; // Avoid to add `.frame(height:) to child VStack hstack.counterAxisSizingMode = "FIXED"; hstack.counterAxisAlignItems = "MIN"; hstack.paddingLeft = 0; hstack.paddingTop = 0; hstack.paddingRight = 0; hstack.paddingBottom = 0; hstack.itemSpacing = 10; hstack.resize(100, 200); hstack.appendChild(createText("1")); hstack.appendChild(createText("2")); hstack.appendChild(createText("3")); hstack.layoutGrow = 0; hstack.layoutAlign = "INHERIT"; hstack.strokes = []; hstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "VERTICAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(hstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` VStack(alignment: .leading, spacing: 10) { HStack(alignment: .top, spacing: 10) { Text("1") Text("2") Text("3") } .frame(height: 200) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); describe("layoutAlign is STRETCH", () => { test("child HStack primary axis size is AUTO and counter axis size is FIXED", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const hstack = figma.createFrame(); hstack.name = "Frame 1"; hstack.layoutMode = "HORIZONTAL"; hstack.primaryAxisSizingMode = "AUTO"; // Avoid to add `.frame(height:) to child VStack hstack.counterAxisSizingMode = "AUTO"; // Avoid to add `.frame(width:) to child VStack hstack.counterAxisAlignItems = "MIN"; hstack.paddingLeft = 0; hstack.paddingTop = 0; hstack.paddingRight = 0; hstack.paddingBottom = 0; hstack.itemSpacing = 10; hstack.resize(100, 200); hstack.appendChild(createText("1")); hstack.appendChild(createText("2")); hstack.appendChild(createText("3")); hstack.layoutGrow = 0; hstack.layoutAlign = "STRETCH"; hstack.strokes = []; hstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "VERTICAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(hstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` VStack(alignment: .leading, spacing: 10) { HStack(alignment: .top, spacing: 10) { Text("1") Text("2") Text("3") } .frame(maxWidth: .infinity) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); }); }); describe("with HStack parent", () => { describe("case for primary axis layout grow", () => { describe("layoutGrow is 0", () => { test("child VStack primary axis size is AUTO and counter axis size is FIXED", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const hstack = figma.createFrame(); hstack.name = "Frame 1"; hstack.layoutMode = "HORIZONTAL"; hstack.primaryAxisSizingMode = "AUTO"; // Avoid to add `.frame(height:) to child VStack hstack.counterAxisSizingMode = "FIXED"; hstack.counterAxisAlignItems = "MIN"; hstack.paddingLeft = 0; hstack.paddingTop = 0; hstack.paddingRight = 0; hstack.paddingBottom = 0; hstack.itemSpacing = 10; hstack.resize(100, 200); hstack.appendChild(createText("1")); hstack.appendChild(createText("2")); hstack.appendChild(createText("3")); hstack.layoutGrow = 0; hstack.strokes = []; hstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "HORIZONTAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(hstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` HStack(alignment: .top, spacing: 10) { HStack(alignment: .top, spacing: 10) { Text("1") Text("2") Text("3") } .frame(height: 200) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); describe("layoutGrow is 1", () => { test("child HStack primary axis size is FIXED and counter axis size is AUTO", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const hstack = figma.createFrame(); hstack.name = "Frame 1"; hstack.layoutMode = "HORIZONTAL"; hstack.primaryAxisSizingMode = "FIXED"; hstack.counterAxisSizingMode = "AUTO"; // Avoid to add .frame(width:) to child VStack hstack.counterAxisAlignItems = "MIN"; hstack.paddingLeft = 0; hstack.paddingTop = 0; hstack.paddingRight = 0; hstack.paddingBottom = 0; hstack.itemSpacing = 10; hstack.resize(100, 200); hstack.appendChild(createText("1")); hstack.appendChild(createText("2")); hstack.appendChild(createText("3")); hstack.layoutGrow = 1; hstack.strokes = []; hstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "HORIZONTAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(hstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` HStack(alignment: .top, spacing: 10) { HStack(alignment: .top, spacing: 10) { Text("1") Text("2") Text("3") } .frame(maxWidth: .infinity) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); }); describe("case for counter axis stretch patern", () => { describe("layoutAlign is INHERIT", () => { test("child HStack primary axis size is AUTO and counter axis size is FIXED", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const hstack = figma.createFrame(); hstack.name = "Frame 1"; hstack.layoutMode = "HORIZONTAL"; hstack.primaryAxisSizingMode = "AUTO"; // Avoid to add `.frame(width:) to child HStack hstack.counterAxisSizingMode = "FIXED"; hstack.counterAxisAlignItems = "MIN"; hstack.paddingLeft = 0; hstack.paddingTop = 0; hstack.paddingRight = 0; hstack.paddingBottom = 0; hstack.itemSpacing = 10; hstack.resize(100, 200); hstack.appendChild(createText("1")); hstack.appendChild(createText("2")); hstack.appendChild(createText("3")); hstack.layoutGrow = 0; hstack.layoutAlign = "INHERIT"; hstack.strokes = []; hstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "HORIZONTAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(hstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` HStack(alignment: .top, spacing: 10) { HStack(alignment: .top, spacing: 10) { Text("1") Text("2") Text("3") } .frame(height: 200) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); describe("layoutAlign is STRETCH", () => { test("child HStack primary axis size is FIXED and counter axis size is AUTO", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const hstack = figma.createFrame(); hstack.name = "Frame 1"; hstack.layoutMode = "HORIZONTAL"; hstack.primaryAxisSizingMode = "AUTO"; // Avoid to add `.frame(height:) to child VStack hstack.counterAxisSizingMode = "AUTO"; // Avoid to add `.frame(width:) to child VStack hstack.counterAxisAlignItems = "MIN"; hstack.paddingLeft = 0; hstack.paddingTop = 0; hstack.paddingRight = 0; hstack.paddingBottom = 0; hstack.itemSpacing = 10; hstack.resize(100, 200); hstack.appendChild(createText("1")); hstack.appendChild(createText("2")); hstack.appendChild(createText("3")); hstack.layoutGrow = 0; hstack.layoutAlign = "STRETCH"; hstack.strokes = []; hstack.effects = []; const parent = figma.createFrame(); parent.name = "Frame 2"; parent.layoutMode = "HORIZONTAL"; // Any values: BEGIN parent.primaryAxisSizingMode = "FIXED"; parent.counterAxisSizingMode = "FIXED"; parent.counterAxisAlignItems = "MIN"; parent.paddingLeft = 0; parent.paddingTop = 0; parent.paddingRight = 0; parent.paddingBottom = 0; parent.itemSpacing = 10; parent.resize(300, 400); // Any values: END parent.appendChild(hstack); parent.appendChild(createText("4")); parent.strokes = []; parent.effects = []; const code = ` HStack(alignment: .top, spacing: 10) { HStack(alignment: .top, spacing: 10) { Text("1") Text("2") Text("3") } .frame(maxHeight: .infinity) Text("4") } .frame(width: 300, height: 400) `; expect(testRun(parent)).toEqual(code.slice("\n".length)); }); }); }); }); describe("without parent", () => { test("HStack primary axis size is FIXED and counter axis size is FIXED", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const hstack = figma.createFrame(); hstack.name = "Frame 1"; hstack.layoutMode = "HORIZONTAL"; hstack.primaryAxisSizingMode = "FIXED"; hstack.counterAxisSizingMode = "FIXED"; hstack.counterAxisAlignItems = "MIN"; hstack.paddingLeft = 0; hstack.paddingTop = 0; hstack.paddingRight = 0; hstack.paddingBottom = 0; hstack.itemSpacing = 10; hstack.resize(100, 200); hstack.appendChild(createText("1")); hstack.appendChild(createText("2")); hstack.appendChild(createText("3")); hstack.strokes = []; hstack.effects = []; const code = ` HStack(alignment: .top, spacing: 10) { Text("1") Text("2") Text("3") } .frame(width: 100, height: 200) `; expect(testRun(hstack)).toEqual(code.slice("\n".length)); }); test("HStack primary axis size is AUTO and counter axis size is FIXED", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const hstack = figma.createFrame(); hstack.name = "Frame 1"; hstack.layoutMode = "HORIZONTAL"; hstack.primaryAxisSizingMode = "AUTO"; hstack.counterAxisSizingMode = "FIXED"; hstack.counterAxisAlignItems = "MIN"; hstack.paddingLeft = 0; hstack.paddingTop = 0; hstack.paddingRight = 0; hstack.paddingBottom = 0; hstack.itemSpacing = 10; hstack.resize(100, 200); hstack.appendChild(createText("1")); hstack.appendChild(createText("2")); hstack.appendChild(createText("3")); hstack.strokes = []; hstack.effects = []; const code = ` HStack(alignment: .top, spacing: 10) { Text("1") Text("2") Text("3") } .frame(height: 200) `; expect(testRun(hstack)).toEqual(code.slice("\n".length)); }); test("HStack primary axis size is AUTO and counter axis size is AUTO", async () => { await figma.loadFontAsync({ family: "Roboto", style: "Regular" }); const hstack = figma.createFrame(); hstack.name = "Frame 1"; hstack.layoutMode = "HORIZONTAL"; hstack.primaryAxisSizingMode = "AUTO"; hstack.counterAxisSizingMode = "AUTO"; hstack.counterAxisAlignItems = "MIN"; hstack.paddingLeft = 0; hstack.paddingTop = 0; hstack.paddingRight = 0; hstack.paddingBottom = 0; hstack.itemSpacing = 10; hstack.resize(100, 200); hstack.appendChild(createText("1")); hstack.appendChild(createText("2")); hstack.appendChild(createText("3")); hstack.strokes = []; hstack.effects = []; const code = ` HStack(alignment: .top, spacing: 10) { Text("1") Text("2") Text("3") } `; expect(testRun(hstack)).toEqual(code.slice("\n".length)); }); }); }); });
the_stack
/// <reference no-default-lib="true"/> ///////////////////////////// /// ECMAScript APIs ///////////////////////////// declare const NaN: number; declare const Infinity: number; /*! ***************************************************************************** Modifications Copyright (c) 2018 Tencent, Inc. All rights reserved. ***************************************************************************** */ /** * Evaluates JavaScript code and executes it. * @ param x A String value that contains valid JavaScript code. */ // WA-no-eval // declare function eval(x: string): any; /** * Converts A string to an integer. * @param s A string to convert into a number. * @param radix A value between 2 and 36 that specifies the base of the number in numString. * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. * All other strings are considered decimal. */ declare function parseInt(s: string, radix?: number): number; /** * Converts a string to a floating-point number. * @param string A string that contains a floating-point number. */ declare function parseFloat(string: string): number; /** * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). * @param number A numeric value. */ declare function isNaN(number: number): boolean; /** * Determines whether a supplied number is finite. * @param number Any numeric value. */ declare function isFinite(number: number): boolean; /** * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). * @param encodedURI A value representing an encoded URI. */ declare function decodeURI(encodedURI: string): string; /** * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). * @param encodedURIComponent A value representing an encoded URI component. */ declare function decodeURIComponent(encodedURIComponent: string): string; /** * Encodes a text string as a valid Uniform Resource Identifier (URI) * @param uri A value representing an encoded URI. */ declare function encodeURI(uri: string): string; /** * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). * @param uriComponent A value representing an encoded URI component. */ declare function encodeURIComponent(uriComponent: string): string; interface PropertyDescriptor { configurable?: boolean; enumerable?: boolean; value?: any; writable?: boolean; get?(): any; set?(v: any): void; } interface PropertyDescriptorMap { [s: string]: PropertyDescriptor; } interface Object { /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ constructor: Function; /** Returns a string representation of an object. */ toString(): string; /** Returns a date converted to a string using the current locale. */ toLocaleString(): string; /** Returns the primitive value of the specified object. */ valueOf(): Object; /** * Determines whether an object has a property with the specified name. * @param v A property name. */ hasOwnProperty(v: string): boolean; /** * Determines whether an object exists in another object's prototype chain. * @param v Another object whose prototype chain is to be checked. */ isPrototypeOf(v: Object): boolean; /** * Determines whether a specified property is enumerable. * @param v A property name. */ propertyIsEnumerable(v: string): boolean; } interface ObjectConstructor { new(value?: any): Object; (): any; (value: any): any; /** A reference to the prototype for a class of objects. */ readonly prototype: Object; /** * Returns the prototype of an object. * @param o The object that references the prototype. */ getPrototypeOf(o: any): any; /** * Gets the own property descriptor of the specified object. * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. * @param o Object that contains the property. * @param p Name of the property. */ getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor | undefined; /** * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. * @param o Object that contains the own properties. */ getOwnPropertyNames(o: any): string[]; /** * Creates an object that has the specified prototype or that has null prototype. * @param o Object to use as a prototype. May be null. */ create(o: object | null): any; /** * Creates an object that has the specified prototype, and that optionally contains specified properties. * @param o Object to use as a prototype. May be null * @param properties JavaScript object that contains one or more property descriptors. */ create(o: object | null, properties: PropertyDescriptorMap & ThisType<any>): any; /** * Adds a property to an object, or modifies attributes of an existing property. * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. * @param p The property name. * @param attributes Descriptor for the property. It can be for a data property or an accessor property. */ defineProperty(o: any, p: string, attributes: PropertyDescriptor & ThisType<any>): any; /** * Adds one or more properties to an object, and/or modifies attributes of existing properties. * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. */ defineProperties(o: any, properties: PropertyDescriptorMap & ThisType<any>): any; /** * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. * @param o Object on which to lock the attributes. */ seal<T>(o: T): T; /** * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. * @param o Object on which to lock the attributes. */ freeze<T>(a: T[]): ReadonlyArray<T>; /** * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. * @param o Object on which to lock the attributes. */ freeze<T extends Function>(f: T): T; /** * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. * @param o Object on which to lock the attributes. */ freeze<T>(o: T): Readonly<T>; /** * Prevents the addition of new properties to an object. * @param o Object to make non-extensible. */ preventExtensions<T>(o: T): T; /** * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. * @param o Object to test. */ isSealed(o: any): boolean; /** * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. * @param o Object to test. */ isFrozen(o: any): boolean; /** * Returns a value that indicates whether new properties can be added to an object. * @param o Object to test. */ isExtensible(o: any): boolean; /** * Returns the names of the enumerable properties and methods of an object. * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ keys(o: {}): string[]; } /** * Provides functionality common to all JavaScript objects. */ declare const Object: ObjectConstructor; /** * Creates a new function. */ interface Function { /** * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. * @param thisArg The object to be used as the this object. * @param argArray A set of arguments to be passed to the function. */ apply(this: Function, thisArg: any, argArray?: any): any; /** * Calls a method of an object, substituting another object for the current object. * @param thisArg The object to be used as the current object. * @param argArray A list of arguments to be passed to the method. */ call(this: Function, thisArg: any, ...argArray: any[]): any; /** * For a given function, creates a bound function that has the same body as the original function. * The this object of the bound function is associated with the specified object, and has the specified initial parameters. * @param thisArg An object to which the this keyword can refer inside the new function. * @param argArray A list of arguments to be passed to the new function. */ bind(this: Function, thisArg: any, ...argArray: any[]): any; /** Returns a string representation of a function. */ toString(): string; prototype: any; readonly length: number; // Non-standard extensions arguments: any; caller: Function; } interface FunctionConstructor { /** * Creates a new function. * @param args A list of arguments the function accepts. */ new(...args: string[]): Function; (...args: string[]): Function; readonly prototype: Function; } declare const Function: FunctionConstructor; interface IArguments { [index: number]: any; length: number; callee: Function; } interface String { /** Returns a string representation of a string. */ toString(): string; /** * Returns the character at the specified index. * @param pos The zero-based index of the desired character. */ charAt(pos: number): string; /** * Returns the Unicode value of the character at the specified location. * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. */ charCodeAt(index: number): number; /** * Returns a string that contains the concatenation of two or more strings. * @param strings The strings to append to the end of the string. */ concat(...strings: string[]): string; /** * Returns the position of the first occurrence of a substring. * @param searchString The substring to search for in the string * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. */ indexOf(searchString: string, position?: number): number; /** * Returns the last occurrence of a substring in the string. * @param searchString The substring to search for. * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. */ lastIndexOf(searchString: string, position?: number): number; /** * Determines whether two strings are equivalent in the current locale. * @param that String to compare to target string */ localeCompare(that: string): number; /** * Matches a string with a regular expression, and returns an array containing the results of that search. * @param regexp A variable name or string literal containing the regular expression pattern and flags. */ match(regexp: string | RegExp): RegExpMatchArray | null; /** * Replaces text in a string, using a regular expression or search string. * @param searchValue A string to search for. * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. */ replace(searchValue: string | RegExp, replaceValue: string): string; /** * Replaces text in a string, using a regular expression or search string. * @param searchValue A string to search for. * @param replacer A function that returns the replacement text. */ replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string; /** * Finds the first substring match in a regular expression search. * @param regexp The regular expression pattern and applicable flags. */ search(regexp: string | RegExp): number; /** * Returns a section of a string. * @param start The index to the beginning of the specified portion of stringObj. * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. * If this value is not specified, the substring continues to the end of stringObj. */ slice(start?: number, end?: number): string; /** * Split a string into substrings using the specified separator and return them as an array. * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. * @param limit A value used to limit the number of elements returned in the array. */ split(separator: string | RegExp, limit?: number): string[]; /** * Returns the substring at the specified location within a String object. * @param start The zero-based index number indicating the beginning of the substring. * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. * If end is omitted, the characters from start through the end of the original string are returned. */ substring(start: number, end?: number): string; /** Converts all the alphabetic characters in a string to lowercase. */ toLowerCase(): string; /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ toLocaleLowerCase(): string; /** Converts all the alphabetic characters in a string to uppercase. */ toUpperCase(): string; /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ toLocaleUpperCase(): string; /** Removes the leading and trailing white space and line terminator characters from a string. */ trim(): string; /** Returns the length of a String object. */ readonly length: number; // IE extensions /** * Gets a substring beginning at the specified location and having the specified length. * @param from The starting position of the desired substring. The index of the first character in the string is zero. * @param length The number of characters to include in the returned substring. */ substr(from: number, length?: number): string; /** Returns the primitive value of the specified object. */ valueOf(): string; readonly [index: number]: string; } interface StringConstructor { new(value?: any): String; (value?: any): string; readonly prototype: String; fromCharCode(...codes: number[]): string; } /** * Allows manipulation and formatting of text strings and determination and location of substrings within strings. */ declare const String: StringConstructor; interface Boolean { /** Returns the primitive value of the specified object. */ valueOf(): boolean; } interface BooleanConstructor { new(value?: any): Boolean; (value?: any): boolean; readonly prototype: Boolean; } declare const Boolean: BooleanConstructor; interface Number { /** * Returns a string representation of an object. * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. */ toString(radix?: number): string; /** * Returns a string representing a number in fixed-point notation. * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. */ toFixed(fractionDigits?: number): string; /** * Returns a string containing a number represented in exponential notation. * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. */ toExponential(fractionDigits?: number): string; /** * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. */ toPrecision(precision?: number): string; /** Returns the primitive value of the specified object. */ valueOf(): number; } interface NumberConstructor { new(value?: any): Number; (value?: any): number; readonly prototype: Number; /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ readonly MAX_VALUE: number; /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ readonly MIN_VALUE: number; /** * A value that is not a number. * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. */ readonly NaN: number; /** * A value that is less than the largest negative number that can be represented in JavaScript. * JavaScript displays NEGATIVE_INFINITY values as -infinity. */ readonly NEGATIVE_INFINITY: number; /** * A value greater than the largest number that can be represented in JavaScript. * JavaScript displays POSITIVE_INFINITY values as infinity. */ readonly POSITIVE_INFINITY: number; } /** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ declare const Number: NumberConstructor; interface TemplateStringsArray extends ReadonlyArray<string> { readonly raw: ReadonlyArray<string>; } interface Math { /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ readonly E: number; /** The natural logarithm of 10. */ readonly LN10: number; /** The natural logarithm of 2. */ readonly LN2: number; /** The base-2 logarithm of e. */ readonly LOG2E: number; /** The base-10 logarithm of e. */ readonly LOG10E: number; /** Pi. This is the ratio of the circumference of a circle to its diameter. */ readonly PI: number; /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ readonly SQRT1_2: number; /** The square root of 2. */ readonly SQRT2: number; /** * Returns the absolute value of a number (the value without regard to whether it is positive or negative). * For example, the absolute value of -5 is the same as the absolute value of 5. * @param x A numeric expression for which the absolute value is needed. */ abs(x: number): number; /** * Returns the arc cosine (or inverse cosine) of a number. * @param x A numeric expression. */ acos(x: number): number; /** * Returns the arcsine of a number. * @param x A numeric expression. */ asin(x: number): number; /** * Returns the arctangent of a number. * @param x A numeric expression for which the arctangent is needed. */ atan(x: number): number; /** * Returns the angle (in radians) from the X axis to a point. * @param y A numeric expression representing the cartesian y-coordinate. * @param x A numeric expression representing the cartesian x-coordinate. */ atan2(y: number, x: number): number; /** * Returns the smallest number greater than or equal to its numeric argument. * @param x A numeric expression. */ ceil(x: number): number; /** * Returns the cosine of a number. * @param x A numeric expression that contains an angle measured in radians. */ cos(x: number): number; /** * Returns e (the base of natural logarithms) raised to a power. * @param x A numeric expression representing the power of e. */ exp(x: number): number; /** * Returns the greatest number less than or equal to its numeric argument. * @param x A numeric expression. */ floor(x: number): number; /** * Returns the natural logarithm (base e) of a number. * @param x A numeric expression. */ log(x: number): number; /** * Returns the larger of a set of supplied numeric expressions. * @param values Numeric expressions to be evaluated. */ max(...values: number[]): number; /** * Returns the smaller of a set of supplied numeric expressions. * @param values Numeric expressions to be evaluated. */ min(...values: number[]): number; /** * Returns the value of a base expression taken to a specified power. * @param x The base value of the expression. * @param y The exponent value of the expression. */ pow(x: number, y: number): number; /** Returns a pseudorandom number between 0 and 1. */ random(): number; /** * Returns a supplied numeric expression rounded to the nearest number. * @param x The value to be rounded to the nearest number. */ round(x: number): number; /** * Returns the sine of a number. * @param x A numeric expression that contains an angle measured in radians. */ sin(x: number): number; /** * Returns the square root of a number. * @param x A numeric expression. */ sqrt(x: number): number; /** * Returns the tangent of a number. * @param x A numeric expression that contains an angle measured in radians. */ tan(x: number): number; } /** An intrinsic object that provides basic mathematics functionality and constants. */ declare const Math: Math; /** Enables basic storage and retrieval of dates and times. */ interface Date { /** Returns a string representation of a date. The format of the string depends on the locale. */ toString(): string; /** Returns a date as a string value. */ toDateString(): string; /** Returns a time as a string value. */ toTimeString(): string; /** Returns a value as a string value appropriate to the host environment's current locale. */ toLocaleString(): string; /** Returns a date as a string value appropriate to the host environment's current locale. */ toLocaleDateString(): string; /** Returns a time as a string value appropriate to the host environment's current locale. */ toLocaleTimeString(): string; /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ valueOf(): number; /** Gets the time value in milliseconds. */ getTime(): number; /** Gets the year, using local time. */ getFullYear(): number; /** Gets the year using Universal Coordinated Time (UTC). */ getUTCFullYear(): number; /** Gets the month, using local time. */ getMonth(): number; /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ getUTCMonth(): number; /** Gets the day-of-the-month, using local time. */ getDate(): number; /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ getUTCDate(): number; /** Gets the day of the week, using local time. */ getDay(): number; /** Gets the day of the week using Universal Coordinated Time (UTC). */ getUTCDay(): number; /** Gets the hours in a date, using local time. */ getHours(): number; /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ getUTCHours(): number; /** Gets the minutes of a Date object, using local time. */ getMinutes(): number; /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ getUTCMinutes(): number; /** Gets the seconds of a Date object, using local time. */ getSeconds(): number; /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ getUTCSeconds(): number; /** Gets the milliseconds of a Date, using local time. */ getMilliseconds(): number; /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ getUTCMilliseconds(): number; /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ getTimezoneOffset(): number; /** * Sets the date and time value in the Date object. * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. */ setTime(time: number): number; /** * Sets the milliseconds value in the Date object using local time. * @param ms A numeric value equal to the millisecond value. */ setMilliseconds(ms: number): number; /** * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). * @param ms A numeric value equal to the millisecond value. */ setUTCMilliseconds(ms: number): number; /** * Sets the seconds value in the Date object using local time. * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ setSeconds(sec: number, ms?: number): number; /** * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ setUTCSeconds(sec: number, ms?: number): number; /** * Sets the minutes value in the Date object using local time. * @param min A numeric value equal to the minutes value. * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ setMinutes(min: number, sec?: number, ms?: number): number; /** * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). * @param min A numeric value equal to the minutes value. * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ setUTCMinutes(min: number, sec?: number, ms?: number): number; /** * Sets the hour value in the Date object using local time. * @param hours A numeric value equal to the hours value. * @param min A numeric value equal to the minutes value. * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ setHours(hours: number, min?: number, sec?: number, ms?: number): number; /** * Sets the hours value in the Date object using Universal Coordinated Time (UTC). * @param hours A numeric value equal to the hours value. * @param min A numeric value equal to the minutes value. * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; /** * Sets the numeric day-of-the-month value of the Date object using local time. * @param date A numeric value equal to the day of the month. */ setDate(date: number): number; /** * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). * @param date A numeric value equal to the day of the month. */ setUTCDate(date: number): number; /** * Sets the month value in the Date object using local time. * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. */ setMonth(month: number, date?: number): number; /** * Sets the month value in the Date object using Universal Coordinated Time (UTC). * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. */ setUTCMonth(month: number, date?: number): number; /** * Sets the year of the Date object using local time. * @param year A numeric value for the year. * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. * @param date A numeric value equal for the day of the month. */ setFullYear(year: number, month?: number, date?: number): number; /** * Sets the year value in the Date object using Universal Coordinated Time (UTC). * @param year A numeric value equal to the year. * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. * @param date A numeric value equal to the day of the month. */ setUTCFullYear(year: number, month?: number, date?: number): number; /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ toUTCString(): string; /** Returns a date as a string value in ISO format. */ toISOString(): string; /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ toJSON(key?: any): string; } interface DateConstructor { new(): Date; new(value: number): Date; new(value: string): Date; new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; (): string; readonly prototype: Date; /** * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. * @param s A date string */ parse(s: string): number; /** * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. * @param month The month as an number between 0 and 11 (January to December). * @param date The date as an number between 1 and 31. * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. * @param ms An number from 0 to 999 that specifies the milliseconds. */ UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; now(): number; } declare const Date: DateConstructor; interface RegExpMatchArray extends Array<string> { index?: number; input?: string; } interface RegExpExecArray extends Array<string> { index: number; input: string; } interface RegExp { /** * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. * @param string The String object or string literal on which to perform the search. */ exec(string: string): RegExpExecArray | null; /** * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. * @param string String on which to perform the search. */ test(string: string): boolean; /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ readonly source: string; /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ readonly global: boolean; /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ readonly ignoreCase: boolean; /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ readonly multiline: boolean; lastIndex: number; // Non-standard extensions compile(): this; } interface RegExpConstructor { new(pattern: RegExp | string): RegExp; new(pattern: string, flags?: string): RegExp; (pattern: RegExp | string): RegExp; (pattern: string, flags?: string): RegExp; readonly prototype: RegExp; // Non-standard extensions $1: string; $2: string; $3: string; $4: string; $5: string; $6: string; $7: string; $8: string; $9: string; lastMatch: string; } declare const RegExp: RegExpConstructor; interface Error { name: string; message: string; stack?: string; } interface ErrorConstructor { new(message?: string): Error; (message?: string): Error; readonly prototype: Error; } declare const Error: ErrorConstructor; interface EvalError extends Error { } interface EvalErrorConstructor { new(message?: string): EvalError; (message?: string): EvalError; readonly prototype: EvalError; } declare const EvalError: EvalErrorConstructor; interface RangeError extends Error { } interface RangeErrorConstructor { new(message?: string): RangeError; (message?: string): RangeError; readonly prototype: RangeError; } declare const RangeError: RangeErrorConstructor; interface ReferenceError extends Error { } interface ReferenceErrorConstructor { new(message?: string): ReferenceError; (message?: string): ReferenceError; readonly prototype: ReferenceError; } declare const ReferenceError: ReferenceErrorConstructor; interface SyntaxError extends Error { } interface SyntaxErrorConstructor { new(message?: string): SyntaxError; (message?: string): SyntaxError; readonly prototype: SyntaxError; } declare const SyntaxError: SyntaxErrorConstructor; interface TypeError extends Error { } interface TypeErrorConstructor { new(message?: string): TypeError; (message?: string): TypeError; readonly prototype: TypeError; } declare const TypeError: TypeErrorConstructor; interface URIError extends Error { } interface URIErrorConstructor { new(message?: string): URIError; (message?: string): URIError; readonly prototype: URIError; } declare const URIError: URIErrorConstructor; interface JSON { /** * Converts a JavaScript Object Notation (JSON) string into an object. * @param text A valid JSON string. * @param reviver A function that transforms the results. This function is called for each member of the object. * If a member contains nested objects, the nested objects are transformed before the parent object is. */ parse(text: string, reviver?: (key: any, value: any) => any): any; /** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * @param value A JavaScript value, usually an object or array, to be converted. * @param replacer A function that transforms the results. * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. */ stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; /** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * @param value A JavaScript value, usually an object or array, to be converted. * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified. * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. */ stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string; } /** * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. */ declare const JSON: JSON; ///////////////////////////// /// ECMAScript Array API (specially handled by compiler) ///////////////////////////// interface ReadonlyArray<T> { /** * Gets the length of the array. This is a number one higher than the highest element defined in an array. */ readonly length: number; /** * Returns a string representation of an array. */ toString(): string; /** * Returns a string representation of an array. The elements are converted to string using thier toLocalString methods. */ toLocaleString(): string; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ concat(...items: ReadonlyArray<T>[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ concat(...items: (T | ReadonlyArray<T>)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): T[]; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. */ indexOf(searchElement: T, fromIndex?: number): number; /** * Returns the index of the last occurrence of a specified value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. */ lastIndexOf(searchElement: T, fromIndex?: number): number; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg?: any): boolean; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg?: any): boolean; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => void, thisArg?: any): void; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ map<U>(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => U, thisArg?: any): U[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ filter<S extends T>(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => value is S, thisArg?: any): S[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => any, thisArg?: any): T[]; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray<T>) => T, initialValue?: T): T; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray<T>) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray<T>) => T, initialValue?: T): T; /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray<T>) => U, initialValue: U): U; readonly [n: number]: T; } interface Array<T> { /** * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. */ length: number; /** * Returns a string representation of an array. */ toString(): string; /** * Returns a string representation of an array. The elements are converted to string using thier toLocalString methods. */ toLocaleString(): string; /** * Appends new elements to an array, and returns the new length of the array. * @param items New elements of the Array. */ push(...items: T[]): number; /** * Removes the last element from an array and returns it. */ pop(): T | undefined; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ concat(...items: ReadonlyArray<T>[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ concat(...items: (T | ReadonlyArray<T>)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Reverses the elements in an Array. */ reverse(): T[]; /** * Removes the first element from an array and returns it. */ shift(): T | undefined; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): T[]; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: T, b: T) => number): this; /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. * @param deleteCount The number of elements to remove. */ splice(start: number, deleteCount?: number): T[]; /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. * @param deleteCount The number of elements to remove. * @param items Elements to insert into the array in place of the deleted elements. */ splice(start: number, deleteCount: number, ...items: T[]): T[]; /** * Inserts new elements at the start of an array. * @param items Elements to insert at the start of the Array. */ unshift(...items: T[]): number; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. */ indexOf(searchElement: T, fromIndex?: number): number; /** * Returns the index of the last occurrence of a specified value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. */ lastIndexOf(searchElement: T, fromIndex?: number): number; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ filter<S extends T>(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; [n: number]: T; } interface ArrayConstructor { new(arrayLength?: number): any[]; new <T>(arrayLength: number): T[]; new <T>(...items: T[]): T[]; (arrayLength?: number): any[]; <T>(arrayLength: number): T[]; <T>(...items: T[]): T[]; isArray(arg: any): arg is Array<any>; readonly prototype: Array<any>; } declare const Array: ArrayConstructor; interface TypedPropertyDescriptor<T> { enumerable?: boolean; configurable?: boolean; writable?: boolean; value?: T; get?: () => T; set?: (value: T) => void; } declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void; declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void; declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void; declare type PromiseConstructorLike = new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) => PromiseLike<T>; 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<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>; } /** * Represents the completion of an asynchronous operation */ interface Promise<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<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>; } interface ArrayLike<T> { readonly length: number; readonly [n: number]: T; } /** * Make all properties in T optional */ type Partial<T> = { [P in keyof T]?: T[P]; }; /** * Make all properties in T readonly */ type Readonly<T> = { readonly [P in keyof T]: T[P]; }; /** * From T pick a set of properties K */ type Pick<T, K extends keyof T> = { [P in K]: T[P]; }; /** * Construct a type with a set of properties K of type T */ type Record<K extends string, T> = { [P in K]: T; }; /** * Marker for contextual 'this' type */ interface ThisType<T> { } /** * Represents a raw buffer of binary data, which is used to store data for the * different typed arrays. ArrayBuffers cannot be read from or written to directly, * but can be passed to a typed array or DataView Object to interpret the raw * buffer as needed. */ interface ArrayBuffer { /** * Read-only. The length of the ArrayBuffer (in bytes). */ readonly byteLength: number; /** * Returns a section of an ArrayBuffer. */ slice(begin: number, end?: number): ArrayBuffer; } /** * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. */ interface ArrayBufferTypes { ArrayBuffer: ArrayBuffer; } type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; new(byteLength: number): ArrayBuffer; isView(arg: any): arg is ArrayBufferView; } declare const ArrayBuffer: ArrayBufferConstructor; interface ArrayBufferView { /** * The ArrayBuffer instance referenced by the array. */ buffer: ArrayBufferLike; /** * The length in bytes of the array. */ byteLength: number; /** * The offset in bytes of the array. */ byteOffset: number; } interface DataView { readonly buffer: ArrayBuffer; readonly byteLength: number; readonly byteOffset: number; /** * Gets the Float32 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getFloat32(byteOffset: number, littleEndian?: boolean): number; /** * Gets the Float64 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getFloat64(byteOffset: number, littleEndian?: boolean): number; /** * Gets the Int8 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getInt8(byteOffset: number): number; /** * Gets the Int16 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getInt16(byteOffset: number, littleEndian?: boolean): number; /** * Gets the Int32 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getInt32(byteOffset: number, littleEndian?: boolean): number; /** * Gets the Uint8 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getUint8(byteOffset: number): number; /** * Gets the Uint16 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getUint16(byteOffset: number, littleEndian?: boolean): number; /** * Gets the Uint32 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getUint32(byteOffset: number, littleEndian?: boolean): number; /** * Stores an Float32 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; /** * Stores an Float64 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; /** * Stores an Int8 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. */ setInt8(byteOffset: number, value: number): void; /** * Stores an Int16 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; /** * Stores an Int32 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; /** * Stores an Uint8 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. */ setUint8(byteOffset: number, value: number): void; /** * Stores an Uint16 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; /** * Stores an Uint32 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; } interface DataViewConstructor { new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; /** * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested * number of bytes could not be allocated an exception is raised. */ interface Int8Array { /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. */ readonly byteLength: number; /** * The offset in bytes of the array. */ readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): this; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Int8Array; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: ArrayLike<number>, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Int8Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): this; /** * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Int8Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; [index: number]: number; } interface Int8ArrayConstructor { readonly prototype: Int8Array; new(length: number): Int8Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Int8Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Int8Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; } declare const Int8Array: Int8ArrayConstructor; /** * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ interface Uint8Array { /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. */ readonly byteLength: number; /** * The offset in bytes of the array. */ readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): this; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Uint8Array; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: ArrayLike<number>, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Uint8Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): this; /** * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Uint8Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; [index: number]: number; } interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new(length: number): Uint8Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Uint8Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Uint8Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } declare const Uint8Array: Uint8ArrayConstructor; /** * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. * If the requested number of bytes could not be allocated an exception is raised. */ interface Uint8ClampedArray { /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. */ readonly byteLength: number; /** * The offset in bytes of the array. */ readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): this; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Uint8ClampedArray; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: ArrayLike<number>, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Uint8ClampedArray; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): this; /** * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Uint8ClampedArray; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; [index: number]: number; } interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new(length: number): Uint8ClampedArray; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Uint8ClampedArray; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Uint8ClampedArray; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; /** * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ interface Int16Array { /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. */ readonly byteLength: number; /** * The offset in bytes of the array. */ readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): this; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Int16Array; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: ArrayLike<number>, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Int16Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): this; /** * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Int16Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; [index: number]: number; } interface Int16ArrayConstructor { readonly prototype: Int16Array; new(length: number): Int16Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Int16Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Int16Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; } declare const Int16Array: Int16ArrayConstructor; /** * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ interface Uint16Array { /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. */ readonly byteLength: number; /** * The offset in bytes of the array. */ readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): this; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Uint16Array; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: ArrayLike<number>, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Uint16Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): this; /** * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Uint16Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; [index: number]: number; } interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new(length: number): Uint16Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Uint16Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Uint16Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; } declare const Uint16Array: Uint16ArrayConstructor; /** * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ interface Int32Array { /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. */ readonly byteLength: number; /** * The offset in bytes of the array. */ readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): this; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Int32Array; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: ArrayLike<number>, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Int32Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): this; /** * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Int32Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; [index: number]: number; } interface Int32ArrayConstructor { readonly prototype: Int32Array; new(length: number): Int32Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Int32Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Int32Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; } declare const Int32Array: Int32ArrayConstructor; /** * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ interface Uint32Array { /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. */ readonly byteLength: number; /** * The offset in bytes of the array. */ readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): this; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Uint32Array; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: ArrayLike<number>, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Uint32Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): this; /** * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Uint32Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; [index: number]: number; } interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new(length: number): Uint32Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Uint32Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Uint32Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; } declare const Uint32Array: Uint32ArrayConstructor; /** * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number * of bytes could not be allocated an exception is raised. */ interface Float32Array { /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. */ readonly byteLength: number; /** * The offset in bytes of the array. */ readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): this; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Float32Array; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: ArrayLike<number>, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Float32Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): this; /** * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Float32Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; [index: number]: number; } interface Float32ArrayConstructor { readonly prototype: Float32Array; new(length: number): Float32Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Float32Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Float32Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; } declare const Float32Array: Float32ArrayConstructor; /** * A typed array of 64-bit float values. The contents are initialized to 0. If the requested * number of bytes could not be allocated an exception is raised. */ interface Float64Array { /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. */ readonly byteLength: number; /** * The offset in bytes of the array. */ readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): this; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Float64Array; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: ArrayLike<number>, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Float64Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): this; /** * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Float64Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; [index: number]: number; } interface Float64ArrayConstructor { readonly prototype: Float64Array; new(length: number): Float64Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Float64Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Float64Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; } declare const Float64Array: Float64ArrayConstructor; ///////////////////////////// /// ECMAScript Internationalization API ///////////////////////////// declare namespace Intl { interface CollatorOptions { usage?: string; localeMatcher?: string; numeric?: boolean; caseFirst?: string; sensitivity?: string; ignorePunctuation?: boolean; } interface ResolvedCollatorOptions { locale: string; usage: string; sensitivity: string; ignorePunctuation: boolean; collation: string; caseFirst: string; numeric: boolean; } interface Collator { compare(x: string, y: string): number; resolvedOptions(): ResolvedCollatorOptions; } var Collator: { new(locales?: string | string[], options?: CollatorOptions): Collator; (locales?: string | string[], options?: CollatorOptions): Collator; supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; }; interface NumberFormatOptions { localeMatcher?: string; style?: string; currency?: string; currencyDisplay?: string; useGrouping?: boolean; minimumIntegerDigits?: number; minimumFractionDigits?: number; maximumFractionDigits?: number; minimumSignificantDigits?: number; maximumSignificantDigits?: number; } interface ResolvedNumberFormatOptions { locale: string; numberingSystem: string; style: string; currency?: string; currencyDisplay?: string; minimumIntegerDigits: number; minimumFractionDigits: number; maximumFractionDigits: number; minimumSignificantDigits?: number; maximumSignificantDigits?: number; useGrouping: boolean; } interface NumberFormat { format(value: number): string; resolvedOptions(): ResolvedNumberFormatOptions; } var NumberFormat: { new(locales?: string | string[], options?: NumberFormatOptions): NumberFormat; (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; }; interface DateTimeFormatOptions { localeMatcher?: string; weekday?: string; era?: string; year?: string; month?: string; day?: string; hour?: string; minute?: string; second?: string; timeZoneName?: string; formatMatcher?: string; hour12?: boolean; timeZone?: string; } interface ResolvedDateTimeFormatOptions { locale: string; calendar: string; numberingSystem: string; timeZone: string; hour12?: boolean; weekday?: string; era?: string; year?: string; month?: string; day?: string; hour?: string; minute?: string; second?: string; timeZoneName?: string; } interface DateTimeFormat { format(date?: Date | number): string; resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { new(locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; }; } interface String { /** * Determines whether two strings are equivalent in the current or specified locale. * @param that String to compare to target string * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. */ localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number; } interface Number { /** * Converts a number to a string by using the current or specified locale. * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string; } interface Date { /** * Converts a date and time to a string by using the current or specified locale. * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; /** * Converts a date to a string by using the current or specified locale. * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; /** * Converts a time to a string by using the current or specified locale. * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string; } declare type PropertyKey = string | number | symbol; interface Array<T> { /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): number; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: T, start?: number, end?: number): this; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; } interface ArrayConstructor { /** * Creates an array from an array-like object. * @param arrayLike An array-like object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from<T, U = T>(arrayLike: ArrayLike<T>, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of<T>(...items: T[]): T[]; } interface DateConstructor { new(value: Date): Date; } interface Function { /** * Returns the name of the function. Function names are read-only and can not be changed. */ readonly name: string; } interface Math { /** * Returns the number of leading zero bits in the 32-bit binary representation of a number. * @param x A numeric expression. */ clz32(x: number): number; /** * Returns the result of 32-bit multiplication of two numbers. * @param x First number * @param y Second number */ imul(x: number, y: number): number; /** * Returns the sign of the x, indicating whether x is positive, negative or zero. * @param x The numeric expression to test */ sign(x: number): number; /** * Returns the base 10 logarithm of a number. * @param x A numeric expression. */ log10(x: number): number; /** * Returns the base 2 logarithm of a number. * @param x A numeric expression. */ log2(x: number): number; /** * Returns the natural logarithm of 1 + x. * @param x A numeric expression. */ log1p(x: number): number; /** * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of * the natural logarithms). * @param x A numeric expression. */ expm1(x: number): number; /** * Returns the hyperbolic cosine of a number. * @param x A numeric expression that contains an angle measured in radians. */ cosh(x: number): number; /** * Returns the hyperbolic sine of a number. * @param x A numeric expression that contains an angle measured in radians. */ sinh(x: number): number; /** * Returns the hyperbolic tangent of a number. * @param x A numeric expression that contains an angle measured in radians. */ tanh(x: number): number; /** * Returns the inverse hyperbolic cosine of a number. * @param x A numeric expression that contains an angle measured in radians. */ acosh(x: number): number; /** * Returns the inverse hyperbolic sine of a number. * @param x A numeric expression that contains an angle measured in radians. */ asinh(x: number): number; /** * Returns the inverse hyperbolic tangent of a number. * @param x A numeric expression that contains an angle measured in radians. */ atanh(x: number): number; /** * Returns the square root of the sum of squares of its arguments. * @param values Values to compute the square root for. * If no arguments are passed, the result is +0. * If there is only one argument, the result is the absolute value. * If any argument is +Infinity or -Infinity, the result is +Infinity. * If any argument is NaN, the result is NaN. * If all arguments are either +0 or −0, the result is +0. */ hypot(...values: number[]): number; /** * Returns the integral part of the a numeric expression, x, removing any fractional digits. * If x is already an integer, the result is x. * @param x A numeric expression. */ trunc(x: number): number; /** * Returns the nearest single precision float representation of a number. * @param x A numeric expression. */ fround(x: number): number; /** * Returns an implementation-dependent approximation to the cube root of number. * @param x A numeric expression. */ cbrt(x: number): number; } interface NumberConstructor { /** * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 * that is representable as a Number value, which is approximately: * 2.2204460492503130808472633361816 x 10‍−‍16. */ readonly EPSILON: number; /** * Returns true if passed value is finite. * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a * number. Only finite values of the type number, result in true. * @param number A numeric value. */ isFinite(number: number): boolean; /** * Returns true if the value passed is an integer, false otherwise. * @param number A numeric value. */ isInteger(number: number): boolean; /** * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter * to a number. Only values of the type number, that are also NaN, result in true. * @param number A numeric value. */ isNaN(number: number): boolean; /** * Returns true if the value passed is a safe integer. * @param number A numeric value. */ isSafeInteger(number: number): boolean; /** * The value of the largest integer n such that n and n + 1 are both exactly representable as * a Number value. * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1. */ readonly MAX_SAFE_INTEGER: number; /** * The value of the smallest integer n such that n and n − 1 are both exactly representable as * a Number value. * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). */ readonly MIN_SAFE_INTEGER: number; /** * Converts a string to a floating-point number. * @param string A string that contains a floating-point number. */ parseFloat(string: string): number; /** * Converts A string to an integer. * @param s A string to convert into a number. * @param radix A value between 2 and 36 that specifies the base of the number in numString. * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. * All other strings are considered decimal. */ parseInt(string: string, radix?: number): number; } interface Object { /** * Determines whether an object has a property with the specified name. * @param v A property name. */ hasOwnProperty(v: PropertyKey): boolean; /** * Determines whether a specified property is enumerable. * @param v A property name. */ propertyIsEnumerable(v: PropertyKey): boolean; } interface ObjectConstructor { /** * Copy the values of all of the enumerable own properties from one or more source objects to a * target object. Returns the target object. * @param target The target object to copy to. * @param source The source object from which to copy properties. */ assign<T, U>(target: T, source: U): T & U; /** * Copy the values of all of the enumerable own properties from one or more source objects to a * target object. Returns the target object. * @param target The target object to copy to. * @param source1 The first source object from which to copy properties. * @param source2 The second source object from which to copy properties. */ assign<T, U, V>(target: T, source1: U, source2: V): T & U & V; /** * Copy the values of all of the enumerable own properties from one or more source objects to a * target object. Returns the target object. * @param target The target object to copy to. * @param source1 The first source object from which to copy properties. * @param source2 The second source object from which to copy properties. * @param source3 The third source object from which to copy properties. */ assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W; /** * Copy the values of all of the enumerable own properties from one or more source objects to a * target object. Returns the target object. * @param target The target object to copy to. * @param sources One or more source objects from which to copy properties */ assign(target: object, ...sources: any[]): any; /** * Returns an array of all symbol properties found directly on object o. * @param o Object to retrieve the symbols from. */ getOwnPropertySymbols(o: any): symbol[]; /** * Returns true if the values are the same value, false otherwise. * @param value1 The first value. * @param value2 The second value. */ is(value1: any, value2: any): boolean; /** * Sets the prototype of a specified object o to object proto or null. Returns the object o. * @param o The object to change its prototype. * @param proto The value of the new prototype or null. */ setPrototypeOf(o: any, proto: object | null): any; /** * Gets the own property descriptor of the specified object. * An own property descriptor is one that is defined directly on the object and is not * inherited from the object's prototype. * @param o Object that contains the property. * @param p Name of the property. */ getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor | undefined; /** * Adds a property to an object, or modifies attributes of an existing property. * @param o Object on which to add or modify the property. This can be a native JavaScript * object (that is, a user-defined object or a built in object) or a DOM object. * @param p The property name. * @param attributes Descriptor for the property. It can be for a data property or an accessor * property. */ defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; } interface ReadonlyArray<T> { /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: T, index: number, obj: ReadonlyArray<T>) => boolean, thisArg?: any): T | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: T, index: number, obj: ReadonlyArray<T>) => boolean, thisArg?: any): number; } interface RegExp { /** * Returns a string indicating the flags of the regular expression in question. This field is read-only. * The characters in this string are sequenced and concatenated in the following order: * * - "g" for global * - "i" for ignoreCase * - "m" for multiline * - "u" for unicode * - "y" for sticky * * If no flags are set, the value is the empty string. */ readonly flags: string; /** * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular * expression. Default is false. Read-only. */ readonly sticky: boolean; /** * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular * expression. Default is false. Read-only. */ readonly unicode: boolean; } interface RegExpConstructor { new(pattern: RegExp, flags?: string): RegExp; (pattern: RegExp, flags?: string): RegExp; } interface String { /** * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point * value of the UTF-16 encoded code point starting at the string element at position pos in * the String resulting from converting this object to a String. * If there is no element at that position, the result is undefined. * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. */ codePointAt(pos: number): number | undefined; /** * Returns true if searchString appears as a substring of the result of converting this * object to a String, at one or more positions that are * greater than or equal to position; otherwise, returns false. * @param searchString search string * @param position If position is undefined, 0 is assumed, so as to search all of the String. */ includes(searchString: string, position?: number): boolean; /** * Returns true if the sequence of elements of searchString converted to a String is the * same as the corresponding elements of this object (converted to a String) starting at * endPosition – length(this). Otherwise returns false. */ endsWith(searchString: string, endPosition?: number): boolean; /** * Returns the String value result of normalizing the string into the normalization form * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default * is "NFC" */ normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string; /** * Returns the String value result of normalizing the string into the normalization form * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default * is "NFC" */ normalize(form?: string): string; /** * Returns a String value that is made from count copies appended together. If count is 0, * T is the empty String is returned. * @param count number of copies to append */ repeat(count: number): string; /** * Returns true if the sequence of elements of searchString converted to a String is the * same as the corresponding elements of this object (converted to a String) starting at * position. Otherwise returns false. */ startsWith(searchString: string, position?: number): boolean; /** * Returns an <a> HTML anchor element and sets the name attribute to the text value * @param name */ anchor(name: string): string; /** Returns a <big> HTML element */ big(): string; /** Returns a <blink> HTML element */ blink(): string; /** Returns a <b> HTML element */ bold(): string; /** Returns a <tt> HTML element */ fixed(): string; /** Returns a <font> HTML element and sets the color attribute value */ fontcolor(color: string): string; /** Returns a <font> HTML element and sets the size attribute value */ fontsize(size: number): string; /** Returns a <font> HTML element and sets the size attribute value */ fontsize(size: string): string; /** Returns an <i> HTML element */ italics(): string; /** Returns an <a> HTML element and sets the href attribute value */ link(url: string): string; /** Returns a <small> HTML element */ small(): string; /** Returns a <strike> HTML element */ strike(): string; /** Returns a <sub> HTML element */ sub(): string; /** Returns a <sup> HTML element */ sup(): string; } interface StringConstructor { /** * Return the String value whose elements are, in order, the elements in the List elements. * If length is 0, the empty string is returned. */ fromCodePoint(...codePoints: number[]): string; /** * String.raw is intended for use as a tag function of a Tagged Template String. When called * as such the first argument will be a well formed template call site object and the rest * parameter will contain the substitution values. * @param template A well-formed template string call site representation. * @param substitutions A set of substitution values. */ raw(template: TemplateStringsArray, ...substitutions: any[]): string; } interface Map<K, V> { clear(): void; delete(key: K): boolean; forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void; get(key: K): V | undefined; has(key: K): boolean; set(key: K, value: V): this; readonly size: number; } interface MapConstructor { new(): Map<any, any>; new <K, V>(entries?: [K, V][]): Map<K, V>; readonly prototype: Map<any, any>; } declare var Map: MapConstructor; interface ReadonlyMap<K, V> { forEach(callbackfn: (value: V, key: K, map: ReadonlyMap<K, V>) => void, thisArg?: any): void; get(key: K): V | undefined; has(key: K): boolean; readonly size: number; } interface WeakMap<K extends object, V> { delete(key: K): boolean; get(key: K): V | undefined; has(key: K): boolean; set(key: K, value: V): this; } interface WeakMapConstructor { new(): WeakMap<object, any>; new <K extends object, V>(entries?: [K, V][]): WeakMap<K, V>; readonly prototype: WeakMap<object, any>; } declare var WeakMap: WeakMapConstructor; interface Set<T> { add(value: T): this; clear(): void; delete(value: T): boolean; forEach(callbackfn: (value: T, value2: T, set: Set<T>) => void, thisArg?: any): void; has(value: T): boolean; readonly size: number; } interface SetConstructor { new(): Set<any>; new <T>(values?: T[]): Set<T>; readonly prototype: Set<any>; } declare var Set: SetConstructor; interface ReadonlySet<T> { forEach(callbackfn: (value: T, value2: T, set: ReadonlySet<T>) => void, thisArg?: any): void; has(value: T): boolean; readonly size: number; } interface WeakSet<T> { add(value: T): this; delete(value: T): boolean; has(value: T): boolean; } interface WeakSetConstructor { new(): WeakSet<object>; new <T extends object>(values?: T[]): WeakSet<T>; readonly prototype: WeakSet<object>; } declare var WeakSet: WeakSetConstructor; interface Generator extends Iterator<any> { } interface GeneratorFunction { /** * Creates a new Generator object. * @param args A list of arguments the function accepts. */ new(...args: any[]): Generator; /** * Creates a new Generator object. * @param args A list of arguments the function accepts. */ (...args: any[]): Generator; /** * The length of the arguments. */ readonly length: number; /** * Returns the name of the function. */ readonly name: string; /** * A reference to the prototype. */ readonly prototype: Generator; } interface GeneratorFunctionConstructor { /** * Creates a new Generator function. * @param args A list of arguments the function accepts. */ new(...args: string[]): GeneratorFunction; /** * Creates a new Generator function. * @param args A list of arguments the function accepts. */ (...args: string[]): GeneratorFunction; /** * The length of the arguments. */ readonly length: number; /** * Returns the name of the function. */ readonly name: string; /** * A reference to the prototype. */ readonly prototype: GeneratorFunction; } declare var GeneratorFunction: GeneratorFunctionConstructor; /// <reference path="lib.es2015.symbol.d.ts" /> interface SymbolConstructor { /** * A method that returns the default iterator for an object. Called by the semantics of the * for-of statement. */ readonly iterator: symbol; } interface IteratorResult<T> { done: boolean; value: T; } interface Iterator<T> { next(value?: any): IteratorResult<T>; return?(value?: any): IteratorResult<T>; throw?(e?: any): IteratorResult<T>; } interface Iterable<T> { [Symbol.iterator](): Iterator<T>; } interface IterableIterator<T> extends Iterator<T> { [Symbol.iterator](): IterableIterator<T>; } interface Array<T> { /** Iterator */ [Symbol.iterator](): IterableIterator<T>; /** * Returns an iterable of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** * Returns an iterable of keys in the array */ keys(): IterableIterator<number>; /** * Returns an iterable of values in the array */ values(): IterableIterator<T>; } interface ArrayConstructor { /** * Creates an array from an iterable object. * @param iterable An iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from<T, U = T>(iterable: Iterable<T>, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; } interface ReadonlyArray<T> { /** Iterator of values in the array. */ [Symbol.iterator](): IterableIterator<T>; /** * Returns an iterable of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** * Returns an iterable of keys in the array */ keys(): IterableIterator<number>; /** * Returns an iterable of values in the array */ values(): IterableIterator<T>; } interface IArguments { /** Iterator */ [Symbol.iterator](): IterableIterator<any>; } interface Map<K, V> { /** Returns an iterable of entries in the map. */ [Symbol.iterator](): IterableIterator<[K, V]>; /** * Returns an iterable of key, value pairs for every entry in the map. */ entries(): IterableIterator<[K, V]>; /** * Returns an iterable of keys in the map */ keys(): IterableIterator<K>; /** * Returns an iterable of values in the map */ values(): IterableIterator<V>; } interface ReadonlyMap<K, V> { /** Returns an iterable of entries in the map. */ [Symbol.iterator](): IterableIterator<[K, V]>; /** * Returns an iterable of key, value pairs for every entry in the map. */ entries(): IterableIterator<[K, V]>; /** * Returns an iterable of keys in the map */ keys(): IterableIterator<K>; /** * Returns an iterable of values in the map */ values(): IterableIterator<V>; } interface MapConstructor { new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>; } interface WeakMap<K extends object, V> { } interface WeakMapConstructor { new <K extends object, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>; } interface Set<T> { /** Iterates over values in the set. */ [Symbol.iterator](): IterableIterator<T>; /** * Returns an iterable of [v,v] pairs for every value 'v' in the set. */ entries(): IterableIterator<[T, T]>; /** * Despite its name, returns an iterable of the values in the set, */ keys(): IterableIterator<T>; /** * Returns an iterable of values in the set. */ values(): IterableIterator<T>; } interface ReadonlySet<T> { /** Iterates over values in the set. */ [Symbol.iterator](): IterableIterator<T>; /** * Returns an iterable of [v,v] pairs for every value 'v' in the set. */ entries(): IterableIterator<[T, T]>; /** * Despite its name, returns an iterable of the values in the set, */ keys(): IterableIterator<T>; /** * Returns an iterable of values in the set. */ values(): IterableIterator<T>; } interface SetConstructor { new <T>(iterable: Iterable<T>): Set<T>; } interface WeakSet<T> { } interface WeakSetConstructor { new <T extends object>(iterable: Iterable<T>): WeakSet<T>; } interface Promise<T> { } interface PromiseConstructor { /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<TAll>(values: Iterable<TAll | PromiseLike<TAll>>): Promise<TAll[]>; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T>(values: Iterable<T | PromiseLike<T>>): Promise<T>; } declare namespace Reflect { function enumerate(target: object): IterableIterator<any>; } interface String { /** Iterator */ [Symbol.iterator](): IterableIterator<string>; } interface Int8Array { [Symbol.iterator](): IterableIterator<number>; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns an list of values in the array */ values(): IterableIterator<number>; } interface Int8ArrayConstructor { new(elements: Iterable<number>): Int8Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; } interface Uint8Array { [Symbol.iterator](): IterableIterator<number>; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns an list of values in the array */ values(): IterableIterator<number>; } interface Uint8ArrayConstructor { new(elements: Iterable<number>): Uint8Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } interface Uint8ClampedArray { [Symbol.iterator](): IterableIterator<number>; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns an list of values in the array */ values(): IterableIterator<number>; } interface Uint8ClampedArrayConstructor { new(elements: Iterable<number>): Uint8ClampedArray; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } interface Int16Array { [Symbol.iterator](): IterableIterator<number>; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns an list of values in the array */ values(): IterableIterator<number>; } interface Int16ArrayConstructor { new(elements: Iterable<number>): Int16Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; } interface Uint16Array { [Symbol.iterator](): IterableIterator<number>; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns an list of values in the array */ values(): IterableIterator<number>; } interface Uint16ArrayConstructor { new(elements: Iterable<number>): Uint16Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; } interface Int32Array { [Symbol.iterator](): IterableIterator<number>; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns an list of values in the array */ values(): IterableIterator<number>; } interface Int32ArrayConstructor { new(elements: Iterable<number>): Int32Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; } interface Uint32Array { [Symbol.iterator](): IterableIterator<number>; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns an list of values in the array */ values(): IterableIterator<number>; } interface Uint32ArrayConstructor { new(elements: Iterable<number>): Uint32Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; } interface Float32Array { [Symbol.iterator](): IterableIterator<number>; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns an list of values in the array */ values(): IterableIterator<number>; } interface Float32ArrayConstructor { new(elements: Iterable<number>): Float32Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; } interface Float64Array { [Symbol.iterator](): IterableIterator<number>; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns an list of values in the array */ values(): IterableIterator<number>; } interface Float64ArrayConstructor { new(elements: Iterable<number>): Float64Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; } interface PromiseConstructor { /** * A reference to the prototype. */ readonly prototype: Promise<any>; /** * Creates a new Promise. * @param executor A callback used to initialize the promise. This callback is passed two arguments: * a resolve callback used resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3, T4, T5, T6>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3, T4, T5>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3, T4>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>]): Promise<[T1, T2, T3, T4]>; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T>(values: (T | PromiseLike<T>)[]): Promise<T[]>; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10>; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8>; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7>; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3, T4, T5, T6>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<T1 | T2 | T3 | T4 | T5 | T6>; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3, T4, T5>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>]): Promise<T1 | T2 | T3 | T4 | T5>; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3, T4>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>]): Promise<T1 | T2 | T3 | T4>; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<T1 | T2 | T3>; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<T1 | T2>; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T>(values: (T | PromiseLike<T>)[]): Promise<T>; /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ reject(reason: any): Promise<never>; /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ reject<T>(reason: any): Promise<T>; /** * Creates a new resolved promise for the provided value. * @param value A promise. * @returns A promise whose internal state matches the provided promise. */ resolve<T>(value: T | PromiseLike<T>): Promise<T>; /** * Creates a new resolved promise . * @returns A resolved promise. */ resolve(): Promise<void>; } declare var Promise: PromiseConstructor; interface ProxyHandler<T extends object> { getPrototypeOf?(target: T): object | null; setPrototypeOf?(target: T, v: any): boolean; isExtensible?(target: T): boolean; preventExtensions?(target: T): boolean; getOwnPropertyDescriptor?(target: T, p: PropertyKey): PropertyDescriptor | undefined; has?(target: T, p: PropertyKey): boolean; get?(target: T, p: PropertyKey, receiver: any): any; set?(target: T, p: PropertyKey, value: any, receiver: any): boolean; deleteProperty?(target: T, p: PropertyKey): boolean; defineProperty?(target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; enumerate?(target: T): PropertyKey[]; ownKeys?(target: T): PropertyKey[]; apply?(target: T, thisArg: any, argArray?: any): any; construct?(target: T, argArray: any, newTarget?: any): object; } interface ProxyConstructor { revocable<T extends object>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; }; new <T extends object>(target: T, handler: ProxyHandler<T>): T; } declare var Proxy: ProxyConstructor; declare namespace Reflect { function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any; function construct(target: Function, argumentsList: ArrayLike<any>, newTarget?: any): any; function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; function deleteProperty(target: object, propertyKey: PropertyKey): boolean; function get(target: object, propertyKey: PropertyKey, receiver?: any): any; function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor | undefined; function getPrototypeOf(target: object): object; function has(target: object, propertyKey: PropertyKey): boolean; function isExtensible(target: object): boolean; function ownKeys(target: object): PropertyKey[]; function preventExtensions(target: object): boolean; function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; function setPrototypeOf(target: object, proto: any): boolean; } interface Symbol { /** Returns a string representation of an object. */ toString(): string; /** Returns the primitive value of the specified object. */ valueOf(): symbol; } interface SymbolConstructor { /** * A reference to the prototype. */ readonly prototype: Symbol; /** * Returns a new unique Symbol value. * @param description Description of the new Symbol object. */ (description?: string | number): symbol; /** * Returns a Symbol object from the global symbol registry matching the given key if found. * Otherwise, returns a new symbol with this key. * @param key key to search for. */ for(key: string): symbol; /** * Returns a key from the global symbol registry matching the given Symbol if found. * Otherwise, returns a undefined. * @param sym Symbol to find the key for. */ keyFor(sym: symbol): string | undefined; } declare var Symbol: SymbolConstructor; /// <reference path="lib.es2015.symbol.d.ts" /> interface SymbolConstructor { /** * A method that determines if a constructor object recognizes an object as one of the * constructor’s instances. Called by the semantics of the instanceof operator. */ readonly hasInstance: symbol; /** * A Boolean value that if true indicates that an object should flatten to its array elements * by Array.prototype.concat. */ readonly isConcatSpreadable: symbol; /** * A regular expression method that matches the regular expression against a string. Called * by the String.prototype.match method. */ readonly match: symbol; /** * A regular expression method that replaces matched substrings of a string. Called by the * String.prototype.replace method. */ readonly replace: symbol; /** * A regular expression method that returns the index within a string that matches the * regular expression. Called by the String.prototype.search method. */ readonly search: symbol; /** * A function valued property that is the constructor function that is used to create * derived objects. */ readonly species: symbol; /** * A regular expression method that splits a string at the indices that match the regular * expression. Called by the String.prototype.split method. */ readonly split: symbol; /** * A method that converts an object to a corresponding primitive value. * Called by the ToPrimitive abstract operation. */ readonly toPrimitive: symbol; /** * A String value that is used in the creation of the default string description of an object. * Called by the built-in method Object.prototype.toString. */ readonly toStringTag: symbol; /** * An Object whose own property names are property names that are excluded from the 'with' * environment bindings of the associated objects. */ readonly unscopables: symbol; } interface Symbol { readonly [Symbol.toStringTag]: "Symbol"; } interface Array<T> { /** * Returns an object whose properties have the value 'true' * when they will be absent when used in a 'with' statement. */ [Symbol.unscopables](): { copyWithin: boolean; entries: boolean; fill: boolean; find: boolean; findIndex: boolean; keys: boolean; values: boolean; }; } interface Date { /** * Converts a Date object to a string. */ [Symbol.toPrimitive](hint: "default"): string; /** * Converts a Date object to a string. */ [Symbol.toPrimitive](hint: "string"): string; /** * Converts a Date object to a number. */ [Symbol.toPrimitive](hint: "number"): number; /** * Converts a Date object to a string or number. * * @param hint The strings "number", "string", or "default" to specify what primitive to return. * * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". */ [Symbol.toPrimitive](hint: string): string | number; } interface Map<K, V> { readonly [Symbol.toStringTag]: "Map"; } interface WeakMap<K extends object, V> { readonly [Symbol.toStringTag]: "WeakMap"; } interface Set<T> { readonly [Symbol.toStringTag]: "Set"; } interface WeakSet<T> { readonly [Symbol.toStringTag]: "WeakSet"; } interface JSON { readonly [Symbol.toStringTag]: "JSON"; } interface Function { /** * Determines whether the given value inherits from this function if this function was used * as a constructor function. * * A constructor function can control which objects are recognized as its instances by * 'instanceof' by overriding this method. */ [Symbol.hasInstance](value: any): boolean; } interface GeneratorFunction { readonly [Symbol.toStringTag]: "GeneratorFunction"; } interface Math { readonly [Symbol.toStringTag]: "Math"; } interface Promise<T> { readonly [Symbol.toStringTag]: "Promise"; } interface PromiseConstructor { readonly [Symbol.species]: Function; } interface RegExp { /** * Matches a string with this regular expression, and returns an array containing the results of * that search. * @param string A string to search within. */ [Symbol.match](string: string): RegExpMatchArray | null; /** * Replaces text in a string, using this regular expression. * @param string A String object or string literal whose contents matching against * this regular expression will be replaced * @param replaceValue A String object or string literal containing the text to replace for every * successful match of this regular expression. */ [Symbol.replace](string: string, replaceValue: string): string; /** * Replaces text in a string, using this regular expression. * @param string A String object or string literal whose contents matching against * this regular expression will be replaced * @param replacer A function that returns the replacement text. */ [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; /** * Finds the position beginning first substring match in a regular expression search * using this regular expression. * * @param string The string to search within. */ [Symbol.search](string: string): number; /** * Returns an array of substrings that were delimited by strings in the original input that * match against this regular expression. * * If the regular expression contains capturing parentheses, then each time this * regular expression matches, the results (including any undefined results) of the * capturing parentheses are spliced. * * @param string string value to split * @param limit if not undefined, the output array is truncated so that it contains no more * than 'limit' elements. */ [Symbol.split](string: string, limit?: number): string[]; } interface RegExpConstructor { [Symbol.species](): RegExpConstructor; } interface String { /** * Matches a string an object that supports being matched against, and returns an array containing the results of that search. * @param matcher An object that supports being matched against. */ match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; /** * Replaces text in a string, using an object that supports replacement within a string. * @param searchValue A object can search for and replace matches within a string. * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. */ replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; /** * Replaces text in a string, using an object that supports replacement within a string. * @param searchValue A object can search for and replace matches within a string. * @param replacer A function that returns the replacement text. */ replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; /** * Finds the first substring match in a regular expression search. * @param searcher An object which supports searching within a string. */ search(searcher: { [Symbol.search](string: string): number; }): number; /** * Split a string into substrings using the specified separator and return them as an array. * @param splitter An object that can split a string. * @param limit A value used to limit the number of elements returned in the array. */ split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; } interface ArrayBuffer { readonly [Symbol.toStringTag]: "ArrayBuffer"; } interface DataView { readonly [Symbol.toStringTag]: "DataView"; } interface Int8Array { readonly [Symbol.toStringTag]: "Int8Array"; } interface Uint8Array { readonly [Symbol.toStringTag]: "UInt8Array"; } interface Uint8ClampedArray { readonly [Symbol.toStringTag]: "Uint8ClampedArray"; } interface Int16Array { readonly [Symbol.toStringTag]: "Int16Array"; } interface Uint16Array { readonly [Symbol.toStringTag]: "Uint16Array"; } interface Int32Array { readonly [Symbol.toStringTag]: "Int32Array"; } interface Uint32Array { readonly [Symbol.toStringTag]: "Uint32Array"; } interface Float32Array { readonly [Symbol.toStringTag]: "Float32Array"; } interface Float64Array { readonly [Symbol.toStringTag]: "Float64Array"; } /*! ***************************************************************************** Modifications Copyright (c) 2018 Tencent, Inc. All rights reserved. ***************************************************************************** */ ///////////////////////////// /// WA-Additional-APIs ///////////////////////////// declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; declare function setTimeout(handler: (...args: any[]) => void, timeout: number): number; declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; declare function atob(encodedString: string): string; declare function btoa(rawString: string): string; interface Console { assert(test?: boolean, message?: string, ...optionalParams: any[]): void; clear(): void; count(countTitle?: string): void; debug(message?: any, ...optionalParams: any[]): void; dir(value?: any, ...optionalParams: any[]): void; dirxml(value: any): void; error(message?: any, ...optionalParams: any[]): void; exception(message?: string, ...optionalParams: any[]): void; group(groupTitle?: string, ...optionalParams: any[]): void; groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void; groupEnd(): void; info(message?: any, ...optionalParams: any[]): void; log(message?: any, ...optionalParams: any[]): void; profile(reportName?: string): void; profileEnd(): void; table(...data: any[]): void; time(timerName?: string): void; timeEnd(timerName?: string): void; trace(message?: any, ...optionalParams: any[]): void; warn(message?: any, ...optionalParams: any[]): void; } declare var Console: { prototype: Console; new(): Console; }; declare var console: Console; interface CallableFunction extends Function { /** * Calls the function with the specified object as the this value and the elements of specified array as the arguments. * @param thisArg The object to be used as the this object. * @param args An array of argument values to be passed to the function. */ apply<T, R>(this: (this: T) => R, thisArg: T): R; apply<T, A extends any[], R>(this: (this: T, ...args: A) => R, thisArg: T, args: A): R; /** * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. * @param thisArg The object to be used as the this object. * @param args Argument values to be passed to the function. */ call<T, A extends any[], R>(this: (this: T, ...args: A) => R, thisArg: T, ...args: A): R; /** * For a given function, creates a bound function that has the same body as the original function. * The this object of the bound function is associated with the specified object, and has the specified initial parameters. * @param thisArg The object to be used as the this object. * @param args Arguments to bind to the parameters of the function. */ bind<T, A extends any[], R>(this: (this: T, ...args: A) => R, thisArg: T): (...args: A) => R; bind<T, A0, A extends any[], R>(this: (this: T, arg0: A0, ...args: A) => R, thisArg: T, arg0: A0): (...args: A) => R; bind<T, A0, A1, A extends any[], R>(this: (this: T, arg0: A0, arg1: A1, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1): (...args: A) => R; bind<T, A0, A1, A2, A extends any[], R>(this: (this: T, arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2): (...args: A) => R; bind<T, A0, A1, A2, A3, A extends any[], R>(this: (this: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3): (...args: A) => R; bind<T, AX, R>(this: (this: T, ...args: AX[]) => R, thisArg: T, ...args: AX[]): (...args: AX[]) => R; } interface NewableFunction extends Function { /** * Calls the function with the specified object as the this value and the elements of specified array as the arguments. * @param thisArg The object to be used as the this object. * @param args An array of argument values to be passed to the function. */ apply<T>(this: new () => T, thisArg: T): void; apply<T, A extends any[]>(this: new (...args: A) => T, thisArg: T, args: A): void; /** * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. * @param thisArg The object to be used as the this object. * @param args Argument values to be passed to the function. */ call<T, A extends any[]>(this: new (...args: A) => T, thisArg: T, ...args: A): void; /** * For a given function, creates a bound function that has the same body as the original function. * The this object of the bound function is associated with the specified object, and has the specified initial parameters. * @param thisArg The object to be used as the this object. * @param args Arguments to bind to the parameters of the function. */ bind<A extends any[], R>(this: new (...args: A) => R, thisArg: any): new (...args: A) => R; bind<A0, A extends any[], R>(this: new (arg0: A0, ...args: A) => R, thisArg: any, arg0: A0): new (...args: A) => R; bind<A0, A1, A extends any[], R>(this: new (arg0: A0, arg1: A1, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1): new (...args: A) => R; bind<A0, A1, A2, A extends any[], R>(this: new (arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2): new (...args: A) => R; bind<A0, A1, A2, A3, A extends any[], R>(this: new (arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2, arg3: A3): new (...args: A) => R; bind<AX, R>(this: new (...args: AX[]) => R, thisArg: any, ...args: AX[]): new (...args: AX[]) => R; } declare namespace wx { interface AccessFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail no such file or directory ${path}': 文件/目录不存在; */ errMsg: string; } interface AccessOption { /** 要判断是否存在的文件/目录路径 */ path: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: AccessCompleteCallback; /** 接口调用失败的回调函数 */ fail?: AccessFailCallback; /** 接口调用成功的回调函数 */ success?: AccessSuccessCallback; } /** 帐号信息 */ interface AccountInfo { /** 小程序帐号信息 */ miniProgram: MiniProgram; /** 插件帐号信息(仅在插件中调用时包含这一项) */ plugin: Plugin; } interface AddCardOption { /** 需要添加的卡券列表 */ cardList: AddCardRequestInfo; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: AddCardCompleteCallback; /** 接口调用失败的回调函数 */ fail?: AddCardFailCallback; /** 接口调用成功的回调函数 */ success?: AddCardSuccessCallback; } /** 需要添加的卡券列表 */ interface AddCardRequestInfo { /** 卡券的扩展参数。需进行 JSON 序列化为**字符串**传入 */ cardExt: CardExt; /** 卡券 ID */ cardId: string; } /** 卡券添加结果列表 */ interface AddCardResponseInfo { /** 卡券的扩展参数,结构请参考前文 */ cardExt: string; /** 用户领取到卡券的 ID */ cardId: string; /** 加密 code,为用户领取到卡券的code加密后的字符串,解密请参照:[code 解码接口](https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1499332673_Unm7V) */ code: string; /** 是否成功 */ isSuccess: boolean; } interface AddCardSuccessCallbackResult { /** 卡券添加结果列表 */ cardList: AddCardResponseInfo; } interface AddPhoneContactOption { /** 名字 */ firstName: string; /** 联系地址城市 */ addressCity?: string; /** 联系地址国家 */ addressCountry?: string; /** 联系地址邮政编码 */ addressPostalCode?: string; /** 联系地址省份 */ addressState?: string; /** 联系地址街道 */ addressStreet?: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: AddPhoneContactCompleteCallback; /** 电子邮件 */ email?: string; /** 接口调用失败的回调函数 */ fail?: AddPhoneContactFailCallback; /** 住宅地址城市 */ homeAddressCity?: string; /** 住宅地址国家 */ homeAddressCountry?: string; /** 住宅地址邮政编码 */ homeAddressPostalCode?: string; /** 住宅地址省份 */ homeAddressState?: string; /** 住宅地址街道 */ homeAddressStreet?: string; /** 住宅传真 */ homeFaxNumber?: string; /** 住宅电话 */ homePhoneNumber?: string; /** 公司电话 */ hostNumber?: string; /** 姓氏 */ lastName?: string; /** 中间名 */ middleName?: string; /** 手机号 */ mobilePhoneNumber?: string; /** 昵称 */ nickName?: string; /** 公司 */ organization?: string; /** 头像本地文件路径 */ photoFilePath?: string; /** 备注 */ remark?: string; /** 接口调用成功的回调函数 */ success?: AddPhoneContactSuccessCallback; /** 职位 */ title?: string; /** 网站 */ url?: string; /** 微信号 */ weChatNumber?: string; /** 工作地址城市 */ workAddressCity?: string; /** 工作地址国家 */ workAddressCountry?: string; /** 工作地址邮政编码 */ workAddressPostalCode?: string; /** 工作地址省份 */ workAddressState?: string; /** 工作地址街道 */ workAddressStreet?: string; /** 工作传真 */ workFaxNumber?: string; /** 工作电话 */ workPhoneNumber?: string; } /** 动画效果 */ interface AnimationOption { /** 动画变化时间,单位 ms */ duration?: number; /** 动画变化方式 * * 可选值: * - 'linear': 动画从头到尾的速度是相同的; * - 'easeIn': 动画以低速开始; * - 'easeOut': 动画以低速结束; * - 'easeInOut': 动画以低速开始和结束; */ timingFunc?: 'linear' | 'easeIn' | 'easeOut' | 'easeInOut'; } interface AppendFileFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail no such file or directory, open ${filePath}': 指定的 filePath 文件不存在; * - 'fail illegal operation on a directory, open "${filePath}" ': 指定的 filePath 是一个已经存在的目录; * - 'fail permission denied, open ${dirPath}': 指定的 filePath 路径没有写权限; * - 'fail sdcard not mounted ': 指定的 filePath 是一个已经存在的目录; */ errMsg: string; } interface AppendFileOption { /** 要追加的文本或二进制数据 */ data: string | ArrayBuffer; /** 要追加内容的文件路径 */ filePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: AppendFileCompleteCallback; /** 指定写入文件的字符编码 * * 可选值: * - 'ascii': ; * - 'base64': ; * - 'binary': ; * - 'hex': ; * - 'ucs2/ucs-2/utf16le/utf-16le': 以小端序读取; * - 'utf-8/utf8': ; * - 'latin1': ; */ encoding?: | 'ascii' | 'base64' | 'binary' | 'hex' | 'ucs2/ucs-2/utf16le/utf-16le' | 'utf-8/utf8' | 'latin1'; /** 接口调用失败的回调函数 */ fail?: AppendFileFailCallback; /** 接口调用成功的回调函数 */ success?: AppendFileSuccessCallback; } /** 用户授权设置信息,详情参考[权限](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/authorize/wx.authorize.html) */ interface AuthSetting { /** 是否授权通讯地址,对应接口 [wx.chooseAddress](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/address/wx.chooseAddress.html) */ 'scope.address': boolean; /** 是否授权摄像头,对应[`<camera />`]((camera)) 组件 */ 'scope.camera': boolean; /** 是否授权获取发票,对应接口 [wx.chooseInvoice](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/invoice/wx.chooseInvoice.html) */ 'scope.invoice': boolean; /** 是否授权发票抬头,对应接口 [wx.chooseInvoiceTitle](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/invoice/wx.chooseInvoiceTitle.html) */ 'scope.invoiceTitle': boolean; /** 是否授权录音功能,对应接口 [wx.startRecord](https://developers.weixin.qq.com/miniprogram/dev/api/media/recorder/wx.startRecord.html) */ 'scope.record': boolean; /** 是否授权用户信息,对应接口 [wx.getUserInfo](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html) */ 'scope.userInfo': boolean; /** 是否授权地理位置,对应接口 [wx.getLocation](https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.getLocation.html), [wx.chooseLocation](https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.chooseLocation.html) */ 'scope.userLocation': boolean; /** 是否授权微信运动步数,对应接口 [wx.getWeRunData](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/werun/wx.getWeRunData.html) */ 'scope.werun': boolean; /** 是否授权保存到相册 [wx.saveImageToPhotosAlbum](https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.saveImageToPhotosAlbum.html), [wx.saveVideoToPhotosAlbum](https://developers.weixin.qq.com/miniprogram/dev/api/media/video/wx.saveVideoToPhotosAlbum.html) */ 'scope.writePhotosAlbum': boolean; } interface AuthorizeOption { /** 需要获取权限的 scope,详见 [scope 列表]((授权#scope-列表)) */ scope: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: AuthorizeCompleteCallback; /** 接口调用失败的回调函数 */ fail?: AuthorizeFailCallback; /** 接口调用成功的回调函数 */ success?: AuthorizeSuccessCallback; } /** 设备服务列表 */ interface BLECharacteristic { /** 该特征值支持的操作类型 */ properties: Properties; /** 蓝牙设备特征值的 uuid */ uuid: string; } /** 设备服务列表 */ interface BLEService { /** 该服务是否为主服务 */ isPrimary: boolean; /** 蓝牙设备服务的 uuid */ uuid: string; } /** BackgroundAudioManager 实例,可通过 [wx.getBackgroundAudioManager](https://developers.weixin.qq.com/miniprogram/dev/api/media/background-audio/wx.getBackgroundAudioManager.html) 获取。 * * **示例代码** * * * ```js const backgroundAudioManager = wx.getBackgroundAudioManager() backgroundAudioManager.title = '此时此刻' backgroundAudioManager.epname = '此时此刻' backgroundAudioManager.singer = '许巍' backgroundAudioManager.coverImgUrl = 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000' // 设置了 src 之后会自动播放 backgroundAudioManager.src = 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46' ``` */ interface BackgroundAudioManager { /** 音频已缓冲的时间,仅保证当前播放时间点到此时间点内容已缓冲。(只读) */ buffered: number; /** 封面图 URL,用于做原生音频播放器背景图。原生音频播放器中的分享功能,分享出去的卡片配图及背景也将使用该图。 */ coverImgUrl: string; /** 当前音频的播放位置(单位:s),只有在有合法 src 时返回。(只读) */ currentTime: number; /** 当前音频的长度(单位:s),只有在有合法 src 时返回。(只读) */ duration: number; /** 专辑名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值。 */ epname: string; /** 当前是否暂停或停止。(只读) */ paused: boolean; /** 音频协议。默认值为 'http',设置 'hls' 可以支持播放 HLS 协议的直播音频。 * * 最低基础库: `1.9.94` */ protocol: string; /** 歌手名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值。 */ singer: string; /** 音频的数据源({% version('2.2.3') %} 开始支持云文件ID)。默认为空字符串,**当设置了新的 src 时,会自动开始播放**,目前支持的格式有 m4a, aac, mp3, wav。 */ src: string; /** 音频开始播放的位置(单位:s)。 */ startTime: number; /** 音频标题,用于原生音频播放器音频标题(必填)。原生音频播放器中的分享功能,分享出去的卡片标题,也将使用该值。 */ title: string; /** 页面链接,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值。 */ webUrl: string; } /** 搜索到的设备列表 */ interface BluetoothDeviceInfo { /** 用于区分设备的 id */ deviceId: string; /** 蓝牙设备名称,某些设备可能没有 */ name: string; } interface BoundingClientRectCallbackResult { /** 节点的下边界坐标 */ bottom: number; /** 节点的 dataset */ dataset: object; /** 节点的高度 */ height: number; /** 节点的 ID */ id: string; /** 节点的左边界坐标 */ left: number; /** 节点的右边界坐标 */ right: number; /** 节点的上边界坐标 */ top: number; /** 节点的宽度 */ width: number; } /** 目标边界 */ interface BoundingClientRectResult { /** 下边界 */ bottom: number; /** 左边界 */ left: number; /** 右边界 */ right: number; /** 上边界 */ top: number; } /** 新搜索到的设备列表 */ interface CallbackResultBlueToothDevice { /** 当前蓝牙设备的信号强度 */ RSSI: number; /** 当前蓝牙设备的广播数据段中的 ManufacturerData 数据段。 */ advertisData: ArrayBuffer; /** 当前蓝牙设备的广播数据段中的 ServiceUUIDs 数据段 */ advertisServiceUUIDs: Array<string>; /** 用于区分设备的 id */ deviceId: string; /** 当前蓝牙设备的广播数据段中的 LocalName 数据段 */ localName: string; /** 蓝牙设备名称,某些设备可能没有 */ name: string; /** 当前蓝牙设备的广播数据段中的 ServiceData 数据段 */ serviceData: object; } interface CameraContextStartRecordOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: CameraContextStartRecordCompleteCallback; /** 接口调用失败的回调函数 */ fail?: CameraContextStartRecordFailCallback; /** 接口调用成功的回调函数 */ success?: CameraContextStartRecordSuccessCallback; /** 超过30s或页面 `onHide` 时会结束录像 */ timeoutCallback?: StartRecordTimeoutCallback; } /** canvas 组件的绘图上下文 */ interface CanvasContext { /** 填充颜色。用法同 [CanvasContext.setFillStyle()](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.setFillStyle.html)。 * * 最低基础库: `1.9.90` */ fillStyle: string; /** 当前字体样式的属性。符合 [CSS font 语法](https://developer.mozilla.org/zh-CN/docs/Web/CSS/font) 的 DOMString 字符串,至少需要提供字体大小和字体族名。默认值为 10px sans-serif。 * * 最低基础库: `1.9.90` */ font: string; /** 全局画笔透明度。范围 0-1,0 表示完全透明,1 表示完全不透明。 */ globalAlpha: number; /** 在绘制新形状时应用的合成操作的类型。目前安卓版本只适用于 `fill` 填充块的合成,用于 `stroke` 线段的合成效果都是 `source-over`。 * * 目前支持的操作有 * - 安卓:xor, source-over, source-atop, destination-out, lighter, overlay, darken, lighten, hard-light * - iOS:xor, source-over, source-atop, destination-over, destination-out, lighter, multiply, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, saturation, luminosity * * 最低基础库: `1.9.90` */ globalCompositeOperation: string; /** 线条的端点样式。用法同 [CanvasContext.setLineCap()](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.setLineCap.html)。 * * 最低基础库: `1.9.90` */ lineCap: number; /** 虚线偏移量,初始值为0 * * 最低基础库: `1.9.90` */ lineDashOffset: number; /** 线条的交点样式。用法同 [CanvasContext.setLineJoin()](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.setLineJoin.html)。 * * 最低基础库: `1.9.90` */ lineJoin: number; /** 线条的宽度。用法同 [CanvasContext.setLineWidth()](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.setLineWidth.html)。 * * 最低基础库: `1.9.90` */ lineWidth: number; /** 最大斜接长度。用法同 [CanvasContext.setMiterLimit()](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.setMiterLimit.html)。 * * 最低基础库: `1.9.90` */ miterLimit: number; /** 阴影的模糊级别 * * 最低基础库: `1.9.90` */ shadowBlur: number; /** 阴影的颜色 * * 最低基础库: `1.9.90` */ shadowColor: number; /** 阴影相对于形状在水平方向的偏移 * * 最低基础库: `1.9.90` */ shadowOffsetX: number; /** 阴影相对于形状在竖直方向的偏移 * * 最低基础库: `1.9.90` */ shadowOffsetY: number; /** 边框颜色。用法同 [CanvasContext.setFillStyle()](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.setStrokeStyle.html)。 * * 最低基础库: `1.9.90` */ strokeStyle: string; } interface CanvasGetImageDataOption { /** 画布标识,传入 `<canvas>` 组件的 `canvas-id` 属性。 */ canvasId: string; /** 将要被提取的图像数据矩形区域的高度 */ height: number; /** 将要被提取的图像数据矩形区域的宽度 */ width: number; /** 将要被提取的图像数据矩形区域的左上角横坐标 */ x: number; /** 将要被提取的图像数据矩形区域的左上角纵坐标 */ y: number; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: CanvasGetImageDataCompleteCallback; /** 接口调用失败的回调函数 */ fail?: CanvasGetImageDataFailCallback; /** 接口调用成功的回调函数 */ success?: CanvasGetImageDataSuccessCallback; } interface CanvasGetImageDataSuccessCallbackResult { /** 图像数据矩形的高度 */ height: number; /** 图像数据矩形的宽度 */ width: number; } interface CanvasPutImageDataOption { /** 画布标识,传入 `<canvas>` 组件的 canvas-id 属性。 */ canvasId: string; /** 图像像素点数据,一维数组,每四项表示一个像素点的 rgba */ data: Uint8ClampedArray; /** 源图像数据矩形区域的高度 */ height: number; /** 源图像数据矩形区域的宽度 */ width: number; /** 源图像数据在目标画布中的位置偏移量(x 轴方向的偏移量) */ x: number; /** 源图像数据在目标画布中的位置偏移量(y 轴方向的偏移量) */ y: number; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: CanvasPutImageDataCompleteCallback; /** 接口调用失败的回调函数 */ fail?: CanvasPutImageDataFailCallback; /** 接口调用成功的回调函数 */ success?: CanvasPutImageDataSuccessCallback; } interface CanvasToTempFilePathOption { /** 画布标识,传入 `<canvas>` 组件的 canvas-id */ canvasId: string; /** 图片的质量,目前仅对 jpg 有效。取值范围为 (0, 1],不在范围内时当作 1.0 处理。 * * 最低基础库: `1.7.0` */ quality: number; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: CanvasToTempFilePathCompleteCallback; /** 输出的图片的高度 * * 最低基础库: `1.2.0` */ destHeight?: number; /** 输出的图片的宽度 * * 最低基础库: `1.2.0` */ destWidth?: number; /** 接口调用失败的回调函数 */ fail?: CanvasToTempFilePathFailCallback; /** 目标文件的类型 * * 可选值: * - 'jpg': jpg 图片; * - 'png': png 图片; * * 最低基础库: `1.7.0` */ fileType?: 'jpg' | 'png'; /** 指定的画布区域的高度 * * 最低基础库: `1.2.0` */ height?: number; /** 接口调用成功的回调函数 */ success?: CanvasToTempFilePathSuccessCallback; /** 指定的画布区域的宽度 * * 最低基础库: `1.2.0` */ width?: number; /** 指定的画布区域的左上角横坐标 * * 最低基础库: `1.2.0` */ x?: number; /** 指定的画布区域的左上角纵坐标 * * 最低基础库: `1.2.0` */ y?: number; } interface CanvasToTempFilePathSuccessCallbackResult { /** 生成文件的临时路径 */ tempFilePath: string; } /** 卡券的扩展参数。需进行 JSON 序列化为**字符串**传入 */ interface CardExt { /** 签名,商户将接口列表中的参数按照指定方式进行签名,签名方式使用 SHA1,具体签名方案参见:[卡券签名](https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1499332673_Unm7V) */ signature: string; /** 时间戳,东八区时间,UTC+8,单位为秒 */ timestamp: number; /** 用户领取的 code,仅自定义 code 模式的卡券须填写,非自定义 code 模式卡券不可填写,[详情](https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025056) */ code?: string; /** 卡券在第三方系统的实际领取时间,为东八区时间戳(UTC+8,精确到秒)。当卡券的有效期类为 DATE_TYPE_FIX_TERM 时专用,标识卡券的实际生效时间,用于解决商户系统内起始时间和领取微信卡券时间不同步的问题。 */ fixed_begintimestamp?: number; /** 随机字符串,由开发者设置传入,加强安全性(若不填写可能被重放请求)。随机字符串,不长于 32 位。推荐使用大小写字母和数字,不同添加请求的 nonce_str 须动态生成,若重复将会导致领取失败。 */ nonce_str?: string; /** 指定领取者的 openid,只有该用户能领取。 bind_openid 字段为 true 的卡券必须填写,bind_openid 字段为 false 不可填写。 */ openid?: string; /** 领取渠道参数,用于标识本次领取的渠道值。 */ outer_str?: string; } interface CheckIsSoterEnrolledInDeviceOption { /** 认证方式 * * 可选值: * - 'fingerPrint': 指纹识别; * - 'facial': 人脸识别(暂未支持); * - 'speech': 声纹识别(暂未支持); */ checkAuthMode: ('fingerPrint' | 'facial' | 'speech')[]; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: CheckIsSoterEnrolledInDeviceCompleteCallback; /** 接口调用失败的回调函数 */ fail?: CheckIsSoterEnrolledInDeviceFailCallback; /** 接口调用成功的回调函数 */ success?: CheckIsSoterEnrolledInDeviceSuccessCallback; } interface CheckIsSoterEnrolledInDeviceSuccessCallbackResult { /** 错误信息 */ errMs: string; /** 是否已录入信息 */ isEnrolled: boolean; } interface CheckIsSupportSoterAuthenticationOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: CheckIsSupportSoterAuthenticationCompleteCallback; /** 接口调用失败的回调函数 */ fail?: CheckIsSupportSoterAuthenticationFailCallback; /** 接口调用成功的回调函数 */ success?: CheckIsSupportSoterAuthenticationSuccessCallback; } interface CheckIsSupportSoterAuthenticationSuccessCallbackResult { /** 该设备支持的可被SOTER识别的生物识别方式 * * 可选值: * - 'fingerPrint': 指纹识别; * - 'facial': 人脸识别(暂未支持); * - 'speech': 声纹识别(暂未支持); */ supportMode: ('fingerPrint' | 'facial' | 'speech')[]; } interface CheckSessionOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: CheckSessionCompleteCallback; /** 接口调用失败的回调函数 */ fail?: CheckSessionFailCallback; /** 接口调用成功的回调函数 */ success?: CheckSessionSuccessCallback; } interface ChooseAddressOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ChooseAddressCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ChooseAddressFailCallback; /** 接口调用成功的回调函数 */ success?: ChooseAddressSuccessCallback; } interface ChooseAddressSuccessCallbackResult { /** 国标收货地址第一级地址 */ cityName: string; /** 国标收货地址第一级地址 */ countyName: string; /** 详细收货地址信息 */ detailInfo: string; /** 错误信息 */ errMsg: string; /** 收货地址国家码 */ nationalCode: string; /** 邮编 */ postalCode: string; /** 国标收货地址第一级地址 */ provinceName: string; /** 收货人手机号码 */ telNumber: string; /** 收货人姓名 */ userName: string; } interface ChooseImageOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ChooseImageCompleteCallback; /** 最多可以选择的图片张数 */ count?: number; /** 接口调用失败的回调函数 */ fail?: ChooseImageFailCallback; /** 所选的图片的尺寸 * * 可选值: * - 'original': 原图; * - 'compressed': 压缩图; */ sizeType?: ('original' | 'compressed')[]; /** 选择图片的来源 * * 可选值: * - 'album': 从相册选图; * - 'camera': 使用相机; */ sourceType?: ('album' | 'camera')[]; /** 接口调用成功的回调函数 */ success?: ChooseImageSuccessCallback; } interface ChooseImageSuccessCallbackResult { /** 图片的本地临时文件路径列表 */ tempFilePaths: Array<string>; /** 图片的本地临时文件列表 * * 最低基础库: `1.2.0` */ tempFiles: Array<ImageFile>; } interface ChooseInvoiceOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ChooseInvoiceCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ChooseInvoiceFailCallback; /** 接口调用成功的回调函数 */ success?: ChooseInvoiceSuccessCallback; } interface ChooseInvoiceSuccessCallbackResult { /** 用户选中的发票列表 */ invoiceInfo: InvoiceInfo; } interface ChooseInvoiceTitleOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ChooseInvoiceTitleCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ChooseInvoiceTitleFailCallback; /** 接口调用成功的回调函数 */ success?: ChooseInvoiceTitleSuccessCallback; } interface ChooseInvoiceTitleSuccessCallbackResult { /** 银行账号 */ bankAccount: string; /** 银行名称 */ bankName: string; /** 单位地址 */ companyAddress: string; /** 错误信息 */ errMsg: string; /** 抬头税号 */ taxNumber: string; /** 手机号码 */ telephone: string; /** 抬头名称 */ title: string; /** 抬头类型 * * 可选值: * - 0: 单位; * - 1: 个人; */ type: 0 | 1; } interface ChooseLocationOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ChooseLocationCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ChooseLocationFailCallback; /** 接口调用成功的回调函数 */ success?: ChooseLocationSuccessCallback; } interface ChooseLocationSuccessCallbackResult { /** 详细地址 */ address: string; /** 纬度,浮点数,范围为-90~90,负数表示南纬。使用 gcj02 国测局坐标系 */ latitude: string; /** 经度,浮点数,范围为-180~180,负数表示西经。使用 gcj02 国测局坐标系 */ longitude: string; /** 位置名称 */ name: string; } interface ChooseVideoOption { /** 默认拉起的是前置或者后置摄像头。部分 Android 手机下由于系统 ROM 不支持无法生效 * * 可选值: * - 'back': 默认拉起后置摄像头; * - 'front': 默认拉起前置摄像头; */ camera?: 'back' | 'front'; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ChooseVideoCompleteCallback; /** 是否压缩所选择的视频文件 * * 最低基础库: `1.6.0` */ compressed?: boolean; /** 接口调用失败的回调函数 */ fail?: ChooseVideoFailCallback; /** 拍摄视频最长拍摄时间,单位秒 */ maxDuration?: number; /** 视频选择的来源 * * 可选值: * - 'album': 从相册选择视频; * - 'camera': 使用相机拍摄视频; */ sourceType?: ('album' | 'camera')[]; /** 接口调用成功的回调函数 */ success?: ChooseVideoSuccessCallback; } interface ChooseVideoSuccessCallbackResult { /** 选定视频的时间长度 */ duration: number; /** 返回选定视频的高度 */ height: number; /** 选定视频的数据量大小 */ size: number; /** 选定视频的临时文件路径 */ tempFilePath: string; /** 返回选定视频的宽度 */ width: number; } interface ClearStorageOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ClearStorageCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ClearStorageFailCallback; /** 接口调用成功的回调函数 */ success?: ClearStorageSuccessCallback; } interface CloseBLEConnectionOption { /** 用于区分设备的 id */ deviceId: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: CloseBLEConnectionCompleteCallback; /** 接口调用失败的回调函数 */ fail?: CloseBLEConnectionFailCallback; /** 接口调用成功的回调函数 */ success?: CloseBLEConnectionSuccessCallback; } interface CloseBluetoothAdapterOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: CloseBluetoothAdapterCompleteCallback; /** 接口调用失败的回调函数 */ fail?: CloseBluetoothAdapterFailCallback; /** 接口调用成功的回调函数 */ success?: CloseBluetoothAdapterSuccessCallback; } interface CloseOption { /** 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。 */ code?: number; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: CloseCompleteCallback; /** 接口调用失败的回调函数 */ fail?: CloseFailCallback; /** 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于 123 字节的 UTF-8 文本(不是字符)。 */ reason?: string; /** 接口调用成功的回调函数 */ success?: CloseSuccessCallback; } interface CloseSocketOption { /** 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。 */ code?: number; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: CloseSocketCompleteCallback; /** 接口调用失败的回调函数 */ fail?: CloseSocketFailCallback; /** 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于 123 字节的 UTF-8 文本(不是字符)。 */ reason?: string; /** 接口调用成功的回调函数 */ success?: CloseSocketSuccessCallback; } /** 颜色。可以用以下几种方式来表示 canvas 中使用的颜色: * * - RGB 颜色: 如 `'rgb(255, 0, 0)'` * - RGBA 颜色:如 `'rgba(255, 0, 0, 0.3)'` * - 16 进制颜色: 如 `'#FF0000'` * - 预定义的颜色: 如 `'red'` * * 其中预定义颜色有以下148个: * *注意**: Color Name 大小写不敏感 * * | Color Name | HEX | * | -------------------- | ------- | * | AliceBlue | #F0F8FF | * | AntiqueWhite | #FAEBD7 | * | Aqua | #00FFFF | * | Aquamarine | #7FFFD4 | * | Azure | #F0FFFF | * | Beige | #F5F5DC | * | Bisque | #FFE4C4 | * | Black | #000000 | * | BlanchedAlmond | #FFEBCD | * | Blue | #0000FF | * | BlueViolet | #8A2BE2 | * | Brown | #A52A2A | * | BurlyWood | #DEB887 | * | CadetBlue | #5F9EA0 | * | Chartreuse | #7FFF00 | * | Chocolate | #D2691E | * | Coral | #FF7F50 | * | CornflowerBlue | #6495ED | * | Cornsilk | #FFF8DC | * | Crimson | #DC143C | * | Cyan | #00FFFF | * | DarkBlue | #00008B | * | DarkCyan | #008B8B | * | DarkGoldenRod | #B8860B | * | DarkGray | #A9A9A9 | * | DarkGrey | #A9A9A9 | * | DarkGreen | #006400 | * | DarkKhaki | #BDB76B | * | DarkMagenta | #8B008B | * | DarkOliveGreen | #556B2F | * | DarkOrange | #FF8C00 | * | DarkOrchid | #9932CC | * | DarkRed | #8B0000 | * | DarkSalmon | #E9967A | * | DarkSeaGreen | #8FBC8F | * | DarkSlateBlue | #483D8B | * | DarkSlateGray | #2F4F4F | * | DarkSlateGrey | #2F4F4F | * | DarkTurquoise | #00CED1 | * | DarkViolet | #9400D3 | * | DeepPink | #FF1493 | * | DeepSkyBlue | #00BFFF | * | DimGray | #696969 | * | DimGrey | #696969 | * | DodgerBlue | #1E90FF | * | FireBrick | #B22222 | * | FloralWhite | #FFFAF0 | * | ForestGreen | #228B22 | * | Fuchsia | #FF00FF | * | Gainsboro | #DCDCDC | * | GhostWhite | #F8F8FF | * | Gold | #FFD700 | * | GoldenRod | #DAA520 | * | Gray | #808080 | * | Grey | #808080 | * | Green | #008000 | * | GreenYellow | #ADFF2F | * | HoneyDew | #F0FFF0 | * | HotPink | #FF69B4 | * | IndianRed | #CD5C5C | * | Indigo | #4B0082 | * | Ivory | #FFFFF0 | * | Khaki | #F0E68C | * | Lavender | #E6E6FA | * | LavenderBlush | #FFF0F5 | * | LawnGreen | #7CFC00 | * | LemonChiffon | #FFFACD | * | LightBlue | #ADD8E6 | * | LightCoral | #F08080 | * | LightCyan | #E0FFFF | * | LightGoldenRodYellow | #FAFAD2 | * | LightGray | #D3D3D3 | * | LightGrey | #D3D3D3 | * | LightGreen | #90EE90 | * | LightPink | #FFB6C1 | * | LightSalmon | #FFA07A | * | LightSeaGreen | #20B2AA | * | LightSkyBlue | #87CEFA | * | LightSlateGray | #778899 | * | LightSlateGrey | #778899 | * | LightSteelBlue | #B0C4DE | * | LightYellow | #FFFFE0 | * | Lime | #00FF00 | * | LimeGreen | #32CD32 | * | Linen | #FAF0E6 | * | Magenta | #FF00FF | * | Maroon | #800000 | * | MediumAquaMarine | #66CDAA | * | MediumBlue | #0000CD | * | MediumOrchid | #BA55D3 | * | MediumPurple | #9370DB | * | MediumSeaGreen | #3CB371 | * | MediumSlateBlue | #7B68EE | * | MediumSpringGreen | #00FA9A | * | MediumTurquoise | #48D1CC | * | MediumVioletRed | #C71585 | * | MidnightBlue | #191970 | * | MintCream | #F5FFFA | * | MistyRose | #FFE4E1 | * | Moccasin | #FFE4B5 | * | NavajoWhite | #FFDEAD | * | Navy | #000080 | * | OldLace | #FDF5E6 | * | Olive | #808000 | * | OliveDrab | #6B8E23 | * | Orange | #FFA500 | * | OrangeRed | #FF4500 | * | Orchid | #DA70D6 | * | PaleGoldenRod | #EEE8AA | * | PaleGreen | #98FB98 | * | PaleTurquoise | #AFEEEE | * | PaleVioletRed | #DB7093 | * | PapayaWhip | #FFEFD5 | * | PeachPuff | #FFDAB9 | * | Peru | #CD853F | * | Pink | #FFC0CB | * | Plum | #DDA0DD | * | PowderBlue | #B0E0E6 | * | Purple | #800080 | * | RebeccaPurple | #663399 | * | Red | #FF0000 | * | RosyBrown | #BC8F8F | * | RoyalBlue | #4169E1 | * | SaddleBrown | #8B4513 | * | Salmon | #FA8072 | * | SandyBrown | #F4A460 | * | SeaGreen | #2E8B57 | * | SeaShell | #FFF5EE | * | Sienna | #A0522D | * | Silver | #C0C0C0 | * | SkyBlue | #87CEEB | * | SlateBlue | #6A5ACD | * | SlateGray | #708090 | * | SlateGrey | #708090 | * | Snow | #FFFAFA | * | SpringGreen | #00FF7F | * | SteelBlue | #4682B4 | * | Tan | #D2B48C | * | Teal | #008080 | * | Thistle | #D8BFD8 | * | Tomato | #FF6347 | * | Turquoise | #40E0D0 | * | Violet | #EE82EE | * | Wheat | #F5DEB3 | * | White | #FFFFFF | * | WhiteSmoke | #F5F5F5 | * | Yellow | #FFFF00 | * | YellowGreen | #9ACD32 | */ interface Color { } interface CompressImageOption { /** 图片路径,图片的路径,可以是相对路径、临时文件路径、存储文件路径 */ src: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: CompressImageCompleteCallback; /** 接口调用失败的回调函数 */ fail?: CompressImageFailCallback; /** 压缩质量,范围0~100,数值越小,质量越低,压缩率越高(仅对jpg有效)。 */ quality?: number; /** 接口调用成功的回调函数 */ success?: CompressImageSuccessCallback; } interface ConnectSocketOption { /** 开发者服务器 wss 接口地址 */ url: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ConnectSocketCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ConnectSocketFailCallback; /** HTTP Header,Header 中不能设置 Referer */ header?: object; /** 子协议数组 * * 最低基础库: `1.4.0` */ protocols?: Array<string>; /** 接口调用成功的回调函数 */ success?: ConnectSocketSuccessCallback; } interface ConnectWifiOption { /** Wi-Fi 设备 BSSID */ BSSID: string; /** Wi-Fi 设备 SSID */ SSID: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ConnectWifiCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ConnectWifiFailCallback; /** Wi-Fi 设备密码 */ password?: string; /** 接口调用成功的回调函数 */ success?: ConnectWifiSuccessCallback; } interface ContextCallbackResult { /** 节点对应的 Context 对象 */ context: object; } interface CopyFileFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail permission denied, copyFile ${srcPath} -> ${destPath}': 指定目标文件路径没有写权限; * - 'fail no such file or directory, copyFile ${srcPath} -> ${destPath}': 源文件不存在,或目标文件路径的上层目录不存在; */ errMsg: string; } interface CopyFileOption { /** 目标文件路径 */ destPath: string; /** 源文件路径,只可以是普通文件 */ srcPath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: CopyFileCompleteCallback; /** 接口调用失败的回调函数 */ fail?: CopyFileFailCallback; /** 接口调用成功的回调函数 */ success?: CopyFileSuccessCallback; } interface CreateAnimationOption { /** 动画延迟时间,单位 ms */ delay?: number; /** 动画持续时间,单位 ms */ duration?: number; /** 动画的效果 * * 可选值: * - 'linear': 动画从头到尾的速度是相同的; * - 'ease': 动画以低速开始,然后加快,在结束前变慢; * - 'ease-in': 动画以低速开始; * - 'ease-in-out': 动画以低速开始和结束; * - 'ease-out': 动画以低速结束; * - 'step-start': 动画第一帧就跳至结束状态直到结束; * - 'step-end': 动画一直保持开始状态,最后一帧跳到结束状态; */ timingFunction?: | 'linear' | 'ease' | 'ease-in' | 'ease-in-out' | 'ease-out' | 'step-start' | 'step-end'; transformOrigin?: string; } interface CreateBLEConnectionOption { /** 用于区分设备的 id */ deviceId: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: CreateBLEConnectionCompleteCallback; /** 接口调用失败的回调函数 */ fail?: CreateBLEConnectionFailCallback; /** 接口调用成功的回调函数 */ success?: CreateBLEConnectionSuccessCallback; /** 超时时间,单位ms,不填表示不会超时 */ timeout?: number; } /** 选项 */ interface CreateIntersectionObserverOption { /** 初始的相交比例,如果调用时检测到的相交比例与这个值不相等且达到阈值,则会触发一次监听器的回调函数。 */ initialRatio?: number; /** 是否同时观测多个目标节点(而非一个),如果设为 true ,observe 的 targetSelector 将选中多个节点(注意:同时选中过多节点将影响渲染性能) * * 最低基础库: `2.0.0` */ observeAll?: boolean; /** 一个数值数组,包含所有阈值。 */ thresholds?: Array<number>; } /** 弹幕内容 */ interface Danmu { /** 弹幕文字 */ text: string; /** 弹幕颜色 */ color?: string; } /** 上报的自定义数据。 */ interface Data { /** 配置中的字段名 */ key: string; /** 上报的数据 */ value: any; } /** 可选的字体描述符 */ interface DescOption { /** 字体样式,可选值为 normal / italic / oblique */ style?: string; /** 设置小型大写字母的字体显示文本,可选值为 normal / small-caps / inherit */ variant?: string; /** 字体粗细,可选值为 normal / bold / 100 / 200../ 900 */ weight?: string; } /** 指定 marker 移动到的目标点 */ interface DestinationOption { /** 纬度 */ latitude: number; /** 经度 */ longitude: number; } interface DownloadFileOption { /** 下载资源的 url */ url: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: DownloadFileCompleteCallback; /** 接口调用失败的回调函数 */ fail?: DownloadFileFailCallback; /** 指定文件下载后存储的路径 * * 最低基础库: `1.8.0` */ filePath?: string; /** HTTP 请求的 Header,Header 中不能设置 Referer */ header?: object; /** 接口调用成功的回调函数 */ success?: DownloadFileSuccessCallback; } interface DownloadFileSuccessCallbackResult { /** 开发者服务器返回的 HTTP 状态码 */ statusCode: number; /** 临时文件路径。如果没传入 filePath 指定文件存储路径,则下载后的文件会存储到一个临时文件 */ tempFilePath: string; } interface DownloadTaskOnHeadersReceivedCallbackResult { /** 开发者服务器返回的 HTTP Response Header */ header: object; } interface DownloadTaskOnProgressUpdateCallbackResult { /** 下载进度百分比 */ progress: number; /** 预期需要下载的数据总长度,单位 Bytes */ totalBytesExpectedToWrite: number; /** 已经下载的数据长度,单位 Bytes */ totalBytesWritten: number; } interface ExitFullScreenOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ExitFullScreenCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ExitFullScreenFailCallback; /** 接口调用成功的回调函数 */ success?: ExitFullScreenSuccessCallback; } interface ExtInfo { /** 第三方平台自定义的数据 */ extConfig: object; } interface Fields { /** 指定样式名列表,返回节点对应样式名的当前值 * * 最低基础库: `2.1.0` */ computedStyle?: Array<string>; /** 是否返回节点对应的 Context 对象 * * 最低基础库: `2.4.2` */ context?: boolean; /** 是否返回节点 dataset */ dataset?: boolean; /** 是否返回节点 id */ id?: boolean; /** 指定属性名列表,返回节点对应属性名的当前属性值(只能获得组件文档中标注的常规属性值,id class style 和事件绑定的属性值不可获取) */ properties?: Array<string>; /** 是否返回节点布局位置(`left` `right` `top` `bottom`) */ rect?: boolean; /** 否 是否返回节点的 `scrollLeft` `scrollTop`,节点必须是 `scroll-view` 或者 `viewport` */ scrollOffset?: boolean; /** 是否返回节点尺寸(`width` `height`) */ size?: boolean; } interface FileSystemManagerGetFileInfoOption { /** 要读取的文件路径 */ filePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: FileSystemManagerGetFileInfoCompleteCallback; /** 接口调用失败的回调函数 */ fail?: FileSystemManagerGetFileInfoFailCallback; /** 接口调用成功的回调函数 */ success?: FileSystemManagerGetFileInfoSuccessCallback; } interface FileSystemManagerGetFileInfoSuccessCallbackResult { /** 文件大小,以字节为单位 */ size: number; } interface FileSystemManagerGetSavedFileListOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: FileSystemManagerGetSavedFileListCompleteCallback; /** 接口调用失败的回调函数 */ fail?: FileSystemManagerGetSavedFileListFailCallback; /** 接口调用成功的回调函数 */ success?: FileSystemManagerGetSavedFileListSuccessCallback; } interface FileSystemManagerGetSavedFileListSuccessCallbackResult { /** 文件数组 */ fileList: FileSystemManagerGetSavedFileListSuccessCallbackResultFileItem; } /** 文件数组 */ interface FileSystemManagerGetSavedFileListSuccessCallbackResultFileItem { /** 文件保存时的时间戳,从1970/01/01 08:00:00 到当前时间的秒数 */ createTime: number; /** 本地路径 */ filePath: string; /** 本地文件大小,以字节为单位 */ size: number; } interface FileSystemManagerRemoveSavedFileOption { /** 需要删除的文件路径 */ filePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: FileSystemManagerRemoveSavedFileCompleteCallback; /** 接口调用失败的回调函数 */ fail?: FileSystemManagerRemoveSavedFileFailCallback; /** 接口调用成功的回调函数 */ success?: FileSystemManagerRemoveSavedFileSuccessCallback; } interface FileSystemManagerSaveFileOption { /** 临时存储文件路径 */ tempFilePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: FileSystemManagerSaveFileCompleteCallback; /** 接口调用失败的回调函数 */ fail?: FileSystemManagerSaveFileFailCallback; /** 要存储的文件路径 */ filePath?: string; /** 接口调用成功的回调函数 */ success?: FileSystemManagerSaveFileSuccessCallback; } interface FileSystemManagerSaveFileSuccessCallbackResult { /** 存储后的文件路径 */ savedFilePath: number; } interface GetAvailableAudioSourcesOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetAvailableAudioSourcesCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetAvailableAudioSourcesFailCallback; /** 接口调用成功的回调函数 */ success?: GetAvailableAudioSourcesSuccessCallback; } interface GetAvailableAudioSourcesSuccessCallbackResult { /** 支持的音频输入源列表,可在 [RecorderManager.start()](https://developers.weixin.qq.com/miniprogram/dev/api/media/recorder/RecorderManager.start.html) 接口中使用。返回值定义参考 https://developer.android.com/reference/kotlin/android/media/MediaRecorder.AudioSource * * 可选值: * - 'auto': 自动设置,默认使用手机麦克风,插上耳麦后自动切换使用耳机麦克风,所有平台适用; * - 'buildInMic': 手机麦克风,仅限 iOS; * - 'headsetMic': 耳机麦克风,仅限 iOS; * - 'mic': 麦克风(没插耳麦时是手机麦克风,插耳麦时是耳机麦克风),仅限 Android; * - 'camcorder': 同 mic,适用于录制音视频内容,仅限 Android; * - 'voice_communication': 同 mic,适用于实时沟通,仅限 Android; * - 'voice_recognition': 同 mic,适用于语音识别,仅限 Android; */ audioSources: ( | 'auto' | 'buildInMic' | 'headsetMic' | 'mic' | 'camcorder' | 'voice_communication' | 'voice_recognition')[]; } interface GetBLEDeviceCharacteristicsOption { /** 蓝牙设备 id */ deviceId: string; /** 蓝牙服务 uuid,需要使用 `getBLEDeviceServices` 获取 */ serviceId: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetBLEDeviceCharacteristicsCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetBLEDeviceCharacteristicsFailCallback; /** 接口调用成功的回调函数 */ success?: GetBLEDeviceCharacteristicsSuccessCallback; } interface GetBLEDeviceCharacteristicsSuccessCallbackResult { /** 设备服务列表 */ characteristics: BLECharacteristic; } interface GetBLEDeviceServicesOption { /** 蓝牙设备 id */ deviceId: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetBLEDeviceServicesCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetBLEDeviceServicesFailCallback; /** 接口调用成功的回调函数 */ success?: GetBLEDeviceServicesSuccessCallback; } interface GetBLEDeviceServicesSuccessCallbackResult { /** 设备服务列表 */ services: BLEService; } interface GetBackgroundAudioPlayerStateOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetBackgroundAudioPlayerStateCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetBackgroundAudioPlayerStateFailCallback; /** 接口调用成功的回调函数 */ success?: GetBackgroundAudioPlayerStateSuccessCallback; } interface GetBackgroundAudioPlayerStateSuccessCallbackResult { /** 选定音频的播放位置(单位:s),只有在音乐播放中时返回 */ currentPosition: number; /** 歌曲数据链接,只有在音乐播放中时返回 */ dataUrl: string; /** 音频的下载进度百分比,只有在音乐播放中时返回 */ downloadPercent: number; /** 选定音频的长度(单位:s),只有在音乐播放中时返回 */ duration: number; /** 播放状态 * * 可选值: * - 0: 暂停中; * - 1: 播放中; * - 2: 没有音乐播放; */ status: 0 | 1 | 2; } interface GetBatteryInfoOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetBatteryInfoCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetBatteryInfoFailCallback; /** 接口调用成功的回调函数 */ success?: GetBatteryInfoSuccessCallback; } interface GetBatteryInfoSuccessCallbackResult { /** 是否正在充电中 */ isCharging: boolean; /** 设备电量,范围 1 - 100 */ level: string; } interface GetBatteryInfoSyncResult { /** 是否正在充电中 */ isCharging: boolean; /** 设备电量,范围 1 - 100 */ level: string; } interface GetBeaconsOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetBeaconsCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetBeaconsFailCallback; /** 接口调用成功的回调函数 */ success?: GetBeaconsSuccessCallback; } interface GetBeaconsSuccessCallbackResult { /** iBeacon 设备列表 */ beacons: Array<IBeaconInfo>; } interface GetBluetoothAdapterStateOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetBluetoothAdapterStateCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetBluetoothAdapterStateFailCallback; /** 接口调用成功的回调函数 */ success?: GetBluetoothAdapterStateSuccessCallback; } interface GetBluetoothAdapterStateSuccessCallbackResult { /** 蓝牙适配器是否可用 */ available: boolean; /** 是否正在搜索设备 */ discovering: boolean; } interface GetBluetoothDevicesOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetBluetoothDevicesCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetBluetoothDevicesFailCallback; /** 接口调用成功的回调函数 */ success?: GetBluetoothDevicesSuccessCallback; } interface GetBluetoothDevicesSuccessCallbackResult { /** uuid 对应的的已连接设备列表 */ devices: GetBluetoothDevicesSuccessCallbackResultBlueToothDevice; } /** uuid 对应的的已连接设备列表 */ interface GetBluetoothDevicesSuccessCallbackResultBlueToothDevice { /** 当前蓝牙设备的信号强度 */ RSSI: number; /** 当前蓝牙设备的广播数据段中的 ManufacturerData 数据段。 */ advertisData: ArrayBuffer; /** 当前蓝牙设备的广播数据段中的 ServiceUUIDs 数据段 */ advertisServiceUUIDs: Array<string>; /** 用于区分设备的 id */ deviceId: string; /** 当前蓝牙设备的广播数据段中的 LocalName 数据段 */ localName: string; /** 蓝牙设备名称,某些设备可能没有 */ name: string; /** 当前蓝牙设备的广播数据段中的 ServiceData 数据段 */ serviceData: object; } interface GetCenterLocationOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetCenterLocationCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetCenterLocationFailCallback; /** 接口调用成功的回调函数 */ success?: GetCenterLocationSuccessCallback; } interface GetCenterLocationSuccessCallbackResult { /** 纬度 */ latitude: number; /** 经度 */ longitude: number; } interface GetClipboardDataOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetClipboardDataCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetClipboardDataFailCallback; /** 接口调用成功的回调函数 */ success?: GetClipboardDataSuccessCallback; } interface GetClipboardDataSuccessCallbackOption { /** 剪贴板的内容 */ data: string; } interface GetConnectedBluetoothDevicesOption { /** 蓝牙设备主 service 的 uuid 列表 */ services: Array<string>; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetConnectedBluetoothDevicesCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetConnectedBluetoothDevicesFailCallback; /** 接口调用成功的回调函数 */ success?: GetConnectedBluetoothDevicesSuccessCallback; } interface GetConnectedBluetoothDevicesSuccessCallbackResult { /** 搜索到的设备列表 */ devices: BluetoothDeviceInfo; } interface GetConnectedWifiOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetConnectedWifiCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetConnectedWifiFailCallback; /** 接口调用成功的回调函数 */ success?: GetConnectedWifiSuccessCallback; } interface GetConnectedWifiSuccessCallbackResult { /** [WifiInfo](https://developers.weixin.qq.com/miniprogram/dev/api/device/wifi/WifiInfo.html) * * Wi-Fi 信息 */ wifi: WifiInfo; } interface GetExtConfigOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetExtConfigCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetExtConfigFailCallback; /** 接口调用成功的回调函数 */ success?: GetExtConfigSuccessCallback; } interface GetExtConfigSuccessCallbackResult { /** 第三方平台自定义的数据 */ extConfig: object; } interface GetFileInfoFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail file not exist': 指定的 filePath 找不到文件; */ errMsg: string; } interface GetHCEStateOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetHCEStateCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetHCEStateFailCallback; /** 接口调用成功的回调函数 */ success?: GetHCEStateSuccessCallback; } interface GetImageInfoOption { /** 图片的路径,可以是相对路径、临时文件路径、存储文件路径、网络图片路径 */ src: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetImageInfoCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetImageInfoFailCallback; /** 接口调用成功的回调函数 */ success?: GetImageInfoSuccessCallback; } interface GetImageInfoSuccessCallbackResult { /** 图片原始高度,单位px。不考虑旋转。 */ height: number; /** [拍照时设备方向](http://sylvana.net/jpegcrop/exif_orientation.html) * * 可选值: * - 'up': 默认方向(手机横持拍照),对应 Exif 中的 1。或无 orientation 信息。; * - 'up-mirrored': 同 up,但镜像翻转,对应 Exif 中的 2; * - 'down': 旋转180度,对应 Exif 中的 3; * - 'down-mirrored': 同 down,但镜像翻转,对应 Exif 中的 4; * - 'left-mirrored': 同 left,但镜像翻转,对应 Exif 中的 5; * - 'right': 顺时针旋转90度,对应 Exif 中的 6; * - 'right-mirrored': 同 right,但镜像翻转,对应 Exif 中的 7; * - 'left': 逆时针旋转90度,对应 Exif 中的 8; * * 最低基础库: `1.9.90` */ orientation: | 'up' | 'up-mirrored' | 'down' | 'down-mirrored' | 'left-mirrored' | 'right' | 'right-mirrored' | 'left'; /** 图片的本地路径 */ path: string; /** 图片格式 * * 最低基础库: `1.9.90` */ type: string; /** 图片原始宽度,单位px。不考虑旋转。 */ width: number; } interface GetLocationOption { /** 传入 true 会返回高度信息,由于获取高度需要较高精确度,会减慢接口返回速度 * * 最低基础库: `1.6.0` */ altitude?: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetLocationCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetLocationFailCallback; /** 接口调用成功的回调函数 */ success?: GetLocationSuccessCallback; /** wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标 */ type?: string; } interface GetLocationSuccessCallbackResult { /** 位置的精确度 */ accuracy: number; /** 高度,单位 m * * 最低基础库: `1.2.0` */ altitude: number; /** 水平精度,单位 m * * 最低基础库: `1.2.0` */ horizontalAccuracy: number; /** 纬度,范围为 -90~90,负数表示南纬 */ latitude: number; /** 经度,范围为 -180~180,负数表示西经 */ longitude: number; /** 速度,单位 m/s */ speed: number; /** 垂直精度,单位 m(Android 无法获取,返回 0) * * 最低基础库: `1.2.0` */ verticalAccuracy: number; } interface GetNetworkTypeOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetNetworkTypeCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetNetworkTypeFailCallback; /** 接口调用成功的回调函数 */ success?: GetNetworkTypeSuccessCallback; } interface GetNetworkTypeSuccessCallbackResult { /** 网络类型 * * 可选值: * - 'wifi': wifi 网络; * - '2g': 2g 网络; * - '3g': 3g 网络; * - '4g': 4g 网络; * - 'unknown': Android 下不常见的网络类型; * - 'none': 无网络; */ networkType: 'wifi' | '2g' | '3g' | '4g' | 'unknown' | 'none'; } interface GetRegionOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetRegionCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetRegionFailCallback; /** 接口调用成功的回调函数 */ success?: GetRegionSuccessCallback; } interface GetRegionSuccessCallbackResult { /** 东北角经纬度 */ northeast: number; /** 西南角经纬度 */ southwest: number; } interface GetSavedFileInfoOption { /** 文件路径 */ filePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetSavedFileInfoCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetSavedFileInfoFailCallback; /** 接口调用成功的回调函数 */ success?: GetSavedFileInfoSuccessCallback; } interface GetSavedFileInfoSuccessCallbackResult { /** 文件保存时的时间戳,从1970/01/01 08:00:00 到该时刻的秒数 */ createTime: number; /** 文件大小,单位 B */ size: number; } interface GetScaleOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetScaleCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetScaleFailCallback; /** 接口调用成功的回调函数 */ success?: GetScaleSuccessCallback; } interface GetScaleSuccessCallbackResult { /** 缩放值 */ scale: number; } interface GetScreenBrightnessOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetScreenBrightnessCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetScreenBrightnessFailCallback; /** 接口调用成功的回调函数 */ success?: GetScreenBrightnessSuccessCallback; } interface GetScreenBrightnessSuccessCallbackOption { /** 屏幕亮度值,范围 0 ~ 1,0 最暗,1 最亮 */ value: number; } interface GetSettingOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetSettingCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetSettingFailCallback; /** 接口调用成功的回调函数 */ success?: GetSettingSuccessCallback; } interface GetSettingSuccessCallbackResult { /** [AuthSetting](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/setting/AuthSetting.html) * * 用户授权结果 */ authSetting: AuthSetting; } interface GetShareInfoOption { /** shareTicket */ shareTicket: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetShareInfoCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetShareInfoFailCallback; /** 接口调用成功的回调函数 */ success?: GetShareInfoSuccessCallback; /** 超时时间,单位 ms * * 最低基础库: `1.9.90` */ timeout?: number; } interface GetShareInfoSuccessCallbackResult { /** 包括敏感数据在内的完整转发信息的加密数据,详细见[加密数据解密算法]((开放数据校验与解密)) */ encryptedData: string; /** 错误信息 */ errMsg: string; /** 加密算法的初始向量,详细见[加密数据解密算法]((开放数据校验与解密)) */ iv: string; } interface GetStorageInfoOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetStorageInfoCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetStorageInfoFailCallback; /** 接口调用成功的回调函数 */ success?: GetStorageInfoSuccessCallback; } interface GetStorageInfoSuccessCallbackOption { /** 当前占用的空间大小, 单位 KB */ currentSize: number; /** 当前 storage 中所有的 key */ keys: Array<string>; /** 限制的空间大小,单位 KB */ limitSize: number; } interface GetStorageInfoSyncOption { /** 当前占用的空间大小, 单位 KB */ currentSize: number; /** 当前 storage 中所有的 key */ keys: Array<string>; /** 限制的空间大小,单位 KB */ limitSize: number; } interface GetStorageOption { /** 本地缓存中指定的 key */ key: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetStorageCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetStorageFailCallback; /** 接口调用成功的回调函数 */ success?: GetStorageSuccessCallback; } interface GetStorageSuccessCallbackResult { /** key对应的内容 */ data: any; } interface GetSystemInfoOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetSystemInfoCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetSystemInfoFailCallback; /** 接口调用成功的回调函数 */ success?: GetSystemInfoSuccessCallback; } interface GetSystemInfoSuccessCallbackResult { /** 客户端基础库版本 * * 最低基础库: `1.1.0` */ SDKVersion: string; /** (仅Android小游戏) 性能等级,-2 或 0:该设备无法运行小游戏,-1:性能未知,>=1 设备性能值,该值越高,设备性能越好 (目前设备最高不到50) * * 最低基础库: `1.8.0` */ benchmarkLevel: number; /** 手机品牌 * * 最低基础库: `1.5.0` */ brand: string; /** 用户字体大小设置。以“我-设置-通用-字体大小”中的设置为准,单位 px。 * * 最低基础库: `1.5.0` */ fontSizeSetting: number; /** 微信设置的语言 */ language: string; /** 手机型号 */ model: string; /** 设备像素比 */ pixelRatio: number; /** 客户端平台 */ platform: string; /** 屏幕高度 * * 最低基础库: `1.1.0` */ screenHeight: number; /** 屏幕宽度 * * 最低基础库: `1.1.0` */ screenWidth: number; /** 状态栏的高度 * * 最低基础库: `1.9.0` */ statusBarHeight: number; /** 操作系统版本 */ system: string; /** 微信版本号 */ version: string; /** 可使用窗口高度 */ windowHeight: number; /** 可使用窗口宽度 */ windowWidth: number; } interface GetSystemInfoSyncResult { /** 客户端基础库版本 * * 最低基础库: `1.1.0` */ SDKVersion: string; /** (仅Android小游戏) 性能等级,-2 或 0:该设备无法运行小游戏,-1:性能未知,>=1 设备性能值,该值越高,设备性能越好 (目前设备最高不到50) * * 最低基础库: `1.8.0` */ benchmarkLevel: number; /** 手机品牌 * * 最低基础库: `1.5.0` */ brand: string; /** 用户字体大小设置。以“我-设置-通用-字体大小”中的设置为准,单位 px。 * * 最低基础库: `1.5.0` */ fontSizeSetting: number; /** 微信设置的语言 */ language: string; /** 手机型号 */ model: string; /** 设备像素比 */ pixelRatio: number; /** 客户端平台 */ platform: string; /** 屏幕高度 * * 最低基础库: `1.1.0` */ screenHeight: number; /** 屏幕宽度 * * 最低基础库: `1.1.0` */ screenWidth: number; /** 状态栏的高度 * * 最低基础库: `1.9.0` */ statusBarHeight: number; /** 操作系统版本 */ system: string; /** 微信版本号 */ version: string; /** 可使用窗口高度 */ windowHeight: number; /** 可使用窗口宽度 */ windowWidth: number; } interface GetUserInfoOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetUserInfoCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetUserInfoFailCallback; /** 显示用户信息的语言 * * 可选值: * - 'en': 英文; * - 'zh_CN': 简体中文; * - 'zh_TW': 繁体中文; */ lang?: 'en' | 'zh_CN' | 'zh_TW'; /** 接口调用成功的回调函数 */ success?: GetUserInfoSuccessCallback; /** 是否带上登录态信息。当 withCredentials 为 true 时,要求此前有调用过 wx.login 且登录态尚未过期,此时返回的数据会包含 encryptedData, iv 等敏感信息;当 withCredentials 为 false 时,不要求有登录态,返回的数据不包含 encryptedData, iv 等敏感信息。 */ withCredentials?: boolean; } interface GetUserInfoSuccessCallbackResult { /** 包括敏感数据在内的完整用户信息的加密数据,详见 [用户数据的签名验证和加解密]((signature#加密数据解密算法)) */ encryptedData: string; /** 加密算法的初始向量,详见 [用户数据的签名验证和加解密]((signature#加密数据解密算法)) */ iv: string; /** 不包括敏感信息的原始数据字符串,用于计算签名 */ rawData: string; /** 使用 sha1( rawData + sessionkey ) 得到字符串,用于校验用户信息,详见 [用户数据的签名验证和加解密]((signature)) */ signature: string; /** [UserInfo](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/UserInfo.html) * * 用户信息对象,不包含 openid 等敏感信息 */ userInfo: UserInfo; } interface GetWeRunDataOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetWeRunDataCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetWeRunDataFailCallback; /** 接口调用成功的回调函数 */ success?: GetWeRunDataSuccessCallback; } interface GetWeRunDataSuccessCallbackResult { /** 包括敏感数据在内的完整用户信息的加密数据,详细见[加密数据解密算法]((signature))。解密后得到的数据结构见后文 */ encryptedData: string; /** 加密算法的初始向量,详细见[加密数据解密算法]((signature)) */ iv: string; } interface GetWifiListOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: GetWifiListCompleteCallback; /** 接口调用失败的回调函数 */ fail?: GetWifiListFailCallback; /** 接口调用成功的回调函数 */ success?: GetWifiListSuccessCallback; } interface HideLoadingOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: HideLoadingCompleteCallback; /** 接口调用失败的回调函数 */ fail?: HideLoadingFailCallback; /** 接口调用成功的回调函数 */ success?: HideLoadingSuccessCallback; } interface HideNavigationBarLoadingOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: HideNavigationBarLoadingCompleteCallback; /** 接口调用失败的回调函数 */ fail?: HideNavigationBarLoadingFailCallback; /** 接口调用成功的回调函数 */ success?: HideNavigationBarLoadingSuccessCallback; } interface HideShareMenuOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: HideShareMenuCompleteCallback; /** 接口调用失败的回调函数 */ fail?: HideShareMenuFailCallback; /** 接口调用成功的回调函数 */ success?: HideShareMenuSuccessCallback; } interface HideTabBarOption { /** 是否需要动画效果 */ animation?: boolean; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: HideTabBarCompleteCallback; /** 接口调用失败的回调函数 */ fail?: HideTabBarFailCallback; /** 接口调用成功的回调函数 */ success?: HideTabBarSuccessCallback; } interface HideTabBarRedDotOption { /** tabBar 的哪一项,从左边算起 */ index: number; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: HideTabBarRedDotCompleteCallback; /** 接口调用失败的回调函数 */ fail?: HideTabBarRedDotFailCallback; /** 接口调用成功的回调函数 */ success?: HideTabBarRedDotSuccessCallback; } interface HideToastOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: HideToastCompleteCallback; /** 接口调用失败的回调函数 */ fail?: HideToastFailCallback; /** 接口调用成功的回调函数 */ success?: HideToastSuccessCallback; } interface IBeaconInfo { /** iBeacon 设备的距离 */ accuracy: number; /** iBeacon 设备的主 id */ major: string; /** iBeacon 设备的次 id */ minor: string; /** 表示设备距离的枚举值 */ proximity: number; /** 表示设备的信号强度 */ rssi: number; /** iBeacon 设备广播的 uuid */ uuid: string; } /** 图片的本地临时文件列表 * * 最低基础库: `1.2.0` */ interface ImageFile { /** 本地临时文件路径 */ path: string; /** 本地临时文件大小,单位 B */ size: number; } interface IncludePointsOption { /** 要显示在可视区域内的坐标点列表 */ points: MapPostion; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: IncludePointsCompleteCallback; /** 接口调用失败的回调函数 */ fail?: IncludePointsFailCallback; /** 坐标点形成的矩形边缘到地图边缘的距离,单位像素。格式为[上,右,下,左],安卓上只能识别数组第一项,上下左右的padding一致。开发者工具暂不支持padding参数。 */ padding?: Array<number>; /** 接口调用成功的回调函数 */ success?: IncludePointsSuccessCallback; } /** InnerAudioContext 实例,可通过 [wx.createInnerAudioContext](https://developers.weixin.qq.com/miniprogram/dev/api/media/audio/wx.createInnerAudioContext.html) 接口获取实例。 * * **支持格式** * * * | 格式 | iOS | Android | * | ---- | ---- | ------- | * | flac | x | √ | * | m4a | x | √ | * | ogg | x | √ | * | ape | x | √ | * | amr | x | √ | * | wma | x | √ | * | wav | √ | √ | * | mp3 | √ | √ | * | mp4 | x | √ | * | aac | √ | √ | * | aiff | √ | x | * | caf | √ | x | * * **示例代码** * * * ```js const innerAudioContext = wx.createInnerAudioContext() innerAudioContext.autoplay = true innerAudioContext.src = 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46' innerAudioContext.onPlay(() => { console.log('开始播放') }) innerAudioContext.onError((res) => { console.log(res.errMsg) console.log(res.errCode) }) ``` */ interface InnerAudioContext { /** 是否自动开始播放,默认为 `false` */ autoplay: boolean; /** 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲(只读) */ buffered: number; /** 当前音频的播放位置(单位 s)。只有在当前有合法的 src 时返回,时间保留小数点后 6 位(只读) */ currentTime: number; /** 当前音频的长度(单位 s)。只有在当前有合法的 src 时返回(只读) */ duration: number; /** 是否循环播放,默认为 `false` */ loop: boolean; /** 是否遵循系统静音开关,默认为 `true`。当此参数为 `false` 时,即使用户打开了静音开关,也能继续发出声音 */ obeyMuteSwitch: boolean; /** 当前是是否暂停或停止状态(只读) */ paused: boolean; /** 音频资源的地址,用于直接播放。{% version('2.2.3') %} 开始支持云文件ID */ src: string; /** 开始播放的位置(单位:s),默认为 0 */ startTime: number; /** 音量。范围 0~1。默认为 1 * * 最低基础库: `1.9.90` */ volume: number; } interface InnerAudioContextOnErrorCallbackResult { /** * * 可选值: * - 10001: 系统错误; * - 10002: 网络错误; * - 10003: 文件错误; * - 10004: 格式错误; * - -1: 未知错误; */ errCode: 10001 | 10002 | 10003 | 10004 | -1; } /** 相交区域的边界 */ interface IntersectionRectResult { /** 下边界 */ bottom: number; /** 左边界 */ left: number; /** 右边界 */ right: number; /** 上边界 */ top: number; } /** 用户选中的发票列表 */ interface InvoiceInfo { /** 所选发票卡券的 cardId */ cardId: string; /** 所选发票卡券的加密 code,报销方可以通过 cardId 和 encryptCode 获得报销发票的信息。 */ encryptCode: string; /** 发票方的 appId */ publisherAppId: string; } /** 启动参数 */ interface LaunchOptionsApp { /** 启动小程序的路径 */ path: string; /** 启动小程序的 query 参数 */ query: object; /** 来源信息。从另一个小程序、公众号或 App 进入小程序时返回。否则返回 `{}`。(参见后文注意) */ referrerInfo: ReferrerInfo; /** 启动小程序的[场景值]((scene)) */ scene: number; /** shareTicket,详见[获取更多转发信息]((转发#获取更多转发信息)) */ shareTicket: string; } interface LivePlayerContextPauseOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: LivePlayerContextPauseCompleteCallback; /** 接口调用失败的回调函数 */ fail?: LivePlayerContextPauseFailCallback; /** 接口调用成功的回调函数 */ success?: LivePlayerContextPauseSuccessCallback; } interface LivePlayerContextRequestFullScreenOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: RequestFullScreenCompleteCallback; /** 设置全屏时的方向 * * 可选值: * - 0: 正常竖向; * - 90: 屏幕逆时针90度; * - -90: 屏幕顺时针90度; */ direction?: 0 | 90 | -90; /** 接口调用失败的回调函数 */ fail?: RequestFullScreenFailCallback; /** 接口调用成功的回调函数 */ success?: RequestFullScreenSuccessCallback; } interface LivePlayerContextResumeOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: LivePlayerContextResumeCompleteCallback; /** 接口调用失败的回调函数 */ fail?: LivePlayerContextResumeFailCallback; /** 接口调用成功的回调函数 */ success?: LivePlayerContextResumeSuccessCallback; } interface LivePlayerContextStopOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: LivePlayerContextStopCompleteCallback; /** 接口调用失败的回调函数 */ fail?: LivePlayerContextStopFailCallback; /** 接口调用成功的回调函数 */ success?: LivePlayerContextStopSuccessCallback; } interface LivePusherContextPauseOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: LivePusherContextPauseCompleteCallback; /** 接口调用失败的回调函数 */ fail?: LivePusherContextPauseFailCallback; /** 接口调用成功的回调函数 */ success?: LivePusherContextPauseSuccessCallback; } interface LivePusherContextResumeOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: LivePusherContextResumeCompleteCallback; /** 接口调用失败的回调函数 */ fail?: LivePusherContextResumeFailCallback; /** 接口调用成功的回调函数 */ success?: LivePusherContextResumeSuccessCallback; } interface LivePusherContextStartOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StartCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StartFailCallback; /** 接口调用成功的回调函数 */ success?: StartSuccessCallback; } interface LivePusherContextStopOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: LivePusherContextStopCompleteCallback; /** 接口调用失败的回调函数 */ fail?: LivePusherContextStopFailCallback; /** 接口调用成功的回调函数 */ success?: LivePusherContextStopSuccessCallback; } interface LoadFontFaceOption { /** 定义的字体名称 */ family: string; /** 字体资源的地址。建议格式为 TTF 和 WOFF,WOFF2 在低版本的iOS上会不兼容。 */ source: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: LoadFontFaceCompleteCallback; /** 可选的字体描述符 */ desc?: DescOption; /** 接口调用失败的回调函数 */ fail?: LoadFontFaceFailCallback; /** 接口调用成功的回调函数 */ success?: LoadFontFaceSuccessCallback; } interface LoginOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: LoginCompleteCallback; /** 接口调用失败的回调函数 */ fail?: LoginFailCallback; /** 接口调用成功的回调函数 */ success?: LoginSuccessCallback; /** 超时时间,单位ms * * 最低基础库: `1.9.90` */ timeout?: number; } interface LoginSuccessCallbackResult { /** 用户登录凭证(有效期五分钟)。开发者需要在开发者服务器后台调用 [code2Session]((code2Session)),使用 code 换取 openid 和 session_key 等信息 */ code: string; } interface MakePhoneCallOption { /** 需要拨打的电话号码 */ phoneNumber: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: MakePhoneCallCompleteCallback; /** 接口调用失败的回调函数 */ fail?: MakePhoneCallFailCallback; /** 接口调用成功的回调函数 */ success?: MakePhoneCallSuccessCallback; } /** 要显示在可视区域内的坐标点列表 */ interface MapPostion { /** 纬度 */ latitude: number; /** 经度 */ longitude: number; } /** 小程序帐号信息 */ interface MiniProgram { /** 小程序 appId */ appId: string; } interface MkdirFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail no such file or directory ${dirPath}': 上级目录不存在; * - 'fail permission denied, open ${dirPath}': 指定的 filePath 路径没有写权限; * - 'fail file already exists ${dirPath}': 有同名文件或目录; */ errMsg: string; } interface MkdirOption { /** 创建的目录路径 */ dirPath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: MkdirCompleteCallback; /** 接口调用失败的回调函数 */ fail?: MkdirFailCallback; /** 是否在递归创建该目录的上级目录后再创建该目录。如果对应的上级目录已经存在,则不创建该上级目录。如 dirPath 为 a/b/c/d 且 recursive 为 true,将创建 a 目录,再在 a 目录下创建 b 目录,以此类推直至创建 a/b/c 目录下的 d 目录。 * * 最低基础库: `2.3.0` */ recursive?: boolean; /** 接口调用成功的回调函数 */ success?: MkdirSuccessCallback; } interface MuteOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: MuteCompleteCallback; /** 接口调用失败的回调函数 */ fail?: MuteFailCallback; /** 接口调用成功的回调函数 */ success?: MuteSuccessCallback; } interface NavigateBackMiniProgramOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: NavigateBackMiniProgramCompleteCallback; /** 需要返回给上一个小程序的数据,上一个小程序可在 `App.onShow` 中获取到这份数据。 [详情]((小程序 App))。 */ extraData?: object; /** 接口调用失败的回调函数 */ fail?: NavigateBackMiniProgramFailCallback; /** 接口调用成功的回调函数 */ success?: NavigateBackMiniProgramSuccessCallback; } interface NavigateBackOption { /** 返回的页面数,如果 delta 大于现有页面数,则返回到首页。 */ delta: number; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: NavigateBackCompleteCallback; /** 接口调用失败的回调函数 */ fail?: NavigateBackFailCallback; /** 接口调用成功的回调函数 */ success?: NavigateBackSuccessCallback; } interface NavigateToMiniProgramOption { /** 要打开的小程序 appId */ appId: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: NavigateToMiniProgramCompleteCallback; /** 要打开的小程序版本。仅在当前小程序为开发版或体验版时此参数有效。如果当前小程序是正式版,则打开的小程序必定是正式版。 * * 可选值: * - 'develop': 开发版; * - 'trial': 体验版; * - 'release': 正式版; */ envVersion?: 'develop' | 'trial' | 'release'; /** 需要传递给目标小程序的数据,目标小程序可在 `App.onLaunch`,`App.onShow` 中获取到这份数据。 */ extraData?: object; /** 接口调用失败的回调函数 */ fail?: NavigateToMiniProgramFailCallback; /** 打开的页面路径,如果为空则打开首页 */ path?: string; /** 接口调用成功的回调函数 */ success?: NavigateToMiniProgramSuccessCallback; } interface NavigateToOption { /** 需要跳转的应用内非 tabBar 的页面的路径, 路径后可以带参数。参数与路径之间使用 `?` 分隔,参数键与参数值用 `=` 相连,不同参数用 `&` 分隔;如 'path?key=value&key2=value2' */ url: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: NavigateToCompleteCallback; /** 接口调用失败的回调函数 */ fail?: NavigateToFailCallback; /** 接口调用成功的回调函数 */ success?: NavigateToSuccessCallback; } interface NotifyBLECharacteristicValueChangeOption { /** 蓝牙特征值的 uuid */ characteristicId: string; /** 蓝牙设备 id */ deviceId: string; /** 蓝牙特征值对应服务的 uuid */ serviceId: string; /** 是否启用 notify */ state: boolean; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: NotifyBLECharacteristicValueChangeCompleteCallback; /** 接口调用失败的回调函数 */ fail?: NotifyBLECharacteristicValueChangeFailCallback; /** 接口调用成功的回调函数 */ success?: NotifyBLECharacteristicValueChangeSuccessCallback; } interface ObserveCallbackResult { /** 目标边界 */ boundingClientRect: BoundingClientRectResult; /** 相交比例 */ intersectionRatio: number; /** 相交区域的边界 */ intersectionRect: IntersectionRectResult; /** 参照区域的边界 */ relativeRect: RelativeRectResult; /** 相交检测时的时间戳 */ time: number; } interface OnAccelerometerChangeCallbackResult { /** X 轴 */ x: number; /** Y 轴 */ y: number; /** Z 轴 */ z: number; } interface OnAppShowCallbackResult { object: ResultOption; } interface OnBLECharacteristicValueChangeCallbackResult { /** 蓝牙特征值的 uuid */ characteristicId: string; /** 蓝牙设备 id */ deviceId: string; /** 蓝牙特征值对应服务的 uuid */ serviceId: string; /** 特征值最新的值 */ value: ArrayBuffer; } interface OnBLEConnectionStateChangeCallbackResult { /** 是否处于已连接状态 */ connected: boolean; /** 蓝牙设备ID */ deviceId: string; } interface OnBeaconServiceChangeCallbackResult { /** 服务目前是否可用 */ available: boolean; /** 目前是否处于搜索状态 */ discovering: boolean; } interface OnBeaconUpdateCallbackResult { /** 当前搜寻到的所有 iBeacon 设备列表 */ beacons: Array<IBeaconInfo>; } interface OnBluetoothAdapterStateChangeCallbackResult { /** 蓝牙适配器是否可用 */ available: boolean; /** 蓝牙适配器是否处于搜索状态 */ discovering: boolean; } interface OnBluetoothDeviceFoundCallbackResult { /** 新搜索到的设备列表 */ devices: CallbackResultBlueToothDevice; } interface OnCheckForUpdateCallbackResult { /** 是否有新版本 */ hasUpdate: boolean; } interface OnCompassChangeCallbackResult { /** 精度 * * 最低基础库: `2.4.0` */ accuracy: number | string; /** 面对的方向度数 */ direction: number; } interface OnDeviceMotionChangeCallbackResult { /** 当 手机坐标 X/Y 和 地球 X/Y 重合时,绕着 Z 轴转动的夹角为 alpha,范围值为 [0, 2*PI)。逆时针转动为正。 */ alpha: number; /** 当手机坐标 Y/Z 和地球 Y/Z 重合时,绕着 X 轴转动的夹角为 beta。范围值为 [-1*PI, PI) 。顶部朝着地球表面转动为正。也有可能朝着用户为正。 */ beta: number; /** 当手机 X/Z 和地球 X/Z 重合时,绕着 Y 轴转动的夹角为 gamma。范围值为 [-1*PI/2, PI/2)。右边朝着地球表面转动为正。 */ gamma: number; } interface OnFrameRecordedCallbackResult { /** 录音分片数据 */ frameBuffer: ArrayBuffer; /** 当前帧是否正常录音结束前的最后一帧 */ isLastFrame: boolean; } interface OnGetWifiListCallbackResult { /** Wi-Fi 列表数据 */ wifiList: Array<WifiInfo>; } interface OnGyroscopeChangeCallbackResult { res: Result; } interface OnHCEMessageCallbackResult { /** `messageType=1` 时 ,客户端接收到 NFC 设备的指令 */ data: ArrayBuffer; /** 消息类型 * * 可选值: * - 1: HCE APDU Command类型,小程序需对此指令进行处理,并调用 sendHCEMessage 接口返回处理指令; * - 2: 设备离场事件类型; */ messageType: 1 | 2; /** `messageType=2` 时,原因 */ reason: number; } interface OnLocalServiceFoundCallbackResult { /** 服务的 ip 地址 */ ip: string; /** 服务的端口 */ port: number; /** 服务的名称 */ serviceName: string; /** 服务的类型 */ serviceType: string; } interface OnLocalServiceLostCallbackResult { /** 服务的名称 */ serviceName: string; /** 服务的类型 */ serviceType: string; } interface OnLocalServiceResolveFailCallbackResult { /** 服务的名称 */ serviceName: string; /** 服务的类型 */ serviceType: string; } interface OnMemoryWarningCallbackResult { /** 内存告警等级,只有 Android 才有,对应系统宏定义 * * 可选值: * - 5: TRIM_MEMORY_RUNNING_MODERATE; * - 10: TRIM_MEMORY_RUNNING_LOW; * - 15: TRIM_MEMORY_RUNNING_CRITICAL; */ level: 5 | 10 | 15; } interface OnNetworkStatusChangeCallbackResult { /** 当前是否有网络链接 */ isConnected: boolean; /** 网络类型 * * 可选值: * - 'wifi': wifi 网络; * - '2g': 2g 网络; * - '3g': 3g 网络; * - '4g': 4g 网络; * - 'unknown': Android 下不常见的网络类型; * - 'none': 无网络; */ networkType: 'wifi' | '2g' | '3g' | '4g' | 'unknown' | 'none'; } interface OnOpenCallbackResult { /** 连接成功的 HTTP 响应 Header * * 最低基础库: `2.0.0` */ header: object; } interface OnSocketMessageCallbackResult { /** 服务器返回的消息 */ data: string | ArrayBuffer; } interface OnSocketOpenCallbackResult { /** 连接成功的 HTTP 响应 Header * * 最低基础库: `2.0.0` */ header: object; } interface OnStopCallbackResult { /** 录音文件的临时路径 */ tempFilePath: string; } interface OnWifiConnectedCallbackResult { /** [WifiInfo](https://developers.weixin.qq.com/miniprogram/dev/api/device/wifi/WifiInfo.html) * * Wi-Fi 信息 */ wifi: WifiInfo; } interface OnWindowResizeCallbackResult { size: Size; } interface OpenBluetoothAdapterOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: OpenBluetoothAdapterCompleteCallback; /** 接口调用失败的回调函数 */ fail?: OpenBluetoothAdapterFailCallback; /** 接口调用成功的回调函数 */ success?: OpenBluetoothAdapterSuccessCallback; } interface OpenCardOption { /** 需要打开的卡券列表 */ cardList: OpenCardRequestInfo; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: OpenCardCompleteCallback; /** 接口调用失败的回调函数 */ fail?: OpenCardFailCallback; /** 接口调用成功的回调函数 */ success?: OpenCardSuccessCallback; } /** 需要打开的卡券列表 */ interface OpenCardRequestInfo { /** 卡券 ID */ cardId: string; /** 由 [wx.addCard](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/card/wx.addCard.html) 的返回对象中的加密 code 通过解密后得到,解密请参照:[code 解码接口](https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1499332673_Unm7V) */ code: string; } interface OpenDocumentOption { /** 文件路径,可通过 downloadFile 获得 */ filePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: OpenDocumentCompleteCallback; /** 接口调用失败的回调函数 */ fail?: OpenDocumentFailCallback; /** 文件类型,指定文件类型打开文件 * * 可选值: * - 'doc': doc 格式; * - 'docx': docx 格式; * - 'xls': xls 格式; * - 'xlsx': xlsx 格式; * - 'ppt': ppt 格式; * - 'pptx': pptx 格式; * - 'pdf': pdf 格式; * * 最低基础库: `1.4.0` */ fileType?: 'doc' | 'docx' | 'xls' | 'xlsx' | 'ppt' | 'pptx' | 'pdf'; /** 接口调用成功的回调函数 */ success?: OpenDocumentSuccessCallback; } interface OpenLocationOption { /** 纬度,范围为-90~90,负数表示南纬。使用 gcj02 国测局坐标系 */ latitude: number; /** 经度,范围为-180~180,负数表示西经。使用 gcj02 国测局坐标系 */ longitude: number; /** 地址的详细说明 */ address?: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: OpenLocationCompleteCallback; /** 接口调用失败的回调函数 */ fail?: OpenLocationFailCallback; /** 位置名 */ name?: string; /** 缩放比例,范围5~18 */ scale?: number; /** 接口调用成功的回调函数 */ success?: OpenLocationSuccessCallback; } interface OpenSettingOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: OpenSettingCompleteCallback; /** 接口调用失败的回调函数 */ fail?: OpenSettingFailCallback; /** 接口调用成功的回调函数 */ success?: OpenSettingSuccessCallback; } interface OpenSettingSuccessCallbackResult { /** [AuthSetting](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/setting/AuthSetting.html) * * 用户授权结果 */ authSetting: AuthSetting; } interface PageScrollToOption { /** 滚动到页面的目标位置,单位 px */ scrollTop: number; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: PageScrollToCompleteCallback; /** 滚动动画的时长,单位 ms */ duration?: number; /** 接口调用失败的回调函数 */ fail?: PageScrollToFailCallback; /** 接口调用成功的回调函数 */ success?: PageScrollToSuccessCallback; } interface PauseBGMOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: PauseBGMCompleteCallback; /** 接口调用失败的回调函数 */ fail?: PauseBGMFailCallback; /** 接口调用成功的回调函数 */ success?: PauseBGMSuccessCallback; } interface PauseBackgroundAudioOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: PauseBackgroundAudioCompleteCallback; /** 接口调用失败的回调函数 */ fail?: PauseBackgroundAudioFailCallback; /** 接口调用成功的回调函数 */ success?: PauseBackgroundAudioSuccessCallback; } interface PauseVoiceOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: PauseVoiceCompleteCallback; /** 接口调用失败的回调函数 */ fail?: PauseVoiceFailCallback; /** 接口调用成功的回调函数 */ success?: PauseVoiceSuccessCallback; } interface PlayBGMOption { /** 加入背景混音的资源地址 */ url: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: PlayBGMCompleteCallback; /** 接口调用失败的回调函数 */ fail?: PlayBGMFailCallback; /** 接口调用成功的回调函数 */ success?: PlayBGMSuccessCallback; } interface PlayBackgroundAudioOption { /** 音乐链接,目前支持的格式有 m4a, aac, mp3, wav */ dataUrl: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: PlayBackgroundAudioCompleteCallback; /** 封面URL */ coverImgUrl?: string; /** 接口调用失败的回调函数 */ fail?: PlayBackgroundAudioFailCallback; /** 接口调用成功的回调函数 */ success?: PlayBackgroundAudioSuccessCallback; /** 音乐标题 */ title?: string; } interface PlayOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: PlayCompleteCallback; /** 接口调用失败的回调函数 */ fail?: PlayFailCallback; /** 接口调用成功的回调函数 */ success?: PlaySuccessCallback; } interface PlayVoiceOption { /** 需要播放的语音文件的文件路径 */ filePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: PlayVoiceCompleteCallback; /** 指定录音时长,到达指定的录音时长后会自动停止录音,单位:秒 * * 最低基础库: `1.6.0` */ duration?: number; /** 接口调用失败的回调函数 */ fail?: PlayVoiceFailCallback; /** 接口调用成功的回调函数 */ success?: PlayVoiceSuccessCallback; } /** 插件帐号信息(仅在插件中调用时包含这一项) */ interface Plugin { /** 插件 appId */ appId: string; /** 插件版本号 */ version: string; } interface PreviewImageOption { /** 需要预览的图片链接列表。{% version('2.2.3') %} 起支持云文件ID。 */ urls: Array<string>; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: PreviewImageCompleteCallback; /** 当前显示图片的链接 */ current?: string; /** 接口调用失败的回调函数 */ fail?: PreviewImageFailCallback; /** 接口调用成功的回调函数 */ success?: PreviewImageSuccessCallback; } /** 该特征值支持的操作类型 */ interface Properties { /** 该特征值是否支持 indicate 操作 */ indicate: boolean; /** 该特征值是否支持 notify 操作 */ notify: boolean; /** 该特征值是否支持 read 操作 */ read: boolean; /** 该特征值是否支持 write 操作 */ write: boolean; } interface ReLaunchOption { /** 需要跳转的应用内页面路径,路径后可以带参数。参数与路径之间使用?分隔,参数键与参数值用=相连,不同参数用&分隔;如 'path?key=value&key2=value2',如果跳转的页面路径是 tabBar 页面则不能带参数 */ url: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ReLaunchCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ReLaunchFailCallback; /** 接口调用成功的回调函数 */ success?: ReLaunchSuccessCallback; } interface ReadBLECharacteristicValueOption { /** 蓝牙特征值的 uuid */ characteristicId: string; /** 蓝牙设备 id */ deviceId: string; /** 蓝牙特征值对应服务的 uuid */ serviceId: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ReadBLECharacteristicValueCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ReadBLECharacteristicValueFailCallback; /** 接口调用成功的回调函数 */ success?: ReadBLECharacteristicValueSuccessCallback; } interface ReadFileFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail no such file or directory, open ${filePath}': 指定的 filePath 所在目录不存在; * - 'fail permission denied, open ${dirPath}': 指定的 filePath 路径没有读权限; */ errMsg: string; } interface ReadFileOption { /** 要读取的文件的路径 */ filePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ReadFileCompleteCallback; /** 指定读取文件的字符编码,如果不传 encoding,则以 ArrayBuffer 格式读取文件的二进制内容 * * 可选值: * - 'ascii': ; * - 'base64': ; * - 'binary': ; * - 'hex': ; * - 'ucs2/ucs-2/utf16le/utf-16le': 以小端序读取; * - 'utf-8/utf8': ; * - 'latin1': ; */ encoding?: | 'ascii' | 'base64' | 'binary' | 'hex' | 'ucs2/ucs-2/utf16le/utf-16le' | 'utf-8/utf8' | 'latin1'; /** 接口调用失败的回调函数 */ fail?: ReadFileFailCallback; /** 接口调用成功的回调函数 */ success?: ReadFileSuccessCallback; } interface ReadFileSuccessCallbackResult { /** 文件内容 */ data: string | ArrayBuffer; } interface ReaddirFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail no such file or directory ${dirPath}': 目录不存在; * - 'fail not a directory ${dirPath}': dirPath 不是目录; * - 'fail permission denied, open ${dirPath}': 指定的 filePath 路径没有读权限; */ errMsg: string; } interface ReaddirOption { /** 要读取的目录路径 */ dirPath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ReaddirCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ReaddirFailCallback; /** 接口调用成功的回调函数 */ success?: ReaddirSuccessCallback; } interface ReaddirSuccessCallbackResult { /** 指定目录下的文件名数组。 */ files: Array<string>; } interface RecorderManagerOnErrorCallbackResult { /** 错误信息 */ errMsg: string; } interface RecorderManagerStartOption { /** 指定录音的音频输入源,可通过 [wx.getAvailableAudioSources()](https://developers.weixin.qq.com/miniprogram/dev/api/media/audio/wx.getAvailableAudioSources.html) 获取当前可用的音频源 * * 可选值: * - 'auto': 自动设置,默认使用手机麦克风,插上耳麦后自动切换使用耳机麦克风,所有平台适用; * - 'buildInMic': 手机麦克风,仅限 iOS; * - 'headsetMic': 耳机麦克风,仅限 iOS; * - 'mic': 麦克风(没插耳麦时是手机麦克风,插耳麦时是耳机麦克风),仅限 Android; * - 'camcorder': 同 mic,适用于录制音视频内容,仅限 Android; * - 'voice_communication': 同 mic,适用于实时沟通,仅限 Android; * - 'voice_recognition': 同 mic,适用于语音识别,仅限 Android; * * 最低基础库: `2.1.0` */ audioSource?: | 'auto' | 'buildInMic' | 'headsetMic' | 'mic' | 'camcorder' | 'voice_communication' | 'voice_recognition'; /** 录音的时长,单位 ms,最大值 600000(10 分钟) */ duration?: number; /** 编码码率,有效值见下表格 */ encodeBitRate?: number; /** 音频格式 * * 可选值: * - 'mp3': mp3 格式; * - 'aac': aac 格式; */ format?: 'mp3' | 'aac'; /** 指定帧大小,单位 KB。传入 frameSize 后,每录制指定帧大小的内容后,会回调录制的文件内容,不指定则不会回调。暂仅支持 mp3 格式。 */ frameSize?: number; /** 录音通道数 * * 可选值: * - 1: 1 个通道; * - 2: 2 个通道; */ numberOfChannels?: 1 | 2; /** 采样率 * * 可选值: * - 8000: 8000 采样率; * - 11025: 11025 采样率; * - 12000: 12000 采样率; * - 16000: 16000 采样率; * - 22050: 22050 采样率; * - 24000: 24000 采样率; * - 32000: 32000 采样率; * - 44100: 44100 采样率; * - 48000: 48000 采样率; */ sampleRate?: | 8000 | 11025 | 12000 | 16000 | 22050 | 24000 | 32000 | 44100 | 48000; } /** 菜单按钮的布局位置信息 */ interface Rect { /** 下边界坐标,单位:px */ bottom: number; /** 高度,单位:px */ height: number; /** 左边界坐标,单位:px */ left: number; /** 右边界坐标,单位:px */ right: number; /** 上边界坐标,单位:px */ top: number; /** 宽度,单位:px */ width: number; } interface RedirectToOption { /** 需要跳转的应用内非 tabBar 的页面的路径, 路径后可以带参数。参数与路径之间使用 `?` 分隔,参数键与参数值用 `=` 相连,不同参数用 `&` 分隔;如 'path?key=value&key2=value2' */ url: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: RedirectToCompleteCallback; /** 接口调用失败的回调函数 */ fail?: RedirectToFailCallback; /** 接口调用成功的回调函数 */ success?: RedirectToSuccessCallback; } /** 来源信息。从另一个小程序、公众号或 App 进入小程序时返回。否则返回 `{}`。(参见后文注意) */ interface ReferrerInfo { /** 来源小程序、公众号或 App 的 appId */ appId: string; /** 来源小程序传过来的数据,scene=1037或1038时支持 */ extraData: object; } /** 来源信息。从另一个小程序、公众号或 App 进入小程序时返回。否则返回 `{}`。(参见后文注意) */ interface ReferrerInfoOption { /** 来源小程序、公众号或 App 的 appId */ appId: string; /** 来源小程序传过来的数据,scene=1037或1038时支持 */ extraData: object; } /** 参照区域的边界 */ interface RelativeRectResult { /** 下边界 */ bottom: number; /** 左边界 */ left: number; /** 右边界 */ right: number; /** 上边界 */ top: number; } /** 用来扩展(或收缩)参照节点布局区域的边界 */ interface RelativeToMargins { /** 节点布局区域的下边界 */ bottom?: number; /** 节点布局区域的左边界 */ left?: number; /** 节点布局区域的右边界 */ right?: number; /** 节点布局区域的上边界 */ top?: number; } /** 用来扩展(或收缩)参照节点布局区域的边界 */ interface RelativeToViewportMargins { /** 节点布局区域的下边界 */ bottom?: number; /** 节点布局区域的左边界 */ left?: number; /** 节点布局区域的右边界 */ right?: number; /** 节点布局区域的上边界 */ top?: number; } interface RemoveSavedFileFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail file not exist': 指定的 tempFilePath 找不到文件; */ errMsg: string; } interface RemoveStorageOption { /** 本地缓存中指定的 key */ key: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: RemoveStorageCompleteCallback; /** 接口调用失败的回调函数 */ fail?: RemoveStorageFailCallback; /** 接口调用成功的回调函数 */ success?: RemoveStorageSuccessCallback; } interface RemoveTabBarBadgeOption { /** tabBar 的哪一项,从左边算起 */ index: number; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: RemoveTabBarBadgeCompleteCallback; /** 接口调用失败的回调函数 */ fail?: RemoveTabBarBadgeFailCallback; /** 接口调用成功的回调函数 */ success?: RemoveTabBarBadgeSuccessCallback; } interface RenameFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail permission denied, rename ${oldPath} -> ${newPath}': 指定源文件或目标文件没有写权限; * - 'fail no such file or directory, rename ${oldPath} -> ${newPath}': 源文件不存在,或目标文件路径的上层目录不存在; */ errMsg: string; } interface RenameOption { /** 新文件路径 */ newPath: string; /** 源文件路径,可以是普通文件或目录 */ oldPath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: RenameCompleteCallback; /** 接口调用失败的回调函数 */ fail?: RenameFailCallback; /** 接口调用成功的回调函数 */ success?: RenameSuccessCallback; } interface RequestOption { /** 开发者服务器接口地址 */ url: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: RequestCompleteCallback; /** 请求的参数 */ data?: string | object | ArrayBuffer; /** 返回的数据格式 * * 可选值: * - 'json': 返回的数据为 JSON,返回后会对返回的数据进行一次 JSON.parse; * - '其他': 不对返回的内容进行 JSON.parse; */ dataType?: 'json' | '其他'; /** 接口调用失败的回调函数 */ fail?: RequestFailCallback; /** 设置请求的 header,header 中不能设置 Referer。 * * `content-type` 默认为 `application/json` */ header?: object; /** HTTP 请求方法 * * 可选值: * - 'OPTIONS': HTTP 请求 OPTIONS; * - 'GET': HTTP 请求 GET; * - 'HEAD': HTTP 请求 HEAD; * - 'POST': HTTP 请求 POST; * - 'PUT': HTTP 请求 PUT; * - 'DELETE': HTTP 请求 DELETE; * - 'TRACE': HTTP 请求 TRACE; * - 'CONNECT': HTTP 请求 CONNECT; */ method?: | 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'; /** 响应的数据类型 * * 可选值: * - 'text': 响应的数据为文本; * - 'arraybuffer': 响应的数据为 ArrayBuffer; * * 最低基础库: `1.7.0` */ responseType?: 'text' | 'arraybuffer'; /** 接口调用成功的回调函数 */ success?: RequestSuccessCallback; } interface RequestPaymentOption { /** 随机字符串,长度为32个字符以下 */ nonceStr: string; /** 统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=*** */ package: string; /** 签名,具体签名方案参见 [小程序支付接口文档](https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3) */ paySign: string; /** 时间戳,从 1970 年 1 月 1 日 00:00:00 至今的秒数,即当前的时间 */ timeStamp: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: RequestPaymentCompleteCallback; /** 接口调用失败的回调函数 */ fail?: RequestPaymentFailCallback; /** 签名算法 * * 可选值: * - 'MD5': MD5; * - 'HMAC-SHA256': HMAC-SHA256; */ signType?: 'MD5' | 'HMAC-SHA256'; /** 接口调用成功的回调函数 */ success?: RequestPaymentSuccessCallback; } interface RequestSuccessCallbackResult { /** 开发者服务器返回的数据 */ data: string | object | ArrayBuffer; /** 开发者服务器返回的 HTTP Response Header * * 最低基础库: `1.2.0` */ header: object; /** 开发者服务器返回的 HTTP 状态码 */ statusCode: number; } interface RequestTaskOnHeadersReceivedCallbackResult { /** 开发者服务器返回的 HTTP Response Header */ header: object; } interface Result { /** x 轴的角速度 */ x: number; /** y 轴的角速度 */ y: number; /** z 轴的角速度 */ z: number; } interface ResultOption { /** 小程序切前台的路径 */ path: string; /** 小程序切前台的 query 参数 */ query: object; /** 来源信息。从另一个小程序、公众号或 App 进入小程序时返回。否则返回 `{}`。(参见后文注意) */ referrerInfo: ReferrerInfoOption; /** 小程序切前台的[场景值]((scene)) */ scene: number; /** shareTicket,详见[获取更多转发信息]((转发#获取更多转发信息)) */ shareTicket: string; } interface ResumeBGMOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResumeBGMCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ResumeBGMFailCallback; /** 接口调用成功的回调函数 */ success?: ResumeBGMSuccessCallback; } interface RmdirFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail no such file or directory ${dirPath}': 目录不存在; * - 'fail directory not empty': 目录不为空; * - 'fail permission denied, open ${dirPath}': 指定的 dirPath 路径没有写权限; */ errMsg: string; } interface RmdirOption { /** 要删除的目录路径 */ dirPath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: RmdirCompleteCallback; /** 接口调用失败的回调函数 */ fail?: RmdirFailCallback; /** 是否递归删除目录。如果为 true,则删除该目录和该目录下的所有子目录以及文件。 * * 最低基础库: `2.3.0` */ recursive?: boolean; /** 接口调用成功的回调函数 */ success?: RmdirSuccessCallback; } interface SaveFileFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail tempFilePath file not exist': 指定的 tempFilePath 找不到文件; * - 'fail permission denied, open "${filePath}"': 指定的 filePath 路径没有写权限; * - 'fail no such file or directory "${dirPath}"': 上级目录不存在; */ errMsg: string; } interface SaveImageToPhotosAlbumOption { /** 图片文件路径,可以是临时文件路径或永久文件路径,不支持网络图片路径 */ filePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SaveImageToPhotosAlbumCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SaveImageToPhotosAlbumFailCallback; /** 接口调用成功的回调函数 */ success?: SaveImageToPhotosAlbumSuccessCallback; } interface SaveVideoToPhotosAlbumOption { /** 视频文件路径,可以是临时文件路径也可以是永久文件路径 */ filePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SaveVideoToPhotosAlbumCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SaveVideoToPhotosAlbumFailCallback; /** 接口调用成功的回调函数 */ success?: SaveVideoToPhotosAlbumSuccessCallback; } interface ScanCodeOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ScanCodeCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ScanCodeFailCallback; /** 是否只能从相机扫码,不允许从相册选择图片 * * 最低基础库: `1.2.0` */ onlyFromCamera?: boolean; /** 扫码类型 * * 可选值: * - 'barCode': 一维码; * - 'qrCode': 二维码; * - 'datamatrix': Data Matrix 码; * - 'pdf417': PDF417 条码; * * 最低基础库: `1.7.0` */ scanType?: ('barCode' | 'qrCode' | 'datamatrix' | 'pdf417')[]; /** 接口调用成功的回调函数 */ success?: ScanCodeSuccessCallback; } interface ScanCodeSuccessCallbackResult { /** 所扫码的字符集 */ charSet: string; /** 当所扫的码为当前小程序的合法二维码时,会返回此字段,内容为二维码携带的 path */ path: string; /** 原始数据,base64编码 */ rawData: string; /** 所扫码的内容 */ result: string; /** 所扫码的类型 * * 可选值: * - 'QR_CODE': 二维码; * - 'AZTEC': 一维码; * - 'CODABAR': 一维码; * - 'CODE_39': 一维码; * - 'CODE_93': 一维码; * - 'CODE_128': 一维码; * - 'DATA_MATRIX': 二维码; * - 'EAN_8': 一维码; * - 'EAN_13': 一维码; * - 'ITF': 一维码; * - 'MAXICODE': 一维码; * - 'PDF_417': 二维码; * - 'RSS_14': 一维码; * - 'RSS_EXPANDED': 一维码; * - 'UPC_A': 一维码; * - 'UPC_E': 一维码; * - 'UPC_EAN_EXTENSION': 一维码; * - 'WX_CODE': 二维码; * - 'CODE_25': 一维码; */ scanType: | 'QR_CODE' | 'AZTEC' | 'CODABAR' | 'CODE_39' | 'CODE_93' | 'CODE_128' | 'DATA_MATRIX' | 'EAN_8' | 'EAN_13' | 'ITF' | 'MAXICODE' | 'PDF_417' | 'RSS_14' | 'RSS_EXPANDED' | 'UPC_A' | 'UPC_E' | 'UPC_EAN_EXTENSION' | 'WX_CODE' | 'CODE_25'; } interface ScrollOffsetCallbackResult { /** 节点的 dataset */ dataset: object; /** 节点的 ID */ id: string; /** 节点的水平滚动位置 */ scrollLeft: number; /** 节点的竖直滚动位置 */ scrollTop: number; } interface SeekBackgroundAudioOption { /** 音乐位置,单位:秒 */ position: number; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SeekBackgroundAudioCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SeekBackgroundAudioFailCallback; /** 接口调用成功的回调函数 */ success?: SeekBackgroundAudioSuccessCallback; } interface SendHCEMessageOption { /** 二进制数据 */ data: ArrayBuffer; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SendHCEMessageCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SendHCEMessageFailCallback; /** 接口调用成功的回调函数 */ success?: SendHCEMessageSuccessCallback; } interface SendOption { /** 需要发送的内容 */ data: string | ArrayBuffer; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SendCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SendFailCallback; /** 接口调用成功的回调函数 */ success?: SendSuccessCallback; } interface SendSocketMessageOption { /** 需要发送的内容 */ data: string | ArrayBuffer; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SendSocketMessageCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SendSocketMessageFailCallback; /** 接口调用成功的回调函数 */ success?: SendSocketMessageSuccessCallback; } interface SetBGMVolumeOption { /** 音量大小 */ volume: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetBGMVolumeCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetBGMVolumeFailCallback; /** 接口调用成功的回调函数 */ success?: SetBGMVolumeSuccessCallback; } interface SetBackgroundColorOption { /** 窗口的背景色,必须为十六进制颜色值 */ backgroundColor?: string; /** 底部窗口的背景色,必须为十六进制颜色值,仅 iOS 支持 */ backgroundColorBottom?: string; /** 顶部窗口的背景色,必须为十六进制颜色值,仅 iOS 支持 */ backgroundColorTop?: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetBackgroundColorCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetBackgroundColorFailCallback; /** 接口调用成功的回调函数 */ success?: SetBackgroundColorSuccessCallback; } interface SetBackgroundTextStyleOption { /** 下拉背景字体、loading 图的样式。 * * 可选值: * - 'dark': dark 样式; * - 'light': light 样式; */ textStyle: 'dark' | 'light'; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetBackgroundTextStyleCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetBackgroundTextStyleFailCallback; /** 接口调用成功的回调函数 */ success?: SetBackgroundTextStyleSuccessCallback; } interface SetClipboardDataOption { /** 剪贴板的内容 */ data: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetClipboardDataCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetClipboardDataFailCallback; /** 接口调用成功的回调函数 */ success?: SetClipboardDataSuccessCallback; } interface SetEnableDebugOption { /** 是否打开调试 */ enableDebug: boolean; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetEnableDebugCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetEnableDebugFailCallback; /** 接口调用成功的回调函数 */ success?: SetEnableDebugSuccessCallback; } interface SetInnerAudioOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetInnerAudioOptionCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetInnerAudioOptionFailCallback; /** 是否与其他音频混播,设置为 true 之后,不会终止其他应用或微信内的音乐 */ mixWithOther?: boolean; /** (仅在 iOS 生效)是否遵循静音开关,设置为 false 之后,即使是在静音模式下,也能播放声音 */ obeyMuteSwitch?: boolean; /** 接口调用成功的回调函数 */ success?: SetInnerAudioOptionSuccessCallback; } interface SetKeepScreenOnOption { /** 是否保持屏幕常亮 */ keepScreenOn: boolean; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetKeepScreenOnCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetKeepScreenOnFailCallback; /** 接口调用成功的回调函数 */ success?: SetKeepScreenOnSuccessCallback; } interface SetNavigationBarColorOption { /** 动画效果 */ animation: AnimationOption; /** 背景颜色值,有效值为十六进制颜色 */ backgroundColor: string; /** 前景颜色值,包括按钮、标题、状态栏的颜色,仅支持 #ffffff 和 #000000 */ frontColor: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetNavigationBarColorCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetNavigationBarColorFailCallback; /** 接口调用成功的回调函数 */ success?: SetNavigationBarColorSuccessCallback; } interface SetNavigationBarTitleOption { /** 页面标题 */ title: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetNavigationBarTitleCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetNavigationBarTitleFailCallback; /** 接口调用成功的回调函数 */ success?: SetNavigationBarTitleSuccessCallback; } interface SetScreenBrightnessOption { /** 屏幕亮度值,范围 0 ~ 1。0 最暗,1 最亮 */ value: number; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetScreenBrightnessCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetScreenBrightnessFailCallback; /** 接口调用成功的回调函数 */ success?: SetScreenBrightnessSuccessCallback; } interface SetStorageOption { /** 需要存储的内容。只支持原生类型、Date、及能够通过`JSON.stringify`序列化的对象。 */ data: any; /** 本地缓存中指定的 key */ key: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetStorageCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetStorageFailCallback; /** 接口调用成功的回调函数 */ success?: SetStorageSuccessCallback; } interface SetTabBarBadgeOption { /** tabBar 的哪一项,从左边算起 */ index: number; /** 显示的文本,超过 4 个字符则显示成 ... */ text: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetTabBarBadgeCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetTabBarBadgeFailCallback; /** 接口调用成功的回调函数 */ success?: SetTabBarBadgeSuccessCallback; } interface SetTabBarItemOption { /** tabBar 的哪一项,从左边算起 */ index: number; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetTabBarItemCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetTabBarItemFailCallback; /** 图片路径,icon 大小限制为 40kb,建议尺寸为 81px * 81px,当 postion 为 top 时,此参数无效,不支持网络图片 */ iconPath?: string; /** 选中时的图片路径,icon 大小限制为 40kb,建议尺寸为 81px * 81px ,当 postion 为 top 时,此参数无效 */ selectedIconPath?: string; /** 接口调用成功的回调函数 */ success?: SetTabBarItemSuccessCallback; /** tab 上的按钮文字 */ text?: string; } interface SetTabBarStyleOption { /** tab 的背景色,HexColor */ backgroundColor: string; /** tabBar上边框的颜色, 仅支持 black/white */ borderStyle: string; /** tab 上的文字默认颜色,HexColor */ color: string; /** tab 上的文字选中时的颜色,HexColor */ selectedColor: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetTabBarStyleCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetTabBarStyleFailCallback; /** 接口调用成功的回调函数 */ success?: SetTabBarStyleSuccessCallback; } interface SetTopBarTextOption { /** 置顶栏文字 */ text: object; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetTopBarTextCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetTopBarTextFailCallback; /** 接口调用成功的回调函数 */ success?: SetTopBarTextSuccessCallback; } interface SetWifiListOption { /** 提供预设的 Wi-Fi 信息列表 */ wifiList: WifiData; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SetWifiListCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SetWifiListFailCallback; /** 接口调用成功的回调函数 */ success?: SetWifiListSuccessCallback; } interface ShowActionSheetOption { /** 按钮的文字数组,数组长度最大为 6 */ itemList: Array<string>; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ShowActionSheetCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ShowActionSheetFailCallback; /** 按钮的文字颜色 */ itemColor?: string; /** 接口调用成功的回调函数 */ success?: ShowActionSheetSuccessCallback; } interface ShowActionSheetSuccessCallbackResult { /** 用户点击的按钮序号,从上到下的顺序,从0开始 */ tapIndex: number; } interface ShowLoadingOption { /** 提示的内容 */ title: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ShowLoadingCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ShowLoadingFailCallback; /** 是否显示透明蒙层,防止触摸穿透 */ mask?: boolean; /** 接口调用成功的回调函数 */ success?: ShowLoadingSuccessCallback; } interface ShowModalOption { /** 提示的内容 */ content: string; /** 提示的标题 */ title: string; /** 取消按钮的文字颜色,必须是 16 进制格式的颜色字符串 */ cancelColor?: string; /** 取消按钮的文字,最多 4 个字符 */ cancelText?: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ShowModalCompleteCallback; /** 确认按钮的文字颜色,必须是 16 进制格式的颜色字符串 */ confirmColor?: string; /** 确认按钮的文字,最多 4 个字符 */ confirmText?: string; /** 接口调用失败的回调函数 */ fail?: ShowModalFailCallback; /** 是否显示取消按钮 */ showCancel?: boolean; /** 接口调用成功的回调函数 */ success?: ShowModalSuccessCallback; } interface ShowModalSuccessCallbackResult { /** 为 true 时,表示用户点击了取消(用于 Android 系统区分点击蒙层关闭还是点击取消按钮关闭) * * 最低基础库: `1.1.0` */ cancel: boolean; /** 为 true 时,表示用户点击了确定按钮 */ confirm: boolean; } interface ShowNavigationBarLoadingOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ShowNavigationBarLoadingCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ShowNavigationBarLoadingFailCallback; /** 接口调用成功的回调函数 */ success?: ShowNavigationBarLoadingSuccessCallback; } interface ShowShareMenuOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ShowShareMenuCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ShowShareMenuFailCallback; /** 接口调用成功的回调函数 */ success?: ShowShareMenuSuccessCallback; /** 是否使用带 shareTicket 的转发[详情]((转发#获取更多转发信息)) */ withShareTicket?: boolean; } interface ShowTabBarOption { /** 是否需要动画效果 */ animation?: boolean; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ShowTabBarCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ShowTabBarFailCallback; /** 接口调用成功的回调函数 */ success?: ShowTabBarSuccessCallback; } interface ShowTabBarRedDotOption { /** tabBar 的哪一项,从左边算起 */ index: number; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ShowTabBarRedDotCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ShowTabBarRedDotFailCallback; /** 接口调用成功的回调函数 */ success?: ShowTabBarRedDotSuccessCallback; } interface ShowToastOption { /** 提示的内容 */ title: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ShowToastCompleteCallback; /** 提示的延迟时间 */ duration?: number; /** 接口调用失败的回调函数 */ fail?: ShowToastFailCallback; /** 图标 * * 可选值: * - 'success': 显示成功图标,此时 title 文本最多显示 7 个汉字长度; * - 'loading': 显示加载图标,此时 title 文本最多显示 7 个汉字长度; * - 'none': 不显示图标,此时 title 文本最多可显示两行,{% version('1.9.0') %}及以上版本支持; */ icon?: 'success' | 'loading' | 'none'; /** 自定义图标的本地路径,image 的优先级高于 icon * * 最低基础库: `1.1.0` */ image?: string; /** 是否显示透明蒙层,防止触摸穿透 */ mask?: boolean; /** 接口调用成功的回调函数 */ success?: ShowToastSuccessCallback; } interface Size { /** 变化后的窗口高度,单位 px */ windowHeight: number; /** 变化后的窗口宽度,单位 px */ windowWidth: number; } interface SnapshotOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SnapshotCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SnapshotFailCallback; /** 接口调用成功的回调函数 */ success?: SnapshotSuccessCallback; } interface SocketTaskOnErrorCallbackResult { /** 错误信息 */ errMsg: string; } interface SocketTaskOnMessageCallbackResult { /** 服务器返回的消息 */ data: string | ArrayBuffer; } interface StartAccelerometerOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StartAccelerometerCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StartAccelerometerFailCallback; /** 监听加速度数据回调函数的执行频率 * * 可选值: * - 'game': 适用于更新游戏的回调频率,在 20ms/次 左右; * - 'ui': 适用于更新 UI 的回调频率,在 60ms/次 左右; * - 'normal': 普通的回调频率,在 200ms/次 左右; * * 最低基础库: `2.1.0` */ interval?: 'game' | 'ui' | 'normal'; /** 接口调用成功的回调函数 */ success?: StartAccelerometerSuccessCallback; } interface StartBeaconDiscoveryOption { /** iBeacon 设备广播的 uuid 列表 */ uuids: Array<string>; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StartBeaconDiscoveryCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StartBeaconDiscoveryFailCallback; /** 是否校验蓝牙开关,仅在 iOS 下有效 */ ignoreBluetoothAvailable?: boolean; /** 接口调用成功的回调函数 */ success?: StartBeaconDiscoverySuccessCallback; } interface StartBluetoothDevicesDiscoveryOption { /** 是否允许重复上报同一设备。如果允许重复上报,则 `wx.onBlueToothDeviceFound` 方法会多次上报同一设备,但是 RSSI 值会有不同。 */ allowDuplicatesKey?: boolean; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StartBluetoothDevicesDiscoveryCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StartBluetoothDevicesDiscoveryFailCallback; /** 上报设备的间隔。0 表示找到新设备立即上报,其他数值根据传入的间隔上报。 */ interval?: number; /** 要搜索但蓝牙设备主 service 的 uuid 列表。某些蓝牙设备会广播自己的主 service 的 uuid。如果设置此参数,则只搜索广播包有对应 uuid 的主服务的蓝牙设备。建议主要通过该参数过滤掉周边不需要处理的其他蓝牙设备。 */ services?: Array<string>; /** 接口调用成功的回调函数 */ success?: StartBluetoothDevicesDiscoverySuccessCallback; } interface StartCompassOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StartCompassCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StartCompassFailCallback; /** 接口调用成功的回调函数 */ success?: StartCompassSuccessCallback; } interface StartDeviceMotionListeningOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StartDeviceMotionListeningCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StartDeviceMotionListeningFailCallback; /** 监听设备方向的变化回调函数的执行频率 * * 可选值: * - 'game': 适用于更新游戏的回调频率,在 20ms/次 左右; * - 'ui': 适用于更新 UI 的回调频率,在 60ms/次 左右; * - 'normal': 普通的回调频率,在 200ms/次 左右; */ interval?: 'game' | 'ui' | 'normal'; /** 接口调用成功的回调函数 */ success?: StartDeviceMotionListeningSuccessCallback; } interface StartGyroscopeOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StartGyroscopeCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StartGyroscopeFailCallback; /** 监听陀螺仪数据回调函数的执行频率 * * 可选值: * - 'game': 适用于更新游戏的回调频率,在 20ms/次 左右; * - 'ui': 适用于更新 UI 的回调频率,在 60ms/次 左右; * - 'normal': 普通的回调频率,在 200ms/次 左右; */ interval?: 'game' | 'ui' | 'normal'; /** 接口调用成功的回调函数 */ success?: StartGyroscopeSuccessCallback; } interface StartHCEOption { /** 需要注册到系统的 AID 列表 */ aid_list: Array<string>; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StartHCECompleteCallback; /** 接口调用失败的回调函数 */ fail?: StartHCEFailCallback; /** 接口调用成功的回调函数 */ success?: StartHCESuccessCallback; } interface StartLocalServiceDiscoveryFailCallbackResult { /** 错误信息 * * 可选值: * - 'invalid param': serviceType 为空; * - 'scan task already exist': 在当前 startLocalServiceDiscovery 发起的搜索未停止的情况下,再次调用 startLocalServiceDiscovery; */ errMsg: string; } interface StartLocalServiceDiscoveryOption { /** 要搜索的服务类型 */ serviceType: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StartLocalServiceDiscoveryCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StartLocalServiceDiscoveryFailCallback; /** 接口调用成功的回调函数 */ success?: StartLocalServiceDiscoverySuccessCallback; } interface StartPullDownRefreshOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StartPullDownRefreshCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StartPullDownRefreshFailCallback; /** 接口调用成功的回调函数 */ success?: StartPullDownRefreshSuccessCallback; } interface StartRecordSuccessCallbackResult { /** 录音文件的临时路径 */ tempFilePath: string; } interface StartRecordTimeoutCallbackResult { /** 封面图片文件的临时路径 */ tempThumbPath: string; /** 视频的文件的临时路径 */ tempVideoPath: string; } interface StartSoterAuthenticationOption { /** 挑战因子。挑战因子为调用者为此次生物鉴权准备的用于签名的字符串关键识别信息,将作为 `resultJSON` 的一部分,供调用者识别本次请求。例如:如果场景为请求用户对某订单进行授权确认,则可以将订单号填入此参数。 */ challenge: string; /** 请求使用的可接受的生物认证方式 * * 可选值: * - 'fingerPrint': 指纹识别; * - 'facial': 人脸识别(暂未支持); * - 'speech': 声纹识别(暂未支持); */ requestAuthModes: ('fingerPrint' | 'facial' | 'speech')[]; /** 验证描述,即识别过程中显示在界面上的对话框提示内容 */ authContent?: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StartSoterAuthenticationCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StartSoterAuthenticationFailCallback; /** 接口调用成功的回调函数 */ success?: StartSoterAuthenticationSuccessCallback; } interface StartSoterAuthenticationSuccessCallbackResult { /** 生物认证方式 */ authMode: string; /** 错误码 */ errCode: number; /** 错误信息 */ errMsg: string; /** 在设备安全区域(TEE)内获得的本机安全信息(如TEE名称版本号等以及防重放参数)以及本次认证信息(仅Android支持,本次认证的指纹ID)。具体说明见下文 */ resultJSON: string; /** 用SOTER安全密钥对 `resultJSON` 的签名(SHA256 with RSA/PSS, saltlen=20) */ resultJSONSignature: string; } interface StartWifiOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StartWifiCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StartWifiFailCallback; /** 接口调用成功的回调函数 */ success?: StartWifiSuccessCallback; } interface StatFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail permission denied, open ${path}': 指定的 path 路径没有读权限; * - 'fail no such file or directory ${path}': 文件不存在; */ errMsg: string; } interface StatOption { /** 文件/目录路径 */ path: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StatCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StatFailCallback; /** 是否递归获取目录下的每个文件的 Stats 信息 * * 最低基础库: `2.3.0` */ recursive?: boolean; /** 接口调用成功的回调函数 */ success?: StatSuccessCallback; } interface StatSuccessCallbackResult { /** [Stats](https://developers.weixin.qq.com/miniprogram/dev/api/file/Stats.html)|Object * * 当 recursive 为 false 时,res.stats 是一个 Stats 对象。当 recursive 为 true 且 path 是一个目录的路径时,res.stats 是一个 Object,key 以 path 为根路径的相对路径,value 是该路径对应的 Stats 对象。 */ stats: Stats | object; } /** 描述文件状态的对象 */ interface Stats { /** 文件最近一次被存取或被执行的时间,UNIX 时间戳,对应 POSIX stat.st_atime */ lastAccessedTime: number; /** 文件最后一次被修改的时间,UNIX 时间戳,对应 POSIX stat.st_mtime */ lastModifiedTime: number; /** 文件的类型和存取的权限,对应 POSIX stat.st_mode */ mode: string; /** 文件大小,单位:B,对应 POSIX stat.st_size */ size: number; } interface StepOption { /** 动画延迟时间,单位 ms */ delay?: number; /** 动画持续时间,单位 ms */ duration?: number; /** 动画的效果 * * 可选值: * - 'linear': 动画从头到尾的速度是相同的; * - 'ease': 动画以低速开始,然后加快,在结束前变慢; * - 'ease-in': 动画以低速开始; * - 'ease-in-out': 动画以低速开始和结束; * - 'ease-out': 动画以低速结束; * - 'step-start': 动画第一帧就跳至结束状态直到结束; * - 'step-end': 动画一直保持开始状态,最后一帧跳到结束状态; */ timingFunction?: | 'linear' | 'ease' | 'ease-in' | 'ease-in-out' | 'ease-out' | 'step-start' | 'step-end'; transformOrigin?: string; } interface StopAccelerometerOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StopAccelerometerCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StopAccelerometerFailCallback; /** 接口调用成功的回调函数 */ success?: StopAccelerometerSuccessCallback; } interface StopBGMOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StopBGMCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StopBGMFailCallback; /** 接口调用成功的回调函数 */ success?: StopBGMSuccessCallback; } interface StopBackgroundAudioOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StopBackgroundAudioCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StopBackgroundAudioFailCallback; /** 接口调用成功的回调函数 */ success?: StopBackgroundAudioSuccessCallback; } interface StopBeaconDiscoveryOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StopBeaconDiscoveryCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StopBeaconDiscoveryFailCallback; /** 接口调用成功的回调函数 */ success?: StopBeaconDiscoverySuccessCallback; } interface StopBluetoothDevicesDiscoveryOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StopBluetoothDevicesDiscoveryCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StopBluetoothDevicesDiscoveryFailCallback; /** 接口调用成功的回调函数 */ success?: StopBluetoothDevicesDiscoverySuccessCallback; } interface StopCompassOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StopCompassCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StopCompassFailCallback; /** 接口调用成功的回调函数 */ success?: StopCompassSuccessCallback; } interface StopDeviceMotionListeningOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StopDeviceMotionListeningCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StopDeviceMotionListeningFailCallback; /** 接口调用成功的回调函数 */ success?: StopDeviceMotionListeningSuccessCallback; } interface StopGyroscopeOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StopGyroscopeCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StopGyroscopeFailCallback; /** 接口调用成功的回调函数 */ success?: StopGyroscopeSuccessCallback; } interface StopHCEOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StopHCECompleteCallback; /** 接口调用失败的回调函数 */ fail?: StopHCEFailCallback; /** 接口调用成功的回调函数 */ success?: StopHCESuccessCallback; } interface StopLocalServiceDiscoveryFailCallbackResult { /** 错误信息 * * 可选值: * - 'task not found': 在当前没有处在搜索服务中的情况下调用 stopLocalServiceDiscovery; */ errMsg: string; } interface StopLocalServiceDiscoveryOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StopLocalServiceDiscoveryCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StopLocalServiceDiscoveryFailCallback; /** 接口调用成功的回调函数 */ success?: StopLocalServiceDiscoverySuccessCallback; } interface StopPullDownRefreshOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StopPullDownRefreshCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StopPullDownRefreshFailCallback; /** 接口调用成功的回调函数 */ success?: StopPullDownRefreshSuccessCallback; } interface StopRecordOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StopRecordCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StopRecordFailCallback; /** 接口调用成功的回调函数 */ success?: StopRecordSuccessCallback; } interface StopRecordSuccessCallbackResult { /** 封面图片文件的临时路径 */ tempThumbPath: string; /** 视频的文件的临时路径 */ tempVideoPath: string; } interface StopVoiceOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StopVoiceCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StopVoiceFailCallback; /** 接口调用成功的回调函数 */ success?: StopVoiceSuccessCallback; } interface StopWifiOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: StopWifiCompleteCallback; /** 接口调用失败的回调函数 */ fail?: StopWifiFailCallback; /** 接口调用成功的回调函数 */ success?: StopWifiSuccessCallback; } interface SwitchCameraOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SwitchCameraCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SwitchCameraFailCallback; /** 接口调用成功的回调函数 */ success?: SwitchCameraSuccessCallback; } interface SwitchTabOption { /** 需要跳转的 tabBar 页面的路径(需在 app.json 的 [tabBar]((config#tabbar)) 字段定义的页面),路径后不能带参数。 */ url: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: SwitchTabCompleteCallback; /** 接口调用失败的回调函数 */ fail?: SwitchTabFailCallback; /** 接口调用成功的回调函数 */ success?: SwitchTabSuccessCallback; } interface TakePhotoOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: TakePhotoCompleteCallback; /** 接口调用失败的回调函数 */ fail?: TakePhotoFailCallback; /** 成像质量 * * 可选值: * - 'high': 高质量; * - 'normal': 普通质量; * - 'low': 低质量; */ quality?: 'high' | 'normal' | 'low'; /** 接口调用成功的回调函数 */ success?: TakePhotoSuccessCallback; } interface TakePhotoSuccessCallbackResult { /** 照片文件的临时路径 */ tempImagePath: string; } interface TextMetrics { /** 文本的宽度 */ width: number; } interface ToggleTorchOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ToggleTorchCompleteCallback; /** 接口调用失败的回调函数 */ fail?: ToggleTorchFailCallback; /** 接口调用成功的回调函数 */ success?: ToggleTorchSuccessCallback; } interface TranslateMarkerOption { /** 移动过程中是否自动旋转 marker */ autoRotate: boolean; /** 指定 marker 移动到的目标点 */ destination: DestinationOption; /** 指定 marker */ markerId: number; /** marker 的旋转角度 */ rotate: number; /** 动画结束回调函数 */ animationEnd?: Function; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: TranslateMarkerCompleteCallback; /** 动画持续时长,平移与旋转分别计算 */ duration?: number; /** 接口调用失败的回调函数 */ fail?: TranslateMarkerFailCallback; /** 接口调用成功的回调函数 */ success?: TranslateMarkerSuccessCallback; } interface UnlinkFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail permission denied, open ${path}': 指定的 path 路径没有读权限; * - 'fail no such file or directory ${path}': 文件不存在; * - 'fail operation not permitted, unlink ${filePath}': 传入的 filePath 是一个目录; */ errMsg: string; } interface UnlinkOption { /** 要删除的文件路径 */ filePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: UnlinkCompleteCallback; /** 接口调用失败的回调函数 */ fail?: UnlinkFailCallback; /** 接口调用成功的回调函数 */ success?: UnlinkSuccessCallback; } interface UnzipFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail permission denied, unzip ${zipFilePath} -> ${destPath}': 指定目标文件路径没有写权限; * - 'fail no such file or directory, unzip ${zipFilePath} -> "${destPath}': 源文件不存在,或目标文件路径的上层目录不存在; */ errMsg: string; } interface UnzipOption { /** 目标目录路径 */ targetPath: string; /** 源文件路径,只可以是 zip 压缩文件 */ zipFilePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: UnzipCompleteCallback; /** 接口调用失败的回调函数 */ fail?: UnzipFailCallback; /** 接口调用成功的回调函数 */ success?: UnzipSuccessCallback; } /** 参数列表 */ interface UpdatableMessageFrontEndParameter { /** 参数名 */ name: string; /** 参数值 */ value: string; } /** 动态消息的模板信息 * * 最低基础库: `2.4.0` */ interface UpdatableMessageFrontEndTemplateInfo { /** 参数列表 */ parameterList: UpdatableMessageFrontEndParameter; } interface UpdateShareMenuOption { /** 动态消息的 activityId。通过 [createActivityId]((createActivityId)) 接口获取 * * 最低基础库: `2.4.0` */ activityId?: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: UpdateShareMenuCompleteCallback; /** 接口调用失败的回调函数 */ fail?: UpdateShareMenuFailCallback; /** 是否是动态消息,详见[动态消息]((updatable-message)) * * 最低基础库: `2.4.0` */ isUpdatableMessage?: boolean; /** 接口调用成功的回调函数 */ success?: UpdateShareMenuSuccessCallback; /** 动态消息的模板信息 * * 最低基础库: `2.4.0` */ templateInfo?: UpdatableMessageFrontEndTemplateInfo; /** 是否使用带 shareTicket 的转发[详情]((转发#获取更多转发信息)) */ withShareTicket?: boolean; } interface UploadFileOption { /** 要上传文件资源的路径 */ filePath: string; /** 文件对应的 key,开发者在服务端可以通过这个 key 获取文件的二进制内容 */ name: string; /** 开发者服务器地址 */ url: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: UploadFileCompleteCallback; /** 接口调用失败的回调函数 */ fail?: UploadFileFailCallback; /** HTTP 请求中其他额外的 form data */ formData?: object; /** HTTP 请求 Header,Header 中不能设置 Referer */ header?: object; /** 接口调用成功的回调函数 */ success?: UploadFileSuccessCallback; } interface UploadFileSuccessCallbackResult { /** 开发者服务器返回的数据 */ data: string; /** 开发者服务器返回的 HTTP 状态码 */ statusCode: number; } interface UploadTaskOnHeadersReceivedCallbackResult { /** 开发者服务器返回的 HTTP Response Header */ header: object; } interface UploadTaskOnProgressUpdateCallbackResult { /** 上传进度百分比 */ progress: number; /** 预期需要上传的数据总长度,单位 Bytes */ totalBytesExpectedToSend: number; /** 已经上传的数据长度,单位 Bytes */ totalBytesSent: number; } /** 用户信息 */ interface UserInfo { /** 用户头像图片的 URL。URL 最后一个数值代表正方形头像大小(有 0、46、64、96、132 数值可选,0 代表 640x640 的正方形头像,46 表示 46x46 的正方形头像,剩余数值以此类推。默认132),用户没有头像时该项为空。若用户更换头像,原有头像 URL 将失效。 */ avatarUrl: string; /** 用户所在城市 */ city: string; /** 用户所在国家 */ country: string; /** 用户性别 * * 可选值: * - 0: 未知; * - 1: 男性; * - 2: 女性; */ gender: 0 | 1 | 2; /** 显示 country,province,city 所用的语言 * * 可选值: * - 'en': 英文; * - 'zh_CN': 简体中文; * - 'zh_TW': 繁体中文; */ language: 'en' | 'zh_CN' | 'zh_TW'; /** 用户昵称 */ nickName: string; /** 用户所在省份 */ province: string; } interface VibrateLongOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: VibrateLongCompleteCallback; /** 接口调用失败的回调函数 */ fail?: VibrateLongFailCallback; /** 接口调用成功的回调函数 */ success?: VibrateLongSuccessCallback; } interface VibrateShortOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: VibrateShortCompleteCallback; /** 接口调用失败的回调函数 */ fail?: VibrateShortFailCallback; /** 接口调用成功的回调函数 */ success?: VibrateShortSuccessCallback; } interface VideoContextRequestFullScreenOption { /** 设置全屏时视频的方向,不指定则根据宽高比自动判断。 * * 可选值: * - 0: 正常竖向; * - 90: 屏幕逆时针90度; * - -90: 屏幕顺时针90度; * * 最低基础库: `1.7.0` */ direction?: 0 | 90 | -90; } /** 提供预设的 Wi-Fi 信息列表 */ interface WifiData { /** Wi-Fi 的 BSSID */ BSSID?: string; /** Wi-Fi 的 SSID */ SSID?: string; /** Wi-Fi 设备密码 */ password?: string; } /** Wifi 信息 */ interface WifiInfo { /** Wi-Fi 的 BSSID */ BSSID: string; /** Wi-Fi 的 SSID */ SSID: string; /** Wi-Fi 是否安全 */ secure: boolean; /** Wi-Fi 信号强度 */ signalStrength: number; } interface WorkerOnMessageCallbackResult { /** 主线程/Worker 线程向当前线程发送的消息 */ message: object; } interface WriteBLECharacteristicValueOption { /** 蓝牙特征值的 uuid */ characteristicId: string; /** 蓝牙设备 id */ deviceId: string; /** 蓝牙特征值对应服务的 uuid */ serviceId: string; /** 蓝牙设备特征值对应的二进制值 */ value: ArrayBuffer; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: WriteBLECharacteristicValueCompleteCallback; /** 接口调用失败的回调函数 */ fail?: WriteBLECharacteristicValueFailCallback; /** 接口调用成功的回调函数 */ success?: WriteBLECharacteristicValueSuccessCallback; } interface WriteFileFailCallbackResult { /** 错误信息 * * 可选值: * - 'fail no such file or directory, open ${filePath}': 指定的 filePath 所在目录不存在; * - 'fail permission denied, open ${dirPath}': 指定的 filePath 路径没有写权限; */ errMsg: string; } interface WriteFileOption { /** 要写入的文本或二进制数据 */ data: string | ArrayBuffer; /** 要写入的文件路径 */ filePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: WriteFileCompleteCallback; /** 指定写入文件的字符编码 * * 可选值: * - 'ascii': ; * - 'base64': ; * - 'binary': ; * - 'hex': ; * - 'ucs2/ucs-2/utf16le/utf-16le': 以小端序读取; * - 'utf-8/utf8': ; * - 'latin1': ; */ encoding?: | 'ascii' | 'base64' | 'binary' | 'hex' | 'ucs2/ucs-2/utf16le/utf-16le' | 'utf-8/utf8' | 'latin1'; /** 接口调用失败的回调函数 */ fail?: WriteFileFailCallback; /** 接口调用成功的回调函数 */ success?: WriteFileSuccessCallback; } interface WxGetFileInfoOption { /** 本地文件路径 */ filePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: WxGetFileInfoCompleteCallback; /** 计算文件摘要的算法 * * 可选值: * - 'md5': md5 算法; * - 'sha1': sha1 算法; */ digestAlgorithm?: 'md5' | 'sha1'; /** 接口调用失败的回调函数 */ fail?: WxGetFileInfoFailCallback; /** 接口调用成功的回调函数 */ success?: WxGetFileInfoSuccessCallback; } interface WxGetFileInfoSuccessCallbackResult { /** 按照传入的 digestAlgorithm 计算得出的的文件摘要 */ digest: string; /** 文件大小,以字节为单位 */ size: number; } interface WxGetSavedFileListOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: WxGetSavedFileListCompleteCallback; /** 接口调用失败的回调函数 */ fail?: WxGetSavedFileListFailCallback; /** 接口调用成功的回调函数 */ success?: WxGetSavedFileListSuccessCallback; } interface WxGetSavedFileListSuccessCallbackResult { /** 文件数组,每一项是一个 FileItem */ fileList: WxGetSavedFileListSuccessCallbackResultFileItem; } /** 文件数组,每一项是一个 FileItem */ interface WxGetSavedFileListSuccessCallbackResultFileItem { /** 文件保存时的时间戳,从1970/01/01 08:00:00 到当前时间的秒数 */ createTime: number; /** 本地路径 */ filePath: string; /** 本地文件大小,以字节为单位 */ size: number; } interface WxRemoveSavedFileOption { /** 需要删除的文件路径 */ filePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: WxRemoveSavedFileCompleteCallback; /** 接口调用失败的回调函数 */ fail?: WxRemoveSavedFileFailCallback; /** 接口调用成功的回调函数 */ success?: WxRemoveSavedFileSuccessCallback; } interface WxSaveFileOption { /** 需要保存的文件的临时路径 */ tempFilePath: string; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: WxSaveFileCompleteCallback; /** 接口调用失败的回调函数 */ fail?: WxSaveFileFailCallback; /** 接口调用成功的回调函数 */ success?: WxSaveFileSuccessCallback; } interface WxSaveFileSuccessCallbackResult { /** 存储后的文件路径 */ savedFilePath: number; } interface WxStartRecordOption { /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: WxStartRecordCompleteCallback; /** 接口调用失败的回调函数 */ fail?: WxStartRecordFailCallback; /** 接口调用成功的回调函数 */ success?: WxStartRecordSuccessCallback; } interface Animation { /** [Array.<Object> Animation.export()](Animation.export.md) * * 导出动画队列。**export 方法每次调用后会清掉之前的动画操作。** */ export(): Array<Object>; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.backgroundColor(string value)](Animation.backgroundColor.md) * * 设置背景色 */ backgroundColor( /** 颜色值 */ value: string, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.bottom(number|string value)](Animation.bottom.md) * * 设置 bottom 值 */ bottom( /** 长度值,如果传入 number 则默认使用 px,可传入其他自定义单位的长度值 */ value: number | string, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.height(number|string value)](Animation.height.md) * * 设置高度 */ height( /** 长度值,如果传入 number 则默认使用 px,可传入其他自定义单位的长度值 */ value: number | string, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.left(number|string value)](Animation.left.md) * * 设置 left 值 */ left( /** 长度值,如果传入 number 则默认使用 px,可传入其他自定义单位的长度值 */ value: number | string, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.matrix()](Animation.matrix.md) * * 同 [transform-function matrix](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix) */ matrix(): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.matrix3d()](Animation.matrix3d.md) * * 同 [transform-function matrix3d](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix3d) */ matrix3d(): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.opacity(number value)](Animation.opacity.md) * * 设置透明度 */ opacity( /** 透明度,范围 0-1 */ value: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.right(number|string value)](Animation.right.md) * * 设置 right 值 */ right( /** 长度值,如果传入 number 则默认使用 px,可传入其他自定义单位的长度值 */ value: number | string, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.rotate(number angle)](Animation.rotate.md) * * 从原点顺时针旋转一个角度 */ rotate( /** 旋转的角度。范围 [-180, 180] */ angle: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.rotate3d(number x, number y, number z, number angle)](Animation.rotate3d.md) * * 从 X 轴顺时针旋转一个角度 */ rotate3d( /** 旋转轴的 x 坐标 */ x: number, /** 旋转轴的 y 坐标 */ y: number, /** 旋转轴的 z 坐标 */ z: number, /** 旋转的角度。范围 [-180, 180] */ angle: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.rotateX(number angle)](Animation.rotateX.md) * * 从 X 轴顺时针旋转一个角度 */ rotateX( /** 旋转的角度。范围 [-180, 180] */ angle: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.rotateY(number angle)](Animation.rotateY.md) * * 从 Y 轴顺时针旋转一个角度 */ rotateY( /** 旋转的角度。范围 [-180, 180] */ angle: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.rotateZ(number angle)](Animation.rotateZ.md) * * 从 Z 轴顺时针旋转一个角度 */ rotateZ( /** 旋转的角度。范围 [-180, 180] */ angle: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.scale(number sx, number sy)](Animation.scale.md) * * 缩放 */ scale( /** 当仅有 sx 参数时,表示在 X 轴、Y 轴同时缩放sx倍数 */ sx: number, /** 在 Y 轴缩放 sy 倍数 */ sy?: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.scale3d(number sx, number sy, number sz)](Animation.scale3d.md) * * 缩放 */ scale3d( /** x 轴的缩放倍数 */ sx: number, /** y 轴的缩放倍数 */ sy: number, /** z 轴的缩放倍数 */ sz: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.scaleX(number scale)](Animation.scaleX.md) * * 缩放 X 轴 */ scaleX( /** X 轴的缩放倍数 */ scale: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.scaleY(number scale)](Animation.scaleY.md) * * 缩放 Y 轴 */ scaleY( /** Y 轴的缩放倍数 */ scale: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.scaleZ(number scale)](Animation.scaleZ.md) * * 缩放 Z 轴 */ scaleZ( /** Z 轴的缩放倍数 */ scale: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.skew(number ax, number ay)](Animation.skew.md) * * 对 X、Y 轴坐标进行倾斜 */ skew( /** 对 X 轴坐标倾斜的角度,范围 [-180, 180] */ ax: number, /** 对 Y 轴坐标倾斜的角度,范围 [-180, 180] */ ay: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.skewX(number angle)](Animation.skewX.md) * * 对 X 轴坐标进行倾斜 */ skewX( /** 倾斜的角度,范围 [-180, 180] */ angle: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.skewY(number angle)](Animation.skewY.md) * * 对 Y 轴坐标进行倾斜 */ skewY( /** 倾斜的角度,范围 [-180, 180] */ angle: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.step(Object object)](Animation.step.md) * * 表示一组动画完成。可以在一组动画中调用任意多个动画方法,一组动画中的所有动画会同时开始,一组动画完成后才会进行下一组动画。 */ step(option?: StepOption): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.top(number|string value)](Animation.top.md) * * 设置 top 值 */ top( /** 长度值,如果传入 number 则默认使用 px,可传入其他自定义单位的长度值 */ value: number | string, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.translate(number tx, number ty)](Animation.translate.md) * * 平移变换 */ translate( /** 当仅有该参数时表示在 X 轴偏移 tx,单位 px */ tx?: number, /** 在 Y 轴平移的距离,单位为 px */ ty?: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.translate3d(number tx, number ty, number tz)](Animation.translate3d.md) * * 对 xyz 坐标进行平移变换 */ translate3d( /** 在 X 轴平移的距离,单位为 px */ tx?: number, /** 在 Y 轴平移的距离,单位为 px */ ty?: number, /** 在 Z 轴平移的距离,单位为 px */ tz?: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.translateX(number translation)](Animation.translateX.md) * * 对 X 轴平移 */ translateX( /** 在 X 轴平移的距离,单位为 px */ translation: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.translateY(number translation)](Animation.translateY.md) * * 对 Y 轴平移 */ translateY( /** 在 Y 轴平移的距离,单位为 px */ translation: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.translateZ(number translation)](Animation.translateZ.md) * * 对 Z 轴平移 */ translateZ( /** 在 Z 轴平移的距离,单位为 px */ translation: number, ): Animation; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) Animation.width(number|string value)](Animation.width.md) * * 设置宽度 */ width( /** 长度值,如果传入 number 则默认使用 px,可传入其他自定义单位的长度值 */ value: number | string, ): Animation; } interface AudioContext { /** [AudioContext.pause()](AudioContext.pause.md) * * 暂停音频。 */ pause(): void; /** [AudioContext.play()](AudioContext.play.md) * * 播放音频。 */ play(): void; /** [AudioContext.seek(number position)](AudioContext.seek.md) * * 跳转到指定位置。 */ seek( /** 跳转位置,单位 s */ position: number, ): void; /** [AudioContext.setSrc(string src)](AudioContext.setSrc.md) * * 设置音频地址 */ setSrc( /** 音频地址 */ src: string, ): void; } interface BackgroundAudioManager { /** [BackgroundAudioManager.onCanplay(function callback)](BackgroundAudioManager.onCanplay.md) * * 监听背景音频进入可播放状态事件。但不保证后面可以流畅播放 */ onCanplay( /** 背景音频进入可播放状态事件的回调函数 */ callback: BackgroundAudioManagerOnCanplayCallback, ): void; /** [BackgroundAudioManager.onEnded(function callback)](BackgroundAudioManager.onEnded.md) * * 监听背景音频自然播放结束事件 */ onEnded( /** 背景音频自然播放结束事件的回调函数 */ callback: BackgroundAudioManagerOnEndedCallback, ): void; /** [BackgroundAudioManager.onError(function callback)](BackgroundAudioManager.onError.md) * * 监听背景音频播放错误事件 */ onError( /** 背景音频播放错误事件的回调函数 */ callback: BackgroundAudioManagerOnErrorCallback, ): void; /** [BackgroundAudioManager.onNext(function callback)](BackgroundAudioManager.onNext.md) * * 监听用户在系统音乐播放面板点击下一曲事件(仅iOS) */ onNext( /** 用户在系统音乐播放面板点击下一曲事件的回调函数 */ callback: OnNextCallback, ): void; /** [BackgroundAudioManager.onPause(function callback)](BackgroundAudioManager.onPause.md) * * 监听背景音频暂停事件 */ onPause( /** 背景音频暂停事件的回调函数 */ callback: BackgroundAudioManagerOnPauseCallback, ): void; /** [BackgroundAudioManager.onPlay(function callback)](BackgroundAudioManager.onPlay.md) * * 监听背景音频播放事件 */ onPlay( /** 背景音频播放事件的回调函数 */ callback: BackgroundAudioManagerOnPlayCallback, ): void; /** [BackgroundAudioManager.onPrev(function callback)](BackgroundAudioManager.onPrev.md) * * 监听用户在系统音乐播放面板点击上一曲事件(仅iOS) */ onPrev( /** 用户在系统音乐播放面板点击上一曲事件的回调函数 */ callback: OnPrevCallback, ): void; /** [BackgroundAudioManager.onSeeked(function callback)](BackgroundAudioManager.onSeeked.md) * * 监听背景音频完成跳转操作事件 */ onSeeked( /** 背景音频完成跳转操作事件的回调函数 */ callback: BackgroundAudioManagerOnSeekedCallback, ): void; /** [BackgroundAudioManager.onSeeking(function callback)](BackgroundAudioManager.onSeeking.md) * * 监听背景音频开始跳转操作事件 */ onSeeking( /** 背景音频开始跳转操作事件的回调函数 */ callback: BackgroundAudioManagerOnSeekingCallback, ): void; /** [BackgroundAudioManager.onStop(function callback)](BackgroundAudioManager.onStop.md) * * 监听背景音频停止事件 */ onStop( /** 背景音频停止事件的回调函数 */ callback: BackgroundAudioManagerOnStopCallback, ): void; /** [BackgroundAudioManager.onTimeUpdate(function callback)](BackgroundAudioManager.onTimeUpdate.md) * * 监听背景音频播放进度更新事件 */ onTimeUpdate( /** 背景音频播放进度更新事件的回调函数 */ callback: BackgroundAudioManagerOnTimeUpdateCallback, ): void; /** [BackgroundAudioManager.onWaiting(function callback)](BackgroundAudioManager.onWaiting.md) * * 监听音频加载中事件。当音频因为数据不足,需要停下来加载时会触发 */ onWaiting( /** 音频加载中事件的回调函数 */ callback: BackgroundAudioManagerOnWaitingCallback, ): void; /** [BackgroundAudioManager.pause()](BackgroundAudioManager.pause.md) * * 暂停音乐 */ pause(): void; /** [BackgroundAudioManager.play()](BackgroundAudioManager.play.md) * * 播放音乐 */ play(): void; /** [BackgroundAudioManager.seek(number currentTime)](BackgroundAudioManager.seek.md) * * 跳转到指定位置 */ seek( /** 跳转的位置,单位 s。精确到小数点后 3 位,即支持 ms 级别精确度 */ currentTime: number, ): void; /** [BackgroundAudioManager.stop()](BackgroundAudioManager.stop.md) * * 停止音乐 */ stop(): void; } interface CameraContext { /** [CameraContext.startRecord(Object object)](CameraContext.startRecord.md) * * 开始录像 */ startRecord(option: CameraContextStartRecordOption): void; /** [CameraContext.stopRecord(Object object)](CameraContext.stopRecord.md) * * 结束录像 */ stopRecord(option?: StopRecordOption): void; /** [CameraContext.takePhoto(Object object)](CameraContext.takePhoto.md) * * 拍摄照片 */ takePhoto(option: TakePhotoOption): void; } interface CanvasContext { /** [CanvasContext.arc(number x, number y, number r, number sAngle, number eAngle, number counterclockwise)](CanvasContext.arc.md) * * 创建一条弧线。 * * - 创建一个圆可以指定起始弧度为 0,终止弧度为 2 * Math.PI。 * - 用 `stroke` 或者 `fill` 方法来在 `canvas` 中画弧线。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') // Draw coordinates ctx.arc(100, 75, 50, 0, 2 * Math.PI) ctx.setFillStyle('#EEEEEE') ctx.fill() ctx.beginPath() ctx.moveTo(40, 75) ctx.lineTo(160, 75) ctx.moveTo(100, 15) ctx.lineTo(100, 135) ctx.setStrokeStyle('#AAAAAA') ctx.stroke() ctx.setFontSize(12) ctx.setFillStyle('black') ctx.fillText('0', 165, 78) ctx.fillText('0.5*PI', 83, 145) ctx.fillText('1*PI', 15, 78) ctx.fillText('1.5*PI', 83, 10) // Draw points ctx.beginPath() ctx.arc(100, 75, 2, 0, 2 * Math.PI) ctx.setFillStyle('lightgreen') ctx.fill() ctx.beginPath() ctx.arc(100, 25, 2, 0, 2 * Math.PI) ctx.setFillStyle('blue') ctx.fill() ctx.beginPath() ctx.arc(150, 75, 2, 0, 2 * Math.PI) ctx.setFillStyle('red') ctx.fill() // Draw arc ctx.beginPath() ctx.arc(100, 75, 50, 0, 1.5 * Math.PI) ctx.setStrokeStyle('#333333') ctx.stroke() ctx.draw() ``` * * ![]((canvas/arc.png)) * * 针对 arc(100, 75, 50, 0, 1.5 * Math.PI)的三个关键坐标如下: * * - 绿色: 圆心 (100, 75) * - 红色: 起始弧度 (0) * - 蓝色: 终止弧度 (1.5 * Math.PI) */ arc( /** 圆心的 x 坐标 */ x: number, /** 圆心的 y 坐标 */ y: number, /** 圆的半径 */ r: number, /** 起始弧度,单位弧度(在3点钟方向) */ sAngle: number, /** 终止弧度 */ eAngle: number, /** 弧度的方向是否是逆时针 */ counterclockwise?: number, ): void; /** [CanvasContext.arcTo(number x1, number y1, number x2, number y2, number radius)](CanvasContext.arcTo.md) * * 根据控制点和半径绘制圆弧路径。 * * 最低基础库: `1.9.90` */ arcTo( /** 第一个控制点的 x 轴坐标 */ x1: number, /** 第一个控制点的 y 轴坐标 */ y1: number, /** 第二个控制点的 x 轴坐标 */ x2: number, /** 第二个控制点的 y 轴坐标 */ y2: number, /** 圆弧的半径 */ radius: number, ): void; /** [CanvasContext.beginPath()](CanvasContext.beginPath.md) * * 开始创建一个路径。需要调用 `fill` 或者 `stroke` 才会使用路径进行填充或描边 * * - 在最开始的时候相当于调用了一次 `beginPath`。 * - 同一个路径内的多次 `setFillStyle`、`setStrokeStyle`、`setLineWidth`等设置,以最后一次设置为准。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') // begin path ctx.rect(10, 10, 100, 30) ctx.setFillStyle('yellow') ctx.fill() // begin another path ctx.beginPath() ctx.rect(10, 40, 100, 30) // only fill this rect, not in current path ctx.setFillStyle('blue') ctx.fillRect(10, 70, 100, 30) ctx.rect(10, 100, 100, 30) // it will fill current path ctx.setFillStyle('red') ctx.fill() ctx.draw() ``` * * ![]((canvas/fill-path.png)) */ beginPath(): void; /** [CanvasContext.bezierCurveTo()](CanvasContext.bezierCurveTo.md) * * 创建三次方贝塞尔曲线路径。曲线的起始点为路径中前一个点。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') // Draw points ctx.beginPath() ctx.arc(20, 20, 2, 0, 2 * Math.PI) ctx.setFillStyle('red') ctx.fill() ctx.beginPath() ctx.arc(200, 20, 2, 0, 2 * Math.PI) ctx.setFillStyle('lightgreen') ctx.fill() ctx.beginPath() ctx.arc(20, 100, 2, 0, 2 * Math.PI) ctx.arc(200, 100, 2, 0, 2 * Math.PI) ctx.setFillStyle('blue') ctx.fill() ctx.setFillStyle('black') ctx.setFontSize(12) // Draw guides ctx.beginPath() ctx.moveTo(20, 20) ctx.lineTo(20, 100) ctx.lineTo(150, 75) ctx.moveTo(200, 20) ctx.lineTo(200, 100) ctx.lineTo(70, 75) ctx.setStrokeStyle('#AAAAAA') ctx.stroke() // Draw quadratic curve ctx.beginPath() ctx.moveTo(20, 20) ctx.bezierCurveTo(20, 100, 200, 100, 200, 20) ctx.setStrokeStyle('black') ctx.stroke() ctx.draw() ``` * * ![]((canvas/bezier-curve.png)) * * 针对 moveTo(20, 20) bezierCurveTo(20, 100, 200, 100, 200, 20) 的三个关键坐标如下: * * - 红色:起始点(20, 20) * - 蓝色:两个控制点(20, 100) (200, 100) * - 绿色:终止点(200, 20) */ bezierCurveTo(): void; /** [CanvasContext.clearRect(number x, number y, number width, number height)](CanvasContext.clearRect.md) * * 清除画布上在该矩形区域内的内容 * * **示例代码** * * * clearRect 并非画一个白色的矩形在地址区域,而是清空,为了有直观感受,对 canvas 加了一层背景色。 * ```html * <canvas canvas-id="myCanvas" style="border: 1px solid; background: #123456;"/> * ``` * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.setFillStyle('red') ctx.fillRect(0, 0, 150, 200) ctx.setFillStyle('blue') ctx.fillRect(150, 0, 150, 200) ctx.clearRect(10, 10, 150, 75) ctx.draw() ``` * ![]((canvas/clear-rect.png)) */ clearRect( /** 矩形路径左上角的横坐标 */ x: number, /** 矩形路径左上角的横坐标 */ y: number, /** 矩形路径的宽度 */ width: number, /** 矩形路径的高度 */ height: number, ): void; /** [CanvasContext.clip()](CanvasContext.clip.md) * * 从原始画布中剪切任意形状和尺寸。一旦剪切了某个区域,则所有之后的绘图都会被限制在被剪切的区域内(不能访问画布上的其他区域)。可以在使用 `clip` 方法前通过使用 `save` 方法对当前画布区域进行保存,并在以后的任意时间通过`restore`方法对其进行恢复。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') wx.downloadFile({ url: 'http://is5.mzstatic.com/image/thumb/Purple128/v4/75/3b/90/753b907c-b7fb-5877-215a-759bd73691a4/source/50x50bb.jpg', success: function(res) { ctx.save() ctx.beginPath() ctx.arc(50, 50, 25, 0, 2*Math.PI) ctx.clip() ctx.drawImage(res.tempFilePath, 25, 25) ctx.restore() ctx.draw() } }) ``` * ![]((canvas/clip.png)) * * 最低基础库: `1.6.0` */ clip(): void; /** [CanvasContext.closePath()](CanvasContext.closePath.md) * * 关闭一个路径。会连接起点和终点。如果关闭路径后没有调用 `fill` 或者 `stroke` 并开启了新的路径,那之前的路径将不会被渲染。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.moveTo(10, 10) ctx.lineTo(100, 10) ctx.lineTo(100, 100) ctx.closePath() ctx.stroke() ctx.draw() ``` * ![]((canvas/close-line.png)) * * ```javascript const ctx = wx.createCanvasContext('myCanvas') // begin path ctx.rect(10, 10, 100, 30) ctx.closePath() // begin another path ctx.beginPath() ctx.rect(10, 40, 100, 30) // only fill this rect, not in current path ctx.setFillStyle('blue') ctx.fillRect(10, 70, 100, 30) ctx.rect(10, 100, 100, 30) // it will fill current path ctx.setFillStyle('red') ctx.fill() ctx.draw() ``` * * ![]((canvas/close-path.png)) */ closePath(): void; /** [CanvasContext.createPattern(string image, string repetition)](CanvasContext.createPattern.md) * * 对指定的图像创建模式的方法,可在指定的方向上重复元图像 * * 最低基础库: `1.9.90` */ createPattern( /** 重复的图像源,仅支持包内路径和临时路径 */ image: string, /** 如何重复图像 */ repetition: string, ): void; /** [CanvasContext.draw(boolean reserve, function callback)](CanvasContext.draw.md) * * 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中。 * * **示例代码** * * * 第二次 draw() reserve 为 true。所以保留了上一次的绘制结果,在上下文设置的 fillStyle 'red' 也变成了默认的 'black'。 * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.setFillStyle('red') ctx.fillRect(10, 10, 150, 100) ctx.draw() ctx.fillRect(50, 50, 150, 100) ctx.draw(true) ``` * ![]((canvas/reserve.png)) * * **示例代码** * * * 第二次 draw() reserve 为 false。所以没有保留了上一次的绘制结果和在上下文设置的 fillStyle 'red'。 * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.setFillStyle('red') ctx.fillRect(10, 10, 150, 100) ctx.draw() ctx.fillRect(50, 50, 150, 100) ctx.draw() ``` * ![]((canvas/un-reserve.png)) */ draw( /** 本次绘制是否接着上一次绘制。即 reserve 参数为 false,则在本次调用绘制之前 native 层会先清空画布再继续绘制;若 reserve 参数为 true,则保留当前画布上的内容,本次调用 drawCanvas 绘制的内容覆盖在上面,默认 false。 */ reserve: boolean, /** 绘制完成后执行的回调函数 */ callback: Function, ): void; /** [CanvasContext.draw(boolean reserve, function callback)](CanvasContext.draw.md) * * 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中。 * * **示例代码** * * * 第二次 draw() reserve 为 true。所以保留了上一次的绘制结果,在上下文设置的 fillStyle 'red' 也变成了默认的 'black'。 * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.setFillStyle('red') ctx.fillRect(10, 10, 150, 100) ctx.draw() ctx.fillRect(50, 50, 150, 100) ctx.draw(true) ``` * ![]((canvas/reserve.png)) * * **示例代码** * * * 第二次 draw() reserve 为 false。所以没有保留了上一次的绘制结果和在上下文设置的 fillStyle 'red'。 * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.setFillStyle('red') ctx.fillRect(10, 10, 150, 100) ctx.draw() ctx.fillRect(50, 50, 150, 100) ctx.draw() ``` * ![]((canvas/un-reserve.png)) */ draw( /** 绘制完成后执行的回调函数 */ callback: Function, ): void; /** [CanvasContext.drawImage(string imageResource, number dx, number dy, number dWidth, number dHeight, number sx, number sy, number sWidth, number sHeight)](CanvasContext.drawImage.md) * * 绘制图像到画布 * * **示例代码** * * * * 有三个版本的写法: * * - drawImage(dx, dy) * - drawImage(dx, dy, dWidth, dHeight) * - drawImage(sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) 从 1.9.0 起支持 * * ```javascript const ctx = wx.createCanvasContext('myCanvas') wx.chooseImage({ success: function(res){ ctx.drawImage(res.tempFilePaths[0], 0, 0, 150, 100) ctx.draw() } }) ``` * ![]((canvas/draw-image.png)) */ drawImage( /** 所要绘制的图片资源 */ imageResource: string, /** 图像的左上角在目标 canvas 上 x 轴的位置 */ dx: number, /** 图像的左上角在目标 canvas 上 y 轴的位置 */ dy: number, /** 在目标画布上绘制图像的宽度,允许对绘制的图像进行缩放 */ dWidth: number, /** 在目标画布上绘制图像的高度,允许对绘制的图像进行缩放 */ dHeight: number, /** 源图像的矩形选择框的左上角 x 坐标 */ sx: number, /** 源图像的矩形选择框的左上角 y 坐标 */ sy: number, /** 源图像的矩形选择框的宽度 */ sWidth: number, /** 源图像的矩形选择框的高度 */ sHeight: number, ): void; /** [CanvasContext.fill()](CanvasContext.fill.md) * * 对当前路径中的内容进行填充。默认的填充色为黑色。 * * **示例代码** * * * * 如果当前路径没有闭合,fill() 方法会将起点和终点进行连接,然后填充。 * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.moveTo(10, 10) ctx.lineTo(100, 10) ctx.lineTo(100, 100) ctx.fill() ctx.draw() ``` * * fill() 填充的的路径是从 beginPath() 开始计算,但是不会将 fillRect() 包含进去。 * * ![]((canvas/fill-line.png)) * * ```javascript const ctx = wx.createCanvasContext('myCanvas') // begin path ctx.rect(10, 10, 100, 30) ctx.setFillStyle('yellow') ctx.fill() // begin another path ctx.beginPath() ctx.rect(10, 40, 100, 30) // only fill this rect, not in current path ctx.setFillStyle('blue') ctx.fillRect(10, 70, 100, 30) ctx.rect(10, 100, 100, 30) // it will fill current path ctx.setFillStyle('red') ctx.fill() ctx.draw() ``` * * ![]((canvas/fill-path.png)) */ fill(): void; /** [CanvasContext.fillRect(number x, number y, number width, number height)](CanvasContext.fillRect.md) * * 填充一个矩形。用 [`setFillStyle`](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.setFillStyle.html) 设置矩形的填充色,如果没设置默认是黑色。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.setFillStyle('red') ctx.fillRect(10, 10, 150, 75) ctx.draw() ``` * ![]((canvas/fill-rect.png)) */ fillRect( /** 矩形路径左上角的横坐标 */ x: number, /** 矩形路径左上角的横坐标 */ y: number, /** 矩形路径的宽度 */ width: number, /** 矩形路径的高度 */ height: number, ): void; /** [CanvasContext.fillText(string text, number x, number y, number maxWidth)](CanvasContext.fillText.md) * * 在画布上绘制被填充的文本 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.setFontSize(20) ctx.fillText('Hello', 20, 20) ctx.fillText('MINA', 100, 100) ctx.draw() ``` * ![]((canvas/text.png)) */ fillText( /** 在画布上输出的文本 */ text: string, /** 绘制文本的左上角 x 坐标位置 */ x: number, /** 绘制文本的左上角 y 坐标位置 */ y: number, /** 需要绘制的最大宽度,可选 */ maxWidth?: number, ): void; /** [CanvasContext.lineTo(number x, number y)](CanvasContext.lineTo.md) * * 增加一个新点,然后创建一条从上次指定点到目标点的线。用 `stroke` 方法来画线条 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.moveTo(10, 10) ctx.rect(10, 10, 100, 50) ctx.lineTo(110, 60) ctx.stroke() ctx.draw() ``` * ![]((canvas/line-to.png)) */ lineTo( /** 目标位置的 x 坐标 */ x: number, /** 目标位置的 y 坐标 */ y: number, ): void; /** [CanvasContext.moveTo(number x, number y)](CanvasContext.moveTo.md) * * 把路径移动到画布中的指定点,不创建线条。用 `stroke` 方法来画线条 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.moveTo(10, 10) ctx.lineTo(100, 10) ctx.moveTo(10, 50) ctx.lineTo(100, 50) ctx.stroke() ctx.draw() ``` * ![]((canvas/move-to.png)) */ moveTo( /** 目标位置的 x 坐标 */ x: number, /** 目标位置的 y 坐标 */ y: number, ): void; /** [CanvasContext.quadraticCurveTo(number cpx, number cpy, number x, number y)](CanvasContext.quadraticCurveTo.md) * * 创建二次贝塞尔曲线路径。曲线的起始点为路径中前一个点。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') // Draw points ctx.beginPath() ctx.arc(20, 20, 2, 0, 2 * Math.PI) ctx.setFillStyle('red') ctx.fill() ctx.beginPath() ctx.arc(200, 20, 2, 0, 2 * Math.PI) ctx.setFillStyle('lightgreen') ctx.fill() ctx.beginPath() ctx.arc(20, 100, 2, 0, 2 * Math.PI) ctx.setFillStyle('blue') ctx.fill() ctx.setFillStyle('black') ctx.setFontSize(12) // Draw guides ctx.beginPath() ctx.moveTo(20, 20) ctx.lineTo(20, 100) ctx.lineTo(200, 20) ctx.setStrokeStyle('#AAAAAA') ctx.stroke() // Draw quadratic curve ctx.beginPath() ctx.moveTo(20, 20) ctx.quadraticCurveTo(20, 100, 200, 20) ctx.setStrokeStyle('black') ctx.stroke() ctx.draw() ``` * * ![]((canvas/quadratic-curve-to.png)) * * 针对 moveTo(20, 20) quadraticCurveTo(20, 100, 200, 20) 的三个关键坐标如下: * * - 红色:起始点(20, 20) * - 蓝色:控制点(20, 100) * - 绿色:终止点(200, 20) */ quadraticCurveTo( /** 贝塞尔控制点的 x 坐标 */ cpx: number, /** 贝塞尔控制点的 y 坐标 */ cpy: number, /** 结束点的 x 坐标 */ x: number, /** 结束点的 y 坐标 */ y: number, ): void; /** [CanvasContext.rect(number x, number y, number width, number height)](CanvasContext.rect.md) * * 创建一个矩形路径。需要用 [`fill`](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.fill.html) 或者 [`stroke`](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.stroke.html) 方法将矩形真正的画到 `canvas` 中 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.rect(10, 10, 150, 75) ctx.setFillStyle('red') ctx.fill() ctx.draw() ``` * ![]((canvas/fill-rect.png)) */ rect( /** 矩形路径左上角的横坐标 */ x: number, /** 矩形路径左上角的横坐标 */ y: number, /** 矩形路径的宽度 */ width: number, /** 矩形路径的高度 */ height: number, ): void; /** [CanvasContext.restore()](CanvasContext.restore.md) * * 恢复之前保存的绘图上下文。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') // save the default fill style ctx.save() ctx.setFillStyle('red') ctx.fillRect(10, 10, 150, 100) // restore to the previous saved state ctx.restore() ctx.fillRect(50, 50, 150, 100) ctx.draw() ``` * ![]((canvas/save-restore.png)) */ restore(): void; /** [CanvasContext.rotate(number rotate)](CanvasContext.rotate.md) * * 以原点为中心顺时针旋转当前坐标轴。多次调用旋转的角度会叠加。原点可以用 `translate` 方法修改。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.strokeRect(100, 10, 150, 100) ctx.rotate(20 * Math.PI / 180) ctx.strokeRect(100, 10, 150, 100) ctx.rotate(20 * Math.PI / 180) ctx.strokeRect(100, 10, 150, 100) ctx.draw() ``` * ![]((canvas/rotate.png)) */ rotate( /** 旋转角度,以弧度计 degrees * Math.PI/180;degrees 范围为 0-360 */ rotate: number, ): void; /** [CanvasContext.save()](CanvasContext.save.md) * * 保存绘图上下文。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') // save the default fill style ctx.save() ctx.setFillStyle('red') ctx.fillRect(10, 10, 150, 100) // restore to the previous saved state ctx.restore() ctx.fillRect(50, 50, 150, 100) ctx.draw() ``` * ![]((canvas/save-restore.png)) */ save(): void; /** [CanvasContext.scale(number scaleWidth, number scaleHeight)](CanvasContext.scale.md) * * 在调用后,之后创建的路径其横纵坐标会被缩放。多次调用倍数会相乘。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.strokeRect(10, 10, 25, 15) ctx.scale(2, 2) ctx.strokeRect(10, 10, 25, 15) ctx.scale(2, 2) ctx.strokeRect(10, 10, 25, 15) ctx.draw() ``` * ![]((canvas/scale.png)) */ scale( /** 横坐标缩放的倍数 (1 = 100%,0.5 = 50%,2 = 200%) */ scaleWidth: number, /** 纵坐标轴缩放的倍数 (1 = 100%,0.5 = 50%,2 = 200%) */ scaleHeight: number, ): void; /** [CanvasContext.setFillStyle([Color](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/Color.html) color)](CanvasContext.setFillStyle.md) * * 设置填充色。 * * **代码示例** * * * ```js const ctx = wx.createCanvasContext('myCanvas') ctx.setFillStyle('red') ctx.fillRect(10, 10, 150, 75) ctx.draw() ``` * ![]((canvas/fill-rect.png)) */ setFillStyle( /** [Color](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/Color.html) * * 填充的颜色,默认颜色为 black。 */ color: Color, ): void; /** [CanvasContext.setFontSize(number fontSize)](CanvasContext.setFontSize.md) * * 设置字体的字号 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.setFontSize(20) ctx.fillText('20', 20, 20) ctx.setFontSize(30) ctx.fillText('30', 40, 40) ctx.setFontSize(40) ctx.fillText('40', 60, 60) ctx.setFontSize(50) ctx.fillText('50', 90, 90) ctx.draw() ``` * ![]((canvas/font-size.png)) */ setFontSize( /** 字体的字号 */ fontSize: number, ): void; /** [CanvasContext.setGlobalAlpha(number alpha)](CanvasContext.setGlobalAlpha.md) * * 设置全局画笔透明度。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.setFillStyle('red') ctx.fillRect(10, 10, 150, 100) ctx.setGlobalAlpha(0.2) ctx.setFillStyle('blue') ctx.fillRect(50, 50, 150, 100) ctx.setFillStyle('yellow') ctx.fillRect(100, 100, 150, 100) ctx.draw() ``` * ![]((canvas/global-alpha.png)) */ setGlobalAlpha( /** 透明度。范围 0-1,0 表示完全透明,1 表示完全不透明。 */ alpha: number, ): void; /** [CanvasContext.setLineCap(string lineCap)](CanvasContext.setLineCap.md) * * 设置线条的端点样式 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.beginPath() ctx.moveTo(10, 10) ctx.lineTo(150, 10) ctx.stroke() ctx.beginPath() ctx.setLineCap('butt') ctx.setLineWidth(10) ctx.moveTo(10, 30) ctx.lineTo(150, 30) ctx.stroke() ctx.beginPath() ctx.setLineCap('round') ctx.setLineWidth(10) ctx.moveTo(10, 50) ctx.lineTo(150, 50) ctx.stroke() ctx.beginPath() ctx.setLineCap('square') ctx.setLineWidth(10) ctx.moveTo(10, 70) ctx.lineTo(150, 70) ctx.stroke() ctx.draw() ``` * ![]((canvas/line-cap.png)) */ setLineCap( /** 线条的结束端点样式 */ lineCap: string, ): void; /** [CanvasContext.setLineDash(Array.<number> pattern, number offset)](CanvasContext.setLineDash.md) * * 设置虚线样式。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.setLineDash([10, 20], 5); ctx.beginPath(); ctx.moveTo(0,100); ctx.lineTo(400, 100); ctx.stroke(); ctx.draw() ``` * ![]((canvas/set-line-dash.png)) * * 最低基础库: `1.6.0` */ setLineDash( /** 一组描述交替绘制线段和间距(坐标空间单位)长度的数字 */ pattern: Array<number>, /** 虚线偏移量 */ offset: number, ): void; /** [CanvasContext.setLineJoin(string lineJoin)](CanvasContext.setLineJoin.md) * * 设置线条的交点样式 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.beginPath() ctx.moveTo(10, 10) ctx.lineTo(100, 50) ctx.lineTo(10, 90) ctx.stroke() ctx.beginPath() ctx.setLineJoin('bevel') ctx.setLineWidth(10) ctx.moveTo(50, 10) ctx.lineTo(140, 50) ctx.lineTo(50, 90) ctx.stroke() ctx.beginPath() ctx.setLineJoin('round') ctx.setLineWidth(10) ctx.moveTo(90, 10) ctx.lineTo(180, 50) ctx.lineTo(90, 90) ctx.stroke() ctx.beginPath() ctx.setLineJoin('miter') ctx.setLineWidth(10) ctx.moveTo(130, 10) ctx.lineTo(220, 50) ctx.lineTo(130, 90) ctx.stroke() ctx.draw() ``` * ![]((canvas/line-join.png)) */ setLineJoin( /** 线条的结束交点样式 */ lineJoin: string, ): void; /** [CanvasContext.setLineWidth(number lineWidth)](CanvasContext.setLineWidth.md) * * 设置线条的宽度 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.beginPath() ctx.moveTo(10, 10) ctx.lineTo(150, 10) ctx.stroke() ctx.beginPath() ctx.setLineWidth(5) ctx.moveTo(10, 30) ctx.lineTo(150, 30) ctx.stroke() ctx.beginPath() ctx.setLineWidth(10) ctx.moveTo(10, 50) ctx.lineTo(150, 50) ctx.stroke() ctx.beginPath() ctx.setLineWidth(15) ctx.moveTo(10, 70) ctx.lineTo(150, 70) ctx.stroke() ctx.draw() ``` * * ![]((canvas/line-width.png)) */ setLineWidth( /** 线条的宽度,单位px */ lineWidth: number, ): void; /** [CanvasContext.setMiterLimit(number miterLimit)](CanvasContext.setMiterLimit.md) * * 设置最大斜接长度。斜接长度指的是在两条线交汇处内角和外角之间的距离。当 [CanvasContext.setLineJoin()](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.setLineJoin.html) 为 miter 时才有效。超过最大倾斜长度的,连接处将以 lineJoin 为 bevel 来显示。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.beginPath() ctx.setLineWidth(10) ctx.setLineJoin('miter') ctx.setMiterLimit(1) ctx.moveTo(10, 10) ctx.lineTo(100, 50) ctx.lineTo(10, 90) ctx.stroke() ctx.beginPath() ctx.setLineWidth(10) ctx.setLineJoin('miter') ctx.setMiterLimit(2) ctx.moveTo(50, 10) ctx.lineTo(140, 50) ctx.lineTo(50, 90) ctx.stroke() ctx.beginPath() ctx.setLineWidth(10) ctx.setLineJoin('miter') ctx.setMiterLimit(3) ctx.moveTo(90, 10) ctx.lineTo(180, 50) ctx.lineTo(90, 90) ctx.stroke() ctx.beginPath() ctx.setLineWidth(10) ctx.setLineJoin('miter') ctx.setMiterLimit(4) ctx.moveTo(130, 10) ctx.lineTo(220, 50) ctx.lineTo(130, 90) ctx.stroke() ctx.draw() ``` * ![]((canvas/miter-limit.png)) */ setMiterLimit( /** 最大斜接长度 */ miterLimit: number, ): void; /** [CanvasContext.setShadow(number offsetX, number offsetY, number blur, string color)](CanvasContext.setShadow.md) * * 设定阴影样式。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.setFillStyle('red') ctx.setShadow(10, 50, 50, 'blue') ctx.fillRect(10, 10, 150, 75) ctx.draw() ``` * ![]((canvas/shadow.png)) */ setShadow( /** 阴影相对于形状在水平方向的偏移,默认值为 0。 */ offsetX: number, /** 阴影相对于形状在竖直方向的偏移,默认值为 0。 */ offsetY: number, /** 阴影的模糊级别,数值越大越模糊。范围 0- 100。,默认值为 0。 */ blur: number, /** 阴影的颜色。默认值为 black。 */ color: string, ): void; /** [CanvasContext.setStrokeStyle([Color](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/Color.html) color)](CanvasContext.setStrokeStyle.md) * * 设置描边颜色。 * * **代码示例** * * * ```js const ctx = wx.createCanvasContext('myCanvas') ctx.setStrokeStyle('red') ctx.strokeRect(10, 10, 150, 75) ctx.draw() ``` * ![]((canvas/stroke-rect.png)) */ setStrokeStyle( /** [Color](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/Color.html) * * 描边的颜色,默认颜色为 black。 */ color: Color, ): void; /** [CanvasContext.setTextAlign(string align)](CanvasContext.setTextAlign.md) * * 设置文字的对齐 * * **示例代码** * * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.setStrokeStyle('red') ctx.moveTo(150, 20) ctx.lineTo(150, 170) ctx.stroke() ctx.setFontSize(15) ctx.setTextAlign('left') ctx.fillText('textAlign=left', 150, 60) ctx.setTextAlign('center') ctx.fillText('textAlign=center', 150, 80) ctx.setTextAlign('right') ctx.fillText('textAlign=right', 150, 100) ctx.draw() ``` * * ![]((canvas/set-text-align.png)) * * 最低基础库: `1.1.0` */ setTextAlign( /** 文字的对齐方式 */ align: string, ): void; /** [CanvasContext.setTextBaseline(string textBaseline)](CanvasContext.setTextBaseline.md) * * 设置文字的竖直对齐 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.setStrokeStyle('red') ctx.moveTo(5, 75) ctx.lineTo(295, 75) ctx.stroke() ctx.setFontSize(20) ctx.setTextBaseline('top') ctx.fillText('top', 5, 75) ctx.setTextBaseline('middle') ctx.fillText('middle', 50, 75) ctx.setTextBaseline('bottom') ctx.fillText('bottom', 120, 75) ctx.setTextBaseline('normal') ctx.fillText('normal', 200, 75) ctx.draw() ``` * ![]((canvas/set-text-baseline.png)) * * 最低基础库: `1.4.0` */ setTextBaseline( /** 文字的竖直对齐方式 */ textBaseline: string, ): void; /** [CanvasContext.setTransform(number scaleX, number scaleY, number skewX, number skewY, number translateX, number translateY)](CanvasContext.setTransform.md) * * 使用矩阵重新设置(覆盖)当前变换的方法 * * 最低基础库: `1.9.90` */ setTransform( /** 水平缩放 */ scaleX: number, /** 垂直缩放 */ scaleY: number, /** 水平倾斜 */ skewX: number, /** 垂直倾斜 */ skewY: number, /** 水平移动 */ translateX: number, /** 垂直移动 */ translateY: number, ): void; /** [CanvasContext.stroke()](CanvasContext.stroke.md) * * 画出当前路径的边框。默认颜色色为黑色。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.moveTo(10, 10) ctx.lineTo(100, 10) ctx.lineTo(100, 100) ctx.stroke() ctx.draw() ``` * ![]((canvas/stroke-line.png)) * * stroke() 描绘的的路径是从 beginPath() 开始计算,但是不会将 strokeRect() 包含进去。 * * ```javascript const ctx = wx.createCanvasContext('myCanvas') // begin path ctx.rect(10, 10, 100, 30) ctx.setStrokeStyle('yellow') ctx.stroke() // begin another path ctx.beginPath() ctx.rect(10, 40, 100, 30) // only stoke this rect, not in current path ctx.setStrokeStyle('blue') ctx.strokeRect(10, 70, 100, 30) ctx.rect(10, 100, 100, 30) // it will stroke current path ctx.setStrokeStyle('red') ctx.stroke() ctx.draw() ``` * * ![]((canvas/stroke-path.png)) */ stroke(): void; /** [CanvasContext.strokeRect(number x, number y, number width, number height)](CanvasContext.strokeRect.md) * * 画一个矩形(非填充)。 用 [`setStrokeStyle`](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.setStrokeStyle.html) 设置矩形线条的颜色,如果没设置默认是黑色。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.setStrokeStyle('red') ctx.strokeRect(10, 10, 150, 75) ctx.draw() ``` * ![]((canvas/stroke-rect.png)) */ strokeRect( /** 矩形路径左上角的横坐标 */ x: number, /** 矩形路径左上角的横坐标 */ y: number, /** 矩形路径的宽度 */ width: number, /** 矩形路径的高度 */ height: number, ): void; /** [CanvasContext.strokeText(string text, number x, number y, number maxWidth)](CanvasContext.strokeText.md) * * 给定的 (x, y) 位置绘制文本描边的方法 * * 最低基础库: `1.9.90` */ strokeText( /** 要绘制的文本 */ text: string, /** 文本起始点的 x 轴坐标 */ x: number, /** 文本起始点的 y 轴坐标 */ y: number, /** 需要绘制的最大宽度,可选 */ maxWidth?: number, ): void; /** [CanvasContext.transform(number scaleX, number scaleY, number skewX, number skewY, number translateX, number translateY)](CanvasContext.transform.md) * * 使用矩阵多次叠加当前变换的方法 * * 最低基础库: `1.9.90` */ transform( /** 水平缩放 */ scaleX: number, /** 垂直缩放 */ scaleY: number, /** 水平倾斜 */ skewX: number, /** 垂直倾斜 */ skewY: number, /** 水平移动 */ translateX: number, /** 垂直移动 */ translateY: number, ): void; /** [CanvasContext.translate(number x, number y)](CanvasContext.translate.md) * * 对当前坐标系的原点 (0, 0) 进行变换。默认的坐标系原点为页面左上角。 * * **示例代码** * * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') ctx.strokeRect(10, 10, 150, 100) ctx.translate(20, 20) ctx.strokeRect(10, 10, 150, 100) ctx.translate(20, 20) ctx.strokeRect(10, 10, 150, 100) ctx.draw() ``` * * ![]((canvas/translate.png)) */ translate( /** 水平坐标平移量 */ x: number, /** 竖直坐标平移量 */ y: number, ): void; /** [Object CanvasContext.measureText(string text)](CanvasContext.measureText.md) * * 测量文本尺寸信息。目前仅返回文本宽度。同步接口。 * * 最低基础库: `1.9.90` */ measureText( /** 要测量的文本 */ text: string, ): TextMetrics; /** [[CanvasGradient](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasGradient.html) CanvasContext.createCircularGradient(number x, number y, number r)](CanvasContext.createCircularGradient.md) * * 创建一个圆形的渐变颜色。起点在圆心,终点在圆环。返回的`CanvasGradient`对象需要使用 [CanvasGradient.addColorStop()](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasGradient.addColorStop.html) 来指定渐变点,至少要两个。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') // Create circular gradient const grd = ctx.createCircularGradient(75, 50, 50) grd.addColorStop(0, 'red') grd.addColorStop(1, 'white') // Fill with gradient ctx.setFillStyle(grd) ctx.fillRect(10, 10, 150, 80) ctx.draw() ``` * ![]((canvas/circular-gradient.png)) */ createCircularGradient( /** 圆心的 x 坐标 */ x: number, /** 圆心的 y 坐标 */ y: number, /** 圆的半径 */ r: number, ): CanvasGradient; /** [[CanvasGradient](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasGradient.html) CanvasContext.createLinearGradient(number x0, number y0, number x1, number y1)](CanvasContext.createLinearGradient.md) * * 创建一个线性的渐变颜色。返回的`CanvasGradient`对象需要使用 [CanvasGradient.addColorStop()](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasGradient.addColorStop.html) 来指定渐变点,至少要两个。 * * **示例代码** * * * ```javascript const ctx = wx.createCanvasContext('myCanvas') // Create linear gradient const grd = ctx.createLinearGradient(0, 0, 200, 0) grd.addColorStop(0, 'red') grd.addColorStop(1, 'white') // Fill with gradient ctx.setFillStyle(grd) ctx.fillRect(10, 10, 150, 80) ctx.draw() ``` * ![]((canvas/linear-gradient.png)) */ createLinearGradient( /** 起点的 x 坐标 */ x0: number, /** 起点的 y 坐标 */ y0: number, /** 终点的 x 坐标 */ x1: number, /** 终点的 y 坐标 */ y1: number, ): CanvasGradient; } interface CanvasGradient { /** [CanvasGradient.addColorStop(number stop, [Color](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/Color.html) color)](CanvasGradient.addColorStop.md) * * 添加颜色的渐变点。小于最小 stop 的部分会按最小 stop 的 color 来渲染,大于最大 stop 的部分会按最大 stop 的 color 来渲染 * * **示例代码** * * * ```js const ctx = wx.createCanvasContext('myCanvas') // Create circular gradient const grd = ctx.createLinearGradient(30, 10, 120, 10) grd.addColorStop(0, 'red') grd.addColorStop(0.16, 'orange') grd.addColorStop(0.33, 'yellow') grd.addColorStop(0.5, 'green') grd.addColorStop(0.66, 'cyan') grd.addColorStop(0.83, 'blue') grd.addColorStop(1, 'purple') // Fill with gradient ctx.setFillStyle(grd) ctx.fillRect(10, 10, 150, 80) ctx.draw() ``` * ![]((canvas/color-stop.png)) */ addColorStop( /** 表示渐变中开始与结束之间的位置,范围 0-1。 */ stop: number, /** [Color](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/Color.html) * * 渐变点的颜色。 */ color: Color, ): void; } interface Console { /** [console.debug()](console.debug.md) * * 向调试面板中打印 debug 日志 */ debug( /** 日志内容,可以有任意多个。 */ ...args: any[] ): void; /** [console.error()](console.error.md) * * 向调试面板中打印 error 日志 */ error( /** 日志内容,可以有任意多个。 */ ...args: any[] ): void; /** [console.group(string label)](console.group.md) * * 在调试面板中创建一个新的分组。随后输出的内容都会被添加一个缩进,表示该内容属于当前分组。调用 [console.groupEnd](https://developers.weixin.qq.com/miniprogram/dev/api/debug/console.groupEnd.html)之后分组结束。 * * **注意** * * * 仅在工具中有效,在 vConsole 中为空函数实现。 */ group( /** 分组标记,可选。 */ label?: string, ): void; /** [console.groupEnd()](console.groupEnd.md) * * 结束由 [console.group](https://developers.weixin.qq.com/miniprogram/dev/api/debug/console.group.html) 创建的分组 * * **注意** * * * 仅在工具中有效,在 vConsole 中为空函数实现。 */ groupEnd(): void; /** [console.info()](console.info.md) * * 向调试面板中打印 info 日志 */ info( /** 日志内容,可以有任意多个。 */ ...args: any[] ): void; /** [console.log()](console.log.md) * * 向调试面板中打印 log 日志 */ log( /** 日志内容,可以有任意多个。 */ ...args: any[] ): void; /** [console.warn()](console.warn.md) * * 向调试面板中打印 warn 日志 */ warn( /** 日志内容,可以有任意多个。 */ ...args: any[] ): void; } interface DownloadTask { /** [DownloadTask.abort()](DownloadTask.abort.md) * * 中断下载任务 * * 最低基础库: `1.4.0` */ abort(): void; /** [DownloadTask.offHeadersReceived(function callback)](DownloadTask.offHeadersReceived.md) * * 取消监听 HTTP Response Header 事件 * * 最低基础库: `2.1.0` */ offHeadersReceived( /** HTTP Response Header 事件的回调函数 */ callback: DownloadTaskOffHeadersReceivedCallback, ): void; /** [DownloadTask.offProgressUpdate(function callback)](DownloadTask.offProgressUpdate.md) * * 取消监听下载进度变化事件 * * 最低基础库: `2.1.0` */ offProgressUpdate( /** 下载进度变化事件的回调函数 */ callback: DownloadTaskOffProgressUpdateCallback, ): void; /** [DownloadTask.onHeadersReceived(function callback)](DownloadTask.onHeadersReceived.md) * * 监听 HTTP Response Header 事件。会比请求完成事件更早 * * 最低基础库: `2.1.0` */ onHeadersReceived( /** HTTP Response Header 事件的回调函数 */ callback: DownloadTaskOnHeadersReceivedCallback, ): void; /** [DownloadTask.onProgressUpdate(function callback)](DownloadTask.onProgressUpdate.md) * * 监听下载进度变化事件 * * 最低基础库: `1.4.0` */ onProgressUpdate( /** 下载进度变化事件的回调函数 */ callback: DownloadTaskOnProgressUpdateCallback, ): void; } interface FileSystemManager { /** [Array.<string> FileSystemManager.readdirSync(string dirPath)](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.readdirSync.html) * * [FileSystemManager.readdir](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.readdir.html) 的同步版本 */ readdirSync( /** 要读取的目录路径 */ dirPath: string, ): Array<string>; /** [FileSystemManager.access(Object object)](FileSystemManager.access.md) * * 判断文件/目录是否存在 */ access(option: AccessOption): void; /** [FileSystemManager.accessSync(string path)](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.accessSync.html) * * [FileSystemManager.access](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.access.html) 的同步版本 */ accessSync( /** 要判断是否存在的文件/目录路径 */ path: string, ): void; /** [FileSystemManager.appendFile(Object object)](FileSystemManager.appendFile.md) * * 在文件结尾追加内容 * * 最低基础库: `2.1.0` */ appendFile(option: AppendFileOption): void; /** [FileSystemManager.appendFileSync(string filePath, string|ArrayBuffer data, string encoding)](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.appendFileSync.html) * * [FileSystemManager.appendFile](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.appendFile.html) 的同步版本 * * 最低基础库: `2.1.0` */ appendFileSync( /** 要追加内容的文件路径 */ filePath: string, /** 要追加的文本或二进制数据 */ data: string | ArrayBuffer, /** 指定写入文件的字符编码 */ encoding?: string, ): void; /** [FileSystemManager.copyFile(Object object)](FileSystemManager.copyFile.md) * * 复制文件 */ copyFile(option: CopyFileOption): void; /** [FileSystemManager.copyFileSync(string srcPath, string destPath)](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.copyFileSync.html) * * [FileSystemManager.copyFile](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.copyFile.html) 的同步版本 */ copyFileSync( /** 源文件路径,只可以是普通文件 */ srcPath: string, /** 目标文件路径 */ destPath: string, ): void; /** [FileSystemManager.getFileInfo(Object object)](FileSystemManager.getFileInfo.md) * * 获取该小程序下的 本地临时文件 或 本地缓存文件 信息 */ getFileInfo(option: FileSystemManagerGetFileInfoOption): void; /** [FileSystemManager.getSavedFileList(Object object)](FileSystemManager.getSavedFileList.md) * * 获取该小程序下已保存的本地缓存文件列表 */ getSavedFileList(option?: FileSystemManagerGetSavedFileListOption): void; /** [FileSystemManager.mkdir(Object object)](FileSystemManager.mkdir.md) * * 创建目录 */ mkdir(option: MkdirOption): void; /** [FileSystemManager.mkdirSync(string dirPath, boolean recursive)](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.mkdirSync.html) * * [FileSystemManager.mkdir](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.mkdir.html) 的同步版本 */ mkdirSync( /** 创建的目录路径 */ dirPath: string, /** 是否在递归创建该目录的上级目录后再创建该目录。如果对应的上级目录已经存在,则不创建该上级目录。如 dirPath 为 a/b/c/d 且 recursive 为 true,将创建 a 目录,再在 a 目录下创建 b 目录,以此类推直至创建 a/b/c 目录下的 d 目录。 * * 最低基础库: `2.3.0` */ recursive?: boolean, ): void; /** [FileSystemManager.readFile(Object object)](FileSystemManager.readFile.md) * * 读取本地文件内容 */ readFile(option: ReadFileOption): void; /** [FileSystemManager.readdir(Object object)](FileSystemManager.readdir.md) * * 读取目录内文件列表 */ readdir(option: ReaddirOption): void; /** [FileSystemManager.removeSavedFile(Object object)](FileSystemManager.removeSavedFile.md) * * 删除该小程序下已保存的本地缓存文件 */ removeSavedFile(option: FileSystemManagerRemoveSavedFileOption): void; /** [FileSystemManager.rename(Object object)](FileSystemManager.rename.md) * * 重命名文件。可以把文件从 oldPath 移动到 newPath */ rename(option: RenameOption): void; /** [FileSystemManager.renameSync(string oldPath, string newPath)](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.renameSync.html) * * [FileSystemManager.rename](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.rename.html) 的同步版本 */ renameSync( /** 源文件路径,可以是普通文件或目录 */ oldPath: string, /** 新文件路径 */ newPath: string, ): void; /** [FileSystemManager.rmdir(Object object)](FileSystemManager.rmdir.md) * * 删除目录 */ rmdir(option: RmdirOption): void; /** [FileSystemManager.rmdirSync(string dirPath, boolean recursive)](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.rmdirSync.html) * * [FileSystemManager.rmdir](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.rmdir.html) 的同步版本 */ rmdirSync( /** 要删除的目录路径 */ dirPath: string, /** 是否递归删除目录。如果为 true,则删除该目录和该目录下的所有子目录以及文件。 * * 最低基础库: `2.3.0` */ recursive?: boolean, ): void; /** [FileSystemManager.saveFile(Object object)](FileSystemManager.saveFile.md) * * 保存临时文件到本地。此接口会移动临时文件,因此调用成功后,tempFilePath 将不可用。 */ saveFile(option: FileSystemManagerSaveFileOption): void; /** [FileSystemManager.stat(Object object)](FileSystemManager.stat.md) * * 获取文件 Stats 对象 */ stat(option: StatOption): void; /** [FileSystemManager.unlink(Object object)](FileSystemManager.unlink.md) * * 删除文件 */ unlink(option: UnlinkOption): void; /** [FileSystemManager.unlinkSync(string filePath)](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.unlinkSync.html) * * [FileSystemManager.unlink](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.unlink.html) 的同步版本 */ unlinkSync( /** 要删除的文件路径 */ filePath: string, ): void; /** [FileSystemManager.unzip(Object object)](FileSystemManager.unzip.md) * * 解压文件 */ unzip(option: UnzipOption): void; /** [FileSystemManager.writeFile(Object object)](FileSystemManager.writeFile.md) * * 写文件 */ writeFile(option: WriteFileOption): void; /** [FileSystemManager.writeFileSync(string filePath, string|ArrayBuffer data, string encoding)](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.writeFileSync.html) * * [FileSystemManager.writeFile](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.writeFile.html) 的同步版本 */ writeFileSync( /** 要写入的文件路径 */ filePath: string, /** 要写入的文本或二进制数据 */ data: string | ArrayBuffer, /** 指定写入文件的字符编码 */ encoding?: string, ): void; /** [[Stats](https://developers.weixin.qq.com/miniprogram/dev/api/file/Stats.html)|Object FileSystemManager.statSync(string path, boolean recursive)](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.statSync.html) * * [FileSystemManager.stat](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.stat.html) 的同步版本 */ statSync( /** 文件/目录路径 */ path: string, /** 是否递归获取目录下的每个文件的 Stats 信息 * * 最低基础库: `2.3.0` */ recursive?: boolean, ): Stats; /** [number FileSystemManager.saveFileSync(string tempFilePath, string filePath)](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.saveFileSync.html) * * [FileSystemManager.saveFile](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.saveFile.html) 的同步版本 */ saveFileSync( /** 临时存储文件路径 */ tempFilePath: string, /** 要存储的文件路径 */ filePath?: string, ): number; /** [string|ArrayBuffer FileSystemManager.readFileSync(string filePath, string encoding)](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.readFileSync.html) * * [FileSystemManager.readFile](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.readFile.html) 的同步版本 */ readFileSync( /** 要读取的文件的路径 */ filePath: string, /** 指定读取文件的字符编码,如果不传 encoding,则以 ArrayBuffer 格式读取文件的二进制内容 */ encoding?: string, ): string; } interface GeneralCallbackResult { errMsg: string; } interface InnerAudioContext { /** [InnerAudioContext.destroy()](InnerAudioContext.destroy.md) * * 销毁当前实例 */ destroy(): void; /** [InnerAudioContext.offCanplay(function callback)](InnerAudioContext.offCanplay.md) * * 取消监听音频进入可以播放状态的事件 * * 最低基础库: `1.9.0` */ offCanplay( /** 音频进入可以播放状态的事件的回调函数 */ callback: OffCanplayCallback, ): void; /** [InnerAudioContext.offEnded(function callback)](InnerAudioContext.offEnded.md) * * 取消监听音频自然播放至结束的事件 * * 最低基础库: `1.9.0` */ offEnded( /** 音频自然播放至结束的事件的回调函数 */ callback: OffEndedCallback, ): void; /** [InnerAudioContext.offError(function callback)](InnerAudioContext.offError.md) * * 取消监听音频播放错误事件 * * 最低基础库: `1.9.0` */ offError( /** 音频播放错误事件的回调函数 */ callback: OffErrorCallback, ): void; /** [InnerAudioContext.offPause(function callback)](InnerAudioContext.offPause.md) * * 取消监听音频暂停事件 * * 最低基础库: `1.9.0` */ offPause( /** 音频暂停事件的回调函数 */ callback: OffPauseCallback, ): void; /** [InnerAudioContext.offPlay(function callback)](InnerAudioContext.offPlay.md) * * 取消监听音频播放事件 * * 最低基础库: `1.9.0` */ offPlay( /** 音频播放事件的回调函数 */ callback: OffPlayCallback, ): void; /** [InnerAudioContext.offSeeked(function callback)](InnerAudioContext.offSeeked.md) * * 取消监听音频完成跳转操作的事件 * * 最低基础库: `1.9.0` */ offSeeked( /** 音频完成跳转操作的事件的回调函数 */ callback: OffSeekedCallback, ): void; /** [InnerAudioContext.offSeeking(function callback)](InnerAudioContext.offSeeking.md) * * 取消监听音频进行跳转操作的事件 * * 最低基础库: `1.9.0` */ offSeeking( /** 音频进行跳转操作的事件的回调函数 */ callback: OffSeekingCallback, ): void; /** [InnerAudioContext.offStop(function callback)](InnerAudioContext.offStop.md) * * 取消监听音频停止事件 * * 最低基础库: `1.9.0` */ offStop( /** 音频停止事件的回调函数 */ callback: OffStopCallback, ): void; /** [InnerAudioContext.offTimeUpdate(function callback)](InnerAudioContext.offTimeUpdate.md) * * 取消监听音频播放进度更新事件 * * 最低基础库: `1.9.0` */ offTimeUpdate( /** 音频播放进度更新事件的回调函数 */ callback: OffTimeUpdateCallback, ): void; /** [InnerAudioContext.offWaiting(function callback)](InnerAudioContext.offWaiting.md) * * 取消监听音频加载中事件 * * 最低基础库: `1.9.0` */ offWaiting( /** 音频加载中事件的回调函数 */ callback: OffWaitingCallback, ): void; /** [InnerAudioContext.onCanplay(function callback)](InnerAudioContext.onCanplay.md) * * 监听音频进入可以播放状态的事件。但不保证后面可以流畅播放 */ onCanplay( /** 音频进入可以播放状态的事件的回调函数 */ callback: InnerAudioContextOnCanplayCallback, ): void; /** [InnerAudioContext.onEnded(function callback)](InnerAudioContext.onEnded.md) * * 监听音频自然播放至结束的事件 */ onEnded( /** 音频自然播放至结束的事件的回调函数 */ callback: InnerAudioContextOnEndedCallback, ): void; /** [InnerAudioContext.onError(function callback)](InnerAudioContext.onError.md) * * 监听音频播放错误事件 */ onError( /** 音频播放错误事件的回调函数 */ callback: InnerAudioContextOnErrorCallback, ): void; /** [InnerAudioContext.onPause(function callback)](InnerAudioContext.onPause.md) * * 监听音频暂停事件 */ onPause( /** 音频暂停事件的回调函数 */ callback: InnerAudioContextOnPauseCallback, ): void; /** [InnerAudioContext.onPlay(function callback)](InnerAudioContext.onPlay.md) * * 监听音频播放事件 */ onPlay( /** 音频播放事件的回调函数 */ callback: InnerAudioContextOnPlayCallback, ): void; /** [InnerAudioContext.onSeeked(function callback)](InnerAudioContext.onSeeked.md) * * 监听音频完成跳转操作的事件 */ onSeeked( /** 音频完成跳转操作的事件的回调函数 */ callback: InnerAudioContextOnSeekedCallback, ): void; /** [InnerAudioContext.onSeeking(function callback)](InnerAudioContext.onSeeking.md) * * 监听音频进行跳转操作的事件 */ onSeeking( /** 音频进行跳转操作的事件的回调函数 */ callback: InnerAudioContextOnSeekingCallback, ): void; /** [InnerAudioContext.onStop(function callback)](InnerAudioContext.onStop.md) * * 监听音频停止事件 */ onStop( /** 音频停止事件的回调函数 */ callback: InnerAudioContextOnStopCallback, ): void; /** [InnerAudioContext.onTimeUpdate(function callback)](InnerAudioContext.onTimeUpdate.md) * * 监听音频播放进度更新事件 */ onTimeUpdate( /** 音频播放进度更新事件的回调函数 */ callback: InnerAudioContextOnTimeUpdateCallback, ): void; /** [InnerAudioContext.onWaiting(function callback)](InnerAudioContext.onWaiting.md) * * 监听音频加载中事件。当音频因为数据不足,需要停下来加载时会触发 */ onWaiting( /** 音频加载中事件的回调函数 */ callback: InnerAudioContextOnWaitingCallback, ): void; /** [InnerAudioContext.pause()](InnerAudioContext.pause.md) * * 暂停。暂停后的音频再播放会从暂停处开始播放 */ pause(): void; /** [InnerAudioContext.play()](InnerAudioContext.play.md) * * 播放 */ play(): void; /** [InnerAudioContext.seek(number position)](InnerAudioContext.seek.md) * * 跳转到指定位置 */ seek( /** 跳转的时间,单位 s。精确到小数点后 3 位,即支持 ms 级别精确度 */ position: number, ): void; /** [InnerAudioContext.stop()](InnerAudioContext.stop.md) * * 停止。停止后的音频再播放会从头开始播放。 */ stop(): void; } interface IntersectionObserver { /** [IntersectionObserver.disconnect()](IntersectionObserver.disconnect.md) * * 停止监听。回调函数将不再触发 * * **注意** * * * 与页面显示区域的相交区域并不准确代表用户可见的区域,因为参与计算的区域是“布局区域”,布局区域可能会在绘制时被其他节点裁剪隐藏(如遇祖先节点中 overflow 样式为 hidden 的节点)或遮盖(如遇 fixed 定位的节点)。 */ disconnect(): void; /** [IntersectionObserver.observe(string targetSelector, function callback)](IntersectionObserver.observe.md) * * 指定目标节点并开始监听相交状态变化情况 */ observe( /** 选择器 */ targetSelector: string, /** 监听相交状态变化的回调函数 */ callback: ObserveCallback, ): void; /** [IntersectionObserver.relativeTo(string selector, Object margins)](IntersectionObserver.relativeTo.md) * * 使用选择器指定一个节点,作为参照区域之一。 */ relativeTo( /** 选择器 */ selector: string, /** 用来扩展(或收缩)参照节点布局区域的边界 */ margins?: RelativeToMargins, ): void; /** [IntersectionObserver.relativeToViewport(Object margins)](IntersectionObserver.relativeToViewport.md) * * 指定页面显示区域作为参照区域之一 * * **示例代码** * * * 下面的示例代码中,如果目标节点(用选择器 .target-class 指定)进入显示区域以下 100px 时,就会触发回调函数。 * ```javascript Page({ onLoad: function(){ wx.createIntersectionObserver().relativeToViewport({bottom: 100}).observe('.target-class', (res) => { res.intersectionRatio // 相交区域占目标节点的布局区域的比例 res.intersectionRect // 相交区域 res.intersectionRect.left // 相交区域的左边界坐标 res.intersectionRect.top // 相交区域的上边界坐标 res.intersectionRect.width // 相交区域的宽度 res.intersectionRect.height // 相交区域的高度 }) } }) ``` */ relativeToViewport( /** 用来扩展(或收缩)参照节点布局区域的边界 */ margins?: RelativeToViewportMargins, ): void; } interface LivePlayerContext { /** [LivePlayerContext.exitFullScreen(Object object)](LivePlayerContext.exitFullScreen.md) * * 退出全屏 */ exitFullScreen(option?: ExitFullScreenOption): void; /** [LivePlayerContext.mute(Object object)](LivePlayerContext.mute.md) * * 静音 */ mute(option?: MuteOption): void; /** [LivePlayerContext.pause(Object object)](LivePlayerContext.pause.md) * * 暂停 * * 最低基础库: `1.9.90` */ pause(option?: LivePlayerContextPauseOption): void; /** [LivePlayerContext.play(Object object)](LivePlayerContext.play.md) * * 播放 */ play(option?: PlayOption): void; /** [LivePlayerContext.requestFullScreen(Object object)](LivePlayerContext.requestFullScreen.md) * * 进入全屏 */ requestFullScreen(option: LivePlayerContextRequestFullScreenOption): void; /** [LivePlayerContext.resume(Object object)](LivePlayerContext.resume.md) * * 恢复 * * 最低基础库: `1.9.90` */ resume(option?: LivePlayerContextResumeOption): void; /** [LivePlayerContext.stop(Object object)](LivePlayerContext.stop.md) * * 停止 */ stop(option?: LivePlayerContextStopOption): void; } interface LivePusherContext { /** [LivePusherContext.pause(Object object)](LivePusherContext.pause.md) * * 暂停推流 */ pause(option?: LivePusherContextPauseOption): void; /** [LivePusherContext.pauseBGM(Object object)](LivePusherContext.pauseBGM.md) * * 暂停背景音 * * 最低基础库: `2.4.0` */ pauseBGM(option?: PauseBGMOption): void; /** [LivePusherContext.playBGM(Object object)](LivePusherContext.playBGM.md) * * 播放背景音 * * 最低基础库: `2.4.0` */ playBGM(option: PlayBGMOption): void; /** [LivePusherContext.resume(Object object)](LivePusherContext.resume.md) * * 恢复推流 */ resume(option?: LivePusherContextResumeOption): void; /** [LivePusherContext.resumeBGM(Object object)](LivePusherContext.resumeBGM.md) * * 恢复背景音 * * 最低基础库: `2.4.0` */ resumeBGM(option?: ResumeBGMOption): void; /** [LivePusherContext.setBGMVolume(Object object)](LivePusherContext.setBGMVolume.md) * * 设置背景音音量 * * 最低基础库: `2.4.0` */ setBGMVolume(option: SetBGMVolumeOption): void; /** [LivePusherContext.snapshot(Object object)](LivePusherContext.snapshot.md) * * 快照 * * 最低基础库: `1.9.90` */ snapshot(option?: SnapshotOption): void; /** [LivePusherContext.start(Object object)](LivePusherContext.start.md) * * 播放推流 */ start(option?: LivePusherContextStartOption): void; /** [LivePusherContext.stop(Object object)](LivePusherContext.stop.md) * * 停止推流 */ stop(option?: LivePusherContextStopOption): void; /** [LivePusherContext.stopBGM(Object object)](LivePusherContext.stopBGM.md) * * 停止背景音 * * 最低基础库: `2.4.0` */ stopBGM(option?: StopBGMOption): void; /** [LivePusherContext.switchCamera(Object object)](LivePusherContext.switchCamera.md) * * 切换前后摄像头 */ switchCamera(option?: SwitchCameraOption): void; /** [LivePusherContext.toggleTorch(Object object)](LivePusherContext.toggleTorch.md) * * 切换 * * 最低基础库: `2.1.0` */ toggleTorch(option?: ToggleTorchOption): void; } interface LogManager { /** [LogManager.debug()](LogManager.debug.md) * * 写 debug 日志 */ debug( /** 日志内容,可以有任意多个。每次调用的参数的总大小不超过100Kb */ ...args: any[] ): void; /** [LogManager.info()](LogManager.info.md) * * 写 info 日志 */ info( /** 日志内容,可以有任意多个。每次调用的参数的总大小不超过100Kb */ ...args: any[] ): void; /** [LogManager.log()](LogManager.log.md) * * 写 log 日志 */ log( /** 日志内容,可以有任意多个。每次调用的参数的总大小不超过100Kb */ ...args: any[] ): void; /** [LogManager.warn()](LogManager.warn.md) * * 写 warn 日志 */ warn( /** 日志内容,可以有任意多个。每次调用的参数的总大小不超过100Kb */ ...args: any[] ): void; } interface MapContext { /** [MapContext.getCenterLocation(Object object)](MapContext.getCenterLocation.md) * * 获取当前地图中心的经纬度。返回的是 gcj02 坐标系,可以用于 [wx.openLocation()](https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.openLocation.html) */ getCenterLocation(option?: GetCenterLocationOption): void; /** [MapContext.getRegion(Object object)](MapContext.getRegion.md) * * 获取当前地图的视野范围 * * 最低基础库: `1.4.0` */ getRegion(option?: GetRegionOption): void; /** [MapContext.getScale(Object object)](MapContext.getScale.md) * * 获取当前地图的缩放级别 * * 最低基础库: `1.4.0` */ getScale(option?: GetScaleOption): void; /** [MapContext.includePoints(Object object)](MapContext.includePoints.md) * * 缩放视野展示所有经纬度 * * 最低基础库: `1.2.0` */ includePoints(option: IncludePointsOption): void; /** [MapContext.moveToLocation()](MapContext.moveToLocation.md) * * 将地图中心移动到当前定位点。需要配合map组件的show-location使用 */ moveToLocation(): void; /** [MapContext.translateMarker(Object object)](MapContext.translateMarker.md) * * 平移marker,带动画 * * 最低基础库: `1.2.0` */ translateMarker(option: TranslateMarkerOption): void; } interface NodesRef { /** [NodesRef.fields(Object fields)](NodesRef.fields.md) * * 获取节点的相关信息。需要获取的字段在fields中指定。返回值是 `nodesRef` 对应的 `selectorQuery` * * **注意** * * * computedStyle 的优先级高于 size,当同时在 computedStyle 里指定了 width/height 和传入了 size: true,则优先返回 computedStyle 获取到的 width/height。 * * **示例代码** * * * ```js Page({ getFields () { wx.createSelectorQuery().select('#the-id').fields({ dataset: true, size: true, scrollOffset: true, properties: ['scrollX', 'scrollY'], computedStyle: ['margin', 'backgroundColor'], context: true, }, function (res) { res.dataset // 节点的dataset res.width // 节点的宽度 res.height // 节点的高度 res.scrollLeft // 节点的水平滚动位置 res.scrollTop // 节点的竖直滚动位置 res.scrollX // 节点 scroll-x 属性的当前值 res.scrollY // 节点 scroll-y 属性的当前值 // 此处返回指定要返回的样式名 res.margin res.backgroundColor res.context // 节点对应的 Context 对象 }).exec() } }) ``` */ fields(fields: Fields): void; /** [[SelectorQuery](https://developers.weixin.qq.com/miniprogram/dev/api/wxml/SelectorQuery.html) NodesRef.boundingClientRect(function callback)](NodesRef.boundingClientRect.md) * * 添加节点的布局位置的查询请求。相对于显示区域,以像素为单位。其功能类似于 DOM 的 `getBoundingClientRect`。返回 `NodesRef` 对应的 `SelectorQuery`。 * * **示例代码** * * * ```js Page({ getRect () { wx.createSelectorQuery().select('#the-id').boundingClientRect(function(rect){ rect.id // 节点的ID rect.dataset // 节点的dataset rect.left // 节点的左边界坐标 rect.right // 节点的右边界坐标 rect.top // 节点的上边界坐标 rect.bottom // 节点的下边界坐标 rect.width // 节点的宽度 rect.height // 节点的高度 }).exec() }, getAllRects () { wx.createSelectorQuery().selectAll('.a-class').boundingClientRect(function(rects){ rects.forEach(function(rect){ rect.id // 节点的ID rect.dataset // 节点的dataset rect.left // 节点的左边界坐标 rect.right // 节点的右边界坐标 rect.top // 节点的上边界坐标 rect.bottom // 节点的下边界坐标 rect.width // 节点的宽度 rect.height // 节点的高度 }) }).exec() } }) ``` */ boundingClientRect( /** 回调函数,在执行 `SelectorQuery.exec` 方法后,节点信息会在 `callback` 中返回。 */ callback?: BoundingClientRectCallback, ): SelectorQuery; /** [[SelectorQuery](https://developers.weixin.qq.com/miniprogram/dev/api/wxml/SelectorQuery.html) NodesRef.context(function callback)](NodesRef.context.md) * * 添加节点的 Context 对象查询请求。目前支持 `VideoContext`、`CanvasContext`、`LivePlayerContext` 和 `MapContext` 的获取。 * * **示例代码** * * * ```js Page({ getContext () { wx.createSelectorQuery().select('.the-video-class').context(function(res){ console.log(res.context) // 节点对应的 Context 对象。如:选中的节点是 <video> 组件,那么此处即返回 VideoContext 对象 }).exec() } }) ``` * * 最低基础库: `2.4.2` */ context( /** 回调函数,在执行 `SelectorQuery.exec` 方法后,返回节点信息。 */ callback?: ContextCallback, ): SelectorQuery; /** [[SelectorQuery](https://developers.weixin.qq.com/miniprogram/dev/api/wxml/SelectorQuery.html) NodesRef.scrollOffset(function callback)](NodesRef.scrollOffset.md) * * 添加节点的滚动位置查询请求。以像素为单位。节点必须是 `scroll-view` 或者 `viewport`,返回 `NodesRef` 对应的 `SelectorQuery`。 * * **示例代码** * * * ```js Page({ getScrollOffset () { wx.createSelectorQuery().selectViewport().scrollOffset(function(res){ res.id // 节点的ID res.dataset // 节点的dataset res.scrollLeft // 节点的水平滚动位置 res.scrollTop // 节点的竖直滚动位置 }).exec() } }) ``` */ scrollOffset( /** 回调函数,在执行 `SelectorQuery.exec` 方法后,节点信息会在 `callback` 中返回。 */ callback?: ScrollOffsetCallback, ): SelectorQuery; } interface RecorderManager { /** [RecorderManager.onError(function callback)](RecorderManager.onError.md) * * 监听录音错误事件 */ onError( /** 录音错误事件的回调函数 */ callback: RecorderManagerOnErrorCallback, ): void; /** [RecorderManager.onFrameRecorded(function callback)](RecorderManager.onFrameRecorded.md) * * 监听已录制完指定帧大小的文件事件。如果设置了 frameSize,则会回调此事件。 */ onFrameRecorded( /** 已录制完指定帧大小的文件事件的回调函数 */ callback: OnFrameRecordedCallback, ): void; /** [RecorderManager.onInterruptionBegin(function callback)](RecorderManager.onInterruptionBegin.md) * * 监听录音因为受到系统占用而被中断开始事件。以下场景会触发此事件:微信语音聊天、微信视频聊天。此事件触发后,录音会被暂停。pause 事件在此事件后触发 * * 最低基础库: `2.3.0` */ onInterruptionBegin( /** 录音因为受到系统占用而被中断开始事件的回调函数 */ callback: OnInterruptionBeginCallback, ): void; /** [RecorderManager.onInterruptionEnd(function callback)](RecorderManager.onInterruptionEnd.md) * * 监听录音中断结束事件。在收到 interruptionBegin 事件之后,小程序内所有录音会暂停,收到此事件之后才可再次录音成功。 * * 最低基础库: `2.3.0` */ onInterruptionEnd( /** 录音中断结束事件的回调函数 */ callback: OnInterruptionEndCallback, ): void; /** [RecorderManager.onPause(function callback)](RecorderManager.onPause.md) * * 监听录音暂停事件 */ onPause( /** 录音暂停事件的回调函数 */ callback: RecorderManagerOnPauseCallback, ): void; /** [RecorderManager.onResume(function callback)](RecorderManager.onResume.md) * * 监听录音继续事件 */ onResume( /** 录音继续事件的回调函数 */ callback: OnResumeCallback, ): void; /** [RecorderManager.onStart(function callback)](RecorderManager.onStart.md) * * 监听录音开始事件 */ onStart( /** 录音开始事件的回调函数 */ callback: OnStartCallback, ): void; /** [RecorderManager.onStop(function callback)](RecorderManager.onStop.md) * * 监听录音结束事件 */ onStop( /** 录音结束事件的回调函数 */ callback: RecorderManagerOnStopCallback, ): void; /** [RecorderManager.pause()](RecorderManager.pause.md) * * 暂停录音 */ pause(): void; /** [RecorderManager.resume()](RecorderManager.resume.md) * * 继续录音 */ resume(): void; /** [RecorderManager.start(Object object)](RecorderManager.start.md) * * 开始录音 * * **采样率与编码码率限制** * * * 每种采样率有对应的编码码率范围有效值,设置不合法的采样率或编码码率会导致录音失败,具体对应关系如下表。 * * | 采样率 | 编码码率 | * | ------ | -------------- | * | 8000 | 16000 ~ 48000 | * | 11025 | 16000 ~ 48000 | * | 12000 | 24000 ~ 64000 | * | 16000 | 24000 ~ 96000 | * | 22050 | 32000 ~ 128000 | * | 24000 | 32000 ~ 128000 | * | 32000 | 48000 ~ 192000 | * | 44100 | 64000 ~ 320000 | * | 48000 | 64000 ~ 320000 | */ start(option: RecorderManagerStartOption): void; /** [RecorderManager.stop()](RecorderManager.stop.md) * * 停止录音 */ stop(): void; } interface RequestTask { /** [RequestTask.abort()](RequestTask.abort.md) * * 中断请求任务 * * 最低基础库: `1.4.0` */ abort(): void; /** [RequestTask.offHeadersReceived(function callback)](RequestTask.offHeadersReceived.md) * * 取消监听 HTTP Response Header 事件 * * 最低基础库: `2.1.0` */ offHeadersReceived( /** HTTP Response Header 事件的回调函数 */ callback: RequestTaskOffHeadersReceivedCallback, ): void; /** [RequestTask.onHeadersReceived(function callback)](RequestTask.onHeadersReceived.md) * * 监听 HTTP Response Header 事件。会比请求完成事件更早 * * 最低基础库: `2.1.0` */ onHeadersReceived( /** HTTP Response Header 事件的回调函数 */ callback: RequestTaskOnHeadersReceivedCallback, ): void; } interface SelectorQuery { /** [[NodesRef](https://developers.weixin.qq.com/miniprogram/dev/api/wxml/NodesRef.html) SelectorQuery.exec(function callback)](SelectorQuery.exec.md) * * 执行所有的请求。请求结果按请求次序构成数组,在callback的第一个参数中返回。 */ exec( /** 回调函数 */ callback?: Function, ): NodesRef; /** [[NodesRef](https://developers.weixin.qq.com/miniprogram/dev/api/wxml/NodesRef.html) SelectorQuery.select(string selector)](SelectorQuery.select.md) * * 在当前页面下选择第一个匹配选择器 `selector` 的节点。返回一个 `NodesRef` 对象实例,可以用于获取节点信息。 * * **selector 语法** * * * selector类似于 CSS 的选择器,但仅支持下列语法。 * * - ID选择器:#the-id * - class选择器(可以连续指定多个):.a-class.another-class * - 子元素选择器:.the-parent > .the-child * - 后代选择器:.the-ancestor .the-descendant * - 跨自定义组件的后代选择器:.the-ancestor >>> .the-descendant * - 多选择器的并集:#a-node, .some-other-nodes */ select( /** 选择器 */ selector: string, ): NodesRef; /** [[NodesRef](https://developers.weixin.qq.com/miniprogram/dev/api/wxml/NodesRef.html) SelectorQuery.selectAll(string selector)](SelectorQuery.selectAll.md) * * 在当前页面下选择匹配选择器 selector 的所有节点。 * * **selector 语法** * * * selector类似于 CSS 的选择器,但仅支持下列语法。 * * - ID选择器:#the-id * - class选择器(可以连续指定多个):.a-class.another-class * - 子元素选择器:.the-parent > .the-child * - 后代选择器:.the-ancestor .the-descendant * - 跨自定义组件的后代选择器:.the-ancestor >>> .the-descendant * - 多选择器的并集:#a-node, .some-other-nodes */ selectAll( /** 选择器 */ selector: string, ): NodesRef; /** [[NodesRef](https://developers.weixin.qq.com/miniprogram/dev/api/wxml/NodesRef.html) SelectorQuery.selectViewport()](SelectorQuery.selectViewport.md) * * 选择显示区域。可用于获取显示区域的尺寸、滚动位置等信息。 */ selectViewport(): NodesRef; /** [[SelectorQuery](https://developers.weixin.qq.com/miniprogram/dev/api/wxml/SelectorQuery.html) SelectorQuery.in(Component component)](SelectorQuery.in.md) * * 将选择器的选取范围更改为自定义组件 `component` 内。(初始时,选择器仅选取页面范围的节点,不会选取任何自定义组件中的节点)。 * * **示例代码** * * * ```js Component({ queryMultipleNodes (){ const query = wx.createSelectorQuery().in(this) query.select('#the-id').boundingClientRect(function(res){ res.top // 这个组件内 #the-id 节点的上边界坐标 }).exec() } }) ``` * * 最低基础库: `1.6.0` */ in( /** 自定义组件实例 */ component: any, ): SelectorQuery; } interface SocketTask { /** [SocketTask.close(Object object)](SocketTask.close.md) * * 关闭 WebSocket 连接 */ close(option: CloseOption): void; /** [SocketTask.onClose(function callback)](SocketTask.onClose.md) * * 监听 WebSocket 连接关闭事件 */ onClose( /** WebSocket 连接关闭事件的回调函数 */ callback: OnCloseCallback, ): void; /** [SocketTask.onError(function callback)](SocketTask.onError.md) * * 监听 WebSocket 错误事件 */ onError( /** WebSocket 错误事件的回调函数 */ callback: SocketTaskOnErrorCallback, ): void; /** [SocketTask.onMessage(function callback)](SocketTask.onMessage.md) * * 监听 WebSocket 接受到服务器的消息事件 */ onMessage( /** WebSocket 接受到服务器的消息事件的回调函数 */ callback: SocketTaskOnMessageCallback, ): void; /** [SocketTask.onOpen(function callback)](SocketTask.onOpen.md) * * 监听 WebSocket 连接打开事件 */ onOpen( /** WebSocket 连接打开事件的回调函数 */ callback: OnOpenCallback, ): void; /** [SocketTask.send(Object object)](SocketTask.send.md) * * 通过 WebSocket 连接发送数据 */ send(option: SendOption): void; } interface Stats { /** [boolean Stats.isDirectory()](Stats.isDirectory.md) * * 判断当前文件是否一个目录 */ isDirectory(): boolean; /** [boolean Stats.isFile()](Stats.isFile.md) * * 判断当前文件是否一个普通文件 */ isFile(): boolean; } interface UpdateManager { /** [UpdateManager.applyUpdate()](UpdateManager.applyUpdate.md) * * 强制小程序重启并使用新版本。在小程序新版本下载完成后(即收到 `onUpdateReady` 回调)调用。 */ applyUpdate(): void; /** [UpdateManager.onCheckForUpdate(function callback)](UpdateManager.onCheckForUpdate.md) * * 监听向微信后台请求检查更新结果事件。微信在小程序冷启动时自动检查更新,不需由开发者主动触发。 */ onCheckForUpdate( /** 向微信后台请求检查更新结果事件的回调函数 */ callback: OnCheckForUpdateCallback, ): void; /** [UpdateManager.onUpdateFailed(function callback)](UpdateManager.onUpdateFailed.md) * * 监听小程序更新失败事件。小程序有新版本,客户端主动触发下载(无需开发者触发),下载失败(可能是网络原因等)后回调 */ onUpdateFailed( /** 小程序更新失败事件的回调函数 */ callback: OnUpdateFailedCallback, ): void; /** [UpdateManager.onUpdateReady(function callback)](UpdateManager.onUpdateReady.md) * * 监听小程序有版本更新事件。客户端主动触发下载(无需开发者触发),下载成功后回调 */ onUpdateReady( /** 小程序有版本更新事件的回调函数 */ callback: OnUpdateReadyCallback, ): void; } interface UploadTask { /** [UploadTask.abort()](UploadTask.abort.md) * * 中断上传任务 * * 最低基础库: `1.4.0` */ abort(): void; /** [UploadTask.offHeadersReceived(function callback)](UploadTask.offHeadersReceived.md) * * 取消监听 HTTP Response Header 事件 * * 最低基础库: `2.1.0` */ offHeadersReceived( /** HTTP Response Header 事件的回调函数 */ callback: UploadTaskOffHeadersReceivedCallback, ): void; /** [UploadTask.offProgressUpdate(function callback)](UploadTask.offProgressUpdate.md) * * 取消监听上传进度变化事件 * * 最低基础库: `2.1.0` */ offProgressUpdate( /** 上传进度变化事件的回调函数 */ callback: UploadTaskOffProgressUpdateCallback, ): void; /** [UploadTask.onHeadersReceived(function callback)](UploadTask.onHeadersReceived.md) * * 监听 HTTP Response Header 事件。会比请求完成事件更早 * * 最低基础库: `2.1.0` */ onHeadersReceived( /** HTTP Response Header 事件的回调函数 */ callback: UploadTaskOnHeadersReceivedCallback, ): void; /** [UploadTask.onProgressUpdate(function callback)](UploadTask.onProgressUpdate.md) * * 监听上传进度变化事件 * * 最低基础库: `1.4.0` */ onProgressUpdate( /** 上传进度变化事件的回调函数 */ callback: UploadTaskOnProgressUpdateCallback, ): void; } interface VideoContext { /** [VideoContext.exitFullScreen()](VideoContext.exitFullScreen.md) * * 退出全屏 * * 最低基础库: `1.4.0` */ exitFullScreen(): void; /** [VideoContext.hideStatusBar()](VideoContext.hideStatusBar.md) * * 隐藏状态栏,仅在iOS全屏下有效 * * 最低基础库: `2.1.0` */ hideStatusBar(): void; /** [VideoContext.pause()](VideoContext.pause.md) * * 暂停视频 */ pause(): void; /** [VideoContext.play()](VideoContext.play.md) * * 播放视频 */ play(): void; /** [VideoContext.playbackRate(number rate)](VideoContext.playbackRate.md) * * 设置倍速播放 * * 最低基础库: `1.4.0` */ playbackRate( /** 倍率,支持 0.5/0.8/1.0/1.25/1.5 */ rate: number, ): void; /** [VideoContext.requestFullScreen(Object object)](VideoContext.requestFullScreen.md) * * 进入全屏 * * 最低基础库: `1.4.0` */ requestFullScreen(option: VideoContextRequestFullScreenOption): void; /** [VideoContext.seek(number position)](VideoContext.seek.md) * * 跳转到指定位置 */ seek( /** 跳转到的位置,单位 s */ position: number, ): void; /** [VideoContext.sendDanmu(Object data)](VideoContext.sendDanmu.md) * * 发送弹幕 */ sendDanmu( /** 弹幕内容 */ data: Danmu, ): void; /** [VideoContext.showStatusBar()](VideoContext.showStatusBar.md) * * 显示状态栏,仅在iOS全屏下有效 * * 最低基础库: `2.1.0` */ showStatusBar(): void; /** [VideoContext.stop()](VideoContext.stop.md) * * 停止视频 * * 最低基础库: `1.7.0` */ stop(): void; } interface Worker { /** [Worker.onMessage(function callback)](Worker.onMessage.md) * * 监听主线程/Worker 线程向当前线程发送的消息的事件。 */ onMessage( /** 主线程/Worker 线程向当前线程发送的消息的事件的回调函数 */ callback: WorkerOnMessageCallback, ): void; /** [Worker.postMessage(Object message)](Worker.postMessage.md) * * 向主线程/Worker 线程发送的消息。 * * **示例代码** * * * worker 线程中 * ```js worker.postMessage({ msg: 'hello from worker' }) ``` * * 主线程中 * ```js const worker = wx.createWorker('workers/request/index.js') worker.postMessage({ msg: 'hello from main' }) ``` */ postMessage( /** 需要发送的消息,必须是一个可序列化的 JavaScript key-value 形式的对象。 */ message: object, ): void; /** [Worker.terminate()](Worker.terminate.md) * * 结束当前 Worker 线程。仅限在主线程 worker 对象上调用。 */ terminate(): void; } interface Wx { /** [Object wx.getAccountInfoSync()](wx.getAccountInfoSync.md) * * 获取当前帐号信息 * * **示例代码** * * * ```js const accountInfo = wx.getAccountInfoSync(); console.log(accountInfo.miniProgram.appId) // 小程序 appId console.log(accountInfo.plugin.appId) // 插件 appId console.log(accountInfo.plugin.version) // 插件版本号, 'a.b.c' 这样的形式 ``` * * 最低基础库: `2.2.2` */ getAccountInfoSync(): AccountInfo; /** [Object wx.getBatteryInfoSync()](https://developers.weixin.qq.com/miniprogram/dev/api/device/battery/wx.getBatteryInfoSync.html) * * [wx.getBatteryInfo](https://developers.weixin.qq.com/miniprogram/dev/api/device/battery/wx.getBatteryInfo.html) 的同步版本 */ getBatteryInfoSync(): GetBatteryInfoSyncResult; /** [Object wx.getExtConfigSync()](wx.getExtConfigSync.md) * * [wx.getExtConfig](https://developers.weixin.qq.com/miniprogram/dev/api/ext/wx.getExtConfig.html) 的同步版本。 * * **Tips** * * * 1. 本接口暂时无法通过 `wx.canIUse` 判断是否兼容,开发者需要自行判断 `wx.getExtConfigSync` 是否存在来兼容 * * **示例代码** * * ```js let extConfig = wx.getExtConfigSync? wx.getExtConfigSync(): {} console.log(extConfig) ``` * * 最低基础库: `1.1.0` */ getExtConfigSync(): ExtInfo; /** [Object wx.getLaunchOptionsSync()](wx.getLaunchOptionsSync.md) * * 获取小程序启动时的参数。与 [`App.onLaunch`]((app-service/app#onlaunchobject)) 的回调参数一致。 * * **返回有效 referrerInfo 的场景** * * * | 场景值 | 场景 | appId含义 | * | ------ | ------------------------------- | ---------- | * | 1020 | 公众号 profile 页相关小程序列表 | 来源公众号 | * | 1035 | 公众号自定义菜单 | 来源公众号 | * | 1036 | App 分享消息卡片 | 来源App | * | 1037 | 小程序打开小程序 | 来源小程序 | * | 1038 | 从另一个小程序返回 | 来源小程序 | * | 1043 | 公众号模板消息 | 来源公众号 | * * **注意** * * * 部分版本在无`referrerInfo`的时候会返回 `undefined`,建议使用 `options.referrerInfo && options.referrerInfo.appId` 进行判断。 * * 最低基础库: `2.1.2` */ getLaunchOptionsSync(): LaunchOptionsApp; /** [Object wx.getMenuButtonBoundingClientRect()](wx.getMenuButtonBoundingClientRect.md) * * 获取菜单按钮(右上角胶囊按钮)的布局位置信息。坐标信息以屏幕左上角为原点。 * * 最低基础库: `2.1.0` */ getMenuButtonBoundingClientRect(): Rect; /** [Object wx.getStorageInfoSync()](https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorageInfoSync.html) * * [wx.getStorageInfo](https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorageInfo.html) 的同步版本 * * **示例代码** * * * ```js wx.getStorageInfo({ success (res) { console.log(res.keys) console.log(res.currentSize) console.log(res.limitSize) } }) ``` * * ```js try { const res = wx.getStorageInfoSync() console.log(res.keys) console.log(res.currentSize) console.log(res.limitSize) } catch (e) { // Do something when catch error } ``` */ getStorageInfoSync(): GetStorageInfoSyncOption; /** [Object wx.getSystemInfoSync()](https://developers.weixin.qq.com/miniprogram/dev/api/system/system-info/wx.getSystemInfoSync.html) * * [wx.getSystemInfo](https://developers.weixin.qq.com/miniprogram/dev/api/system/system-info/wx.getSystemInfo.html) 的同步版本 * * **示例代码** * * * ```js wx.getSystemInfo({ success (res) { console.log(res.model) console.log(res.pixelRatio) console.log(res.windowWidth) console.log(res.windowHeight) console.log(res.language) console.log(res.version) console.log(res.platform) } }) ``` * * ```js try { const res = wx.getSystemInfoSync() console.log(res.model) console.log(res.pixelRatio) console.log(res.windowWidth) console.log(res.windowHeight) console.log(res.language) console.log(res.version) console.log(res.platform) } catch (e) { // Do something when catch error } ``` */ getSystemInfoSync(): GetSystemInfoSyncResult; /** [[Animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html) wx.createAnimation(Object object)](wx.createAnimation.md) * * 创建一个动画实例 [animation](https://developers.weixin.qq.com/miniprogram/dev/api/ui/animation/Animation.html)。调用实例的方法来描述动画。最后通过动画实例的 export 方法导出动画数据传递给组件的 animation 属性。 */ createAnimation(option: CreateAnimationOption): Animation; /** [[AudioContext](https://developers.weixin.qq.com/miniprogram/dev/api/media/audio/AudioContext.html) wx.createAudioContext(string id, Object this)](wx.createAudioContext.md) * * 创建 `audio` 上下文 `AudioContext` 对象。 */ createAudioContext( /** `<audio/>` 组件的 id */ id: string, /** 在自定义组件下,当前组件实例的this,以操作组件内 `<audio/>` 组件 */ component?: any, ): AudioContext; /** [[BackgroundAudioManager](https://developers.weixin.qq.com/miniprogram/dev/api/media/background-audio/BackgroundAudioManager.html) wx.getBackgroundAudioManager()](wx.getBackgroundAudioManager.md) * * 获取**全局唯一**的背景音频管理器。 * 小程序切入后台,如果音频处于播放状态,可以继续播放。但是后台状态不能通过调用API操纵音频的播放状态。 * * 从微信客户端6.7.2版本开始,若需要在小程序切后台后继续播放音频,需要在 [app.json]((全局配置)) 中配置 `requiredBackgroundModes` 属性。开发版和体验版上可以直接生效,正式版还需通过审核。 * * 最低基础库: `1.2.0` */ getBackgroundAudioManager(): BackgroundAudioManager; /** [[CameraContext](https://developers.weixin.qq.com/miniprogram/dev/api/media/camera/CameraContext.html) wx.createCameraContext()](wx.createCameraContext.md) * * 创建 `camera` 上下文 `CameraContext` 对象。 * * 最低基础库: `1.6.0` */ createCameraContext(): CameraContext; /** [[CanvasContext](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.html) wx.createCanvasContext(string canvasId, Object this)](wx.createCanvasContext.md) * * 创建 canvas 的绘图上下文 `CanvasContext` 对象 */ createCanvasContext( /** 要获取上下文的 `<canvas>` 组件 canvas-id 属性 */ canvasId: string, /** 在自定义组件下,当前组件实例的this,表示在这个自定义组件下查找拥有 canvas-id 的 `<canvas/>` ,如果省略则不在任何自定义组件内查找 */ component?: any, ): CanvasContext; /** [[DownloadTask](https://developers.weixin.qq.com/miniprogram/dev/api/network/download/DownloadTask.html) wx.downloadFile(Object object)](wx.downloadFile.md) * * 下载文件资源到本地。客户端直接发起一个 HTTPS GET 请求,返回文件的本地临时路径。使用前请注意阅读[相关说明]((network))。 * * 注意:请在服务端响应的 header 中指定合理的 `Content-Type` 字段,以保证客户端正确处理文件类型。 * * **示例代码** * * * ```js wx.downloadFile({ url: 'https://example.com/audio/123', //仅为示例,并非真实的资源 success (res) { // 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容 if (res.statusCode === 200) { wx.playVoice({ filePath: res.tempFilePath }) } } }) ``` */ downloadFile(option: DownloadFileOption): DownloadTask; /** [[FileSystemManager](https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.html) wx.getFileSystemManager()](wx.getFileSystemManager.md) * * 获取全局唯一的文件管理器 * * 最低基础库: `1.9.9` */ getFileSystemManager(): FileSystemManager; /** [[InnerAudioContext](https://developers.weixin.qq.com/miniprogram/dev/api/media/audio/InnerAudioContext.html) wx.createInnerAudioContext()](wx.createInnerAudioContext.md) * * 创建内部 `audio` 上下文 `InnerAudioContext` 对象。 * * 最低基础库: `1.6.0` */ createInnerAudioContext(): InnerAudioContext; /** [[IntersectionObserver](https://developers.weixin.qq.com/miniprogram/dev/api/wxml/IntersectionObserver.html) wx.createIntersectionObserver(Object this, Object options)](wx.createIntersectionObserver.md) * * 创建并返回一个 IntersectionObserver 对象实例。在自定义组件中,可以使用 `this.createIntersectionObserver([options])` 来代替。 * * **示例代码** * * * {% minicode('LAbMxkmI7F2A') %} * * 最低基础库: `1.9.3` */ createIntersectionObserver( /** 自定义组件实例 */ component: any, /** 选项 */ options: CreateIntersectionObserverOption, ): IntersectionObserver; /** [[IntersectionObserver](https://developers.weixin.qq.com/miniprogram/dev/api/wxml/IntersectionObserver.html) wx.createIntersectionObserver(Object this, Object options)](wx.createIntersectionObserver.md) * * 创建并返回一个 IntersectionObserver 对象实例。在自定义组件中,可以使用 `this.createIntersectionObserver([options])` 来代替。 * * **示例代码** * * * {% minicode('LAbMxkmI7F2A') %} * * 最低基础库: `1.9.3` */ createIntersectionObserver( /** 选项 */ options: CreateIntersectionObserverOption, ): IntersectionObserver; /** [[LivePlayerContext](https://developers.weixin.qq.com/miniprogram/dev/api/media/live/LivePlayerContext.html) wx.createLivePlayerContext(string id, Object this)](wx.createLivePlayerContext.md) * * 创建 `live-player` 上下文 `LivePlayerContext` 对象。 * * 最低基础库: `1.7.0` */ createLivePlayerContext( /** `<live-player/>` 组件的 id */ id: string, /** 在自定义组件下,当前组件实例的this,以操作组件内 `<live-player/>` 组件 */ component?: any, ): LivePlayerContext; /** [[LivePusherContext](https://developers.weixin.qq.com/miniprogram/dev/api/media/live/LivePusherContext.html) wx.createLivePusherContext()](wx.createLivePusherContext.md) * * 创建 `live-pusher` 上下文 `LivePusherContext` 对象。 * * 最低基础库: `1.7.0` */ createLivePusherContext(): LivePusherContext; /** [[LogManager](https://developers.weixin.qq.com/miniprogram/dev/api/debug/LogManager.html) wx.getLogManager(number level)](wx.getLogManager.md) * * 获取日志管理器对象。 * * **示例代码** * * * ```js const logger = wx.getLogManager() logger.log({str: 'hello world'}, 'basic log', 100, [1, 2, 3]) logger.info({str: 'hello world'}, 'info log', 100, [1, 2, 3]) logger.debug({str: 'hello world'}, 'debug log', 100, [1, 2, 3]) logger.warn({str: 'hello world'}, 'warn log', 100, [1, 2, 3]) ``` * * 最低基础库: `2.1.0` */ getLogManager( /** 取值为0/1,取值为0表示是否会把 `App`、`Page` 的生命周期函数和 `wx` 命名空间下的函数调用写入日志,取值为1则不会。默认值是 0 * * 最低基础库: `2.3.2` */ level?: number, ): LogManager; /** [[MapContext](https://developers.weixin.qq.com/miniprogram/dev/api/map/MapContext.html) wx.createMapContext(string mapId, Object this)](wx.createMapContext.md) * * 创建 `map` 上下文 `MapContext` 对象。 */ createMapContext( /** `<map/>` 组件的 id */ mapId: string, /** 在自定义组件下,当前组件实例的this,以操作组件内 `<map/>` 组件 */ component?: any, ): MapContext; /** [[RecorderManager](https://developers.weixin.qq.com/miniprogram/dev/api/media/recorder/RecorderManager.html) wx.getRecorderManager()](wx.getRecorderManager.md) * * 获取**全局唯一**的录音管理器 RecorderManager * * 最低基础库: `1.6.0` */ getRecorderManager(): RecorderManager; /** [[RequestTask](https://developers.weixin.qq.com/miniprogram/dev/api/network/request/RequestTask.html) wx.request(Object object)](wx.request.md) * * 发起 HTTPS 网络请求。使用前请注意阅读[相关说明]((network))。 * * **data 参数说明** * * * 最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String 。转换规则如下: * - 对于 `GET` 方法的数据,会将数据转换成 query string(`encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...`) * - 对于 `POST` 方法且 `header['content-type']` 为 `application/json` 的数据,会对数据进行 JSON 序列化 * - 对于 `POST` 方法且 `header['content-type']` 为 `application/x-www-form-urlencoded` 的数据,会将数据转换成 query string `(encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...)` * * **示例代码** * * * ```js wx.request({ url: 'test.php', //仅为示例,并非真实的接口地址 data: { x: '', y: '' }, header: { 'content-type': 'application/json' // 默认值 }, success (res) { console.log(res.data) } }) ``` */ request(option: RequestOption): RequestTask; /** [[SelectorQuery](https://developers.weixin.qq.com/miniprogram/dev/api/wxml/SelectorQuery.html) wx.createSelectorQuery()](wx.createSelectorQuery.md) * * 返回一个 SelectorQuery 对象实例。 * * **示例代码** * * * ```js const query = wx.createSelectorQuery() query.select('#the-id').boundingClientRect() query.selectViewport().scrollOffset() query.exec(function(res){ res[0].top // #the-id节点的上边界坐标 res[1].scrollTop // 显示区域的竖直滚动位置 }) ``` * * 最低基础库: `1.4.0` */ createSelectorQuery(): SelectorQuery; /** [[SocketTask](https://developers.weixin.qq.com/miniprogram/dev/api/network/websocket/SocketTask.html) wx.connectSocket(Object object)](wx.connectSocket.md) * * 创建一个 WebSocket 连接。使用前请注意阅读[相关说明]((network))。 * * **并发数** * * * - 1.7.0 及以上版本,最多可以同时存在 5(小游戏)/2(小程序)个 WebSocket 连接。 * - 1.7.0 以下版本,一个小程序同时只能有一个 WebSocket 连接,如果当前已存在一个 WebSocket 连接,会自动关闭该连接,并重新创建一个 WebSocket 连接。 * * **示例代码** * * * ```js wx.connectSocket({ url: 'wss://example.qq.com', data:{ x: '', y: '' }, header:{ 'content-type': 'application/json' }, protocols: ['protocol1'], method:"GET" }) ``` */ connectSocket(option: ConnectSocketOption): SocketTask; /** [[UpdateManager](https://developers.weixin.qq.com/miniprogram/dev/api/update/UpdateManager.html) wx.getUpdateManager()](wx.getUpdateManager.md) * * 获取**全局唯一**的版本更新管理器,用于管理小程序更新。关于小程序的更新机制,可以查看[运行机制]((operating-mechanism))文档。 * * 最低基础库: `1.9.90` */ getUpdateManager(): UpdateManager; /** [[UploadTask](https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/UploadTask.html) wx.uploadFile(Object object)](wx.uploadFile.md) * * 将本地资源上传到服务器。客户端发起一个 HTTPS POST 请求,其中 `content-type` 为 `multipart/form-data`。使用前请注意阅读[相关说明]((network))。 * * **示例代码** * * * ```js wx.chooseImage({ success (res) { const tempFilePaths = res.tempFilePaths wx.uploadFile({ url: 'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址 filePath: tempFilePaths[0], name: 'file', formData: { 'user': 'test' }, success (res){ const data = res.data //do something } }) } }) ``` */ uploadFile(option: UploadFileOption): UploadTask; /** [[VideoContext](https://developers.weixin.qq.com/miniprogram/dev/api/media/video/VideoContext.html) wx.createVideoContext(string id, Object this)](wx.createVideoContext.md) * * 创建 `video` 上下文 `VideoContext` 对象。 */ createVideoContext( /** `<video/>` 组件的 id */ id: string, /** 在自定义组件下,当前组件实例的this,以操作组件内 `<video/>` 组件 */ component?: any, ): VideoContext; /** [[Worker](https://developers.weixin.qq.com/miniprogram/dev/api/worker/wx.createWorker.html) wx.createWorker(string scriptPath)](wx.createWorker.md) * * 创建一个 [Worker 线程]((多线程 Worker))。目前限制最多只能创建一个 Worker,创建下一个 Worker 前请先调用 [Worker.terminate](https://developers.weixin.qq.com/miniprogram/dev/api/worker/Worker.terminate.html) * * 最低基础库: `1.9.90` */ createWorker( /** worker 入口文件的**绝对路径** */ scriptPath: string, ): Worker; /** [any wx.getStorageSync(string key)](https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorageSync.html) * * [wx.getStorage](https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorage.html) 的同步版本 * * **示例代码** * * * ```js wx.getStorage({ key: 'key', success (res) { console.log(res.data) } }) ``` * * ```js try { var value = wx.getStorageSync('key') if (value) { // Do something with return value } } catch (e) { // Do something when catch error } ``` */ getStorageSync( /** 本地缓存中指定的 key */ key: string, ): any; /** [boolean wx.canIUse(string schema)](wx.canIUse.md) * * 判断小程序的API,回调,参数,组件等是否在当前版本可用。 * * **参数说明** * * * - `${API}` 代表 API 名字 * - `${method}` 代表调用方式,有效值为return, success, object, callback * - `${param}` 代表参数或者返回值 * - `${options}` 代表参数的可选值 * - `${component}` 代表组件名字 * - `${attribute}` 代表组件属性 * - `${option}` 代表组件属性的可选值 * * **示例代码** * * * ```js wx.canIUse('openBluetoothAdapter') wx.canIUse('getSystemInfoSync.return.screenWidth') wx.canIUse('getSystemInfo.success.screenWidth') wx.canIUse('showToast.object.image') wx.canIUse('onCompassChange.callback.direction') wx.canIUse('request.object.method.GET') wx.canIUse('live-player') wx.canIUse('text.selectable') wx.canIUse('button.open-type.contact') ``` * * 最低基础库: `1.1.1` */ canIUse( /** 使用 `${API}.${method}.${param}.${options}` 或者 `${component}.${attribute}.${option}` 方式来调用 */ schema: string, ): boolean; /** [wx.addCard(Object object)](wx.addCard.md) * * 批量添加卡券。只有通过 [认证](https://developers.weixin.qq.com/miniprogram/product/renzheng.html) 的小程序才能使用。更多文档请参考 [微信卡券接口文档](https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&key=1490190158&version=1&lang=zh_CN&platform=2)。 * * **cardExt 说明** * * * cardExt 是卡券的扩展参数,其值是一个 JSON 字符串。 * * **示例代码** * * * ```js wx.addCard({ cardList: [ { cardId: '', cardExt: '{"code": "", "openid": "", "timestamp": "", "signature":""}' }, { cardId: '', cardExt: '{"code": "", "openid": "", "timestamp": "", "signature":""}' } ], success (res) { console.log(res.cardList) // 卡券添加结果 } }) ``` * * 最低基础库: `1.1.0` */ addCard(option: AddCardOption): void; /** [wx.addPhoneContact(Object object)](wx.addPhoneContact.md) * * 添加手机通讯录联系人。用户可以选择将该表单以「新增联系人」或「添加到已有联系人」的方式,写入手机系统通讯录。 * * 最低基础库: `1.2.0` */ addPhoneContact(option: AddPhoneContactOption): void; /** [wx.authorize(Object object)](wx.authorize.md) * * 提前向用户发起授权请求。调用后会立刻弹窗询问用户是否同意授权小程序使用某项功能或获取用户的某些数据,但不会实际调用对应接口。如果用户之前已经同意授权,则不会出现弹窗,直接返回成功。更多用法详见 [用户授权]((authorize))。 * * **示例代码** * * * ```js // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope wx.getSetting({ success(res) { if (!res.authSetting['scope.record']) { wx.authorize({ scope: 'scope.record', success () { // 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问 wx.startRecord() } }) } } }) ``` * * 最低基础库: `1.2.0` */ authorize(option: AuthorizeOption): void; /** [wx.canvasGetImageData(Object object, Object this)](wx.canvasGetImageData.md) * * 获取 canvas 区域隐含的像素数据。 * * **示例代码** * * * {% minicode('GlCRTlmS7n27') %} * * ```js wx.canvasGetImageData({ canvasId: 'myCanvas', x: 0, y: 0, width: 100, height: 100, success(res) { console.log(res.width) // 100 console.log(res.height) // 100 console.log(res.data instanceof Uint8ClampedArray) // true console.log(res.data.length) // 100 * 100 * 4 } }) ``` * * 最低基础库: `1.9.0` */ canvasGetImageData( option: CanvasGetImageDataOption, /** 在自定义组件下,当前组件实例的this,以操作组件内 `<canvas/>` 组件 */ component?: any, ): void; /** [wx.canvasPutImageData(Object object, Object this)](wx.canvasPutImageData.md) * * 将像素数据绘制到画布。在自定义组件下,第二个参数传入自定义组件实例 this,以操作组件内 <canvas> 组件 * * 最低基础库: `1.9.0` */ canvasPutImageData( option: CanvasPutImageDataOption, /** 在自定义组件下,当前组件实例的this,以操作组件内 `<canvas/>` 组件 */ component?: any, ): void; /** [wx.canvasToTempFilePath(Object object, Object this)](wx.canvasToTempFilePath.md) * * 把当前画布指定区域的内容导出生成指定大小的图片。在 `draw()` 回调里调用该方法才能保证图片导出成功。 */ canvasToTempFilePath( option: CanvasToTempFilePathOption, /** 在自定义组件下,当前组件实例的this,以操作组件内 `<canvas/>` 组件 */ component?: any, ): void; /** [wx.checkIsSoterEnrolledInDevice(Object object)](wx.checkIsSoterEnrolledInDevice.md) * * 获取设备内是否录入如指纹等生物信息的接口 * * **示例代码** * * * ```js wx.checkIsSoterEnrolledInDevice({ checkAuthMode: 'fingerPrint', success(res) { console.log(res.isEnrolled) } }) ``` * * 最低基础库: `1.6.0` */ checkIsSoterEnrolledInDevice( option: CheckIsSoterEnrolledInDeviceOption, ): void; /** [wx.checkIsSupportSoterAuthentication(Object object)](wx.checkIsSupportSoterAuthentication.md) * * 获取本机支持的 SOTER 生物认证方式 * * **示例代码** * * * ```js wx.checkIsSupportSoterAuthentication({ success(res) { // res.supportMode = [] 不具备任何被SOTER支持的生物识别方式 // res.supportMode = ['fingerPrint'] 只支持指纹识别 // res.supportMode = ['fingerPrint', 'facial'] 支持指纹识别和人脸识别 } }) ``` * * 最低基础库: `1.5.0` */ checkIsSupportSoterAuthentication( option?: CheckIsSupportSoterAuthenticationOption, ): void; /** [wx.checkSession(Object object)](wx.checkSession.md) * * 检查登录态是否过期。 * * 通过 wx.login 接口获得的用户登录态拥有一定的时效性。用户越久未使用小程序,用户登录态越有可能失效。反之如果用户一直在使用小程序,则用户登录态一直保持有效。具体时效逻辑由微信维护,对开发者透明。开发者只需要调用 wx.checkSession 接口检测当前用户登录态是否有效。 * * 登录态过期后开发者可以再调用 wx.login 获取新的用户登录态。调用成功说明当前 session_key 未过期,调用失败说明 session_key 已过期。更多使用方法详见 [小程序登录]((login))。 * * **示例代码** * * * ```js wx.checkSession({ success () { //session_key 未过期,并且在本生命周期一直有效 }, fail () { // session_key 已经失效,需要重新执行登录流程 wx.login() //重新登录 } }) ``` */ checkSession(option?: CheckSessionOption): void; /** [wx.chooseAddress(Object object)](wx.chooseAddress.md) * * 获取用户收货地址。调起用户编辑收货地址原生界面,并在编辑完成后返回用户选择的地址。 * * **示例代码** * * * {% minicode('024hHnmd772y') %} * ```js wx.chooseAddress({ success (res) { console.log(res.userName) console.log(res.postalCode) console.log(res.provinceName) console.log(res.cityName) console.log(res.countyName) console.log(res.detailInfo) console.log(res.nationalCode) console.log(res.telNumber) } }) ``` * * 最低基础库: `1.1.0` */ chooseAddress(option?: ChooseAddressOption): void; /** [wx.chooseImage(Object object)](wx.chooseImage.md) * * 从本地相册选择图片或使用相机拍照。 * * **示例代码** * * ```js wx.chooseImage({ count: 1, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success (res) { // tempFilePath可以作为img标签的src属性显示图片 const tempFilePaths = res.tempFilePaths } }) ``` */ chooseImage(option: ChooseImageOption): void; /** [wx.chooseInvoice(Object object)](wx.chooseInvoice.md) * * 选择用户已有的发票 * * **通过 cardId 和 encryptCode 获得报销发票的信息** * * * 请参考[微信电子发票文档](https://mp.weixin.qq.com/wiki?t=resource/res_main&id=21517918939oae3U)中,「查询报销发票信息」部分。 * 其中 `access_token` 的获取请参考[getAccessToken]((getAccessToken))文档 * * 最低基础库: `2.3.0` */ chooseInvoice(option?: ChooseInvoiceOption): void; /** [wx.chooseInvoiceTitle(Object object)](wx.chooseInvoiceTitle.md) * * 选择用户的发票抬头 * * **示例代码** * * * {% minicode('GJ4S9nmQ7x2E') %} * * ```js wx.chooseInvoiceTitle({ success(res) {} }) ``` * * 最低基础库: `1.5.0` */ chooseInvoiceTitle(option?: ChooseInvoiceTitleOption): void; /** [wx.chooseLocation(Object object)](wx.chooseLocation.md) * * 打开地图选择位置。 */ chooseLocation(option?: ChooseLocationOption): void; /** [wx.chooseVideo(Object object)](wx.chooseVideo.md) * * 拍摄视频或从手机相册中选视频。 * * **示例代码** * * * ```js wx.chooseVideo({ sourceType: ['album','camera'], maxDuration: 60, camera: 'back', success(res) { console.log(res.tempFilePath) } }) ``` */ chooseVideo(option: ChooseVideoOption): void; /** [wx.clearStorage(Object object)](wx.clearStorage.md) * * 清理本地数据缓存 * * **示例代码** * * * ```js wx.clearStorage() ``` * * ```js try { wx.clearStorageSync() } catch(e) { // Do something when catch error } ``` */ clearStorage(option?: ClearStorageOption): void; /** [wx.clearStorageSync()](https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.clearStorageSync.html) * * [wx.clearStorage](https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.clearStorage.html) 的同步版本 * * **示例代码** * * * ```js wx.clearStorage() ``` * * ```js try { wx.clearStorageSync() } catch(e) { // Do something when catch error } ``` */ clearStorageSync(): void; /** [wx.closeBLEConnection(Object object)](wx.closeBLEConnection.md) * * 断开与低功耗蓝牙设备的连接。 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * ```js wx.closeBLEConnection({ deviceId, success (res) { console.log(res) } }) ``` * * 最低基础库: `1.1.0` */ closeBLEConnection(option: CloseBLEConnectionOption): void; /** [wx.closeBluetoothAdapter(Object object)](wx.closeBluetoothAdapter.md) * * 关闭蓝牙模块。调用该方法将断开所有已建立的连接并释放系统资源。建议在使用蓝牙流程后,与 `wx.openBluetoothAdapter` 成对调用。 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * ```js wx.closeBluetoothAdapter({ success (res) { console.log(res) } }) ``` * * 最低基础库: `1.1.0` */ closeBluetoothAdapter(option?: CloseBluetoothAdapterOption): void; /** [wx.closeSocket(Object object)](wx.closeSocket.md) * * 关闭 WebSocket 连接 * * **示例代码** * * * ```js wx.connectSocket({ url: 'test.php' }) //注意这里有时序问题, //如果 wx.connectSocket 还没回调 wx.onSocketOpen,而先调用 wx.closeSocket,那么就做不到关闭 WebSocket 的目的。 //必须在 WebSocket 打开期间调用 wx.closeSocket 才能关闭。 wx.onSocketOpen(function() { wx.closeSocket() }) wx.onSocketClose(function(res) { console.log('WebSocket 已关闭!') }) ``` */ closeSocket(option: CloseSocketOption): void; /** [wx.compressImage(Object object)](wx.compressImage.md) * * 压缩图片接口,可选压缩质量 * * **示例代码** * * * ```js wx.compressImage({ src: '', // 图片路径 quality: 80 // 压缩质量 }) ``` * * 最低基础库: `2.4.0` */ compressImage(option: CompressImageOption): void; /** [wx.connectWifi(Object object)](wx.connectWifi.md) * * 连接 Wi-Fi。若已知 Wi-Fi 信息,可以直接利用该接口连接。仅 Android 与 iOS 11 以上版本支持。 * * **示例代码** * * * ```js wx.connectWifi({ SSID: '', BSSID: '', success (res) { console.log(res.errMsg) } }) ``` * * 最低基础库: `1.6.0` */ connectWifi(option: ConnectWifiOption): void; /** [wx.createBLEConnection(Object object)](wx.createBLEConnection.md) * * 连接低功耗蓝牙设备。 * * 若小程序在之前已有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备,无需进行搜索操作。 * * **注意** * * * - 请保证尽量成对的调用 `createBLEConnection` 和 `closeBLEConnection` 接口。安卓如果多次调用 `createBLEConnection` 创建连接,有可能导致系统持有同一设备多个连接的实例,导致调用 `closeBLEConnection` 的时候并不能真正的断开与设备的连接。 * - 蓝牙连接随时可能断开,建议监听 `wx.onBLEConnectionStateChange` 回调事件,当蓝牙设备断开时按需执行重连操作 * - 若对未连接的设备或已断开连接的设备调用数据读写操作的接口,会返回 10006 错误,建议进行重连操作。 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * ```js wx.createBLEConnection({ // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 deviceId, success (res) { console.log(res) } }) ``` * * 最低基础库: `1.1.0` */ createBLEConnection(option: CreateBLEConnectionOption): void; /** [wx.getAvailableAudioSources(Object object)](wx.getAvailableAudioSources.md) * * 获取当前支持的音频输入源 * * 最低基础库: `2.1.0` */ getAvailableAudioSources(option?: GetAvailableAudioSourcesOption): void; /** [wx.getBLEDeviceCharacteristics(Object object)](wx.getBLEDeviceCharacteristics.md) * * 获取蓝牙设备某个服务中所有特征值(characteristic)。 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * ```js wx.getBLEDeviceCharacteristics({ // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 deviceId, // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取 serviceId, success (res) { console.log('device getBLEDeviceCharacteristics:', res.characteristics) } }) ``` * * 最低基础库: `1.1.0` */ getBLEDeviceCharacteristics( option: GetBLEDeviceCharacteristicsOption, ): void; /** [wx.getBLEDeviceServices(Object object)](wx.getBLEDeviceServices.md) * * 获取蓝牙设备所有服务(service)。 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * ```js wx.getBLEDeviceServices({ // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 deviceId, success (res) { console.log('device services:', res.services) } }) ``` * * 最低基础库: `1.1.0` */ getBLEDeviceServices(option: GetBLEDeviceServicesOption): void; /** [wx.getBackgroundAudioPlayerState(Object object)](wx.getBackgroundAudioPlayerState.md) * * 获取后台音乐播放状态。 * * **示例代码** * * * ```js wx.getBackgroundAudioPlayerState({ success (res) { const status = res.status const dataUrl = res.dataUrl const currentPosition = res.currentPosition const duration = res.duration const downloadPercent = res.downloadPercent } }) ``` */ getBackgroundAudioPlayerState( option?: GetBackgroundAudioPlayerStateOption, ): void; /** [wx.getBatteryInfo(Object object)](wx.getBatteryInfo.md) * * 获取设备电量。同步 API [wx.getBatteryInfoSync](https://developers.weixin.qq.com/miniprogram/dev/api/device/battery/wx.getBatteryInfoSync.html) 在 iOS 上不可用。 */ getBatteryInfo(option?: GetBatteryInfoOption): void; /** [wx.getBeacons(Object object)](wx.getBeacons.md) * * 获取所有已搜索到的 iBeacon 设备 * * 最低基础库: `1.2.0` */ getBeacons(option?: GetBeaconsOption): void; /** [wx.getBluetoothAdapterState(Object object)](wx.getBluetoothAdapterState.md) * * 获取本机蓝牙适配器状态。 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * ```js wx.getBluetoothAdapterState({ success (res) { console.log(res) } }) ``` * * 最低基础库: `1.1.0` */ getBluetoothAdapterState(option?: GetBluetoothAdapterStateOption): void; /** [wx.getBluetoothDevices(Object object)](wx.getBluetoothDevices.md) * * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * * ```js // ArrayBuffer转16进度字符串示例 function ab2hex(buffer) { var hexArr = Array.prototype.map.call( new Uint8Array(buffer), function(bit) { return ('00' + bit.toString(16)).slice(-2) } ) return hexArr.join(''); } wx.getBluetoothDevices({ success: function (res) { console.log(res) if (res.devices[0]) { console.log(ab2hex(res.devices[0].advertisData)) } } }) ``` * * **注意事项** * * * - 该接口获取到的设备列表为**蓝牙模块生效期间所有搜索到的蓝牙设备**,若在蓝牙模块使用流程结束后未及时调用 `wx.closeBluetoothAdapter` 释放资源,会存在调用该接口会返回之前的蓝牙使用流程中搜索到的蓝牙设备,可能设备已经不在用户身边,无法连接。 * - 蓝牙设备在被搜索到时,系统返回的 name 字段一般为广播包中的 LocalName 字段中的设备名称,而如果与蓝牙设备建立连接,系统返回的 name 字段会改为从蓝牙设备上获取到的 `GattName`。若需要动态改变设备名称并展示,建议使用 `localName` 字段。 * * 最低基础库: `1.1.0` */ getBluetoothDevices(option?: GetBluetoothDevicesOption): void; /** [wx.getClipboardData(Object object)](wx.getClipboardData.md) * * 获取系统剪贴板的内容 * * **示例代码** * * * ```js wx.getClipboardData({ success (res){ console.log(res.data) } }) ``` * * 最低基础库: `1.1.0` */ getClipboardData(option?: GetClipboardDataOption): void; /** [wx.getConnectedBluetoothDevices(Object object)](wx.getConnectedBluetoothDevices.md) * * 根据 uuid 获取处于已连接状态的设备。 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * ```js wx.getConnectedBluetoothDevices({ success (res) { console.log(res) } }) ``` * * 最低基础库: `1.1.0` */ getConnectedBluetoothDevices( option: GetConnectedBluetoothDevicesOption, ): void; /** [wx.getConnectedWifi(Object object)](wx.getConnectedWifi.md) * * 获取已连接中的 Wi-Fi 信息。 * * 最低基础库: `1.6.0` */ getConnectedWifi(option?: GetConnectedWifiOption): void; /** [wx.getExtConfig(Object object)](wx.getExtConfig.md) * * 获取[第三方平台]((devtools/ext))自定义的数据字段。 * * **Tips** * * * 1. 本接口暂时无法通过 `wx.canIUse` 判断是否兼容,开发者需要自行判断 `wx.getExtConfig` 是否存在来兼容 * * **示例代码** * * ```js if (wx.getExtConfig) { wx.getExtConfig({ success (res) { console.log(res.extConfig) } }) } ``` * * 最低基础库: `1.1.0` */ getExtConfig(option?: GetExtConfigOption): void; /** [wx.getFileInfo(Object object)](wx.getFileInfo.md) * * 获取文件信息 * * **示例代码** * * * ```js wx.getFileInfo({ success (res) { console.log(res.size) console.log(res.digest) } }) ``` * * 最低基础库: `1.4.0` */ getFileInfo(option: WxGetFileInfoOption): void; /** [wx.getHCEState(Object object)](wx.getHCEState.md) * * 判断当前设备是否支持 HCE 能力。 * * **示例代码** * * * ```js wx.getHCEState({ success (res) { console.log(res.errCode) } }) ``` * * 最低基础库: `1.7.0` */ getHCEState(option?: GetHCEStateOption): void; /** [wx.getImageInfo(Object object)](wx.getImageInfo.md) * * 获取图片信息。网络图片需先配置download域名才能生效。 * * **示例代码** * * * {% minicode('Kd47Sbmr6yYu') %} * * ```js wx.getImageInfo({ src: 'images/a.jpg', success (res) { console.log(res.width) console.log(res.height) } }) wx.chooseImage({ success (res) { wx.getImageInfo({ src: res.tempFilePaths[0], success (res) { console.log(res.width) console.log(res.height) } }) } }) ``` */ getImageInfo(option: GetImageInfoOption): void; /** [wx.getLocation(Object object)](wx.getLocation.md) * * 获取当前的地理位置、速度。当用户离开小程序后,此接口无法调用。 * * **示例代码** * * * ```js wx.getLocation({ type: 'wgs84', success (res) { const latitude = res.latitude const longitude = res.longitude const speed = res.speed const accuracy = res.accuracy } }) ``` * * **注意** * * * - 工具中定位模拟使用IP定位,可能会有一定误差。且工具目前仅支持 gcj02 坐标。 * - 使用第三方服务进行逆地址解析时,请确认第三方服务默认的坐标系,正确进行坐标转换。 */ getLocation(option: GetLocationOption): void; /** [wx.getNetworkType(Object object)](wx.getNetworkType.md) * * 获取网络类型 * * **示例代码** * * * ```js wx.getNetworkType({ success (res) { const networkType = res.networkType } }) ``` */ getNetworkType(option?: GetNetworkTypeOption): void; /** [wx.getSavedFileInfo(Object object)](wx.getSavedFileInfo.md) * * 获取本地文件的文件信息。此接口只能用于获取已保存到本地的文件,若需要获取临时文件信息,请使用 [wx.getFileInfo()](https://developers.weixin.qq.com/miniprogram/dev/api/file/wx.getFileInfo.html) 接口。 * * **示例代码** * * * ```js wx.getSavedFileList({ success (res) { console.log(res.fileList) } }) ``` */ getSavedFileInfo(option: GetSavedFileInfoOption): void; /** [wx.getSavedFileList(Object object)](wx.getSavedFileList.md) * * 获取该小程序下已保存的本地缓存文件列表 * * **示例代码** * * * ```js wx.getSavedFileList({ success (res) { console.log(res.fileList) } }) ``` */ getSavedFileList(option?: WxGetSavedFileListOption): void; /** [wx.getScreenBrightness(Object object)](wx.getScreenBrightness.md) * * 获取屏幕亮度 * * **说明** * * * - 若安卓系统设置中开启了自动调节亮度功能,则屏幕亮度会根据光线自动调整,该接口仅能获取自动调节亮度之前的值,而非实时的亮度值。 * * 最低基础库: `1.2.0` */ getScreenBrightness(option?: GetScreenBrightnessOption): void; /** [wx.getSetting(Object object)](wx.getSetting.md) * * 获取用户的当前设置。**返回值中只会出现小程序已经向用户请求过的[权限](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/authorize/wx.authorize.html)**。 * * **示例代码** * * * ```js wx.getSetting({ success (res) { console.log(res.authSetting) // res.authSetting = { // "scope.userInfo": true, // "scope.userLocation": true // } } }) ``` * * 最低基础库: `1.2.0` */ getSetting(option?: GetSettingOption): void; /** [wx.getShareInfo(Object object)](wx.getShareInfo.md) * * 获取转发详细信息 * * **示例代码** * * * encryptedData 解密后为以下 json 结构,详见[加密数据解密算法]((开放数据校验与解密))。其中 openGId 为当前群的唯一标识 * * ```json { "openGId": "OPENGID" } ``` * * **Tips** * * * - 如需要展示群名称,可以使用[开放数据组件]((open-data)) * * 最低基础库: `1.1.0` */ getShareInfo(option: GetShareInfoOption): void; /** [wx.getStorage(Object object)](wx.getStorage.md) * * 从本地缓存中异步获取指定 key 的内容 * * **示例代码** * * * ```js wx.getStorage({ key: 'key', success (res) { console.log(res.data) } }) ``` * * ```js try { var value = wx.getStorageSync('key') if (value) { // Do something with return value } } catch (e) { // Do something when catch error } ``` */ getStorage(option: GetStorageOption): void; /** [wx.getStorageInfo(Object object)](wx.getStorageInfo.md) * * 异步获取当前storage的相关信息 * * **示例代码** * * * ```js wx.getStorageInfo({ success (res) { console.log(res.keys) console.log(res.currentSize) console.log(res.limitSize) } }) ``` * * ```js try { const res = wx.getStorageInfoSync() console.log(res.keys) console.log(res.currentSize) console.log(res.limitSize) } catch (e) { // Do something when catch error } ``` */ getStorageInfo(option?: GetStorageInfoOption): void; /** [wx.getSystemInfo(Object object)](wx.getSystemInfo.md) * * 获取系统信息 * * **示例代码** * * * ```js wx.getSystemInfo({ success (res) { console.log(res.model) console.log(res.pixelRatio) console.log(res.windowWidth) console.log(res.windowHeight) console.log(res.language) console.log(res.version) console.log(res.platform) } }) ``` * * ```js try { const res = wx.getSystemInfoSync() console.log(res.model) console.log(res.pixelRatio) console.log(res.windowWidth) console.log(res.windowHeight) console.log(res.language) console.log(res.version) console.log(res.platform) } catch (e) { // Do something when catch error } ``` */ getSystemInfo(option?: GetSystemInfoOption): void; /** [wx.getUserInfo(Object object)](wx.getUserInfo.md) * * 获取用户信息。 * * **接口调整说明** * * * 在用户未授权过的情况下调用此接口,将不再出现授权弹窗,会直接进入 fail 回调(详见[《公告》]({% postUrl(0000a26e1aca6012e896a517556c01) %}))。在用户已授权的情况下调用此接口,可成功获取用户信息。 * * **示例代码** * * * ```html * <!-- 如果只是展示用户头像昵称,可以使用 <open-data /> 组件 --> * <open-data type="userAvatarUrl"></open-data> * <open-data type="userNickName"></open-data> * <!-- 需要使用 button 来授权登录 --> * <button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授权登录</button> * <view wx:else>请升级微信版本</view> * ``` * * ```js Page({ data: { canIUse: wx.canIUse('button.open-type.getUserInfo') }, onLoad: function() { // 查看是否授权 wx.getSetting({ success (res){ if (res.authSetting['scope.userInfo']) { // 已经授权,可以直接调用 getUserInfo 获取头像昵称 wx.getUserInfo({ success: function(res) { console.log(res.userInfo) } }) } } }) }, bindGetUserInfo (e) { console.log(e.detail.userInfo) } }) ``` */ getUserInfo(option: GetUserInfoOption): void; /** [wx.getWeRunData(Object object)](wx.getWeRunData.md) * * 获取用户过去三十天微信运动步数。需要先调用 [wx.login](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html) 接口。步数信息会在用户主动进入小程序时更新。 * * **示例代码** * * * ```js wx.getWeRunData({ success (res) { const encryptedData = res.encryptedData } }) ``` * * **encryptedData 解密后 JSON 结构** * * * ```json { "stepInfoList": [ { "timestamp": 1445866601, "step": 100 }, { "timestamp": 1445876601, "step": 120 } ] } ``` * * stepInfoList 中,每一项结构如下: * * | 属性 | 类型 | 说明 | * | --- | ---- | --- | * | timestamp | number | 时间戳,表示数据对应的时间 | * | step | number | 微信运动步数 | * * 最低基础库: `1.2.0` */ getWeRunData(option?: GetWeRunDataOption): void; /** [wx.getWifiList(Object object)](wx.getWifiList.md) * * 请求获取 Wi-Fi 列表。在 `onGetWifiList` 注册的回调中返回 `wifiList` 数据。 * * iOS 将跳转到系统的 Wi-Fi 界面,Android 不会跳转。 iOS 11.0 及 iOS 11.1 两个版本因系统问题,该方法失效。但在 iOS 11.2 中已修复。 * * 最低基础库: `1.6.0` */ getWifiList(option?: GetWifiListOption): void; /** [wx.hideLoading(Object object)](wx.hideLoading.md) * * 隐藏 loading 提示框 * * 最低基础库: `1.1.0` */ hideLoading(option?: HideLoadingOption): void; /** [wx.hideNavigationBarLoading(Object object)](wx.hideNavigationBarLoading.md) * * 在当前页面隐藏导航条加载动画 */ hideNavigationBarLoading(option?: HideNavigationBarLoadingOption): void; /** [wx.hideShareMenu(Object object)](wx.hideShareMenu.md) * * 隐藏转发按钮 * * **示例代码** * * * ```js wx.hideShareMenu() ``` * * 最低基础库: `1.1.0` */ hideShareMenu(option?: HideShareMenuOption): void; /** [wx.hideTabBar(Object object)](wx.hideTabBar.md) * * 隐藏 tabBar * * 最低基础库: `1.9.0` */ hideTabBar(option: HideTabBarOption): void; /** [wx.hideTabBarRedDot(Object object)](wx.hideTabBarRedDot.md) * * 隐藏 tabBar 某一项的右上角的红点 * * 最低基础库: `1.9.0` */ hideTabBarRedDot(option: HideTabBarRedDotOption): void; /** [wx.hideToast(Object object)](wx.hideToast.md) * * 隐藏消息提示框 */ hideToast(option?: HideToastOption): void; /** [wx.loadFontFace(Object object)](wx.loadFontFace.md) * * 动态加载网络字体。文件地址需为下载类型。iOS 仅支持 https 格式文件地址。 * * 注意: * 1. 引入中文字体,体积过大时会发生错误,建议抽离出部分中文,减少体积,或者用图片替代 * 2. 字体链接必须是https(ios不支持http) * 3. 字体链接必须是同源下的,或开启了cors支持,小程序的域名是`servicewechat.com` * 4. canvas等原生组件不支持使用接口添加的字体 * 5. 工具里提示 Faild to load font可以忽略 * * **示例代码** * * * {% minicode('b6Zrajm67R2x') %} * ```js wx.loadFontFace({ family: 'Bitstream Vera Serif Bold', source: 'url("https://sungd.github.io/Pacifico.ttf")', success: console.log }) ``` * * 最低基础库: `2.1.0` */ loadFontFace(option: LoadFontFaceOption): void; /** [wx.login(Object object)](wx.login.md) * * 调用接口获取登录凭证(code)。通过凭证进而换取用户登录态信息,包括用户的唯一标识(openid)及本次登录的会话密钥(session_key)等。用户数据的加解密通讯需要依赖会话密钥完成。更多使用方法详见 [小程序登录]((login))。 * * **示例代码** * * * ```js wx.login({ success (res) { if (res.code) { //发起网络请求 wx.request({ url: 'https://test.com/onLogin', data: { code: res.code } }) } else { console.log('登录失败!' + res.errMsg) } } }) ``` */ login(option: LoginOption): void; /** [wx.makePhoneCall(Object object)](wx.makePhoneCall.md) * * 拨打电话 * * **示例代码** * * * ```js wx.makePhoneCall({ phoneNumber: '1340000' //仅为示例,并非真实的电话号码 }) ``` */ makePhoneCall(option: MakePhoneCallOption): void; /** [wx.navigateBack(Object object)](wx.navigateBack.md) * * 关闭当前页面,返回上一页面或多级页面。可通过 [getCurrentPages()]((页面路由#getcurrentpages)) 获取当前的页面栈,决定需要返回几层。 */ navigateBack(option: NavigateBackOption): void; /** [wx.navigateBackMiniProgram(Object object)](wx.navigateBackMiniProgram.md) * * 返回到上一个小程序。只有在当前小程序是被其他小程序打开时可以调用成功 * * 注意:**微信客户端 iOS 6.5.9,Android 6.5.10 及以上版本支持** * * **示例代码** * * * ```js wx.navigateBackMiniProgram({ extraData: { foo: 'bar' }, success(res) { // 返回成功 } }) ``` * * 最低基础库: `1.3.0` */ navigateBackMiniProgram(option: NavigateBackMiniProgramOption): void; /** [wx.navigateTo(Object object)](wx.navigateTo.md) * * 保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面。使用 [wx.navigateBack](https://developers.weixin.qq.com/miniprogram/dev/api/route/wx.navigateBack.html) 可以返回到原页面。 * * **示例代码** * * * * ```js wx.navigateTo({ url: 'test?id=1' }) ``` * * ```javascript //test.js Page({ onLoad: function(option){ console.log(option.query) } }) ``` */ navigateTo(option: NavigateToOption): void; /** [wx.navigateToMiniProgram(Object object)](wx.navigateToMiniProgram.md) * * 打开另一个小程序 * * **使用限制** * * * ##### 需要用户触发跳转 * 从 2.3.0 版本开始,若用户未点击小程序页面任意位置,则开发者将无法调用此接口自动跳转至其他小程序。 * ##### 需要用户确认跳转 * 从 2.3.0 版本开始,在跳转至其他小程序前,将统一增加弹窗,询问是否跳转,用户确认后才可以跳转其他小程序。如果用户点击取消,则回调 `fail cancel`。 * ##### 每个小程序可跳转的其他小程序数量限制为不超过 10 个 * 从 2.4.0 版本以及指定日期(具体待定)开始,开发者提交新版小程序代码时,如使用了跳转其他小程序功能,则需要在代码配置中声明将要跳转的小程序名单,限定不超过 10 个,否则将无法通过审核。该名单可在发布新版时更新,不支持动态修改。配置方法详见 [配置]((config))。调用此接口时,所跳转的 appId 必须在配置列表中,否则回调 `fail appId "${appId}" is not in navigateToMiniProgramAppIdList`。 * * **关于调试** * * * - 在开发者工具上调用此 API 并不会真实的跳转到另外的小程序,但是开发者工具会校验本次调用跳转是否成功。[详情](https://developers.weixin.qq.com/miniprogram/dev/devtools/different.html#跳转小程序调试支持) * - 开发者工具上支持被跳转的小程序处理接收参数的调试。[详情](https://developers.weixin.qq.com/miniprogram/dev/devtools/different.html#跳转小程序调试支持) * * **示例代码** * * * ```js wx.navigateToMiniProgram({ appId: '', path: 'page/index/index?id=123', extraData: { foo: 'bar' }, envVersion: 'develop', success(res) { // 打开成功 } }) ``` * * 最低基础库: `[object Object]` */ navigateToMiniProgram(option: NavigateToMiniProgramOption): void; /** [wx.nextTick(function callback)](wx.nextTick.md) * * 延迟一部分操作到下一个时间片再执行。(类似于 setTimeout) * * **说明** * * * * 因为自定义组件中的 setData 和 triggerEvent 等接口本身是同步的操作,当这几个接口被连续调用时,都是在一个同步流程中执行完的,因此若逻辑不当可能会导致出错。 * * 一个极端的案例:当父组件的 setData 引发了子组件的 triggerEvent,进而使得父组件又进行了一次 setData,期间有通过 wx:if 语句对子组件进行卸载,就有可能引发奇怪的错误,所以对于不需要在一个同步流程内完成的逻辑,可以使用此接口延迟到下一个时间片再执行。 * * 最低基础库: `2.2.3` */ nextTick(callback: Function): void; /** [wx.notifyBLECharacteristicValueChange(Object object)](wx.notifyBLECharacteristicValueChange.md) * * 启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。注意:必须设备的特征值支持 notify 或者 indicate 才可以成功调用。 * * 另外,必须先启用 `notifyBLECharacteristicValueChange` 才能监听到设备 `characteristicValueChange` 事件 * * **注意** * * * - 订阅操作成功后需要设备主动更新特征值的 value,才会触发 `wx.onBLECharacteristicValueChange` 回调。 * - 安卓平台上,在调用 `notifyBLECharacteristicValueChange` 成功后立即调用 `writeBLECharacteristicValue` 接口,在部分机型上会发生 10008 系统错误 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * ```js wx.notifyBLECharacteristicValueChange({ state: true, // 启用 notify 功能 // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 deviceId, // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取 serviceId, // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取 characteristicId, success (res) { console.log('notifyBLECharacteristicValueChange success', res.errMsg) } }) ``` * * 最低基础库: `1.1.0` */ notifyBLECharacteristicValueChange( option: NotifyBLECharacteristicValueChangeOption, ): void; /** [wx.offAppHide(function callback)](wx.offAppHide.md) * * 取消监听小程序切后台事件 * * 最低基础库: `2.1.2` */ offAppHide( /** 小程序切后台事件的回调函数 */ callback: OffAppHideCallback, ): void; /** [wx.offAppShow(function callback)](wx.offAppShow.md) * * 取消监听小程序切前台事件 * * 最低基础库: `2.1.2` */ offAppShow( /** 小程序切前台事件的回调函数 */ callback: OffAppShowCallback, ): void; /** [wx.offError(function callback)](wx.offError.md) * * 取消监听小程序错误事件。 * * 最低基础库: `2.1.2` */ offError( /** 小程序错误事件的回调函数 */ callback: Function, ): void; /** [wx.offLocalServiceDiscoveryStop(function callback)](wx.offLocalServiceDiscoveryStop.md) * * 取消监听 mDNS 服务停止搜索的事件 * * 最低基础库: `2.4.0` */ offLocalServiceDiscoveryStop( /** mDNS 服务停止搜索的事件的回调函数 */ callback: OffLocalServiceDiscoveryStopCallback, ): void; /** [wx.offLocalServiceFound(function callback)](wx.offLocalServiceFound.md) * * 取消监听 mDNS 服务发现的事件 * * 最低基础库: `2.4.0` */ offLocalServiceFound( /** mDNS 服务发现的事件的回调函数 */ callback: OffLocalServiceFoundCallback, ): void; /** [wx.offLocalServiceLost(function callback)](wx.offLocalServiceLost.md) * * 取消监听 mDNS 服务离开的事件 * * 最低基础库: `2.4.0` */ offLocalServiceLost( /** mDNS 服务离开的事件的回调函数 */ callback: OffLocalServiceLostCallback, ): void; /** [wx.offLocalServiceResolveFail(function callback)](wx.offLocalServiceResolveFail.md) * * 取消监听 mDNS 服务解析失败的事件 * * 最低基础库: `2.4.0` */ offLocalServiceResolveFail( /** mDNS 服务解析失败的事件的回调函数 */ callback: OffLocalServiceResolveFailCallback, ): void; /** [wx.offPageNotFound(function callback)](wx.offPageNotFound.md) * * 取消监听小程序要打开的页面不存在事件 * * 最低基础库: `2.1.2` */ offPageNotFound( /** 小程序要打开的页面不存在事件的回调函数 */ callback: OffPageNotFoundCallback, ): void; /** [wx.offWindowResize(function callback)](wx.offWindowResize.md) * * 取消监听窗口尺寸变化事件 * * 最低基础库: `2.3.0` */ offWindowResize( /** 窗口尺寸变化事件的回调函数 */ callback: OffWindowResizeCallback, ): void; /** [wx.onAccelerometerChange(function callback)](wx.onAccelerometerChange.md) * * 监听加速度数据事件。频率根据 [wx.startAccelerometer()](https://developers.weixin.qq.com/miniprogram/dev/api/device/accelerometer/wx.startAccelerometer.html) 的 interval 参数。可使用 [wx.stopAccelerometer()](https://developers.weixin.qq.com/miniprogram/dev/api/device/accelerometer/wx.stopAccelerometer.html) 停止监听。 * * **示例代码** * * * ```js wx.onAccelerometerChange(function (res) { console.log(res.x) console.log(res.y) console.log(res.z) }) ``` */ onAccelerometerChange( /** 加速度数据事件的回调函数 */ callback: OnAccelerometerChangeCallback, ): void; /** [wx.onAppHide(function callback)](wx.onAppHide.md) * * 监听小程序切后台事件。该事件与 [`App.onHide`]((app-service/app#onhide)) 的回调时机一致。 * * 最低基础库: `2.1.2` */ onAppHide( /** 小程序切后台事件的回调函数 */ callback: OnAppHideCallback, ): void; /** [wx.onAppShow(function callback)](wx.onAppShow.md) * * 监听小程序切前台事件。该事件与 [`App.onShow`]((app-service/app#onshowobject)) 的回调参数一致。 * * **返回有效 referrerInfo 的场景** * * * | 场景值 | 场景 | appId含义 | * | ------ | ------------------------------- | ---------- | * | 1020 | 公众号 profile 页相关小程序列表 | 来源公众号 | * | 1035 | 公众号自定义菜单 | 来源公众号 | * | 1036 | App 分享消息卡片 | 来源App | * | 1037 | 小程序打开小程序 | 来源小程序 | * | 1038 | 从另一个小程序返回 | 来源小程序 | * | 1043 | 公众号模板消息 | 来源公众号 | * * **注意** * * * 部分版本在无`referrerInfo`的时候会返回 `undefined`,建议使用 `options.referrerInfo && options.referrerInfo.appId` 进行判断。 * * 最低基础库: `2.1.2` */ onAppShow( /** 小程序切前台事件的回调函数 */ callback: OnAppShowCallback, ): void; /** [wx.onBLECharacteristicValueChange(function callback)](wx.onBLECharacteristicValueChange.md) * * 监听低功耗蓝牙设备的特征值变化事件。必须先启用 `notifyBLECharacteristicValueChange` 接口才能接收到设备推送的 notification。 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * * ```js // ArrayBuffer转16进度字符串示例 function ab2hex(buffer) { let hexArr = Array.prototype.map.call( new Uint8Array(buffer), function(bit) { return ('00' + bit.toString(16)).slice(-2) } ) return hexArr.join(''); } wx.onBLECharacteristicValueChange(function(res) { console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`) console.log(ab2hex(res.value)) }) ``` * * 最低基础库: `1.1.0` */ onBLECharacteristicValueChange( /** 低功耗蓝牙设备的特征值变化事件的回调函数 */ callback: OnBLECharacteristicValueChangeCallback, ): void; /** [wx.onBLEConnectionStateChange(function callback)](wx.onBLEConnectionStateChange.md) * * 监听低功耗蓝牙连接状态的改变事件。包括开发者主动连接或断开连接,设备丢失,连接异常断开等等 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * ```js wx.onBLEConnectionStateChange(function(res) { // 该方法回调中可以用于处理连接意外断开等异常情况 console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`) }) ``` * * 最低基础库: `1.1.1` */ onBLEConnectionStateChange( /** 低功耗蓝牙连接状态的改变事件的回调函数 */ callback: OnBLEConnectionStateChangeCallback, ): void; /** [wx.onBackgroundAudioPause(function callback)](wx.onBackgroundAudioPause.md) * * 监听音乐暂停事件。 */ onBackgroundAudioPause( /** 音乐暂停事件的回调函数 */ callback: OnBackgroundAudioPauseCallback, ): void; /** [wx.onBackgroundAudioPlay(function callback)](wx.onBackgroundAudioPlay.md) * * 监听音乐播放事件。 */ onBackgroundAudioPlay( /** 音乐播放事件的回调函数 */ callback: OnBackgroundAudioPlayCallback, ): void; /** [wx.onBackgroundAudioStop(function callback)](wx.onBackgroundAudioStop.md) * * 监听音乐停止事件。 */ onBackgroundAudioStop( /** 音乐停止事件的回调函数 */ callback: OnBackgroundAudioStopCallback, ): void; /** [wx.onBeaconServiceChange(function callback)](wx.onBeaconServiceChange.md) * * 监听 iBeacon 服务状态变化事件 * * 最低基础库: `1.2.0` */ onBeaconServiceChange( /** iBeacon 服务状态变化事件的回调函数 */ callback: OnBeaconServiceChangeCallback, ): void; /** [wx.onBeaconUpdate(function callback)](wx.onBeaconUpdate.md) * * 监听 iBeacon 设备更新事件 * * 最低基础库: `1.2.0` */ onBeaconUpdate( /** iBeacon 设备更新事件的回调函数 */ callback: OnBeaconUpdateCallback, ): void; /** [wx.onBluetoothAdapterStateChange(function callback)](wx.onBluetoothAdapterStateChange.md) * * 监听蓝牙适配器状态变化事件 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * ```js wx.onBluetoothAdapterStateChange(function (res) { console.log('adapterState changed, now is', res) }) ``` * * 最低基础库: `1.1.0` */ onBluetoothAdapterStateChange( /** 蓝牙适配器状态变化事件的回调函数 */ callback: OnBluetoothAdapterStateChangeCallback, ): void; /** [wx.onBluetoothDeviceFound(function callback)](wx.onBluetoothDeviceFound.md) * * 监听寻找到新设备的事件 * * **注意** * * * - 若在 `wx.onBluetoothDeviceFound` 回调了某个设备,则此设备会添加到 `wx.getBluetoothDevices` 接口获取到的数组中。 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * * ```js // ArrayBuffer转16进度字符串示例 function ab2hex(buffer) { var hexArr = Array.prototype.map.call( new Uint8Array(buffer), function(bit) { return ('00' + bit.toString(16)).slice(-2) } ) return hexArr.join(''); } wx.onBluetoothDeviceFound(function(devices) { console.log('new device list has founded') console.dir(devices) console.log(ab2hex(devices[0].advertisData)) }) ``` * * 最低基础库: `1.1.0` */ onBluetoothDeviceFound( /** 寻找到新设备的事件的回调函数 */ callback: OnBluetoothDeviceFoundCallback, ): void; /** [wx.onCompassChange(function callback)](wx.onCompassChange.md) * * 监听罗盘数据变化事件。频率:5 次/秒,接口调用后会自动开始监听,可使用 wx.stopCompass 停止监听。 * * **accuracy 在 iOS/Android 的差异** * * * 由于平台差异,accuracy 在 iOS/Android 的值不同。 * * - iOS:accuracy 是一个 number 类型的值,表示相对于磁北极的偏差。0 表示设备指向磁北,90 表示指向东,180 表示指向南,依此类推。 * - Android:accuracy 是一个 string 类型的枚举值。 * * | 值 | 说明 | * | --------------- | -------------------------------------------------------------------------------------- | * | high | 高精度 | * | medium | 中等精度 | * | low | 低精度 | * | no-contact | 不可信,传感器失去连接 | * | unreliable | 不可信,原因未知 | * | unknow ${value} | 未知的精度枚举值,即该 Android 系统此时返回的表示精度的 value 不是一个标准的精度枚举值 | */ onCompassChange( /** 罗盘数据变化事件的回调函数 */ callback: OnCompassChangeCallback, ): void; /** [wx.onDeviceMotionChange(function callback)](wx.onDeviceMotionChange.md) * * 监听设备方向变化事件。频率根据 [wx.startDeviceMotionListening()](https://developers.weixin.qq.com/miniprogram/dev/api/device/motion/wx.startDeviceMotionListening.html) 的 interval 参数。可以使用 [wx.stopDeviceMotionListening()](https://developers.weixin.qq.com/miniprogram/dev/api/device/motion/wx.stopDeviceMotionListening.html) 停止监听。 * * 最低基础库: `2.3.0` */ onDeviceMotionChange( /** 设备方向变化事件的回调函数 */ callback: OnDeviceMotionChangeCallback, ): void; /** [wx.onError(function callback)](wx.onError.md) * * 监听小程序错误事件。如脚本错误或 API 调用报错等。该事件与 [`App.onError`]((app-service/app#onerrorstring-error)) 的回调时机与参数一致。 * * 最低基础库: `2.1.2` */ onError( /** 小程序错误事件的回调函数 */ callback: OnAppErrorCallback, ): void; /** [wx.onGetWifiList(function callback)](wx.onGetWifiList.md) * * 监听获取到 Wi-Fi 列表数据事件 * * 最低基础库: `1.6.0` */ onGetWifiList( /** 获取到 Wi-Fi 列表数据事件的回调函数 */ callback: OnGetWifiListCallback, ): void; /** [wx.onGyroscopeChange(function callback)](wx.onGyroscopeChange.md) * * 监听陀螺仪数据变化事件。频率根据 [wx.startGyroscope()](https://developers.weixin.qq.com/miniprogram/dev/api/device/gyroscope/wx.startGyroscope.html) 的 interval 参数。可以使用 [wx.stopGyroscope()](https://developers.weixin.qq.com/miniprogram/dev/api/device/gyroscope/wx.stopGyroscope.html) 停止监听。 * * 最低基础库: `2.3.0` */ onGyroscopeChange( /** 陀螺仪数据变化事件的回调函数 */ callback: OnGyroscopeChangeCallback, ): void; /** [wx.onHCEMessage(function callback)](wx.onHCEMessage.md) * * 监听接收 NFC 设备消息事件 * * 最低基础库: `1.7.0` */ onHCEMessage( /** 接收 NFC 设备消息事件的回调函数 */ callback: OnHCEMessageCallback, ): void; /** [wx.onLocalServiceDiscoveryStop(function callback)](wx.onLocalServiceDiscoveryStop.md) * * 监听 mDNS 服务停止搜索的事件 * * 最低基础库: `2.4.0` */ onLocalServiceDiscoveryStop( /** mDNS 服务停止搜索的事件的回调函数 */ callback: OnLocalServiceDiscoveryStopCallback, ): void; /** [wx.onLocalServiceFound(function callback)](wx.onLocalServiceFound.md) * * 监听 mDNS 服务发现的事件 * * 最低基础库: `2.4.0` */ onLocalServiceFound( /** mDNS 服务发现的事件的回调函数 */ callback: OnLocalServiceFoundCallback, ): void; /** [wx.onLocalServiceLost(function callback)](wx.onLocalServiceLost.md) * * 监听 mDNS 服务离开的事件 * * 最低基础库: `2.4.0` */ onLocalServiceLost( /** mDNS 服务离开的事件的回调函数 */ callback: OnLocalServiceLostCallback, ): void; /** [wx.onLocalServiceResolveFail(function callback)](wx.onLocalServiceResolveFail.md) * * 监听 mDNS 服务解析失败的事件 * * 最低基础库: `2.4.0` */ onLocalServiceResolveFail( /** mDNS 服务解析失败的事件的回调函数 */ callback: OnLocalServiceResolveFailCallback, ): void; /** [wx.onMemoryWarning(function callback)](wx.onMemoryWarning.md) * * 监听内存不足告警事件。 * * 当 iOS/Android 向小程序进程发出内存警告时,触发该事件。触发该事件不意味小程序被杀,大部分情况下仅仅是告警,开发者可在收到通知后回收一些不必要资源避免进一步加剧内存紧张。 * * **示例代码** * * * ```js * wx.onMemoryWarning(function () { * console.log('onMemoryWarningReceive') * }) * `` * * 最低基础库: `2.0.2` */ onMemoryWarning( /** 内存不足告警事件的回调函数 */ callback: OnMemoryWarningCallback, ): void; /** [wx.onNetworkStatusChange(function callback)](wx.onNetworkStatusChange.md) * * 监听网络状态变化事件 * * **示例代码** * * * ```js wx.onNetworkStatusChange(function (res) { console.log(res.isConnected) console.log(res.networkType) }) ``` * * 最低基础库: `1.1.0` */ onNetworkStatusChange( /** 网络状态变化事件的回调函数 */ callback: OnNetworkStatusChangeCallback, ): void; /** [wx.onPageNotFound(function callback)](wx.onPageNotFound.md) * * 监听小程序要打开的页面不存在事件。该事件与 [`App.onPageNotFound`]((app-service/app#onpagenotfoundobject)) 的回调时机一致。 * * **注意** * * * - 开发者可以在回调中进行页面重定向,但必须在回调中**同步**处理,异步处理(例如 `setTimeout` 异步执行)无效。 * - 若开发者没有调用 `wx.onPageNotFound` 绑定监听,也没有声明 `App.onPageNotFound`,当跳转页面不存在时,将推入微信客户端原生的页面不存在提示页面。 * - 如果回调中又重定向到另一个不存在的页面,将推入微信客户端原生的页面不存在提示页面,并且不再第二次回调。 * * 最低基础库: `2.1.2` */ onPageNotFound( /** 小程序要打开的页面不存在事件的回调函数 */ callback: OnPageNotFoundCallback, ): void; /** [wx.onSocketClose(function callback)](wx.onSocketClose.md) * * 监听 WebSocket 连接关闭事件 */ onSocketClose( /** WebSocket 连接关闭事件的回调函数 */ callback: OnSocketCloseCallback, ): void; /** [wx.onSocketError(function callback)](wx.onSocketError.md) * * 监听 WebSocket 错误事件 */ onSocketError( /** WebSocket 错误事件的回调函数 */ callback: OnSocketErrorCallback, ): void; /** [wx.onSocketMessage(function callback)](wx.onSocketMessage.md) * * 监听 WebSocket 接受到服务器的消息事件 */ onSocketMessage( /** WebSocket 接受到服务器的消息事件的回调函数 */ callback: OnSocketMessageCallback, ): void; /** [wx.onSocketOpen(function callback)](wx.onSocketOpen.md) * * 监听 WebSocket 连接打开事件 */ onSocketOpen( /** WebSocket 连接打开事件的回调函数 */ callback: OnSocketOpenCallback, ): void; /** [wx.onUserCaptureScreen(function callback)](wx.onUserCaptureScreen.md) * * 监听用户主动截屏事件。用户使用系统截屏按键截屏时触发 * * **示例代码** * * * ```js wx.onUserCaptureScreen(function (res) { console.log('用户截屏了') }) ``` * * 最低基础库: `1.4.0` */ onUserCaptureScreen( /** 用户主动截屏事件的回调函数 */ callback: OnUserCaptureScreenCallback, ): void; /** [wx.onWifiConnected(function callback)](wx.onWifiConnected.md) * * 监听连接上 Wi-Fi 的事件 * * 最低基础库: `1.6.0` */ onWifiConnected( /** 连接上 Wi-Fi 的事件的回调函数 */ callback: OnWifiConnectedCallback, ): void; /** [wx.onWindowResize(function callback)](wx.onWindowResize.md) * * 监听窗口尺寸变化事件 * * 最低基础库: `2.3.0` */ onWindowResize( /** 窗口尺寸变化事件的回调函数 */ callback: OnWindowResizeCallback, ): void; /** [wx.openBluetoothAdapter(Object object)](wx.openBluetoothAdapter.md) * * 初始化蓝牙模块 * * **注意** * * * - 其他蓝牙相关 API 必须在 `wx.openBluetoothAdapter` 调用之后使用。否则 API 会返回错误(errCode=10000)。 * - 在用户蓝牙开关未开启或者手机不支持蓝牙功能的情况下,调用 `wx.openBluetoothAdapter` 会返回错误(errCode=10001),表示手机蓝牙功能不可用。此时小程序蓝牙模块已经初始化完成,可通过 `wx.onBluetoothAdapterStateChange` 监听手机蓝牙状态的改变,也可以调用蓝牙模块的所有API。 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * ```js wx.openBluetoothAdapter({ success (res) { console.log(res) } }) ``` * * 最低基础库: `1.1.0` */ openBluetoothAdapter(option?: OpenBluetoothAdapterOption): void; /** [wx.openCard(Object object)](wx.openCard.md) * * 查看微信卡包中的卡券。只有通过 [认证](https://developers.weixin.qq.com/miniprogram/product/renzheng.html) 的小程序才能使用。更多文档请参考 [微信卡券接口文档](https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&key=1490190158&version=1&lang=zh_CN&platform=2)。 * * **示例代码** * * * ```js wx.openCard({ cardList: [{ cardId: '', code: '' }, { cardId: '', code: '' }], success (res) { } }) ``` * * 最低基础库: `1.1.0` */ openCard(option: OpenCardOption): void; /** [wx.openDocument(Object object)](wx.openDocument.md) * * 新开页面打开文档 */ openDocument(option: OpenDocumentOption): void; /** [wx.openLocation(Object object)](wx.openLocation.md) * * 使用微信内置地图查看位置 * * **示例代码** * * * ```js wx.getLocation({ type: 'gcj02', //返回可以用于wx.openLocation的经纬度 success (res) { const latitude = res.latitude const longitude = res.longitude wx.openLocation({ latitude, longitude, scale: 18 }) } }) ``` */ openLocation(option: OpenLocationOption): void; /** [wx.openSetting(Object object)](wx.openSetting.md) * * 调起客户端小程序设置界面,返回用户设置的操作结果。**设置界面只会出现小程序已经向用户请求过的[权限](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/authorize/wx.authorize.html)**。 * * * 注意:{% version(2.3.0) %} 版本开始,用户发生点击行为后,才可以跳转打开设置页,管理授权信息。[详情]({% postUrl(000cea2305cc5047af5733de751008) %}) * * **示例代码** * * * ```js wx.openSetting({ success (res) { console.log(res.authSetting) // res.authSetting = { // "scope.userInfo": true, // "scope.userLocation": true // } } }) ``` * * 最低基础库: `1.1.0` */ openSetting(option?: OpenSettingOption): void; /** [wx.pageScrollTo(Object object)](wx.pageScrollTo.md) * * 将页面滚动到目标位置 * * **示例代码** * * * ```js wx.pageScrollTo({ scrollTop: 0, duration: 300 }) ``` * * 最低基础库: `1.4.0` */ pageScrollTo(option: PageScrollToOption): void; /** [wx.pauseBackgroundAudio(Object object)](wx.pauseBackgroundAudio.md) * * 暂停播放音乐。 * * **示例代码** * * * ```js wx.pauseBackgroundAudio() ``` */ pauseBackgroundAudio(option?: PauseBackgroundAudioOption): void; /** [wx.pauseVoice(Object object)](wx.pauseVoice.md) * * 暂停正在播放的语音。再次调用 [`wx.playVoice`](https://developers.weixin.qq.com/miniprogram/dev/api/media/audio/wx.playVoice.html) 播放同一个文件时,会从暂停处开始播放。如果想从头开始播放,需要先调用 [`wx.stopVoice`](https://developers.weixin.qq.com/miniprogram/dev/api/media/audio/wx.stopVoice.html)。 * * **示例代码** * * * ```js wx.startRecord({ success (res) { const tempFilePath = res.tempFilePath wx.playVoice({ filePath: tempFilePath }) setTimeout(() => { wx.pauseVoice() }, 5000) } }) ``` */ pauseVoice(option?: PauseVoiceOption): void; /** [wx.playBackgroundAudio(Object object)](wx.playBackgroundAudio.md) * * 使用后台播放器播放音乐。对于微信客户端来说,只能同时有一个后台音乐在播放。当用户离开小程序后,音乐将暂停播放;当用户在其他小程序占用了音乐播放器,原有小程序内的音乐将停止播放。 * * **示例代码** * * * ```js wx.playBackgroundAudio({ dataUrl: '', title: '', coverImgUrl: '' }) ``` */ playBackgroundAudio(option: PlayBackgroundAudioOption): void; /** [wx.playVoice(Object object)](wx.playVoice.md) * * 开始播放语音。同时只允许一个语音文件正在播放,如果前一个语音文件还没播放完,将中断前一个语音播放。 * * **示例代码** * * * ```js wx.startRecord({ success (res) { const tempFilePath = res.tempFilePath wx.playVoice({ filePath: tempFilePath, complete () { } }) } }) ``` */ playVoice(option: PlayVoiceOption): void; /** [wx.previewImage(Object object)](wx.previewImage.md) * * 在新页面中全屏预览图片。预览的过程中用户可以进行保存图片、发送给朋友等操作。 * * **示例代码** * * * ```js wx.previewImage({ current: '', // 当前显示图片的http链接 urls: [] // 需要预览的图片http链接列表 }) ``` */ previewImage(option: PreviewImageOption): void; /** [wx.reLaunch(Object object)](wx.reLaunch.md) * * 关闭所有页面,打开到应用内的某个页面 * * **示例代码** * * * ```js wx.reLaunch({ url: 'test?id=1' }) ``` * * ```html * // test * Page({ * onLoad (option) { * console.log(option.query) * } * }) * ``` * * 最低基础库: `1.1.0` */ reLaunch(option: ReLaunchOption): void; /** [wx.readBLECharacteristicValue(Object object)](wx.readBLECharacteristicValue.md) * * 读取低功耗蓝牙设备的特征值的二进制数据值。注意:必须设备的特征值支持 read 才可以成功调用。 * * **注意** * * * - 并行调用多次会存在读失败的可能性。 * - 接口读取到的信息需要在 `onBLECharacteristicValueChange` 方法注册的回调中获取。 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * ```js // 必须在这里的回调才能获取 wx.onBLECharacteristicValueChange(function(characteristic) { console.log('characteristic value comed:', characteristic) }) wx.readBLECharacteristicValue({ // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 deviceId, // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取 serviceId, // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取 characteristicId, success (res) { console.log('readBLECharacteristicValue:', res.errCode) } }) ``` * * 最低基础库: `1.1.0` */ readBLECharacteristicValue(option: ReadBLECharacteristicValueOption): void; /** [wx.redirectTo(Object object)](wx.redirectTo.md) * * 关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。 * * **示例代码** * * * ```js wx.redirectTo({ url: 'test?id=1' }) ``` */ redirectTo(option: RedirectToOption): void; /** [wx.removeSavedFile(Object object)](wx.removeSavedFile.md) * * 删除本地缓存文件 * * **示例代码** * * * ```js wx.getSavedFileList({ success (res) { if (res.fileList.length > 0){ wx.removeSavedFile({ filePath: res.fileList[0].filePath, complete (res) { console.log(res) } }) } } }) ``` */ removeSavedFile(option: WxRemoveSavedFileOption): void; /** [wx.removeStorage(Object object)](wx.removeStorage.md) * * 从本地缓存中移除指定 key * * **示例代码** * * * ```js wx.removeStorage({ key: 'key', success (res) { console.log(res.data) } }) ``` * * ```js try { wx.removeStorageSync('key') } catch (e) { // Do something when catch error } ``` */ removeStorage(option: RemoveStorageOption): void; /** [wx.removeStorageSync(string key)](https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.removeStorageSync.html) * * [wx.removeStorage](https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.removeStorage.html) 的同步版本 * * **示例代码** * * * ```js wx.removeStorage({ key: 'key', success (res) { console.log(res.data) } }) ``` * * ```js try { wx.removeStorageSync('key') } catch (e) { // Do something when catch error } ``` */ removeStorageSync( /** 本地缓存中指定的 key */ key: string, ): void; /** [wx.removeTabBarBadge(Object object)](wx.removeTabBarBadge.md) * * 移除 tabBar 某一项右上角的文本 * * 最低基础库: `1.9.0` */ removeTabBarBadge(option: RemoveTabBarBadgeOption): void; /** [wx.reportAnalytics(string eventName, Object data)](wx.reportAnalytics.md) * * 自定义分析数据上报接口。使用前,需要在小程序管理后台自定义分析中新建事件,配置好事件名与字段。 * * **示例代码** * * * ```js wx.reportAnalytics('purchase', { price: 120, color: 'red' }) ``` */ reportAnalytics( /** 事件名 */ eventName: string, /** 上报的自定义数据。 */ data: Data, ): void; /** [wx.reportMonitor(string name, number value)](wx.reportMonitor.md) * * 自定义业务数据监控上报接口。 * * **使用说明** * * * 使用前,需要在「小程序管理后台-运维中心-性能监控-业务数据监控」中新建监控事件,配置监控描述与告警类型。每一个监控事件对应唯一的监控ID,开发者最多可以创建128个监控事件。 * * **示例代码** * * * ```js wx.reportMonitor('1', 1) ``` * * 最低基础库: `2.0.1` */ reportMonitor( /** 监控ID,在「小程序管理后台」新建数据指标后获得 */ name: string, /** 上报数值,经处理后会在「小程序管理后台」上展示每分钟的上报总量 */ value: number, ): void; /** [wx.requestPayment(Object object)](wx.requestPayment.md) * * 发起微信支付。了解更多信息,请查看[微信支付接口文档](https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_3&index=1) * * **示例代码** * * * ```js wx.requestPayment({ timeStamp: '', nonceStr: '', package: '', signType: 'MD5', paySign: '', success (res) { }, fail (res) { } }) ``` */ requestPayment(option: RequestPaymentOption): void; /** [wx.saveFile(Object object)](wx.saveFile.md) * * 保存文件到本地。注意:**saveFile 会把临时文件移动,因此调用成功后传入的 tempFilePath 将不可用** * * **示例代码** * * * ```js wx.chooseImage({ success: function(res) { const tempFilePaths = res.tempFilePaths wx.saveFile({ tempFilePath: tempFilePaths[0], success (res) { const savedFilePath = res.savedFilePath } }) } }) ``` * * **注意** * * * 本地文件存储的大小限制为 10M */ saveFile(option: WxSaveFileOption): void; /** [wx.saveImageToPhotosAlbum(Object object)](wx.saveImageToPhotosAlbum.md) * * 保存图片到系统相册。 * * **示例代码** * * * ```js wx.saveImageToPhotosAlbum({ success(res) { } }) ``` * * 最低基础库: `1.2.0` */ saveImageToPhotosAlbum(option: SaveImageToPhotosAlbumOption): void; /** [wx.saveVideoToPhotosAlbum(Object object)](wx.saveVideoToPhotosAlbum.md) * * 保存视频到系统相册 * * **示例代码** * * * ```js wx.saveVideoToPhotosAlbum({ filePath: 'wxfile://xxx', success (res) { console.log(res.errMsg) } }) ``` * * 最低基础库: `1.2.0` */ saveVideoToPhotosAlbum(option: SaveVideoToPhotosAlbumOption): void; /** [wx.scanCode(Object object)](wx.scanCode.md) * * 调起客户端扫码界面进行扫码 * * **示例代码** * * * ```js // 允许从相机和相册扫码 wx.scanCode({ success (res) { console.log(res) } }) // 只允许从相机扫码 wx.scanCode({ onlyFromCamera: true, success (res) { console.log(res) } }) ``` */ scanCode(option: ScanCodeOption): void; /** [wx.seekBackgroundAudio(Object object)](wx.seekBackgroundAudio.md) * * 控制音乐播放进度。 * * **示例代码** * * * ```js wx.seekBackgroundAudio({ position: 30 }) ``` */ seekBackgroundAudio(option: SeekBackgroundAudioOption): void; /** [wx.sendHCEMessage(Object object)](wx.sendHCEMessage.md) * * 发送 NFC 消息。仅在安卓系统下有效。 * * **示例代码** * * * ```js const buffer = new ArrayBuffer(1) const dataView = new DataView(buffer) dataView.setUint8(0, 0) wx.startHCE({ success (res) { wx.onHCEMessage(function(res) { if (res.messageType === 1) { wx.sendHCEMessage({data: buffer}) } }) } }) ``` * * 最低基础库: `1.7.0` */ sendHCEMessage(option: SendHCEMessageOption): void; /** [wx.sendSocketMessage(Object object)](wx.sendSocketMessage.md) * * 通过 WebSocket 连接发送数据。需要先 wx.connectSocket,并在 wx.onSocketOpen 回调之后才能发送。 * * **示例代码** * * * ```js const socketOpen = false const socketMsgQueue = [] wx.connectSocket({ url: 'test.php' }) wx.onSocketOpen(function(res) { socketOpen = true for (let i = 0; i < socketMsgQueue.length; i++){ sendSocketMessage(socketMsgQueue[i]) } socketMsgQueue = [] }) function sendSocketMessage(msg) { if (socketOpen) { wx.sendSocketMessage({ data:msg }) } else { socketMsgQueue.push(msg) } } ``` */ sendSocketMessage(option: SendSocketMessageOption): void; /** [wx.setBackgroundColor(Object object)](wx.setBackgroundColor.md) * * 动态设置窗口的背景色 * * **示例代码** * * * ```js wx.setBackgroundColor({ backgroundColor: '#ffffff', // 窗口的背景色为白色 }) wx.setBackgroundColor({ backgroundColorTop: '#ffffff', // 顶部窗口的背景色为白色 backgroundColorBottom: '#ffffff', // 底部窗口的背景色为白色 }) ``` * * 最低基础库: `2.1.0` */ setBackgroundColor(option: SetBackgroundColorOption): void; /** [wx.setBackgroundTextStyle(Object object)](wx.setBackgroundTextStyle.md) * * 动态设置下拉背景字体、loading 图的样式 * * **示例代码** * * * ```js wx.setBackgroundTextStyle({ textStyle: 'dark' // 下拉背景字体、loading 图的样式为dark }) ``` * * 最低基础库: `2.1.0` */ setBackgroundTextStyle(option: SetBackgroundTextStyleOption): void; /** [wx.setClipboardData(Object object)](wx.setClipboardData.md) * * 设置系统剪贴板的内容 * * **示例代码** * * * ```js wx.setClipboardData({ data: 'data', success (res) { wx.getClipboardData({ success (res) { console.log(res.data) // data } }) } }) ``` * * 最低基础库: `1.1.0` */ setClipboardData(option: SetClipboardDataOption): void; /** [wx.setEnableDebug(Object object)](wx.setEnableDebug.md) * * 设置是否打开调试开关。此开关对正式版也能生效。 * * **示例代码** * * * ```javascript // 打开调试 wx.setEnableDebug({ enableDebug: true }) // 关闭调试 wx.setEnableDebug({ enableDebug: false }) ``` * * **Tips** * * * - 在正式版打开调试还有一种方法,就是先在开发版或体验版打开调试,再切到正式版就能看到vConsole。 * * 最低基础库: `1.4.0` */ setEnableDebug(option: SetEnableDebugOption): void; /** [wx.setInnerAudioOption(Object object)](wx.setInnerAudioOption.md) * * 设置 [InnerAudioContext](https://developers.weixin.qq.com/miniprogram/dev/api/media/audio/InnerAudioContext.html) 的播放选项。设置之后对当前小程序全局生效。 * * 最低基础库: `2.3.0` */ setInnerAudioOption(option: SetInnerAudioOption): void; /** [wx.setKeepScreenOn(Object object)](wx.setKeepScreenOn.md) * * 设置是否保持常亮状态。仅在当前小程序生效,离开小程序后设置失效。 * * **示例代码** * * * ```js wx.setKeepScreenOn({ keepScreenOn: true }) ``` * * 最低基础库: `1.4.0` */ setKeepScreenOn(option: SetKeepScreenOnOption): void; /** [wx.setNavigationBarColor(Object object)](wx.setNavigationBarColor.md) * * 设置页面导航条颜色 * * 最低基础库: `1.4.0` */ setNavigationBarColor(option: SetNavigationBarColorOption): void; /** [wx.setNavigationBarTitle(Object object)](wx.setNavigationBarTitle.md) * * 动态设置当前页面的标题 * * **示例代码** * * * ```js wx.setNavigationBarTitle({ title: '当前页面' }) ``` */ setNavigationBarTitle(option: SetNavigationBarTitleOption): void; /** [wx.setScreenBrightness(Object object)](wx.setScreenBrightness.md) * * 设置屏幕亮度 * * 最低基础库: `1.2.0` */ setScreenBrightness(option: SetScreenBrightnessOption): void; /** [wx.setStorage(Object object)](wx.setStorage.md) * * 将数据存储在本地缓存中指定的 key 中。会覆盖掉原来该 key 对应的内容。数据存储生命周期跟小程序本身一致,即除用户主动删除或超过一定时间被自动清理,否则数据都一直可用。单个 key 允许存储的最大数据长度为 1MB,所有数据存储上限为 10MB。 * * **示例代码** * * * ```js wx.setStorage({ key:"key", data:"value" }) ``` * ```js try { wx.setStorageSync('key', 'value') } catch (e) { } ``` */ setStorage(option: SetStorageOption): void; /** [wx.setStorageSync(string key, any data)](https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.setStorageSync.html) * * [wx.setStorage](https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.setStorage.html) 的同步版本 * * **示例代码** * * * ```js wx.setStorage({ key:"key", data:"value" }) ``` * ```js try { wx.setStorageSync('key', 'value') } catch (e) { } ``` */ setStorageSync( /** 本地缓存中指定的 key */ key: string, /** 需要存储的内容。只支持原生类型、Date、及能够通过`JSON.stringify`序列化的对象。 */ data: any, ): void; /** [wx.setTabBarBadge(Object object)](wx.setTabBarBadge.md) * * 为 tabBar 某一项的右上角添加文本 * * **示例代码** * * * ```js wx.setTabBarBadge({ index: 0, text: '1' }) ``` * * 最低基础库: `1.9.0` */ setTabBarBadge(option: SetTabBarBadgeOption): void; /** [wx.setTabBarItem(Object object)](wx.setTabBarItem.md) * * 动态设置 tabBar 某一项的内容 * * **示例代码** * * * ```js wx.setTabBarItem({ index: 0, text: 'text', iconPath: '/path/to/iconPath', selectedIconPath: '/path/to/selectedIconPath' }) ``` * * 最低基础库: `1.9.0` */ setTabBarItem(option: SetTabBarItemOption): void; /** [wx.setTabBarStyle(Object object)](wx.setTabBarStyle.md) * * 动态设置 tabBar 的整体样式 * * **示例代码** * * * ```js wx.setTabBarStyle({ color: '#FF0000', selectedColor: '#00FF00', backgroundColor: '#0000FF', borderStyle: 'white' }) ``` * * 最低基础库: `1.9.0` */ setTabBarStyle(option: SetTabBarStyleOption): void; /** [wx.setTopBarText(Object object)](wx.setTopBarText.md) * * 动态设置置顶栏文字内容。只有当前小程序被置顶时能生效,如果当前小程序没有被置顶,也能调用成功,但是不会立即生效,只有在用户将这个小程序置顶后才换上设置的文字内容. * * **示例代码** * * * ```js wx.setTopBarText({ text: 'hello, world!' }) ``` * * **注意** * * * - 调用成功后,需间隔 5s 才能再次调用此接口,如果在 5s 内再次调用此接口,会回调 fail,errMsg:"setTopBarText: fail invoke too frequently" * * 最低基础库: `1.4.3` */ setTopBarText(option: SetTopBarTextOption): void; /** [wx.setWifiList(Object object)](wx.setWifiList.md) * * 设置 `wifiList` 中 AP 的相关信息。在 `onGetWifiList` 回调后调用,**iOS特有接口**。 * * **注意** * * * - 该接口只能在 `onGetWifiList` 回调之后才能调用。 * - 此时客户端会挂起,等待小程序设置 Wi-Fi 信息,请务必尽快调用该接口,若无数据请传入一个空数组。 * - 有可能随着周边 Wi-Fi 列表的刷新,单个流程内收到多次带有存在重复的 Wi-Fi 列表的回调。 * * **示例代码** * * * ```js wx.onGetWifiList(function(res) { if (res.wifiList.length) { wx.setWifiList({ wifiList: [{ SSID: res.wifiList[0].SSID, BSSID: res.wifiList[0].BSSID, password: '123456' }] }) } else { wx.setWifiList({ wifiList: [] }) } }) wx.getWifiList() ``` * * 最低基础库: `1.6.0` */ setWifiList(option: SetWifiListOption): void; /** [wx.showActionSheet(Object object)](wx.showActionSheet.md) * * ​显示操作菜单 * * **示例代码** * * * ```js wx.showActionSheet({ itemList: ['A', 'B', 'C'], success (res) { console.log(res.tapIndex) }, fail (res) { console.log(res.errMsg) } }) ``` * * **注意** * * * - Android 6.7.2 以下版本,点击取消或蒙层时,回调 fail, errMsg 为 "fail cancel"; * - Android 6.7.2 及以上版本 和 iOS 点击蒙层不会关闭模态弹窗,所以尽量避免使用「取消」分支中实现业务逻辑 */ showActionSheet(option: ShowActionSheetOption): void; /** [wx.showLoading(Object object)](wx.showLoading.md) * * 显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框 * * **示例代码** * * * ```js wx.showLoading({ title: '加载中', }) setTimeout(function () { wx.hideLoading() }, 2000) ``` * * **注意** * * * - `wx.showLoading` 和 `wx.showToast` 同时只能显示一个 * - `wx.showLoading` 应与 `wx.hideLoading` 配对使用 * * 最低基础库: `1.1.0` */ showLoading(option: ShowLoadingOption): void; /** [wx.showModal(Object object)](wx.showModal.md) * * 显示模态对话框 * * **示例代码** * * * ```js wx.showModal({ title: '提示', content: '这是一个模态弹窗', success (res) { if (res.confirm) { console.log('用户点击确定') } else if (res.cancel) { console.log('用户点击取消') } } }) ``` * * **注意** * * * - Android 6.7.2 以下版本,点击取消或蒙层时,回调 fail, errMsg 为 "fail cancel"; * - Android 6.7.2 及以上版本 和 iOS 点击蒙层不会关闭模态弹窗,所以尽量避免使用「取消」分支中实现业务逻辑 */ showModal(option: ShowModalOption): void; /** [wx.showNavigationBarLoading(Object object)](wx.showNavigationBarLoading.md) * * 在当前页面显示导航条加载动画 */ showNavigationBarLoading(option?: ShowNavigationBarLoadingOption): void; /** [wx.showShareMenu(Object object)](wx.showShareMenu.md) * * 显示当前页面的转发按钮 * * **示例代码** * * * ```js wx.showShareMenu({ withShareTicket: true }) ``` * * 最低基础库: `1.1.0` */ showShareMenu(option: ShowShareMenuOption): void; /** [wx.showTabBar(Object object)](wx.showTabBar.md) * * 显示 tabBar * * 最低基础库: `1.9.0` */ showTabBar(option: ShowTabBarOption): void; /** [wx.showTabBarRedDot(Object object)](wx.showTabBarRedDot.md) * * 显示 tabBar 某一项的右上角的红点 * * 最低基础库: `1.9.0` */ showTabBarRedDot(option: ShowTabBarRedDotOption): void; /** [wx.showToast(Object object)](wx.showToast.md) * * 显示消息提示框 * * **示例代码** * * * ```js wx.showToast({ title: '成功', icon: 'success', duration: 2000 }) ``` * * **注意** * * * - `wx.showLoading` 和 `wx.showToast` 同时只能显示一个 * - `wx.showToast` 应与 `wx.hideToast` 配对使用 */ showToast(option: ShowToastOption): void; /** [wx.startAccelerometer(Object object)](wx.startAccelerometer.md) * * 开始监听加速度数据。 * * **示例代码** * * * ```js wx.startAccelerometer({ interval: 'game' }) ``` * * **注意** * * * - 根据机型性能、当前 CPU 与内存的占用情况,`interval` 的设置与实际 `wx.onAccelerometerChange()` 回调函数的执行频率会有一些出入。 * * 最低基础库: `1.1.0` */ startAccelerometer(option: StartAccelerometerOption): void; /** [wx.startBeaconDiscovery(Object object)](wx.startBeaconDiscovery.md) * * 开始搜索附近的 iBeacon 设备 * * **示例代码** * * * ```js wx.startBeaconDiscovery({ success(res) { } }) ``` * * 最低基础库: `1.2.0` */ startBeaconDiscovery(option: StartBeaconDiscoveryOption): void; /** [wx.startBluetoothDevicesDiscovery(Object object)](wx.startBluetoothDevicesDiscovery.md) * * 开始搜寻附近的蓝牙外围设备。**此操作比较耗费系统资源,请在搜索并连接到设备后调用 `wx.stopBluetoothDevicesDiscovery` 方法停止搜索。** * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * * ```js // 以微信硬件平台的蓝牙智能灯为例,主服务的 UUID 是 FEE7。传入这个参数,只搜索主服务 UUID 为 FEE7 的设备 wx.startBluetoothDevicesDiscovery({ services: ['FEE7'], success (res) { console.log(res) } }) ``` * * 最低基础库: `1.1.0` */ startBluetoothDevicesDiscovery( option: StartBluetoothDevicesDiscoveryOption, ): void; /** [wx.startCompass(Object object)](wx.startCompass.md) * * 开始监听罗盘数据 * * **示例代码** * * * ```js wx.startCompass() ``` * * 最低基础库: `1.1.0` */ startCompass(option?: StartCompassOption): void; /** [wx.startDeviceMotionListening(Object object)](wx.startDeviceMotionListening.md) * * 开始监听设备方向的变化。 * * 最低基础库: `2.3.0` */ startDeviceMotionListening(option: StartDeviceMotionListeningOption): void; /** [wx.startGyroscope(Object object)](wx.startGyroscope.md) * * 开始监听陀螺仪数据。 * * 最低基础库: `2.3.0` */ startGyroscope(option: StartGyroscopeOption): void; /** [wx.startHCE(Object object)](wx.startHCE.md) * * 初始化 NFC 模块。 * * **示例代码** * * * ```js wx.startHCE({ aid_list: ['F222222222'] success (res) { console.log(res.errMsg) } }) ``` * * 最低基础库: `1.7.0` */ startHCE(option: StartHCEOption): void; /** [wx.startLocalServiceDiscovery(Object object)](wx.startLocalServiceDiscovery.md) * * 开始搜索局域网下的 mDNS 服务。搜索的结果会通过 wx.onLocalService* 事件返回。 * * **注意** * * * 1. wx.startLocalServiceDiscovery 是一个消耗性能的行为,开始 30 秒后会自动 stop 并执行 wx.onLocalServiceDiscoveryStop 注册的回调函数。 * 2. 在调用 wx.startLocalServiceDiscovery 后,在这次搜索行为停止后才能发起下次 wx.startLocalServiceDiscovery。停止本次搜索行为的操作包括调用 wx.stopLocalServiceDiscovery 和 30 秒后系统自动 stop 本次搜索。 * * 最低基础库: `2.4.0` */ startLocalServiceDiscovery(option: StartLocalServiceDiscoveryOption): void; /** [wx.startPullDownRefresh(Object object)](wx.startPullDownRefresh.md) * * 开始下拉刷新。调用后触发下拉刷新动画,效果与用户手动下拉刷新一致。 * * **示例代码** * * * ```js wx.startPullDownRefresh() ``` * * 最低基础库: `1.5.0` */ startPullDownRefresh(option?: StartPullDownRefreshOption): void; /** [wx.startRecord(Object object)](wx.startRecord.md) * * 开始录音。当主动调用 [`wx.stopRecord`](https://developers.weixin.qq.com/miniprogram/dev/api/media/recorder/wx.stopRecord.html),或者录音超过1分钟时自动结束录音。当用户离开小程序时,此接口无法调用。 * * **示例代码** * * * ```js wx.startRecord({ success (res) { const tempFilePath = res.tempFilePath } }) setTimeout(function () { wx.stopRecord() // 结束录音 }, 10000) ``` */ startRecord(option: WxStartRecordOption): void; /** [wx.startSoterAuthentication(Object object)](wx.startSoterAuthentication.md) * * 开始 SOTER 生物认证。验证流程请参考[说明](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/soter/wx.startSoterAuthentication.html)。 * * **resultJSON 说明** * * * 此数据为设备TEE中,将传入的challenge和TEE内其他安全信息组成的数据进行组装而来的JSON,对下述字段的解释如下表。例子如下: * | 字段名 | 说明 | * |---------|-------------------------------------------------------------------------------------------| * | raw | 调用者传入的challenge | * | fid | (仅Android支持)本次生物识别认证的生物信息编号(如指纹识别则是指纹信息在本设备内部编号) | * | counter | 防重放特征参数 | * | tee_n | TEE名称(如高通或者trustonic等) | * | tee_v | TEE版本号 | * | fp_n | 指纹以及相关逻辑模块提供商(如FPC等) | * | fp_v | 指纹以及相关模块版本号 | * | cpu_id | 机器唯一识别ID | * | uid | 概念同Android系统定义uid,即应用程序编号 | * * ```json { "raw":"msg", "fid":"2", "counter":123, "tee_n":"TEE Name", "tee_v":"TEE Version", "fp_n":"Fingerprint Sensor Name", "fp_v":"Fingerprint Sensor Version", "cpu_id":"CPU Id", "uid":"21" } ``` * * **示例代码** * * * {% minicode('q3tCKkmJ7g2e') %} * ```js wx.startSoterAuthentication({ requestAuthModes: ['fingerPrint'], challenge: '123456', authContent: '请用指纹解锁', success(res) { } }) ``` * * 最低基础库: `1.5.0` */ startSoterAuthentication(option: StartSoterAuthenticationOption): void; /** [wx.startWifi(Object object)](wx.startWifi.md) * * 初始化 Wi-Fi 模块。 * * **示例代码** * * * {% minicode('8P7zrkmd7r2n') %} * ```js wx.startWifi({ success (res) { console.log(res.errMsg) } }) ``` * * 最低基础库: `1.6.0` */ startWifi(option?: StartWifiOption): void; /** [wx.stopAccelerometer(Object object)](wx.stopAccelerometer.md) * * 停止监听加速度数据。 * * **示例代码** * * * ```js wx.stopAccelerometer() ``` * * 最低基础库: `1.1.0` */ stopAccelerometer(option?: StopAccelerometerOption): void; /** [wx.stopBackgroundAudio(Object object)](wx.stopBackgroundAudio.md) * * 停止播放音乐。 * * **示例代码** * * * ```js wx.stopBackgroundAudio() ``` */ stopBackgroundAudio(option?: StopBackgroundAudioOption): void; /** [wx.stopBeaconDiscovery(Object object)](wx.stopBeaconDiscovery.md) * * 停止搜索附近的 iBeacon 设备 * * 最低基础库: `1.2.0` */ stopBeaconDiscovery(option?: StopBeaconDiscoveryOption): void; /** [wx.stopBluetoothDevicesDiscovery(Object object)](wx.stopBluetoothDevicesDiscovery.md) * * 停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * ```js wx.stopBluetoothDevicesDiscovery({ success (res) { console.log(res) } }) ``` * * 最低基础库: `1.1.0` */ stopBluetoothDevicesDiscovery( option?: StopBluetoothDevicesDiscoveryOption, ): void; /** [wx.stopCompass(Object object)](wx.stopCompass.md) * * 停止监听罗盘数据 * * **示例代码** * * * ```js wx.stopCompass() ``` * * 最低基础库: `1.1.0` */ stopCompass(option?: StopCompassOption): void; /** [wx.stopDeviceMotionListening(Object object)](wx.stopDeviceMotionListening.md) * * 停止监听设备方向的变化。 * * 最低基础库: `2.3.0` */ stopDeviceMotionListening(option?: StopDeviceMotionListeningOption): void; /** [wx.stopGyroscope(Object object)](wx.stopGyroscope.md) * * 停止监听陀螺仪数据。 * * 最低基础库: `2.3.0` */ stopGyroscope(option?: StopGyroscopeOption): void; /** [wx.stopHCE(Object object)](wx.stopHCE.md) * * 关闭 NFC 模块。仅在安卓系统下有效。 * * **示例代码** * * * ```js wx.stopHCE({ success (res) { console.log(res.errMsg) } }) ``` * * 最低基础库: `1.7.0` */ stopHCE(option?: StopHCEOption): void; /** [wx.stopLocalServiceDiscovery(Object object)](wx.stopLocalServiceDiscovery.md) * * 停止搜索 mDNS 服务 * * 最低基础库: `2.4.0` */ stopLocalServiceDiscovery(option?: StopLocalServiceDiscoveryOption): void; /** [wx.stopPullDownRefresh(Object object)](wx.stopPullDownRefresh.md) * * 停止当前页面下拉刷新。 * * **示例代码** * * * ```js Page({ onPullDownRefresh () { wx.stopPullDownRefresh() } }) ``` * * 最低基础库: `1.5.0` */ stopPullDownRefresh(option?: StopPullDownRefreshOption): void; /** [wx.stopRecord()](wx.stopRecord.md) * * 停止录音。 * * **示例代码** * * * ```js wx.startRecord({ success (res) { const tempFilePath = res.tempFilePath } }) setTimeout(function () { wx.stopRecord() // 结束录音 }, 10000) ``` */ stopRecord(): void; /** [wx.stopVoice(Object object)](wx.stopVoice.md) * * 结束播放语音。 * * **示例代码** * * * ```js wx.startRecord({ success (res) { const tempFilePath = res.tempFilePath wx.playVoice({ filePath: tempFilePath, }) setTimeout(() => { wx.stopVoice() }, 5000) } }) ``` */ stopVoice(option?: StopVoiceOption): void; /** [wx.stopWifi(Object object)](wx.stopWifi.md) * * 关闭 Wi-Fi 模块。 * * **示例代码** * * * ```js wx.stopWifi({ success (res) { console.log(res.errMsg) } }) ``` * * 最低基础库: `1.6.0` */ stopWifi(option?: StopWifiOption): void; /** [wx.switchTab(Object object)](wx.switchTab.md) * * 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面 * * **示例代码** * * * ```json { "tabBar": { "list": [{ "pagePath": "index", "text": "首页" },{ "pagePath": "other", "text": "其他" }] } } ``` * * ```js wx.switchTab({ url: '/index' }) ``` */ switchTab(option: SwitchTabOption): void; /** [wx.updateShareMenu(Object object)](wx.updateShareMenu.md) * * 更新转发属性 * * **示例代码** * * * ```js wx.updateShareMenu({ withShareTicket: true, success () { } }) ``` * * 最低基础库: `1.2.0` */ updateShareMenu(option: UpdateShareMenuOption): void; /** [wx.vibrateLong(Object object)](wx.vibrateLong.md) * * 使手机发生较长时间的振动(400 ms) * * 最低基础库: `1.2.0` */ vibrateLong(option?: VibrateLongOption): void; /** [wx.vibrateShort(Object object)](wx.vibrateShort.md) * * 使手机发生较短时间的振动(15 ms)。仅在 iPhone `7 / 7 Plus` 以上及 Android 机型生效 * * 最低基础库: `1.2.0` */ vibrateShort(option?: VibrateShortOption): void; /** [wx.writeBLECharacteristicValue(Object object)](wx.writeBLECharacteristicValue.md) * * 向低功耗蓝牙设备特征值中写入二进制数据。注意:必须设备的特征值支持 write 才可以成功调用。 * * **注意** * * * - 并行调用多次会存在写失败的可能性。 * - 小程序不会对写入数据包大小做限制,但系统与蓝牙设备会限制蓝牙4.0单次传输的数据大小,超过最大字节数后会发生写入错误,建议每次写入不超过20字节。 * - 若单次写入数据过长,iOS 上存在系统不会有任何回调的情况(包括错误回调)。 * - 安卓平台上,在调用 `notifyBLECharacteristicValueChange` 成功后立即调用 `writeBLECharacteristicValue` 接口,在部分机型上会发生 10008 系统错误 * * **示例代码** * * * {% minicode('pQU51zmz7a3K') %} * ```js // 向蓝牙设备发送一个0x00的16进制数据 let buffer = new ArrayBuffer(1) let dataView = new DataView(buffer) dataView.setUint8(0, 0) wx.writeBLECharacteristicValue({ // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取 deviceId, // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取 serviceId, // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取 characteristicId, // 这里的value是ArrayBuffer类型 value: buffer, success (res) { console.log('writeBLECharacteristicValue success', res.errMsg) } }) ``` * * 最低基础库: `1.1.0` */ writeBLECharacteristicValue( option: WriteBLECharacteristicValueOption, ): void; } /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type AccessCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type AccessFailCallback = (result: AccessFailCallbackResult) => void; /** 接口调用成功的回调函数 */ type AccessSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type AddCardCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type AddCardFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type AddCardSuccessCallback = (result: AddCardSuccessCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type AddPhoneContactCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type AddPhoneContactFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type AddPhoneContactSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type AppendFileCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type AppendFileFailCallback = (result: AppendFileFailCallbackResult) => void; /** 接口调用成功的回调函数 */ type AppendFileSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type AuthorizeCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type AuthorizeFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type AuthorizeSuccessCallback = (res: GeneralCallbackResult) => void; /** 背景音频进入可播放状态事件的回调函数 */ type BackgroundAudioManagerOnCanplayCallback = ( res: GeneralCallbackResult, ) => void; /** 背景音频自然播放结束事件的回调函数 */ type BackgroundAudioManagerOnEndedCallback = ( res: GeneralCallbackResult, ) => void; /** 背景音频播放错误事件的回调函数 */ type BackgroundAudioManagerOnErrorCallback = ( res: GeneralCallbackResult, ) => void; /** 背景音频暂停事件的回调函数 */ type BackgroundAudioManagerOnPauseCallback = ( res: GeneralCallbackResult, ) => void; /** 背景音频播放事件的回调函数 */ type BackgroundAudioManagerOnPlayCallback = ( res: GeneralCallbackResult, ) => void; /** 背景音频完成跳转操作事件的回调函数 */ type BackgroundAudioManagerOnSeekedCallback = ( res: GeneralCallbackResult, ) => void; /** 背景音频开始跳转操作事件的回调函数 */ type BackgroundAudioManagerOnSeekingCallback = ( res: GeneralCallbackResult, ) => void; /** 背景音频停止事件的回调函数 */ type BackgroundAudioManagerOnStopCallback = ( res: GeneralCallbackResult, ) => void; /** 背景音频播放进度更新事件的回调函数 */ type BackgroundAudioManagerOnTimeUpdateCallback = ( res: GeneralCallbackResult, ) => void; /** 音频加载中事件的回调函数 */ type BackgroundAudioManagerOnWaitingCallback = ( res: GeneralCallbackResult, ) => void; /** 回调函数,在执行 `SelectorQuery.exec` 方法后,节点信息会在 `callback` 中返回。 */ type BoundingClientRectCallback = ( result: BoundingClientRectCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type CameraContextStartRecordCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type CameraContextStartRecordFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type CameraContextStartRecordSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type CanvasGetImageDataCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type CanvasGetImageDataFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type CanvasGetImageDataSuccessCallback = ( result: CanvasGetImageDataSuccessCallbackResult, /** 图像像素点数据,一维数组,每四项表示一个像素点的 rgba */ data: Uint8ClampedArray, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type CanvasPutImageDataCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type CanvasPutImageDataFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type CanvasPutImageDataSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type CanvasToTempFilePathCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type CanvasToTempFilePathFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type CanvasToTempFilePathSuccessCallback = ( result: CanvasToTempFilePathSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type CheckIsSoterEnrolledInDeviceCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type CheckIsSoterEnrolledInDeviceFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type CheckIsSoterEnrolledInDeviceSuccessCallback = ( result: CheckIsSoterEnrolledInDeviceSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type CheckIsSupportSoterAuthenticationCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type CheckIsSupportSoterAuthenticationFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type CheckIsSupportSoterAuthenticationSuccessCallback = ( result: CheckIsSupportSoterAuthenticationSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type CheckSessionCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type CheckSessionFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type CheckSessionSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ChooseAddressCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ChooseAddressFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ChooseAddressSuccessCallback = ( result: ChooseAddressSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ChooseImageCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ChooseImageFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ChooseImageSuccessCallback = ( result: ChooseImageSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ChooseInvoiceCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ChooseInvoiceFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ChooseInvoiceSuccessCallback = ( result: ChooseInvoiceSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ChooseInvoiceTitleCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type ChooseInvoiceTitleFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ChooseInvoiceTitleSuccessCallback = ( result: ChooseInvoiceTitleSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ChooseLocationCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ChooseLocationFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ChooseLocationSuccessCallback = ( result: ChooseLocationSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ChooseVideoCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ChooseVideoFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ChooseVideoSuccessCallback = ( result: ChooseVideoSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ClearStorageCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ClearStorageFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ClearStorageSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type CloseBLEConnectionCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type CloseBLEConnectionFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type CloseBLEConnectionSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type CloseBluetoothAdapterCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type CloseBluetoothAdapterFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type CloseBluetoothAdapterSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type CloseCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type CloseFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type CloseSocketCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type CloseSocketFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type CloseSocketSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type CloseSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type CompressImageCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type CompressImageFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type CompressImageSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ConnectSocketCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ConnectSocketFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ConnectSocketSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ConnectWifiCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ConnectWifiFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ConnectWifiSuccessCallback = (res: GeneralCallbackResult) => void; /** 回调函数,在执行 `SelectorQuery.exec` 方法后,返回节点信息。 */ type ContextCallback = (result: ContextCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type CopyFileCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type CopyFileFailCallback = (result: CopyFileFailCallbackResult) => void; /** 接口调用成功的回调函数 */ type CopyFileSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type CreateBLEConnectionCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type CreateBLEConnectionFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type CreateBLEConnectionSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type DownloadFileCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type DownloadFileFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type DownloadFileSuccessCallback = ( result: DownloadFileSuccessCallbackResult, ) => void; /** HTTP Response Header 事件的回调函数 */ type DownloadTaskOffHeadersReceivedCallback = ( res: GeneralCallbackResult, ) => void; /** 下载进度变化事件的回调函数 */ type DownloadTaskOffProgressUpdateCallback = ( res: GeneralCallbackResult, ) => void; /** HTTP Response Header 事件的回调函数 */ type DownloadTaskOnHeadersReceivedCallback = ( result: DownloadTaskOnHeadersReceivedCallbackResult, ) => void; /** 下载进度变化事件的回调函数 */ type DownloadTaskOnProgressUpdateCallback = ( result: DownloadTaskOnProgressUpdateCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ExitFullScreenCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ExitFullScreenFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ExitFullScreenSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type FileSystemManagerGetFileInfoCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type FileSystemManagerGetFileInfoFailCallback = ( result: GetFileInfoFailCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type FileSystemManagerGetFileInfoSuccessCallback = ( result: FileSystemManagerGetFileInfoSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type FileSystemManagerGetSavedFileListCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type FileSystemManagerGetSavedFileListFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type FileSystemManagerGetSavedFileListSuccessCallback = ( result: FileSystemManagerGetSavedFileListSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type FileSystemManagerRemoveSavedFileCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type FileSystemManagerRemoveSavedFileFailCallback = ( result: RemoveSavedFileFailCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type FileSystemManagerRemoveSavedFileSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type FileSystemManagerSaveFileCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type FileSystemManagerSaveFileFailCallback = ( result: SaveFileFailCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type FileSystemManagerSaveFileSuccessCallback = ( result: FileSystemManagerSaveFileSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetAvailableAudioSourcesCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type GetAvailableAudioSourcesFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type GetAvailableAudioSourcesSuccessCallback = ( result: GetAvailableAudioSourcesSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetBLEDeviceCharacteristicsCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type GetBLEDeviceCharacteristicsFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type GetBLEDeviceCharacteristicsSuccessCallback = ( result: GetBLEDeviceCharacteristicsSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetBLEDeviceServicesCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type GetBLEDeviceServicesFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetBLEDeviceServicesSuccessCallback = ( result: GetBLEDeviceServicesSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetBackgroundAudioPlayerStateCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type GetBackgroundAudioPlayerStateFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type GetBackgroundAudioPlayerStateSuccessCallback = ( result: GetBackgroundAudioPlayerStateSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetBatteryInfoCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetBatteryInfoFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetBatteryInfoSuccessCallback = ( result: GetBatteryInfoSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetBeaconsCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetBeaconsFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetBeaconsSuccessCallback = ( result: GetBeaconsSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetBluetoothAdapterStateCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type GetBluetoothAdapterStateFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type GetBluetoothAdapterStateSuccessCallback = ( result: GetBluetoothAdapterStateSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetBluetoothDevicesCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type GetBluetoothDevicesFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetBluetoothDevicesSuccessCallback = ( result: GetBluetoothDevicesSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetCenterLocationCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetCenterLocationFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetCenterLocationSuccessCallback = ( result: GetCenterLocationSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetClipboardDataCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetClipboardDataFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetClipboardDataSuccessCallback = ( option: GetClipboardDataSuccessCallbackOption, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetConnectedBluetoothDevicesCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type GetConnectedBluetoothDevicesFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type GetConnectedBluetoothDevicesSuccessCallback = ( result: GetConnectedBluetoothDevicesSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetConnectedWifiCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetConnectedWifiFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetConnectedWifiSuccessCallback = ( result: GetConnectedWifiSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetExtConfigCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetExtConfigFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetExtConfigSuccessCallback = ( result: GetExtConfigSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetHCEStateCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetHCEStateFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetHCEStateSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetImageInfoCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetImageInfoFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetImageInfoSuccessCallback = ( result: GetImageInfoSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetLocationCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetLocationFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetLocationSuccessCallback = ( result: GetLocationSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetNetworkTypeCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetNetworkTypeFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetNetworkTypeSuccessCallback = ( result: GetNetworkTypeSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetRegionCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetRegionFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetRegionSuccessCallback = ( result: GetRegionSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetSavedFileInfoCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetSavedFileInfoFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetSavedFileInfoSuccessCallback = ( result: GetSavedFileInfoSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetScaleCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetScaleFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetScaleSuccessCallback = ( result: GetScaleSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetScreenBrightnessCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type GetScreenBrightnessFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetScreenBrightnessSuccessCallback = ( option: GetScreenBrightnessSuccessCallbackOption, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetSettingCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetSettingFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetSettingSuccessCallback = ( result: GetSettingSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetShareInfoCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetShareInfoFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetShareInfoSuccessCallback = ( result: GetShareInfoSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetStorageCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetStorageFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetStorageInfoCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetStorageInfoFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetStorageInfoSuccessCallback = ( option: GetStorageInfoSuccessCallbackOption, ) => void; /** 接口调用成功的回调函数 */ type GetStorageSuccessCallback = ( result: GetStorageSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetSystemInfoCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetSystemInfoFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetSystemInfoSuccessCallback = ( result: GetSystemInfoSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetUserInfoCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetUserInfoFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetUserInfoSuccessCallback = ( result: GetUserInfoSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetWeRunDataCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetWeRunDataFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetWeRunDataSuccessCallback = ( result: GetWeRunDataSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type GetWifiListCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type GetWifiListFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type GetWifiListSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type HideLoadingCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type HideLoadingFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type HideLoadingSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type HideNavigationBarLoadingCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type HideNavigationBarLoadingFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type HideNavigationBarLoadingSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type HideShareMenuCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type HideShareMenuFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type HideShareMenuSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type HideTabBarCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type HideTabBarFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type HideTabBarRedDotCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type HideTabBarRedDotFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type HideTabBarRedDotSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type HideTabBarSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type HideToastCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type HideToastFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type HideToastSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type IncludePointsCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type IncludePointsFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type IncludePointsSuccessCallback = (res: GeneralCallbackResult) => void; /** 音频进入可以播放状态的事件的回调函数 */ type InnerAudioContextOnCanplayCallback = ( res: GeneralCallbackResult, ) => void; /** 音频自然播放至结束的事件的回调函数 */ type InnerAudioContextOnEndedCallback = (res: GeneralCallbackResult) => void; /** 音频播放错误事件的回调函数 */ type InnerAudioContextOnErrorCallback = ( result: InnerAudioContextOnErrorCallbackResult, ) => void; /** 音频暂停事件的回调函数 */ type InnerAudioContextOnPauseCallback = (res: GeneralCallbackResult) => void; /** 音频播放事件的回调函数 */ type InnerAudioContextOnPlayCallback = (res: GeneralCallbackResult) => void; /** 音频完成跳转操作的事件的回调函数 */ type InnerAudioContextOnSeekedCallback = (res: GeneralCallbackResult) => void; /** 音频进行跳转操作的事件的回调函数 */ type InnerAudioContextOnSeekingCallback = ( res: GeneralCallbackResult, ) => void; /** 音频停止事件的回调函数 */ type InnerAudioContextOnStopCallback = (res: GeneralCallbackResult) => void; /** 音频播放进度更新事件的回调函数 */ type InnerAudioContextOnTimeUpdateCallback = ( res: GeneralCallbackResult, ) => void; /** 音频加载中事件的回调函数 */ type InnerAudioContextOnWaitingCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type LivePlayerContextPauseCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type LivePlayerContextPauseFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type LivePlayerContextPauseSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type LivePlayerContextResumeCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type LivePlayerContextResumeFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type LivePlayerContextResumeSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type LivePlayerContextStopCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type LivePlayerContextStopFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type LivePlayerContextStopSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type LivePusherContextPauseCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type LivePusherContextPauseFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type LivePusherContextPauseSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type LivePusherContextResumeCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type LivePusherContextResumeFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type LivePusherContextResumeSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type LivePusherContextStopCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type LivePusherContextStopFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type LivePusherContextStopSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type LoadFontFaceCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type LoadFontFaceFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type LoadFontFaceSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type LoginCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type LoginFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type LoginSuccessCallback = (result: LoginSuccessCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type MakePhoneCallCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type MakePhoneCallFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type MakePhoneCallSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type MkdirCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type MkdirFailCallback = (result: MkdirFailCallbackResult) => void; /** 接口调用成功的回调函数 */ type MkdirSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type MuteCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type MuteFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type MuteSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type NavigateBackCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type NavigateBackFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type NavigateBackMiniProgramCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type NavigateBackMiniProgramFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type NavigateBackMiniProgramSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type NavigateBackSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type NavigateToCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type NavigateToFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type NavigateToMiniProgramCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type NavigateToMiniProgramFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type NavigateToMiniProgramSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type NavigateToSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type NotifyBLECharacteristicValueChangeCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type NotifyBLECharacteristicValueChangeFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type NotifyBLECharacteristicValueChangeSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 监听相交状态变化的回调函数 */ type ObserveCallback = (result: ObserveCallbackResult) => void; /** 小程序切后台事件的回调函数 */ type OffAppHideCallback = (res: GeneralCallbackResult) => void; /** 小程序切前台事件的回调函数 */ type OffAppShowCallback = (res: GeneralCallbackResult) => void; /** 音频进入可以播放状态的事件的回调函数 */ type OffCanplayCallback = (res: GeneralCallbackResult) => void; /** 音频自然播放至结束的事件的回调函数 */ type OffEndedCallback = (res: GeneralCallbackResult) => void; /** 音频播放错误事件的回调函数 */ type OffErrorCallback = (res: GeneralCallbackResult) => void; /** mDNS 服务停止搜索的事件的回调函数 */ type OffLocalServiceDiscoveryStopCallback = ( res: GeneralCallbackResult, ) => void; /** mDNS 服务发现的事件的回调函数 */ type OffLocalServiceFoundCallback = (res: GeneralCallbackResult) => void; /** mDNS 服务离开的事件的回调函数 */ type OffLocalServiceLostCallback = (res: GeneralCallbackResult) => void; /** mDNS 服务解析失败的事件的回调函数 */ type OffLocalServiceResolveFailCallback = ( res: GeneralCallbackResult, ) => void; /** 小程序要打开的页面不存在事件的回调函数 */ type OffPageNotFoundCallback = (res: GeneralCallbackResult) => void; /** 音频暂停事件的回调函数 */ type OffPauseCallback = (res: GeneralCallbackResult) => void; /** 音频播放事件的回调函数 */ type OffPlayCallback = (res: GeneralCallbackResult) => void; /** 音频完成跳转操作的事件的回调函数 */ type OffSeekedCallback = (res: GeneralCallbackResult) => void; /** 音频进行跳转操作的事件的回调函数 */ type OffSeekingCallback = (res: GeneralCallbackResult) => void; /** 音频停止事件的回调函数 */ type OffStopCallback = (res: GeneralCallbackResult) => void; /** 音频播放进度更新事件的回调函数 */ type OffTimeUpdateCallback = (res: GeneralCallbackResult) => void; /** 音频加载中事件的回调函数 */ type OffWaitingCallback = (res: GeneralCallbackResult) => void; /** 窗口尺寸变化事件的回调函数 */ type OffWindowResizeCallback = (res: GeneralCallbackResult) => void; /** 加速度数据事件的回调函数 */ type OnAccelerometerChangeCallback = ( result: OnAccelerometerChangeCallbackResult, ) => void; /** 小程序错误事件的回调函数 */ type OnAppErrorCallback = ( /** 错误信息,包含堆栈 */ error: string, ) => void; /** 小程序切后台事件的回调函数 */ type OnAppHideCallback = (res: GeneralCallbackResult) => void; /** 小程序切前台事件的回调函数 */ type OnAppShowCallback = (result: OnAppShowCallbackResult) => void; /** 低功耗蓝牙设备的特征值变化事件的回调函数 */ type OnBLECharacteristicValueChangeCallback = ( result: OnBLECharacteristicValueChangeCallbackResult, ) => void; /** 低功耗蓝牙连接状态的改变事件的回调函数 */ type OnBLEConnectionStateChangeCallback = ( result: OnBLEConnectionStateChangeCallbackResult, ) => void; /** 音乐暂停事件的回调函数 */ type OnBackgroundAudioPauseCallback = (res: GeneralCallbackResult) => void; /** 音乐播放事件的回调函数 */ type OnBackgroundAudioPlayCallback = (res: GeneralCallbackResult) => void; /** 音乐停止事件的回调函数 */ type OnBackgroundAudioStopCallback = (res: GeneralCallbackResult) => void; /** iBeacon 服务状态变化事件的回调函数 */ type OnBeaconServiceChangeCallback = ( result: OnBeaconServiceChangeCallbackResult, ) => void; /** iBeacon 设备更新事件的回调函数 */ type OnBeaconUpdateCallback = (result: OnBeaconUpdateCallbackResult) => void; /** 蓝牙适配器状态变化事件的回调函数 */ type OnBluetoothAdapterStateChangeCallback = ( result: OnBluetoothAdapterStateChangeCallbackResult, ) => void; /** 寻找到新设备的事件的回调函数 */ type OnBluetoothDeviceFoundCallback = ( result: OnBluetoothDeviceFoundCallbackResult, ) => void; /** 向微信后台请求检查更新结果事件的回调函数 */ type OnCheckForUpdateCallback = ( result: OnCheckForUpdateCallbackResult, ) => void; /** WebSocket 连接关闭事件的回调函数 */ type OnCloseCallback = (res: GeneralCallbackResult) => void; /** 罗盘数据变化事件的回调函数 */ type OnCompassChangeCallback = ( result: OnCompassChangeCallbackResult, ) => void; /** 设备方向变化事件的回调函数 */ type OnDeviceMotionChangeCallback = ( result: OnDeviceMotionChangeCallbackResult, ) => void; /** 已录制完指定帧大小的文件事件的回调函数 */ type OnFrameRecordedCallback = ( result: OnFrameRecordedCallbackResult, ) => void; /** 获取到 Wi-Fi 列表数据事件的回调函数 */ type OnGetWifiListCallback = (result: OnGetWifiListCallbackResult) => void; /** 陀螺仪数据变化事件的回调函数 */ type OnGyroscopeChangeCallback = ( result: OnGyroscopeChangeCallbackResult, ) => void; /** 接收 NFC 设备消息事件的回调函数 */ type OnHCEMessageCallback = (result: OnHCEMessageCallbackResult) => void; /** 录音因为受到系统占用而被中断开始事件的回调函数 */ type OnInterruptionBeginCallback = (res: GeneralCallbackResult) => void; /** 录音中断结束事件的回调函数 */ type OnInterruptionEndCallback = (res: GeneralCallbackResult) => void; /** mDNS 服务停止搜索的事件的回调函数 */ type OnLocalServiceDiscoveryStopCallback = ( res: GeneralCallbackResult, ) => void; /** mDNS 服务发现的事件的回调函数 */ type OnLocalServiceFoundCallback = ( result: OnLocalServiceFoundCallbackResult, ) => void; /** mDNS 服务离开的事件的回调函数 */ type OnLocalServiceLostCallback = ( result: OnLocalServiceLostCallbackResult, ) => void; /** mDNS 服务解析失败的事件的回调函数 */ type OnLocalServiceResolveFailCallback = ( result: OnLocalServiceResolveFailCallbackResult, ) => void; /** 内存不足告警事件的回调函数 */ type OnMemoryWarningCallback = ( result: OnMemoryWarningCallbackResult, ) => void; /** 网络状态变化事件的回调函数 */ type OnNetworkStatusChangeCallback = ( result: OnNetworkStatusChangeCallbackResult, ) => void; /** 用户在系统音乐播放面板点击下一曲事件的回调函数 */ type OnNextCallback = (res: GeneralCallbackResult) => void; /** WebSocket 连接打开事件的回调函数 */ type OnOpenCallback = (result: OnOpenCallbackResult) => void; /** 小程序要打开的页面不存在事件的回调函数 */ type OnPageNotFoundCallback = (res: GeneralCallbackResult) => void; /** 用户在系统音乐播放面板点击上一曲事件的回调函数 */ type OnPrevCallback = (res: GeneralCallbackResult) => void; /** 录音继续事件的回调函数 */ type OnResumeCallback = (res: GeneralCallbackResult) => void; /** WebSocket 连接关闭事件的回调函数 */ type OnSocketCloseCallback = (res: GeneralCallbackResult) => void; /** WebSocket 错误事件的回调函数 */ type OnSocketErrorCallback = (res: GeneralCallbackResult) => void; /** WebSocket 接受到服务器的消息事件的回调函数 */ type OnSocketMessageCallback = ( result: OnSocketMessageCallbackResult, ) => void; /** WebSocket 连接打开事件的回调函数 */ type OnSocketOpenCallback = (result: OnSocketOpenCallbackResult) => void; /** 录音开始事件的回调函数 */ type OnStartCallback = (res: GeneralCallbackResult) => void; /** 小程序更新失败事件的回调函数 */ type OnUpdateFailedCallback = (res: GeneralCallbackResult) => void; /** 小程序有版本更新事件的回调函数 */ type OnUpdateReadyCallback = (res: GeneralCallbackResult) => void; /** 用户主动截屏事件的回调函数 */ type OnUserCaptureScreenCallback = (res: GeneralCallbackResult) => void; /** 连接上 Wi-Fi 的事件的回调函数 */ type OnWifiConnectedCallback = ( result: OnWifiConnectedCallbackResult, ) => void; /** 窗口尺寸变化事件的回调函数 */ type OnWindowResizeCallback = (result: OnWindowResizeCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type OpenBluetoothAdapterCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type OpenBluetoothAdapterFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type OpenBluetoothAdapterSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type OpenCardCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type OpenCardFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type OpenCardSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type OpenDocumentCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type OpenDocumentFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type OpenDocumentSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type OpenLocationCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type OpenLocationFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type OpenLocationSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type OpenSettingCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type OpenSettingFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type OpenSettingSuccessCallback = ( result: OpenSettingSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type PageScrollToCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type PageScrollToFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type PageScrollToSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type PauseBGMCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type PauseBGMFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type PauseBGMSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type PauseBackgroundAudioCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type PauseBackgroundAudioFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type PauseBackgroundAudioSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type PauseVoiceCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type PauseVoiceFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type PauseVoiceSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type PlayBGMCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type PlayBGMFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type PlayBGMSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type PlayBackgroundAudioCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type PlayBackgroundAudioFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type PlayBackgroundAudioSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type PlayCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type PlayFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type PlaySuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type PlayVoiceCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type PlayVoiceFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type PlayVoiceSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type PreviewImageCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type PreviewImageFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type PreviewImageSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ReLaunchCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ReLaunchFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ReLaunchSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ReadBLECharacteristicValueCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type ReadBLECharacteristicValueFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type ReadBLECharacteristicValueSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ReadFileCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ReadFileFailCallback = (result: ReadFileFailCallbackResult) => void; /** 接口调用成功的回调函数 */ type ReadFileSuccessCallback = ( result: ReadFileSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ReaddirCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ReaddirFailCallback = (result: ReaddirFailCallbackResult) => void; /** 接口调用成功的回调函数 */ type ReaddirSuccessCallback = (result: ReaddirSuccessCallbackResult) => void; /** 录音错误事件的回调函数 */ type RecorderManagerOnErrorCallback = ( result: RecorderManagerOnErrorCallbackResult, ) => void; /** 录音暂停事件的回调函数 */ type RecorderManagerOnPauseCallback = (res: GeneralCallbackResult) => void; /** 录音结束事件的回调函数 */ type RecorderManagerOnStopCallback = (result: OnStopCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type RedirectToCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type RedirectToFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type RedirectToSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type RemoveStorageCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type RemoveStorageFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type RemoveStorageSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type RemoveTabBarBadgeCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type RemoveTabBarBadgeFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type RemoveTabBarBadgeSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type RenameCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type RenameFailCallback = (result: RenameFailCallbackResult) => void; /** 接口调用成功的回调函数 */ type RenameSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type RequestCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type RequestFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type RequestFullScreenCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type RequestFullScreenFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type RequestFullScreenSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type RequestPaymentCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type RequestPaymentFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type RequestPaymentSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type RequestSuccessCallback = (result: RequestSuccessCallbackResult) => void; /** HTTP Response Header 事件的回调函数 */ type RequestTaskOffHeadersReceivedCallback = ( res: GeneralCallbackResult, ) => void; /** HTTP Response Header 事件的回调函数 */ type RequestTaskOnHeadersReceivedCallback = ( result: RequestTaskOnHeadersReceivedCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ResumeBGMCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ResumeBGMFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ResumeBGMSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type RmdirCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type RmdirFailCallback = (result: RmdirFailCallbackResult) => void; /** 接口调用成功的回调函数 */ type RmdirSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SaveImageToPhotosAlbumCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type SaveImageToPhotosAlbumFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type SaveImageToPhotosAlbumSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SaveVideoToPhotosAlbumCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type SaveVideoToPhotosAlbumFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type SaveVideoToPhotosAlbumSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ScanCodeCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ScanCodeFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ScanCodeSuccessCallback = ( result: ScanCodeSuccessCallbackResult, ) => void; /** 回调函数,在执行 `SelectorQuery.exec` 方法后,节点信息会在 `callback` 中返回。 */ type ScrollOffsetCallback = (result: ScrollOffsetCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SeekBackgroundAudioCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type SeekBackgroundAudioFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SeekBackgroundAudioSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SendCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SendFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SendHCEMessageCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SendHCEMessageFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SendHCEMessageSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SendSocketMessageCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SendSocketMessageFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SendSocketMessageSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SendSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetBGMVolumeCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SetBGMVolumeFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetBGMVolumeSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetBackgroundColorCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type SetBackgroundColorFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetBackgroundColorSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetBackgroundTextStyleCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type SetBackgroundTextStyleFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type SetBackgroundTextStyleSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetClipboardDataCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SetClipboardDataFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetClipboardDataSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetEnableDebugCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SetEnableDebugFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetEnableDebugSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetInnerAudioOptionCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type SetInnerAudioOptionFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetInnerAudioOptionSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetKeepScreenOnCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SetKeepScreenOnFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetKeepScreenOnSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetNavigationBarColorCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type SetNavigationBarColorFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetNavigationBarColorSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetNavigationBarTitleCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type SetNavigationBarTitleFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetNavigationBarTitleSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetScreenBrightnessCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type SetScreenBrightnessFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetScreenBrightnessSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetStorageCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SetStorageFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetStorageSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetTabBarBadgeCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SetTabBarBadgeFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetTabBarBadgeSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetTabBarItemCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SetTabBarItemFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetTabBarItemSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetTabBarStyleCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SetTabBarStyleFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetTabBarStyleSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetTopBarTextCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SetTopBarTextFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetTopBarTextSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SetWifiListCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SetWifiListFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SetWifiListSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ShowActionSheetCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ShowActionSheetFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ShowActionSheetSuccessCallback = ( result: ShowActionSheetSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ShowLoadingCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ShowLoadingFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ShowLoadingSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ShowModalCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ShowModalFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ShowModalSuccessCallback = ( result: ShowModalSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ShowNavigationBarLoadingCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type ShowNavigationBarLoadingFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type ShowNavigationBarLoadingSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ShowShareMenuCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ShowShareMenuFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ShowShareMenuSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ShowTabBarCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ShowTabBarFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ShowTabBarRedDotCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ShowTabBarRedDotFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ShowTabBarRedDotSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ShowTabBarSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ShowToastCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ShowToastFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ShowToastSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SnapshotCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SnapshotFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SnapshotSuccessCallback = (res: GeneralCallbackResult) => void; /** WebSocket 错误事件的回调函数 */ type SocketTaskOnErrorCallback = ( result: SocketTaskOnErrorCallbackResult, ) => void; /** WebSocket 接受到服务器的消息事件的回调函数 */ type SocketTaskOnMessageCallback = ( result: SocketTaskOnMessageCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StartAccelerometerCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type StartAccelerometerFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StartAccelerometerSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StartBeaconDiscoveryCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type StartBeaconDiscoveryFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StartBeaconDiscoverySuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StartBluetoothDevicesDiscoveryCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type StartBluetoothDevicesDiscoveryFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type StartBluetoothDevicesDiscoverySuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StartCompassCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type StartCompassFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StartCompassSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StartCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StartDeviceMotionListeningCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type StartDeviceMotionListeningFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type StartDeviceMotionListeningSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type StartFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StartGyroscopeCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type StartGyroscopeFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StartGyroscopeSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StartHCECompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type StartHCEFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StartHCESuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StartLocalServiceDiscoveryCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type StartLocalServiceDiscoveryFailCallback = ( result: StartLocalServiceDiscoveryFailCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type StartLocalServiceDiscoverySuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StartPullDownRefreshCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type StartPullDownRefreshFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StartPullDownRefreshSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 超过30s或页面 `onHide` 时会结束录像 */ type StartRecordTimeoutCallback = ( result: StartRecordTimeoutCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StartSoterAuthenticationCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type StartSoterAuthenticationFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type StartSoterAuthenticationSuccessCallback = ( result: StartSoterAuthenticationSuccessCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type StartSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StartWifiCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type StartWifiFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StartWifiSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StatCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type StatFailCallback = (result: StatFailCallbackResult) => void; /** 接口调用成功的回调函数 */ type StatSuccessCallback = (result: StatSuccessCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StopAccelerometerCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type StopAccelerometerFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StopAccelerometerSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StopBGMCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type StopBGMFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StopBGMSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StopBackgroundAudioCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type StopBackgroundAudioFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StopBackgroundAudioSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StopBeaconDiscoveryCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type StopBeaconDiscoveryFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StopBeaconDiscoverySuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StopBluetoothDevicesDiscoveryCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type StopBluetoothDevicesDiscoveryFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type StopBluetoothDevicesDiscoverySuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StopCompassCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type StopCompassFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StopCompassSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StopDeviceMotionListeningCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type StopDeviceMotionListeningFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type StopDeviceMotionListeningSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StopGyroscopeCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type StopGyroscopeFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StopGyroscopeSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StopHCECompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type StopHCEFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StopHCESuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StopLocalServiceDiscoveryCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type StopLocalServiceDiscoveryFailCallback = ( result: StopLocalServiceDiscoveryFailCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type StopLocalServiceDiscoverySuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StopPullDownRefreshCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type StopPullDownRefreshFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StopPullDownRefreshSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StopRecordCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type StopRecordFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StopRecordSuccessCallback = ( result: StopRecordSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StopVoiceCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type StopVoiceFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StopVoiceSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type StopWifiCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type StopWifiFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type StopWifiSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SwitchCameraCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SwitchCameraFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SwitchCameraSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type SwitchTabCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type SwitchTabFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type SwitchTabSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type TakePhotoCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type TakePhotoFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type TakePhotoSuccessCallback = ( result: TakePhotoSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type ToggleTorchCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type ToggleTorchFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type ToggleTorchSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type TranslateMarkerCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type TranslateMarkerFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type TranslateMarkerSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type UnlinkCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type UnlinkFailCallback = (result: UnlinkFailCallbackResult) => void; /** 接口调用成功的回调函数 */ type UnlinkSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type UnzipCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type UnzipFailCallback = (result: UnzipFailCallbackResult) => void; /** 接口调用成功的回调函数 */ type UnzipSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type UpdateShareMenuCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type UpdateShareMenuFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type UpdateShareMenuSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type UploadFileCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type UploadFileFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type UploadFileSuccessCallback = ( result: UploadFileSuccessCallbackResult, ) => void; /** HTTP Response Header 事件的回调函数 */ type UploadTaskOffHeadersReceivedCallback = ( res: GeneralCallbackResult, ) => void; /** 上传进度变化事件的回调函数 */ type UploadTaskOffProgressUpdateCallback = ( res: GeneralCallbackResult, ) => void; /** HTTP Response Header 事件的回调函数 */ type UploadTaskOnHeadersReceivedCallback = ( result: UploadTaskOnHeadersReceivedCallbackResult, ) => void; /** 上传进度变化事件的回调函数 */ type UploadTaskOnProgressUpdateCallback = ( result: UploadTaskOnProgressUpdateCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type VibrateLongCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type VibrateLongFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type VibrateLongSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type VibrateShortCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type VibrateShortFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type VibrateShortSuccessCallback = (res: GeneralCallbackResult) => void; /** 主线程/Worker 线程向当前线程发送的消息的事件的回调函数 */ type WorkerOnMessageCallback = ( result: WorkerOnMessageCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type WriteBLECharacteristicValueCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type WriteBLECharacteristicValueFailCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用成功的回调函数 */ type WriteBLECharacteristicValueSuccessCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type WriteFileCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type WriteFileFailCallback = (result: WriteFileFailCallbackResult) => void; /** 接口调用成功的回调函数 */ type WriteFileSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type WxGetFileInfoCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type WxGetFileInfoFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type WxGetFileInfoSuccessCallback = ( result: WxGetFileInfoSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type WxGetSavedFileListCompleteCallback = ( res: GeneralCallbackResult, ) => void; /** 接口调用失败的回调函数 */ type WxGetSavedFileListFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type WxGetSavedFileListSuccessCallback = ( result: WxGetSavedFileListSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type WxRemoveSavedFileCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type WxRemoveSavedFileFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type WxRemoveSavedFileSuccessCallback = (res: GeneralCallbackResult) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type WxSaveFileCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type WxSaveFileFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type WxSaveFileSuccessCallback = ( result: WxSaveFileSuccessCallbackResult, ) => void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ type WxStartRecordCompleteCallback = (res: GeneralCallbackResult) => void; /** 接口调用失败的回调函数 */ type WxStartRecordFailCallback = (res: GeneralCallbackResult) => void; /** 接口调用成功的回调函数 */ type WxStartRecordSuccessCallback = ( result: StartRecordSuccessCallbackResult, ) => void; } declare const wx: wx.Wx; declare namespace App { interface ILaunchOptions { query: number } interface IReferrerInfo { /** 来源小程序或公众号或App的 appId * * 以下场景支持返回 referrerInfo.appId: * - 1020(公众号 profile 页相关小程序列表): appId * - 1035(公众号自定义菜单):来源公众号 appId * - 1036(App 分享消息卡片):来源应用 appId * - 1037(小程序打开小程序):来源小程序 appId * - 1038(从另一个小程序返回):来源小程序 appId * - 1043(公众号模板消息):来源公众号 appId */ appId: string /** 来源小程序传过来的数据,scene=1037或1038时支持 */ extraData?: any } type SceneValues = 1001 | 1005 | 1006 | 1007 | 1008 | 1011 | 1012 | 1013 | 1014 | 1017 | 1019 | 1020 | 1022 | 1023 | 1024 | 1025 | 1026 | 1027 | 1028 | 1029 | 1030 | 1031 | 1032 | 1034 | 1035 | 1036 | 1037 | 1038 | 1039 | 1042 | 1043 | 1044 | 1045 | 1046 | 1047 | 1048 | 1049 | 1052 | 1053 | 1054 | 1056 | 1057 | 1058 | 1059 | 1064 | 1067 | 1068 | 1069 | 1071 | 1072 | 1073 | 1074 | 1077 | 1078 | 1079 | 1081 | 1082 | 1084 | 1089 | 1090 | 1091 | 1092 | 1095 | 1096 | 1097 | 1099 | 1102 | 1103 | 1104 | number interface ILaunchShowOption { /** 打开小程序的路径 */ path: string /** 打开小程序的query */ query: IAnyObject /** 打开小程序的场景值 * - 1001: 发现栏小程序主入口,「最近使用」列表(基础库2.2.4版本起包含「我的小程序」列表) * - 1005: 顶部搜索框的搜索结果页 * - 1006: 发现栏小程序主入口搜索框的搜索结果页 * - 1007: 单人聊天会话中的小程序消息卡片 * - 1008: 群聊会话中的小程序消息卡片 * - 1011: 扫描二维码 * - 1012: 长按图片识别二维码 * - 1013: 手机相册选取二维码 * - 1014: 小程序模板消息 * - 1017: 前往体验版的入口页 * - 1019: 微信钱包 * - 1020: 公众号 profile 页相关小程序列表 * - 1022: 聊天顶部置顶小程序入口 * - 1023: 安卓系统桌面图标 * - 1024: 小程序 profile 页 * - 1025: 扫描一维码 * - 1026: 附近小程序列表 * - 1027: 顶部搜索框搜索结果页「使用过的小程序」列表 * - 1028: 我的卡包 * - 1029: 卡券详情页 * - 1030: 自动化测试下打开小程序 * - 1031: 长按图片识别一维码 * - 1032: 手机相册选取一维码 * - 1034: 微信支付完成页 * - 1035: 公众号自定义菜单 * - 1036: App 分享消息卡片 * - 1037: 小程序打开小程序 * - 1038: 从另一个小程序返回 * - 1039: 摇电视 * - 1042: 添加好友搜索框的搜索结果页 * - 1043: 公众号模板消息 * - 1044: 带 shareTicket 的小程序消息卡片 [详情]((转发#获取更多转发信息)) * - 1045: 朋友圈广告 * - 1046: 朋友圈广告详情页 * - 1047: 扫描小程序码 * - 1048: 长按图片识别小程序码 * - 1049: 手机相册选取小程序码 * - 1052: 卡券的适用门店列表 * - 1053: 搜一搜的结果页 * - 1054: 顶部搜索框小程序快捷入口 * - 1056: 音乐播放器菜单 * - 1057: 钱包中的银行卡详情页 * - 1058: 公众号文章 * - 1059: 体验版小程序绑定邀请页 * - 1064: 微信连Wi-Fi状态栏 * - 1067: 公众号文章广告 * - 1068: 附近小程序列表广告 * - 1069: 移动应用 * - 1071: 钱包中的银行卡列表页 * - 1072: 二维码收款页面 * - 1073: 客服消息列表下发的小程序消息卡片 * - 1074: 公众号会话下发的小程序消息卡片 * - 1077: 摇周边 * - 1078: 连Wi-Fi成功页 * - 1079: 微信游戏中心 * - 1081: 客服消息下发的文字链 * - 1082: 公众号会话下发的文字链 * - 1084: 朋友圈广告原生页 * - 1089: 微信聊天主界面下拉,「最近使用」栏(基础库2.2.4版本起包含「我的小程序」栏) * - 1090: 长按小程序右上角菜单唤出最近使用历史 * - 1091: 公众号文章商品卡片 * - 1092: 城市服务入口 * - 1095: 小程序广告组件 * - 1096: 聊天记录 * - 1097: 微信支付签约页 * - 1099: 页面内嵌插件 * - 1102: 公众号 profile 页服务预览 * - 1103: 发现栏小程序主入口,「我的小程序」列表(基础库2.2.4版本起废弃) * - 1104: 微信聊天主界面下拉,「我的小程序」栏(基础库2.2.4版本起废弃) */ scene: SceneValues /** shareTicket,详见 [获取更多转发信息]((转发#获取更多转发信息)) */ shareTicket: string /** 当场景为由从另一个小程序或公众号或App打开时,返回此字段 */ referrerInfo?: IReferrerInfo } interface IPageNotFoundOption { /** 不存在页面的路径 */ path: string /** 打开不存在页面的 query */ query: IAnyObject /** 是否本次启动的首个页面(例如从分享等入口进来,首个页面是开发者配置的分享页面) */ isEntryPage: boolean } interface AppInstance<T extends IAnyObject = {}> { /** 生命周期回调—监听小程序初始化 * * 小程序初始化完成时触发,全局只触发一次。 */ onLaunch?(options?: ILaunchShowOption): void /** 生命周期回调—监听小程序显示 * * 小程序启动,或从后台进入前台显示时 */ onShow?(options?: ILaunchShowOption): void /** 生命周期回调—监听小程序隐藏 * * 小程序从前台进入后台时 */ onHide?(): void /** 错误监听函数 * * 小程序发生脚本错误,或者 api */ onError?(/** 错误信息,包含堆栈 */error?: string): void /** 页面不存在监听函数 * * 小程序要打开的页面不存在时触发,会带上页面信息回调该函数 * * **注意:** * 1. 如果开发者没有添加 `onPageNotFound` 监听,当跳转页面不存在时,将推入微信客户端原生的页面不存在提示页面。 * 2. 如果 `onPageNotFound` 回调中又重定向到另一个不存在的页面,将推入微信客户端原生的页面不存在提示页面,并且不再回调 `onPageNotFound`。 * * 最低基础库: 1.9.90 */ onPageNotFound?(options?: IPageNotFoundOption): void } interface AppConstructor { <T extends IAnyObject & AppInstance>( options: AppInstance<T> & T ): void } interface IGetAppOption { /** 在 `App` 未定义时返回默认实现。当App被调用时,默认实现中定义的属性会被覆盖合并到App中。一般用于独立分包 * * 最低基础库: 2.2.4 */ allowDefault: boolean } interface GetApp { <T extends IAnyObject>(opts?: IGetAppOption): AppInstance<T> & T } } declare const App: App.AppConstructor declare const getApp: App.GetApp declare namespace Page { interface ICustomShareContent { /** 转发标题。默认值:当前小程序名称 */ title?: string /** 转发路径,必须是以 / 开头的完整路径。默认值:当前页面 path */ path?: string /** 自定义图片路径,可以是本地文件路径、代码包文件路径或者网络图片路径。支持PNG及JPG。显示图片长宽比是 5:4,最低基础库: `1.5.0`。默认值:使用默认截图 */ imageUrl?: string } interface IPageScrollOption { /** 页面在垂直方向已滚动的距离(单位px) */ scrollTop: number } interface IShareAppMessageOption { /** 转发事件来源。 * * 可选值: * - `button`:页面内转发按钮; * - `menu`:右上角转发菜单。 * * 最低基础库: `1.2.4` */ from: 'button' | 'menu' | string /** 如果 `from` 值是 `button`,则 `target` 是触发这次转发事件的 `button`,否则为 `undefined` * * 最低基础库: `1.2.4` */ target: any /** 页面中包含`<web-view>`组件时,返回当前`<web-view>`的url * * 最低基础库: `1.6.4` */ webViewUrl?: string } interface ITabItemTapOption { /** 被点击tabItem的序号,从0开始,最低基础库: `1.9.0` */ index: string /** 被点击tabItem的页面路径,最低基础库: `1.9.0` */ pagePath: string /** 被点击tabItem的按钮文字,最低基础库: `1.9.0` */ text: string } interface PageInstanceBaseProps<D extends IAnyObject = any> { /** 页面的初始数据 * * `data` 是页面第一次渲染使用的**初始数据**。 * * 页面加载时,`data` 将会以`JSON`字符串的形式由逻辑层传至渲染层,因此`data`中的数据必须是可以转成`JSON`的类型:字符串,数字,布尔值,对象,数组。 * * 渲染层可以通过 `WXML` 对数据进行绑定。 */ data?: D /** `setData` 函数用于将数据从逻辑层发送到视图层(异步),同时改变对应的 `this.data` 的值(同步)。 * * **注意:** * * 1. **直接修改 this.data 而不调用 this.setData 是无法改变页面的状态的,还会造成数据不一致**。 * 1. 仅支持设置可 JSON 化的数据。 * 1. 单次设置的数据不能超过1024kB,请尽量避免一次设置过多的数据。 * 1. 请不要把 data 中任何一项的 value 设为 `undefined` ,否则这一项将不被设置并可能遗留一些潜在问题。 */ setData?<K extends keyof D>( /** 这次要改变的数据 * * 以 `key: value` 的形式表示,将 `this.data` 中的 `key` 对应的值改变成 `value`。 * * 其中 `key` 可以以数据路径的形式给出,支持改变数组中的某一项或对象的某个属性,如 `array[2].message`,`a.b.c.d`,并且不需要在 this.data 中预先定义。 */ data: D | Pick<D, K> | IAnyObject, /** setData引起的界面更新渲染完毕后的回调函数,最低基础库: `1.5.0` */ callback?: () => void ): void /** 到当前页面的路径,类型为`String`。最低基础库: `1.2.0` */ route?: string } interface PageInstance<D extends IAnyObject = any, T extends IAnyObject = any> extends PageInstanceBaseProps<D> { /** 生命周期回调—监听页面加载 * * 页面加载时触发。一个页面只会调用一次,可以在 onLoad 的参数中获取打开当前页面路径中的参数。 */ onLoad?( /** 打开当前页面路径中的参数 */ query?: { [queryKey: string]: string } ): void /** 生命周期回调—监听页面显示 * * 页面显示/切入前台时触发。 */ onShow?(): void /** 生命周期回调—监听页面初次渲染完成 * * 页面初次渲染完成时触发。一个页面只会调用一次,代表页面已经准备妥当,可以和视图层进行交互。 * * 注意:对界面内容进行设置的 API 如`wx.setNavigationBarTitle`,请在`onReady`之后进行。 */ onReady?(): void /** 生命周期回调—监听页面隐藏 * * 页面隐藏/切入后台时触发。 如 `navigateTo` 或底部 `tab` 切换到其他页面,小程序切入后台等。 */ onHide?(): void /** 生命周期回调—监听页面卸载 * * 页面卸载时触发。如`redirectTo`或`navigateBack`到其他页面时。 */ onUnload?(): void /** 监听用户下拉动作 * * 监听用户下拉刷新事件。 * - 需要在`app.json`的`window`选项中或页面配置中开启`enablePullDownRefresh`。 * - 可以通过`wx.startPullDownRefresh`触发下拉刷新,调用后触发下拉刷新动画,效果与用户手动下拉刷新一致。 * - 当处理完数据刷新后,`wx.stopPullDownRefresh`可以停止当前页面的下拉刷新。 */ onPullDownRefresh?(): void /** 页面上拉触底事件的处理函数 * * 监听用户上拉触底事件。 * - 可以在`app.json`的`window`选项中或页面配置中设置触发距离`onReachBottomDistance`。 * - 在触发距离内滑动期间,本事件只会被触发一次。 */ onReachBottom?(): void /** 用户点击右上角转发 * * 监听用户点击页面内转发按钮(`<button>` 组件 `open-type="share"`)或右上角菜单“转发”按钮的行为,并自定义转发内容。 * * **注意:只有定义了此事件处理函数,右上角菜单才会显示“转发”按钮** * * 此事件需要 return 一个 Object,用于自定义转发内容 */ onShareAppMessage?( /** 分享发起来源参数 */ options?: IShareAppMessageOption ): ICustomShareContent /** 页面滚动触发事件的处理函数 * * 监听用户滑动页面事件。 */ onPageScroll?( /** 页面滚动参数 */ options?: IPageScrollOption ): void /** 当前是 tab 页时,点击 tab 时触发,最低基础库: `1.9.0` */ onTabItemTap?( /** tab 点击参数 */ options?: ITabItemTapOption ): void } interface PageConstructor { <D extends IAnyObject, T extends IAnyObject & PageInstance>( options: PageInstance<D, T> & T ): void } interface GetCurrentPages { <D extends IAnyObject = {}, T extends IAnyObject = {}>(): (PageInstance<D, T> & T)[] } } declare const Page: Page.PageConstructor declare const getCurrentPages: Page.GetCurrentPages ///////////////////// ///// WX Cloud Apis ///////////////////// /** * Common interfaces and types */ interface IAPIError { errMsg: string, } interface IAPIParam<T = any> { config?: ICloudConfig, success?: (res: T) => void, fail?: (err: IAPIError) => void, complete?: (val: T | IAPIError) => void, } interface IAPISuccessParam { errMsg: string, } type IAPICompleteParam = IAPISuccessParam | IAPIError type IAPIFunction<T, P extends IAPIParam<T>> = (param: P) => Promise<T> | any interface IInitCloudConfig { env?: string | { database?: string, functions?: string, storage?: string, }, traceUser?: boolean, } interface ICloudConfig { env?: string, traceUser?: boolean, } interface IICloudAPI { init: (config?: IInitCloudConfig) => void, [api: string]: AnyFunction | IAPIFunction<any, any>, } interface ICloudService { name: string, getAPIs: () => { [name: string]: IAPIFunction<any, any> }, } interface ICloudServices { [serviceName: string]: ICloudService } interface ICloudMetaData { session_id: string, } declare class InternalSymbol { } type AnyObject = { [x: string]: any } type AnyArray = any[] type AnyFunction = (...args: any[]) => any /** * original wx */ declare namespace WXNS { interface AnyObject { [key: string]: any } interface IAPIParam<T> { success?: (res: T) => void, fail?: (err: IAPIError) => void, complete?: (val: T | IAPIError) => void, } interface CommonAPIResult { errMsg: string, } interface IAPIError { errMsg: string, } interface IProgressUpdateEvent { progress: number, totalBytesWritten: number, totalBytesExpectedToWrite: number, } interface operateWXData { (param: any): void } interface uploadFile { /** * upload file * @param param */ (param: IUploadFileParam): IUploadFileTask } interface IUploadFileParam extends IAPIParam<IUploadFileSuccessResult> { url: string, filePath: string, name: string, header?: AnyObject, } interface IUploadFileSuccessResult extends CommonAPIResult { data: string, statusCode: number, } interface IUploadFileTask { onProgressUpdate: (fn: (event: IProgressUpdateEvent) => void) => void, abort: AnyFunction, } interface downloadFile { /** * download file * @param param */ (param: IDownloadFileParam): IDownloadFileTask } interface IDownloadFileParam extends IAPIParam<IDownloadFileSuccessResult> { url: string, header?: AnyObject, } interface IDownloadFileSuccessResult extends CommonAPIResult { tempFilePath: string, statusCode: number, } interface IDownloadFileTask { onProgressUpdate: (fn: (event: IProgressUpdateEvent) => void) => void, abort: AnyFunction, } interface request { (param: IRequestParam): IRequestTask } interface IRequestParam extends IAPIParam<IRequestSuccessResult> { url: string, data?: AnyObject | string | ArrayBuffer, header?: AnyObject, method?: string, dataType?: string, responseType?: string, } interface IRequestSuccessResult { data: AnyObject | string | ArrayBuffer, statusCode: number, header: AnyObject, } interface IRequestTask { abort: () => void } interface getFileInfo { (param: IGetFileInfoParam): void } interface IGetFileInfoParam extends IAPIParam<IGetFileInfoSuccessResult> { filePath: string, digestAlgorithm?: string, } interface IGetFileInfoSuccessResult { size: number, digest: string, } } declare namespace wx { interface WX { cloud: { init: (config?: ICloudConfig) => void, // callFunction: (param: ICloud.CallFunctionParam) => Promise<ICloud.CallFunctionResult> | void, // uploadFile: (param: ICloud.UploadFileParam) => Promise<ICloud.UploadFileResult> | WXNS.IUploadFileTask, // downloadFile: (param: ICloud.DownloadFileParam) => Promise<ICloud.DownloadFileResult> | WXNS.IDownloadFileTask, // getTempFileURL: (param: ICloud.GetTempFileURLParam) => Promise<ICloud.GetTempFileURLResult> | void, // deleteFile: (param: ICloud.DeleteFileParam) => Promise<ICloud.DeleteFileResult> | void, callFunction(param: OQ<ICloud.CallFunctionParam>): void callFunction(param: RQ<ICloud.CallFunctionParam>): Promise<ICloud.CallFunctionResult> uploadFile(param: OQ<ICloud.UploadFileParam>): WXNS.IUploadFileTask uploadFile(param: RQ<ICloud.UploadFileParam>): Promise<ICloud.UploadFileResult> downloadFile(param: OQ<ICloud.DownloadFileParam>): WXNS.IDownloadFileTask downloadFile(param: RQ<ICloud.DownloadFileParam>): Promise<ICloud.DownloadFileResult> getTempFileURL(param: OQ<ICloud.GetTempFileURLParam>): void, getTempFileURL(param: RQ<ICloud.GetTempFileURLParam>): Promise<ICloud.GetTempFileURLResult> deleteFile(param: OQ<ICloud.DeleteFileParam>): void, deleteFile(param: RQ<ICloud.DeleteFileParam>): Promise<ICloud.DeleteFileResult> database: (config?: ICloudConfig) => DB.Database, } } } declare namespace ICloud { interface ICloudAPIParam<T = any> extends IAPIParam<T> { config?: ICloudConfig } // === API: callFunction === export type CallFunctionData = AnyObject export interface CallFunctionResult extends IAPISuccessParam { result: AnyObject | string | undefined, } export interface CallFunctionParam extends ICloudAPIParam<CallFunctionResult> { name: string, data?: CallFunctionData, slow?: boolean, } // === end === // === API: uploadFile === export interface UploadFileResult extends IAPISuccessParam { fileID: string, statusCode: number, } export interface UploadFileParam extends ICloudAPIParam<UploadFileResult> { cloudPath: string, filePath: string, header?: AnyObject, } // === end === // === API: downloadFile === export interface DownloadFileResult extends IAPISuccessParam { tempFilePath: string, statusCode: number, } export interface DownloadFileParam extends ICloudAPIParam<DownloadFileResult> { fileID: string, cloudPath?: string, } // === end === // === API: getTempFileURL === export interface GetTempFileURLResult extends IAPISuccessParam { fileList: GetTempFileURLResultItem[], } export interface GetTempFileURLResultItem { fileID: string, tempFileURL: string, maxAge: number, status: number, errMsg: string, } export interface GetTempFileURLParam extends ICloudAPIParam<GetTempFileURLResult> { fileList: string[], } // === end === // === API: deleteFile === interface DeleteFileResult extends IAPISuccessParam { fileList: DeleteFileResultItem[], } interface DeleteFileResultItem { fileID: string, status: number, errMsg: string, } interface DeleteFileParam extends ICloudAPIParam<DeleteFileResult> { fileList: string[], } // === end === } // === Database === declare namespace DB { /** * The class of all exposed cloud database instances */ export class Database { public readonly config: ICloudConfig public readonly command: DatabaseCommand public readonly Geo: Geo public readonly serverDate: () => ServerDate private constructor(); collection(collectionName: string): CollectionReference } export class CollectionReference extends Query { public readonly collectionName: string public readonly database: Database private constructor(name: string, database: Database) doc(docId: string | number): DocumentReference // add(options: IAddDocumentOptions): Promise<IAddResult> | void add(options: OQ<IAddDocumentOptions>): void add(options: RQ<IAddDocumentOptions>): Promise<IAddResult> } export class DocumentReference { private constructor(docId: string | number, database: Database) field(object: object): this // get(options?: IGetDocumentOptions): Promise<IQuerySingleResult> | void // set(options?: ISetSingleDocumentOptions): Promise<ISetResult> | void // update(options?: IUpdateSingleDocumentOptions): Promise<IUpdateResult> | void // remove(options?: IRemoveSingleDocumentOptions): Promise<IRemoveResult> | void // get(options?: IGetDocumentOptions): Promise<IQuerySingleResult> | void get(): Promise<IQuerySingleResult> get(options: OQ<IGetDocumentOptions>): void get(options: RQ<IGetDocumentOptions>): Promise<IQuerySingleResult> // set(options?: ISetSingleDocumentOptions): Promise<ISetResult> | void set(): Promise<ISetResult> set(options: OQ<ISetSingleDocumentOptions>): void set(options: RQ<ISetSingleDocumentOptions>): Promise<ISetResult> // update(options?: IUpdateSingleDocumentOptions): Promise<IUpdateResult> | void update(): Promise<IUpdateResult> update(options: OQ<IUpdateSingleDocumentOptions>): void update(options: RQ<IUpdateSingleDocumentOptions>): Promise<IUpdateResult> // remove(options?: IRemoveSingleDocumentOptions): Promise<IRemoveResult> | void remove(): Promise<IRemoveResult> remove(options: OQ<IRemoveSingleDocumentOptions>): void remove(options: RQ<IRemoveSingleDocumentOptions>): Promise<IRemoveResult> } export class Query { where(condition: IQueryCondition): Query orderBy(fieldPath: string, order: string): Query limit(max: number): Query skip(offset: number): Query field(object: object): Query // get(options?: IGetDocumentOptions): Promise<IQueryResult> | void // // update(options?: IUpdateDocumentOptions): Promise<IUpdateResult> | void // // remove(options?: IRemoveDocumentOptions): Promise<IRemoveResult> | void // count(options?: ICountDocumentOptions): Promise<ICountResult> | void // get(options?: IGetDocumentOptions): Promise<IQueryResult> | void get(): Promise<IQueryResult> get(options: OQ<IGetDocumentOptions>): void get(options: RQ<IGetDocumentOptions>): Promise<IQueryResult> // update(options?: IUpdateDocumentOptions): Promise<IUpdateResult> | void // remove(options?: IRemoveDocumentOptions): Promise<IRemoveResult> | void // count(options?: ICountDocumentOptions): Promise<ICountResult> | void count(): Promise<ICountResult> count(options: OQ<ICountDocumentOptions>): void count(options: RQ<ICountDocumentOptions>): Promise<ICountResult> } export interface DatabaseCommand { eq(val: any): DatabaseQueryCommand neq(val: any): DatabaseQueryCommand gt(val: any): DatabaseQueryCommand gte(val: any): DatabaseQueryCommand lt(val: any): DatabaseQueryCommand lte(val: any): DatabaseQueryCommand in(val: any[]): DatabaseQueryCommand nin(val: any[]): DatabaseQueryCommand and(...expressions: (DatabaseLogicCommand | IQueryCondition)[]): DatabaseLogicCommand or(...expressions: (DatabaseLogicCommand | IQueryCondition)[]): DatabaseLogicCommand set(val: any): DatabaseUpdateCommand remove(): DatabaseUpdateCommand inc(val: number): DatabaseUpdateCommand mul(val: number): DatabaseUpdateCommand push(...values: any[]): DatabaseUpdateCommand pop(): DatabaseUpdateCommand shift(): DatabaseUpdateCommand unshift(...values: any[]): DatabaseUpdateCommand } export enum LOGIC_COMMANDS_LITERAL { AND = 'and', OR = 'or', NOT = 'not', NOR = 'nor', } export class DatabaseLogicCommand { public fieldName: string | InternalSymbol public operator: LOGIC_COMMANDS_LITERAL | string public operands: any[] _setFieldName(fieldName: string): DatabaseLogicCommand and(...expressions: (DatabaseLogicCommand | IQueryCondition)[]): DatabaseLogicCommand or(...expressions: (DatabaseLogicCommand | IQueryCondition)[]): DatabaseLogicCommand } export enum QUERY_COMMANDS_LITERAL { EQ = 'eq', NEQ = 'neq', GT = 'gt', GTE = 'gte', LT = 'lt', LTE = 'lte', IN = 'in', NIN = 'nin', } export class DatabaseQueryCommand extends DatabaseLogicCommand { ; public operator: QUERY_COMMANDS_LITERAL | string _setFieldName(fieldName: string): DatabaseQueryCommand eq(val: any): DatabaseLogicCommand neq(val: any): DatabaseLogicCommand gt(val: any): DatabaseLogicCommand gte(val: any): DatabaseLogicCommand lt(val: any): DatabaseLogicCommand lte(val: any): DatabaseLogicCommand in(val: any[]): DatabaseLogicCommand nin(val: any[]): DatabaseLogicCommand } export enum UPDATE_COMMANDS_LITERAL { SET = 'set', REMOVE = 'remove', INC = 'inc', MUL = 'mul', PUSH = 'push', POP = 'pop', SHIFT = 'shift', UNSHIFT = 'unshift' } export class DatabaseUpdateCommand { public fieldName: string | InternalSymbol public operator: UPDATE_COMMANDS_LITERAL public operands: any[] constructor(operator: UPDATE_COMMANDS_LITERAL, operands: any[], fieldName?: string | InternalSymbol) _setFieldName(fieldName: string): DatabaseUpdateCommand; } export class Batch { } /** * A contract that all API provider must adhere to */ export class APIBaseContract<PROMISE_RETURN, CALLBACK_RETURN, PARAM extends IAPIParam, CONTEXT = any> { getContext(param: PARAM): CONTEXT /** * In case of callback-style invocation, this function will be called */ getCallbackReturn(param: PARAM, context: CONTEXT): CALLBACK_RETURN getFinalParam<T extends PARAM>(param: PARAM, context: CONTEXT): T run<T extends PARAM>(param: T): Promise<PROMISE_RETURN> } export interface GeoPointConstructor { new(longitude: number, latitide: number): GeoPoint; } export interface Geo { Point: { new(longitude: number, latitide: number): GeoPoint (longitude: number, latitide: number): GeoPoint}; } export abstract class GeoPoint { public longitude: number; public latitude: number constructor(longitude: number, latitude: number) toJSON(): object toString(): string } export interface IServerDateOptions { offset: number } export abstract class ServerDate { public readonly options: IServerDateOptions constructor(options?: IServerDateOptions) } export type DocumentId = string | number export interface IDocumentData { _id?: DocumentId; [key: string]: any, } export interface IDBAPIParam extends IAPIParam { } export interface IAddDocumentOptions extends IDBAPIParam { data: IDocumentData, } export interface IGetDocumentOptions extends IDBAPIParam { } export interface ICountDocumentOptions extends IDBAPIParam { } export interface IUpdateDocumentOptions extends IDBAPIParam { data: IUpdateCondition, } export interface IUpdateSingleDocumentOptions extends IDBAPIParam { data: IUpdateCondition, } export interface ISetDocumentOptions extends IDBAPIParam { data: IUpdateCondition, } export interface ISetSingleDocumentOptions extends IDBAPIParam { data: IUpdateCondition, } export interface IRemoveDocumentOptions extends IDBAPIParam { query: IQueryCondition, } export interface IRemoveSingleDocumentOptions extends IDBAPIParam { } export interface IQueryCondition { [key: string]: any, } export type IStringQueryCondition = string export interface IQueryResult extends IAPISuccessParam { data: IDocumentData[], } export interface IQuerySingleResult extends IAPISuccessParam { data: IDocumentData, } export interface IUpdateCondition { [key: string]: any, } export type IStringUpdateCondition = string export interface ISetCondition { } export interface IAddResult extends IAPISuccessParam { _id: DocumentId, } export interface IUpdateResult extends IAPISuccessParam { stats: { updated: number, // created: number, } } export interface ISetResult extends IAPISuccessParam { _id: DocumentId, stats: { updated: number, created: number, } } export interface IRemoveResult extends IAPISuccessParam { stats: { removed: number, } } export interface ICountResult extends IAPISuccessParam { total: number } } /** * Utils */ declare type Required<T> = { [P in keyof T]-?: T[P]; }; type OQ<T extends Optional<Record<'complete' | 'success' | 'fail', (...args: any[]) => any>>> = (RQ<T> & Required<Pick<T, 'success'>>) | (RQ<T> & Required<Pick<T, 'fail'>>) | (RQ<T> & Required<Pick<T, 'complete'>>) | (RQ<T> & Required<Pick<T, 'success' | 'fail'>>) | (RQ<T> & Required<Pick<T, 'success' | 'complete'>>) | (RQ<T> & Required<Pick<T, 'fail' | 'complete'>>) | (RQ<T> & Required<Pick<T, 'fail' | 'complete' | 'success'>>) type RQ<T extends Optional<Record<'complete' | 'success' | 'fail', (...args: any[]) => any>>> = Pick<T, Exclude<keyof T, 'complete' | 'success' | 'fail'>> declare type IAnyObject = Record<string, any> declare type Exclude<T, U> = T extends U ? never : T; declare type KVInfer<T> = { [K in keyof T]: T[K] } declare type Void<T> = T | undefined | null type PartialOptional<T, K extends keyof T> = Partial<Pick<T, K>> & Pick<T, Exclude<keyof T, K>> type Optional<T> = { [K in keyof T]+?: T[K] }
the_stack
import { Channel, Client, Endorsement, Endorser, Endpoint, IdentityContext, ProposalResponse, User, Utils, ConnectOptions, EndorsementResponse } from 'fabric-common'; import * as protos from 'fabric-protos'; import { Identity, IdentityProvider, Wallet } from 'fabric-network'; import { LifecycleCommon } from './LifecycleCommon'; const logger: any = Utils.getLogger('LifecyclePeer'); export interface LifecyclePeerOptions { name: string, url: string, mspid: string, sslTargetNameOverride?: string, pem?: string, clientCertKey?: string; clientKey?: string; requestTimeout?: number; apiOptions?: object; } export interface InstalledSmartContract { label: string; packageId: string; } export class LifecyclePeer { public name!: string; public url!: string; public mspid!: string; public sslTargetNameOverride?: string; public pem?: string; public clientCertKey?: string; public clientKey?: string; public requestTimeout?: number; public apiOptions?: object; private wallet: Wallet | undefined; private identity: string | undefined; /** * internal use only * @param options: LifecyclePeerOptions */ constructor(options: LifecyclePeerOptions) { Object.assign(this, options); } /** * Set the wallet and identity that you want to use when doing lifecycle operations * @param wallet Wallet, the wallet containing the identity to be used to interact with the peer * @param identity string, the name of the identity to be used to interact with the peer */ public setCredentials(wallet: Wallet, identity: string): void { this.wallet = wallet; this.identity = identity; } /** * Install a smart contract package onto a peer * @param buffer Buffer, the smart contract package buffer * @param requestTimeout number, [optional] the timeout used when performing the install operation * @return Promise<string>, the packageId of the installed smart contract */ public async installSmartContractPackage(buffer: Buffer, requestTimeout?: number): Promise<string | undefined> { const method: string = 'installPackage'; logger.debug(method); let packageId: string | undefined; if (!buffer) { throw new Error('parameter buffer missing'); } try { logger.debug('%s - build the install smart contract request', method); const protoArgs: protos.lifecycle.IInstallChaincodeArgs = {}; protoArgs.chaincode_install_package = new Uint8Array(buffer); const arg: Uint8Array = protos.lifecycle.InstallChaincodeArgs.encode(protoArgs).finish(); const buildRequest: { fcn: string; args: Buffer[] } = { fcn: 'InstallChaincode', args: [Buffer.from(arg)] }; const responses: ProposalResponse = await this.sendRequest(buildRequest, '_lifecycle', requestTimeout); const payloads: Buffer[] = await LifecycleCommon.processResponse(responses); const installChaincodeResult: protos.lifecycle.InstallChaincodeResult = protos.lifecycle.InstallChaincodeResult.decode(payloads[0]); packageId = installChaincodeResult.package_id; logger.debug('%s - return %s', method, packageId); return packageId; } catch (error) { logger.error('Problem with the request :: %s', error); logger.error(' problem at ::' + error.stack); throw new Error(`Could not install smart contact received error: ${error.message}`); } } /** * Install a smart contract package - CDS - onto a peer * @param buffer Buffer, the smart contract package buffer * @param requestTimeout number, [optional] the timeout used when performing the install operation * @return Promise<void>, nothing to return */ public async installSmartContractPackageCds(buffer: Buffer, requestTimeout?: number): Promise<void> { const method: string = 'installPackage'; logger.debug(method); if (!buffer) { throw new Error('parameter buffer missing'); } try { logger.debug('%s - build the install smart contract request', method); const buildRequest: { fcn: string; args: Buffer[] } = { fcn: 'install', args: [buffer] }; const responses: ProposalResponse = await this.sendRequest(buildRequest, 'lscc', requestTimeout); await LifecycleCommon.processResponse(responses); logger.debug('%s - return %s', method); return; } catch (error) { logger.error('Problem with the request :: %s', error); logger.error(' problem at ::' + error.stack); throw new Error(`Could not install smart contact received error: ${error.message}`); } } /** * Get all the smart contracts installed on a peer * @param requestTimeout number [optional, [optional] the timeout used when performing the install operation * @return Promise<InstalledSmartContract>, the label and packageId of each installed smart contract */ public async getAllInstalledSmartContracts(requestTimeout?: number): Promise<InstalledSmartContract[]> { const method: string = 'getAllInstalledSmartContracts'; logger.debug(method); const results: InstalledSmartContract[] = []; try { logger.debug('%s - build the get all installed smart contracts request', method); const arg: Uint8Array = protos.lifecycle.QueryInstalledChaincodesArgs.encode({}).finish(); const buildRequest: { fcn: string; args: Buffer[] } = { fcn: 'QueryInstalledChaincodes', args: [Buffer.from(arg)] }; const responses: ProposalResponse = await this.sendRequest(buildRequest, '_lifecycle', requestTimeout); const payloads: Buffer[] = await LifecycleCommon.processResponse(responses); // only sent to one peer so should only be one payload const queryAllResults: protos.lifecycle.QueryInstalledChaincodesResult = protos.lifecycle.QueryInstalledChaincodesResult.decode(payloads[0]); for (const queryResults of queryAllResults.installed_chaincodes) { const packageId: string = queryResults.package_id; const label: string = queryResults.label; const result: InstalledSmartContract = { packageId: packageId, label: label }; results.push(result); } logger.debug('%s - end', method); return results; } catch (error) { logger.error('Problem with the request :: %s', error); logger.error(' problem at ::' + error.stack); throw new Error(`Could not get all the installed smart contract packages, received: ${error.message}`); } } public async getAllInstalledSmartContractsV1(requestTimeout?: number): Promise<InstalledSmartContract[]> { const method: string = 'getAllInstalledSmartContracts'; logger.debug(method); const results: InstalledSmartContract[] = []; try { logger.debug('%s - build the get all installed smart contracts request', method); const buildRequest: { fcn: string; args: Buffer[] } = { fcn: 'GetInstalledChaincodes', args: [] }; const result: ProposalResponse = await this.sendRequest(buildRequest, 'lscc', requestTimeout); if (result) { // will only be one response as we are only querying one peer if (result.errors && result.errors[0] instanceof Error) { throw result.errors[0]; } const response: EndorsementResponse = result.responses[0]; if (response.response) { if (response.response.status === 200) { const queryTrans: protos.protos.ChaincodeQueryResponse = protos.protos.ChaincodeQueryResponse.decode(response.response.payload); for (const queryResults of queryTrans.chaincodes) { const contract: InstalledSmartContract = { packageId: queryResults.name, label: `${queryResults.name}@${queryResults.version}` }; results.push(contract); } logger.debug('%s - end', method); return results; } else if (response.response.message) { throw new Error(response.response.message); } } // no idea what we have, lets fail it and send it back throw new Error(response.toString()); } throw new Error('Payload results are missing from the query'); } catch (error) { logger.error('Problem with the request :: %s', error); logger.error(' problem at ::' + error.stack); throw new Error(`Could not get all the installed smart contract packages, received: ${error.message}`); } } /** * Get the buffer containing a smart contract package that has been installed on the peer * @param packageId string, the packageId of the installed smart contract package to be retrieved * @param requestTimeout number, [optional] the timeout used when performing the install operation * @return Promise<Buffer>, the buffer containing the smart contract package */ public async getInstalledSmartContractPackage(packageId: string, requestTimeout?: number): Promise<Buffer> { const method: string = 'getInstalledSmartContractPackage'; logger.debug(method); if (!packageId) { throw new Error('parameter packageId missing'); } let result: Buffer; try { logger.debug('%s - build the get package chaincode request', method); const protoArgs: protos.lifecycle.IGetInstalledChaincodePackageArgs = {}; protoArgs.package_id = packageId; const arg: Uint8Array = protos.lifecycle.GetInstalledChaincodePackageArgs.encode(protoArgs).finish(); const buildRequest: { fcn: string; args: Buffer[] } = { fcn: 'GetInstalledChaincodePackage', args: [Buffer.from(arg)] }; const responses: ProposalResponse = await this.sendRequest(buildRequest, '_lifecycle', requestTimeout); const payloads: Buffer[] = await LifecycleCommon.processResponse(responses); // only sent to one peer so can only be one payload const results: protos.lifecycle.GetInstalledChaincodePackageResult = protos.lifecycle.GetInstalledChaincodePackageResult.decode(payloads[0]); const packageBytes: Uint8Array = results.chaincode_install_package; // the package bytes result = Buffer.from(packageBytes); logger.debug('%s - end', method); return result; } catch (error) { logger.error('Problem with the request :: %s', error); logger.error(' problem at ::' + error.stack); throw new Error(`Could not get the installed smart contract package, received: ${error.message}`); } } public async getChannelCapabilities(channelName: string, requestTimeout?: number): Promise<string[]> { const buildRequest: { fcn: string; args: Buffer[] } = { fcn: 'GetConfigBlock', args: [channelName as any] }; const response: ProposalResponse = await this.sendRequest(buildRequest, 'cscc', requestTimeout); const payload: Buffer[] = await LifecycleCommon.processResponse(response); const block: protos.common.Block = protos.common.Block.decode(payload[0]); const blockData: Uint8Array = block.data.data[0]; const envelope: protos.common.Envelope = protos.common.Envelope.decode(blockData); const dataPayload: protos.common.Payload = protos.common.Payload.decode(envelope.payload); const configEnvelope: protos.common.ConfigEnvelope = protos.common.ConfigEnvelope.decode(dataPayload.data); const _capabilities: protos.common.Capabilities = protos.common.Capabilities.decode(configEnvelope.config.channel_group.groups.Application.values.Capabilities.value); const capabilities: any = _capabilities.capabilities; const keys: string[] = Object.keys(capabilities); return keys; } /** * Get a list of all the channel names that the peer has joined * @param requestTimeout number, [optional] the timeout used when performing the install operation * @return Promise<string[]>, An array of the names of the channels */ public async getAllChannelNames(requestTimeout?: number): Promise<string[]> { const method: string = 'getAllChannelNames'; logger.debug(method); const results: string[] = []; try { logger.debug('%s - build the get all installed smart contracts request', method); const buildRequest: { fcn: string; args: Buffer[] } = { fcn: 'GetChannels', args: [] }; const responses: ProposalResponse = await this.sendRequest(buildRequest, 'cscc', requestTimeout); const payloads: Buffer[] = await LifecycleCommon.processResponse(responses); // only sent to one peer so only one payload const queryTrans: protos.protos.ChannelQueryResponse = protos.protos.ChannelQueryResponse.decode(payloads[0]); logger.debug('queryChannels - ProcessedTransaction.channelInfo.length :: %s', queryTrans.channels.length); for (const channelInfo of queryTrans.channels) { logger.debug('>>> channel id %s ', channelInfo.channel_id); results.push(channelInfo.channel_id); } logger.debug('%s - end', method); return results; } catch (error) { logger.error('Problem with the request :: %s', error); logger.error(' problem at ::' + error.stack); throw new Error(`Could not get all channel names, received: ${error.message}`); } } private initialize(): Client { const fabricClient: Client = new Client('lifecycle'); fabricClient.setTlsClientCertAndKey(this.clientCertKey!, this.clientKey!); const options: ConnectOptions = { url: this.url }; if (this.pem) { options.pem = this.pem; } if (this.sslTargetNameOverride) { options['ssl-target-name-override'] = this.sslTargetNameOverride; } if (this.requestTimeout) { options.requestTimeout = this.requestTimeout; } if (this.apiOptions) { Object.assign(options, this.apiOptions); } const endpoint: Endpoint = fabricClient.newEndpoint(options); // this will add the peer to the list of endorsers const endorser: Endorser = fabricClient.getEndorser(this.name, this.mspid); endorser.setEndpoint(endpoint); return fabricClient; } private async sendRequest(buildRequest: { fcn: string, args: Buffer[] }, smartContractName: string, requestTimeout?: number): Promise<ProposalResponse> { if (!this.wallet || !this.identity) { throw new Error('Wallet or identity property not set, call setCredentials first'); } const fabricClient: Client = this.initialize(); const endorser: Endorser = fabricClient.getEndorser(this.name, this.mspid); try { // @ts-ignore await endorser.connect(); const channel: Channel = fabricClient.newChannel('noname'); // this will tell the peer it is a system wide request // not for a specific channel // @ts-ignore channel['name'] = ''; const endorsement: Endorsement = channel.newEndorsement(smartContractName); const identity: Identity | undefined = await this.wallet.get(this.identity); if (!identity) { throw new Error(`Identity ${this.identity} does not exist in the wallet`); } const provider: IdentityProvider = this.wallet.getProviderRegistry().getProvider(identity.type); const user: User = await provider.getUserContext(identity, this.identity); const identityContext: IdentityContext = fabricClient.newIdentityContext(user); endorsement.build(identityContext, buildRequest as any); logger.debug('%s - sign the get all install smart contract request'); endorsement.sign(identityContext); const endorseRequest: any = { targets: [endorser] }; if (requestTimeout || this.requestTimeout) { // use the one set in the params if set otherwise use the one set when the peer was added endorseRequest.requestTimeout = requestTimeout ? requestTimeout : this.requestTimeout; } logger.debug('%s - send the query request'); const response: ProposalResponse = await endorsement.send(endorseRequest); return response; } finally { endorser.disconnect(); } } }
the_stack
import * as d3 from "d3"; import { assert } from "chai"; import * as Typesettable from "typesettable"; import * as Plottable from "../../src"; import { getTranslateValues } from "../../src/utils/domUtils"; import * as TestMethods from "../testMethods"; describe("Labels", () => { const LABEL_CLASS = "label"; let CLOSETO_REQUIRMENT: number; before(() => { CLOSETO_REQUIRMENT = window.Pixel_CloseTo_Requirement; // HACKHACK #2422: use an open source web font by default for Plottable window.Pixel_CloseTo_Requirement = 3; }); after(() => { window.Pixel_CloseTo_Requirement = CLOSETO_REQUIRMENT; }); describe("Label", () => { describe("Basic Usage", () => { let div: d3.Selection<HTMLDivElement, any, any, any>; beforeEach(() => { div = TestMethods.generateDiv(); }); it("can update text after label is created", () => { const label = new Plottable.Components.Label("a"); label.renderTo(div); assert.strictEqual(label.content().select("text").text(), "a", "the text starts at the specified string"); assert.operator(label.height(), ">", 0, "height is positive for non-empty string"); label.text("hello world"); label.renderTo(div); assert.strictEqual(label.content().select("text").text(), "hello world", "the label text updated properly"); assert.operator(label.height(), ">", 0, "height is positive for non-empty string"); div.remove(); }); it("can change label angle after label is created", () => { const label = new Plottable.Components.Label("CHANGING ORIENTATION"); label.renderTo(div); const content = label.content(); let text = content.select("text"); let bbox = Plottable.Utils.DOM.elementBBox(text); assert.closeTo(bbox.height, label.height(), 1, "label is in horizontal position"); label.angle(90); text = content.select("text"); bbox = Plottable.Utils.DOM.elementBBox(text); TestMethods.assertBBoxInclusion(label.element(), text); assert.closeTo(bbox.height, label.width(), window.Pixel_CloseTo_Requirement, "label is in vertical position"); div.remove(); }); it("positions centered text in the middle of horizontal space", () => { const DIV_WIDTH = Plottable.Utils.DOM.elementWidth(div); const label = new Plottable.Components.Label("X").renderTo(div); const textTranslate = getTranslateValues(label.content().select("g")); const eleLeft = parseFloat(label.element().style("left")); const textWidth = Plottable.Utils.DOM.elementBBox(label.content().select("text")).width; const midPoint = eleLeft + textTranslate[0] + textWidth / 2; assert.closeTo(midPoint, DIV_WIDTH / 2, window.Pixel_CloseTo_Requirement, "label is centered"); div.remove(); }); it("truncates text that is too long to be render", () => { const DIV_WIDTH = Plottable.Utils.DOM.elementWidth(div); const label = new Plottable.Components.Label("THIS LABEL IS SO LONG WHOEVER WROTE IT WAS PROBABLY DERANGED"); label.renderTo(div); const content = label.content(); const text = content.select("text"); const bbox = Plottable.Utils.DOM.elementBBox(text); assert.strictEqual(bbox.height, label.height(), "text height === label.minimumHeight()"); assert.operator(bbox.width, "<=", DIV_WIDTH, "the text is not wider than the SVG width"); div.remove(); }); it("truncates text to empty string if space given is too small", () => { div.style("width", "5px"); const label = new Plottable.Components.Label("Yeah, not gonna fit..."); label.renderTo(div); const text = label.content().select("text"); assert.strictEqual(text.text(), "", "text was truncated to empty string"); div.remove(); }); it("sets width to 0 if a label text is changed to empty string", () => { const label = new Plottable.Components.Label("foo"); label.renderTo(div); label.text(""); assert.strictEqual(label.width(), 0, "width updated to 0"); div.remove(); }); it("renders left-rotated text properly", () => { const str = "LEFT-ROTATED LABEL"; const label = new Plottable.Components.Label(str, -90); label.renderTo(div); const content = label.content(); const text = content.select("text"); const textBBox = Plottable.Utils.DOM.elementBBox(text); TestMethods.assertBBoxInclusion(label.element(), text); assert.closeTo(textBBox.height, label.width(), window.Pixel_CloseTo_Requirement, "text height"); // OS/Browser specific kerning messes with typesetter's per-character measurement const widthFudge = str.length; assert.closeTo(textBBox.width, label.height(), window.Pixel_CloseTo_Requirement + widthFudge, "text width"); div.remove(); }); it("renders right-rotated text properly", () => { const str = "RIGHT-ROTATED LABEL"; const label = new Plottable.Components.Label(str, 90); label.renderTo(div); const content = label.content(); const text = content.select("text"); const textBBox = Plottable.Utils.DOM.elementBBox(text); TestMethods.assertBBoxInclusion(label.element(), text); assert.closeTo(textBBox.height, label.width(), window.Pixel_CloseTo_Requirement, "text height"); // OS/Browser specific kerning messes with typesetter's per-character measurement const widthFudge = str.length; assert.closeTo(textBBox.width, label.height(), window.Pixel_CloseTo_Requirement + widthFudge, "text width"); div.remove(); }); }); describe("Input validation", () => { it("only accepts strings as input for text", () => { const label = new Plottable.Components.Label(); // HACKHACK #2661: Cannot assert errors being thrown with description (<any> assert).throws(() => label.text(<any> 23), Error, "Label.text() only takes strings as input", "error on inputing number"); (<any> assert).throws(() => label.text(<any> new Date()), Error, "Label.text() only takes strings as input", "error on inputing Date"); assert.doesNotThrow(() => label.text("string"), Error, "text() accepts strings"); assert.strictEqual(label.text(null), "string", "text(null) returns text string"); }); it("converts angle to stay within -180 and 180", () => { const label360 = new Plottable.Components.Label("noScope", 360); assert.strictEqual(label360.angle(), 0, "angles are converted to range [-180, 180] (360 -> 0)"); const label270 = new Plottable.Components.Label("turnRight", 270); assert.strictEqual(label270.angle(), -90, "angles are converted to range [-180, 180] (270 -> -90)"); const labelNeg270 = new Plottable.Components.Label("turnRight", -270); assert.strictEqual(labelNeg270.angle(), 90, "angles are converted to range [-180, 180] (-270 -> 90)"); }); it("throws error on invalid angles", () => { const badAngle = 10; (<any> assert).throws(() => new Plottable.Components.Label("foo").angle(badAngle), Error, `${badAngle} is not a valid angle for Label`, "only accept -90/0/90 for angle"); (<any> assert).throws(() => new Plottable.Components.Label("foo", badAngle), Error, `${badAngle} is not a valid angle for Label`, "only accept -90/0/90 for angle"); }); it("errors on negative padding", () => { const testLabel = new Plottable.Components.Label("testing label"); (<any> assert).throws(() => testLabel.padding(-10), Error, "Cannot be less than 0", "error on negative input"); }); }); describe("Padding", () => { const PADDING = 30; let div: d3.Selection<HTMLDivElement, any, any, any>; let label: Plottable.Components.Label; beforeEach(() => { div = TestMethods.generateDiv(); label = new Plottable.Components.Label("testing label").padding(PADDING); }); it("adds padding for label accordingly under left alignment", () => { label.xAlignment("left").renderTo(div); const testTextRect = (<Element> label.content().select("text").node()).getBoundingClientRect(); const elementRect = label.element().node().getBoundingClientRect(); assert.closeTo(testTextRect.left, elementRect.left + PADDING, window.Pixel_CloseTo_Requirement, "left difference by padding amount"); div.remove(); }); it("adds padding for label accordingly under right alignment", () => { label.xAlignment("right").renderTo(div); const testTextRect = (<Element> label.content().select("text").node()).getBoundingClientRect(); const elementRect = label.element().node().getBoundingClientRect(); assert.closeTo(testTextRect.right, elementRect.right - PADDING, window.Pixel_CloseTo_Requirement, "right difference by padding amount"); div.remove(); }); it("adds padding for label accordingly under top alignment", () => { label.yAlignment("top").renderTo(div); const testTextRect = (<Element> label.content().select("text").node()).getBoundingClientRect(); const elementRect = label.element().node().getBoundingClientRect(); assert.closeTo(testTextRect.top, elementRect.top + PADDING, window.Pixel_CloseTo_Requirement, "top difference by padding amount"); div.remove(); }); it("adds padding for label accordingly under bottom alignment", () => { label.yAlignment("bottom").renderTo(div); const testTextRect = (<Element> label.content().select("text").node()).getBoundingClientRect(); const elementRect = label.element().node().getBoundingClientRect(); assert.closeTo(testTextRect.bottom, elementRect.bottom - PADDING, window.Pixel_CloseTo_Requirement, "bottom difference by padding amount"); div.remove(); }); it("puts space around the label", () => { label.renderTo(div); const context = new Typesettable.SvgContext(label.content().node() as SVGElement); const measurer = new Typesettable.CacheMeasurer(context); const measure = measurer.measure("testing label"); assert.operator(label.width(), ">", measure.width, "padding increases size of the component"); assert.operator(label.width(), "<=", measure.width + 2 * PADDING, "width at most incorporates full padding amount"); assert.operator(label.height(), ">", measure.height, "padding increases size of the component"); assert.operator(label.height(), ">=", measure.height + 2 * PADDING, "height at most incorporates full padding amount"); div.remove(); }); }); }); describe("TitleLabel", () => { it("has appropriate css class", () => { const label = new Plottable.Components.TitleLabel("A CHART TITLE"); const div = TestMethods.generateDiv(); label.renderTo(div); assert.isTrue(label.hasClass(LABEL_CLASS), "element has label css class"); assert.isTrue(label.hasClass(Plottable.Components.TitleLabel.TITLE_LABEL_CLASS), "element has title-label css class"); div.remove(); }); }); describe("AxisLabel", () => { it("has appropriate css class", () => { const labelText = "Axis Label"; const label = new Plottable.Components.AxisLabel(labelText); const div = TestMethods.generateDiv(); label.renderTo(div); assert.isTrue(label.hasClass(LABEL_CLASS), "element has label css class"); assert.isTrue(label.hasClass(Plottable.Components.AxisLabel.AXIS_LABEL_CLASS), "title element has axis-label css class"); assert.strictEqual(label.content().text(), labelText, "label doesn't contain the correct text"); div.remove(); }); }); });
the_stack
import { AutoPollingService } from './auto-polling.service'; import { TestBed, fakeAsync, tick } from '@angular/core/testing'; import { SearchService } from 'app/service/search.service'; import { Subject, of, throwError } from 'rxjs'; import { QueryBuilder } from '../query-builder'; import { SearchResponse } from 'app/model/search-response'; import { SearchRequest } from 'app/model/search-request'; import { Spy } from 'jasmine-core'; import { DialogService } from 'app/service/dialog.service'; import { RestError } from 'app/model/rest-error'; import { DialogType } from 'app/model/dialog-type'; import { RefreshInterval } from 'app/alerts/configure-rows/configure-rows-enums'; const DEFAULT_POLLING_INTERVAL = RefreshInterval.TEN_MIN; class QueryBuilderFake { private _filter = ''; query: '*' addOrUpdateFilter() {}; setFilter(filter: string): void { this._filter = filter; }; get searchRequest(): SearchRequest { return { query: this._filter, fields: [], size: 2, indices: [], from: 0, sort: [], facetFields: [], }; }; } describe('AutoPollingService', () => { let autoPollingService: AutoPollingService; let searchServiceFake: SearchService; function getIntervalInMS(): number { return autoPollingService.getInterval() * 1000; } beforeEach(() => { localStorage.getItem = () => null; localStorage.setItem = () => {}; TestBed.configureTestingModule({ providers: [ AutoPollingService, { provide: DialogService, useClass: () => {} }, { provide: SearchService, useClass: () => { return { search: () => of(new SearchResponse()), } } }, { provide: QueryBuilder, useClass: QueryBuilderFake }, ] }); autoPollingService = TestBed.get(AutoPollingService); searchServiceFake = TestBed.get(SearchService); }); afterEach(() => { autoPollingService.onDestroy(); }); describe('polling basics', () => { it('should mark polling as active after start', () => { autoPollingService.start(); expect(autoPollingService.getIsPollingActive()).toBe(true); }); it('should mark polling as inactive after stop', () => { autoPollingService.start(); expect(autoPollingService.getIsPollingActive()).toBe(true); autoPollingService.stop(); expect(autoPollingService.getIsPollingActive()).toBe(false); }); it('should send an initial request on start', () => { spyOn(searchServiceFake, 'search').and.callThrough(); autoPollingService.start(); expect(searchServiceFake.search).toHaveBeenCalled(); }); it('should broadcast response to initial request via data subject', () => { autoPollingService.data.subscribe((result) => { expect(result).toEqual(new SearchResponse()); }); autoPollingService.start(); }); it('should start polling when start called', fakeAsync(() => { spyOn(searchServiceFake, 'search').and.callThrough(); autoPollingService.start(); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); autoPollingService.stop(); })); it('should broadcast polling response via data subject', fakeAsync(() => { const searchObservableFake = new Subject<SearchResponse>(); const pollResponseFake = new SearchResponse(); autoPollingService.start(); // The reason am mocking the searchService.search here is to not interfere // with the initial request triggered right after the start searchServiceFake.search = () => searchObservableFake; autoPollingService.data.subscribe((result) => { expect(result).toBe(pollResponseFake); autoPollingService.stop(); }); tick(autoPollingService.getInterval() * 1000); searchObservableFake.next(pollResponseFake); })); it('should polling and broadcasting based on the interval', fakeAsync(() => { const searchObservableFake = new Subject<SearchResponse>(); const broadcastObserverSpy = jasmine.createSpy('broadcastObserverSpy'); const testInterval = 2; autoPollingService.setInterval(testInterval); autoPollingService.start(); // The reason am mocking the searchService.search here is to not interfere // with the initial request triggered right after the start searchServiceFake.search = () => searchObservableFake; spyOn(searchServiceFake, 'search').and.callThrough(); autoPollingService.data.subscribe(broadcastObserverSpy); tick(testInterval * 1000); expect(searchServiceFake.search).toHaveBeenCalledTimes(1); searchObservableFake.next({ total: 2 } as SearchResponse); expect(broadcastObserverSpy).toHaveBeenCalledTimes(1); expect(broadcastObserverSpy.calls.argsFor(0)[0]).toEqual({ total: 2 }); tick(testInterval * 1000); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); searchObservableFake.next({ total: 3 } as SearchResponse); expect(broadcastObserverSpy).toHaveBeenCalledTimes(2); expect(broadcastObserverSpy.calls.argsFor(1)[0]).toEqual({ total: 3 }); autoPollingService.stop(); })); it('interval change should impact the polling even when it is active', fakeAsync(() => { autoPollingService.start(); // The reason am mocking the searchService.search here is to not interfere // with the initial request triggered right after the start spyOn(searchServiceFake, 'search').and.callThrough(); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(1); autoPollingService.setInterval(9); tick(4000); expect(searchServiceFake.search).toHaveBeenCalledTimes(1); tick(5000); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); autoPollingService.setInterval(2); tick(1000); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); tick(1000); expect(searchServiceFake.search).toHaveBeenCalledTimes(3); autoPollingService.stop(); })); it('should stop polling when stop triggered', fakeAsync(() => { const searchObservableFake = new Subject<SearchResponse>(); const broadcastObserverSpy = jasmine.createSpy('broadcastObserverSpy'); autoPollingService.start(); // The reason am mocking the searchService.search here is to not interfere // with the initial request triggered right after the start searchServiceFake.search = () => searchObservableFake; spyOn(searchServiceFake, 'search').and.callThrough(); autoPollingService.data.subscribe(broadcastObserverSpy); tick(getIntervalInMS()); searchObservableFake.next({ total: 3 } as SearchResponse); expect(searchServiceFake.search).toHaveBeenCalledTimes(1); autoPollingService.stop(); tick(getIntervalInMS() * 4); expect(searchServiceFake.search).toHaveBeenCalledTimes(1); })); it('should use the latest query from query builder', fakeAsync(() => { const queryBuilderFake = TestBed.get(QueryBuilder); spyOn(searchServiceFake, 'search').and.callThrough(); queryBuilderFake.setFilter('testFieldAA:testValueAA'); autoPollingService.start(); expect((searchServiceFake.search as Spy).calls.argsFor(0)[0].query).toBe('testFieldAA:testValueAA'); queryBuilderFake.setFilter('testFieldBB:testValueBB'); tick(getIntervalInMS()); expect((searchServiceFake.search as Spy).calls.argsFor(1)[0].query).toBe('testFieldBB:testValueBB'); queryBuilderFake.setFilter('*'); tick(getIntervalInMS()); expect((searchServiceFake.search as Spy).calls.argsFor(2)[0].query).toBe('*'); autoPollingService.stop(); })); it('should show notification on http error', fakeAsync(() => { const fakeDialogService = TestBed.get(DialogService); fakeDialogService.launchDialog = () => {}; spyOn(fakeDialogService, 'launchDialog'); autoPollingService.start(); spyOn(searchServiceFake, 'search').and.returnValue(throwError(new RestError())); tick(getIntervalInMS()); expect(fakeDialogService.launchDialog).toHaveBeenCalledWith( 'Server were unable to apply query string. Evaluate query string and restart polling.', DialogType.Error ); autoPollingService.stop(); })); }); describe('polling suppression - to prevent collision with other features', () => { it('should suspend polling even if it is started', fakeAsync(() => { spyOn(searchServiceFake, 'search').and.callThrough(); autoPollingService.start(); expect(searchServiceFake.search).toHaveBeenCalledTimes(1); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(3); autoPollingService.setSuppression(true); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(3); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(3); autoPollingService.stop(); })); it('should continue polling when freed from suppression if it is started ', fakeAsync(() => { spyOn(searchServiceFake, 'search').and.callThrough(); autoPollingService.start(); expect(searchServiceFake.search).toHaveBeenCalledTimes(1); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(3); autoPollingService.setSuppression(true); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(3); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(3); autoPollingService.setSuppression(false); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(4); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(5); autoPollingService.stop(); })); it('should have no impact when polling stopped', fakeAsync(() => { spyOn(searchServiceFake, 'search').and.callThrough(); autoPollingService.start(); expect(searchServiceFake.search).toHaveBeenCalledTimes(1); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); autoPollingService.stop(); autoPollingService.setSuppression(true); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); autoPollingService.setSuppression(false); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); })); }); describe('request congestion handling - when refresh interval faster than response time', () => { it('should skip new poll request when there is congestion', fakeAsync(() => { const searchObservableFake = new Subject<SearchResponse>(); searchServiceFake.search = () => searchObservableFake; spyOn(searchServiceFake, 'search').and.callThrough(); autoPollingService.start(); searchObservableFake.next({ total: 2 } as SearchResponse); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); expect(autoPollingService.getIsCongestion()).toBe(false); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); expect(autoPollingService.getIsCongestion()).toBe(true); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); expect(autoPollingService.getIsCongestion()).toBe(true); autoPollingService.stop(); })); it('should continue polling when congestion resolves', fakeAsync(() => { const searchObservableFake = new Subject<SearchResponse>(); searchServiceFake.search = () => searchObservableFake; spyOn(searchServiceFake, 'search').and.callThrough(); autoPollingService.start(); searchObservableFake.next({ total: 2 } as SearchResponse); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); expect(autoPollingService.getIsCongestion()).toBe(false); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); expect(autoPollingService.getIsCongestion()).toBe(true); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); expect(autoPollingService.getIsCongestion()).toBe(true); searchObservableFake.next({ total: 2 } as SearchResponse); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(3); expect(autoPollingService.getIsCongestion()).toBe(false); autoPollingService.stop(); })); }); describe('cancellation by manual request', () => { it('should be able to drop current response and continue polling', fakeAsync(() => { const broadcastObserverSpy = jasmine.createSpy('broadcastObserverSpy'); const searchObservableFake = new Subject<SearchResponse>(); autoPollingService.start(); searchServiceFake.search = () => searchObservableFake; spyOn(searchServiceFake, 'search').and.callThrough(); autoPollingService.data.subscribe(broadcastObserverSpy); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(1); searchObservableFake.next({ total: 2 } as SearchResponse); expect(broadcastObserverSpy).toHaveBeenCalledTimes(1); tick(getIntervalInMS() / 2); autoPollingService.dropNextAndContinue(); tick(getIntervalInMS() / 2); expect(searchServiceFake.search).toHaveBeenCalledTimes(1); searchObservableFake.next({ total: 3 } as SearchResponse); expect(broadcastObserverSpy).toHaveBeenCalledTimes(1); tick(getIntervalInMS()); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); searchObservableFake.next({ total: 4 } as SearchResponse); expect(broadcastObserverSpy).toHaveBeenCalledTimes(2); autoPollingService.stop(); })); }); describe('polling state persisting and restoring', () => { it('should persist polling state on start', () => { spyOn(localStorage, 'setItem'); autoPollingService.start(); expect(localStorage.setItem).toHaveBeenCalledWith('autoPolling', `{"isActive":true,"refreshInterval":${DEFAULT_POLLING_INTERVAL}}`); }); it('should persist polling state on stop', () => { spyOn(localStorage, 'setItem'); autoPollingService.stop(); expect(localStorage.setItem).toHaveBeenCalledWith('autoPolling', `{"isActive":false,"refreshInterval":${DEFAULT_POLLING_INTERVAL}}`); }); it('should persist polling state on interval change', () => { spyOn(localStorage, 'setItem'); autoPollingService.setInterval(4); expect(localStorage.setItem).toHaveBeenCalledWith('autoPolling', '{"isActive":false,"refreshInterval":4}'); }); it('should restore polling state on construction with a delay', fakeAsync(() => { const queryBuilderFake = TestBed.get(QueryBuilder); const dialogServiceFake = TestBed.get(DialogService); spyOn(localStorage, 'getItem').and.returnValue('{"isActive":true,"refreshInterval":443}'); const localAutoPollingSvc = new AutoPollingService(searchServiceFake, queryBuilderFake, dialogServiceFake); tick(localAutoPollingSvc.AUTO_START_DELAY); expect(localStorage.getItem).toHaveBeenCalledWith('autoPolling'); expect(localAutoPollingSvc.getIsPollingActive()).toBe(true); expect(localAutoPollingSvc.getInterval()).toBe(443); localAutoPollingSvc.stop(); })); it('should start polling on construction when persisted isActive==true', fakeAsync(() => { const queryBuilderFake = TestBed.get(QueryBuilder); const dialogServiceFake = TestBed.get(DialogService); spyOn(searchServiceFake, 'search').and.callThrough(); spyOn(localStorage, 'getItem').and.returnValue('{"isActive":true,"refreshInterval":10}'); const localAutoPollingSvc = new AutoPollingService(searchServiceFake, queryBuilderFake, dialogServiceFake); tick(localAutoPollingSvc.AUTO_START_DELAY); expect(searchServiceFake.search).toHaveBeenCalledTimes(1); tick(localAutoPollingSvc.getInterval() * 1000); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); tick(localAutoPollingSvc.getInterval() * 1000); expect(searchServiceFake.search).toHaveBeenCalledTimes(3); localAutoPollingSvc.stop(); })); it('should start polling on construction with the persisted interval', fakeAsync(() => { const queryBuilderFake = TestBed.get(QueryBuilder); const dialogServiceFake = TestBed.get(DialogService); spyOn(searchServiceFake, 'search').and.callThrough(); spyOn(localStorage, 'getItem').and.returnValue('{"isActive":true,"refreshInterval":4}'); const localAutoPollingSvc = new AutoPollingService(searchServiceFake, queryBuilderFake, dialogServiceFake); tick(localAutoPollingSvc.AUTO_START_DELAY); expect(searchServiceFake.search).toHaveBeenCalledTimes(1); tick(4000); expect(searchServiceFake.search).toHaveBeenCalledTimes(2); tick(4000); expect(searchServiceFake.search).toHaveBeenCalledTimes(3); localAutoPollingSvc.stop(); })); }); });
the_stack
import type {MeshAttribute, MeshAttributes} from '@loaders.gl/schema'; import {getMeshBoundingBox} from '@loaders.gl/schema'; import {decompressLZF} from './decompress-lzf'; import {getPCDSchema} from './get-pcd-schema'; import type {PCDHeader} from './pcd-types'; type NormalizedAttributes = { POSITION: { value: Float32Array; size: number; }; NORMAL?: { value: Float32Array; size: number; }; COLOR_0?: { value: Uint8Array; size: number; }; }; type HeaderAttributes = { [attributeName: string]: number[]; }; const LITTLE_ENDIAN: boolean = true; /** * * @param data * @returns */ export default function parsePCD(data: ArrayBufferLike) { // parse header (always ascii format) const textData = new TextDecoder().decode(data); const pcdHeader = parsePCDHeader(textData); let attributes: any = {}; // parse data switch (pcdHeader.data) { case 'ascii': attributes = parsePCDASCII(pcdHeader, textData); break; case 'binary': attributes = parsePCDBinary(pcdHeader, data); break; case 'binary_compressed': attributes = parsePCDBinaryCompressed(pcdHeader, data); break; default: throw new Error(`PCD: ${pcdHeader.data} files are not supported`); } attributes = getMeshAttributes(attributes); const header = getMeshHeader(pcdHeader, attributes); const metadata = new Map([ ['mode', '0'], ['boundingBox', JSON.stringify(header.boundingBox)] ]); const schema = getPCDSchema(pcdHeader, metadata); return { loaderData: { header: pcdHeader }, header, schema, mode: 0, // POINTS indices: null, attributes }; } // Create a header that contains common data for PointCloud category loaders function getMeshHeader(pcdHeader: PCDHeader, attributes: NormalizedAttributes): Partial<PCDHeader> { if (typeof pcdHeader.width === 'number' && typeof pcdHeader.height === 'number') { const pointCount = pcdHeader.width * pcdHeader.height; // Supports "organized" point sets return { vertexCount: pointCount, boundingBox: getMeshBoundingBox(attributes) }; } return pcdHeader; } /** * @param attributes * @returns Normalized attributes */ function getMeshAttributes(attributes: HeaderAttributes): {[attributeName: string]: MeshAttribute} { const normalizedAttributes: MeshAttributes = { POSITION: { // Binary PCD is only 32 bit value: new Float32Array(attributes.position), size: 3 } }; if (attributes.normal && attributes.normal.length > 0) { normalizedAttributes.NORMAL = { value: new Float32Array(attributes.normal), size: 3 }; } if (attributes.color && attributes.color.length > 0) { // TODO - RGBA normalizedAttributes.COLOR_0 = { value: new Uint8Array(attributes.color), size: 3 }; } return normalizedAttributes; } /** * Incoming data parsing * @param data * @returns Header */ /* eslint-disable complexity, max-statements */ function parsePCDHeader(data: string): PCDHeader { const result1 = data.search(/[\r\n]DATA\s(\S*)\s/i); const result2 = /[\r\n]DATA\s(\S*)\s/i.exec(data.substr(result1 - 1)); const pcdHeader: any = {}; pcdHeader.data = result2 && result2[1]; if (result2 !== null) { pcdHeader.headerLen = (result2 && result2[0].length) + result1; } pcdHeader.str = data.substr(0, pcdHeader.headerLen); // remove comments pcdHeader.str = pcdHeader.str.replace(/\#.*/gi, ''); // parse pcdHeader.version = /VERSION (.*)/i.exec(pcdHeader.str); pcdHeader.fields = /FIELDS (.*)/i.exec(pcdHeader.str); pcdHeader.size = /SIZE (.*)/i.exec(pcdHeader.str); pcdHeader.type = /TYPE (.*)/i.exec(pcdHeader.str); pcdHeader.count = /COUNT (.*)/i.exec(pcdHeader.str); pcdHeader.width = /WIDTH (.*)/i.exec(pcdHeader.str); pcdHeader.height = /HEIGHT (.*)/i.exec(pcdHeader.str); pcdHeader.viewpoint = /VIEWPOINT (.*)/i.exec(pcdHeader.str); pcdHeader.points = /POINTS (.*)/i.exec(pcdHeader.str); // evaluate if (pcdHeader.version !== null) { pcdHeader.version = parseFloat(pcdHeader.version[1]); } if (pcdHeader.fields !== null) { pcdHeader.fields = pcdHeader.fields[1].split(' '); } if (pcdHeader.type !== null) { pcdHeader.type = pcdHeader.type[1].split(' '); } if (pcdHeader.width !== null) { pcdHeader.width = parseInt(pcdHeader.width[1], 10); } if (pcdHeader.height !== null) { pcdHeader.height = parseInt(pcdHeader.height[1], 10); } if (pcdHeader.viewpoint !== null) { pcdHeader.viewpoint = pcdHeader.viewpoint[1]; } if (pcdHeader.points !== null) { pcdHeader.points = parseInt(pcdHeader.points[1], 10); } if ( pcdHeader.points === null && typeof pcdHeader.width === 'number' && typeof pcdHeader.height === 'number' ) { pcdHeader.points = pcdHeader.width * pcdHeader.height; } if (pcdHeader.size !== null) { pcdHeader.size = pcdHeader.size[1].split(' ').map((x) => parseInt(x, 10)); } if (pcdHeader.count !== null) { pcdHeader.count = pcdHeader.count[1].split(' ').map((x) => parseInt(x, 10)); } else { pcdHeader.count = []; if (pcdHeader.fields !== null) { for (let i = 0; i < pcdHeader.fields.length; i++) { pcdHeader.count.push(1); } } } pcdHeader.offset = {}; let sizeSum = 0; if (pcdHeader.fields !== null && pcdHeader.size !== null) { for (let i = 0; i < pcdHeader.fields.length; i++) { if (pcdHeader.data === 'ascii') { pcdHeader.offset[pcdHeader.fields[i]] = i; } else { pcdHeader.offset[pcdHeader.fields[i]] = sizeSum; sizeSum += pcdHeader.size[i]; } } } // for binary only pcdHeader.rowSize = sizeSum; return pcdHeader; } /** * @param pcdHeader * @param textData * @returns [attributes] */ /* eslint-enable complexity, max-statements */ function parsePCDASCII(pcdHeader: PCDHeader, textData: string): HeaderAttributes { const position: number[] = []; const normal: number[] = []; const color: number[] = []; const offset = pcdHeader.offset; const pcdData = textData.substr(pcdHeader.headerLen); const lines = pcdData.split('\n'); for (let i = 0; i < lines.length; i++) { if (lines[i] !== '') { const line = lines[i].split(' '); if (offset.x !== undefined) { position.push(parseFloat(line[offset.x])); position.push(parseFloat(line[offset.y])); position.push(parseFloat(line[offset.z])); } if (offset.rgb !== undefined) { const floatValue = parseFloat(line[offset.rgb]); const binaryColor = new Float32Array([floatValue]); const dataview = new DataView(binaryColor.buffer, 0); color.push(dataview.getUint8(0)); color.push(dataview.getUint8(1)); color.push(dataview.getUint8(2)); // TODO - handle alpha channel / RGBA? } if (offset.normal_x !== undefined) { normal.push(parseFloat(line[offset.normal_x])); normal.push(parseFloat(line[offset.normal_y])); normal.push(parseFloat(line[offset.normal_z])); } } } return {position, normal, color}; } /** * @param pcdHeader * @param data * @returns [attributes] */ function parsePCDBinary(pcdHeader: PCDHeader, data: ArrayBufferLike): HeaderAttributes { const position: number[] = []; const normal: number[] = []; const color: number[] = []; const dataview = new DataView(data, pcdHeader.headerLen); const offset = pcdHeader.offset; for (let i = 0, row = 0; i < pcdHeader.points; i++, row += pcdHeader.rowSize) { if (offset.x !== undefined) { position.push(dataview.getFloat32(row + offset.x, LITTLE_ENDIAN)); position.push(dataview.getFloat32(row + offset.y, LITTLE_ENDIAN)); position.push(dataview.getFloat32(row + offset.z, LITTLE_ENDIAN)); } if (offset.rgb !== undefined) { color.push(dataview.getUint8(row + offset.rgb + 0)); color.push(dataview.getUint8(row + offset.rgb + 1)); color.push(dataview.getUint8(row + offset.rgb + 2)); } if (offset.normal_x !== undefined) { normal.push(dataview.getFloat32(row + offset.normal_x, LITTLE_ENDIAN)); normal.push(dataview.getFloat32(row + offset.normal_y, LITTLE_ENDIAN)); normal.push(dataview.getFloat32(row + offset.normal_z, LITTLE_ENDIAN)); } } return {position, normal, color}; } /** Parse compressed PCD data in in binary_compressed form ( https://pointclouds.org/documentation/tutorials/pcd_file_format.html) * from https://github.com/mrdoob/three.js/blob/master/examples/jsm/loaders/PCDLoader.js * @license MIT (http://opensource.org/licenses/MIT) * @param pcdHeader * @param data * @returns [attributes] */ function parsePCDBinaryCompressed(PCDheader: PCDHeader, data: ArrayBufferLike): HeaderAttributes { const position: number[] = []; const normal: number[] = []; const color: number[] = []; const sizes = new Uint32Array(data.slice(PCDheader.headerLen, PCDheader.headerLen + 8)); const compressedSize = sizes[0]; const decompressedSize = sizes[1]; const decompressed = decompressLZF( new Uint8Array(data, PCDheader.headerLen + 8, compressedSize), decompressedSize ); const dataview = new DataView(decompressed.buffer); const offset = PCDheader.offset; for (let i = 0; i < PCDheader.points; i++) { if (offset.x !== undefined) { position.push( dataview.getFloat32( (PCDheader.points as number) * offset.x + (PCDheader.size as number[])[0] * i, LITTLE_ENDIAN ) ); position.push( dataview.getFloat32( (PCDheader.points as number) * offset.y + (PCDheader.size as number[])[1] * i, LITTLE_ENDIAN ) ); position.push( dataview.getFloat32( (PCDheader.points as number) * offset.z + (PCDheader.size as number[])[2] * i, LITTLE_ENDIAN ) ); } if (offset.rgb !== undefined) { color.push( dataview.getUint8( (PCDheader.points as number) * offset.rgb + (PCDheader.size as number[])[3] * i + 0 ) / 255.0 ); color.push( dataview.getUint8( (PCDheader.points as number) * offset.rgb + (PCDheader.size as number[])[3] * i + 1 ) / 255.0 ); color.push( dataview.getUint8( (PCDheader.points as number) * offset.rgb + (PCDheader.size as number[])[3] * i + 2 ) / 255.0 ); } if (offset.normal_x !== undefined) { normal.push( dataview.getFloat32( (PCDheader.points as number) * offset.normal_x + (PCDheader.size as number[])[4] * i, LITTLE_ENDIAN ) ); normal.push( dataview.getFloat32( (PCDheader.points as number) * offset.normal_y + (PCDheader.size as number[])[5] * i, LITTLE_ENDIAN ) ); normal.push( dataview.getFloat32( (PCDheader.points as number) * offset.normal_z + (PCDheader.size as number[])[6] * i, LITTLE_ENDIAN ) ); } } return { position, normal, color }; }
the_stack
import { Aurelia, customElement, ICustomElementViewModel, ICustomElementController } from '@aurelia/runtime-html'; import { assert, TestContext } from '@aurelia/testing'; function createFixture() { const ctx = TestContext.create(); const au = new Aurelia(ctx.container); const host = ctx.createElement('div'); const p = ctx.platform; return { au, host, p }; } describe('show.integration.spec.ts', function () { describe('show/hide alias works properly', function () { it('show + hide', async function () { const { au, host, p } = createFixture(); @customElement({ name: 'app', template: '<div show.bind="show"></div><div hide.bind="hide"></div>' }) class App implements ICustomElementViewModel { public $controller!: ICustomElementController<this>; public show: boolean = true; public appliedShow: boolean = true; public hide: boolean = false; public appliedHide: boolean = false; public showDiv!: HTMLDivElement; public hideDiv!: HTMLDivElement; public created() { this.showDiv = this.$controller.nodes.firstChild as HTMLDivElement; this.hideDiv = this.$controller.nodes.lastChild as HTMLDivElement; } public assert(label: string) { if (this.appliedShow) { assert.strictEqual(this.showDiv.style.getPropertyValue('display'), '', `display should be '' at ${label} (show is ${this.show}, appliedShow is ${this.appliedShow})`); assert.strictEqual(this.showDiv.style.getPropertyPriority('display'), '', `priority should be '' at ${label} (show is ${this.show}, appliedShow is ${this.appliedShow})`); } else { assert.strictEqual(this.showDiv.style.getPropertyValue('display'), 'none', `display should be 'none' at ${label} (show is ${this.show}, appliedShow is ${this.appliedShow})`); assert.strictEqual(this.showDiv.style.getPropertyPriority('display'), 'important', `priority should be 'important' at ${label} (show is ${this.show}, appliedShow is ${this.appliedShow})`); } if (this.appliedHide) { assert.strictEqual(this.hideDiv.style.getPropertyValue('display'), 'none', `display should be 'none' at ${label} (hide is ${this.hide}, appliedHide is ${this.appliedHide})`); assert.strictEqual(this.hideDiv.style.getPropertyPriority('display'), 'important', `priority should be 'important' at ${label} (hide is ${this.hide}, appliedHide is ${this.appliedHide})`); } else { assert.strictEqual(this.hideDiv.style.getPropertyValue('display'), '', `display should be '' at ${label} (hide is ${this.hide}, appliedHide is ${this.appliedHide})`); assert.strictEqual(this.hideDiv.style.getPropertyPriority('display'), '', `priority should be '' at ${label} (hide is ${this.hide}, appliedHide is ${this.appliedHide})`); } } } const component = new App(); au.app({ host, component }); await au.start(); component.show = false; component.hide = true; component.assert(`started after mutating`); p.domWriteQueue.flush(); component.appliedShow = false; component.appliedHide = true; component.assert(`started after flushing dom writes`); await au.stop(); }); it('hide + show', async function () { const { au, host, p } = createFixture(); @customElement({ name: 'app', template: '<div hide.bind="hide"></div><div show.bind="show"></div>' }) class App implements ICustomElementViewModel { public $controller!: ICustomElementController<this>; public show: boolean = true; public appliedShow: boolean = true; public hide: boolean = false; public appliedHide: boolean = false; public showDiv!: HTMLDivElement; public hideDiv!: HTMLDivElement; public created() { this.hideDiv = this.$controller.nodes.firstChild as HTMLDivElement; this.showDiv = this.$controller.nodes.lastChild as HTMLDivElement; } public assert(label: string) { if (this.appliedShow) { assert.strictEqual(this.showDiv.style.getPropertyValue('display'), '', `display should be '' at ${label} (show is ${this.show}, appliedShow is ${this.appliedShow})`); assert.strictEqual(this.showDiv.style.getPropertyPriority('display'), '', `priority should be '' at ${label} (show is ${this.show}, appliedShow is ${this.appliedShow})`); } else { assert.strictEqual(this.showDiv.style.getPropertyValue('display'), 'none', `display should be 'none' at ${label} (show is ${this.show}, appliedShow is ${this.appliedShow})`); assert.strictEqual(this.showDiv.style.getPropertyPriority('display'), 'important', `priority should be 'important' at ${label} (show is ${this.show}, appliedShow is ${this.appliedShow})`); } if (this.appliedHide) { assert.strictEqual(this.hideDiv.style.getPropertyValue('display'), 'none', `display should be 'none' at ${label} (hide is ${this.hide}, appliedHide is ${this.appliedHide})`); assert.strictEqual(this.hideDiv.style.getPropertyPriority('display'), 'important', `priority should be 'important' at ${label} (hide is ${this.hide}, appliedHide is ${this.appliedHide})`); } else { assert.strictEqual(this.hideDiv.style.getPropertyValue('display'), '', `display should be '' at ${label} (hide is ${this.hide}, appliedHide is ${this.appliedHide})`); assert.strictEqual(this.hideDiv.style.getPropertyPriority('display'), '', `priority should be '' at ${label} (hide is ${this.hide}, appliedHide is ${this.appliedHide})`); } } } const component = new App(); au.app({ host, component }); await au.start(); component.show = false; component.hide = true; component.assert(`started after mutating`); p.domWriteQueue.flush(); component.appliedShow = false; component.appliedHide = true; component.assert(`started after flushing dom writes`); await au.stop(); }); }); for (const style of [ { tag: 'style="display:block"', display: 'block', }, { tag: '', display: '', } ]) { // Invert value during 'attaching' hook for (const attaching of [true ,false]) { // Invert value during 'attached' hook for (const attached of [true ,false]) { // Invert value during 'detaching' hook for (const detaching of [true ,false]) { // Invert value during 'unbinding' hook for (const unbinding of [true, false]) { describe('show', function () { // Initial value for (const show of [true ,false]) { it(`display:'${style.display}',show:${show},attaching:${attaching},attached:${attached},detaching:${detaching},unbinding:${unbinding}`, async function () { const { au, host, p } = createFixture(); let run = 1; @customElement({ name: 'app', template: `<div ${style.tag} show.bind="show"></div>` }) class App implements ICustomElementViewModel { public $controller!: ICustomElementController<this>; public show: boolean = show; public appliedShow: boolean = true; public div!: HTMLDivElement; public created() { this.div = this.$controller.nodes.firstChild as HTMLDivElement; } // No need to invert during 'binding' or 'bound' because child controller activation happens after 'attaching', // so these would never affect the test outcomes. public binding() { this.assert(`binding (run ${run})`); } public bound() { this.assert(`bound (run ${run})`); } public attaching() { this.assert(`attaching initial (run ${run})`); if (attaching) { this.show = !this.show; this.assert(`attaching after mutating (run ${run})`); } } public attached() { this.appliedShow = this.show; this.assert(`attached initial (run ${run})`); if (attached) { this.show = !this.show; this.assert(`attached after mutating (run ${run})`); } p.domWriteQueue.flush(); this.appliedShow = this.show; this.assert(`attached after flushing dom writes (run ${run})`); } public detaching() { this.assert(`detaching initial (run ${run})`); if (detaching) { this.show = !this.show; this.assert(`detaching after mutating (run ${run})`); } } public unbinding() { this.assert(`unbinding initial (run ${run})`); if (unbinding) { this.show = !this.show; this.assert(`unbinding after mutating (run ${run})`); } } public assert(label: string) { if (this.appliedShow) { assert.strictEqual(this.div.style.getPropertyValue('display'), style.display, `display should be '' at ${label} (show is ${this.show}, appliedShow is ${this.appliedShow})`); assert.strictEqual(this.div.style.getPropertyPriority('display'), '', `priority should be '' at ${label} (show is ${this.show}, appliedShow is ${this.appliedShow})`); } else { assert.strictEqual(this.div.style.getPropertyValue('display'), 'none', `display should be 'none' at ${label} (show is ${this.show}, appliedShow is ${this.appliedShow})`); assert.strictEqual(this.div.style.getPropertyPriority('display'), 'important', `priority should be 'important' at ${label} (show is ${this.show}, appliedShow is ${this.appliedShow})`); } } } const component = new App(); au.app({ host, component }); await au.start(); component.show = !component.show; component.assert(`started after mutating (run ${run})`); p.domWriteQueue.flush(); component.appliedShow = component.show; component.assert(`started after flushing dom writes (run ${run})`); await au.stop(); ++run; await au.start(); component.show = !component.show; component.assert(`started after mutating (run ${run})`); p.domWriteQueue.flush(); component.appliedShow = component.show; component.assert(`started after flushing dom writes (run ${run})`); await au.stop(); }); } }); describe('hide', function () { for (const hide of [true ,false]) { it(`display:'${style.display}',hide:${hide},attaching:${attaching},attached:${attached},detaching:${detaching},unbinding:${unbinding}`, async function () { const { au, host, p } = createFixture(); let run = 1; @customElement({ name: 'app', template: `<div ${style.tag} hide.bind="hide"></div>` }) class App implements ICustomElementViewModel { public $controller!: ICustomElementController<this>; public hide: boolean = hide; public appliedHide: boolean = false; public div!: HTMLDivElement; public created() { this.div = this.$controller.nodes.firstChild as HTMLDivElement; } // No need to invert during 'binding' or 'bound' because child controller activation happens after 'attaching', // so these would never affect the test outcomes. public binding() { this.assert(`binding (run ${run})`); } public bound() { this.assert(`bound (run ${run})`); } public attaching() { this.assert(`attaching initial (run ${run})`); if (attaching) { this.hide = !this.hide; this.assert(`attaching after mutating (run ${run})`); } } public attached() { this.appliedHide = this.hide; this.assert(`attached initial (run ${run})`); if (attached) { this.hide = !this.hide; this.assert(`attached after mutating (run ${run})`); } p.domWriteQueue.flush(); this.appliedHide = this.hide; this.assert(`attached after flushing dom writes (run ${run})`); } public detaching() { this.assert(`detaching initial (run ${run})`); if (detaching) { this.hide = !this.hide; this.assert(`detaching after mutating (run ${run})`); } } public unbinding() { this.assert(`unbinding initial (run ${run})`); if (unbinding) { this.hide = !this.hide; this.assert(`unbinding after mutating (run ${run})`); } } public assert(label: string) { if (this.appliedHide) { assert.strictEqual(this.div.style.getPropertyValue('display'), 'none', `display should be 'none' at ${label} (hide is ${this.hide}, appliedHide is ${this.appliedHide})`); assert.strictEqual(this.div.style.getPropertyPriority('display'), 'important', `priority should be 'important' at ${label} (hide is ${this.hide}, appliedHide is ${this.appliedHide})`); } else { assert.strictEqual(this.div.style.getPropertyValue('display'), style.display, `display should be '' at ${label} (hide is ${this.hide}, appliedHide is ${this.appliedHide})`); assert.strictEqual(this.div.style.getPropertyPriority('display'), '', `priority should be '' at ${label} (hide is ${this.hide}, appliedHide is ${this.appliedHide})`); } } } const component = new App(); au.app({ host, component }); await au.start(); component.hide = !component.hide; component.assert(`started after mutating (run ${run})`); p.domWriteQueue.flush(); component.appliedHide = component.hide; component.assert(`started after flushing dom writes (run ${run})`); await au.stop(); ++run; await au.start(); component.hide = !component.hide; component.assert(`started after mutating (run ${run})`); p.domWriteQueue.flush(); component.appliedHide = component.hide; component.assert(`started after flushing dom writes (run ${run})`); await au.stop(); }); } }); } } } } } // it.only('test', async function () { // const ctx = TestContext.create(); // const { container } = ctx; // const child = container.createChild(); // }); });
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * Class for CheckServiceProviderAvailabilityInput */ export interface CheckServiceProviderAvailabilityInput { /** * Gets or sets the PeeringServiceLocation */ peeringServiceLocation?: string; /** * Gets or sets the PeeringServiceProvider */ peeringServiceProvider?: string; } /** * The SKU that defines the tier and kind of the peering. */ export interface PeeringSku { /** * The name of the peering SKU. Possible values include: 'Basic_Exchange_Free', * 'Basic_Direct_Free', 'Premium_Direct_Free', 'Premium_Exchange_Metered', * 'Premium_Direct_Metered', 'Premium_Direct_Unlimited' */ name?: Name; /** * The tier of the peering SKU. Possible values include: 'Basic', 'Premium' */ tier?: Tier; /** * The family of the peering SKU. Possible values include: 'Direct', 'Exchange' */ family?: Family; /** * The size of the peering SKU. Possible values include: 'Free', 'Metered', 'Unlimited' */ size?: Size; } /** * The properties that define a BGP session. */ export interface BgpSession { /** * The IPv4 prefix that contains both ends' IPv4 addresses. */ sessionPrefixV4?: string; /** * The IPv6 prefix that contains both ends' IPv6 addresses. */ sessionPrefixV6?: string; /** * The IPv4 session address on Microsoft's end. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly microsoftSessionIPv4Address?: string; /** * The IPv6 session address on Microsoft's end. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly microsoftSessionIPv6Address?: string; /** * The IPv4 session address on peer's end. */ peerSessionIPv4Address?: string; /** * The IPv6 session address on peer's end. */ peerSessionIPv6Address?: string; /** * The state of the IPv4 session. Possible values include: 'None', 'Idle', 'Connect', 'Active', * 'OpenSent', 'OpenConfirm', 'OpenReceived', 'Established', 'PendingAdd', 'PendingUpdate', * 'PendingRemove' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly sessionStateV4?: SessionStateV4; /** * The state of the IPv6 session. Possible values include: 'None', 'Idle', 'Connect', 'Active', * 'OpenSent', 'OpenConfirm', 'OpenReceived', 'Established', 'PendingAdd', 'PendingUpdate', * 'PendingRemove' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly sessionStateV6?: SessionStateV6; /** * The maximum number of prefixes advertised over the IPv4 session. */ maxPrefixesAdvertisedV4?: number; /** * The maximum number of prefixes advertised over the IPv6 session. */ maxPrefixesAdvertisedV6?: number; /** * The MD5 authentication key of the session. */ md5AuthenticationKey?: string; } /** * The properties that define a direct connection. */ export interface DirectConnection { /** * The bandwidth of the connection. */ bandwidthInMbps?: number; /** * The bandwidth that is actually provisioned. */ provisionedBandwidthInMbps?: number; /** * The field indicating if Microsoft provides session ip addresses. Possible values include: * 'Microsoft', 'Peer' */ sessionAddressProvider?: SessionAddressProvider; /** * The flag that indicates whether or not the connection is used for peering service. */ useForPeeringService?: boolean; /** * The PeeringDB.com ID of the facility at which the connection has to be set up. */ peeringDBFacilityId?: number; /** * The state of the connection. Possible values include: 'None', 'PendingApproval', 'Approved', * 'ProvisioningStarted', 'ProvisioningFailed', 'ProvisioningCompleted', 'Validating', 'Active' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly connectionState?: ConnectionState; /** * The BGP session associated with the connection. */ bgpSession?: BgpSession; /** * The unique identifier (GUID) for the connection. */ connectionIdentifier?: string; } /** * The sub resource. */ export interface SubResource { /** * The identifier of the referenced resource. */ id?: string; } /** * The properties that define a direct peering. */ export interface PeeringPropertiesDirect { /** * The set of connections that constitute a direct peering. */ connections?: DirectConnection[]; /** * The flag that indicates whether or not the peering is used for peering service. */ useForPeeringService?: boolean; /** * The reference of the peer ASN. */ peerAsn?: SubResource; /** * The type of direct peering. Possible values include: 'Edge', 'Transit', 'Cdn', 'Internal' */ directPeeringType?: DirectPeeringType; } /** * The properties that define an exchange connection. */ export interface ExchangeConnection { /** * The PeeringDB.com ID of the facility at which the connection has to be set up. */ peeringDBFacilityId?: number; /** * The state of the connection. Possible values include: 'None', 'PendingApproval', 'Approved', * 'ProvisioningStarted', 'ProvisioningFailed', 'ProvisioningCompleted', 'Validating', 'Active' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly connectionState?: ConnectionState; /** * The BGP session associated with the connection. */ bgpSession?: BgpSession; /** * The unique identifier (GUID) for the connection. */ connectionIdentifier?: string; } /** * The properties that define an exchange peering. */ export interface PeeringPropertiesExchange { /** * The set of connections that constitute an exchange peering. */ connections?: ExchangeConnection[]; /** * The reference of the peer ASN. */ peerAsn?: SubResource; } /** * The ARM resource class. */ export interface Resource extends BaseResource { /** * The name of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The ID of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The type of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * Peering is a logical representation of a set of connections to the Microsoft Cloud Edge at a * location. */ export interface Peering extends Resource { /** * The SKU that defines the tier and kind of the peering. */ sku: PeeringSku; /** * The kind of the peering. Possible values include: 'Direct', 'Exchange' */ kind: Kind; /** * The properties that define a direct peering. */ direct?: PeeringPropertiesDirect; /** * The properties that define an exchange peering. */ exchange?: PeeringPropertiesExchange; /** * The location of the peering. */ peeringLocation?: string; /** * The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', * 'Deleting', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: ProvisioningState; /** * The location of the resource. */ location: string; /** * The resource tags. */ tags?: { [propertyName: string]: string }; } /** * The information related to the operation. */ export interface OperationDisplayInfo { /** * The name of the resource provider. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provider?: string; /** * The type of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly resource?: string; /** * The name of the operation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly operation?: string; /** * The description of the operation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; } /** * The peering API operation. */ export interface Operation { /** * The name of the operation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The information related to the operation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly display?: OperationDisplayInfo; /** * The flag that indicates whether the operation applies to data plane. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isDataAction?: boolean; } /** * The contact information of the peer. */ export interface ContactInfo { /** * The list of email addresses. */ emails?: string[]; /** * The list of contact numbers. */ phone?: string[]; } /** * The essential information related to the peer's ASN. */ export interface PeerAsn extends Resource { /** * The Autonomous System Number (ASN) of the peer. */ peerAsn?: number; /** * The contact information of the peer. */ peerContactInfo?: ContactInfo; /** * The name of the peer. */ peerName?: string; /** * The validation state of the ASN associated with the peer. Possible values include: 'None', * 'Pending', 'Approved', 'Failed' */ validationState?: ValidationState; } /** * The properties that define a direct peering facility. */ export interface DirectPeeringFacility { /** * The address of the direct peering facility. */ address?: string; /** * The type of the direct peering. Possible values include: 'Edge', 'Transit', 'Cdn', 'Internal' */ directPeeringType?: DirectPeeringType; /** * The PeeringDB.com ID of the facility. */ peeringDBFacilityId?: number; /** * The PeeringDB.com URL of the facility. */ peeringDBFacilityLink?: string; } /** * The properties that define a peering bandwidth offer. */ export interface PeeringBandwidthOffer { /** * The name of the bandwidth offer. */ offerName?: string; /** * The value of the bandwidth offer in Mbps. */ valueInMbps?: number; } /** * The properties that define a direct peering location. */ export interface PeeringLocationPropertiesDirect { /** * The list of direct peering facilities at the peering location. */ peeringFacilities?: DirectPeeringFacility[]; /** * The list of bandwidth offers available at the peering location. */ bandwidthOffers?: PeeringBandwidthOffer[]; } /** * The properties that define an exchange peering facility. */ export interface ExchangePeeringFacility { /** * The name of the exchange peering facility. */ exchangeName?: string; /** * The bandwidth of the connection between Microsoft and the exchange peering facility. */ bandwidthInMbps?: number; /** * The IPv4 address of Microsoft at the exchange peering facility. */ microsoftIPv4Address?: string; /** * The IPv6 address of Microsoft at the exchange peering facility. */ microsoftIPv6Address?: string; /** * The IPv4 prefixes associated with the exchange peering facility. */ facilityIPv4Prefix?: string; /** * The IPv6 prefixes associated with the exchange peering facility. */ facilityIPv6Prefix?: string; /** * The PeeringDB.com ID of the facility. */ peeringDBFacilityId?: number; /** * The PeeringDB.com URL of the facility. */ peeringDBFacilityLink?: string; } /** * The properties that define an exchange peering location. */ export interface PeeringLocationPropertiesExchange { /** * The list of exchange peering facilities at the peering location. */ peeringFacilities?: ExchangePeeringFacility[]; } /** * Peering location is where connectivity could be established to the Microsoft Cloud Edge. */ export interface PeeringLocation extends Resource { /** * The kind of peering that the peering location supports. Possible values include: 'Direct', * 'Exchange' */ kind?: Kind; /** * The properties that define a direct peering location. */ direct?: PeeringLocationPropertiesDirect; /** * The properties that define an exchange peering location. */ exchange?: PeeringLocationPropertiesExchange; /** * The name of the peering location. */ peeringLocation?: string; /** * The country in which the peering location exists. */ country?: string; /** * The Azure region associated with the peering location. */ azureRegion?: string; } /** * The resource tags. */ export interface ResourceTags { /** * Gets or sets the tags, a dictionary of descriptors arm object */ tags?: { [propertyName: string]: string }; } /** * PeeringService location */ export interface PeeringServiceLocation extends Resource { /** * Country of the customer */ country?: string; /** * State of the customer */ state?: string; /** * Azure region for the location */ azureRegion?: string; } /** * The peering service prefix class. */ export interface PeeringServicePrefix extends Resource { /** * Valid route prefix */ prefix?: string; /** * The prefix validation state. Possible values include: 'None', 'Invalid', 'Verified', 'Failed', * 'Pending', 'Unknown' */ prefixValidationState?: PrefixValidationState; /** * The prefix learned type. Possible values include: 'None', 'ViaPartner', 'ViaSession' */ learnedType?: LearnedType; /** * The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', * 'Deleting', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: ProvisioningState; } /** * PeeringService provider */ export interface PeeringServiceProvider extends Resource { /** * The name of the service provider. */ serviceProviderName?: string; } /** * Peering Service */ export interface PeeringService extends Resource { /** * The PeeringServiceLocation of the Customer. */ peeringServiceLocation?: string; /** * The MAPS Provider Name. */ peeringServiceProvider?: string; /** * The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', * 'Deleting', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: ProvisioningState; /** * The location of the resource. */ location: string; /** * The resource tags. */ tags?: { [propertyName: string]: string }; } /** * The error response that indicates why an operation has failed. */ export interface ErrorResponse { /** * The error code. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly code?: string; /** * The error message. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; } /** * Optional Parameters. */ export interface PeeringManagementClientCheckServiceProviderAvailabilityOptionalParams extends msRest.RequestOptionsBase { /** * Gets or sets the PeeringServiceLocation */ peeringServiceLocation?: string; /** * Gets or sets the PeeringServiceProvider */ peeringServiceProvider?: string; } /** * Optional Parameters. */ export interface PeeringLocationsListOptionalParams extends msRest.RequestOptionsBase { /** * The type of direct peering. Possible values include: 'Edge', 'Transit', 'Cdn', 'Internal' */ directPeeringType?: DirectPeeringType1; } /** * Optional Parameters. */ export interface PeeringsUpdateOptionalParams extends msRest.RequestOptionsBase { /** * Gets or sets the tags, a dictionary of descriptors arm object */ tags?: { [propertyName: string]: string }; } /** * Optional Parameters. */ export interface PeeringServicesUpdateOptionalParams extends msRest.RequestOptionsBase { /** * Gets or sets the tags, a dictionary of descriptors arm object */ tags?: { [propertyName: string]: string }; } /** * An interface representing PeeringManagementClientOptions. */ export interface PeeringManagementClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * The paginated list of peerings. * @extends Array<Peering> */ export interface PeeringListResult extends Array<Peering> { /** * The link to fetch the next page of peerings. */ nextLink?: string; } /** * @interface * The paginated list of peering API operations. * @extends Array<Operation> */ export interface OperationListResult extends Array<Operation> { /** * The link to fetch the next page of peering API operations. */ nextLink?: string; } /** * @interface * The paginated list of peer ASNs. * @extends Array<PeerAsn> */ export interface PeerAsnListResult extends Array<PeerAsn> { /** * The link to fetch the next page of peer ASNs. */ nextLink?: string; } /** * @interface * The paginated list of peering locations. * @extends Array<PeeringLocation> */ export interface PeeringLocationListResult extends Array<PeeringLocation> { /** * The link to fetch the next page of peering locations. */ nextLink?: string; } /** * @interface * The paginated list of peering service locations. * @extends Array<PeeringServiceLocation> */ export interface PeeringServiceLocationListResult extends Array<PeeringServiceLocation> { /** * The link to fetch the next page of peering service locations. */ nextLink?: string; } /** * @interface * The paginated list of [T]. * @extends Array<PeeringServicePrefix> */ export interface PeeringServicePrefixListResult extends Array<PeeringServicePrefix> { /** * The link to fetch the next page of [T]. */ nextLink?: string; } /** * @interface * The paginated list of peering service providers. * @extends Array<PeeringServiceProvider> */ export interface PeeringServiceProviderListResult extends Array<PeeringServiceProvider> { /** * The link to fetch the next page of peering service providers. */ nextLink?: string; } /** * @interface * The paginated list of peering services. * @extends Array<PeeringService> */ export interface PeeringServiceListResult extends Array<PeeringService> { /** * The link to fetch the next page of peering services. */ nextLink?: string; } /** * Defines values for Name. * Possible values include: 'Basic_Exchange_Free', 'Basic_Direct_Free', 'Premium_Direct_Free', * 'Premium_Exchange_Metered', 'Premium_Direct_Metered', 'Premium_Direct_Unlimited' * @readonly * @enum {string} */ export type Name = 'Basic_Exchange_Free' | 'Basic_Direct_Free' | 'Premium_Direct_Free' | 'Premium_Exchange_Metered' | 'Premium_Direct_Metered' | 'Premium_Direct_Unlimited'; /** * Defines values for Tier. * Possible values include: 'Basic', 'Premium' * @readonly * @enum {string} */ export type Tier = 'Basic' | 'Premium'; /** * Defines values for Family. * Possible values include: 'Direct', 'Exchange' * @readonly * @enum {string} */ export type Family = 'Direct' | 'Exchange'; /** * Defines values for Size. * Possible values include: 'Free', 'Metered', 'Unlimited' * @readonly * @enum {string} */ export type Size = 'Free' | 'Metered' | 'Unlimited'; /** * Defines values for Kind. * Possible values include: 'Direct', 'Exchange' * @readonly * @enum {string} */ export type Kind = 'Direct' | 'Exchange'; /** * Defines values for SessionAddressProvider. * Possible values include: 'Microsoft', 'Peer' * @readonly * @enum {string} */ export type SessionAddressProvider = 'Microsoft' | 'Peer'; /** * Defines values for ConnectionState. * Possible values include: 'None', 'PendingApproval', 'Approved', 'ProvisioningStarted', * 'ProvisioningFailed', 'ProvisioningCompleted', 'Validating', 'Active' * @readonly * @enum {string} */ export type ConnectionState = 'None' | 'PendingApproval' | 'Approved' | 'ProvisioningStarted' | 'ProvisioningFailed' | 'ProvisioningCompleted' | 'Validating' | 'Active'; /** * Defines values for SessionStateV4. * Possible values include: 'None', 'Idle', 'Connect', 'Active', 'OpenSent', 'OpenConfirm', * 'OpenReceived', 'Established', 'PendingAdd', 'PendingUpdate', 'PendingRemove' * @readonly * @enum {string} */ export type SessionStateV4 = 'None' | 'Idle' | 'Connect' | 'Active' | 'OpenSent' | 'OpenConfirm' | 'OpenReceived' | 'Established' | 'PendingAdd' | 'PendingUpdate' | 'PendingRemove'; /** * Defines values for SessionStateV6. * Possible values include: 'None', 'Idle', 'Connect', 'Active', 'OpenSent', 'OpenConfirm', * 'OpenReceived', 'Established', 'PendingAdd', 'PendingUpdate', 'PendingRemove' * @readonly * @enum {string} */ export type SessionStateV6 = 'None' | 'Idle' | 'Connect' | 'Active' | 'OpenSent' | 'OpenConfirm' | 'OpenReceived' | 'Established' | 'PendingAdd' | 'PendingUpdate' | 'PendingRemove'; /** * Defines values for DirectPeeringType. * Possible values include: 'Edge', 'Transit', 'Cdn', 'Internal' * @readonly * @enum {string} */ export type DirectPeeringType = 'Edge' | 'Transit' | 'Cdn' | 'Internal'; /** * Defines values for ProvisioningState. * Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' * @readonly * @enum {string} */ export type ProvisioningState = 'Succeeded' | 'Updating' | 'Deleting' | 'Failed'; /** * Defines values for ValidationState. * Possible values include: 'None', 'Pending', 'Approved', 'Failed' * @readonly * @enum {string} */ export type ValidationState = 'None' | 'Pending' | 'Approved' | 'Failed'; /** * Defines values for PrefixValidationState. * Possible values include: 'None', 'Invalid', 'Verified', 'Failed', 'Pending', 'Unknown' * @readonly * @enum {string} */ export type PrefixValidationState = 'None' | 'Invalid' | 'Verified' | 'Failed' | 'Pending' | 'Unknown'; /** * Defines values for LearnedType. * Possible values include: 'None', 'ViaPartner', 'ViaSession' * @readonly * @enum {string} */ export type LearnedType = 'None' | 'ViaPartner' | 'ViaSession'; /** * Defines values for DirectPeeringType1. * Possible values include: 'Edge', 'Transit', 'Cdn', 'Internal' * @readonly * @enum {string} */ export type DirectPeeringType1 = 'Edge' | 'Transit' | 'Cdn' | 'Internal'; /** * Defines values for CheckServiceProviderAvailabilityOKResponse. * Possible values include: 'Available', 'UnAvailable' * @readonly * @enum {string} */ export type CheckServiceProviderAvailabilityOKResponse = 'Available' | 'UnAvailable'; /** * Defines values for Kind1. * Possible values include: 'Direct', 'Exchange' * @readonly * @enum {string} */ export type Kind1 = 'Direct' | 'Exchange'; /** * Defines values for Kind2. * Possible values include: 'Direct', 'Exchange' * @readonly * @enum {string} */ export type Kind2 = 'Direct' | 'Exchange'; /** * Contains response data for the checkServiceProviderAvailability operation. */ export type CheckServiceProviderAvailabilityResponse = { /** * The parsed response body. */ body: CheckServiceProviderAvailabilityOKResponse; /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CheckServiceProviderAvailabilityOKResponse; }; }; /** * Contains response data for the list operation. */ export type LegacyPeeringsListResponse = PeeringListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringListResult; }; }; /** * Contains response data for the listNext operation. */ export type LegacyPeeringsListNextResponse = PeeringListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringListResult; }; }; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the get operation. */ export type PeerAsnsGetResponse = PeerAsn & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeerAsn; }; }; /** * Contains response data for the createOrUpdate operation. */ export type PeerAsnsCreateOrUpdateResponse = PeerAsn & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeerAsn; }; }; /** * Contains response data for the listBySubscription operation. */ export type PeerAsnsListBySubscriptionResponse = PeerAsnListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeerAsnListResult; }; }; /** * Contains response data for the listBySubscriptionNext operation. */ export type PeerAsnsListBySubscriptionNextResponse = PeerAsnListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeerAsnListResult; }; }; /** * Contains response data for the list operation. */ export type PeeringLocationsListResponse = PeeringLocationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringLocationListResult; }; }; /** * Contains response data for the listNext operation. */ export type PeeringLocationsListNextResponse = PeeringLocationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringLocationListResult; }; }; /** * Contains response data for the get operation. */ export type PeeringsGetResponse = Peering & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Peering; }; }; /** * Contains response data for the createOrUpdate operation. */ export type PeeringsCreateOrUpdateResponse = Peering & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Peering; }; }; /** * Contains response data for the update operation. */ export type PeeringsUpdateResponse = Peering & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Peering; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type PeeringsListByResourceGroupResponse = PeeringListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringListResult; }; }; /** * Contains response data for the listBySubscription operation. */ export type PeeringsListBySubscriptionResponse = PeeringListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringListResult; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type PeeringsListByResourceGroupNextResponse = PeeringListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringListResult; }; }; /** * Contains response data for the listBySubscriptionNext operation. */ export type PeeringsListBySubscriptionNextResponse = PeeringListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringListResult; }; }; /** * Contains response data for the list operation. */ export type PeeringServiceLocationsListResponse = PeeringServiceLocationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringServiceLocationListResult; }; }; /** * Contains response data for the listNext operation. */ export type PeeringServiceLocationsListNextResponse = PeeringServiceLocationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringServiceLocationListResult; }; }; /** * Contains response data for the get operation. */ export type PeeringServicePrefixesGetResponse = PeeringServicePrefix & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringServicePrefix; }; }; /** * Contains response data for the createOrUpdate operation. */ export type PeeringServicePrefixesCreateOrUpdateResponse = PeeringServicePrefix & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringServicePrefix; }; }; /** * Contains response data for the listByPeeringService operation. */ export type PrefixesListByPeeringServiceResponse = PeeringServicePrefixListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringServicePrefixListResult; }; }; /** * Contains response data for the listByPeeringServiceNext operation. */ export type PrefixesListByPeeringServiceNextResponse = PeeringServicePrefixListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringServicePrefixListResult; }; }; /** * Contains response data for the list operation. */ export type PeeringServiceProvidersListResponse = PeeringServiceProviderListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringServiceProviderListResult; }; }; /** * Contains response data for the listNext operation. */ export type PeeringServiceProvidersListNextResponse = PeeringServiceProviderListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringServiceProviderListResult; }; }; /** * Contains response data for the get operation. */ export type PeeringServicesGetResponse = PeeringService & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringService; }; }; /** * Contains response data for the createOrUpdate operation. */ export type PeeringServicesCreateOrUpdateResponse = PeeringService & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringService; }; }; /** * Contains response data for the update operation. */ export type PeeringServicesUpdateResponse = PeeringService & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringService; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type PeeringServicesListByResourceGroupResponse = PeeringServiceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringServiceListResult; }; }; /** * Contains response data for the listBySubscription operation. */ export type PeeringServicesListBySubscriptionResponse = PeeringServiceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringServiceListResult; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type PeeringServicesListByResourceGroupNextResponse = PeeringServiceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringServiceListResult; }; }; /** * Contains response data for the listBySubscriptionNext operation. */ export type PeeringServicesListBySubscriptionNextResponse = PeeringServiceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PeeringServiceListResult; }; };
the_stack
import * as $protobuf from "protobufjs"; /** Namespace px. */ export namespace px { /** Namespace vispb. */ namespace vispb { /** PXType enum. */ enum PXType { PX_UNKNOWN = 0, PX_BOOLEAN = 1, PX_INT64 = 2, PX_FLOAT64 = 3, PX_STRING = 4, PX_SERVICE = 1000, PX_POD = 1001, PX_CONTAINER = 1002, PX_NAMESPACE = 1003, PX_NODE = 1004, PX_LIST = 2000, PX_STRING_LIST = 2001 } /** Properties of a Vis. */ interface IVis { /** Vis variables */ variables?: (px.vispb.Vis.IVariable[]|null); /** Vis widgets */ widgets?: (px.vispb.IWidget[]|null); /** Vis globalFuncs */ globalFuncs?: (px.vispb.Vis.IGlobalFunc[]|null); } /** Represents a Vis. */ class Vis implements IVis { /** * Constructs a new Vis. * @param [properties] Properties to set */ constructor(properties?: px.vispb.IVis); /** Vis variables. */ public variables: px.vispb.Vis.IVariable[]; /** Vis widgets. */ public widgets: px.vispb.IWidget[]; /** Vis globalFuncs. */ public globalFuncs: px.vispb.Vis.IGlobalFunc[]; /** * Creates a new Vis instance using the specified properties. * @param [properties] Properties to set * @returns Vis instance */ public static create(properties?: px.vispb.IVis): px.vispb.Vis; /** * Encodes the specified Vis message. Does not implicitly {@link px.vispb.Vis.verify|verify} messages. * @param message Vis message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.IVis, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Vis message, length delimited. Does not implicitly {@link px.vispb.Vis.verify|verify} messages. * @param message Vis message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.IVis, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Vis message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Vis * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.Vis; /** * Decodes a Vis message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Vis * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.Vis; /** * Verifies a Vis message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Vis message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Vis */ public static fromObject(object: { [k: string]: any }): px.vispb.Vis; /** * Creates a plain object from a Vis message. Also converts values to other types if specified. * @param message Vis * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.Vis, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Vis to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Vis { /** Properties of a Variable. */ interface IVariable { /** Variable name */ name?: (string|null); /** Variable type */ type?: (px.vispb.PXType|null); /** Variable defaultValue */ defaultValue?: (google.protobuf.IStringValue|null); /** Variable description */ description?: (string|null); /** Variable validValues */ validValues?: (string[]|null); } /** Represents a Variable. */ class Variable implements IVariable { /** * Constructs a new Variable. * @param [properties] Properties to set */ constructor(properties?: px.vispb.Vis.IVariable); /** Variable name. */ public name: string; /** Variable type. */ public type: px.vispb.PXType; /** Variable defaultValue. */ public defaultValue?: (google.protobuf.IStringValue|null); /** Variable description. */ public description: string; /** Variable validValues. */ public validValues: string[]; /** * Creates a new Variable instance using the specified properties. * @param [properties] Properties to set * @returns Variable instance */ public static create(properties?: px.vispb.Vis.IVariable): px.vispb.Vis.Variable; /** * Encodes the specified Variable message. Does not implicitly {@link px.vispb.Vis.Variable.verify|verify} messages. * @param message Variable message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.Vis.IVariable, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Variable message, length delimited. Does not implicitly {@link px.vispb.Vis.Variable.verify|verify} messages. * @param message Variable message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.Vis.IVariable, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Variable message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Variable * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.Vis.Variable; /** * Decodes a Variable message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Variable * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.Vis.Variable; /** * Verifies a Variable message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Variable message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Variable */ public static fromObject(object: { [k: string]: any }): px.vispb.Vis.Variable; /** * Creates a plain object from a Variable message. Also converts values to other types if specified. * @param message Variable * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.Vis.Variable, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Variable to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GlobalFunc. */ interface IGlobalFunc { /** GlobalFunc outputName */ outputName?: (string|null); /** GlobalFunc func */ func?: (px.vispb.Widget.IFunc|null); } /** Represents a GlobalFunc. */ class GlobalFunc implements IGlobalFunc { /** * Constructs a new GlobalFunc. * @param [properties] Properties to set */ constructor(properties?: px.vispb.Vis.IGlobalFunc); /** GlobalFunc outputName. */ public outputName: string; /** GlobalFunc func. */ public func?: (px.vispb.Widget.IFunc|null); /** * Creates a new GlobalFunc instance using the specified properties. * @param [properties] Properties to set * @returns GlobalFunc instance */ public static create(properties?: px.vispb.Vis.IGlobalFunc): px.vispb.Vis.GlobalFunc; /** * Encodes the specified GlobalFunc message. Does not implicitly {@link px.vispb.Vis.GlobalFunc.verify|verify} messages. * @param message GlobalFunc message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.Vis.IGlobalFunc, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GlobalFunc message, length delimited. Does not implicitly {@link px.vispb.Vis.GlobalFunc.verify|verify} messages. * @param message GlobalFunc message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.Vis.IGlobalFunc, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GlobalFunc message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GlobalFunc * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.Vis.GlobalFunc; /** * Decodes a GlobalFunc message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GlobalFunc * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.Vis.GlobalFunc; /** * Verifies a GlobalFunc message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GlobalFunc message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GlobalFunc */ public static fromObject(object: { [k: string]: any }): px.vispb.Vis.GlobalFunc; /** * Creates a plain object from a GlobalFunc message. Also converts values to other types if specified. * @param message GlobalFunc * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.Vis.GlobalFunc, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GlobalFunc to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a Widget. */ interface IWidget { /** Widget name */ name?: (string|null); /** Widget position */ position?: (px.vispb.Widget.IPosition|null); /** Widget func */ func?: (px.vispb.Widget.IFunc|null); /** Widget globalFuncOutputName */ globalFuncOutputName?: (string|null); /** Widget displaySpec */ displaySpec?: (google.protobuf.IAny|null); } /** Represents a Widget. */ class Widget implements IWidget { /** * Constructs a new Widget. * @param [properties] Properties to set */ constructor(properties?: px.vispb.IWidget); /** Widget name. */ public name: string; /** Widget position. */ public position?: (px.vispb.Widget.IPosition|null); /** Widget func. */ public func?: (px.vispb.Widget.IFunc|null); /** Widget globalFuncOutputName. */ public globalFuncOutputName?: (string|null); /** Widget displaySpec. */ public displaySpec?: (google.protobuf.IAny|null); /** Widget funcOrRef. */ public funcOrRef?: ("func"|"globalFuncOutputName"); /** * Creates a new Widget instance using the specified properties. * @param [properties] Properties to set * @returns Widget instance */ public static create(properties?: px.vispb.IWidget): px.vispb.Widget; /** * Encodes the specified Widget message. Does not implicitly {@link px.vispb.Widget.verify|verify} messages. * @param message Widget message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.IWidget, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Widget message, length delimited. Does not implicitly {@link px.vispb.Widget.verify|verify} messages. * @param message Widget message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.IWidget, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Widget message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Widget * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.Widget; /** * Decodes a Widget message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Widget * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.Widget; /** * Verifies a Widget message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Widget message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Widget */ public static fromObject(object: { [k: string]: any }): px.vispb.Widget; /** * Creates a plain object from a Widget message. Also converts values to other types if specified. * @param message Widget * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.Widget, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Widget to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Widget { /** Properties of a Position. */ interface IPosition { /** Position x */ x?: (number|null); /** Position y */ y?: (number|null); /** Position w */ w?: (number|null); /** Position h */ h?: (number|null); } /** Represents a Position. */ class Position implements IPosition { /** * Constructs a new Position. * @param [properties] Properties to set */ constructor(properties?: px.vispb.Widget.IPosition); /** Position x. */ public x: number; /** Position y. */ public y: number; /** Position w. */ public w: number; /** Position h. */ public h: number; /** * Creates a new Position instance using the specified properties. * @param [properties] Properties to set * @returns Position instance */ public static create(properties?: px.vispb.Widget.IPosition): px.vispb.Widget.Position; /** * Encodes the specified Position message. Does not implicitly {@link px.vispb.Widget.Position.verify|verify} messages. * @param message Position message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.Widget.IPosition, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Position message, length delimited. Does not implicitly {@link px.vispb.Widget.Position.verify|verify} messages. * @param message Position message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.Widget.IPosition, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Position message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Position * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.Widget.Position; /** * Decodes a Position message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Position * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.Widget.Position; /** * Verifies a Position message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Position message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Position */ public static fromObject(object: { [k: string]: any }): px.vispb.Widget.Position; /** * Creates a plain object from a Position message. Also converts values to other types if specified. * @param message Position * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.Widget.Position, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Position to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Func. */ interface IFunc { /** Func name */ name?: (string|null); /** Func args */ args?: (px.vispb.Widget.Func.IFuncArg[]|null); } /** Represents a Func. */ class Func implements IFunc { /** * Constructs a new Func. * @param [properties] Properties to set */ constructor(properties?: px.vispb.Widget.IFunc); /** Func name. */ public name: string; /** Func args. */ public args: px.vispb.Widget.Func.IFuncArg[]; /** * Creates a new Func instance using the specified properties. * @param [properties] Properties to set * @returns Func instance */ public static create(properties?: px.vispb.Widget.IFunc): px.vispb.Widget.Func; /** * Encodes the specified Func message. Does not implicitly {@link px.vispb.Widget.Func.verify|verify} messages. * @param message Func message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.Widget.IFunc, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Func message, length delimited. Does not implicitly {@link px.vispb.Widget.Func.verify|verify} messages. * @param message Func message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.Widget.IFunc, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Func message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Func * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.Widget.Func; /** * Decodes a Func message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Func * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.Widget.Func; /** * Verifies a Func message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Func message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Func */ public static fromObject(object: { [k: string]: any }): px.vispb.Widget.Func; /** * Creates a plain object from a Func message. Also converts values to other types if specified. * @param message Func * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.Widget.Func, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Func to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Func { /** Properties of a FuncArg. */ interface IFuncArg { /** FuncArg name */ name?: (string|null); /** FuncArg value */ value?: (string|null); /** FuncArg variable */ variable?: (string|null); } /** Represents a FuncArg. */ class FuncArg implements IFuncArg { /** * Constructs a new FuncArg. * @param [properties] Properties to set */ constructor(properties?: px.vispb.Widget.Func.IFuncArg); /** FuncArg name. */ public name: string; /** FuncArg value. */ public value?: (string|null); /** FuncArg variable. */ public variable?: (string|null); /** FuncArg input. */ public input?: ("value"|"variable"); /** * Creates a new FuncArg instance using the specified properties. * @param [properties] Properties to set * @returns FuncArg instance */ public static create(properties?: px.vispb.Widget.Func.IFuncArg): px.vispb.Widget.Func.FuncArg; /** * Encodes the specified FuncArg message. Does not implicitly {@link px.vispb.Widget.Func.FuncArg.verify|verify} messages. * @param message FuncArg message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.Widget.Func.IFuncArg, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FuncArg message, length delimited. Does not implicitly {@link px.vispb.Widget.Func.FuncArg.verify|verify} messages. * @param message FuncArg message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.Widget.Func.IFuncArg, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FuncArg message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FuncArg * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.Widget.Func.FuncArg; /** * Decodes a FuncArg message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FuncArg * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.Widget.Func.FuncArg; /** * Verifies a FuncArg message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FuncArg message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FuncArg */ public static fromObject(object: { [k: string]: any }): px.vispb.Widget.Func.FuncArg; /** * Creates a plain object from a FuncArg message. Also converts values to other types if specified. * @param message FuncArg * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.Widget.Func.FuncArg, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FuncArg to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } /** Properties of an Axis. */ interface IAxis { /** Axis label */ label?: (string|null); } /** Represents an Axis. */ class Axis implements IAxis { /** * Constructs a new Axis. * @param [properties] Properties to set */ constructor(properties?: px.vispb.IAxis); /** Axis label. */ public label: string; /** * Creates a new Axis instance using the specified properties. * @param [properties] Properties to set * @returns Axis instance */ public static create(properties?: px.vispb.IAxis): px.vispb.Axis; /** * Encodes the specified Axis message. Does not implicitly {@link px.vispb.Axis.verify|verify} messages. * @param message Axis message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.IAxis, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Axis message, length delimited. Does not implicitly {@link px.vispb.Axis.verify|verify} messages. * @param message Axis message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.IAxis, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Axis message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Axis * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.Axis; /** * Decodes an Axis message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Axis * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.Axis; /** * Verifies an Axis message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Axis message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Axis */ public static fromObject(object: { [k: string]: any }): px.vispb.Axis; /** * Creates a plain object from an Axis message. Also converts values to other types if specified. * @param message Axis * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.Axis, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Axis to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a BarChart. */ interface IBarChart { /** BarChart bar */ bar?: (px.vispb.BarChart.IBar|null); /** BarChart title */ title?: (string|null); /** BarChart xAxis */ xAxis?: (px.vispb.IAxis|null); /** BarChart yAxis */ yAxis?: (px.vispb.IAxis|null); } /** Represents a BarChart. */ class BarChart implements IBarChart { /** * Constructs a new BarChart. * @param [properties] Properties to set */ constructor(properties?: px.vispb.IBarChart); /** BarChart bar. */ public bar?: (px.vispb.BarChart.IBar|null); /** BarChart title. */ public title: string; /** BarChart xAxis. */ public xAxis?: (px.vispb.IAxis|null); /** BarChart yAxis. */ public yAxis?: (px.vispb.IAxis|null); /** * Creates a new BarChart instance using the specified properties. * @param [properties] Properties to set * @returns BarChart instance */ public static create(properties?: px.vispb.IBarChart): px.vispb.BarChart; /** * Encodes the specified BarChart message. Does not implicitly {@link px.vispb.BarChart.verify|verify} messages. * @param message BarChart message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.IBarChart, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified BarChart message, length delimited. Does not implicitly {@link px.vispb.BarChart.verify|verify} messages. * @param message BarChart message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.IBarChart, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a BarChart message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BarChart * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.BarChart; /** * Decodes a BarChart message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns BarChart * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.BarChart; /** * Verifies a BarChart message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a BarChart message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns BarChart */ public static fromObject(object: { [k: string]: any }): px.vispb.BarChart; /** * Creates a plain object from a BarChart message. Also converts values to other types if specified. * @param message BarChart * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.BarChart, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this BarChart to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace BarChart { /** Properties of a Bar. */ interface IBar { /** Bar value */ value?: (string|null); /** Bar label */ label?: (string|null); /** Bar stackBy */ stackBy?: (string|null); /** Bar groupBy */ groupBy?: (string|null); /** Bar horizontal */ horizontal?: (boolean|null); } /** Represents a Bar. */ class Bar implements IBar { /** * Constructs a new Bar. * @param [properties] Properties to set */ constructor(properties?: px.vispb.BarChart.IBar); /** Bar value. */ public value: string; /** Bar label. */ public label: string; /** Bar stackBy. */ public stackBy: string; /** Bar groupBy. */ public groupBy: string; /** Bar horizontal. */ public horizontal: boolean; /** * Creates a new Bar instance using the specified properties. * @param [properties] Properties to set * @returns Bar instance */ public static create(properties?: px.vispb.BarChart.IBar): px.vispb.BarChart.Bar; /** * Encodes the specified Bar message. Does not implicitly {@link px.vispb.BarChart.Bar.verify|verify} messages. * @param message Bar message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.BarChart.IBar, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Bar message, length delimited. Does not implicitly {@link px.vispb.BarChart.Bar.verify|verify} messages. * @param message Bar message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.BarChart.IBar, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Bar message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Bar * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.BarChart.Bar; /** * Decodes a Bar message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Bar * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.BarChart.Bar; /** * Verifies a Bar message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Bar message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Bar */ public static fromObject(object: { [k: string]: any }): px.vispb.BarChart.Bar; /** * Creates a plain object from a Bar message. Also converts values to other types if specified. * @param message Bar * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.BarChart.Bar, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Bar to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a HistogramChart. */ interface IHistogramChart { /** HistogramChart histogram */ histogram?: (px.vispb.HistogramChart.IHistogram|null); /** HistogramChart title */ title?: (string|null); /** HistogramChart xAxis */ xAxis?: (px.vispb.IAxis|null); /** HistogramChart yAxis */ yAxis?: (px.vispb.IAxis|null); } /** Represents a HistogramChart. */ class HistogramChart implements IHistogramChart { /** * Constructs a new HistogramChart. * @param [properties] Properties to set */ constructor(properties?: px.vispb.IHistogramChart); /** HistogramChart histogram. */ public histogram?: (px.vispb.HistogramChart.IHistogram|null); /** HistogramChart title. */ public title: string; /** HistogramChart xAxis. */ public xAxis?: (px.vispb.IAxis|null); /** HistogramChart yAxis. */ public yAxis?: (px.vispb.IAxis|null); /** * Creates a new HistogramChart instance using the specified properties. * @param [properties] Properties to set * @returns HistogramChart instance */ public static create(properties?: px.vispb.IHistogramChart): px.vispb.HistogramChart; /** * Encodes the specified HistogramChart message. Does not implicitly {@link px.vispb.HistogramChart.verify|verify} messages. * @param message HistogramChart message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.IHistogramChart, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified HistogramChart message, length delimited. Does not implicitly {@link px.vispb.HistogramChart.verify|verify} messages. * @param message HistogramChart message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.IHistogramChart, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a HistogramChart message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns HistogramChart * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.HistogramChart; /** * Decodes a HistogramChart message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns HistogramChart * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.HistogramChart; /** * Verifies a HistogramChart message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a HistogramChart message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns HistogramChart */ public static fromObject(object: { [k: string]: any }): px.vispb.HistogramChart; /** * Creates a plain object from a HistogramChart message. Also converts values to other types if specified. * @param message HistogramChart * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.HistogramChart, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this HistogramChart to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace HistogramChart { /** Properties of a Histogram. */ interface IHistogram { /** Histogram value */ value?: (string|null); /** Histogram maxbins */ maxbins?: (number|Long|null); /** Histogram minstep */ minstep?: (number|null); /** Histogram horizontal */ horizontal?: (boolean|null); /** Histogram prebinCount */ prebinCount?: (string|null); } /** Represents a Histogram. */ class Histogram implements IHistogram { /** * Constructs a new Histogram. * @param [properties] Properties to set */ constructor(properties?: px.vispb.HistogramChart.IHistogram); /** Histogram value. */ public value: string; /** Histogram maxbins. */ public maxbins: (number|Long); /** Histogram minstep. */ public minstep: number; /** Histogram horizontal. */ public horizontal: boolean; /** Histogram prebinCount. */ public prebinCount: string; /** * Creates a new Histogram instance using the specified properties. * @param [properties] Properties to set * @returns Histogram instance */ public static create(properties?: px.vispb.HistogramChart.IHistogram): px.vispb.HistogramChart.Histogram; /** * Encodes the specified Histogram message. Does not implicitly {@link px.vispb.HistogramChart.Histogram.verify|verify} messages. * @param message Histogram message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.HistogramChart.IHistogram, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Histogram message, length delimited. Does not implicitly {@link px.vispb.HistogramChart.Histogram.verify|verify} messages. * @param message Histogram message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.HistogramChart.IHistogram, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Histogram message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Histogram * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.HistogramChart.Histogram; /** * Decodes a Histogram message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Histogram * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.HistogramChart.Histogram; /** * Verifies a Histogram message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Histogram message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Histogram */ public static fromObject(object: { [k: string]: any }): px.vispb.HistogramChart.Histogram; /** * Creates a plain object from a Histogram message. Also converts values to other types if specified. * @param message Histogram * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.HistogramChart.Histogram, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Histogram to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a TimeseriesChart. */ interface ITimeseriesChart { /** TimeseriesChart timeseries */ timeseries?: (px.vispb.TimeseriesChart.ITimeseries[]|null); /** TimeseriesChart title */ title?: (string|null); /** TimeseriesChart xAxis */ xAxis?: (px.vispb.IAxis|null); /** TimeseriesChart yAxis */ yAxis?: (px.vispb.IAxis|null); } /** Represents a TimeseriesChart. */ class TimeseriesChart implements ITimeseriesChart { /** * Constructs a new TimeseriesChart. * @param [properties] Properties to set */ constructor(properties?: px.vispb.ITimeseriesChart); /** TimeseriesChart timeseries. */ public timeseries: px.vispb.TimeseriesChart.ITimeseries[]; /** TimeseriesChart title. */ public title: string; /** TimeseriesChart xAxis. */ public xAxis?: (px.vispb.IAxis|null); /** TimeseriesChart yAxis. */ public yAxis?: (px.vispb.IAxis|null); /** * Creates a new TimeseriesChart instance using the specified properties. * @param [properties] Properties to set * @returns TimeseriesChart instance */ public static create(properties?: px.vispb.ITimeseriesChart): px.vispb.TimeseriesChart; /** * Encodes the specified TimeseriesChart message. Does not implicitly {@link px.vispb.TimeseriesChart.verify|verify} messages. * @param message TimeseriesChart message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.ITimeseriesChart, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified TimeseriesChart message, length delimited. Does not implicitly {@link px.vispb.TimeseriesChart.verify|verify} messages. * @param message TimeseriesChart message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.ITimeseriesChart, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a TimeseriesChart message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns TimeseriesChart * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.TimeseriesChart; /** * Decodes a TimeseriesChart message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns TimeseriesChart * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.TimeseriesChart; /** * Verifies a TimeseriesChart message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a TimeseriesChart message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns TimeseriesChart */ public static fromObject(object: { [k: string]: any }): px.vispb.TimeseriesChart; /** * Creates a plain object from a TimeseriesChart message. Also converts values to other types if specified. * @param message TimeseriesChart * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.TimeseriesChart, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this TimeseriesChart to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace TimeseriesChart { /** Properties of a Timeseries. */ interface ITimeseries { /** Timeseries value */ value?: (string|null); /** Timeseries series */ series?: (string|null); /** Timeseries stackBySeries */ stackBySeries?: (boolean|null); /** Timeseries mode */ mode?: (px.vispb.TimeseriesChart.Timeseries.Mode|null); } /** Represents a Timeseries. */ class Timeseries implements ITimeseries { /** * Constructs a new Timeseries. * @param [properties] Properties to set */ constructor(properties?: px.vispb.TimeseriesChart.ITimeseries); /** Timeseries value. */ public value: string; /** Timeseries series. */ public series: string; /** Timeseries stackBySeries. */ public stackBySeries: boolean; /** Timeseries mode. */ public mode: px.vispb.TimeseriesChart.Timeseries.Mode; /** * Creates a new Timeseries instance using the specified properties. * @param [properties] Properties to set * @returns Timeseries instance */ public static create(properties?: px.vispb.TimeseriesChart.ITimeseries): px.vispb.TimeseriesChart.Timeseries; /** * Encodes the specified Timeseries message. Does not implicitly {@link px.vispb.TimeseriesChart.Timeseries.verify|verify} messages. * @param message Timeseries message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.TimeseriesChart.ITimeseries, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Timeseries message, length delimited. Does not implicitly {@link px.vispb.TimeseriesChart.Timeseries.verify|verify} messages. * @param message Timeseries message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.TimeseriesChart.ITimeseries, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Timeseries message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Timeseries * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.TimeseriesChart.Timeseries; /** * Decodes a Timeseries message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Timeseries * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.TimeseriesChart.Timeseries; /** * Verifies a Timeseries message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Timeseries message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Timeseries */ public static fromObject(object: { [k: string]: any }): px.vispb.TimeseriesChart.Timeseries; /** * Creates a plain object from a Timeseries message. Also converts values to other types if specified. * @param message Timeseries * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.TimeseriesChart.Timeseries, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Timeseries to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Timeseries { /** Mode enum. */ enum Mode { MODE_UNKNOWN = 0, MODE_LINE = 2, MODE_POINT = 3, MODE_AREA = 4 } } } /** Properties of a VegaChart. */ interface IVegaChart { /** VegaChart spec */ spec?: (string|null); } /** Represents a VegaChart. */ class VegaChart implements IVegaChart { /** * Constructs a new VegaChart. * @param [properties] Properties to set */ constructor(properties?: px.vispb.IVegaChart); /** VegaChart spec. */ public spec: string; /** * Creates a new VegaChart instance using the specified properties. * @param [properties] Properties to set * @returns VegaChart instance */ public static create(properties?: px.vispb.IVegaChart): px.vispb.VegaChart; /** * Encodes the specified VegaChart message. Does not implicitly {@link px.vispb.VegaChart.verify|verify} messages. * @param message VegaChart message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.IVegaChart, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified VegaChart message, length delimited. Does not implicitly {@link px.vispb.VegaChart.verify|verify} messages. * @param message VegaChart message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.IVegaChart, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a VegaChart message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns VegaChart * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.VegaChart; /** * Decodes a VegaChart message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns VegaChart * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.VegaChart; /** * Verifies a VegaChart message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a VegaChart message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns VegaChart */ public static fromObject(object: { [k: string]: any }): px.vispb.VegaChart; /** * Creates a plain object from a VegaChart message. Also converts values to other types if specified. * @param message VegaChart * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.VegaChart, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this VegaChart to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Table. */ interface ITable { /** Table gutterColumn */ gutterColumn?: (string|null); } /** Represents a Table. */ class Table implements ITable { /** * Constructs a new Table. * @param [properties] Properties to set */ constructor(properties?: px.vispb.ITable); /** Table gutterColumn. */ public gutterColumn: string; /** * Creates a new Table instance using the specified properties. * @param [properties] Properties to set * @returns Table instance */ public static create(properties?: px.vispb.ITable): px.vispb.Table; /** * Encodes the specified Table message. Does not implicitly {@link px.vispb.Table.verify|verify} messages. * @param message Table message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.ITable, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Table message, length delimited. Does not implicitly {@link px.vispb.Table.verify|verify} messages. * @param message Table message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.ITable, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Table message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Table * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.Table; /** * Decodes a Table message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Table * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.Table; /** * Verifies a Table message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Table message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Table */ public static fromObject(object: { [k: string]: any }): px.vispb.Table; /** * Creates a plain object from a Table message. Also converts values to other types if specified. * @param message Table * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.Table, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Table to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Graph. */ interface IGraph { /** Graph dotColumn */ dotColumn?: (string|null); /** Graph adjacencyList */ adjacencyList?: (px.vispb.Graph.IAdjacencyList|null); /** Graph edgeWeightColumn */ edgeWeightColumn?: (string|null); /** Graph nodeWeightColumn */ nodeWeightColumn?: (string|null); /** Graph edgeColorColumn */ edgeColorColumn?: (string|null); /** Graph edgeThresholds */ edgeThresholds?: (px.vispb.Graph.IEdgeThresholds|null); /** Graph edgeHoverInfo */ edgeHoverInfo?: (string[]|null); /** Graph edgeLength */ edgeLength?: (number|Long|null); /** Graph enableDefaultHierarchy */ enableDefaultHierarchy?: (boolean|null); } /** Represents a Graph. */ class Graph implements IGraph { /** * Constructs a new Graph. * @param [properties] Properties to set */ constructor(properties?: px.vispb.IGraph); /** Graph dotColumn. */ public dotColumn?: (string|null); /** Graph adjacencyList. */ public adjacencyList?: (px.vispb.Graph.IAdjacencyList|null); /** Graph edgeWeightColumn. */ public edgeWeightColumn: string; /** Graph nodeWeightColumn. */ public nodeWeightColumn: string; /** Graph edgeColorColumn. */ public edgeColorColumn: string; /** Graph edgeThresholds. */ public edgeThresholds?: (px.vispb.Graph.IEdgeThresholds|null); /** Graph edgeHoverInfo. */ public edgeHoverInfo: string[]; /** Graph edgeLength. */ public edgeLength: (number|Long); /** Graph enableDefaultHierarchy. */ public enableDefaultHierarchy: boolean; /** Graph input. */ public input?: ("dotColumn"|"adjacencyList"); /** * Creates a new Graph instance using the specified properties. * @param [properties] Properties to set * @returns Graph instance */ public static create(properties?: px.vispb.IGraph): px.vispb.Graph; /** * Encodes the specified Graph message. Does not implicitly {@link px.vispb.Graph.verify|verify} messages. * @param message Graph message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.IGraph, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Graph message, length delimited. Does not implicitly {@link px.vispb.Graph.verify|verify} messages. * @param message Graph message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.IGraph, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Graph message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Graph * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.Graph; /** * Decodes a Graph message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Graph * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.Graph; /** * Verifies a Graph message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Graph message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Graph */ public static fromObject(object: { [k: string]: any }): px.vispb.Graph; /** * Creates a plain object from a Graph message. Also converts values to other types if specified. * @param message Graph * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.Graph, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Graph to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Graph { /** Properties of an AdjacencyList. */ interface IAdjacencyList { /** AdjacencyList fromColumn */ fromColumn?: (string|null); /** AdjacencyList toColumn */ toColumn?: (string|null); } /** Represents an AdjacencyList. */ class AdjacencyList implements IAdjacencyList { /** * Constructs a new AdjacencyList. * @param [properties] Properties to set */ constructor(properties?: px.vispb.Graph.IAdjacencyList); /** AdjacencyList fromColumn. */ public fromColumn: string; /** AdjacencyList toColumn. */ public toColumn: string; /** * Creates a new AdjacencyList instance using the specified properties. * @param [properties] Properties to set * @returns AdjacencyList instance */ public static create(properties?: px.vispb.Graph.IAdjacencyList): px.vispb.Graph.AdjacencyList; /** * Encodes the specified AdjacencyList message. Does not implicitly {@link px.vispb.Graph.AdjacencyList.verify|verify} messages. * @param message AdjacencyList message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.Graph.IAdjacencyList, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified AdjacencyList message, length delimited. Does not implicitly {@link px.vispb.Graph.AdjacencyList.verify|verify} messages. * @param message AdjacencyList message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.Graph.IAdjacencyList, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an AdjacencyList message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns AdjacencyList * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.Graph.AdjacencyList; /** * Decodes an AdjacencyList message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns AdjacencyList * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.Graph.AdjacencyList; /** * Verifies an AdjacencyList message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an AdjacencyList message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns AdjacencyList */ public static fromObject(object: { [k: string]: any }): px.vispb.Graph.AdjacencyList; /** * Creates a plain object from an AdjacencyList message. Also converts values to other types if specified. * @param message AdjacencyList * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.Graph.AdjacencyList, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this AdjacencyList to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an EdgeThresholds. */ interface IEdgeThresholds { /** EdgeThresholds mediumThreshold */ mediumThreshold?: (number|Long|null); /** EdgeThresholds highThreshold */ highThreshold?: (number|Long|null); } /** Represents an EdgeThresholds. */ class EdgeThresholds implements IEdgeThresholds { /** * Constructs a new EdgeThresholds. * @param [properties] Properties to set */ constructor(properties?: px.vispb.Graph.IEdgeThresholds); /** EdgeThresholds mediumThreshold. */ public mediumThreshold: (number|Long); /** EdgeThresholds highThreshold. */ public highThreshold: (number|Long); /** * Creates a new EdgeThresholds instance using the specified properties. * @param [properties] Properties to set * @returns EdgeThresholds instance */ public static create(properties?: px.vispb.Graph.IEdgeThresholds): px.vispb.Graph.EdgeThresholds; /** * Encodes the specified EdgeThresholds message. Does not implicitly {@link px.vispb.Graph.EdgeThresholds.verify|verify} messages. * @param message EdgeThresholds message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.Graph.IEdgeThresholds, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EdgeThresholds message, length delimited. Does not implicitly {@link px.vispb.Graph.EdgeThresholds.verify|verify} messages. * @param message EdgeThresholds message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.Graph.IEdgeThresholds, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EdgeThresholds message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EdgeThresholds * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.Graph.EdgeThresholds; /** * Decodes an EdgeThresholds message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EdgeThresholds * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.Graph.EdgeThresholds; /** * Verifies an EdgeThresholds message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EdgeThresholds message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EdgeThresholds */ public static fromObject(object: { [k: string]: any }): px.vispb.Graph.EdgeThresholds; /** * Creates a plain object from an EdgeThresholds message. Also converts values to other types if specified. * @param message EdgeThresholds * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.Graph.EdgeThresholds, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EdgeThresholds to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a RequestGraph. */ interface IRequestGraph { /** RequestGraph requestorPodColumn */ requestorPodColumn?: (string|null); /** RequestGraph responderPodColumn */ responderPodColumn?: (string|null); /** RequestGraph requestorServiceColumn */ requestorServiceColumn?: (string|null); /** RequestGraph responderServiceColumn */ responderServiceColumn?: (string|null); /** RequestGraph p50Column */ p50Column?: (string|null); /** RequestGraph p90Column */ p90Column?: (string|null); /** RequestGraph p99Column */ p99Column?: (string|null); /** RequestGraph errorRateColumn */ errorRateColumn?: (string|null); /** RequestGraph requestsPerSecondColumn */ requestsPerSecondColumn?: (string|null); /** RequestGraph inboundBytesPerSecondColumn */ inboundBytesPerSecondColumn?: (string|null); /** RequestGraph outboundBytesPerSecondColumn */ outboundBytesPerSecondColumn?: (string|null); /** RequestGraph totalRequestCountColumn */ totalRequestCountColumn?: (string|null); } /** Represents a RequestGraph. */ class RequestGraph implements IRequestGraph { /** * Constructs a new RequestGraph. * @param [properties] Properties to set */ constructor(properties?: px.vispb.IRequestGraph); /** RequestGraph requestorPodColumn. */ public requestorPodColumn: string; /** RequestGraph responderPodColumn. */ public responderPodColumn: string; /** RequestGraph requestorServiceColumn. */ public requestorServiceColumn: string; /** RequestGraph responderServiceColumn. */ public responderServiceColumn: string; /** RequestGraph p50Column. */ public p50Column: string; /** RequestGraph p90Column. */ public p90Column: string; /** RequestGraph p99Column. */ public p99Column: string; /** RequestGraph errorRateColumn. */ public errorRateColumn: string; /** RequestGraph requestsPerSecondColumn. */ public requestsPerSecondColumn: string; /** RequestGraph inboundBytesPerSecondColumn. */ public inboundBytesPerSecondColumn: string; /** RequestGraph outboundBytesPerSecondColumn. */ public outboundBytesPerSecondColumn: string; /** RequestGraph totalRequestCountColumn. */ public totalRequestCountColumn: string; /** * Creates a new RequestGraph instance using the specified properties. * @param [properties] Properties to set * @returns RequestGraph instance */ public static create(properties?: px.vispb.IRequestGraph): px.vispb.RequestGraph; /** * Encodes the specified RequestGraph message. Does not implicitly {@link px.vispb.RequestGraph.verify|verify} messages. * @param message RequestGraph message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.IRequestGraph, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified RequestGraph message, length delimited. Does not implicitly {@link px.vispb.RequestGraph.verify|verify} messages. * @param message RequestGraph message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.IRequestGraph, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a RequestGraph message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns RequestGraph * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.RequestGraph; /** * Decodes a RequestGraph message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns RequestGraph * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.RequestGraph; /** * Verifies a RequestGraph message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a RequestGraph message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns RequestGraph */ public static fromObject(object: { [k: string]: any }): px.vispb.RequestGraph; /** * Creates a plain object from a RequestGraph message. Also converts values to other types if specified. * @param message RequestGraph * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.RequestGraph, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this RequestGraph to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a StackTraceFlameGraph. */ interface IStackTraceFlameGraph { /** StackTraceFlameGraph stacktraceColumn */ stacktraceColumn?: (string|null); /** StackTraceFlameGraph countColumn */ countColumn?: (string|null); /** StackTraceFlameGraph percentageColumn */ percentageColumn?: (string|null); /** StackTraceFlameGraph namespaceColumn */ namespaceColumn?: (string|null); /** StackTraceFlameGraph podColumn */ podColumn?: (string|null); /** StackTraceFlameGraph containerColumn */ containerColumn?: (string|null); /** StackTraceFlameGraph pidColumn */ pidColumn?: (string|null); /** StackTraceFlameGraph nodeColumn */ nodeColumn?: (string|null); /** StackTraceFlameGraph percentageLabel */ percentageLabel?: (string|null); } /** Represents a StackTraceFlameGraph. */ class StackTraceFlameGraph implements IStackTraceFlameGraph { /** * Constructs a new StackTraceFlameGraph. * @param [properties] Properties to set */ constructor(properties?: px.vispb.IStackTraceFlameGraph); /** StackTraceFlameGraph stacktraceColumn. */ public stacktraceColumn: string; /** StackTraceFlameGraph countColumn. */ public countColumn: string; /** StackTraceFlameGraph percentageColumn. */ public percentageColumn: string; /** StackTraceFlameGraph namespaceColumn. */ public namespaceColumn: string; /** StackTraceFlameGraph podColumn. */ public podColumn: string; /** StackTraceFlameGraph containerColumn. */ public containerColumn: string; /** StackTraceFlameGraph pidColumn. */ public pidColumn: string; /** StackTraceFlameGraph nodeColumn. */ public nodeColumn: string; /** StackTraceFlameGraph percentageLabel. */ public percentageLabel: string; /** * Creates a new StackTraceFlameGraph instance using the specified properties. * @param [properties] Properties to set * @returns StackTraceFlameGraph instance */ public static create(properties?: px.vispb.IStackTraceFlameGraph): px.vispb.StackTraceFlameGraph; /** * Encodes the specified StackTraceFlameGraph message. Does not implicitly {@link px.vispb.StackTraceFlameGraph.verify|verify} messages. * @param message StackTraceFlameGraph message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: px.vispb.IStackTraceFlameGraph, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified StackTraceFlameGraph message, length delimited. Does not implicitly {@link px.vispb.StackTraceFlameGraph.verify|verify} messages. * @param message StackTraceFlameGraph message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: px.vispb.IStackTraceFlameGraph, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a StackTraceFlameGraph message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns StackTraceFlameGraph * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): px.vispb.StackTraceFlameGraph; /** * Decodes a StackTraceFlameGraph message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns StackTraceFlameGraph * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): px.vispb.StackTraceFlameGraph; /** * Verifies a StackTraceFlameGraph message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a StackTraceFlameGraph message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns StackTraceFlameGraph */ public static fromObject(object: { [k: string]: any }): px.vispb.StackTraceFlameGraph; /** * Creates a plain object from a StackTraceFlameGraph message. Also converts values to other types if specified. * @param message StackTraceFlameGraph * @param [options] Conversion options * @returns Plain object */ public static toObject(message: px.vispb.StackTraceFlameGraph, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this StackTraceFlameGraph to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } /** Namespace google. */ export namespace google { /** Namespace protobuf. */ namespace protobuf { /** Properties of an Any. */ interface IAny { /** Any type_url */ type_url?: (string|null); /** Any value */ value?: (Uint8Array|null); } /** Represents an Any. */ class Any implements IAny { /** * Constructs a new Any. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IAny); /** Any type_url. */ public type_url: string; /** Any value. */ public value: Uint8Array; /** * Creates a new Any instance using the specified properties. * @param [properties] Properties to set * @returns Any instance */ public static create(properties?: google.protobuf.IAny): google.protobuf.Any; /** * Encodes the specified Any message. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. * @param message Any message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Any message, length delimited. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. * @param message Any message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Any message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Any * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Any; /** * Decodes an Any message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Any * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Any; /** * Verifies an Any message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Any message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Any */ public static fromObject(object: { [k: string]: any }): google.protobuf.Any; /** * Creates a plain object from an Any message. Also converts values to other types if specified. * @param message Any * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Any to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DoubleValue. */ interface IDoubleValue { /** DoubleValue value */ value?: (number|null); } /** Represents a DoubleValue. */ class DoubleValue implements IDoubleValue { /** * Constructs a new DoubleValue. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IDoubleValue); /** DoubleValue value. */ public value: number; /** * Creates a new DoubleValue instance using the specified properties. * @param [properties] Properties to set * @returns DoubleValue instance */ public static create(properties?: google.protobuf.IDoubleValue): google.protobuf.DoubleValue; /** * Encodes the specified DoubleValue message. Does not implicitly {@link google.protobuf.DoubleValue.verify|verify} messages. * @param message DoubleValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IDoubleValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DoubleValue message, length delimited. Does not implicitly {@link google.protobuf.DoubleValue.verify|verify} messages. * @param message DoubleValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IDoubleValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DoubleValue message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DoubleValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DoubleValue; /** * Decodes a DoubleValue message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DoubleValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DoubleValue; /** * Verifies a DoubleValue message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DoubleValue */ public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; /** * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. * @param message DoubleValue * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DoubleValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FloatValue. */ interface IFloatValue { /** FloatValue value */ value?: (number|null); } /** Represents a FloatValue. */ class FloatValue implements IFloatValue { /** * Constructs a new FloatValue. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFloatValue); /** FloatValue value. */ public value: number; /** * Creates a new FloatValue instance using the specified properties. * @param [properties] Properties to set * @returns FloatValue instance */ public static create(properties?: google.protobuf.IFloatValue): google.protobuf.FloatValue; /** * Encodes the specified FloatValue message. Does not implicitly {@link google.protobuf.FloatValue.verify|verify} messages. * @param message FloatValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFloatValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FloatValue message, length delimited. Does not implicitly {@link google.protobuf.FloatValue.verify|verify} messages. * @param message FloatValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFloatValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FloatValue message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FloatValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FloatValue; /** * Decodes a FloatValue message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FloatValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FloatValue; /** * Verifies a FloatValue message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FloatValue */ public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; /** * Creates a plain object from a FloatValue message. Also converts values to other types if specified. * @param message FloatValue * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FloatValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an Int64Value. */ interface IInt64Value { /** Int64Value value */ value?: (number|Long|null); } /** Represents an Int64Value. */ class Int64Value implements IInt64Value { /** * Constructs a new Int64Value. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IInt64Value); /** Int64Value value. */ public value: (number|Long); /** * Creates a new Int64Value instance using the specified properties. * @param [properties] Properties to set * @returns Int64Value instance */ public static create(properties?: google.protobuf.IInt64Value): google.protobuf.Int64Value; /** * Encodes the specified Int64Value message. Does not implicitly {@link google.protobuf.Int64Value.verify|verify} messages. * @param message Int64Value message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IInt64Value, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Int64Value message, length delimited. Does not implicitly {@link google.protobuf.Int64Value.verify|verify} messages. * @param message Int64Value message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IInt64Value, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Int64Value message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Int64Value * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Int64Value; /** * Decodes an Int64Value message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Int64Value * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Int64Value; /** * Verifies an Int64Value message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Int64Value */ public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; /** * Creates a plain object from an Int64Value message. Also converts values to other types if specified. * @param message Int64Value * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Int64Value to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a UInt64Value. */ interface IUInt64Value { /** UInt64Value value */ value?: (number|Long|null); } /** Represents a UInt64Value. */ class UInt64Value implements IUInt64Value { /** * Constructs a new UInt64Value. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IUInt64Value); /** UInt64Value value. */ public value: (number|Long); /** * Creates a new UInt64Value instance using the specified properties. * @param [properties] Properties to set * @returns UInt64Value instance */ public static create(properties?: google.protobuf.IUInt64Value): google.protobuf.UInt64Value; /** * Encodes the specified UInt64Value message. Does not implicitly {@link google.protobuf.UInt64Value.verify|verify} messages. * @param message UInt64Value message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IUInt64Value, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified UInt64Value message, length delimited. Does not implicitly {@link google.protobuf.UInt64Value.verify|verify} messages. * @param message UInt64Value message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IUInt64Value, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a UInt64Value message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns UInt64Value * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UInt64Value; /** * Decodes a UInt64Value message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns UInt64Value * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UInt64Value; /** * Verifies a UInt64Value message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns UInt64Value */ public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; /** * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. * @param message UInt64Value * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this UInt64Value to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an Int32Value. */ interface IInt32Value { /** Int32Value value */ value?: (number|null); } /** Represents an Int32Value. */ class Int32Value implements IInt32Value { /** * Constructs a new Int32Value. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IInt32Value); /** Int32Value value. */ public value: number; /** * Creates a new Int32Value instance using the specified properties. * @param [properties] Properties to set * @returns Int32Value instance */ public static create(properties?: google.protobuf.IInt32Value): google.protobuf.Int32Value; /** * Encodes the specified Int32Value message. Does not implicitly {@link google.protobuf.Int32Value.verify|verify} messages. * @param message Int32Value message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IInt32Value, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Int32Value message, length delimited. Does not implicitly {@link google.protobuf.Int32Value.verify|verify} messages. * @param message Int32Value message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IInt32Value, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Int32Value message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Int32Value * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Int32Value; /** * Decodes an Int32Value message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Int32Value * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Int32Value; /** * Verifies an Int32Value message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Int32Value */ public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; /** * Creates a plain object from an Int32Value message. Also converts values to other types if specified. * @param message Int32Value * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Int32Value to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a UInt32Value. */ interface IUInt32Value { /** UInt32Value value */ value?: (number|null); } /** Represents a UInt32Value. */ class UInt32Value implements IUInt32Value { /** * Constructs a new UInt32Value. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IUInt32Value); /** UInt32Value value. */ public value: number; /** * Creates a new UInt32Value instance using the specified properties. * @param [properties] Properties to set * @returns UInt32Value instance */ public static create(properties?: google.protobuf.IUInt32Value): google.protobuf.UInt32Value; /** * Encodes the specified UInt32Value message. Does not implicitly {@link google.protobuf.UInt32Value.verify|verify} messages. * @param message UInt32Value message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IUInt32Value, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified UInt32Value message, length delimited. Does not implicitly {@link google.protobuf.UInt32Value.verify|verify} messages. * @param message UInt32Value message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IUInt32Value, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a UInt32Value message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns UInt32Value * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UInt32Value; /** * Decodes a UInt32Value message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns UInt32Value * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UInt32Value; /** * Verifies a UInt32Value message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns UInt32Value */ public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; /** * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. * @param message UInt32Value * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this UInt32Value to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a BoolValue. */ interface IBoolValue { /** BoolValue value */ value?: (boolean|null); } /** Represents a BoolValue. */ class BoolValue implements IBoolValue { /** * Constructs a new BoolValue. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IBoolValue); /** BoolValue value. */ public value: boolean; /** * Creates a new BoolValue instance using the specified properties. * @param [properties] Properties to set * @returns BoolValue instance */ public static create(properties?: google.protobuf.IBoolValue): google.protobuf.BoolValue; /** * Encodes the specified BoolValue message. Does not implicitly {@link google.protobuf.BoolValue.verify|verify} messages. * @param message BoolValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IBoolValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified BoolValue message, length delimited. Does not implicitly {@link google.protobuf.BoolValue.verify|verify} messages. * @param message BoolValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IBoolValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a BoolValue message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BoolValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.BoolValue; /** * Decodes a BoolValue message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns BoolValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.BoolValue; /** * Verifies a BoolValue message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns BoolValue */ public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; /** * Creates a plain object from a BoolValue message. Also converts values to other types if specified. * @param message BoolValue * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this BoolValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a StringValue. */ interface IStringValue { /** StringValue value */ value?: (string|null); } /** Represents a StringValue. */ class StringValue implements IStringValue { /** * Constructs a new StringValue. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IStringValue); /** StringValue value. */ public value: string; /** * Creates a new StringValue instance using the specified properties. * @param [properties] Properties to set * @returns StringValue instance */ public static create(properties?: google.protobuf.IStringValue): google.protobuf.StringValue; /** * Encodes the specified StringValue message. Does not implicitly {@link google.protobuf.StringValue.verify|verify} messages. * @param message StringValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IStringValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified StringValue message, length delimited. Does not implicitly {@link google.protobuf.StringValue.verify|verify} messages. * @param message StringValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IStringValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a StringValue message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns StringValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.StringValue; /** * Decodes a StringValue message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns StringValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.StringValue; /** * Verifies a StringValue message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a StringValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns StringValue */ public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; /** * Creates a plain object from a StringValue message. Also converts values to other types if specified. * @param message StringValue * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this StringValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a BytesValue. */ interface IBytesValue { /** BytesValue value */ value?: (Uint8Array|null); } /** Represents a BytesValue. */ class BytesValue implements IBytesValue { /** * Constructs a new BytesValue. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IBytesValue); /** BytesValue value. */ public value: Uint8Array; /** * Creates a new BytesValue instance using the specified properties. * @param [properties] Properties to set * @returns BytesValue instance */ public static create(properties?: google.protobuf.IBytesValue): google.protobuf.BytesValue; /** * Encodes the specified BytesValue message. Does not implicitly {@link google.protobuf.BytesValue.verify|verify} messages. * @param message BytesValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IBytesValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified BytesValue message, length delimited. Does not implicitly {@link google.protobuf.BytesValue.verify|verify} messages. * @param message BytesValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IBytesValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a BytesValue message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BytesValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.BytesValue; /** * Decodes a BytesValue message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns BytesValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.BytesValue; /** * Verifies a BytesValue message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns BytesValue */ public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; /** * Creates a plain object from a BytesValue message. Also converts values to other types if specified. * @param message BytesValue * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this BytesValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } }
the_stack
import {map} from './dsl'; var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ]; var escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); function isArray(test) { return Object.prototype.toString.call(test) === "[object Array]"; } // A Segment represents a segment in the original route description. // Each Segment type provides an `eachChar` and `regex` method. // // The `eachChar` method invokes the callback with one or more character // specifications. A character specification consumes one or more input // characters. // // The `regex` method returns a regex fragment for the segment. If the // segment is a dynamic of star segment, the regex fragment also includes // a capture. // // A character specification contains: // // * `validChars`: a String with a list of all valid characters, or // * `invalidChars`: a String with a list of all invalid characters // * `repeat`: true if the character specification can repeat function StaticSegment(string) { this.string = string; } StaticSegment.prototype = { eachChar: function(callback) { var string = this.string, ch; for (var i=0, l=string.length; i<l; i++) { ch = string.charAt(i); callback({ validChars: ch }); } }, regex: function() { return this.string.replace(escapeRegex, '\\$1'); }, generate: function() { return this.string; } }; function DynamicSegment(name) { this.name = name; } DynamicSegment.prototype = { eachChar: function(callback) { callback({ invalidChars: "/", repeat: true }); }, regex: function() { return "([^/]+)"; }, generate: function(params) { return params[this.name]; } }; function StarSegment(name) { this.name = name; } StarSegment.prototype = { eachChar: function(callback) { callback({ invalidChars: "", repeat: true }); }, regex: function() { return "(.+)"; }, generate: function(params) { return params[this.name]; } }; function EpsilonSegment() {} EpsilonSegment.prototype = { eachChar: function() {}, regex: function() { return ""; }, generate: function() { return ""; } }; function parse(route, names, types) { // normalize route as not starting with a "/". Recognition will // also normalize. if (route.charAt(0) === "/") { route = route.substr(1); } var segments = route.split("/"), results = []; for (var i=0, l=segments.length; i<l; i++) { var segment = segments[i], match; if (match = segment.match(/^:([^\/]+)$/)) { results.push(new DynamicSegment(match[1])); names.push(match[1]); types.dynamics++; } else if (match = segment.match(/^\*([^\/]+)$/)) { results.push(new StarSegment(match[1])); names.push(match[1]); types.stars++; } else if(segment === "") { results.push(new EpsilonSegment()); } else { results.push(new StaticSegment(segment)); types.statics++; } } return results; } // A State has a character specification and (`charSpec`) and a list of possible // subsequent states (`nextStates`). // // If a State is an accepting state, it will also have several additional // properties: // // * `regex`: A regular expression that is used to extract parameters from paths // that reached this accepting state. // * `handlers`: Information on how to convert the list of captures into calls // to registered handlers with the specified parameters // * `types`: How many static, dynamic or star segments in this route. Used to // decide which route to use if multiple registered routes match a path. // // Currently, State is implemented naively by looping over `nextStates` and // comparing a character specification against a character. A more efficient // implementation would use a hash of keys pointing at one or more next states. function State(charSpec?) { this.charSpec = charSpec; this.nextStates = []; } State.prototype = { get: function(charSpec) { var nextStates = this.nextStates; for (var i=0, l=nextStates.length; i<l; i++) { var child = nextStates[i]; var isEqual = child.charSpec.validChars === charSpec.validChars; isEqual = isEqual && child.charSpec.invalidChars === charSpec.invalidChars; if (isEqual) { return child; } } }, put: function(charSpec) { var state; // If the character specification already exists in a child of the current // state, just return that state. if (state = this.get(charSpec)) { return state; } // Make a new state for the character spec state = new State(charSpec); // Insert the new state as a child of the current state this.nextStates.push(state); // If this character specification repeats, insert the new state as a child // of itself. Note that this will not trigger an infinite loop because each // transition during recognition consumes a character. if (charSpec.repeat) { state.nextStates.push(state); } // Return the new state return state; }, // Find a list of child states matching the next character match: function(ch) { // DEBUG "Processing `" + ch + "`:" var nextStates = this.nextStates, child, charSpec, chars; // DEBUG " " + debugState(this) var returned = []; for (var i=0, l=nextStates.length; i<l; i++) { child = nextStates[i]; charSpec = child.charSpec; if (typeof (chars = charSpec.validChars) !== 'undefined') { if (chars.indexOf(ch) !== -1) { returned.push(child); } } else if (typeof (chars = charSpec.invalidChars) !== 'undefined') { if (chars.indexOf(ch) === -1) { returned.push(child); } } } return returned; } /** IF DEBUG , debug: function() { var charSpec = this.charSpec, debug = "[", chars = charSpec.validChars || charSpec.invalidChars; if (charSpec.invalidChars) { debug += "^"; } debug += chars; debug += "]"; if (charSpec.repeat) { debug += "+"; } return debug; } END IF **/ }; /** IF DEBUG function debug(log) { console.log(log); } function debugState(state) { return state.nextStates.map(function(n) { if (n.nextStates.length === 0) { return "( " + n.debug() + " [accepting] )"; } return "( " + n.debug() + " <then> " + n.nextStates.map(function(s) { return s.debug() }).join(" or ") + " )"; }).join(", ") } END IF **/ // This is a somewhat naive strategy, but should work in a lot of cases // A better strategy would properly resolve /posts/:id/new and /posts/edit/:id. // // This strategy generally prefers more static and less dynamic matching. // Specifically, it // // * prefers fewer stars to more, then // * prefers using stars for less of the match to more, then // * prefers fewer dynamic segments to more, then // * prefers more static segments to more function sortSolutions(states) { return states.sort(function(a, b) { if (a.types.stars !== b.types.stars) { return a.types.stars - b.types.stars; } if (a.types.stars) { if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; } if (a.types.dynamics !== b.types.dynamics) { return b.types.dynamics - a.types.dynamics; } } if (a.types.dynamics !== b.types.dynamics) { return a.types.dynamics - b.types.dynamics; } if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; } return 0; }); } function recognizeChar(states, ch) { var nextStates = []; for (var i=0, l=states.length; i<l; i++) { var state = states[i]; nextStates = nextStates.concat(state.match(ch)); } return nextStates; } var oCreate = Object.create || function(proto) { function F() {} F.prototype = proto; return new F(); }; function RecognizeResults(queryParams) { this.queryParams = queryParams || {}; } RecognizeResults.prototype = oCreate({ splice: Array.prototype.splice, slice: Array.prototype.slice, push: Array.prototype.push, length: 0, queryParams: null }); function findHandler(state, path, queryParams) { var handlers = state.handlers, regex = state.regex; var captures = path.match(regex), currentCapture = 1; var result = new RecognizeResults(queryParams); for (var i=0, l=handlers.length; i<l; i++) { var handler = handlers[i], names = handler.names, params = {}; for (var j=0, m=names.length; j<m; j++) { params[names[j]] = captures[currentCapture++]; } result.push({ handler: handler.handler, params: params, isDynamic: !!names.length }); } return result; } function addSegment(currentState, segment) { segment.eachChar(function(ch) { var state; currentState = currentState.put(ch); }); return currentState; } // The main interface export var RouteRecognizer = function() { this.rootState = new State(); this.names = {}; }; RouteRecognizer.prototype = { add: function(routes, options) { var currentState = this.rootState, regex = "^", types = { statics: 0, dynamics: 0, stars: 0 }, handlers = [], allSegments = [], name; var isEmpty = true; for (var i=0, l=routes.length; i<l; i++) { var route = routes[i], names = []; var segments = parse(route.path, names, types); allSegments = allSegments.concat(segments); for (var j=0, m=segments.length; j<m; j++) { var segment = segments[j]; if (segment instanceof EpsilonSegment) { continue; } isEmpty = false; // Add a "/" for the new segment currentState = currentState.put({ validChars: "/" }); regex += "/"; // Add a representation of the segment to the NFA and regex currentState = addSegment(currentState, segment); regex += segment.regex(); } var handler = { handler: route.handler, names: names }; handlers.push(handler); } if (isEmpty) { currentState = currentState.put({ validChars: "/" }); regex += "/"; } currentState.handlers = handlers; currentState.regex = new RegExp(regex + "$"); currentState.types = types; if (name = options && options.as) { this.names[name] = { segments: allSegments, handlers: handlers }; } }, handlersFor: function(name) { var route = this.names[name], result = []; if (!route) { throw new Error("There is no route named " + name); } for (var i=0, l=route.handlers.length; i<l; i++) { result.push(route.handlers[i]); } return result; }, hasRoute: function(name) { return !!this.names[name]; }, generate: function(name, params) { var route = this.names[name], output = ""; if (!route) { throw new Error("There is no route named " + name); } var segments = route.segments; for (var i=0, l=segments.length; i<l; i++) { var segment = segments[i]; if (segment instanceof EpsilonSegment) { continue; } output += "/"; output += segment.generate(params); } if (output.charAt(0) !== '/') { output = '/' + output; } if (params && params.queryParams) { output += this.generateQueryString(params.queryParams, route.handlers); } return output; }, generateQueryString: function(params, handlers) { var pairs = []; var keys = []; for(var key in params) { if (params.hasOwnProperty(key)) { keys.push(key); } } keys.sort(); for (var i = 0, len = keys.length; i < len; i++) { key = keys[i]; var value = params[key]; if (value === null) { continue; } var pair = encodeURIComponent(key); if (isArray(value)) { for (var j = 0, l = value.length; j < l; j++) { var arrayPair = key + '[]' + '=' + encodeURIComponent(value[j]); pairs.push(arrayPair); } } else { pair += "=" + encodeURIComponent(value); pairs.push(pair); } } if (pairs.length === 0) { return ''; } return "?" + pairs.join("&"); }, parseQueryString: function(queryString) { var pairs = queryString.split("&"), queryParams = {}; for(var i=0; i < pairs.length; i++) { var pair = pairs[i].split('='), key = decodeURIComponent(pair[0]), keyLength = key.length, isArray = false, value; if (pair.length === 1) { value = 'true'; } else { //Handle arrays if (keyLength > 2 && key.slice(keyLength -2) === '[]') { isArray = true; key = key.slice(0, keyLength - 2); if(!queryParams[key]) { queryParams[key] = []; } } value = pair[1] ? decodeURIComponent(pair[1]) : ''; } if (isArray) { queryParams[key].push(value); } else { queryParams[key] = value; } } return queryParams; }, recognize: function(path) { var states = [ this.rootState ], pathLen, i, l, queryStart, queryParams = {}, isSlashDropped = false; queryStart = path.indexOf('?'); if (queryStart !== -1) { var queryString = path.substr(queryStart + 1, path.length); path = path.substr(0, queryStart); queryParams = this.parseQueryString(queryString); } path = decodeURI(path); // DEBUG GROUP path if (path.charAt(0) !== "/") { path = "/" + path; } pathLen = path.length; if (pathLen > 1 && path.charAt(pathLen - 1) === "/") { path = path.substr(0, pathLen - 1); isSlashDropped = true; } for (i=0, l=path.length; i<l; i++) { states = recognizeChar(states, path.charAt(i)); if (!states.length) { break; } } // END DEBUG GROUP var solutions = []; for (i=0, l=states.length; i<l; i++) { if (states[i].handlers) { solutions.push(states[i]); } } states = sortSolutions(solutions); var state = solutions[0]; if (state && state.handlers) { // if a trailing slash was dropped and a star segment is the last segment // specified, put the trailing slash back if (isSlashDropped && state.regex.source.slice(-5) === "(.+)$") { path = path + "/"; } return findHandler(state, path, queryParams); } } }; RouteRecognizer.prototype.map = map;
the_stack
import FormDesign from '@/@types/form-design'; import { formControls, initAntDesignControls, formItemProps, columnItemProps, basicProps } from "@/formControls_antd.tsx"; import { cloneForce } from "@/lib/clone"; import axios from 'axios'; import common, { createModelId } from './common'; import store from '@/config/store'; /** 获取数据源 * @param {any} dataSource 数据源 * @param {any} type 类型 * @param {object} [options={}] 配置项 */ export function getDataSource(dataSource: any, type: any, options: { map?: (arr: any) => any, filter?: (arr: any) => boolean } = {}): Promise<Record<string, any>[]> { if (!type) throw new Error('类型参数不能为空。'); let re: Promise<Record<string, any>[]> = new Promise((resolve, reject) => resolve([])); const _exec = (_re) => { if (options.map && _re?.map) { _re = _re.map(options.map); } if (options.filter && _re?.filter) { _re = _re.filter(options.filter); } return _re; } switch (type) { case 'model-list': re = new Promise((resolve, reject) => resolve(_exec(dataSource))); break; case 'json': re = new Promise((resolve, reject) => resolve(_exec(dataSource))); break; case 'variable': if (typeof(dataSource) == 'string') { re = new Promise((resolve, reject) => { try { console.log(store.getters); let _re = Function('__data__', 'return __data__.' + dataSource)(store.getters?.getFormScript?.data); resolve(_exec(_re)); } catch (error) { reject(error); } }); } else { re = new Promise((resolve, reject) => resolve(_exec(dataSource))); } break; case 'expression': re = new Promise((resolve, reject) => resolve(_exec(Function('__data__', 'let me = __data__; return ' + dataSource)({ ...store.getters?.getFormScript?.data, ...store.getters?.getformScript?.methods })))); break; case 'basic-data': re = common.post('ExtenalApi/GetBasicDataById', { enterpriseId: store.getters.getEnterpriseId, languageCulture: "zh-CN", code: dataSource, filters: {} }).then(d => new Promise((resolve, reject) => resolve(_exec(d)))); break; case 'view-data': re = common.post('ExtenalApi/GetViewTable', { enterpriseId: store.getters.getEnterpriseId, languageCulture: "zh-CN", code: dataSource, filters: {} }).then(d => new Promise((resolve, reject) => { if (d.viewTable) { resolve(_exec(d.viewTable)); } else { reject(); } })); break; default: if (type?.type === 'api') { let api: FormDesign.Api | undefined = store.getters?.getApiList?.find(i => i.address == dataSource?.address); if (api) { re = axios.request({ method: api.type, url: api.address, [{ get:'params', post: 'data' }[api.type]]: dataSource?.params ? Function(dataSource.params)() : {} }).then(d => new Promise((resolve, reject) => resolve(_exec(dataSource?.formatter ? (Function(dataSource.formatter)()(d)) : d)))); } else { throw new Error('API不存在。'); } } break; } return re; } /** 填充控件属性 */ export function fillPropertys(controls: Array<FormDesign.FormControl>, componentLibraryName: string): Array<FormDesign.FormControl> { /** 原始组件列表 */ let _originalControlList: Array<FormDesign.FormControl> = cloneForce(controls); /** 对应组件库组件列表 */ let _controlList: Array<FormDesign.FormControl> = []; /** 初始化组件函数 */ let _initControls: Function = () => {}; switch (componentLibraryName) { case 'ant-design': _controlList = formControls; _initControls = initAntDesignControls; break; case 'vant': break; case 'uni': break; default: throw new Error(`找不到${componentLibraryName}组件库。`); } const _cb = (list: Array<FormDesign.FormControl>) => { if(list?.length) { for (let i = 0; i < list.length; i++) { let _children = list[i].children; let _control = _controlList.find(control => control.name == list[i].name); if (_control) { list[i].id = createModelId(10); list[i].control.defaultAttrs = cloneForce(_control.control.defaultAttrs); list[i].autoPrefix = _control.autoPrefix; list[i].title = _control.title; list[i].type = _control.type; list[i].isFormItem = _control.isFormItem; list[i].propertys = cloneForce(_control.propertys); list[i].render = _control.render; list[i].isHide = _control.isHide; list[i].isOriginal = _control.isOriginal; } if (_children?.length) { for (let o = 0; o < _children.length; o++) { _cb(_children[o]); } } } let _list = _initControls(list); for (let index = 0; index < list.length; index++) { list[index] = { ..._list[index], // propertyEditors: list[index].propertyEditors }; } } }; _cb(_originalControlList); return _originalControlList; } /** 拍平控件树 */ export function flatControls(controls: Array<FormDesign.FormControl>) { let _controlList: Array<FormDesign.FormControl> = []; const _cb = (list: Array<FormDesign.FormControl>) => { if(list?.length) { for (let i = 0; i < list.length; i++) { let _children = list[i].children; _controlList.push(list[i]); if (_children?.length) { for (let o = 0; o < _children.length; o++) { _cb(_children[o]); } } } } }; _cb(controls); return _controlList; } /** 获取变量真实值 */ export function getValue(variable: FormDesign.FormVariable) { return variable.default; } /** 根据变量返回对应类型的原始变量字符串 */ export function getDefaultStrForValue(val: any): string { if (typeof(val) != 'object') { switch (typeof(val)) { case 'string': return '\"\"'; case 'number': return '0'; case 'boolean': return 'false'; case 'function': return '() => {}'; case 'symbol': return 'Symbol()'; default: return 'undefined'; } } else { let type = Object.prototype.toString.apply(val).slice(8, -1); if (type == 'Object') return JSON.stringify(val, undefined, ' ').split('\n').map((i, index) => { if (index > 0) return ' ' + i.replace(/"\S+":/g, txt => txt.slice(1, -2) + ':'); else return i; }).join('\n'); else return `new ${val}()`; } } /** 解析函数并获取函数头 */ export function functionHeaderParse(match: [string, string], content: string): { body: string, bodyRanges: Array<Array<number>> } { let _regRange = new RegExp(`${match[0]}|${match[1]}`, 'g'); let _item: RegExpExecArray | null = null; let _rangeIndex = 0; let _functionRanges: Array<Array<number>> = []; let _content = content; while(_item = _regRange.exec(_content)) { if (_item !== null) { if (!_functionRanges[_rangeIndex]) { _functionRanges[_rangeIndex] = [_item.index, 0]; } switch (_content[_item.index]) { case match[0]: _functionRanges[_rangeIndex][1] = _functionRanges[_rangeIndex][1] + 1; break; case match[1]: _functionRanges[_rangeIndex][1] = _functionRanges[_rangeIndex][1] - 1; break; default: break; } if (_functionRanges[_rangeIndex][1] == 0) { _functionRanges[_rangeIndex][1] = _item.index; _rangeIndex++; } } } for (let index = _functionRanges.length - 1; index >= 0; index--) { _content = `${_content.substr(0, _functionRanges[index][0])};${_content.substr(_functionRanges[index][1] + 1)}`; } return { body: _content, bodyRanges: _functionRanges }; } /** 获取真实属性 */ export function getRealProp(control: FormDesign.FormControl, propName: string, script: FormDesign.FormScript) { const props = control.control.attrs; if (!props['__' + propName]) return props[propName]; let _editor = control.propertyEditors?.[propName]; let _value = props['__' + propName]; switch (_editor) { case 'expression': _value = Function('__data__', 'let me = __data__; return ' + _value)({ ...script.data instanceof Function ? script.data() : script.data, ...script.methods }); break; } return _value; } export function getRealProps(control: FormDesign.FormControl, script: FormDesign.FormScript) { return Object.keys(control.control.attrs).map(i => getRealProp(control, i, script)); } /** 解析Vue代码 */ export function variableVueScript(strVariable: string): { script: FormDesign.FormScript, comment: Record<string, string> } { let _reg = /\/\*\*\s*(?<remark>.*?)\s*\*\/\s*(?<name>[a-zA-Z0-9_]+)(:|\()/g; let _item: RegExpExecArray | null; let _list: Record<string, string> = {}; while(_item = _reg.exec(strVariable)) { if (_item !== null) { _list[_item.groups?.name || ''] = _item.groups?.remark || ''; } } return { script: Function(strVariable)() as FormDesign.FormScript, comment: _list }; } /** 判断节点是否为高级子表单的子节点 */ export function isFormChild(controlId, controls: FormDesign.FormControl[]) { return controls .filter(i => i.name == 'complex-childform') .map(i => i.children) .flat(2) .map(i => i.id) .includes(controlId); } /** 判断节点是否为Flex的子节点 */ export function isFlexChild(controlId, controls: FormDesign.FormControl[]) { return controls .filter(i => i.name == 'flex') .map(i => i.children) .flat(2) .map(i => i.id) .includes(controlId); } /** 导出Vue模板代码 */ export function exportTemplate({ formConfig, panel }: { formConfig: FormDesign.FormConfig, panel: FormDesign.FormPanel }) { let _control: FormDesign.FormControl; /** 构造控件的属性 */ const _generateAttrs = (control: FormDesign.BasicControl, config?: { in?: string[], out?: string[] }, isTableChild: boolean = false) => { let _re = ''; _re += Object.entries(control.attrs || {}).filter(([key, value]) => value).map(([key, value]) => { if (config?.in?.includes(key) === false) return ''; if (config?.out?.includes(key) === true) return ''; const _isSync = _control.propertys.find(i => i.name == key)?.isSync === true; if (key.startsWith('__')) return ''; // TODO: 需要在这加上关于其他通用属性的校验! const _propertys = _control.propertys; if (formConfig.formComponentLib == 'ant-design') { _propertys.concat(basicProps); if (isFormChild(_control.id, panel.children)) { _propertys.concat(columnItemProps); } else if (isFlexChild(_control.id, panel.children)) { _propertys.concat(formItemProps); } else if (_control.isFormItem) { _propertys.concat(formItemProps); } } /** 是否为原始 */ const _isOriginalType = _control?.propertyEditors?.[key] === undefined || _propertys?.find?.(i => i?.name == key)?.editor === _control?.propertyEditors?.[key]; let _reStr = ''; if (_isOriginalType === false) { _reStr += `${key}_type='${_control?.propertyEditors?.[key]}' `; value = control.attrs['__' + key]; } else { const _propType = _propertys.find(i => i.name == key)?.editor || _control?.propertyEditors?.[key]; _reStr += `${key}_type='${_propType}' `; } // 如果是明细表下面的组件 if (isTableChild) { switch (key) { case 'remark': return ''; case 'dataIndex': return `:model='"detail_" + index + "_${value}"' v-model='record.${value}'`; case 'visible': return `v-show='${value}'`; case 'model': case 'label': return ''; default: break; } } else { switch (key) { case 'remark': return ''; case 'model': return `model='${value}' v-model='${value}'`; case 'visible': return `v-show='${value}'`; default: break; } } if (_control?.propertyEditors?.[key]) { switch (_control?.propertyEditors?.[key]) { case 'boolean': case 'pixel': case 'int': case 'float': case 'byte': case 'list': case 'javascript': case 'function': _reStr += `:${key}${_isSync?'.sync':''}='${value}'`; break; case 'expression': case 'variable': _reStr += `:${key}${_isSync?'.sync':''}='${value}'`; break; case 'singer-line': case 'multi-line': case 'color': case 'icon': _reStr += `${key}='${value}'`; break; case 'json': case 'model-list': _reStr += ` :${key}${_isSync?'.sync':''}='${JSON.stringify(value)}'`; break; case 'rules': if (value.length) { let _ruleTxt = ''; _ruleTxt += `:${key}='[`; _ruleTxt += value.map(i => { let _ruleItem = Object.entries(i).map(([ruleKey, ruleValue]) => { let _ruleValue = ruleValue; if (typeof(_ruleValue) === 'string') return `${ruleKey}: "${ruleValue}"`; else return `${ruleKey}: ${ruleValue}`; }).join(', '); return `{ ${_ruleItem} }`.replace(/\{\{value\}\}/g, i[i.category]); }).join(', ').replace(/\{\{label\}\}/g, control.attrs.label); _ruleTxt += ']\''; return `${_ruleTxt}`; } else { return ''; } break; case 'view-data': case 'basic-data': case 'api': _reStr += ` ${key}='${control.attrs['__' + key]}'`; break; case 'box': break; default: break; } return _reStr; } let _value = value; if (value instanceof Object || value instanceof Array) { _value = JSON.stringify(value); } // if (control.attrs['__' + key]) return ''; if (typeof(_value) === 'string') return `${key}='${_value.replace(/me\./g, 'this.').replace(/'/g, '\\\'')}'`; else return `:${key}${_isSync?'.sync':''}='${_value}'`; }).filter(i => i).join(' '); let _events = Object.entries(control.events || {}); if (_events.length) { _re += ' '; _re += _events.map(([key, value]) => { let _value = value; if (value instanceof Object || value instanceof Array) { _value = JSON.stringify(value); } return `@${key}='${_value}'`; }).filter(i => i).join(' '); } return _re; }; /** 构造单个基础控件 */ const _generateSingerBasicControl = (control: FormDesign.BasicControl, level, mainIndex?: number) => { let _re = ''; _re += `<${control.control} `; _re += _generateAttrs(control); if (control.control == 'a-divider') { debugger; _re += ` name="d${mainIndex}" `; } let _slots = Object.entries(control.slot); if (_slots.length) { _re += '\n'; _slots.map(([key, value]) => { _re += `${' '.repeat(level + 1)}<template #${key}>\n`; _re += value.map(item => _generateSingerBasicControl(item, level + 2)); _re += `${' '.repeat(level + 1)}</template>\n`; }).join('\n\n'); _re += `${' '.repeat(level)}`; } _re += `</${control.control}>\n`; return _re; }; /** 构造单个控件 */ const _generateSingerControl = (control: FormDesign.FormControl, level, pControl?: FormDesign.FormControl, mainIndex?: number) => { _control = control; let _re = ''; let _reControl = ''; // if (control.isFormItem) { // let _attrs = control.control.attrs; // _re += `<a-form-item class="" :colon="false" :label-col="{ span: ${_attrs.labelSpan}, offset: ${_attrs.labelOffset} }" :wrapper-col="{ span: ${_attrs.wrapperSpan}, offset: ${_attrs.wrapperOffset} }" ${_generateAttrs(control.control, { in: ['label', 'labelCol'] })}> // {{control}} // </a-form-item>`.split('\n').map(i => (i.startsWith('{{') ? '' : ' '.repeat(level)) + i).join('\n'); // level++; // } else { // _re += '{{control}}'; // } _re += '{{control}}'; if (control.render) { let _renderTemplete = control.render(control).split('\n').map(i => (i.startsWith('{{') ? '' : ' '.repeat(level)) + i).join('\n'); _renderTemplete = _renderTemplete.replace('{{attrs}}', _generateAttrs(control.control, {}, pControl?.name === 'complex-childform')); let _children: FormDesign.FormControl[] = control.children?.flat(2) || []; _renderTemplete = _renderTemplete.replace(/\{\{children_(\d+)\}\}/g, (txt, index) => { if (_children[Number(index)]) { return _generateSingerControl(_children[Number(index)], level + 2, control, mainIndex); } else { return ''; } }); _reControl += _renderTemplete; } else { if (pControl?.name === 'complex-childform') { if (control.control.attrs.onlyText) { return _re.replace('{{control}}', `{{text}}`); } } if (control.isOriginal === true) { _reControl += `${' '.repeat(level)}<${control.control.control} `; } else { _reControl += `${' '.repeat(level)}<form-control :form="form" :onlyText="isOnlyText" control='${control.control.control}' `; } if (control.ref) { _reControl += `ref='${control.ref}' `; } _reControl += _generateAttrs(control.control, {}, pControl?.name === 'complex-childform'); _reControl += `>`; if (control.control.attrs.text) { _reControl += control.control.attrs.text; } if (control.children) { control.children.forEach((child, childIndex) => { if (child) { _reControl += `<template #child${childIndex}>`; _reControl += child.flat(1).map(child => _generateSingerControl(child, level + 1, control, mainIndex)); _reControl += '</template>'; } }); } let _slots = Object.entries(control.control.slot); if (_slots.length) { _reControl += '\n'; _slots.map(([key, value]) => { _reControl += `${' '.repeat(level + 1)}<template #${key}>\n`; _reControl += value.map(item => _generateSingerBasicControl(item, level + 2)); _reControl += `${' '.repeat(level + 1)}</template>\n`; }).join('\n\n'); _reControl += `${' '.repeat(level)}`; } if (control.isOriginal === true) { _reControl += `</${control.control.control}>`; } else { _reControl += `</form-control>`; } } return _re.replace('{{control}}', _reControl); }; /** 递归构造控件 */ const _generateControlStr = (controls: FormDesign.FormControl[]) => { let _re = ''; _re += controls.map((i, index) => _generateSingerControl(i, 2, undefined, index)).join('\n'); return _re; }; /** 构造Vue页面文件 */ let _vueTxt = `<div> <!-- FormTitle : ${formConfig.formTitle} --> <!-- FormName : ${formConfig.formName} --> <!-- CreateDate : ${new Date().format('yyyy-MM-dd HH:mm')} --> <div class="page-${formConfig.formName}"> <h1 class="form-title">${formConfig.formTitle}</h1> ${_generateControlStr(panel.children)} </div> </div>`; console.log(_vueTxt); return _vueTxt; }
the_stack
import { Context } from './Context'; import { Local } from './Local'; import { Type, isV8Type } from './type'; export function assign( context: Context, destination: Local, value: Local | string, allowSkip?: boolean, ) { let val: Local; if (typeof value === 'string') { const tmp = context.locals.symbol('assign_tmp'); tmp.setCode(value); val = tmp; } else { val = value; } if (destination.initialized || !allowSkip) { context.emitAssign(destination, val); } else { destination.assign(val); } } export function plus( context: Context, destination: Local, l: Local | number, r: Local | number, ) { const tmp = context.locals.symbol('plus_tmp'); if (typeof l === 'number' && typeof r === 'number') { // This would allow constant folding once, since we name it Type.Number // and give no notice it is still a constant. tmp.setType(Type.Number); tmp.setCode(l + r); } else if (typeof l === 'number' || typeof r === 'number') { const ltmp = context.locals.symbol('plus_ltmp', Type.Number); if (typeof l === 'number') { ltmp.setCode(l); plus(context, destination, ltmp, r); } else if (typeof r === 'number') { ltmp.setCode(r); plus(context, destination, l, ltmp); } return; } else if (l.getType() === Type.Number && r.getType() === Type.Number) { tmp.setType(Type.Number); tmp.setCode(`${l.getCode()} + ${r.getCode()}`, true); } else if (l.getType() === Type.V8String || r.getType() === Type.V8String) { // If either is a string, it must be a string. tmp.setType(Type.V8String); tmp.setCode( `stringPlus(isolate, ${l.getCode(Type.V8Value)}, ${r.getCode( Type.V8Value, )})`, ); } else if (l.getType() === Type.V8Number && r.getType() === Type.V8Number) { tmp.setType(Type.Number); tmp.setCode(`${l.getCode(Type.Number)} + ${r.getCode(Type.Number)}`, true); } else { tmp.setType(Type.V8Value); tmp.setCode( `genericPlus(isolate, ${l.getCode(Type.V8Value)}, ${r.getCode( Type.V8Value, )})`, ); } assign(context, destination, tmp, true); } export function times( context: Context, destination: Local, l: Local, r: Local, ) { const tmp = context.locals.symbol('times_tmp', Type.Number); if (l.getType() === Type.Number && r.getType() === Type.Number) { tmp.setCode(`${l.getCode()} * ${r.getCode()}`, true); } else if (l.getType() === Type.V8Number && r.getType() === Type.V8Number) { tmp.setCode(`${l.getCode(Type.Number)} * ${r.getCode(Type.Number)}`, true); } else { tmp.setType(Type.V8Number); tmp.setCode( `genericTimes(isolate, ${l.getCode(Type.V8Value)}, ${r.getCode( Type.V8Value, )})`, ); } assign(context, destination, tmp, true); } export function minus( context: Context, destination: Local, l: Local | number, r: Local | number, ) { const tmp = context.locals.symbol('minus_tmp', Type.Number); if (typeof l === 'number' && typeof r === 'number') { // This would allow constant folding once, since we name it Type.Number // and give no notice it is still a constant. tmp.setType(Type.Number); tmp.setCode(l - r); } else if (typeof l === 'number' || typeof r === 'number') { const ltmp = context.locals.symbol('minus_ltmp', Type.Number); if (typeof l === 'number') { ltmp.setCode(l); minus(context, destination, ltmp, r); } else if (typeof r === 'number') { ltmp.setCode(r); minus(context, destination, l, ltmp); } return; } else if (l.getType() === Type.Number && r.getType() === Type.Number) { tmp.setType(Type.Number); tmp.setCode(`${l.getCode()} - ${r.getCode()}`, true); } else if (l.getType() === Type.V8Number && r.getType() === Type.V8Number) { tmp.setType(Type.Number); tmp.setCode(`${l.getCode(Type.Number)} - ${r.getCode(Type.Number)}`, true); } else { tmp.setType(Type.V8Value); tmp.setCode( `genericMinus(isolate, ${l.getCode(Type.V8Value)}, ${r.getCode( Type.V8Value, )})`, ); } assign(context, destination, tmp, true); } export function and(context: Context, destination: Local, l: Local, r: Local) { const tmp = context.locals.symbol('and_tmp', Type.Number); if (l.getType() === Type.Number && r.getType() === Type.Number) { tmp.setType(Type.Number); tmp.setCode(`${l.getCode()} ? ${r.getCode()} : ${l.getCode()}`, true); } else if (l.getType() === Type.Boolean && r.getType() === Type.Boolean) { tmp.setType(Type.Boolean); tmp.setCode(`${l.getCode()} ? ${r.getCode()} : ${l.getCode()}`, true); } else if (l.getType() === Type.V8Boolean && r.getType() === Type.V8Boolean) { tmp.setType(Type.V8Boolean); tmp.setCode( `${l.getCode(Type.Boolean)} ? (${r.getCode( Type.Boolean, )} ? ${r.getCode()} : ${l.getCode()}) : ${l.getCode()}`, true, ); } else { tmp.setCode( `${l.getCode(Type.Boolean)} ? (${r.getCode( Type.Boolean, )} ? ${r.getCode()} : ${l.getCode()}) : ${l.getCode()}`, true, ); } assign(context, destination, tmp, true); } export function strictEquals( context: Context, destination: Local, l: Local, r: Local, ) { const tmp = context.locals.symbol('seq_tmp', Type.Boolean); if ( !isV8Type(l.getType()) && !isV8Type(r.getType()) && l.getType() !== r.getType() ) { tmp.setCode(false); } else if (l.getType() === Type.Number && r.getType() === Type.Number) { tmp.setCode(`${l.getCode()} == ${r.getCode()}`, true); } else if (l.getType() === Type.Boolean && r.getType() === Type.Boolean) { tmp.setCode(`${l.getCode()} == ${r.getCode()}`, true); } else if (l.getType() === Type.V8Number && r.getType() === Type.V8Number) { tmp.setCode(`${l.getCode(Type.Number)} == ${r.getCode(Type.Number)}`, true); } else { tmp.setCode( `${l.getCode(Type.V8Value)}->StrictEquals(${r.getCode(Type.V8Value)})`, ); } assign(context, destination, tmp, true); } export function strictNotEquals( context: Context, destination: Local, l: Local, r: Local, ) { const tmp = context.locals.symbol('sneq_tmp', Type.Boolean); if ( !isV8Type(l.getType()) && !isV8Type(r.getType()) && l.getType() !== r.getType() ) { tmp.setCode(true); } else if (l.getType() === Type.Number && r.getType() === Type.Number) { tmp.setCode(`${l.getCode()} != ${r.getCode()}`, true); } else if (l.getType() === Type.Boolean && r.getType() === Type.Boolean) { tmp.setCode(`${l.getCode()} != ${r.getCode()}`, true); } else if (l.getType() === Type.V8Number && r.getType() === Type.V8Number) { tmp.setCode(`${l.getCode(Type.Number)} != ${r.getCode(Type.Number)}`, true); } else { tmp.setCode( `!${l.getCode(Type.V8Value)}->StrictEquals(${r.getCode(Type.V8Value)})`, ); } assign(context, destination, tmp, true); } export function equals( context: Context, destination: Local, l: Local, r: Local, ) { const tmp = context.locals.symbol('eq_tmp', Type.Boolean); if (l.getType() === Type.Number && r.getType() === Type.Number) { tmp.setCode(`${l.getCode()} == ${r.getCode()}`, true); } else if (l.getType() === Type.Boolean && r.getType() === Type.Boolean) { tmp.setCode(`${l.getCode()} == ${r.getCode()}`, true); } else if (l.getType() === Type.V8Number && r.getType() === Type.V8Number) { tmp.setCode(`${l.getCode(Type.Number)} == ${r.getCode(Type.Number)}`, true); } else { tmp.setCode( `${l.getCode(Type.V8Value)}->Equals(${r.getCode(Type.V8Value)})`, ); } assign(context, destination, tmp, true); } export function notEquals( context: Context, destination: Local, l: Local, r: Local, ) { const tmp = context.locals.symbol('neq_tmp', Type.Boolean); if (l.getType() === Type.Number && r.getType() === Type.Number) { tmp.setCode(`${l.getCode()} != ${r.getCode()}`, true); } else if (l.getType() === Type.Boolean && r.getType() === Type.Boolean) { tmp.setCode(`${l.getCode()} != ${r.getCode()}`, true); } else if (l.getType() === Type.V8Number && r.getType() === Type.V8Number) { tmp.setCode(`${l.getCode(Type.Number)} != ${r.getCode(Type.Number)}`, true); } else { tmp.setCode( `!${l.getCode(Type.V8Value)}->Equals(${r.getCode(Type.V8Value)})`, ); } assign(context, destination, tmp, true); } export function greaterThan( context: Context, destination: Local, l: Local, r: Local, ) { const tmp = context.locals.symbol('gt_tmp', Type.Boolean); if (l.getType() === Type.Number && r.getType() === Type.Number) { tmp.setCode(`${l.getCode()} > ${r.getCode()}`, true); } else { tmp.setCode(`${l.getCode(Type.Number)} > ${r.getCode(Type.Number)}`, true); } assign(context, destination, tmp, true); } export function greaterThanEquals( context: Context, destination: Local, l: Local, r: Local, ) { const tmp = context.locals.symbol('gte_tmp', Type.Boolean); if (l.getType() === Type.Number && r.getType() === Type.Number) { tmp.setCode(`${l.getCode()} >= ${r.getCode()}`, true); } else { tmp.setCode(`${l.getCode(Type.Number)} >= ${r.getCode(Type.Number)}`, true); } assign(context, destination, tmp); } export function lessThan( context: Context, destination: Local, l: Local, r: Local, ) { const tmp = context.locals.symbol('lt_tmp', Type.Boolean); if (l.getType() === Type.Number && r.getType() === Type.Number) { tmp.setCode(`${l.getCode()} < ${r.getCode()}`, true); } else { tmp.setCode(`${l.getCode(Type.Number)} < ${r.getCode(Type.Number)}`, true); } assign(context, destination, tmp); } export function lessThanEquals( context: Context, destination: Local, l: Local, r: Local, ) { const tmp = context.locals.symbol('lte_tmp', Type.Boolean); if (l.getType() === Type.Number && r.getType() === Type.Number) { tmp.setCode(`${l.getCode()} <= ${r.getCode()}`, true); } else { tmp.setCode(`${l.getCode(Type.Number)} <= ${r.getCode(Type.Number)}`, true); } assign(context, destination, tmp); }
the_stack
// IMPORTANT // This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator // Generated from: https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Calendar API v3 */ function load(name: "calendar", version: "v3"): PromiseLike<void>; function load(name: "calendar", version: "v3", callback: () => any): void; const acl: calendar.AclResource; const calendarList: calendar.CalendarListResource; const calendars: calendar.CalendarsResource; const channels: calendar.ChannelsResource; const colors: calendar.ColorsResource; const events: calendar.EventsResource; const freebusy: calendar.FreebusyResource; const settings: calendar.SettingsResource; namespace calendar { interface Acl { /** ETag of the collection. */ etag?: string; /** List of rules on the access control list. */ items?: AclRule[]; /** Type of the collection ("calendar#acl"). */ kind?: string; /** Token used to access the next page of this result. Omitted if no further results are available, in which case nextSyncToken is provided. */ nextPageToken?: string; /** * Token used at a later point in time to retrieve only the entries that have changed since this result was returned. Omitted if further results are * available, in which case nextPageToken is provided. */ nextSyncToken?: string; } interface AclRule { /** ETag of the resource. */ etag?: string; /** Identifier of the ACL rule. */ id?: string; /** Type of the resource ("calendar#aclRule"). */ kind?: string; /** * The role assigned to the scope. Possible values are: * - "none" - Provides no access. * - "freeBusyReader" - Provides read access to free/busy information. * - "reader" - Provides read access to the calendar. Private events will appear to users with reader access, but event details will be hidden. * - "writer" - Provides read and write access to the calendar. Private events will appear to users with writer access, and event details will be visible. * * - "owner" - Provides ownership of the calendar. This role has all of the permissions of the writer role with the additional ability to see and * manipulate ACLs. */ role?: string; /** The scope of the rule. */ scope?: { /** * The type of the scope. Possible values are: * - "default" - The public scope. This is the default value. * - "user" - Limits the scope to a single user. * - "group" - Limits the scope to a group. * - "domain" - Limits the scope to a domain. Note: The permissions granted to the "default", or public, scope apply to any user, authenticated or not. */ type?: string; /** The email address of a user or group, or the name of a domain, depending on the scope type. Omitted for type "default". */ value?: string; }; } interface Calendar { /** Description of the calendar. Optional. */ description?: string; /** ETag of the resource. */ etag?: string; /** Identifier of the calendar. To retrieve IDs call the calendarList.list() method. */ id?: string; /** Type of the resource ("calendar#calendar"). */ kind?: string; /** Geographic location of the calendar as free-form text. Optional. */ location?: string; /** Title of the calendar. */ summary?: string; /** The time zone of the calendar. (Formatted as an IANA Time Zone Database name, e.g. "Europe/Zurich".) Optional. */ timeZone?: string; } interface CalendarList { /** ETag of the collection. */ etag?: string; /** Calendars that are present on the user's calendar list. */ items?: CalendarListEntry[]; /** Type of the collection ("calendar#calendarList"). */ kind?: string; /** Token used to access the next page of this result. Omitted if no further results are available, in which case nextSyncToken is provided. */ nextPageToken?: string; /** * Token used at a later point in time to retrieve only the entries that have changed since this result was returned. Omitted if further results are * available, in which case nextPageToken is provided. */ nextSyncToken?: string; } interface CalendarListEntry { /** * The effective access role that the authenticated user has on the calendar. Read-only. Possible values are: * - "freeBusyReader" - Provides read access to free/busy information. * - "reader" - Provides read access to the calendar. Private events will appear to users with reader access, but event details will be hidden. * - "writer" - Provides read and write access to the calendar. Private events will appear to users with writer access, and event details will be visible. * * - "owner" - Provides ownership of the calendar. This role has all of the permissions of the writer role with the additional ability to see and * manipulate ACLs. */ accessRole?: string; /** * The main color of the calendar in the hexadecimal format "#0088aa". This property supersedes the index-based colorId property. To set or change this * property, you need to specify colorRgbFormat=true in the parameters of the insert, update and patch methods. Optional. */ backgroundColor?: string; /** * The color of the calendar. This is an ID referring to an entry in the calendar section of the colors definition (see the colors endpoint). This * property is superseded by the backgroundColor and foregroundColor properties and can be ignored when using these properties. Optional. */ colorId?: string; /** The default reminders that the authenticated user has for this calendar. */ defaultReminders?: EventReminder[]; /** Whether this calendar list entry has been deleted from the calendar list. Read-only. Optional. The default is False. */ deleted?: boolean; /** Description of the calendar. Optional. Read-only. */ description?: string; /** ETag of the resource. */ etag?: string; /** * The foreground color of the calendar in the hexadecimal format "#ffffff". This property supersedes the index-based colorId property. To set or change * this property, you need to specify colorRgbFormat=true in the parameters of the insert, update and patch methods. Optional. */ foregroundColor?: string; /** Whether the calendar has been hidden from the list. Optional. The default is False. */ hidden?: boolean; /** Identifier of the calendar. */ id?: string; /** Type of the resource ("calendar#calendarListEntry"). */ kind?: string; /** Geographic location of the calendar as free-form text. Optional. Read-only. */ location?: string; /** The notifications that the authenticated user is receiving for this calendar. */ notificationSettings?: { /** The list of notifications set for this calendar. */ notifications?: CalendarNotification[]; }; /** Whether the calendar is the primary calendar of the authenticated user. Read-only. Optional. The default is False. */ primary?: boolean; /** Whether the calendar content shows up in the calendar UI. Optional. The default is False. */ selected?: boolean; /** Title of the calendar. Read-only. */ summary?: string; /** The summary that the authenticated user has set for this calendar. Optional. */ summaryOverride?: string; /** The time zone of the calendar. Optional. Read-only. */ timeZone?: string; } interface CalendarNotification { /** * The method used to deliver the notification. Possible values are: * - "email" - Reminders are sent via email. * - "sms" - Reminders are sent via SMS. This value is read-only and is ignored on inserts and updates. SMS reminders are only available for G Suite * customers. */ method?: string; /** * The type of notification. Possible values are: * - "eventCreation" - Notification sent when a new event is put on the calendar. * - "eventChange" - Notification sent when an event is changed. * - "eventCancellation" - Notification sent when an event is cancelled. * - "eventResponse" - Notification sent when an event is changed. * - "agenda" - An agenda with the events of the day (sent out in the morning). */ type?: string; } interface Channel { /** The address where notifications are delivered for this channel. */ address?: string; /** Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional. */ expiration?: string; /** A UUID or similar unique string that identifies this channel. */ id?: string; /** Identifies this as a notification channel used to watch for changes to a resource. Value: the fixed string "api#channel". */ kind?: string; /** Additional parameters controlling delivery channel behavior. Optional. */ params?: Record<string, string>; /** A Boolean value to indicate whether payload is wanted. Optional. */ payload?: boolean; /** An opaque ID that identifies the resource being watched on this channel. Stable across different API versions. */ resourceId?: string; /** A version-specific identifier for the watched resource. */ resourceUri?: string; /** An arbitrary string delivered to the target address with each notification delivered over this channel. Optional. */ token?: string; /** The type of delivery mechanism used for this channel. */ type?: string; } interface ColorDefinition { /** The background color associated with this color definition. */ background?: string; /** The foreground color that can be used to write on top of a background with 'background' color. */ foreground?: string; } interface Colors { /** * A global palette of calendar colors, mapping from the color ID to its definition. A calendarListEntry resource refers to one of these color IDs in its * color field. Read-only. */ calendar?: Record<string, ColorDefinition>; /** * A global palette of event colors, mapping from the color ID to its definition. An event resource may refer to one of these color IDs in its color * field. Read-only. */ event?: Record<string, ColorDefinition>; /** Type of the resource ("calendar#colors"). */ kind?: string; /** Last modification time of the color palette (as a RFC3339 timestamp). Read-only. */ updated?: string; } interface Error { /** Domain, or broad category, of the error. */ domain?: string; /** * Specific reason for the error. Some of the possible values are: * - "groupTooBig" - The group of users requested is too large for a single query. * - "tooManyCalendarsRequested" - The number of calendars requested is too large for a single query. * - "notFound" - The requested resource was not found. * - "internalError" - The API service has encountered an internal error. Additional error types may be added in the future, so clients should gracefully * handle additional error statuses not included in this list. */ reason?: string; } interface Event { /** Whether anyone can invite themselves to the event (currently works for Google+ events only). Optional. The default is False. */ anyoneCanAddSelf?: boolean; /** * File attachments for the event. Currently only Google Drive attachments are supported. * In order to modify attachments the supportsAttachments request parameter should be set to true. * There can be at most 25 attachments per event, */ attachments?: EventAttachment[]; /** The attendees of the event. See the Events with attendees guide for more information on scheduling events with other calendar users. */ attendees?: EventAttendee[]; /** * Whether attendees may have been omitted from the event's representation. When retrieving an event, this may be due to a restriction specified by the * maxAttendee query parameter. When updating an event, this can be used to only update the participant's response. Optional. The default is False. */ attendeesOmitted?: boolean; /** The color of the event. This is an ID referring to an entry in the event section of the colors definition (see the colors endpoint). Optional. */ colorId?: string; /** Creation time of the event (as a RFC3339 timestamp). Read-only. */ created?: string; /** The creator of the event. Read-only. */ creator?: { /** The creator's name, if available. */ displayName?: string; /** The creator's email address, if available. */ email?: string; /** The creator's Profile ID, if available. It corresponds to theid field in the People collection of the Google+ API */ id?: string; /** Whether the creator corresponds to the calendar on which this copy of the event appears. Read-only. The default is False. */ self?: boolean; }; /** Description of the event. Optional. */ description?: string; /** The (exclusive) end time of the event. For a recurring event, this is the end time of the first instance. */ end?: EventDateTime; /** * Whether the end time is actually unspecified. An end time is still provided for compatibility reasons, even if this attribute is set to True. The * default is False. */ endTimeUnspecified?: boolean; /** ETag of the resource. */ etag?: string; /** Extended properties of the event. */ extendedProperties?: { /** Properties that are private to the copy of the event that appears on this calendar. */ private?: Record<string, string>; /** Properties that are shared between copies of the event on other attendees' calendars. */ shared?: Record<string, string>; }; /** A gadget that extends this event. */ gadget?: { /** * The gadget's display mode. Optional. Possible values are: * - "icon" - The gadget displays next to the event's title in the calendar view. * - "chip" - The gadget displays when the event is clicked. */ display?: string; /** The gadget's height in pixels. The height must be an integer greater than 0. Optional. */ height?: number; /** The gadget's icon URL. The URL scheme must be HTTPS. */ iconLink?: string; /** The gadget's URL. The URL scheme must be HTTPS. */ link?: string; /** Preferences. */ preferences?: Record<string, string>; /** The gadget's title. */ title?: string; /** The gadget's type. */ type?: string; /** The gadget's width in pixels. The width must be an integer greater than 0. Optional. */ width?: number; }; /** Whether attendees other than the organizer can invite others to the event. Optional. The default is True. */ guestsCanInviteOthers?: boolean; /** Whether attendees other than the organizer can modify the event. Optional. The default is False. */ guestsCanModify?: boolean; /** Whether attendees other than the organizer can see who the event's attendees are. Optional. The default is True. */ guestsCanSeeOtherGuests?: boolean; /** An absolute link to the Google+ hangout associated with this event. Read-only. */ hangoutLink?: string; /** An absolute link to this event in the Google Calendar Web UI. Read-only. */ htmlLink?: string; /** * Event unique identifier as defined in RFC5545. It is used to uniquely identify events accross calendaring systems and must be supplied when importing * events via the import method. * Note that the icalUID and the id are not identical and only one of them should be supplied at event creation time. One difference in their semantics is * that in recurring events, all occurrences of one event have different ids while they all share the same icalUIDs. */ iCalUID?: string; /** * Opaque identifier of the event. When creating new single or recurring events, you can specify their IDs. Provided IDs must follow these rules: * - characters allowed in the ID are those used in base32hex encoding, i.e. lowercase letters a-v and digits 0-9, see section 3.1.2 in RFC2938 * - the length of the ID must be between 5 and 1024 characters * - the ID must be unique per calendar Due to the globally distributed nature of the system, we cannot guarantee that ID collisions will be detected at * event creation time. To minimize the risk of collisions we recommend using an established UUID algorithm such as one described in RFC4122. * If you do not specify an ID, it will be automatically generated by the server. * Note that the icalUID and the id are not identical and only one of them should be supplied at event creation time. One difference in their semantics is * that in recurring events, all occurrences of one event have different ids while they all share the same icalUIDs. */ id?: string; /** Type of the resource ("calendar#event"). */ kind?: string; /** Geographic location of the event as free-form text. Optional. */ location?: string; /** * Whether this is a locked event copy where no changes can be made to the main event fields "summary", "description", "location", "start", "end" or * "recurrence". The default is False. Read-Only. */ locked?: boolean; /** * The organizer of the event. If the organizer is also an attendee, this is indicated with a separate entry in attendees with the organizer field set to * True. To change the organizer, use the move operation. Read-only, except when importing an event. */ organizer?: { /** The organizer's name, if available. */ displayName?: string; /** The organizer's email address, if available. It must be a valid email address as per RFC5322. */ email?: string; /** The organizer's Profile ID, if available. It corresponds to theid field in the People collection of the Google+ API */ id?: string; /** Whether the organizer corresponds to the calendar on which this copy of the event appears. Read-only. The default is False. */ self?: boolean; }; /** * For an instance of a recurring event, this is the time at which this event would start according to the recurrence data in the recurring event * identified by recurringEventId. Immutable. */ originalStartTime?: EventDateTime; /** Whether this is a private event copy where changes are not shared with other copies on other calendars. Optional. Immutable. The default is False. */ privateCopy?: boolean; /** * List of RRULE, EXRULE, RDATE and EXDATE lines for a recurring event, as specified in RFC5545. Note that DTSTART and DTEND lines are not allowed in this * field; event start and end times are specified in the start and end fields. This field is omitted for single events or instances of recurring events. */ recurrence?: string[]; /** For an instance of a recurring event, this is the id of the recurring event to which this instance belongs. Immutable. */ recurringEventId?: string; /** Information about the event's reminders for the authenticated user. */ reminders?: { /** * If the event doesn't use the default reminders, this lists the reminders specific to the event, or, if not set, indicates that no reminders are set for * this event. The maximum number of override reminders is 5. */ overrides?: EventReminder[]; /** Whether the default reminders of the calendar apply to the event. */ useDefault?: boolean; }; /** Sequence number as per iCalendar. */ sequence?: number; /** * Source from which the event was created. For example, a web page, an email message or any document identifiable by an URL with HTTP or HTTPS scheme. * Can only be seen or modified by the creator of the event. */ source?: { /** Title of the source; for example a title of a web page or an email subject. */ title?: string; /** URL of the source pointing to a resource. The URL scheme must be HTTP or HTTPS. */ url?: string; }; /** The (inclusive) start time of the event. For a recurring event, this is the start time of the first instance. */ start?: EventDateTime; /** * Status of the event. Optional. Possible values are: * - "confirmed" - The event is confirmed. This is the default status. * - "tentative" - The event is tentatively confirmed. * - "cancelled" - The event is cancelled. */ status?: string; /** Title of the event. */ summary?: string; /** * Whether the event blocks time on the calendar. Optional. Possible values are: * - "opaque" - Default value. The event does block time on the calendar. This is equivalent to setting Show me as to Busy in the Calendar UI. * - "transparent" - The event does not block time on the calendar. This is equivalent to setting Show me as to Available in the Calendar UI. */ transparency?: string; /** Last modification time of the event (as a RFC3339 timestamp). Read-only. */ updated?: string; /** * Visibility of the event. Optional. Possible values are: * - "default" - Uses the default visibility for events on the calendar. This is the default value. * - "public" - The event is public and event details are visible to all readers of the calendar. * - "private" - The event is private and only event attendees may view event details. * - "confidential" - The event is private. This value is provided for compatibility reasons. */ visibility?: string; } interface EventAttachment { /** * ID of the attached file. Read-only. * For Google Drive files, this is the ID of the corresponding Files resource entry in the Drive API. */ fileId?: string; /** * URL link to the attachment. * For adding Google Drive file attachments use the same format as in alternateLink property of the Files resource in the Drive API. */ fileUrl?: string; /** URL link to the attachment's icon. Read-only. */ iconLink?: string; /** Internet media type (MIME type) of the attachment. */ mimeType?: string; /** Attachment title. */ title?: string; } interface EventAttendee { /** Number of additional guests. Optional. The default is 0. */ additionalGuests?: number; /** The attendee's response comment. Optional. */ comment?: string; /** The attendee's name, if available. Optional. */ displayName?: string; /** The attendee's email address, if available. This field must be present when adding an attendee. It must be a valid email address as per RFC5322. */ email?: string; /** The attendee's Profile ID, if available. It corresponds to theid field in the People collection of the Google+ API */ id?: string; /** Whether this is an optional attendee. Optional. The default is False. */ optional?: boolean; /** Whether the attendee is the organizer of the event. Read-only. The default is False. */ organizer?: boolean; /** Whether the attendee is a resource. Read-only. The default is False. */ resource?: boolean; /** * The attendee's response status. Possible values are: * - "needsAction" - The attendee has not responded to the invitation. * - "declined" - The attendee has declined the invitation. * - "tentative" - The attendee has tentatively accepted the invitation. * - "accepted" - The attendee has accepted the invitation. */ responseStatus?: string; /** Whether this entry represents the calendar on which this copy of the event appears. Read-only. The default is False. */ self?: boolean; } interface EventDateTime { /** The date, in the format "yyyy-mm-dd", if this is an all-day event. */ date?: string; /** * The time, as a combined date-time value (formatted according to RFC3339). A time zone offset is required unless a time zone is explicitly specified in * timeZone. */ dateTime?: string; /** * The time zone in which the time is specified. (Formatted as an IANA Time Zone Database name, e.g. "Europe/Zurich".) For recurring events this field is * required and specifies the time zone in which the recurrence is expanded. For single events this field is optional and indicates a custom time zone for * the event start/end. */ timeZone?: string; } interface EventReminder { /** * The method used by this reminder. Possible values are: * - "email" - Reminders are sent via email. * - "sms" - Reminders are sent via SMS. These are only available for G Suite customers. Requests to set SMS reminders for other account types are * ignored. * - "popup" - Reminders are sent via a UI popup. */ method?: string; /** Number of minutes before the start of the event when the reminder should trigger. Valid values are between 0 and 40320 (4 weeks in minutes). */ minutes?: number; } interface Events { /** * The user's access role for this calendar. Read-only. Possible values are: * - "none" - The user has no access. * - "freeBusyReader" - The user has read access to free/busy information. * - "reader" - The user has read access to the calendar. Private events will appear to users with reader access, but event details will be hidden. * - "writer" - The user has read and write access to the calendar. Private events will appear to users with writer access, and event details will be * visible. * - "owner" - The user has ownership of the calendar. This role has all of the permissions of the writer role with the additional ability to see and * manipulate ACLs. */ accessRole?: string; /** * The default reminders on the calendar for the authenticated user. These reminders apply to all events on this calendar that do not explicitly override * them (i.e. do not have reminders.useDefault set to True). */ defaultReminders?: EventReminder[]; /** Description of the calendar. Read-only. */ description?: string; /** ETag of the collection. */ etag?: string; /** List of events on the calendar. */ items?: Event[]; /** Type of the collection ("calendar#events"). */ kind?: string; /** Token used to access the next page of this result. Omitted if no further results are available, in which case nextSyncToken is provided. */ nextPageToken?: string; /** * Token used at a later point in time to retrieve only the entries that have changed since this result was returned. Omitted if further results are * available, in which case nextPageToken is provided. */ nextSyncToken?: string; /** Title of the calendar. Read-only. */ summary?: string; /** The time zone of the calendar. Read-only. */ timeZone?: string; /** Last modification time of the calendar (as a RFC3339 timestamp). Read-only. */ updated?: string; } interface FreeBusyCalendar { /** List of time ranges during which this calendar should be regarded as busy. */ busy?: TimePeriod[]; /** Optional error(s) (if computation for the calendar failed). */ errors?: Error[]; } interface FreeBusyGroup { /** List of calendars' identifiers within a group. */ calendars?: string[]; /** Optional error(s) (if computation for the group failed). */ errors?: Error[]; } interface FreeBusyRequest { /** Maximal number of calendars for which FreeBusy information is to be provided. Optional. */ calendarExpansionMax?: number; /** * Maximal number of calendar identifiers to be provided for a single group. Optional. An error will be returned for a group with more members than this * value. */ groupExpansionMax?: number; /** List of calendars and/or groups to query. */ items?: FreeBusyRequestItem[]; /** The end of the interval for the query. */ timeMax?: string; /** The start of the interval for the query. */ timeMin?: string; /** Time zone used in the response. Optional. The default is UTC. */ timeZone?: string; } interface FreeBusyRequestItem { /** The identifier of a calendar or a group. */ id?: string; } interface FreeBusyResponse { /** List of free/busy information for calendars. */ calendars?: Record<string, FreeBusyCalendar>; /** Expansion of groups. */ groups?: Record<string, FreeBusyGroup>; /** Type of the resource ("calendar#freeBusy"). */ kind?: string; /** The end of the interval. */ timeMax?: string; /** The start of the interval. */ timeMin?: string; } interface Setting { /** ETag of the resource. */ etag?: string; /** The id of the user setting. */ id?: string; /** Type of the resource ("calendar#setting"). */ kind?: string; /** Value of the user setting. The format of the value depends on the ID of the setting. It must always be a UTF-8 string of length up to 1024 characters. */ value?: string; } interface Settings { /** Etag of the collection. */ etag?: string; /** List of user settings. */ items?: Setting[]; /** Type of the collection ("calendar#settings"). */ kind?: string; /** Token used to access the next page of this result. Omitted if no further results are available, in which case nextSyncToken is provided. */ nextPageToken?: string; /** * Token used at a later point in time to retrieve only the entries that have changed since this result was returned. Omitted if further results are * available, in which case nextPageToken is provided. */ nextSyncToken?: string; } interface TimePeriod { /** The (exclusive) end of the time period. */ end?: string; /** The (inclusive) start of the time period. */ start?: string; } interface AclResource { /** Deletes an access control rule. */ delete(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** ACL rule identifier. */ ruleId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Returns an access control rule. */ get(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** ACL rule identifier. */ ruleId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<AclRule>; /** Creates an access control rule. */ insert(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<AclRule>; /** Returns the rules in the access control list for the calendar. */ list(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: 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; /** * Maximum number of entries returned on one result page. By default the value is 100 entries. The page size can never be larger than 250 entries. * Optional. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Token specifying which result page to return. Optional. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** * Whether to include deleted ACLs in the result. Deleted ACLs are represented by role equal to "none". Deleted ACLs will always be included if syncToken * is provided. Optional. The default is False. */ showDeleted?: boolean; /** * Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list * request contain only entries that have changed since then. All entries deleted since the previous list request will always be in the result set and it * is not allowed to set showDeleted to False. * If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full * synchronization without any syncToken. * Learn more about incremental synchronization. * Optional. The default is to return all entries. */ syncToken?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Acl>; /** Updates an access control rule. This method supports patch semantics. */ patch(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** ACL rule identifier. */ ruleId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<AclRule>; /** Updates an access control rule. */ update(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** ACL rule identifier. */ ruleId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<AclRule>; /** Watch for changes to ACL resources. */ watch(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: 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; /** * Maximum number of entries returned on one result page. By default the value is 100 entries. The page size can never be larger than 250 entries. * Optional. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Token specifying which result page to return. Optional. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** * Whether to include deleted ACLs in the result. Deleted ACLs are represented by role equal to "none". Deleted ACLs will always be included if syncToken * is provided. Optional. The default is False. */ showDeleted?: boolean; /** * Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list * request contain only entries that have changed since then. All entries deleted since the previous list request will always be in the result set and it * is not allowed to set showDeleted to False. * If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full * synchronization without any syncToken. * Learn more about incremental synchronization. * Optional. The default is to return all entries. */ syncToken?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Channel>; } interface CalendarListResource { /** Deletes an entry on the user's calendar list. */ delete(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Returns an entry on the user's calendar list. */ get(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<CalendarListEntry>; /** Adds an entry to the user's calendar list. */ insert(request: { /** Data format for the response. */ alt?: string; /** * Whether to use the foregroundColor and backgroundColor fields to write the calendar colors (RGB). If this feature is used, the index-based colorId * field will be set to the best matching option automatically. Optional. The default is False. */ colorRgbFormat?: boolean; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<CalendarListEntry>; /** Returns entries on the user's calendar list. */ list(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * Maximum number of entries returned on one result page. By default the value is 100 entries. The page size can never be larger than 250 entries. * Optional. */ maxResults?: number; /** The minimum access role for the user in the returned entries. Optional. The default is no restriction. */ minAccessRole?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Token specifying which result page to return. Optional. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether to include deleted calendar list entries in the result. Optional. The default is False. */ showDeleted?: boolean; /** Whether to show hidden entries. Optional. The default is False. */ showHidden?: boolean; /** * Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list * request contain only entries that have changed since then. If only read-only fields such as calendar properties or ACLs have changed, the entry won't * be returned. All entries deleted and hidden since the previous list request will always be in the result set and it is not allowed to set showDeleted * neither showHidden to False. * To ensure client state consistency minAccessRole query parameter cannot be specified together with nextSyncToken. * If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full * synchronization without any syncToken. * Learn more about incremental synchronization. * Optional. The default is to return all entries. */ syncToken?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<CalendarList>; /** Updates an entry on the user's calendar list. This method supports patch semantics. */ patch(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** * Whether to use the foregroundColor and backgroundColor fields to write the calendar colors (RGB). If this feature is used, the index-based colorId * field will be set to the best matching option automatically. Optional. The default is False. */ colorRgbFormat?: boolean; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<CalendarListEntry>; /** Updates an entry on the user's calendar list. */ update(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** * Whether to use the foregroundColor and backgroundColor fields to write the calendar colors (RGB). If this feature is used, the index-based colorId * field will be set to the best matching option automatically. Optional. The default is False. */ colorRgbFormat?: boolean; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<CalendarListEntry>; /** Watch for changes to CalendarList resources. */ watch(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * Maximum number of entries returned on one result page. By default the value is 100 entries. The page size can never be larger than 250 entries. * Optional. */ maxResults?: number; /** The minimum access role for the user in the returned entries. Optional. The default is no restriction. */ minAccessRole?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Token specifying which result page to return. Optional. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether to include deleted calendar list entries in the result. Optional. The default is False. */ showDeleted?: boolean; /** Whether to show hidden entries. Optional. The default is False. */ showHidden?: boolean; /** * Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list * request contain only entries that have changed since then. If only read-only fields such as calendar properties or ACLs have changed, the entry won't * be returned. All entries deleted and hidden since the previous list request will always be in the result set and it is not allowed to set showDeleted * neither showHidden to False. * To ensure client state consistency minAccessRole query parameter cannot be specified together with nextSyncToken. * If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full * synchronization without any syncToken. * Learn more about incremental synchronization. * Optional. The default is to return all entries. */ syncToken?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Channel>; } interface CalendarsResource { /** Clears a primary calendar. This operation deletes all events associated with the primary calendar of an account. */ clear(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Deletes a secondary calendar. Use calendars.clear for clearing all events on primary calendars. */ delete(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Returns metadata for a calendar. */ get(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Calendar>; /** Creates a secondary calendar. */ insert(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Calendar>; /** Updates metadata for a calendar. This method supports patch semantics. */ patch(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Calendar>; /** Updates metadata for a calendar. */ update(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Calendar>; } interface ChannelsResource { /** Stop watching resources through this channel */ stop(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; } interface ColorsResource { /** Returns the color definitions for calendars and events. */ get(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Colors>; } interface EventsResource { /** Deletes an event. */ delete(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Event identifier. */ eventId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether to send notifications about the deletion of the event. Optional. The default is False. */ sendNotifications?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Returns an event. */ get(request: { /** Data format for the response. */ alt?: string; /** * Whether to always include a value in the email field for the organizer, creator and attendees, even if no real email is available (i.e. a generated, * non-working value will be provided). The use of this option is discouraged and should only be used by clients which cannot handle the absence of an * email address value in the mentioned places. Optional. The default is False. */ alwaysIncludeEmail?: boolean; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Event identifier. */ eventId: 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; /** * The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. * Optional. */ maxAttendees?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Time zone used in the response. Optional. The default is the time zone of the calendar. */ timeZone?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Event>; /** Imports an event. This operation is used to add a private copy of an existing event to a calendar. */ import(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether API client performing operation supports event attachments. Optional. The default is False. */ supportsAttachments?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Event>; /** Creates an event. */ insert(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: 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; /** * The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. * Optional. */ maxAttendees?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether to send notifications about the creation of the new event. Optional. The default is False. */ sendNotifications?: boolean; /** Whether API client performing operation supports event attachments. Optional. The default is False. */ supportsAttachments?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Event>; /** Returns instances of the specified recurring event. */ instances(request: { /** Data format for the response. */ alt?: string; /** * Whether to always include a value in the email field for the organizer, creator and attendees, even if no real email is available (i.e. a generated, * non-working value will be provided). The use of this option is discouraged and should only be used by clients which cannot handle the absence of an * email address value in the mentioned places. Optional. The default is False. */ alwaysIncludeEmail?: boolean; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Recurring event identifier. */ eventId: 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; /** * The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. * Optional. */ maxAttendees?: number; /** Maximum number of events returned on one result page. By default the value is 250 events. The page size can never be larger than 2500 events. Optional. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The original start time of the instance in the result. Optional. */ originalStart?: string; /** Token specifying which result page to return. Optional. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** * Whether to include deleted events (with status equals "cancelled") in the result. Cancelled instances of recurring events will still be included if * singleEvents is False. Optional. The default is False. */ showDeleted?: boolean; /** * Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. Must be an RFC3339 timestamp with * mandatory time zone offset. */ timeMax?: string; /** * Lower bound (inclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. Must be an RFC3339 timestamp with * mandatory time zone offset. */ timeMin?: string; /** Time zone used in the response. Optional. The default is the time zone of the calendar. */ timeZone?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Events>; /** Returns events on the specified calendar. */ list(request: { /** Data format for the response. */ alt?: string; /** * Whether to always include a value in the email field for the organizer, creator and attendees, even if no real email is available (i.e. a generated, * non-working value will be provided). The use of this option is discouraged and should only be used by clients which cannot handle the absence of an * email address value in the mentioned places. Optional. The default is False. */ alwaysIncludeEmail?: boolean; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** Specifies event ID in the iCalendar format to be included in the response. Optional. */ iCalUID?: 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; /** * The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. * Optional. */ maxAttendees?: number; /** * Maximum number of events returned on one result page. The number of events in the resulting page may be less than this value, or none at all, even if * there are more events matching the query. Incomplete pages can be detected by a non-empty nextPageToken field in the response. By default the value is * 250 events. The page size can never be larger than 2500 events. Optional. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The order of the events returned in the result. Optional. The default is an unspecified, stable order. */ orderBy?: string; /** Token specifying which result page to return. Optional. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Extended properties constraint specified as propertyName=value. Matches only private properties. This parameter might be repeated multiple times to * return events that match all given constraints. */ privateExtendedProperty?: string; /** Free text search terms to find events that match these terms in any field, except for extended properties. Optional. */ q?: string; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** * Extended properties constraint specified as propertyName=value. Matches only shared properties. This parameter might be repeated multiple times to * return events that match all given constraints. */ sharedExtendedProperty?: string; /** * Whether to include deleted events (with status equals "cancelled") in the result. Cancelled instances of recurring events (but not the underlying * recurring event) will still be included if showDeleted and singleEvents are both False. If showDeleted and singleEvents are both True, only single * instances of deleted events (but not the underlying recurring events) are returned. Optional. The default is False. */ showDeleted?: boolean; /** Whether to include hidden invitations in the result. Optional. The default is False. */ showHiddenInvitations?: boolean; /** * Whether to expand recurring events into instances and only return single one-off events and instances of recurring events, but not the underlying * recurring events themselves. Optional. The default is False. */ singleEvents?: boolean; /** * Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list * request contain only entries that have changed since then. All events deleted since the previous list request will always be in the result set and it * is not allowed to set showDeleted to False. * There are several query parameters that cannot be specified together with nextSyncToken to ensure consistency of the client state. * * These are: * - iCalUID * - orderBy * - privateExtendedProperty * - q * - sharedExtendedProperty * - timeMin * - timeMax * - updatedMin If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full * synchronization without any syncToken. * Learn more about incremental synchronization. * Optional. The default is to return all entries. */ syncToken?: string; /** * Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. Must be an RFC3339 timestamp with * mandatory time zone offset, e.g., 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z. Milliseconds may be provided but will be ignored. If timeMin is set, * timeMax must be greater than timeMin. */ timeMax?: string; /** * Lower bound (inclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. Must be an RFC3339 timestamp with * mandatory time zone offset, e.g., 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z. Milliseconds may be provided but will be ignored. If timeMax is set, * timeMin must be smaller than timeMax. */ timeMin?: string; /** Time zone used in the response. Optional. The default is the time zone of the calendar. */ timeZone?: string; /** * Lower bound for an event's last modification time (as a RFC3339 timestamp) to filter by. When specified, entries deleted since this time will always be * included regardless of showDeleted. Optional. The default is not to filter by last modification time. */ updatedMin?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Events>; /** Moves an event to another calendar, i.e. changes an event's organizer. */ move(request: { /** Data format for the response. */ alt?: string; /** Calendar identifier of the source calendar where the event currently is on. */ calendarId: string; /** Calendar identifier of the target calendar where the event is to be moved to. */ destination: string; /** Event identifier. */ eventId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether to send notifications about the change of the event's organizer. Optional. The default is False. */ sendNotifications?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Event>; /** Updates an event. This method supports patch semantics. */ patch(request: { /** Data format for the response. */ alt?: string; /** * Whether to always include a value in the email field for the organizer, creator and attendees, even if no real email is available (i.e. a generated, * non-working value will be provided). The use of this option is discouraged and should only be used by clients which cannot handle the absence of an * email address value in the mentioned places. Optional. The default is False. */ alwaysIncludeEmail?: boolean; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Event identifier. */ eventId: 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; /** * The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. * Optional. */ maxAttendees?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether to send notifications about the event update (e.g. attendee's responses, title changes, etc.). Optional. The default is False. */ sendNotifications?: boolean; /** Whether API client performing operation supports event attachments. Optional. The default is False. */ supportsAttachments?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Event>; /** Creates an event based on a simple text string. */ quickAdd(request: { /** Data format for the response. */ alt?: string; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether to send notifications about the creation of the event. Optional. The default is False. */ sendNotifications?: boolean; /** The text describing the event to be created. */ text: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Event>; /** Updates an event. */ update(request: { /** Data format for the response. */ alt?: string; /** * Whether to always include a value in the email field for the organizer, creator and attendees, even if no real email is available (i.e. a generated, * non-working value will be provided). The use of this option is discouraged and should only be used by clients which cannot handle the absence of an * email address value in the mentioned places. Optional. The default is False. */ alwaysIncludeEmail?: boolean; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Event identifier. */ eventId: 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; /** * The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. * Optional. */ maxAttendees?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether to send notifications about the event update (e.g. attendee's responses, title changes, etc.). Optional. The default is False. */ sendNotifications?: boolean; /** Whether API client performing operation supports event attachments. Optional. The default is False. */ supportsAttachments?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Event>; /** Watch for changes to Events resources. */ watch(request: { /** Data format for the response. */ alt?: string; /** * Whether to always include a value in the email field for the organizer, creator and attendees, even if no real email is available (i.e. a generated, * non-working value will be provided). The use of this option is discouraged and should only be used by clients which cannot handle the absence of an * email address value in the mentioned places. Optional. The default is False. */ alwaysIncludeEmail?: boolean; /** * Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in * user, use the "primary" keyword. */ calendarId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** Specifies event ID in the iCalendar format to be included in the response. Optional. */ iCalUID?: 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; /** * The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. * Optional. */ maxAttendees?: number; /** * Maximum number of events returned on one result page. The number of events in the resulting page may be less than this value, or none at all, even if * there are more events matching the query. Incomplete pages can be detected by a non-empty nextPageToken field in the response. By default the value is * 250 events. The page size can never be larger than 2500 events. Optional. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The order of the events returned in the result. Optional. The default is an unspecified, stable order. */ orderBy?: string; /** Token specifying which result page to return. Optional. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Extended properties constraint specified as propertyName=value. Matches only private properties. This parameter might be repeated multiple times to * return events that match all given constraints. */ privateExtendedProperty?: string; /** Free text search terms to find events that match these terms in any field, except for extended properties. Optional. */ q?: string; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** * Extended properties constraint specified as propertyName=value. Matches only shared properties. This parameter might be repeated multiple times to * return events that match all given constraints. */ sharedExtendedProperty?: string; /** * Whether to include deleted events (with status equals "cancelled") in the result. Cancelled instances of recurring events (but not the underlying * recurring event) will still be included if showDeleted and singleEvents are both False. If showDeleted and singleEvents are both True, only single * instances of deleted events (but not the underlying recurring events) are returned. Optional. The default is False. */ showDeleted?: boolean; /** Whether to include hidden invitations in the result. Optional. The default is False. */ showHiddenInvitations?: boolean; /** * Whether to expand recurring events into instances and only return single one-off events and instances of recurring events, but not the underlying * recurring events themselves. Optional. The default is False. */ singleEvents?: boolean; /** * Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list * request contain only entries that have changed since then. All events deleted since the previous list request will always be in the result set and it * is not allowed to set showDeleted to False. * There are several query parameters that cannot be specified together with nextSyncToken to ensure consistency of the client state. * * These are: * - iCalUID * - orderBy * - privateExtendedProperty * - q * - sharedExtendedProperty * - timeMin * - timeMax * - updatedMin If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full * synchronization without any syncToken. * Learn more about incremental synchronization. * Optional. The default is to return all entries. */ syncToken?: string; /** * Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. Must be an RFC3339 timestamp with * mandatory time zone offset, e.g., 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z. Milliseconds may be provided but will be ignored. If timeMin is set, * timeMax must be greater than timeMin. */ timeMax?: string; /** * Lower bound (inclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. Must be an RFC3339 timestamp with * mandatory time zone offset, e.g., 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z. Milliseconds may be provided but will be ignored. If timeMax is set, * timeMin must be smaller than timeMax. */ timeMin?: string; /** Time zone used in the response. Optional. The default is the time zone of the calendar. */ timeZone?: string; /** * Lower bound for an event's last modification time (as a RFC3339 timestamp) to filter by. When specified, entries deleted since this time will always be * included regardless of showDeleted. Optional. The default is not to filter by last modification time. */ updatedMin?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Channel>; } interface FreebusyResource { /** Returns free/busy information for a set of calendars. */ query(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<FreeBusyResponse>; } interface SettingsResource { /** Returns a single user setting. */ get(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The id of the user setting. */ setting: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Setting>; /** Returns all user settings for the authenticated user. */ list(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * Maximum number of entries returned on one result page. By default the value is 100 entries. The page size can never be larger than 250 entries. * Optional. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Token specifying which result page to return. Optional. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** * Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list * request contain only entries that have changed since then. * If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full * synchronization without any syncToken. * Learn more about incremental synchronization. * Optional. The default is to return all entries. */ syncToken?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Settings>; /** Watch for changes to Settings resources. */ watch(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * Maximum number of entries returned on one result page. By default the value is 100 entries. The page size can never be larger than 250 entries. * Optional. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Token specifying which result page to return. Optional. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** * Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list * request contain only entries that have changed since then. * If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full * synchronization without any syncToken. * Learn more about incremental synchronization. * Optional. The default is to return all entries. */ syncToken?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Channel>; } } }
the_stack
import { partition, ProtocolService } from '@airgap/angular-core' import { BeaconRequestOutputMessage, BeaconResponseInputMessage } from '@airgap/beacon-sdk' import { AirGapMarketWallet, IACMessageDefinitionObject, IACMessageType, ICoinProtocol, MainProtocolSymbols, SignedTransaction, TezosSaplingProtocol, RawEthereumTransaction } from '@airgap/coinlib-core' import { NetworkType } from '@airgap/coinlib-core/utils/ProtocolNetwork' import { Component } from '@angular/core' import { ActivatedRoute, Router } from '@angular/router' import { AlertController, LoadingController, Platform, ToastController } from '@ionic/angular' import BigNumber from 'bignumber.js' import { AccountProvider } from 'src/app/services/account/account.provider' import { BrowserService } from 'src/app/services/browser/browser.service' import { DataService, DataServiceKey } from 'src/app/services/data/data.service' import { BeaconService } from '../../services/beacon/beacon.service' import { PushBackendProvider } from '../../services/push-backend/push-backend' import { ErrorCategory, handleErrorSentry } from '../../services/sentry-error-handler/sentry-error-handler' import { WalletStorageKey, WalletStorageService } from '../../services/storage/storage' import { WalletconnectService } from 'src/app/services/walletconnect/walletconnect.service' const SECOND: number = 1000 const TOAST_DURATION: number = SECOND * 3 const TOAST_ERROR_DURATION: number = SECOND * 5 const TIMEOUT_TRANSACTION_QUEUED: number = SECOND * 20 @Component({ selector: 'page-transaction-confirm', templateUrl: 'transaction-confirm.html', styleUrls: ['./transaction-confirm.scss'] }) export class TransactionConfirmPage { public messageDefinitionObjects: IACMessageDefinitionObject[] public txInfos: [string, ICoinProtocol, BeaconRequestOutputMessage | { transaction: RawEthereumTransaction; id: string }][] = [] public protocols: ICoinProtocol[] = [] constructor( private readonly loadingCtrl: LoadingController, private readonly toastCtrl: ToastController, private readonly router: Router, private readonly route: ActivatedRoute, private readonly alertCtrl: AlertController, private readonly platform: Platform, private readonly storageProvider: WalletStorageService, private readonly beaconService: BeaconService, private readonly pushBackendProvider: PushBackendProvider, private readonly browserService: BrowserService, private readonly accountService: AccountProvider, private readonly protocolService: ProtocolService, private readonly dataService: DataService, private readonly walletConnectService: WalletconnectService ) {} public dismiss(): void { this.router.navigateByUrl('/tabs/portfolio').catch(handleErrorSentry(ErrorCategory.NAVIGATION)) } public async ionViewWillEnter() { await this.platform.ready() if (this.route.snapshot.data.special) { const info = this.route.snapshot.data.special this.messageDefinitionObjects = info.messageDefinitionObjects } // TODO: Multi messages // tslint:disable-next-line:no-unnecessary-type-assertion this.messageDefinitionObjects.forEach(async (messageObject) => { const protocol = await this.protocolService.getProtocol(messageObject.protocol) const wallet = this.accountService.walletBySerializerAccountIdentifier( (messageObject.payload as SignedTransaction).accountIdentifier, messageObject.protocol ) const [request, savedProtocol] = await this.beaconService.getVaultRequest() const selectedProtocol = request && savedProtocol && savedProtocol.identifier === protocol.identifier ? savedProtocol : wallet && wallet.protocol ? wallet.protocol : protocol this.txInfos.push([(messageObject.payload as SignedTransaction).transaction, selectedProtocol, request]) this.protocols.push(selectedProtocol) }) } public async broadcastTransaction() { if (this.protocols.length === 1 && this.protocols[0].identifier === MainProtocolSymbols.XTZ_SHIELDED) { // temporary await this.wrapInTezosOperation(this.protocols[0] as TezosSaplingProtocol, this.txInfos[0][0]) return } const loading = await this.loadingCtrl.create({ message: 'Broadcasting...' }) loading.present().catch(handleErrorSentry(ErrorCategory.NAVIGATION)) const interval = setTimeout(async () => { loading.dismiss().catch(handleErrorSentry(ErrorCategory.NAVIGATION)) const toast: HTMLIonToastElement = await this.toastCtrl.create({ duration: TOAST_DURATION, message: 'Transaction queued. It might take some time until your TX shows up!', buttons: [ { text: 'Ok', role: 'cancel' } ], position: 'bottom' }) toast.present().catch(handleErrorSentry(ErrorCategory.IONIC_TOAST)) this.router.navigateByUrl('/tabs/portfolio').catch(handleErrorSentry(ErrorCategory.NAVIGATION)) }, TIMEOUT_TRANSACTION_QUEUED) this.txInfos.forEach(async ([signedTx, protocol, request], index) => { protocol .broadcastTransaction(signedTx) .then(async (txId) => { if (request) { // TODO: Type if (request['transaction']) { this.walletConnectService.approveRequest(request.id, txId) } else { const response = { id: request.id, type: this.beaconService.getResponseByRequestType((request as BeaconRequestOutputMessage).type), transactionHash: txId } as BeaconResponseInputMessage this.beaconService.respond(response, request as any).catch(handleErrorSentry(ErrorCategory.BEACON)) } } if (interval) { clearInterval(interval) } // TODO: Remove once we introduce pending transaction handling // TODO: Multi messages // tslint:disable-next-line:no-unnecessary-type-assertion const signedTxWrapper = this.messageDefinitionObjects[index].payload as SignedTransaction const lastTx: { protocol: string accountIdentifier: string date: number } = { protocol: this.messageDefinitionObjects[index].protocol, accountIdentifier: signedTxWrapper.accountIdentifier, date: new Date().getTime() } this.storageProvider.set(WalletStorageKey.LAST_TX_BROADCAST, lastTx).catch(handleErrorSentry(ErrorCategory.STORAGE)) loading.dismiss().catch(handleErrorSentry(ErrorCategory.NAVIGATION)) this.showTransactionSuccessfulAlert(protocol, txId) // POST TX TO BACKEND // Only send it if we are on mainnet if (protocol.options.network.type === NetworkType.MAINNET) { const signed = ( await protocol.getTransactionDetailsFromSigned(this.messageDefinitionObjects[index].payload as SignedTransaction) )[0] as any // necessary for the transaction backend signed.amount = signed.amount.toString() signed.fee = signed.fee.toString() signed.signedTx = signedTx signed.hash = txId this.pushBackendProvider.postPendingTx(signed) // Don't await } // END POST TX TO BACKEND }) .catch((error) => { if (interval) { clearInterval(interval) } handleErrorSentry(ErrorCategory.COINLIB)(error) loading.dismiss().catch(handleErrorSentry(ErrorCategory.NAVIGATION)) // TODO: Remove this special error case once we remove web3 from the coin-lib if (error && error.message && error.message.startsWith('Failed to check for transaction receipt')) { ;(protocol.getTransactionDetailsFromSigned(this.messageDefinitionObjects[index].payload as SignedTransaction) as any).then( (signed) => { if (signed.hash) { this.showTransactionSuccessfulAlert(protocol, signed.hash) // POST TX TO BACKEND // necessary for the transaction backend signed.amount = signed.amount.toString() signed.fee = signed.fee.toString() signed.signedTx = signedTx this.pushBackendProvider.postPendingTx(signed) // Don't await // END POST TX TO BACKEND } else { handleErrorSentry(ErrorCategory.COINLIB)('No transaction hash present in signed ETH transaction') } } ) } else { this.toastCtrl .create({ duration: TOAST_ERROR_DURATION, message: 'Transaction broadcasting failed: ' + error, buttons: [ { text: 'Ok', role: 'cancel' } ], position: 'bottom' }) .then((toast) => { toast.present().catch(handleErrorSentry(ErrorCategory.NAVIGATION)) }) .catch(handleErrorSentry(ErrorCategory.IONIC_TOAST)) } this.router.navigateByUrl('/tabs/portfolio').catch(handleErrorSentry(ErrorCategory.NAVIGATION)) }) }) } private async showTransactionSuccessfulAlert(protocol: ICoinProtocol, transactionHash: string): Promise<void> { const blockexplorer: string = await protocol.getBlockExplorerLinkForTxId(transactionHash) this.alertCtrl .create({ header: 'Transaction broadcasted!', message: 'Your transaction has been successfully broadcasted', buttons: [ { text: 'Open Blockexplorer', handler: (): void => { this.browserService.openUrl(blockexplorer) this.router.navigateByUrl('/tabs/portfolio').catch(handleErrorSentry(ErrorCategory.NAVIGATION)) } }, { text: 'Ok', handler: (): void => { this.router.navigateByUrl('/tabs/portfolio').catch(handleErrorSentry(ErrorCategory.NAVIGATION)) } } ] }) .then((alert: HTMLIonAlertElement) => { alert.present().catch(handleErrorSentry(ErrorCategory.NAVIGATION)) }) .catch(handleErrorSentry(ErrorCategory.IONIC_ALERT)) } private async wrapInTezosOperation(protocol: TezosSaplingProtocol, transaction: string): Promise<void> { const wallet = await this.selectTezosTzAccount(protocol) const unsignedTx = await protocol.wrapSaplingTransactions( wallet.publicKey, transaction, new BigNumber(wallet.protocol.feeDefaults.medium).shiftedBy(wallet.protocol.feeDecimals).toString(), true ) const airGapTxs = await protocol.getTransactionDetails( { publicKey: wallet.publicKey, transaction: unsignedTx }, { knownViewingKeys: this.accountService.getKnownViewingKeys() } ) this.accountService.startInteraction(wallet, unsignedTx, IACMessageType.TransactionSignRequest, airGapTxs) } private async selectTezosTzAccount(protocol: ICoinProtocol): Promise<AirGapMarketWallet> { return new Promise<AirGapMarketWallet>((resolve) => { const wallets: AirGapMarketWallet[] = this.accountService.getWalletList() const [compatibleWallets, incompatibleWallets]: [AirGapMarketWallet[], AirGapMarketWallet[]] = partition<AirGapMarketWallet>( wallets, (wallet: AirGapMarketWallet) => wallet.protocol.identifier === MainProtocolSymbols.XTZ ) const info = { actionType: 'broadcast', targetIdentifier: protocol.identifier, compatibleWallets, incompatibleWallets, callback: resolve } this.dataService.setData(DataServiceKey.ACCOUNTS, info) this.router.navigateByUrl(`/select-wallet/${DataServiceKey.ACCOUNTS}`).catch(handleErrorSentry(ErrorCategory.NAVIGATION)) }) } }
the_stack
export const description = ` - Test pipeline outputs with different color target formats. `; import { makeTestGroup } from '../../../../common/framework/test_group.js'; import { unreachable } from '../../../../common/util/util.js'; import { kRenderableColorTextureFormats, kTextureFormatInfo } from '../../../capability_info.js'; import { GPUTest } from '../../../gpu_test.js'; import { kTexelRepresentationInfo } from '../../../util/texture/texel_data.js'; class F extends GPUTest { getFragmentShaderCode( output: readonly number[], sampleType: GPUTextureSampleType, componentCount: number ): string { let fragColorType; let suffix; let fractionDigits = 0; switch (sampleType) { case 'sint': fragColorType = 'i32'; suffix = ''; break; case 'uint': fragColorType = 'u32'; suffix = 'u'; break; case 'float': fragColorType = 'f32'; suffix = ''; fractionDigits = 4; break; default: unreachable(); } const v = output.map(n => n.toFixed(fractionDigits)); let outputType; let result; switch (componentCount) { case 1: outputType = fragColorType; result = `${v[0]}${suffix}`; break; case 2: outputType = `vec2<${fragColorType}>`; result = `${outputType}(${v[0]}${suffix}, ${v[1]}${suffix})`; break; case 3: outputType = `vec3<${fragColorType}>`; result = `${outputType}(${v[0]}${suffix}, ${v[1]}${suffix}, ${v[2]}${suffix})`; break; case 4: outputType = `vec4<${fragColorType}>`; result = `${outputType}(${v[0]}${suffix}, ${v[1]}${suffix}, ${v[2]}${suffix}, ${v[3]}${suffix})`; break; default: unreachable(); } return ` [[stage(fragment)]] fn main() -> [[location(0)]] ${outputType} { return ${result}; }`; } } export const g = makeTestGroup(F); g.test('color,component_count') .desc( `Test that extra components of the output (e.g. f32, vec2<f32>, vec3<f32>, vec4<f32>) are discarded.` ) .params(u => u .combine('format', kRenderableColorTextureFormats) .beginSubcases() .combine('componentCount', [1, 2, 3, 4]) .filter(x => x.componentCount >= kTexelRepresentationInfo[x.format].componentOrder.length) ) .fn(async t => { const { format, componentCount } = t.params; const info = kTextureFormatInfo[format]; await t.selectDeviceOrSkipTestCase(info.feature); // expected RGBA values // extra channels are discarded const result = [0, 1, 0, 1]; const renderTarget = t.device.createTexture({ format, size: { width: 1, height: 1, depthOrArrayLayers: 1 }, usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT, }); const pipeline = t.device.createRenderPipeline({ vertex: { module: t.device.createShaderModule({ code: ` [[stage(vertex)]] fn main( [[builtin(vertex_index)]] VertexIndex : u32 ) -> [[builtin(position)]] vec4<f32> { var pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>( vec2<f32>(-1.0, -3.0), vec2<f32>(3.0, 1.0), vec2<f32>(-1.0, 1.0)); return vec4<f32>(pos[VertexIndex], 0.0, 1.0); } `, }), entryPoint: 'main', }, fragment: { module: t.device.createShaderModule({ code: t.getFragmentShaderCode(result, info.sampleType, componentCount), }), entryPoint: 'main', targets: [{ format }], }, primitive: { topology: 'triangle-list' }, }); const encoder = t.device.createCommandEncoder(); const pass = encoder.beginRenderPass({ colorAttachments: [ { view: renderTarget.createView(), storeOp: 'store', loadValue: { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }, }, ], }); pass.setPipeline(pipeline); pass.draw(3); pass.endPass(); t.device.queue.submit([encoder.finish()]); t.expectSingleColor(renderTarget, format, { size: [1, 1, 1], exp: { R: result[0], G: result[1], B: result[2], A: result[3] }, }); }); g.test('color,component_count,blend') .desc( `Test that blending behaves correctly when: - fragment output has no alpha, but the src alpha is not used for the blend operation indicated by blend factors - attachment format has no alpha, and the dst alpha should be assumed as 1 The attachment has a load value of [1, 0, 0, 1] ` ) .params(u => u .combine('format', ['r8unorm', 'rg8unorm', 'rgba8unorm', 'bgra8unorm'] as const) .beginSubcases() // _result is expected values in the color attachment (extra channels are discarded) // output is the fragment shader output vector // 0.498 -> 0x7f, 0.502 -> 0x80 .combineWithParams([ // fragment output has no alpha { _result: [0, 0, 0, 0], output: [0], colorSrcFactor: 'one', colorDstFactor: 'zero', alphaSrcFactor: 'zero', alphaDstFactor: 'zero', }, { _result: [0, 0, 0, 0], output: [0], colorSrcFactor: 'dst-alpha', colorDstFactor: 'zero', alphaSrcFactor: 'zero', alphaDstFactor: 'zero', }, { _result: [1, 0, 0, 0], output: [0], colorSrcFactor: 'one-minus-dst-alpha', colorDstFactor: 'dst-alpha', alphaSrcFactor: 'zero', alphaDstFactor: 'one', }, { _result: [0.498, 0, 0, 0], output: [0.498], colorSrcFactor: 'dst-alpha', colorDstFactor: 'zero', alphaSrcFactor: 'zero', alphaDstFactor: 'one', }, { _result: [0, 1, 0, 0], output: [0, 1], colorSrcFactor: 'one', colorDstFactor: 'zero', alphaSrcFactor: 'zero', alphaDstFactor: 'zero', }, { _result: [0, 1, 0, 0], output: [0, 1], colorSrcFactor: 'dst-alpha', colorDstFactor: 'zero', alphaSrcFactor: 'zero', alphaDstFactor: 'zero', }, { _result: [1, 0, 0, 0], output: [0, 1], colorSrcFactor: 'one-minus-dst-alpha', colorDstFactor: 'dst-alpha', alphaSrcFactor: 'zero', alphaDstFactor: 'one', }, { _result: [0, 1, 0, 0], output: [0, 1, 0], colorSrcFactor: 'one', colorDstFactor: 'zero', alphaSrcFactor: 'zero', alphaDstFactor: 'zero', }, { _result: [0, 1, 0, 0], output: [0, 1, 0], colorSrcFactor: 'dst-alpha', colorDstFactor: 'zero', alphaSrcFactor: 'zero', alphaDstFactor: 'zero', }, { _result: [1, 0, 0, 0], output: [0, 1, 0], colorSrcFactor: 'one-minus-dst-alpha', colorDstFactor: 'dst-alpha', alphaSrcFactor: 'zero', alphaDstFactor: 'one', }, // fragment output has alpha { _result: [0.502, 1, 0, 0.498], output: [0, 1, 0, 0.498], colorSrcFactor: 'one', colorDstFactor: 'one-minus-src-alpha', alphaSrcFactor: 'one', alphaDstFactor: 'zero', }, { _result: [0.502, 0.498, 0, 0.498], output: [0, 1, 0, 0.498], colorSrcFactor: 'src-alpha', colorDstFactor: 'one-minus-src-alpha', alphaSrcFactor: 'one', alphaDstFactor: 'zero', }, { _result: [0, 1, 0, 0.498], output: [0, 1, 0, 0.498], colorSrcFactor: 'dst-alpha', colorDstFactor: 'zero', alphaSrcFactor: 'one', alphaDstFactor: 'zero', }, { _result: [0, 1, 0, 0.498], output: [0, 1, 0, 0.498], colorSrcFactor: 'dst-alpha', colorDstFactor: 'zero', alphaSrcFactor: 'zero', alphaDstFactor: 'src', }, { _result: [1, 0, 0, 1], output: [0, 1, 0, 0.498], colorSrcFactor: 'one-minus-dst-alpha', colorDstFactor: 'dst-alpha', alphaSrcFactor: 'zero', alphaDstFactor: 'dst-alpha', }, ] as const) .filter(x => x.output.length >= kTexelRepresentationInfo[x.format].componentOrder.length) ) .fn(async t => { const { format, _result, output, colorSrcFactor, colorDstFactor, alphaSrcFactor, alphaDstFactor, } = t.params; const componentCount = output.length; const info = kTextureFormatInfo[format]; await t.selectDeviceOrSkipTestCase(info.feature); const renderTarget = t.device.createTexture({ format, size: { width: 1, height: 1, depthOrArrayLayers: 1 }, usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT, }); const pipeline = t.device.createRenderPipeline({ vertex: { module: t.device.createShaderModule({ code: ` [[stage(vertex)]] fn main( [[builtin(vertex_index)]] VertexIndex : u32 ) -> [[builtin(position)]] vec4<f32> { var pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>( vec2<f32>(-1.0, -3.0), vec2<f32>(3.0, 1.0), vec2<f32>(-1.0, 1.0)); return vec4<f32>(pos[VertexIndex], 0.0, 1.0); } `, }), entryPoint: 'main', }, fragment: { module: t.device.createShaderModule({ code: t.getFragmentShaderCode(output, info.sampleType, componentCount), }), entryPoint: 'main', targets: [ { format, blend: { color: { srcFactor: colorSrcFactor, dstFactor: colorDstFactor, operation: 'add', }, alpha: { srcFactor: alphaSrcFactor, dstFactor: alphaDstFactor, operation: 'add', }, }, }, ], }, primitive: { topology: 'triangle-list' }, }); const encoder = t.device.createCommandEncoder(); const pass = encoder.beginRenderPass({ colorAttachments: [ { view: renderTarget.createView(), storeOp: 'store', loadValue: { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }, }, ], }); pass.setPipeline(pipeline); pass.draw(3); pass.endPass(); t.device.queue.submit([encoder.finish()]); t.expectSingleColor(renderTarget, format, { size: [1, 1, 1], exp: { R: _result[0], G: _result[1], B: _result[2], A: _result[3] }, }); });
the_stack
import { ChangeDetectorRef, Component, ElementRef, EventEmitter, HostBinding, HostListener, Input, OnDestroy, OnInit, Output, Renderer2, RendererStyleFlags2, ViewEncapsulation } from '@angular/core'; import { animate, AnimationBuilder, AnimationPlayer, style } from '@angular/animations'; import { MediaObserver } from '@angular/flex-layout'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { NotaddSidebarService } from './sidebar.service'; import { NotaddMatchMediaService } from '@notadd/services/match-media.service'; import { NotaddConfigService } from '@notadd/services/config.service'; @Component({ selector: 'notadd-sidebar', templateUrl: './sidebar.component.html', styleUrls: ['./sidebar.component.scss'], encapsulation: ViewEncapsulation.None }) export class NotaddSidebarComponent implements OnInit, OnDestroy { @Input() name: string; @Input() key: string; @Input() position: 'left' | 'right'; @HostBinding('class.open') opened: boolean; @Input() lockedOpen: string; @HostBinding('class.locked-open') isLockedOpen: boolean; @Input() collapseWidth: number; @Input() collapseAutoTriggerOnHover: boolean; @HostBinding('class.expanded') expanded: boolean; @Input() invisibleOverlay: boolean; @Output() collapseChanged: EventEmitter<boolean>; @Output() openedChanged: EventEmitter<boolean>; private _collapsed: boolean; private notaddConfig: any; private wasActive: boolean; private wasCollapsed: boolean; private backdrop: HTMLElement | undefined = void (0); private player: AnimationPlayer; private ngUnsubscribe: Subject<any>; @HostBinding('class.animations-enabled') private animationsEnabled: boolean; constructor( private animationBuilder: AnimationBuilder, private changeDetectorRef: ChangeDetectorRef, private elementRef: ElementRef, private mediaObserver: MediaObserver, private renderer: Renderer2, private sidebarService: NotaddSidebarService, private matchMediaService: NotaddMatchMediaService, private configService: NotaddConfigService ) { this.collapseAutoTriggerOnHover = true; this.collapseWidth = 64; this.collapseChanged = new EventEmitter(); this.openedChanged = new EventEmitter(); this.opened = false; this.position = 'left'; this.invisibleOverlay = false; this.animationsEnabled = false; this.collapsed = false; this.ngUnsubscribe = new Subject(); } /** * 折叠 * * @param {boolean} value */ @Input() set collapsed(value: boolean) { this._collapsed = value; if (!this.opened) { return; } // 改变padding位置 let sibling, styleRule; const styleValue = this.collapseWidth + 'px'; if (this.position === 'left') { sibling = this.elementRef.nativeElement.nextElementSibling; styleRule = 'padding-left'; } else { sibling = this.elementRef.nativeElement.previousElementSibling; styleRule = 'padding-right'; } if (!sibling) { return; } // 折叠 if (value) { this.collapse(); // 设置折叠宽度 this.renderer.setStyle(this.elementRef.nativeElement, 'width', styleValue); this.renderer.setStyle(this.elementRef.nativeElement, 'min-width', styleValue); this.renderer.setStyle(this.elementRef.nativeElement, 'max-width', styleValue); // 设置style和class this.renderer.setStyle(sibling, styleRule, styleValue, RendererStyleFlags2.Important + RendererStyleFlags2.DashCase); this.renderer.addClass(this.elementRef.nativeElement, 'folded'); } else { this.expand(); // 移除折叠宽度 this.renderer.removeStyle(this.elementRef.nativeElement, 'width'); this.renderer.removeStyle(this.elementRef.nativeElement, 'min-width'); this.renderer.removeStyle(this.elementRef.nativeElement, 'max-width'); // 移除styly和class this.renderer.removeStyle(sibling, styleRule); this.renderer.removeClass(this.elementRef.nativeElement, 'folded'); } // 触发'collapseChanged'事件 this.collapseChanged.emit(this.collapsed); } get collapsed(): boolean { return this._collapsed; } ngOnInit() { this.configService.config .pipe(takeUntil(this.ngUnsubscribe)) .subscribe((config) => { this.notaddConfig = config; }); this.sidebarService.register(this.name, this); this.setupVisibility(); this.setupPosition(); this.setupLockedOpen(); this.setupCollapsed(); } ngOnDestroy(): void { if (this.collapsed) { this.expand(); } this.sidebarService.unregister(this.name); this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); } private setupVisibility(): void { this.renderer.setStyle(this.elementRef.nativeElement, 'box-shadow', 'none'); this.renderer.setStyle(this.elementRef.nativeElement, 'visibility', 'hidden'); } private setupPosition(): void { if (this.position === 'right') { this.renderer.addClass(this.elementRef.nativeElement, 'right-positioned'); } else { this.renderer.addClass(this.elementRef.nativeElement, 'left-positioned'); } } private setupLockedOpen(): void { if (!this.lockedOpen) { return; } this.wasActive = false; this.wasCollapsed = this.collapsed; this.showSidebar(); this.matchMediaService.onMediaChange .pipe(takeUntil(this.ngUnsubscribe)) .subscribe(() => { const isActive = this.mediaObserver.isActive(this.lockedOpen); if (this.wasActive === isActive) { return; } if (isActive) { this.isLockedOpen = true; this.showSidebar(); this.opened = true; this.openedChanged.emit(this.opened); if (this.wasCollapsed) { this.enableAnimations(); this.collapsed = true; this.changeDetectorRef.markForCheck(); } this.hideBackdrop(); } else { this.isLockedOpen = false; this.expand(); this.opened = false; this.openedChanged.emit(this.opened); this.hideSidebar(); } this.wasActive = isActive; }); } private setupCollapsed(): void { if (!this.collapsed) { return; } if (!this.opened) { return; } let sibling, styleRule; const styleValue = this.collapseWidth + 'px'; if (this.position === 'left') { sibling = this.elementRef.nativeElement.nextElementSibling; styleRule = 'padding-left'; } else { sibling = this.elementRef.nativeElement.previousElementSibling; styleRule = 'padding-right'; } if (!sibling) { return; } this.collapse(); this.renderer.setStyle(this.elementRef.nativeElement, 'width', styleValue); this.renderer.setStyle(this.elementRef.nativeElement, 'min-width', styleValue); this.renderer.setStyle(this.elementRef.nativeElement, 'max-width', styleValue); this.renderer.setStyle(sibling, styleRule, styleValue, RendererStyleFlags2.Important + RendererStyleFlags2.DashCase); this.renderer.addClass(this.elementRef.nativeElement, 'collapsed'); } private showBackdrop(): void { this.backdrop = this.renderer.createElement('div'); this.backdrop.classList.add('notadd-sidebar-overlay'); if (this.invisibleOverlay) { this.backdrop.classList.add('notadd-sidebar-overlay-invisible'); } this.renderer.appendChild(this.elementRef.nativeElement.parentElement, this.backdrop); this.player = this.animationBuilder .build([ animate('300ms ease', style({opacity: 1})) ]).create(this.backdrop); this.player.play(); this.backdrop.addEventListener('click', () => { this.close(); } ); this.changeDetectorRef.markForCheck(); } private hideBackdrop(): void { if (!this.backdrop) { return; } this.player = this.animationBuilder .build([ animate('300ms ease', style({opacity: 0})) ]).create(this.backdrop); this.player.play(); this.player.onDone(() => { if (this.backdrop) { this.backdrop.parentNode.removeChild(this.backdrop); this.backdrop = void (0); } }); this.changeDetectorRef.markForCheck(); } private showSidebar(): void { this.renderer.removeStyle(this.elementRef.nativeElement, 'box-shadow'); this.renderer.removeStyle(this.elementRef.nativeElement, 'visibility'); this.changeDetectorRef.markForCheck(); } private hideSidebar(delay = true): void { const delayAmount = delay ? 300 : 0; setTimeout(() => { this.renderer.setStyle(this.elementRef.nativeElement, 'box-shadow', 'none'); this.renderer.setStyle(this.elementRef.nativeElement, 'visibility', 'hidden'); }, delayAmount); this.changeDetectorRef.markForCheck(); } private enableAnimations(): void { if (this.animationsEnabled) { return; } this.animationsEnabled = true; this.changeDetectorRef.markForCheck(); } open(): void { if (this.opened || this.isLockedOpen) { return; } this.enableAnimations(); this.showSidebar(); this.showBackdrop(); this.opened = true; this.openedChanged.emit(this.opened); this.changeDetectorRef.markForCheck(); } close(): void { if (!this.opened || this.isLockedOpen) { return; } this.enableAnimations(); this.hideBackdrop(); this.opened = false; this.openedChanged.emit(this.opened); this.hideSidebar(); this.changeDetectorRef.markForCheck(); } toggleOpen(): void { if (this.opened) { this.close(); } else { this.open(); } } @HostListener('mouseenter') onMouseEnter(): void { if (!this.collapseAutoTriggerOnHover) { return; } this.expandTemporarily(); } @HostListener('mouseleave') onMouseLeave(): void { if (!this.collapseAutoTriggerOnHover) { return; } this.collapseTemporarily(); } collapse(): void { if (this.collapsed) { return; } this.enableAnimations(); this.collapsed = true; this.changeDetectorRef.markForCheck(); } expand(): void { if (!this.collapsed) { return; } this.enableAnimations(); this.collapsed = false; this.changeDetectorRef.markForCheck(); } toggleFold(): void { if (this.collapsed) { this.expand(); } else { this.collapse(); } } collapseTemporarily(): void { if (!this.collapsed) { return; } this.enableAnimations(); this.expanded = false; const styleValue = this.collapseWidth + 'px'; this.renderer.setStyle(this.elementRef.nativeElement, 'width', styleValue); this.renderer.setStyle(this.elementRef.nativeElement, 'min-width', styleValue); this.renderer.setStyle(this.elementRef.nativeElement, 'max-width', styleValue); this.changeDetectorRef.markForCheck(); } expandTemporarily(): void { if (!this.collapsed) { return; } this.enableAnimations(); this.expanded = true; this.renderer.removeStyle(this.elementRef.nativeElement, 'width'); this.renderer.removeStyle(this.elementRef.nativeElement, 'min-width'); this.renderer.removeStyle(this.elementRef.nativeElement, 'max-width'); this.changeDetectorRef.markForCheck(); } }
the_stack
* Subnet对象 */ export interface Subnet { /** * VPC实例ID。 注意:此字段可能返回 null,表示取不到有效值。 */ VpcId: string /** * 子网实例ID,例如:subnet-bthucmmy。 注意:此字段可能返回 null,表示取不到有效值。 */ SubnetId: string /** * 子网名称。 注意:此字段可能返回 null,表示取不到有效值。 */ SubnetName: string /** * 子网的 IPv4 CIDR。 注意:此字段可能返回 null,表示取不到有效值。 */ CidrBlock: string /** * 创建时间。 注意:此字段可能返回 null,表示取不到有效值。 */ CreatedTime: string /** * 可用IP数。 注意:此字段可能返回 null,表示取不到有效值。 */ AvailableIpAddressCount: number /** * 子网的 IPv6 CIDR。 注意:此字段可能返回 null,表示取不到有效值。 */ Ipv6CidrBlock: string /** * 总IP数 注意:此字段可能返回 null,表示取不到有效值。 */ TotalIpAddressCount: number /** * 是否为默认Subnet 注意:此字段可能返回 null,表示取不到有效值。 */ IsDefault: boolean } /** * DescribeSubnet请求参数结构体 */ export interface DescribeSubnetRequest { /** * 返回数量。 */ Limit: number /** * 偏移量。 */ Offset: number /** * 查询指定VpcId下的子网信息。 */ VpcId: string /** * 查找关键字 */ SearchWord?: string } /** * DescribeVsms返回参数结构体 */ export interface DescribeVsmsResponse { /** * 获取实例的总个数 */ TotalCount: number /** * 资源信息 注意:此字段可能返回 null,表示取不到有效值。 */ VsmList: Array<ResourceInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeSupportedHsm返回参数结构体 */ export interface DescribeSupportedHsmResponse { /** * 当前地域所支持的设备列表 */ DeviceTypes: Array<DeviceInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * InquiryPriceBuyVsm请求参数结构体 */ export interface InquiryPriceBuyVsmRequest { /** * 需购买实例的数量 */ GoodsNum: number /** * 付费模式:0表示按需计费/后付费,1表示预付费 */ PayMode: number /** * 商品的时间大小 */ TimeSpan: string /** * 商品的时间单位,m表示月,y表示年 */ TimeUnit: string /** * 货币类型,默认为CNY */ Currency?: string /** * 默认为CREATE,可选RENEW */ Type?: string } /** * DescribeVpc返回参数结构体 */ export interface DescribeVpcResponse { /** * 可查询到的所有Vpc实例总数。 */ TotalCount: number /** * Vpc对象列表 注意:此字段可能返回 null,表示取不到有效值。 */ VpcList: Array<Vpc> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ModifyVsmAttributes请求参数结构体 */ export interface ModifyVsmAttributesRequest { /** * 资源Id */ ResourceId: string /** * UpdateResourceName-修改资源名称, UpdateSgIds-修改安全组名称, UpdateNetWork-修改网络, Default-默认不修改 */ Type: Array<string> /** * 资源名称 */ ResourceName?: string /** * 安全组Id */ SgIds?: Array<string> /** * 虚拟专网Id */ VpcId?: string /** * 子网Id */ SubnetId?: string } /** * DescribeSubnet返回参数结构体 */ export interface DescribeSubnetResponse { /** * 返回的子网数量。 */ TotalCount: number /** * 返回的子网实例列表。 注意:此字段可能返回 null,表示取不到有效值。 */ SubnetList: Array<Subnet> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 支持的Vsm类型信息 */ export interface VsmInfo { /** * VSM类型名称 */ TypeName: string /** * VSM类型值 */ TypeID: number } /** * DescribeSupportedHsm请求参数结构体 */ export type DescribeSupportedHsmRequest = null /** * 安全组基础信息 */ export interface SgUnit { /** * 安全组Id 注意:此字段可能返回 null,表示取不到有效值。 */ SgId: string /** * 安全组名称 注意:此字段可能返回 null,表示取不到有效值。 */ SgName: string /** * 备注 注意:此字段可能返回 null,表示取不到有效值。 */ SgRemark: string /** * 创建时间 注意:此字段可能返回 null,表示取不到有效值。 */ CreateTime: string } /** * DescribeHSMByVpcId返回参数结构体 */ export interface DescribeHSMByVpcIdResponse { /** * HSM数量 */ TotalCount?: number /** * 作为查询条件的VpcId */ VpcId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeUsgRule返回参数结构体 */ export interface DescribeUsgRuleResponse { /** * 安全组详情 注意:此字段可能返回 null,表示取不到有效值。 */ SgRules?: Array<UsgRuleDetail> /** * 安全组详情数量 注意:此字段可能返回 null,表示取不到有效值。 */ TotalCount?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 标签 */ export interface Tag { /** * 标签键 */ TagKey: string /** * 标签值 */ TagValue: string } /** * 资源信息 */ export interface ResourceInfo { /** * 资源Id 注意:此字段可能返回 null,表示取不到有效值。 */ ResourceId: string /** * 资源名称 注意:此字段可能返回 null,表示取不到有效值。 */ ResourceName: string /** * 资源状态 注意:此字段可能返回 null,表示取不到有效值。 */ Status: number /** * 资源IP 注意:此字段可能返回 null,表示取不到有效值。 */ Vip: string /** * 资源所属Vpc 注意:此字段可能返回 null,表示取不到有效值。 */ VpcId: string /** * 资源所属子网 注意:此字段可能返回 null,表示取不到有效值。 */ SubnetId: string /** * 资源所属HSM规格 注意:此字段可能返回 null,表示取不到有效值。 */ Model: string /** * 资源类型 注意:此字段可能返回 null,表示取不到有效值。 */ VsmType: number /** * 地域Id 注意:此字段可能返回 null,表示取不到有效值。 */ RegionId: number /** * 区域Id 注意:此字段可能返回 null,表示取不到有效值。 */ ZoneId: number /** * 过期时间 注意:此字段可能返回 null,表示取不到有效值。 */ ExpireTime: number /** * 地域名 注意:此字段可能返回 null,表示取不到有效值。 */ RegionName: string /** * 区域名 注意:此字段可能返回 null,表示取不到有效值。 */ ZoneName: string /** * 实例的安全组列表 注意:此字段可能返回 null,表示取不到有效值。 */ SgList: Array<SgUnit> /** * 子网名称 注意:此字段可能返回 null,表示取不到有效值。 */ SubnetName: string /** * 当前实例是否已经过期 注意:此字段可能返回 null,表示取不到有效值。 */ Expired: boolean /** * 为正数表示实例距离过期时间还剩余多少秒,为负数表示已经过期多少秒 注意:此字段可能返回 null,表示取不到有效值。 */ RemainSeconds: number /** * Vpc名称 注意:此字段可能返回 null,表示取不到有效值。 */ VpcName: string /** * 创建者Uin账号 注意:此字段可能返回 null,表示取不到有效值。 */ CreateUin: string /** * 自动续费状态标识, 0-手动续费,1-自动续费,2-到期不续 注意:此字段可能返回 null,表示取不到有效值。 */ RenewFlag: number /** * 标签列表 注意:此字段可能返回 null,表示取不到有效值。 */ Tags: Array<Tag> /** * 厂商 注意:此字段可能返回 null,表示取不到有效值。 */ Manufacturer: string } /** * DescribeVpc请求参数结构体 */ export interface DescribeVpcRequest { /** * 返回偏移量。 */ Offset: number /** * 返回数量。 */ Limit: number /** * 搜索关键字 */ SearchWord?: string } /** * VPC对象 */ export interface Vpc { /** * Vpc名称 注意:此字段可能返回 null,表示取不到有效值。 */ VpcName: string /** * VpcId 注意:此字段可能返回 null,表示取不到有效值。 */ VpcId: string /** * 创建时间 注意:此字段可能返回 null,表示取不到有效值。 */ CreatedTime: string /** * 是否为默认VPC 注意:此字段可能返回 null,表示取不到有效值。 */ IsDefault: boolean } /** * DescribeUsg请求参数结构体 */ export interface DescribeUsgRequest { /** * 偏移量,当Offset和Limit均为0时将一次性返回用户所有的安全组列表。 */ Offset: number /** * 返回量,当Offset和Limit均为0时将一次性返回用户所有的安全组列表。 */ Limit: number /** * 搜索关键字 */ SearchWord?: string } /** * DescribeVsmAttributes返回参数结构体 */ export interface DescribeVsmAttributesResponse { /** * 资源Id */ ResourceId: string /** * 资源名称 */ ResourceName: string /** * 资源状态,1表示资源为正常,2表示资源处于隔离状态 */ Status: number /** * 资源IP */ Vip: string /** * 资源所属Vpc */ VpcId: string /** * 资源所属子网 */ SubnetId: string /** * 资源所属HSM的规格 */ Model: string /** * 资源类型,17表示EVSM,33表示GVSM,49表示SVSM */ VsmType: number /** * 地域Id,返回腾讯云地域代码,如广州为1,北京为8 */ RegionId: number /** * 区域Id,返回腾讯云每个地域的可用区代码 */ ZoneId: number /** * 过期时间 */ ExpireTime: number /** * 安全组详情信息 注意:此字段可能返回 null,表示取不到有效值。 */ SgList: Array<UsgRuleDetail> /** * 子网名 注意:此字段可能返回 null,表示取不到有效值。 */ SubnetName: string /** * 地域名 注意:此字段可能返回 null,表示取不到有效值。 */ RegionName: string /** * 区域名 注意:此字段可能返回 null,表示取不到有效值。 */ ZoneName: string /** * 实例是否已经过期 注意:此字段可能返回 null,表示取不到有效值。 */ Expired: boolean /** * 为正数表示实例距离过期时间剩余秒数,为负数表示实例已经过期多少秒 注意:此字段可能返回 null,表示取不到有效值。 */ RemainSeconds: number /** * 私有虚拟网络名称 注意:此字段可能返回 null,表示取不到有效值。 */ VpcName: string /** * VPC的IPv4 CIDR 注意:此字段可能返回 null,表示取不到有效值。 */ VpcCidrBlock: string /** * 子网的CIDR 注意:此字段可能返回 null,表示取不到有效值。 */ SubnetCidrBlock: string /** * 资源所关联的Tag 注意:此字段可能返回 null,表示取不到有效值。 */ Tags: Array<Tag> /** * 资源续费标识,0表示默认状态(用户未设置,即初始状态), 1表示自动续费,2表示明确不自动续费(用户设置) 注意:此字段可能返回 null,表示取不到有效值。 */ RenewFlag: number /** * 厂商 注意:此字段可能返回 null,表示取不到有效值。 */ Manufacturer: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 标签过滤参数 */ export interface TagFilter { /** * 标签键 */ TagKey: string /** * 标签值 */ TagValue?: Array<string> } /** * DescribeHSMByVpcId请求参数结构体 */ export interface DescribeHSMByVpcIdRequest { /** * VPC标识符 */ VpcId: string } /** * 安全组规则详情 */ export interface UsgRuleDetail { /** * 入站规则 注意:此字段可能返回 null,表示取不到有效值。 */ InBound: Array<UsgPolicy> /** * 出站规则 注意:此字段可能返回 null,表示取不到有效值。 */ OutBound: Array<UsgPolicy> /** * 安全组Id 注意:此字段可能返回 null,表示取不到有效值。 */ SgId: string /** * 安全组名称 注意:此字段可能返回 null,表示取不到有效值。 */ SgName: string /** * 备注 注意:此字段可能返回 null,表示取不到有效值。 */ SgRemark: string /** * 创建时间 注意:此字段可能返回 null,表示取不到有效值。 */ CreateTime: string /** * 版本 注意:此字段可能返回 null,表示取不到有效值。 */ Version: number } /** * InquiryPriceBuyVsm返回参数结构体 */ export interface InquiryPriceBuyVsmResponse { /** * 原始总金额 注意:此字段可能返回 null,表示取不到有效值。 */ TotalCost: number /** * 购买的实例数量 注意:此字段可能返回 null,表示取不到有效值。 */ GoodsNum: number /** * 商品的时间大小 注意:此字段可能返回 null,表示取不到有效值。 */ TimeSpan: string /** * 商品的时间单位 注意:此字段可能返回 null,表示取不到有效值。 */ TimeUnit: string /** * 应付总金额 注意:此字段可能返回 null,表示取不到有效值。 */ OriginalCost: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeHSMBySubnetId返回参数结构体 */ export interface DescribeHSMBySubnetIdResponse { /** * HSM数量 */ TotalCount?: number /** * 作为查询条件的SubnetId */ SubnetId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 支持的加密机类型信息 */ export interface HsmInfo { /** * 加密机型号 */ Model: string /** * 此类型的加密机所支持的VSM类型列表 */ VsmTypes: Array<VsmInfo> } /** * DescribeUsg返回参数结构体 */ export interface DescribeUsgResponse { /** * 用户的安全组列表 注意:此字段可能返回 null,表示取不到有效值。 */ SgList: Array<SgUnit> /** * 返回的安全组数量 */ TotalCount: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeHSMBySubnetId请求参数结构体 */ export interface DescribeHSMBySubnetIdRequest { /** * Subnet标识符 */ SubnetId: string } /** * DescribeVsms请求参数结构体 */ export interface DescribeVsmsRequest { /** * 偏移 */ Offset: number /** * 最大数量 */ Limit: number /** * 查询关键字 */ SearchWord?: string /** * 标签过滤条件 */ TagFilters?: Array<TagFilter> /** * 设备所属的厂商名称,根据厂商来进行筛选 */ Manufacturer?: string } /** * 设备厂商信息 */ export interface DeviceInfo { /** * 厂商名称 */ Manufacturer: string /** * 此厂商旗下的设备信息列表 */ HsmTypes: Array<HsmInfo> } /** * DescribeUsgRule请求参数结构体 */ export interface DescribeUsgRuleRequest { /** * 根据安全组Id获取安全组详情 */ SgIds: Array<string> } /** * ModifyVsmAttributes返回参数结构体 */ export interface ModifyVsmAttributesResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeVsmAttributes请求参数结构体 */ export interface DescribeVsmAttributesRequest { /** * 资源Id */ ResourceId: string } /** * 安全组策略 */ export interface UsgPolicy { /** * cidr格式地址 注意:此字段可能返回 null,表示取不到有效值。 */ Ip: string /** * 安全组id代表的地址集合 注意:此字段可能返回 null,表示取不到有效值。 */ Id: string /** * 地址组id代表的地址集合 注意:此字段可能返回 null,表示取不到有效值。 */ AddressModule: string /** * 协议 注意:此字段可能返回 null,表示取不到有效值。 */ Proto: string /** * 端口 注意:此字段可能返回 null,表示取不到有效值。 */ Port: string /** * 服务组id代表的协议和端口集合 注意:此字段可能返回 null,表示取不到有效值。 */ ServiceModule: string /** * 备注 注意:此字段可能返回 null,表示取不到有效值。 */ Desc: string /** * 匹配后行为:ACCEPT/DROP 注意:此字段可能返回 null,表示取不到有效值。 */ Action: string }
the_stack
import { Injectable, Optional, Injector } from '@angular/core'; import { Router, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router'; import { AppInsights } from 'applicationinsights-js'; import { filter } from 'rxjs/operators'; import IAppInsights = Microsoft.ApplicationInsights.IAppInsights; // Since AI.SeverityLevel isn't working we can just use our own export enum SeverityLevel { Verbose = 0, Information = 1, Warning = 2, Error = 3, Critical = 4, } export class AppInsightsConfig implements Microsoft.ApplicationInsights.IConfig { instrumentationKeySetLater?: boolean; // Will be deprecated in next major version instrumentationKeySetlater?: boolean; instrumentationKey?: string; endpointUrl?: string; emitLineDelimitedJson?: boolean; accountId?: string; sessionRenewalMs?: number; sessionExpirationMs?: number; maxBatchSizeInBytes?: number; maxBatchInterval?: number; enableDebug?: boolean; disableExceptionTracking?: boolean; disableTelemetry?: boolean; verboseLogging?: boolean; diagnosticLogInterval?: number; samplingPercentage?: number; autoTrackPageVisitTime?: boolean; disableAjaxTracking?: boolean; overridePageViewDuration?: boolean; maxAjaxCallsPerView?: number; disableDataLossAnalysis?: boolean; disableCorrelationHeaders?: boolean; correlationHeaderExcludedDomains?: string[]; disableFlushOnBeforeUnload?: boolean; enableSessionStorageBuffer?: boolean; isCookieUseDisabled?: boolean; cookieDomain?: string; isRetryDisabled?: boolean; url?: string; isStorageUseDisabled?: boolean; isBeaconApiDisabled?: boolean; sdkExtension?: string; isBrowserLinkTrackingEnabled?: boolean; appId?: string; enableCorsCorrelation?: boolean; namePrefix?: string; overrideTrackPageMetrics?: boolean; enableAutoRouteTracking?: boolean; enableRequestHeaderTracking?: boolean; enableResponseHeaderTracking?: boolean; enableAjaxErrorStatusText?: boolean; enableAjaxPerfTracking?: boolean; maxAjaxPerfLookupAttempts?: number; ajaxPerfLookupDelay?: number; distributedTracingMode?: boolean; enableUnhandledPromiseRejectionTracking?: boolean; disableInstrumentaionKeyValidation?: boolean; enablePerfMgr?: boolean; perfEvtsSendAll?: boolean; } @Injectable() export class AppInsightsService implements IAppInsights { get context(): Microsoft.ApplicationInsights.ITelemetryContext { return AppInsights.context; } get queue(): Array<() => void> { return AppInsights.queue } config: AppInsightsConfig; constructor( @Optional() _config: AppInsightsConfig, private _injector: Injector ) { this.config = _config; } // https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#trackevent /** * Log a user action or other occurrence. * @param name A string to identify this event in the portal. * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. */ trackEvent(eventName: string, eventProperties?: { [name: string]: string }, metricProperty?: { [name: string]: number }) { try { AppInsights.trackEvent(eventName, eventProperties, metricProperty); } catch (ex) { console.warn('Angular application insights Error [trackEvent]: ', ex); } } /** * Start timing an extended event. Call {@link stopTrackEvent} to log the event when it ends. * @param name A string that identifies this event uniquely within the document. */ startTrackEvent(name: string): any { try { AppInsights.startTrackEvent(name); } catch (ex) { console.warn('Angular application insights Error [startTrackEvent]: ', ex); } } /** * Log an extended event that you started timing with {@link startTrackEvent}. * @param name The string you used to identify this event in startTrackEvent. * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. */ stopTrackEvent(name: string, properties?: { [p: string]: string }, measurements?: { [p: string]: number }): any { try { AppInsights.stopTrackEvent(name, properties, measurements); } catch (ex) { console.warn('Angular application insights Error [stopTrackEvent]: ', ex); } } // https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#trackpageview /** * Logs that a page or other item was viewed. * @param name The string you used as the name in startTrackPage. Defaults to the document title. * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. * @param duration number - the number of milliseconds it took to load the page. Defaults to undefined. If set to default value, page load time is calculated internally. */ trackPageView(name?: string, url?: string, properties?: { [name: string]: string }, measurements?: { [name: string]: number }, duration?: number) { try { AppInsights.trackPageView(name, url, properties, measurements, duration); } catch (ex) { console.warn('Angular application insights Error [trackPageView]: ', ex); } } // https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#starttrackpage /** * Starts timing how long the user views a page or other item. Call this when the page opens. * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title. */ startTrackPage(name?: string) { try { AppInsights.startTrackPage(name); } catch (ex) { console.warn('Angular application insights Error [startTrackPage]: ', ex); } } // https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#stoptrackpage /** * Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes. * @param name The string you used as the name in startTrackPage. Defaults to the document title. * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. */ stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string }, measurements?: { [name: string]: number }) { try { AppInsights.stopTrackPage(name, url, properties, measurements); } catch (ex) { console.warn('Angular application insights Error [stopTrackPage]: ', ex); } } // https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#trackmetric /** * Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators. * To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the * telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals. * @param name A string that identifies the metric. * @param average Number representing either a single measurement, or the average of several measurements. * @param sampleCount The number of measurements represented by the average. Defaults to 1. * @param min The smallest measurement in the sample. Defaults to the average. * @param max The largest measurement in the sample. Defaults to the average. */ trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string }) { try { AppInsights.trackMetric(name, average, sampleCount, min, max, properties); } catch (ex) { console.warn('Angular application insights Error [trackTrace]: ', ex); } } // https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#trackexception /** * Log an exception you have caught. * @param exception An Error from a catch clause, or the string error message. * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. * @param severityLevel SeverityLevel | AI.SeverityLevel - severity level */ trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string }, measurements?: { [name: string]: number }, severityLevel?: SeverityLevel | AI.SeverityLevel) { try { AppInsights.trackException(exception, handledAt, properties, measurements, severityLevel); } catch (ex) { console.warn('Angular application insights Error [trackException]: ', ex); } } // https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#tracktrace // trackTrace(message: string, properties?: {[string]:string}, severityLevel?: SeverityLevel | AI.SeverityLevel) // Log a diagnostic event such as entering or leaving a method. /** * Log a diagnostic message. * @param message A message string * @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty. */ trackTrace(message: string, properties?: { [name: string]: string }, severityLevel?: SeverityLevel | AI.SeverityLevel) { try { AppInsights.trackTrace(message, properties, severityLevel); } catch (ex) { console.warn('Angular application insights Error [trackTrace]: ', ex); } } // https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#trackdependency /** * Log a dependency call (for instance: ajax) * @param id unique id, this is used by the backend o correlate server requests. Use Util.newId() to generate a unique Id. * @param method represents request verb (GET, POST, etc.) * @param absoluteUrl absolute url used to make the dependency request * @param pathName the path part of the absolute url * @param totalTime total request time * @param success indicates if the request was sessessful * @param resultCode response code returned by the dependency request * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. */ trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, properties?: { [name: string]: string }, measurements?: { [name: string]: number }) { try { AppInsights.trackDependency(id, method, absoluteUrl, pathName, totalTime, success, resultCode, properties, measurements); } catch (ex) { console.warn('Angular application insights Error [trackDependency]: ', ex); } } // https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#flush // flush() // Immediately send all queued telemetry. Synchronous. // * You don't usually have to use this, as it happens automatically on window closing. flush() { try { AppInsights.flush(); } catch (ex) { console.warn('Angular application insights Error [flush]: ', ex); } } // https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#setauthenticatedusercontext /** * Sets the authenticated user id and the account id. * User auth id and account id should be of type string. They should not contain commas, semi-colons, equal signs, spaces, or vertical-bars. * * By default the method will only set the authUserID and accountId for all events in this page view. To add them to all events within * the whole session, you should either call this method on every page view or set `storeInCookie = true`. * * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. * @param accountId {string} - An optional string to represent the account associated with the authenticated user. * @param storeInCookie {boolean} - AuthenticateUserID will be stored in a cookie and added to all events within this session. */ setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie: boolean = false) { try { AppInsights.setAuthenticatedUserContext(authenticatedUserId, accountId, storeInCookie); } catch (ex) { console.warn('Angular application insights Error [setAuthenticatedUserContext]: ', ex); } } // https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#clearauthenticatedusercontext /** * Clears the authenticated user id and the account id from the user context. */ clearAuthenticatedUserContext() { try { AppInsights.clearAuthenticatedUserContext(); } catch (ex) { console.warn('Angular application insights Error [clearAuthenticatedUserContext]: ', ex); } } _onerror(message: string): any { console.warn('Angular application insights Error [_onerror]: ', message); } /** * Initialize Application Insights for Angular * Make sure your config{} has been set */ public init(): void { if (this.config) { // Deprecation Warning(s) if (this.config.instrumentationKeySetlater) { console.warn( `\n\n Warning: [instrumentationKeySetlater] will soon be deprecated.\n Use .instrumentationKeySetLater (capital "L" in "L"ater) instead to prevent any possible errors in the future! \n\n`); } if (this.config.instrumentationKey) { try { AppInsights.downloadAndSetup(this.config); // Make sure "router" exists - in case of UIRouterModule where it does not if (!this.config.overrideTrackPageMetrics && this.router) { this.router.events.pipe( filter(event => event instanceof NavigationStart) ) .subscribe((event: NavigationStart) => { this.startTrackPage(event.url); }); this.router.events.pipe( filter(event => ( event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError )) ) .subscribe((event: NavigationEnd) => { this.stopTrackPage(event.url); }); } } catch (ex) { console.warn('Angular application insights Error [downloadAndSetup]: ', ex); } } else { if (!this.config.instrumentationKeySetLater && !this.config.instrumentationKeySetlater) { // there is no this.config.instrumentationKey AND no this.config.instrumentationKeySetLater => Add log. console.warn('An instrumentationKey value is required to initialize AppInsightsService'); } } } else { console.warn('You need forRoot on ApplicationInsightsModule, with or instrumentationKeySetLater or instrumentationKey set at least'); } } private get router() { try { return this._injector.get(Router); } catch (ex) { // @angular/router is not included - App must be utilizing UIRouter return null; } } }
the_stack
import { Directive, ElementRef, Input, Output, EventEmitter, OnChanges, SimpleChange, Optional, ViewContainerRef, ViewChild, OnDestroy, Inject, } from '@angular/core'; import { IonContent } from '@ionic/angular'; import { CoreSites } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreIframeUtils, CoreIframeUtilsProvider } from '@services/utils/iframe'; import { CoreTextUtils } from '@services/utils/text'; import { CoreUtils } from '@services/utils/utils'; import { CoreSite } from '@classes/site'; import { NgZone, Platform, Translate } from '@singletons'; import { CoreExternalContentDirective } from './external-content'; import { CoreLinkDirective } from './link'; import { CoreFilter, CoreFilterFilter, CoreFilterFormatTextOptions } from '@features/filter/services/filter'; import { CoreFilterDelegate } from '@features/filter/services/filter-delegate'; import { CoreFilterHelper } from '@features/filter/services/filter-helper'; import { CoreSubscriptions } from '@singletons/subscriptions'; import { CoreComponentsRegistry } from '@singletons/components-registry'; import { CoreCollapsibleItemDirective } from './collapsible-item'; import { CoreCancellablePromise } from '@classes/cancellable-promise'; import { AsyncComponent } from '@classes/async-component'; import { CoreText } from '@singletons/text'; import { CoreDom } from '@singletons/dom'; import { CoreEvents } from '@singletons/events'; import { CoreRefreshContext, CORE_REFRESH_CONTEXT } from '@/core/utils/refresh-context'; /** * Directive to format text rendered. It renders the HTML and treats all links and media, using CoreLinkDirective * and CoreExternalContentDirective. It also applies filters if needed. * * Please use this directive if your text needs to be filtered or it can contain links or media (images, audio, video). * * Example usage: * <core-format-text [text]="myText" [component]="component" [componentId]="componentId"></core-format-text> */ @Directive({ selector: 'core-format-text', }) export class CoreFormatTextDirective implements OnChanges, OnDestroy, AsyncComponent { @ViewChild(CoreCollapsibleItemDirective) collapsible?: CoreCollapsibleItemDirective; @Input() text?: string; // The text to format. @Input() siteId?: string; // Site ID to use. @Input() component?: string; // Component for CoreExternalContentDirective. @Input() componentId?: string | number; // Component ID to use in conjunction with the component. @Input() adaptImg?: boolean | string = true; // Whether to adapt images to screen width. @Input() clean?: boolean | string; // Whether all the HTML tags should be removed. @Input() singleLine?: boolean | string; // Whether new lines should be removed (all text in single line). Only if clean=true. @Input() highlight?: string; // Text to highlight. @Input() filter?: boolean | string; // Whether to filter the text. If not defined, true if contextLevel and instanceId are set. @Input() contextLevel?: string; // The context level of the text. @Input() contextInstanceId?: number; // The instance ID related to the context. @Input() courseId?: number; // Course ID the text belongs to. It can be used to improve performance with filters. @Input() wsNotFiltered?: boolean | string; // If true it means the WS didn't filter the text for some reason. @Input() captureLinks?: boolean; // Whether links should tried to be opened inside the app. Defaults to true. @Input() openLinksInApp?: boolean; // Whether links should be opened in InAppBrowser. @Input() hideIfEmpty = false; // If true, the tag will contain nothing if text is empty. @Input() fullOnClick?: boolean | string; // @deprecated on 4.0 Won't do anything. @Input() fullTitle?: string; // @deprecated on 4.0 Won't do anything. /** * Max height in pixels to render the content box. It should be 50 at least to make sense. */ @Input() maxHeight?: number; // @deprecated on 4.0 Use collapsible-item directive instead. @Output() afterRender: EventEmitter<void>; // Called when the data is rendered. @Output() onClick: EventEmitter<void> = new EventEmitter(); // Called when clicked. protected element: HTMLElement; protected emptyText = ''; protected domPromises: CoreCancellablePromise<void>[] = []; protected domElementPromise?: CoreCancellablePromise<void>; constructor( element: ElementRef, @Optional() protected content: IonContent, protected viewContainerRef: ViewContainerRef, @Optional() @Inject(CORE_REFRESH_CONTEXT) protected refreshContext?: CoreRefreshContext, ) { CoreComponentsRegistry.register(element.nativeElement, this); this.element = element.nativeElement; this.element.classList.add('core-loading'); // Hide contents until they're treated. this.emptyText = this.hideIfEmpty ? '' : '&nbsp;'; this.element.innerHTML = this.emptyText; this.afterRender = new EventEmitter<void>(); this.element.addEventListener('click', this.elementClicked.bind(this)); this.siteId = this.siteId || CoreSites.getCurrentSiteId(); } /** * @inheritdoc */ ngOnChanges(changes: { [name: string]: SimpleChange }): void { if (changes.text || changes.filter || changes.contextLevel || changes.contextInstanceId) { this.formatAndRenderContents(); } } /** * @inheritdoc */ ngOnDestroy(): void { this.domElementPromise?.cancel(); this.domPromises.forEach((promise) => { promise.cancel();}); } /** * @inheritdoc */ async ready(): Promise<void> { if (!this.element.classList.contains('core-loading')) { return; } await new Promise<void>(resolve => { const subscription = this.afterRender.subscribe(() => { subscription.unsubscribe(); resolve(); }); }); } /** * Apply CoreExternalContentDirective to a certain element. * * @param element Element to add the attributes to. * @return External content instance or undefined if siteId is not provided. */ protected addExternalContent(element: Element): CoreExternalContentDirective | undefined { if (!this.siteId) { return; } // Angular doesn't let adding directives dynamically. Create the CoreExternalContentDirective manually. const extContent = new CoreExternalContentDirective(new ElementRef(element)); extContent.component = this.component; extContent.componentId = this.componentId; extContent.siteId = this.siteId; extContent.src = element.getAttribute('src') || undefined; extContent.href = element.getAttribute('href') || element.getAttribute('xlink:href') || undefined; extContent.targetSrc = element.getAttribute('target-src') || undefined; extContent.poster = element.getAttribute('poster') || undefined; extContent.ngAfterViewInit(); return extContent; } /** * Add class to adapt media to a certain element. * * @param element Element to add the class to. */ protected addMediaAdaptClass(element: HTMLElement): void { element.classList.add('core-media-adapt-width'); } /** * Wrap an image with a container to adapt its width. * * @param img Image to adapt. */ protected adaptImage(img: HTMLElement): void { // Element to wrap the image. const container = document.createElement('span'); const originalWidth = img.attributes.getNamedItem('width'); const forcedWidth = Number(originalWidth?.value); if (originalWidth && !isNaN(forcedWidth)) { if (originalWidth.value.indexOf('%') < 0) { img.style.width = forcedWidth + 'px'; } else { img.style.width = forcedWidth + '%'; } } container.classList.add('core-adapted-img-container'); container.style.cssFloat = img.style.cssFloat; // Copy the float to correctly position the search icon. if (img.classList.contains('atto_image_button_right')) { container.classList.add('atto_image_button_right'); } else if (img.classList.contains('atto_image_button_left')) { container.classList.add('atto_image_button_left'); } else if (img.classList.contains('atto_image_button_text-top')) { container.classList.add('atto_image_button_text-top'); } else if (img.classList.contains('atto_image_button_middle')) { container.classList.add('atto_image_button_middle'); } else if (img.classList.contains('atto_image_button_text-bottom')) { container.classList.add('atto_image_button_text-bottom'); } CoreDomUtils.wrapElement(img, container); } /** * Add magnifying glass icons to view adapted images at full size. */ async addMagnifyingGlasses(): Promise<void> { const imgs = Array.from(this.element.querySelectorAll('.core-adapted-img-container > img')); if (!imgs.length) { return; } // If cannot calculate element's width, use viewport width to avoid false adapt image icons appearing. const elWidth = await this.getElementWidth(); imgs.forEach((img: HTMLImageElement) => { // Skip image if it's inside a link. if (img.closest('a')) { return; } let imgWidth = Number(img.getAttribute('width')); if (!imgWidth) { // No width attribute, use real size. imgWidth = img.naturalWidth; } if (imgWidth <= elWidth) { return; } const imgSrc = CoreTextUtils.escapeHTML(img.getAttribute('data-original-src') || img.getAttribute('src')); const label = Translate.instant('core.openfullimage'); const button = document.createElement('button'); button.classList.add('core-image-viewer-icon'); button.classList.add('hidden'); button.setAttribute('aria-label', label); // Add an ion-icon item to apply the right styles, but the ion-icon component won't be executed. button.innerHTML = '<ion-icon name="fas-expand-alt" aria-hidden="true" \ src="assets/fonts/font-awesome/solid/expand-alt.svg">\ </ion-icon>'; button.addEventListener('click', (e: Event) => { e.preventDefault(); e.stopPropagation(); CoreDomUtils.viewImage(imgSrc, img.getAttribute('alt'), this.component, this.componentId); }); img.parentNode?.appendChild(button); if (img.complete && img.naturalWidth > 0) { // Image has already loaded, show the button. button.classList.remove('hidden'); } else { // Show the button when the image is loaded. img.onload = () => button.classList.remove('hidden'); } }); } /** * Listener to call when the element is clicked. * * @param e Click event. */ protected elementClicked(e: MouseEvent): void { if (e.defaultPrevented) { // Ignore it if the event was prevented by some other listener. return; } if (this.onClick.observers.length > 0) { this.onClick.emit(); return; } if (!this.text) { return; } this.collapsible?.elementClicked(e); } /** * Finish the rendering, displaying the element again and calling afterRender. */ protected async finishRender(): Promise<void> { // Show the element again. this.element.classList.remove('core-loading'); await CoreUtils.nextTick(); // Emit the afterRender output. this.afterRender.emit(); } /** * Format contents and render. */ protected async formatAndRenderContents(): Promise<void> { if (!this.text) { this.element.innerHTML = this.emptyText; // Remove current contents. await this.finishRender(); return; } if (!this.element.getAttribute('singleLine')) { this.element.setAttribute('singleLine', String(CoreUtils.isTrueOrOne(this.singleLine))); } this.text = this.text ? this.text.trim() : ''; const result = await this.formatContents(); // Disable media adapt to correctly calculate the height. this.element.classList.add('core-disable-media-adapt'); this.element.innerHTML = ''; // Remove current contents. // Move the children to the current element to be able to calculate the height. CoreDomUtils.moveChildren(result.div, this.element); await CoreUtils.nextTick(); // Use collapsible-item directive instead. if (this.maxHeight && !this.collapsible) { this.collapsible = new CoreCollapsibleItemDirective(new ElementRef(this.element)); this.collapsible.height = this.maxHeight; this.collapsible.ngOnInit(); } // Add magnifying glasses to images. this.addMagnifyingGlasses(); if (result.options.filter) { // Let filters handle HTML. We do it here because we don't want them to block the render of the text. CoreFilterDelegate.handleHtml( this.element, result.filters, this.viewContainerRef, result.options, [], this.component, this.componentId, result.siteId, ); } this.element.classList.remove('core-disable-media-adapt'); await this.finishRender(); } /** * Apply formatText and set sub-directives. * * @return Promise resolved with a div element containing the code. */ protected async formatContents(): Promise<FormatContentsResult> { // Retrieve the site since it might be needed later. const site = await CoreUtils.ignoreErrors(CoreSites.getSite(this.siteId)); const siteId = site?.getId(); if (site && this.contextLevel == 'course' && this.contextInstanceId !== undefined && this.contextInstanceId <= 0) { this.contextInstanceId = site.getSiteHomeId(); } const filter = this.filter === undefined ? !!(this.contextLevel && this.contextInstanceId !== undefined) : CoreUtils.isTrueOrOne(this.filter); const options: CoreFilterFormatTextOptions = { clean: CoreUtils.isTrueOrOne(this.clean), singleLine: CoreUtils.isTrueOrOne(this.singleLine), highlight: this.highlight, courseId: this.courseId, wsNotFiltered: CoreUtils.isTrueOrOne(this.wsNotFiltered), }; let formatted: string; let filters: CoreFilterFilter[] = []; if (filter) { const filterResult = await CoreFilterHelper.getFiltersAndFormatText( this.text || '', this.contextLevel || '', this.contextInstanceId ?? -1, options, siteId, ); filters = filterResult.filters; formatted = filterResult.text; } else { formatted = await CoreFilter.formatText(this.text || '', options, [], siteId); } formatted = this.treatWindowOpen(formatted); const div = document.createElement('div'); div.innerHTML = formatted; this.treatHTMLElements(div, site); return { div, filters, options, siteId, }; } /** * Treat HTML elements when formatting contents. * * @param div Div element. * @param site Site instance. * @return Promise resolved when done. */ protected async treatHTMLElements(div: HTMLElement, site?: CoreSite): Promise<void> { const images = Array.from(div.querySelectorAll('img')); const anchors = Array.from(div.querySelectorAll('a')); const audios = Array.from(div.querySelectorAll('audio')); const videos = Array.from(div.querySelectorAll('video')); const iframes = Array.from(div.querySelectorAll('iframe')); const buttons = Array.from(div.querySelectorAll('.button')); const elementsWithInlineStyles = Array.from(div.querySelectorAll('*[style]')); const stopClicksElements = Array.from(div.querySelectorAll('button,input,select,textarea')); const frames = Array.from(div.querySelectorAll(CoreIframeUtilsProvider.FRAME_TAGS.join(',').replace(/iframe,?/, ''))); const svgImages = Array.from(div.querySelectorAll('image')); const promises: Promise<void>[] = []; this.treatAppUrlElements(div, site); // Walk through the content to find the links and add our directive to it. // Important: We need to look for links first because in 'img' we add new links without core-link. anchors.forEach((anchor) => { if (anchor.dataset.appUrl) { // Link already treated in treatAppUrlElements, ignore it. return; } // Angular 2 doesn't let adding directives dynamically. Create the CoreLinkDirective manually. const linkDir = new CoreLinkDirective(new ElementRef(anchor), this.content); linkDir.capture = this.captureLinks ?? true; linkDir.inApp = this.openLinksInApp; linkDir.ngOnInit(); this.addExternalContent(anchor); }); const externalImages: CoreExternalContentDirective[] = []; if (images && images.length > 0) { // Walk through the content to find images, and add our directive. images.forEach((img: HTMLElement) => { this.addMediaAdaptClass(img); const externalImage = this.addExternalContent(img); if (externalImage && !externalImage.invalid) { externalImages.push(externalImage); } if (CoreUtils.isTrueOrOne(this.adaptImg) && !img.classList.contains('icon')) { this.adaptImage(img); } }); } audios.forEach((audio) => { this.treatMedia(audio); }); videos.forEach((video) => { this.treatMedia(video, true); }); iframes.forEach((iframe) => { promises.push(this.treatIframe(iframe, site)); }); svgImages.forEach((image) => { this.addExternalContent(image); }); // Handle buttons with inner links. buttons.forEach((button: HTMLElement) => { // Check if it has a link inside. if (button.querySelector('a')) { button.classList.add('core-button-with-inner-link'); } }); // Handle inline styles. elementsWithInlineStyles.forEach((el: HTMLElement) => { // Only add external content for tags that haven't been treated already. if (el.tagName != 'A' && el.tagName != 'IMG' && el.tagName != 'AUDIO' && el.tagName != 'VIDEO' && el.tagName != 'SOURCE' && el.tagName != 'TRACK') { this.addExternalContent(el); } }); // Stop propagating click events. stopClicksElements.forEach((element: HTMLElement) => { element.addEventListener('click', (e) => { e.stopPropagation(); }); }); // Handle all kind of frames. frames.forEach((frame: HTMLFrameElement | HTMLObjectElement | HTMLEmbedElement) => { CoreIframeUtils.treatFrame(frame, false); }); CoreDomUtils.handleBootstrapTooltips(div); if (externalImages.length) { // Wait for images to load. const promise = CoreUtils.allPromises(externalImages.map((externalImage) => { if (externalImage.loaded) { // Image has already been loaded, no need to wait. return Promise.resolve(); } return new Promise(resolve => CoreSubscriptions.once(externalImage.onLoad, resolve)); })); // Automatically reject the promise after 5 seconds to prevent blocking the user forever. promises.push(CoreUtils.ignoreErrors(CoreUtils.timeoutPromise(promise, 5000))); } await Promise.all(promises); } /** * Treat elements with an app-url data attribute. * * @param div Div containing the elements. * @param site Site. */ protected treatAppUrlElements(div: HTMLElement, site?: CoreSite): void { const appUrlElements = Array.from(div.querySelectorAll<HTMLElement>('*[data-app-url]')); appUrlElements.forEach((element) => { const url = element.dataset.appUrl; if (!url) { return; } if (element.tagName !== 'BUTTON' && element.tagName !== 'A') { element.setAttribute('tabindex', '0'); element.setAttribute('role', 'button'); } CoreDom.onActivate(element, async (event) => { event.preventDefault(); event.stopPropagation(); site = site || CoreSites.getCurrentSite(); if (!site) { return; } const confirmMessage = element.dataset.appUrlConfirm; const openInApp = element.dataset.openIn === 'app'; const refreshOnResume = element.dataset.appUrlResumeAction === 'refresh'; if (confirmMessage) { try { await CoreDomUtils.showConfirm(Translate.instant(confirmMessage)); } catch { return; } } if (openInApp) { site.openInAppWithAutoLoginIfSameSite(url); if (refreshOnResume && this.refreshContext) { // Refresh the context when the IAB is closed. CoreEvents.once(CoreEvents.IAB_EXIT, () => { this.refreshContext?.refreshContext(); }); } } else { site.openInBrowserWithAutoLoginIfSameSite(url, undefined, { showBrowserWarning: !confirmMessage, }); if (refreshOnResume && this.refreshContext) { // Refresh the context when the app is resumed. CoreSubscriptions.once(Platform.resume, () => { NgZone.run(async () => { this.refreshContext?.refreshContext(); }); }); } } }); }); } /** * Returns the element width in pixels. * * @return The width of the element in pixels. */ protected async getElementWidth(): Promise<number> { if (!this.domElementPromise) { this.domElementPromise = CoreDom.waitToBeInDOM(this.element); } await this.domElementPromise; let width = this.element.getBoundingClientRect().width; if (!width) { // All elements inside are floating or inline. Change display mode to allow calculate the width. const previousDisplay = getComputedStyle(this.element).display; this.element.style.display = 'inline-block'; await CoreUtils.nextTick(); width = this.element.getBoundingClientRect().width; this.element.style.display = previousDisplay; } // Aproximate using parent elements. let element = this.element; while (!width && element.parentElement) { element = element.parentElement; const computedStyle = getComputedStyle(element); const padding = CoreDomUtils.getComputedStyleMeasure(computedStyle, 'paddingLeft') + CoreDomUtils.getComputedStyleMeasure(computedStyle, 'paddingRight'); // Use parent width as an aproximation. width = element.getBoundingClientRect().width - padding; } return width > 0 && width < window.innerWidth ? width : window.innerWidth; } /** * Add media adapt class and apply CoreExternalContentDirective to the media element and its sources and tracks. * * @param element Video or audio to treat. * @param isVideo Whether it's a video. */ protected treatMedia(element: HTMLElement, isVideo: boolean = false): void { this.addMediaAdaptClass(element); this.addExternalContent(element); // Hide download button if not hidden already. let controlsList = element.getAttribute('controlsList') || ''; if (!controlsList.includes('nodownload')) { if (!controlsList.trim()) { controlsList = 'nodownload'; } else { controlsList = controlsList.split(' ').concat('nodownload').join(' '); } element.setAttribute('controlsList', controlsList); } const sources = Array.from(element.querySelectorAll('source')); const tracks = Array.from(element.querySelectorAll('track')); const hasPoster = isVideo && !!element.getAttribute('poster'); if (isVideo && !hasPoster) { this.fixVideoSrcPlaceholder(element); } sources.forEach((source) => { if (isVideo && !hasPoster) { this.fixVideoSrcPlaceholder(source); } source.setAttribute('target-src', source.getAttribute('src') || ''); source.removeAttribute('src'); this.addExternalContent(source); }); tracks.forEach((track) => { this.addExternalContent(track); }); // Stop propagating click events. element.addEventListener('click', (e) => { e.stopPropagation(); }); } /** * Try to fix the placeholder displayed when a video doesn't have a poster. * * @param element Element to fix. */ protected fixVideoSrcPlaceholder(element: HTMLElement): void { const src = element.getAttribute('src'); if (!src) { return; } if (src.match(/#t=\d/)) { return; } element.setAttribute('src', src + '#t=0.001'); } /** * Add media adapt class and treat the iframe source. * * @param iframe Iframe to treat. * @param site Site instance. */ protected async treatIframe(iframe: HTMLIFrameElement, site: CoreSite | undefined): Promise<void> { const src = iframe.src; const currentSite = CoreSites.getCurrentSite(); this.addMediaAdaptClass(iframe); if (CoreIframeUtils.shouldDisplayHelpForUrl(src)) { this.addIframeHelp(iframe); } if (currentSite?.containsUrl(src)) { // URL points to current site, try to use auto-login. // Remove iframe src, otherwise it can cause auto-login issues if there are several iframes with auto-login. iframe.src = ''; const finalUrl = await CoreIframeUtils.getAutoLoginUrlForIframe(iframe, src); await CoreIframeUtils.fixIframeCookies(finalUrl); iframe.src = finalUrl; CoreIframeUtils.treatFrame(iframe, false); return; } await CoreIframeUtils.fixIframeCookies(src); if (site && src) { // Check if it's a Vimeo video. If it is, use the wsplayer script instead to make restricted videos work. const matches = src.match(/https?:\/\/player\.vimeo\.com\/video\/([0-9]+)([?&]+h=([a-zA-Z0-9]*))?/); if (matches && matches[1]) { let newUrl = CoreText.concatenatePaths(site.getURL(), '/media/player/vimeo/wsplayer.php?video=') + matches[1] + '&token=' + site.getToken(); let privacyHash: string | undefined | null = matches[3]; if (!privacyHash) { // No privacy hash using the new format. Check the legacy format. const matches = src.match(/https?:\/\/player\.vimeo\.com\/video\/([0-9]+)(\/([a-zA-Z0-9]+))?/); privacyHash = matches && matches[3]; } if (privacyHash) { newUrl += `&h=${privacyHash}`; } const domPromise = CoreDom.waitToBeInDOM(iframe); this.domPromises.push(domPromise); await domPromise; // Width and height are mandatory, we need to calculate them. let width: string | number; let height: string | number; if (iframe.width) { width = iframe.width; } else { width = iframe.getBoundingClientRect().width; if (!width) { width = window.innerWidth; } } if (iframe.height) { height = iframe.height; } else { height = iframe.getBoundingClientRect().height; if (!height) { height = width; } } // Width and height parameters are required in 3.6 and older sites. if (site && !site.isVersionGreaterEqualThan('3.7')) { newUrl += '&width=' + width + '&height=' + height; } await CoreIframeUtils.fixIframeCookies(newUrl); iframe.src = newUrl; if (!iframe.width) { iframe.width = String(width); } if (!iframe.height) { iframe.height = String(height); } // Do the iframe responsive. if (iframe.parentElement?.classList.contains('embed-responsive')) { iframe.addEventListener('load', () => { if (iframe.contentDocument) { const css = document.createElement('style'); css.setAttribute('type', 'text/css'); css.innerHTML = 'iframe {width: 100%;height: 100%;}'; iframe.contentDocument.head.appendChild(css); } }); } } } CoreIframeUtils.treatFrame(iframe, false); } /** * Add iframe help option. * * @param iframe Iframe. */ protected addIframeHelp(iframe: HTMLIFrameElement): void { const helpDiv = document.createElement('div'); helpDiv.classList.add('ion-text-center', 'ion-text-wrap'); const button = document.createElement('ion-button'); button.setAttribute('fill', 'clear'); button.setAttribute('aria-haspopup', 'dialog'); button.classList.add('core-iframe-help', 'core-button-as-link'); button.innerHTML = Translate.instant('core.iframehelp'); button.addEventListener('click', () => { CoreIframeUtils.openIframeHelpModal(); }); helpDiv.appendChild(button); iframe.after(helpDiv); } /** * Convert window.open to window.openWindowSafely inside HTML tags. * * @param text Text to treat. * @return Treated text. */ protected treatWindowOpen(text: string): string { // Get HTML tags that include window.open. Script tags aren't executed so there's no need to treat them. const matches = text.match(/<[^>]+window\.open\([^)]*\)[^>]*>/g); if (matches) { matches.forEach((match) => { // Replace all the window.open inside the tag. const treated = match.replace(/window\.open\(/g, 'window.openWindowSafely('); text = text.replace(match, treated); }); } return text; } } type FormatContentsResult = { div: HTMLElement; filters: CoreFilterFilter[]; options: CoreFilterFormatTextOptions; siteId?: string; };
the_stack
import { CdmConstants, CdmCorpusContext, CdmE2ERelationship, CdmEntityDeclarationDefinition, CdmFolderDefinition, CdmImport, CdmManifestDefinition, cdmObjectType, cdmLogCode, copyOptions, resolveOptions, CdmTraitReferenceBase, Logger } from '../../internal'; import * as copyDataUtils from '../../Utilities/CopyDataUtils'; import * as timeUtils from '../../Utilities/timeUtils'; import { AttributeGroupPersistence } from './AttributeGroupPersistence'; import { ConstantEntityPersistence } from './ConstantEntityPersistence'; import { DataTypePersistence } from './DataTypePersistence'; import { DocumentPersistence } from './DocumentPersistence'; import { E2ERelationshipPersistence } from './E2ERelationshipPersistence'; import { EntityPersistence } from './EntityPersistence'; import { ImportPersistence } from './ImportPersistence'; import { LocalEntityDeclarationPersistence } from './LocalEntityDeclarationPersistence'; import { ManifestDeclarationPersistence } from './ManifestDeclarationPersistence'; import { PurposePersistence } from './PurposePersistence'; import { ReferencedEntityDeclarationPersistence } from './ReferencedEntityDeclarationPersistence'; import { TraitPersistence } from './TraitPersistence'; import { EntityDeclarationDefinition, entityDeclarationDefinitionType, ManifestContent, ManifestDeclaration, TraitGroupReference, TraitReference } from './types'; import * as utils from './utils'; export class ManifestPersistence { private static TAG: string = ManifestPersistence.name; // Whether this persistence class has async methods. public static readonly isPersistenceAsync: boolean = false; // The file format/extension types this persistence class supports. public static readonly formats: string[] = [CdmConstants.manifestExtension, CdmConstants.folioExtension]; public static fromObject( ctx: CdmCorpusContext, name: string, namespace: string, path: string, dataObj: ManifestContent ): CdmManifestDefinition { // Determine name of the manifest let manifestName: string; if (dataObj) { manifestName = dataObj.manifestName ? dataObj.manifestName : dataObj.folioName; } // We haven't found the name in the file, use one provided in the call but without the suffixes if (!manifestName && name) { manifestName = name.replace(CdmConstants.manifestExtension, '') .replace(CdmConstants.folioExtension, ''); } const manifest: CdmManifestDefinition = ctx.corpus.MakeObject<CdmManifestDefinition>(cdmObjectType.manifestDef, manifestName); // this is the document name which is assumed by constructor to be related to the the manifestName, but may not be manifest.name = name; manifest.folderPath = path; manifest.namespace = namespace; if (dataObj) { if (dataObj.explanation) { manifest.explanation = dataObj.explanation; } if (dataObj.$schema) { manifest.schema = dataObj.$schema; } // support old model syntax if (dataObj.schemaVersion) { manifest.jsonSchemaSemanticVersion = dataObj.schemaVersion; } if (dataObj.jsonSchemaSemanticVersion) { manifest.jsonSchemaSemanticVersion = dataObj.jsonSchemaSemanticVersion; } if (manifest.jsonSchemaSemanticVersion !== '1.0.0') { // tslint:disable-next-line:no-suspicious-comment // TODO: validate that this is a version we can understand with the OM } if (dataObj.documentVersion) { manifest.documentVersion = dataObj.documentVersion; } if (dataObj.manifestName) { manifest.manifestName = dataObj.manifestName; // Might be populated in the case of folio.cdm.json or manifest.cdm.json file. } else if (dataObj.folioName) { manifest.manifestName = dataObj.folioName; } if (dataObj.imports) { for (const importObj of dataObj.imports) { manifest.imports.push(ImportPersistence.fromData(ctx, importObj)); } } if (dataObj.definitions && Array.isArray(dataObj.definitions)) { for (const definition of dataObj.definitions) { if ('dataTypeName' in definition) { manifest.definitions.push(DataTypePersistence.fromData(ctx, definition)); } else if ('purposeName' in definition) { manifest.definitions.push(PurposePersistence.fromData(ctx, definition)); } else if ('attributeGroupName' in definition) { manifest.definitions.push(AttributeGroupPersistence.fromData(ctx, definition)); } else if ('traitName' in definition) { manifest.definitions.push(TraitPersistence.fromData(ctx, definition)); } else if ('entityShape' in definition) { manifest.definitions.push(ConstantEntityPersistence.fromData(ctx, definition)); } else if ('entityName' in definition) { manifest.definitions.push(EntityPersistence.fromData(ctx, definition)); } } } if (dataObj.lastFileStatusCheckTime) { manifest.lastFileStatusCheckTime = new Date(dataObj.lastFileStatusCheckTime); } if (dataObj.lastFileModifiedTime) { manifest.lastFileModifiedTime = new Date(dataObj.lastFileModifiedTime); } if (dataObj.lastChildFileModifiedTime) { manifest.lastChildFileModifiedTime = new Date(dataObj.lastChildFileModifiedTime); } utils.addArrayToCdmCollection<CdmTraitReferenceBase>( manifest.exhibitsTraits, utils.createTraitReferenceArray(ctx, dataObj.exhibitsTraits) ); if (dataObj.entities) { const fullPath: string = `${namespace ? `${namespace}:${path}` : path}`; for (const entityObj of dataObj.entities) { let entity: CdmEntityDeclarationDefinition; if (entityObj.type) { if (entityObj.type === entityDeclarationDefinitionType.localEntity) { entity = LocalEntityDeclarationPersistence.fromData(ctx, fullPath, entityObj); } else if (entityObj.type === entityDeclarationDefinitionType.referencedEntity) { entity = ReferencedEntityDeclarationPersistence.fromData(ctx, fullPath, entityObj); } else { Logger.error(ctx, this.TAG, this.fromObject.name, null, cdmLogCode.ErrPersistEntityDeclarationMissing, entityObj.entityName); } } else { // We see old structure of entity declaration, check for entity schema/declaration. if (entityObj.entitySchema) { // Local entity declaration used to use entity schema. entity = LocalEntityDeclarationPersistence.fromData(ctx, fullPath, entityObj); } else { // While referenced entity declaration used to use entity declaration. entity = ReferencedEntityDeclarationPersistence.fromData(ctx, fullPath, entityObj); } } manifest.entities.push(entity); } } if (dataObj.relationships) { for (const rel of dataObj.relationships) { manifest.relationships.push(E2ERelationshipPersistence.fromData(ctx, rel)); } } if (dataObj.subManifests) { for (const subManifest of dataObj.subManifests) { manifest.subManifests.push(ManifestDeclarationPersistence.fromData(ctx, subManifest)); } // Might be populated in the case of folio.cdm.json or manifest.cdm.json file. } else if (dataObj.subFolios) { for (const subFolio of dataObj.subFolios) { manifest.subManifests.push(ManifestDeclarationPersistence.fromData(ctx, subFolio)); } } } return manifest; } public static fromData(ctx: CdmCorpusContext, docName: string, jsonData: string, folder: CdmFolderDefinition): CdmManifestDefinition { const dataObj = JSON.parse(jsonData); return ManifestPersistence.fromObject(ctx, docName, folder.namespace, folder.folderPath, dataObj); } public static toData(instance: CdmManifestDefinition, resOpt: resolveOptions, options: copyOptions): ManifestContent { const manifestContent: ManifestContent = DocumentPersistence.toData(instance, resOpt, options) as ManifestContent; manifestContent.manifestName = instance.manifestName; manifestContent.lastFileStatusCheckTime = timeUtils.getFormattedDateString(instance.lastFileStatusCheckTime); manifestContent.lastFileModifiedTime = timeUtils.getFormattedDateString(instance.lastFileModifiedTime); manifestContent.lastChildFileModifiedTime = timeUtils.getFormattedDateString(instance.lastChildFileModifiedTime); manifestContent.documentVersion = instance.documentVersion; manifestContent.explanation = instance.explanation; manifestContent.exhibitsTraits = copyDataUtils.arrayCopyData<string | TraitReference | TraitGroupReference>( resOpt, instance.exhibitsTraits.allItems, options); manifestContent.entities = copyDataUtils.arrayCopyData<EntityDeclarationDefinition>( resOpt, instance.entities, options ); manifestContent.subManifests = copyDataUtils.arrayCopyData<ManifestDeclaration>(resOpt, instance.subManifests, options); if (instance.imports && instance.imports.length > 0) { manifestContent.imports = []; instance.imports.allItems.forEach((importDoc: CdmImport) => { manifestContent.imports.push(ImportPersistence.toData(importDoc, new resolveOptions(), {})); }); } if (instance.relationships && instance.relationships.length > 0) { manifestContent.relationships = instance.relationships.allItems.map((relationship: CdmE2ERelationship) => { return E2ERelationshipPersistence.toData(relationship, resOpt, options); }); } return manifestContent; } }
the_stack
import { ChoiceSchema, XmlSerlializationFormat, ExternalDocumentation, ApiVersion, Deprecation, ChoiceValue, SetType, } from "@autorest/codemodel"; import { Session } from "@autorest/extension-base"; import { getPascalIdentifier } from "@azure-tools/codegen"; import * as OpenAPI from "@azure-tools/openapi"; import { StringFormat, JsonType, ParameterLocation, includeXDashKeys, includeXDashProperties, } from "@azure-tools/openapi"; import { keyBy } from "lodash"; export interface XMSEnum { modelAsString?: boolean; values: [{ value: any; description?: string; name?: string }]; name: string; } const removeKnownParameters = [ "x-ms-metadata", "x-ms-enum", "x-ms-code-generation-settings", "x-ms-client-name", "x-ms-parameter-location", "x-ms-original", "x-ms-requestBody-name", "x-ms-requestBody-index", "x-ms-api-version", "x-ms-text", ]; // ref: https://www.w3schools.com/charsets/ref_html_ascii.asp const specialCharacterMapping: { [character: string]: string } = { "!": "exclamation mark", '"': "quotation mark", "#": "number sign", $: "dollar sign", "%": "percent sign", "&": "ampersand", "'": "apostrophe", "(": "left parenthesis", ")": "right parenthesis", "*": "asterisk", "+": "plus sign", ",": "comma", "-": "hyphen", ".": "period", "/": "slash", ":": "colon", ";": "semicolon", "<": "less-than", "=": "equals-to", ">": "greater-than", "?": "question mark", "@": "at sign", "[": "left square bracket", "\\": "backslash", "]": "right square bracket", "^": "caret", _: "underscore", "`": "grave accent", "{": "left curly brace", "|": "vertical bar", "}": "right curly brace", "~": "tilde", }; const apiVersionParameterNames = ["api-version", "apiversion", "x-ms-api-version", "x-ms-version"]; export function getValidEnumValueName(originalString: string): string { if (typeof originalString === "string") { return !originalString.match(/[A-Za-z0-9]/g) ? getPascalIdentifier( originalString .split("") .map((x) => specialCharacterMapping[x]) .join(" "), ) : originalString; } return originalString; } export class Interpretations { isTrue(value: any) { return value === true || value === "true" || value === "True" || value === "TRUE"; } getConstantValue(schema: OpenAPI.Schema, value: any) { switch (schema.type) { case JsonType.String: switch (schema.format) { // member should be byte array // on wire format should be base64url case StringFormat.Base64Url: // return this.parseBase64UrlValue(value); return value; case StringFormat.Byte: case StringFormat.Certificate: // return this.parseByteArrayValue(value); return value; case StringFormat.Char: // a single character return `${value}`.charAt(0); case StringFormat.Date: // return this.parseDateValue(value); return value; case StringFormat.DateTime: // return this.parseDateTimeValue(value); return value; case StringFormat.DateTimeRfc1123: // return this.parseDateTimeRfc1123Value(value); return value; case StringFormat.Duration: // return this.parseDurationValue(value); return value; case StringFormat.Uuid: return value; case StringFormat.Url: return value; case StringFormat.Password: throw new Error("Constant values for String/Passwords should never be in input documents"); case StringFormat.OData: return value; case StringFormat.None: case undefined: case null: return value; default: // console.error(`String schema '${name}' with unknown format: '${schema.format}' is treated as simple string.`); throw new Error( `Unknown type for constant value for String '${schema.format}'--cannot create constant value.`, ); } case JsonType.Boolean: return this.isTrue(value); case JsonType.Number: return Number.parseFloat(value); case JsonType.Integer: return Number.parseInt(value); } } isApiVersionParameter(parameter: OpenAPI.Parameter): boolean { // Always let x-ms-api-version override the check if (parameter["x-ms-api-version"] !== undefined) { return !!parameter["x-ms-api-version"] === true; } // It's an api-version parameter if it's a query param with an expected name return ( parameter.in === ParameterLocation.Query && !!apiVersionParameterNames.find((each) => each === parameter.name.toLowerCase()) ); } getEnumChoices(schema: OpenAPI.Schema): Array<ChoiceValue> { if (schema && schema.enum) { const xmse = <XMSEnum>schema["x-ms-enum"]; return xmse && xmse.values ? xmse.values.map((each) => { const name = getValidEnumValueName(each.name !== undefined ? each.name : each.value); const value = this.getConstantValue(schema, each.value); return new ChoiceValue(`${name}`, each.description || ``, value); }) : schema.enum.map((each) => { const name = getValidEnumValueName(each); const value = this.getConstantValue(schema, each); return new ChoiceValue(`${name}`, ``, value); }); } return []; } isEmptyObject(schema: OpenAPI.Schema): boolean { const hasAdditionalProps = typeof schema.additionalProperties === "boolean" ? schema.additionalProperties : Object.keys(schema.additionalProperties ?? {}).length !== 0; const allOfCount = schema.allOf?.length ?? 0; const anyOfCount = schema.anyOf?.length ?? 0; const oneOfCount = schema.oneOf?.length ?? 0; const propertyCount = Object.keys(schema.properties ?? {}).length; return ( schema.type === JsonType.Object && allOfCount + anyOfCount + oneOfCount + propertyCount === 0 && !hasAdditionalProps && !schema.discriminator ); } getSerialization(schema: OpenAPI.Schema): any | undefined { const xml = this.getXmlSerialization(schema); if (xml) { return { xml, }; } return undefined; } getXmlSerialization(schema: OpenAPI.Schema): XmlSerlializationFormat | undefined { if (schema.xml) { if (schema.xml["x-ms-text"] && schema.xml.attribute) { throw new Error(`XML serialization for a schema cannot be in both 'text' and 'attribute'`); } return { attribute: schema.xml.attribute || false, wrapped: schema.xml.wrapped || false, text: schema.xml["x-ms-text"] || false, name: schema.xml.name || undefined, namespace: schema.xml.namespace || undefined, prefix: schema.xml.prefix || undefined, extensions: this.getExtensionProperties(schema.xml), }; } return undefined; } getExternalDocs(schema: OpenAPI.Schema): ExternalDocumentation | undefined { return undefined; } getExample(schema: OpenAPI.Schema): any { return undefined; } getApiVersions(schema: OpenAPI.Schema | OpenAPI.HttpOperation | OpenAPI.PathItem): Array<ApiVersion> | undefined { if (schema["x-ms-metadata"] && schema["x-ms-metadata"]["apiVersions"]) { const v = (schema["x-ms-metadata"]["apiVersions"] ?? []).map((each: string) => SetType(ApiVersion, { version: each.replace(/^-/, "").replace(/\+$/, ""), range: each.startsWith("-") ? <any>"-" : each.endsWith("+") ? "+" : undefined, }), ); return v; } return undefined; } getApiVersionValues(node: OpenAPI.Schema | OpenAPI.HttpOperation | OpenAPI.PathItem): Array<string> { if (node["x-ms-metadata"] && node["x-ms-metadata"]["apiVersions"]) { return [...new Set<string>((node["x-ms-metadata"]["apiVersions"] as any) ?? [])]; } return []; } public getDeprecation(schema: OpenAPI.Deprecatable): Deprecation | undefined { if (!schema.deprecated) { return undefined; } // We don't have any additional information at this time. Just returning an empty object saying this is deprecated. return {}; } constructor(private session: Session<OpenAPI.Model>) {} xmsMeta(obj: any, key: string) { const m = obj["x-ms-metadata"]; return m ? m[key] : undefined; } xmsMetaFallback(obj: any, obj2: any, key: string) { return this.xmsMeta(obj, key) || this.xmsMeta(obj2, key); } splitOpId(opId: string) { const p = opId.indexOf("_"); return p != -1 ? { group: opId.substr(0, p), member: opId.substr(p + 1), } : { group: "", member: opId, }; } isBinarySchema(schema: OpenAPI.Schema | undefined) { return !!( schema && (schema.format === StringFormat.Binary || schema.format === "file" || <any>schema.type === "file") ); } getOperationId(httpMethod: string, path: string, original: OpenAPI.HttpOperation) { if (original.operationId) { return this.splitOpId(original.operationId); } // synthesize from tags. if (original.tags && original.tags.length > 0) { const newOperationId = original.tags.length === 1 ? `${original.tags[0]}` : `${original.tags[0]}_${original.tags[1]}`; this.session.warning( `Generating 'operationId' to '${newOperationId}' for '${httpMethod}' operation on path '${path}' `, ["Interpretations"], original, ); return this.splitOpId(newOperationId); } this.session.error( `NEED 'operationId' for '${httpMethod}' operation on path '${path}' `, ["Interpretations"], original, ); return this.splitOpId("unknown-method"); } getDescription( defaultValue: string, original: OpenAPI.Extensions & { title?: string; summary?: string; description?: string }, ): string { if (original) { return original.description || original.title || original.summary || defaultValue; } return defaultValue; } getPreferredName(original: any, preferredName?: string, fallbackName?: string) { return ( original["x-ms-client-name"] ?? preferredName ?? original?.["x-ms-metadata"]?.["name"] ?? fallbackName ?? original["name"] ?? "MISSING_NAME" ); } getName(defaultValue: string, original: any): string { return original["x-ms-client-name"] ?? original?.["x-ms-metadata"]?.["name"] ?? defaultValue; } /** gets the operation path from metadata, falls back to the OAI3 path key */ getPath(pathItem: OpenAPI.PathItem, operation: OpenAPI.HttpOperation, path: string) { return this.xmsMeta(pathItem, "path") ?? this.xmsMeta(operation, "path") ?? path; } /* /** creates server entries that are kept in the codeModel.protocol.http, and then referenced in each operation * * @note - this is where deduplication of server entries happens. * / getServers(operation: OpenAPI.HttpOperation): Array<HttpServer> { return values(operation.servers).select(server => { const p = <HttpModel>this.codeModel.protocol.http; const f = p && p.servers.find(each => each.url === server.url); if (f) { return f; } const s = new HttpServer(server.url, this.getDescription('MISSING-SERVER-DESCRIPTION', server)); if (server.variables && length(server.variables) > 0) { s.variables = items(server.variables).where(each => !!each.key).select(each => { const description = this.getDescription('MISSING-SERVER_VARIABLE-DESCRIPTION', each.value); const variable = each.value; const schema = variable.enum ? this.getEnumSchemaForVarible(each.key, variable) : this.codeModel.schemas.add(new StringSchema(`ServerVariable/${each.key}`, description)); const serverVariable = new ServerVariable( each.key, this.getDescription('MISSING-SERVER_VARIABLE-DESCRIPTION', variable), schema, { default: variable.default, // required: TODO: implement required on server variables }); return serverVariable; }).toArray(); } (<HttpModel>this.codeModel.protocol.http).servers.push(s); return s; }).toArray(); } */ getEnumSchemaForVarible(name: string, somethingWithEnum: { enum?: Array<string> }): ChoiceSchema { return new ChoiceSchema(name, this.getDescription("MISSING-SERVER-VARIABLE-ENUM-DESCRIPTION", somethingWithEnum)); } getExtensionProperties( dictionary: Record<string, any>, additional?: Record<string, any>, ): Record<string, any> | undefined { const main = Interpretations.getExtensionProperties(dictionary); if (additional) { const more = Interpretations.getExtensionProperties(additional); if (more) { return { ...main, ...more }; } } return main; } getClientDefault( dictionary: Record<string, any>, additional?: Record<string, any>, ): string | number | boolean | undefined { return dictionary?.["x-ms-client-default"] || additional?.["x-ms-client-default"] || undefined; } static getExtensionProperties(dictionary: Record<string, any>): Record<string, any> | undefined { const result: Record<string, any> = includeXDashProperties(dictionary); for (const each of removeKnownParameters) { delete result[each]; } return Object.keys(result).length === 0 ? undefined : result; } }
the_stack
import { Directive, ElementRef, EventEmitter, Input, OnDestroy, Optional, Output, Renderer2, ChangeDetectorRef } from "@angular/core"; import {HttpClient} from "@angular/common/http"; import {TranslateService} from "@ngx-translate/core"; import {AbstractJigsawComponent} from "../../../common/common"; import {CommonUtils} from "../../../common/core/utils/common-utils"; export type UploadFileInfoFallback = { name: string, url: string, file: File, reason: string, state: 'pause' | 'loading' | 'success' | 'error' }; /** * @internal */ @Directive() export class JigsawUploadFallbackBase extends AbstractJigsawComponent implements OnDestroy { constructor(@Optional() protected _http: HttpClient, protected _renderer: Renderer2, protected _elementRef: ElementRef, @Optional() protected _translateService: TranslateService, protected _cdr: ChangeDetectorRef) { super(); } /** * @NoMarkForCheckRequired */ @Input() public targetUrl: string = '/rdk/service/common/upload'; /** * @NoMarkForCheckRequired */ @Input() public fileType: string; /** * @NoMarkForCheckRequired */ @Input() public multiple: boolean = true; /** * @NoMarkForCheckRequired */ @Input() public contentField: string = 'file'; /** * @NoMarkForCheckRequired */ @Input() public fileNameField: string = 'filename'; /** * @NoMarkForCheckRequired */ @Input() public fileVerify: string; /** * @NoMarkForCheckRequired */ @Input() public additionalFields: { [prop: string]: string }; private _minSize: number; /** * @NoMarkForCheckRequired */ @Input() public get minSize(): number { return this._minSize; } public set minSize(value: number) { if (isNaN(value)) { console.error('minSize property must be a number, please input a number or number string'); return; } this._minSize = Number(value); } private _maxSize: number; /** * @NoMarkForCheckRequired */ @Input() public get maxSize(): number { return this._maxSize; } public set maxSize(value: number) { if (isNaN(value)) { console.error('max property must be a number, please input a number or number string'); return; } this._maxSize = Number(value); } @Output() public progress = new EventEmitter<UploadFileInfoFallback>(); @Output() public remove = new EventEmitter<UploadFileInfoFallback>(); @Output() public complete = new EventEmitter<UploadFileInfoFallback[]>(); @Output() public start = new EventEmitter<UploadFileInfoFallback[]>(); @Output() /** * @deprecated */ public update = new EventEmitter<UploadFileInfoFallback[]>(); /** * @internal */ public _$uploadMode: 'select' | 'selectAndList' = 'select'; protected _fileInputEl: Element; private _removeFileChangeEvent: Function; /** * @internal */ public _$validFiles: UploadFileInfoFallback[] = []; /** * @internal */ public _$invalidFiles: UploadFileInfoFallback[] = []; public get _$allFiles(): UploadFileInfoFallback[] { return [...this._$validFiles, ...this._$invalidFiles]; } /** * @internal */ public _$selectFile($event) { $event.preventDefault(); $event.stopPropagation(); let e = document.createEvent("MouseEvent"); e.initEvent("click", true, true); if (!this._fileInputEl) { this._fileInputEl = document.createElement('input'); this._fileInputEl.setAttribute('type', 'file'); if (CommonUtils.isIE()) { //指令模式动态创建的input不在dom中的时候,ie11无法监听click事件,此处将其加入body中,设置其不可见 this._fileInputEl.setAttribute('display', 'none'); document.body.appendChild(this._fileInputEl); } } if (this.multiple) { this._fileInputEl.setAttribute('multiple', 'true'); } else { this._fileInputEl.removeAttribute('multiple'); } this._fileInputEl.setAttribute('accept', this.fileType); this._removeFileChangeEvent = this._removeFileChangeEvent ? this._removeFileChangeEvent : this._renderer.listen(this._fileInputEl, 'change', () => { this._upload(); }); this._fileInputEl.dispatchEvent(e); } protected _upload(files?: FileList) { if (!this._http) { console.error('Jigsaw upload pc-components must inject HttpClientModule, please import it to the module!'); return; } if (!files) { const fileInput = this._fileInputEl; files = fileInput['files']; } if (!files || !files.length) { console.warn('there are no upload files'); return; } if (!this.multiple) { this._$validFiles = []; this._$invalidFiles = []; } this._classifyFiles(Array.from(files)); const pendingFiles = this._$validFiles.filter(file => file.state == 'pause'); for (let i = 0, len = Math.min(5, pendingFiles.length); i < len; i++) { // 最多前5个文件同时上传给服务器 this._sequenceUpload(pendingFiles[i]); } this._$uploadMode = 'selectAndList'; if (pendingFiles.length > 0) { this.start.emit(this._$validFiles); } if (this._fileInputEl) { this._fileInputEl['value'] = null; } } private _testFileType(fileName: string, type: string): boolean { const re = new RegExp(`.+\\${type.trim()}$`, 'i'); return re.test(fileName); } private _classifyFiles(files: File[]): void { if (this.fileType) { const fileTypes = this.fileType.split(','); const oldFiles = files; files = files.filter(f => !!fileTypes.find(ft => this._testFileType(f.name, ft))); oldFiles.filter(f => files.indexOf(f) == -1).forEach(file => { this._$invalidFiles.push({ name: file.name, state: 'error', url: '', file: file, reason: this._translateService.instant(`upload.fileTypeError`) }) }); } if (this.minSize) { const oldFiles = files; files = files.filter(f => f.size >= this.minSize * 1024 * 1024); oldFiles.filter(f => files.indexOf(f) == -1).forEach(file => { this._$invalidFiles.push({ name: file.name, state: 'error', url: '', file: file, reason: this._translateService.instant(`upload.fileMinSizeError`) }) }); } if (this.maxSize) { const oldFiles = files; files = files.filter(f => f.size <= this.maxSize * 1024 * 1024); oldFiles.filter(f => files.indexOf(f) == -1).forEach(file => { this._$invalidFiles.push({ name: file.name, state: 'error', url: '', file: file, reason: this._translateService.instant(`upload.fileMaxSizeError`) }) }); } files.forEach((file: File) => { this._$validFiles.push({ name: file.name, state: 'pause', url: '', file: file, reason: '' }); }); } private _isAllFilesUploaded(): boolean { return !this._$validFiles.find(f => f.state == 'loading' || f.state == 'pause'); } private _sequenceUpload(fileInfo: UploadFileInfoFallback) { fileInfo.state = 'loading'; const formData = new FormData(); formData.append(this.contentField, fileInfo.file); this._appendAdditionalFields(formData, fileInfo.file.name); this._http.post(this.targetUrl, formData, {responseType: 'text'}).subscribe(res => { fileInfo.state = 'success'; fileInfo.url = res; fileInfo.reason = ''; this._afterCurFileUploaded(fileInfo); }, (e) => { fileInfo.state = 'error'; fileInfo.reason = this._translateService.instant(`upload.${e.statusText}`); this._afterCurFileUploaded(fileInfo); }); } private _appendAdditionalFields(formData: FormData, fileName: string): void { const additionalFields = CommonUtils.shallowCopy(this.additionalFields || {}); // 为了避免引入破坏性,这里按照顺序append const fileNameField = this.fileNameField ? this.fileNameField.trim() : ''; if (fileNameField) { formData.append(fileNameField, encodeURIComponent(fileName)); delete additionalFields[fileNameField]; } const fileVerify = this.fileVerify ? this.fileVerify.trim() : ''; if (fileVerify) { formData.append('file-verify', encodeURIComponent(fileVerify)); delete additionalFields['file-verify']; } for (let prop in this.additionalFields) { formData.append(prop, encodeURIComponent(this.additionalFields[prop])); } } private _afterCurFileUploaded(fileInfo: UploadFileInfoFallback) { this.progress.emit(fileInfo); const waitingFile = this._$validFiles.find(f => f.state == 'pause'); if (waitingFile) { this._sequenceUpload(waitingFile) } else if (this._isAllFilesUploaded()) { this.complete.emit(this._$validFiles); this.update.emit(this._$validFiles) } this._cdr.markForCheck(); } /** * @internal */ public _$removeFile(file) { this.remove.emit(file); let fileIndex = this._$validFiles.findIndex(f => f == file); if (fileIndex != -1) { this._$validFiles.splice(fileIndex, 1); // 保持向下兼容 if (this._isAllFilesUploaded()) { this.update.emit(this._$validFiles); } } fileIndex = this._$invalidFiles.findIndex(f => f == file); if (fileIndex != -1) { this._$invalidFiles.splice(fileIndex, 1); } if (this._fileInputEl) { this._fileInputEl['value'] = null; } } public clearFileList() { this._$validFiles = []; this._$invalidFiles = []; this._cdr.detectChanges(); } ngOnDestroy() { super.ngOnDestroy(); if (this._removeFileChangeEvent) { this._removeFileChangeEvent(); this._removeFileChangeEvent = null; } this._fileInputEl = null; } }
the_stack
/* This file is part of the Microsoft PowerApps code samples. Copyright (C) Microsoft Corporation. All rights reserved. This source code is intended only as a supplement to Microsoft Development Tools and/or on-line documentation. See these other materials for detailed information regarding Microsoft code samples. THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. */ import { IInputs, IOutputs } from "./generated/ManifestTypes"; import DataSetInterfaces = ComponentFramework.PropertyHelper.DataSetApi; type DataSet = ComponentFramework.PropertyTypes.DataSet; // Define const here const RowRecordId = "rowRecId"; // Style name of Load More Button const LoadMoreButton_Hidden_Style = "LoadMoreButton_Hidden_Style"; export class TableGrid implements ComponentFramework.StandardControl<IInputs, IOutputs> { // Cached context object for the latest updateView private contextObj: ComponentFramework.Context<IInputs>; // Div element created as part of this control's main container private mainContainer: HTMLDivElement; // Table element created as part of this control's table private dataTable: HTMLTableElement; // Button element created as part of this control private loadPageButton: HTMLButtonElement; /** * Empty constructor. */ constructor() { // no-op: method not leveraged by this example custom control } /** * Used to initialize the control instance. Controls can kick off remote server calls and other initialization actions here. * Data-set values are not initialized here, use updateView. * @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to property names defined in the manifest, as well as utility functions. * @param notifyOutputChanged A callback method to alert the framework that the control has new outputs ready to be retrieved asynchronously. * @param state A piece of data that persists in one session for a single user. Can be set at any point in a controls life cycle by calling 'setControlState' in the Mode interface. * @param container If a control is marked control-type='standard', it will receive an empty div element within which it can render its content. */ public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container: HTMLDivElement): void { // Need to track container resize so that control could get the available width. The available height won't be provided even this is true context.mode.trackContainerResize(true); // Create main table container div. this.mainContainer = document.createElement("div"); this.mainContainer.classList.add("SimpleTable_MainContainer_Style"); // Create data table container div. this.dataTable = document.createElement("table"); this.dataTable.classList.add("SimpleTable_Table_Style"); // Create data table container div. this.loadPageButton = document.createElement("button"); this.loadPageButton.setAttribute("type", "button"); this.loadPageButton.innerText = context.resources.getString("PCF_TableGrid_LoadMore_ButtonLabel"); this.loadPageButton.classList.add(LoadMoreButton_Hidden_Style); this.loadPageButton.classList.add("LoadMoreButton_Style"); this.loadPageButton.addEventListener("click", this.onLoadMoreButtonClick.bind(this)); // Adding the main table and loadNextPage button created to the container DIV. this.mainContainer.appendChild(this.dataTable); this.mainContainer.appendChild(this.loadPageButton); container.appendChild(this.mainContainer); } /** * Called when any value in the property bag has changed. This includes field values, data-sets, global values such as container height and width, offline status, control metadata values such as label, visible, etc. * @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to names defined in the manifest, as well as utility functions */ public updateView(context: ComponentFramework.Context<IInputs>): void { this.contextObj = context; this.toggleLoadMoreButtonWhenNeeded(context.parameters.simpleTableGrid); if (!context.parameters.simpleTableGrid.loading) { // Get sorted columns on View const columnsOnView = this.getSortedColumnsOnView(context); if (!columnsOnView?.length) { return; } const columnWidthDistribution = this.getColumnWidthDistribution(context, columnsOnView); while (this.dataTable.lastChild) { this.dataTable.removeChild(this.dataTable.lastChild); } this.dataTable.appendChild(this.createTableHeader(columnsOnView, columnWidthDistribution)); this.dataTable.appendChild(this.createTableBody(columnsOnView, columnWidthDistribution, context.parameters.simpleTableGrid)); this.dataTable.parentElement!.style.height = `${window.innerHeight - this.dataTable.offsetTop - 70}px`; } } /** * It is called by the framework prior to a control receiving new data. * @returns an object based on nomenclature defined in manifest, expecting object[s] for property marked as "bound" or "output" */ public getOutputs(): IOutputs { return {}; } /** * Called when the control is to be removed from the DOM tree. Controls should use this call for cleanup. * i.e. cancelling any pending remote calls, removing listeners, etc. */ public destroy(): void { // no-op: method not leveraged by this example custom control } /** * Get sorted columns on view * @param context * @return sorted columns object on View */ private getSortedColumnsOnView(context: ComponentFramework.Context<IInputs>): DataSetInterfaces.Column[] { if (!context.parameters.simpleTableGrid.columns) { return []; } const columns = context.parameters.simpleTableGrid.columns .filter((columnItem: DataSetInterfaces.Column) => { // some column are supplementary and their order is not > 0 return columnItem.order >= 0; }); // Sort those columns so that they will be rendered in order columns.sort((a: DataSetInterfaces.Column, b: DataSetInterfaces.Column) => { return a.order - b.order; }); return columns; } /** * Get column width distribution * @param context context object of this cycle * @param columnsOnView columns array on the configured view * @returns column width distribution */ private getColumnWidthDistribution(context: ComponentFramework.Context<IInputs>, columnsOnView: DataSetInterfaces.Column[]): string[] { const widthDistribution: string[] = []; // Considering need to remove border & padding length const totalWidth: number = context.mode.allocatedWidth - 250; let widthSum = 0; columnsOnView.forEach((columnItem) => { widthSum += columnItem.visualSizeFactor; }); let remainWidth: number = totalWidth; columnsOnView.forEach((item, index) => { let widthPerCell = ""; if (index !== columnsOnView.length - 1) { const cellWidth = Math.round((item.visualSizeFactor / widthSum) * totalWidth); remainWidth = remainWidth - cellWidth; widthPerCell = `${cellWidth}px`; } else { widthPerCell = `${remainWidth}px`; } widthDistribution.push(widthPerCell); }); return widthDistribution; } private createTableHeader(columnsOnView: DataSetInterfaces.Column[], widthDistribution: string[]): HTMLTableSectionElement { const tableHeader: HTMLTableSectionElement = document.createElement("thead"); const tableHeaderRow: HTMLTableRowElement = document.createElement("tr"); tableHeaderRow.classList.add("SimpleTable_TableRow_Style"); columnsOnView.forEach((columnItem, index) => { const tableHeaderCell = document.createElement("th"); tableHeaderCell.classList.add("SimpleTable_TableHeader_Style"); const innerDiv = document.createElement("div"); innerDiv.classList.add("SimpleTable_TableCellInnerDiv_Style"); innerDiv.style.maxWidth = widthDistribution[index]; innerDiv.innerText = columnItem.displayName; tableHeaderCell.appendChild(innerDiv); tableHeaderRow.appendChild(tableHeaderCell); }); tableHeader.appendChild(tableHeaderRow); return tableHeader; } private createTableBody(columnsOnView: DataSetInterfaces.Column[], widthDistribution: string[], gridParam: DataSet): HTMLTableSectionElement { const tableBody: HTMLTableSectionElement = document.createElement("tbody"); if (gridParam.sortedRecordIds.length > 0) { for (const currentRecordId of gridParam.sortedRecordIds) { const tableRecordRow: HTMLTableRowElement = document.createElement("tr"); tableRecordRow.classList.add("SimpleTable_TableRow_Style"); tableRecordRow.addEventListener("click", this.onRowClick.bind(this)); // Set the recordId on the row dom tableRecordRow.setAttribute(RowRecordId, gridParam.records[currentRecordId].getRecordId()); columnsOnView.forEach((columnItem, index) => { const tableRecordCell = document.createElement("td"); tableRecordCell.classList.add("SimpleTable_TableCell_Style"); const innerDiv = document.createElement("div"); innerDiv.classList.add("SimpleTable_TableCellInnerDiv_Style"); innerDiv.style.maxWidth = widthDistribution[index]; innerDiv.innerText = gridParam.records[currentRecordId].getFormattedValue(columnItem.name); tableRecordCell.appendChild(innerDiv); tableRecordRow.appendChild(tableRecordCell); }); tableBody.appendChild(tableRecordRow); } } else { const tableRecordRow: HTMLTableRowElement = document.createElement("tr"); const tableRecordCell: HTMLTableCellElement = document.createElement("td"); tableRecordCell.classList.add("No_Record_Style"); tableRecordCell.colSpan = columnsOnView.length; tableRecordCell.innerText = this.contextObj.resources.getString("PCF_TableGrid_No_Record_Found"); tableRecordRow.appendChild(tableRecordCell); tableBody.appendChild(tableRecordRow); } return tableBody; } /** * Row Click Event handler for the associated row when being clicked * @param event */ private onRowClick(event: Event): void { const rowRecordId = (event.currentTarget as HTMLTableRowElement).getAttribute(RowRecordId); if (rowRecordId) { const entityReference = this.contextObj.parameters.simpleTableGrid.records[rowRecordId].getNamedReference(); const entityFormOptions = { entityName: entityReference.etn!, entityId: entityReference.id.guid, }; this.contextObj.navigation.openForm(entityFormOptions); } } /** * Toggle 'LoadMore' button when needed */ private toggleLoadMoreButtonWhenNeeded(gridParam: DataSet): void { if (gridParam.paging.hasNextPage && this.loadPageButton.classList.contains(LoadMoreButton_Hidden_Style)) { this.loadPageButton.classList.remove(LoadMoreButton_Hidden_Style); } else if (!gridParam.paging.hasNextPage && !this.loadPageButton.classList.contains(LoadMoreButton_Hidden_Style)) { this.loadPageButton.classList.add(LoadMoreButton_Hidden_Style); } } /** * 'LoadMore' Button Event handler when load more button clicks * @param event */ private onLoadMoreButtonClick(event: Event): void { this.contextObj.parameters.simpleTableGrid.paging.loadNextPage(); this.toggleLoadMoreButtonWhenNeeded(this.contextObj.parameters.simpleTableGrid); } }
the_stack
import React, { useState, useEffect } from 'react'; import type { ProColumns } from '@ant-design/pro-table'; import { FileOutlined, FolderTwoTone, HomeOutlined, ApartmentOutlined, DeleteOutlined, UploadOutlined, LinkOutlined, DownloadOutlined, InboxOutlined, } from '@ant-design/icons'; import { Drawer, Breadcrumb, Upload, Switch, Divider, Modal, Button, Tooltip, message, } from 'antd'; import styles from '../index.module.css'; import ProTable from '@ant-design/pro-table'; import { querySSHFile, deleteSSHFile } from '@/services/anew/ssh'; import lds from 'lodash'; export type FileManagerProps = { modalVisible: boolean; handleChange: (modalVisible: boolean) => void; connectId: string; }; const FileManager: React.FC<FileManagerProps> = (props) => { const { modalVisible, handleChange, connectId } = props; const [columnData, setColumnData] = useState<API.SSHFileList[]>([]); const [showHidden, setShowHidden] = useState<boolean>(false); const [childrenDrawer, setChildrenDrawer] = useState<boolean>(false); const [currentPathArr, setCurrentPathArr] = useState<string[]>([]); const [initPath, setInitPath] = useState<string>(''); const _dirSort = (item: API.SSHFileList) => { return item.isDir; }; const getFileData = (key: string, path: string) => { querySSHFile(key, path).then((res) => { const obj = lds.orderBy(res.data, [_dirSort, 'name'], ['desc', 'asc']); showHidden ? setColumnData(obj) : setColumnData(obj.filter((x) => !x.name.startsWith('.'))); try { // 获取服务器的当前路径 let pathb = obj[0].path; const index = pathb.lastIndexOf('/'); pathb = pathb.substring(0, index + 1); setCurrentPathArr(pathb.split('/').filter((x: any) => x !== '')); setInitPath(pathb); // 保存当前路径,刷新用 } catch (exception) { setCurrentPathArr(path.split('/').filter((x) => x !== '')); setInitPath(path); } }); }; const getChdirDirData = (key: string, path: string) => { const index = currentPathArr.indexOf(path); const currentDir = '/' + currentPathArr.splice(0, index + 1).join('/'); getFileData(key, currentDir); }; const handleDelete = (key: string, path: string) => { if (!path) return; const index = path.lastIndexOf('/'); const currentDir = path.substring(0, index + 1); const currentFile = path.substring(index + 1, path.length); const content = `您是否要删除 ${currentFile}?`; Modal.confirm({ title: '注意', content, onOk: () => { deleteSSHFile(key, path).then((res) => { if (res.code === 200 && res.status === true) { message.success(res.message); getFileData(key, currentDir); } }); }, onCancel() { }, }); }; const handleDownload = (key: string, path: string) => { if (!path) return; const index = path.lastIndexOf('/'); const currentFile = path.substring(index + 1, path.length); const content = `您是否要下载 ${currentFile}?`; Modal.confirm({ title: '注意', content, onOk: () => { const token = localStorage.getItem('token'); const link = document.createElement('a'); link.href = `/api/v1/host/ssh/download?key=${key}&path=${path}&token=${token}`; document.body.appendChild(link); const evt = document.createEvent('MouseEvents'); evt.initEvent('click', false, false); link.dispatchEvent(evt); document.body.removeChild(link); }, onCancel() { }, }); }; const uploadProps = { name: 'file', action: `/api/v1/host/ssh/upload?key=${connectId}&path=${initPath}`, multiple: true, headers: { Authorization: `Bearer ${localStorage.getItem('token')}`, }, // showUploadList: { // removeIcon: false, // showRemoveIcon: false, // }, onChange(info: any) { // if (info.file.status !== 'uploading') { // console.log(info.file, info.fileList); // } //console.log(info); if (info.file.status === 'done') { message.success(`${info.file.name} file uploaded successfully`); getFileData(connectId, initPath as string); // 刷新数据 } else if (info.file.status === 'error') { message.error(`${info.file.name} file upload failed.`); } }, progress: { strokeColor: { '0%': '#108ee9', '100%': '#87d068', }, strokeWidth: 3, format: (percent: any) => `${parseFloat(percent.toFixed(2))}%`, }, }; const columns: ProColumns<API.SSHFileList>[] = [ { title: '名称', dataIndex: 'name', render: (_, record) => record.isDir ? ( <div onClick={() => getFileData(connectId, record.path)} style={{ cursor: 'pointer' }}> <FolderTwoTone /> <span style={{ color: '#1890ff', paddingLeft: 5 }}>{record.name}</span> </div> ) : ( <React.Fragment> {record.isLink ? ( <div> <LinkOutlined /> <Tooltip title="Is Link"> <span style={{ color: '#3cb371', paddingLeft: 5 }}>{record.name}</span> </Tooltip> </div> ) : ( <div> <FileOutlined /> <span style={{ paddingLeft: 5 }}>{record.name}</span> </div> )} </React.Fragment> ), }, { title: '大小', dataIndex: 'size', }, { title: '修改时间', dataIndex: 'mtime', }, { title: '属性', dataIndex: 'mode', }, { title: '操作', dataIndex: 'option', valueType: 'option', render: (_, record) => !record.isDir && !record.isLink ? ( <> <Tooltip title="下载文件"> <DownloadOutlined style={{ fontSize: '17px', color: 'blue' }} onClick={() => handleDownload(connectId, record.path)} /> </Tooltip> <Divider type="vertical" /> <Tooltip title="删除文件"> <DeleteOutlined style={{ fontSize: '17px', color: 'red' }} onClick={() => handleDelete(connectId, record.path)} /> </Tooltip> </> ) : null, }, ]; useEffect(() => { // 是否显示隐藏文件 getFileData(connectId, initPath as string); // 刷新数据 }, [showHidden]); const { Dragger } = Upload; return ( <Drawer title="文件管理器" placement="right" width={800} visible={modalVisible} onClose={()=>handleChange(false)} getContainer={false} > {/* <input style={{ display: 'none' }} type="file" ref={(ref) => (this.input = ref)} /> */} <div className={styles.drawerHeader}> <Breadcrumb> <Breadcrumb.Item href="#" onClick={() => getFileData(connectId, '/')}> <ApartmentOutlined /> </Breadcrumb.Item> <Breadcrumb.Item href="#" onClick={() => getFileData(connectId, '')}> <HomeOutlined /> </Breadcrumb.Item> {currentPathArr.map((item) => ( <Breadcrumb.Item key={item} href="#" onClick={() => getChdirDirData(connectId, item)}> <span>{item}</span> </Breadcrumb.Item> ))} </Breadcrumb> <div style={{ display: 'flex', alignItems: 'center' }}> <span>显示隐藏文件:</span> <Switch checked={showHidden} checkedChildren="开启" unCheckedChildren="关闭" onChange={(v) => { setShowHidden(v); }} /> <Button style={{ marginLeft: 10 }} size="small" type="primary" icon={<UploadOutlined />} onClick={() => setChildrenDrawer(true)} > 上传文件 </Button> </div> </div> <Drawer title="上传文件" width={320} closable={false} onClose={() => setChildrenDrawer(false)} visible={childrenDrawer} > <div style={{ height: 150 }}> <Dragger {...uploadProps}> <p className="ant-upload-drag-icon"> <InboxOutlined /> </p> <p className="ant-upload-text">单击或拖入上传</p> <p className="ant-upload-hint">支持多文件</p> </Dragger> </div> </Drawer> <ProTable pagination={false} search={false} toolBarRender={false} rowKey="name" dataSource={columnData} columns={columns} /> </Drawer> ); }; export default FileManager;
the_stack
import {Body} from './body' import {ButtonAction, ActionHive, ActionFunc} from './action-hive' import {Choices, ChoicesRecord, generateChoicesButtons, combineHideAndChoices} from './choices' import {ChooseOptions} from './buttons/choose' import {ContextFunc, ContextPathFunc, ConstOrContextFunc, ConstOrContextPathFunc, RegExpLike} from './generic-types' import {ensureTriggerChild} from './path' import {Keyboard, ButtonTemplate, CallbackButtonTemplate, ButtonTemplateRow, InlineKeyboard} from './keyboard' import {MenuLike, Submenu} from './menu-like' import {PaginationOptions, createPaginationChoices, SetPageFunction} from './buttons/pagination' import {SelectOptions, generateSelectButtons} from './buttons/select' import {SingleButtonOptions} from './buttons/basic' import {SubmenuOptions, ChooseIntoSubmenuOptions} from './buttons/submenu' import {ToggleOptions, generateToggleButton} from './buttons/toggle' export interface InteractionOptions<Context> extends SingleButtonOptions<Context> { /** * Function which is called when the button is pressed */ readonly do: ActionFunc<Context>; } export class MenuTemplate<Context> { private readonly _body: ContextPathFunc<Context, Body> private readonly _keyboard: Keyboard<Context> = new Keyboard() private readonly _actions: ActionHive<Context> = new ActionHive() private readonly _submenus: Set<Submenu<Context>> = new Set() constructor( body: ConstOrContextPathFunc<Context, Body>, ) { this._body = typeof body === 'function' ? body : () => body } /** * Creates the message body. Usage only recommended for advanced usage of this library. * @param context Context to be supplied to the buttons on on creation */ async renderBody(context: Context, path: string): Promise<Body> { return this._body(context, path) } /** * Creates the raw keyboard information. Usage only recommended for advanced usage of this library. * @param context Context to be supplied to the buttons on on creation * @param path Path within the menu. Will be used for the relativePaths */ async renderKeyboard(context: Context, path: string): Promise<InlineKeyboard> { return this._keyboard.render(context, path) } /** * Creates the actions that the buttons of the template want to happen. Usage only recommended for advanced usage of this library. * @param path Path within the menu. Will be used for the relativePaths */ renderActionHandlers(path: RegExpLike): ReadonlySet<ButtonAction<Context>> { return this._actions.list(path) } /** * Lists the submenus used in this menu template. Usage only recommended for advanced usage of this library. */ listSubmenus(): ReadonlySet<Submenu<Context>> { return this._submenus } /** * Allows for manual creation of a button in a very raw way of doing. Less user friendly but very customizable. * @param button constant or function returning a button representation to be added to the keyboard * @param options additional options */ manual(button: ConstOrContextPathFunc<Context, ButtonTemplate>, options: SingleButtonOptions<Context> = {}): void { const {hide} = options if (hide) { this._keyboard.add(Boolean(options.joinLastRow), async (context, path) => { if (await hide(context, path)) { return undefined } return typeof button === 'function' ? button(context, path) : button }) } else { this._keyboard.add(Boolean(options.joinLastRow), button) } } /** * Allows for manual creation of many buttons. Less user friendly but very customizable. * @param creator function generating a keyboard part */ manualRow(creator: ContextPathFunc<Context, ButtonTemplateRow[]>): void { this._keyboard.addCreator(creator) } /** * Allows for manual creation of actions. Less user friendly but very customizable. * Is probably used together with manualRow. * @param trigger regular expression which is appended to the menu path. * @param action function which is called when the trigger is matched. * @example * menuTemplate.manualRow((context, path) => [[{text: 'Page 2', relativePath: 'custom-pagination:2'}, {text: 'Page 3', relativePath: 'custom-pagination:3'}]]) * menuTemplate.manualAction(/custom-pagination:(\d+)$/, (context, path) => { * console.log('manualAction', path, context.match![1]) * return '.' * }) */ manualAction(trigger: RegExpLike, action: ActionFunc<Context>): void { this._actions.add(trigger, action, undefined) } /** * Add an url button to the keyboard * @param text text to be displayed on the button * @param url url where this button should be heading * @param options additional options */ url(text: ConstOrContextPathFunc<Context, string>, url: ConstOrContextPathFunc<Context, string>, options: SingleButtonOptions<Context> = {}): void { this.manual(async (context, path) => ({ text: typeof text === 'function' ? await text(context, path) : text, url: typeof url === 'function' ? await url(context, path) : url, }), options) } /** * Add a switch_inline_query button to the keyboard * @param text text to be displayed on the button * @param query query that is shown next to the bot username. Can be empty ('') * @param options additional options */ switchToChat(text: ConstOrContextPathFunc<Context, string>, query: ConstOrContextPathFunc<Context, string>, options: SingleButtonOptions<Context> = {}): void { this.manual(async (context, path) => ({ text: typeof text === 'function' ? await text(context, path) : text, switch_inline_query: typeof query === 'function' ? await query(context, path) : query, }), options) } /** * Add a switch_inline_query_current_chat button to the keyboard * @param text text to be displayed on the button * @param query query that is shown next to the bot username. Can be empty ('') * @param options additional options */ switchToCurrentChat(text: ConstOrContextPathFunc<Context, string>, query: ConstOrContextPathFunc<Context, string>, options: SingleButtonOptions<Context> = {}): void { this.manual(async (context, path) => ({ text: typeof text === 'function' ? await text(context, path) : text, switch_inline_query_current_chat: typeof query === 'function' ? await query(context, path) : query, }), options) } // TODO: add login_url, callback_game, pay for easier access (like url button) // see https://core.telegram.org/bots/api#inlinekeyboardbutton /** * Button which only purpose is to move around the menu on click. * The relative path is inspired by the cd command. * If you want to execute a function on click use `menuTemplate.interact(…)` instead. * @param text text to be displayed on the button * @param relativePath relative target path like 'child/', '..' or '../sibling/ * @param options additional options * * @example menuTemplate.navigate('back to parent menu', '..') * @example menuTemplate.navigate('to the root menu', '/') * @example menuTemplate.navigate('to a sibling menu', '../sibling/') */ navigate(text: ConstOrContextPathFunc<Context, string>, relativePath: string, options: SingleButtonOptions<Context> = {}): void { this._keyboard.add(Boolean(options.joinLastRow), generateCallbackButtonTemplate(text, relativePath, options.hide)) } /** * Add a button to which a function is executed on click. * You can update the menu afterwards by returning a relative path. If you only want to update the menu or move around use `menuTemplate.navigate(…)` instead. * @param text text to be displayed on the button * @param action unique identifier for this button within the menu template * @param options additional options. Requires `do` as you want to do something when the user pressed the button. * @example * menuTemplate.interact('Knock Knock', 'unique', { * do: async context => { * await context.answerCallbackQuery('Who is there?') * return false // Do not update the menu afterwards * } * }) * @example * menuTemplate.interact('Update the current menu afterwards', 'unique', { * do: async context => { * // do what you want to do * return '.' // . like the current one -> this menu * } * }) */ interact(text: ConstOrContextPathFunc<Context, string>, action: string, options: InteractionOptions<Context>): void { if ('doFunc' in options) { throw new TypeError('doFunc was renamed to do') } if (typeof options.do !== 'function') { throw new TypeError('You have to specify `do` in order to have an interaction for this button. If you only want to navigate use `menuTemplate.navigate(…)` instead.') } this._actions.add(new RegExp(action + '$'), options.do, options.hide) this._keyboard.add(Boolean(options.joinLastRow), generateCallbackButtonTemplate(text, action, options.hide)) } /** * Add a button to a submenu * @param text text to be displayed on the button * @param action unique identifier for this button within the menu template * @param submenu submenu to be entered on click * @param options additional options * @example * const submenuTemplate = new MenuTemplate('I am a submenu') * submenuTemplate.interact('Text', 'unique', { * do: async ctx => ctx.answerCallbackQuery('You hit a button in a submenu') * }) * submenuTemplate.manualRow(createBackMainMenuButtons()) * * menuTemplate.submenu('enter submenu', 'unique', submenuTemplate) */ submenu(text: ConstOrContextPathFunc<Context, string>, action: string, submenu: MenuLike<Context>, options: SubmenuOptions<Context> = {}): void { ensureTriggerChild(action) const actionRegex = new RegExp(action + '/') if ([...this._submenus].map(o => o.action.source).includes(actionRegex.source)) { throw new Error(`There is already a submenu with the action "${action}". Change the action in order to access both menus.`) } this._submenus.add({ action: actionRegex, hide: options.hide, menu: submenu, }) this._keyboard.add(Boolean(options.joinLastRow), generateCallbackButtonTemplate(text, action + '/', options.hide)) } /** * Let the user choose one of many options and execute a function for the one the user picked * @param actionPrefix prefix which is used to create a unique identifier for each of the resulting buttons * @param choices choices the user can pick from * @param options additional options. Requires `do` as you want to do something when the user pressed a button. */ choose(actionPrefix: string, choices: ConstOrContextFunc<Context, Choices>, options: ChooseOptions<Context>): void { if ('doFunc' in options) { throw new TypeError('doFunc was renamed to do') } if (typeof options.do !== 'function') { throw new TypeError('You have to specify `do` in order to have an interaction for the buttons.') } const trigger = new RegExp(actionPrefix + ':(.+)$') this._actions.add( trigger, async (context, path) => options.do(context, getKeyFromPath(trigger, path)), options.disableChoiceExistsCheck ? options.hide : combineHideAndChoices(actionPrefix, choices, options.hide), ) if (options.setPage) { const pageTrigger = new RegExp(actionPrefix + 'P:(\\d+)$') this._actions.add(pageTrigger, setPageAction(pageTrigger, options.setPage), options.hide) } this._keyboard.addCreator(generateChoicesButtons(actionPrefix, false, choices, options)) } /** * Submenu which is entered when a user picks one of many choices * @param actionPrefix prefix which is used to create a unique identifier for each of the resulting buttons * @param choices choices the user can pick from. Also see `menuTemplate.choose(…)` for examples on choices * @param submenu submenu to be entered when one of the choices is picked * @param options additional options * @example * const submenu = new MenuTemplate<MyContext>(ctx => `Welcome to ${ctx.match[1]}`) * submenu.interact('Text', 'unique', { * do: async ctx => { * console.log('Take a look at ctx.match. It contains the chosen city', ctx.match) * await ctx.answerCallbackQuery('You hit a button in a submenu') * return false * } * }) * submenu.manualRow(createBackMainMenuButtons()) * * menu.chooseIntoSubmenu('unique', ['Gotham', 'Mos Eisley', 'Springfield'], submenu) */ chooseIntoSubmenu(actionPrefix: string, choices: ConstOrContextFunc<Context, Choices>, submenu: MenuLike<Context>, options: ChooseIntoSubmenuOptions<Context> = {}): void { ensureTriggerChild(actionPrefix) const actionRegex = new RegExp(actionPrefix + ':([^/]+)/') if ([...this._submenus].map(o => o.action.source).includes(actionRegex.source)) { throw new Error(`There is already a submenu with the action "${actionPrefix}". Change the action in order to access both menus.`) } this._submenus.add({ action: actionRegex, hide: options.disableChoiceExistsCheck ? options.hide : combineHideAndChoices(actionPrefix, choices, options.hide), menu: submenu, }) if (options.setPage) { const pageTrigger = new RegExp(actionPrefix + 'P:(\\d+)$') this._actions.add(pageTrigger, setPageAction(pageTrigger, options.setPage), options.hide) } this._keyboard.addCreator(generateChoicesButtons(actionPrefix, true, choices, options)) } /** * Let the user select one (or multiple) options from a set of choices * @param actionPrefix prefix which is used to create a unique identifier for each of the resulting buttons * @param choices choices the user can pick from. Also see `menuTemplate.choose(…)` for examples on choices * @param options additional options. Requires `set` and `isSet`. * @example * // User can select exactly one * menuTemplate.select('unique', ['at home', 'at work', 'somewhere else'], { * isSet: (context, key) => context.session.currentLocation === key, * set: (context, key) => { * context.session.currentLocation = key * return true * } * }) * @example * // User can select one of multiple options * menuTemplate.select('unique', ['has arms', 'has legs', 'has eyes', 'has wings'], { * showFalseEmoji: true, * isSet: (context, key) => Boolean(context.session.bodyparts[key]), * set: (context, key, newState) => { * context.session.bodyparts[key] = newState * return true * } * }) */ select(actionPrefix: string, choices: ConstOrContextFunc<Context, Choices>, options: SelectOptions<Context>): void { if ('setFunc' in options || 'isSetFunc' in options) { throw new TypeError('setFunc and isSetFunc were renamed to set and isSet') } if (typeof options.set !== 'function' || typeof options.isSet !== 'function') { throw new TypeError('You have to specify `set` and `isSet` in order to work with select. If you just want to let the user choose between multiple options use `menuTemplate.choose(…)` instead.') } const trueTrigger = new RegExp(actionPrefix + 'T:(.+)$') this._actions.add( trueTrigger, async (context, path) => { const key = getKeyFromPath(trueTrigger, path) return options.set(context, key, true) }, options.disableChoiceExistsCheck ? options.hide : combineHideAndChoices(actionPrefix + 'T', choices, options.hide), ) const falseTrigger = new RegExp(actionPrefix + 'F:(.+)$') this._actions.add( falseTrigger, async (context, path) => { const key = getKeyFromPath(falseTrigger, path) return options.set(context, key, false) }, options.disableChoiceExistsCheck ? options.hide : combineHideAndChoices(actionPrefix + 'F', choices, options.hide), ) if (options.setPage) { const pageTrigger = new RegExp(actionPrefix + 'P:(\\d+)$') this._actions.add(pageTrigger, setPageAction(pageTrigger, options.setPage), options.hide) } this._keyboard.addCreator(generateSelectButtons(actionPrefix, choices, options)) } /** * Shows a row of pagination buttons. * When the user presses one of the buttons `setPage` is called with the specified button. * In order to determine which is the current page and how many pages there are `getCurrentPage` and `getTotalPages` are called to which you have to return the current value * @param actionPrefix prefix which is used to create a unique identifier for each of the resulting buttons * @param options additional options. Requires `getCurrentPage`, `getTotalPages` and `setPage`. */ pagination(actionPrefix: string, options: PaginationOptions<Context>): void { if (typeof options.getCurrentPage !== 'function' || typeof options.getTotalPages !== 'function' || typeof options.setPage !== 'function') { throw new TypeError('You have to specify `getCurrentPage`, `getTotalPages` and `setPage`.') } const paginationChoices: ContextFunc<Context, ChoicesRecord> = async context => { const totalPages = await options.getTotalPages(context) const currentPage = await options.getCurrentPage(context) return createPaginationChoices(totalPages, currentPage) } const trigger = new RegExp(actionPrefix + ':(\\d+)$') this._actions.add(trigger, setPageAction(trigger, options.setPage), options.hide) this._keyboard.addCreator(generateChoicesButtons(actionPrefix, false, paginationChoices, { columns: 5, hide: options.hide, })) } /** * Toogle a value when the button is pressed. * If you want to toggle multiple values use `menuTemplate.select(…)` * @param text text to be displayed on the button * @param actionPrefix unique identifier for this button within the menu template * @param options additional options. Requires `set` and `isSet`. * @example * menuTemplate.toggle('Text', 'unique', { * isSet: context => Boolean(context.session.isFunny), * set: (context, newState) => { * context.session.isFunny = newState * return true * } * }) * @example * // You can use a custom format for the state instead of the default emoji * menuTemplate.toggle('Lamp', 'unique', { * formatState: (context, text, state) => `${text}: ${state ? 'on' : 'off'}`, * isSet: context => Boolean(context.session.lamp), * set: (context, newState) => { * context.session.lamp = newState * return true * } * }) */ toggle(text: ConstOrContextPathFunc<Context, string>, actionPrefix: string, options: ToggleOptions<Context>): void { if ('setFunc' in options || 'isSetFunc' in options) { throw new TypeError('setFunc and isSetFunc were renamed to set and isSet') } if (typeof options.set !== 'function' || typeof options.isSet !== 'function') { throw new TypeError('You have to specify `set` and `isSet` in order to work with toggle. If you just want to implement something more generic use `interact`') } this._actions.add( new RegExp(actionPrefix + ':true$'), async (context, path) => options.set(context, true, path), options.hide, ) this._actions.add( new RegExp(actionPrefix + ':false$'), async (context, path) => options.set(context, false, path), options.hide, ) this._keyboard.add(Boolean(options.joinLastRow), generateToggleButton(text, actionPrefix, options)) } } function generateCallbackButtonTemplate<Context>(text: ConstOrContextPathFunc<Context, string>, relativePath: string, hide: undefined | ContextPathFunc<Context, boolean>): ContextPathFunc<Context, CallbackButtonTemplate | undefined> { return async (context, path) => { if (await hide?.(context, path)) { return undefined } return { relativePath, text: typeof text === 'function' ? await text(context, path) : text, } } } function getKeyFromPath(trigger: RegExpLike, path: string): string { const match = new RegExp(trigger.source, trigger.flags).exec(path) const key = match?.[1] if (!key) { throw new Error(`Could not read key from path '${path}' for trigger '${trigger.source}'`) } return key } function setPageAction<Context>(pageTrigger: RegExpLike, setPage: SetPageFunction<Context>): ActionFunc<Context> { return async (context, path) => { const key = getKeyFromPath(pageTrigger, path) const page = Number(key) await setPage(context, page) return '.' } }
the_stack
import * as Common from '../../core/common/common.js'; import * as Host from '../../core/host/host.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; import * as SDK from '../../core/sdk/sdk.js'; import * as Protocol from '../../generated/protocol.js'; import * as IssuesManager from '../../models/issues_manager/issues_manager.js'; import * as NetworkForward from '../../panels/network/forward/forward.js'; import * as ClientVariations from '../../third_party/chromium/client-variations/client-variations.js'; // eslint-disable-next-line rulesdir/es_modules_import import objectPropertiesSectionStyles from '../../ui/legacy/components/object_ui/objectPropertiesSection.css.js'; // eslint-disable-next-line rulesdir/es_modules_import import objectValueStyles from '../../ui/legacy/components/object_ui/objectValue.css.js'; import * as UI from '../../ui/legacy/legacy.js'; import requestHeadersTreeStyles from './requestHeadersTree.css.js'; import requestHeadersViewStyles from './requestHeadersView.css.js'; const UIStrings = { /** *@description Text in Request Headers View of the Network panel */ general: 'General', /** *@description A context menu item in the Watch Expressions Sidebar Pane of the Sources panel and Network pane request. */ copyValue: 'Copy value', /** *@description Text for a link to the issues panel */ learnMoreInTheIssuesTab: 'Learn more in the issues tab', /** *@description Text that is usually a hyperlink to more documentation */ learnMore: 'Learn more', /** *@description Text in Request Headers View of the Network panel */ requestUrl: 'Request URL', /** *@description Text to show more content */ showMore: 'Show more', /** *@description Text for toggling the view of header data (e.g. query string parameters) from source to parsed in the headers tab */ viewParsed: 'View parsed', /** *@description Text for toggling the view of header data (e.g. query string parameters) from parsed to source in the headers tab */ viewSource: 'View source', /** *@description Text in Request Headers View of the Network panel */ requestHeaders: 'Request Headers', /** *@description A context menu item in the Network Log View Columns of the Network panel */ responseHeaders: 'Response Headers', /** *@description Status code of an event */ statusCode: 'Status Code', /** *@description Text that refers to the network request method */ requestMethod: 'Request Method', /** *@description Text in Request Headers View of the Network panel */ fromMemoryCache: '(from memory cache)', /** *@description Text in Request Headers View of the Network panel */ fromServiceWorker: '(from `service worker`)', /** *@description Text in Request Headers View of the Network panel */ fromSignedexchange: '(from signed-exchange)', /** *@description Text in Request Headers View of the Network panel */ fromPrefetchCache: '(from prefetch cache)', /** *@description Text in Request Headers View of the Network panel */ fromDiskCache: '(from disk cache)', /** *@description Text in Request Headers View of the Network panel */ fromWebBundle: '(from Web Bundle)', /** *@description Message to explain lack of raw headers for a particular network request */ provisionalHeadersAreShownS: 'Provisional headers are shown. Disable cache to see full headers.', /** *@description Tooltip to explain lack of raw headers for a particular network request */ onlyProvisionalHeadersAre: 'Only provisional headers are available because this request was not sent over the network and instead was served from a local cache, which doesn’t store the original request headers. Disable cache to see full request headers.', /** *@description Message to explain lack of raw headers for a particular network request */ provisionalHeadersAreShown: 'Provisional headers are shown', /** *@description Comment used in decoded X-Client-Data HTTP header output in Headers View of the Network panel */ activeClientExperimentVariation: 'Active `client experiment variation IDs`.', /** *@description Comment used in decoded X-Client-Data HTTP header output in Headers View of the Network panel */ activeClientExperimentVariationIds: 'Active `client experiment variation IDs` that trigger server-side behavior.', /** *@description Text in Headers View of the Network panel for X-Client-Data HTTP headers */ decoded: 'Decoded:', /** *@description Text in Network Log View Columns of the Network panel */ remoteAddress: 'Remote Address', /** *@description Text in Request Headers View of the Network panel */ referrerPolicy: 'Referrer Policy', /** *@description Text in Headers View of the Network panel */ toEmbedThisFrameInYourDocument: 'To embed this frame in your document, the response needs to enable the cross-origin embedder policy by specifying the following response header:', /** *@description Text in Headers View of the Network panel */ toUseThisResourceFromADifferent: 'To use this resource from a different origin, the server needs to specify a cross-origin resource policy in the response headers:', /** *@description Text in Headers View of the Network panel */ chooseThisOptionIfTheResourceAnd: 'Choose this option if the resource and the document are served from the same site.', /** *@description Text in Headers View of the Network panel */ onlyChooseThisOptionIfAn: 'Only choose this option if an arbitrary website including this resource does not impose a security risk.', /** *@description Text in Headers View of the Network panel */ thisDocumentWasBlockedFrom: 'This document was blocked from loading in an `iframe` with a `sandbox` attribute because this document specified a cross-origin opener policy.', /** *@description Text in Headers View of the Network panel */ toUseThisResourceFromADifferentSite: 'To use this resource from a different site, the server may relax the cross-origin resource policy response header:', /** *@description Text in Headers View of the Network panel */ toUseThisResourceFromADifferentOrigin: 'To use this resource from a different origin, the server may relax the cross-origin resource policy response header:', /** * @description Shown in the network panel for network requests that meet special criteria. * 'Attribution' is a term used by the "Attribution Reporting API" and refers to an event, e.g. * buying an item in an online store after an ad was clicked. * @example {foo} PH1 */ recordedAttribution: 'Recorded attribution with `trigger-data`: {PH1}', }; const str_ = i18n.i18n.registerUIStrings('panels/network/RequestHeadersView.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); const i18nLazyString = i18n.i18n.getLazilyComputedLocalizedString.bind(undefined, str_); export class RequestHeadersView extends UI.Widget.VBox { private request: SDK.NetworkRequest.NetworkRequest; private showRequestHeadersText: boolean; private showResponseHeadersText: boolean; private highlightedElement: UI.TreeOutline.TreeElement|null; private readonly root: Category; private urlItem: UI.TreeOutline.TreeElement; private readonly requestMethodItem: UI.TreeOutline.TreeElement; private readonly statusCodeItem: UI.TreeOutline.TreeElement; private readonly remoteAddressItem: UI.TreeOutline.TreeElement; private readonly referrerPolicyItem: UI.TreeOutline.TreeElement; private readonly responseHeadersCategory: Category; private readonly requestHeadersCategory: Category; constructor(request: SDK.NetworkRequest.NetworkRequest) { super(); this.element.classList.add('request-headers-view'); this.request = request; this.showRequestHeadersText = false; this.showResponseHeadersText = false; this.highlightedElement = null; const root = new UI.TreeOutline.TreeOutlineInShadow(); root.registerCSSFiles([objectValueStyles, objectPropertiesSectionStyles, requestHeadersTreeStyles]); root.element.classList.add('request-headers-tree'); root.makeDense(); root.setUseLightSelectionColor(true); this.element.appendChild(root.element); const generalCategory = new Category(root, 'general', i18nString(UIStrings.general)); generalCategory.hidden = false; this.root = generalCategory; this.setDefaultFocusedElement(this.root.listItemElement); this.urlItem = generalCategory.createLeaf(); this.requestMethodItem = generalCategory.createLeaf(); headerNames.set(this.requestMethodItem, 'Request-Method'); this.statusCodeItem = generalCategory.createLeaf(); headerNames.set(this.statusCodeItem, 'Status-Code'); this.remoteAddressItem = generalCategory.createLeaf(); this.remoteAddressItem.hidden = true; this.referrerPolicyItem = generalCategory.createLeaf(); this.referrerPolicyItem.hidden = true; this.responseHeadersCategory = new Category(root, 'responseHeaders', ''); this.requestHeadersCategory = new Category(root, 'requestHeaders', ''); } wasShown(): void { this.clearHighlight(); this.registerCSSFiles([requestHeadersViewStyles]); this.request.addEventListener(SDK.NetworkRequest.Events.RemoteAddressChanged, this.refreshRemoteAddress, this); this.request.addEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged, this.refreshRequestHeaders, this); this.request.addEventListener(SDK.NetworkRequest.Events.ResponseHeadersChanged, this.refreshResponseHeaders, this); this.request.addEventListener(SDK.NetworkRequest.Events.FinishedLoading, this.refreshHTTPInformation, this); this.refreshURL(); this.refreshRequestHeaders(); this.refreshResponseHeaders(); this.refreshHTTPInformation(); this.refreshRemoteAddress(); this.refreshReferrerPolicy(); this.root.select(/* omitFocus */ true, /* selectedByUser */ false); } willHide(): void { this.request.removeEventListener(SDK.NetworkRequest.Events.RemoteAddressChanged, this.refreshRemoteAddress, this); this.request.removeEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged, this.refreshRequestHeaders, this); this.request.removeEventListener( SDK.NetworkRequest.Events.ResponseHeadersChanged, this.refreshResponseHeaders, this); this.request.removeEventListener(SDK.NetworkRequest.Events.FinishedLoading, this.refreshHTTPInformation, this); } private addEntryContextMenuHandler(treeElement: UI.TreeOutline.TreeElement, value: string): void { treeElement.listItemElement.addEventListener('contextmenu', event => { event.consume(true); const contextMenu = new UI.ContextMenu.ContextMenu(event); const decodedValue = decodeURIComponent(value); const copyDecodedValueHandler = (): void => { Host.userMetrics.actionTaken(Host.UserMetrics.Action.NetworkPanelCopyValue); Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(decodedValue); }; contextMenu.clipboardSection().appendItem(i18nString(UIStrings.copyValue), copyDecodedValueHandler); contextMenu.show(); }); } private formatHeader(name: string, value: string): DocumentFragment { const fragment = document.createDocumentFragment(); fragment.createChild('div', 'header-name').textContent = name + ': '; fragment.createChild('span', 'header-separator'); fragment.createChild('div', 'header-value source-code').textContent = value; return fragment; } private formatHeaderObject(header: BlockedReasonDetailDescriptor): DocumentFragment { const fragment = document.createDocumentFragment(); if (header.headerNotSet) { fragment.createChild('div', 'header-badge header-badge-error header-badge-text').textContent = 'not-set'; } // Highlight successful Attribution Reporting API redirects. If the request was // not canceled, then something went wrong. if (header.name.toLowerCase() === 'location' && this.request.canceled) { const url = new URL(header.value?.toString() || '', this.request.parsedURL.securityOrigin()); const triggerData = getTriggerDataFromAttributionRedirect(url); if (triggerData) { fragment.createChild('div', 'header-badge header-badge-success header-badge-text').textContent = 'Attribution Reporting API'; header.details = { explanation: (): string => i18nString(UIStrings.recordedAttribution, {PH1: triggerData}), examples: [], link: null, }; } } const colon = header.value ? ': ' : ''; fragment.createChild('div', 'header-name').textContent = header.name + colon; fragment.createChild('span', 'header-separator'); if (header.value) { if (header.headerValueIncorrect) { fragment.createChild('div', 'header-value source-code header-warning').textContent = header.value.toString(); } else { fragment.createChild('div', 'header-value source-code').textContent = header.value.toString(); } } if (header.details) { const detailsNode = fragment.createChild('div', 'header-details'); const callToAction = detailsNode.createChild('div', 'call-to-action'); const callToActionBody = callToAction.createChild('div', 'call-to-action-body'); callToActionBody.createChild('div', 'explanation').textContent = header.details.explanation(); for (const example of header.details.examples) { const exampleNode = callToActionBody.createChild('div', 'example'); exampleNode.createChild('code').textContent = example.codeSnippet; if (example.comment) { exampleNode.createChild('span', 'comment').textContent = example.comment(); } } if (IssuesManager.RelatedIssue.hasIssueOfCategory( this.request, IssuesManager.Issue.IssueCategory.CrossOriginEmbedderPolicy)) { const link = document.createElement('div'); link.classList.add('devtools-link'); link.onclick = (): void => { Host.userMetrics.issuesPanelOpenedFrom(Host.UserMetrics.IssueOpener.LearnMoreLinkCOEP); IssuesManager.RelatedIssue.reveal(this.request, IssuesManager.Issue.IssueCategory.CrossOriginEmbedderPolicy); }; const text = document.createElement('span'); text.classList.add('devtools-link'); text.textContent = i18nString(UIStrings.learnMoreInTheIssuesTab); link.appendChild(text); link.prepend(UI.Icon.Icon.create('largeicon-breaking-change', 'icon')); callToActionBody.appendChild(link); } else if (header.details.link) { const link = UI.XLink.XLink.create(header.details.link.url, i18nString(UIStrings.learnMore), 'link'); link.prepend(UI.Icon.Icon.create('largeicon-link')); callToActionBody.appendChild(link); } } return fragment; } private refreshURL(): void { const requestURL = this.request.url(); this.urlItem.title = this.formatHeader(i18nString(UIStrings.requestUrl), requestURL); this.addEntryContextMenuHandler(this.urlItem, requestURL); } private populateTreeElementWithSourceText(treeElement: UI.TreeOutline.TreeElement, sourceText: string|null): void { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/naming-convention const max_len = 3000; const text = (sourceText || '').trim(); const trim = text.length > max_len; const sourceTextElement = document.createElement('span'); sourceTextElement.classList.add('header-value'); sourceTextElement.classList.add('source-code'); sourceTextElement.textContent = trim ? text.substr(0, max_len) : text; const sourceTreeElement = new UI.TreeOutline.TreeElement(sourceTextElement); treeElement.removeChildren(); treeElement.appendChild(sourceTreeElement); if (!trim) { return; } const showMoreButton = document.createElement('button'); showMoreButton.classList.add('request-headers-show-more-button'); showMoreButton.textContent = i18nString(UIStrings.showMore); function showMore(): void { showMoreButton.remove(); sourceTextElement.textContent = text; sourceTreeElement.listItemElement.removeEventListener('contextmenu', onContextMenuShowMore); } showMoreButton.addEventListener('click', showMore); function onContextMenuShowMore(event: Event): void { const contextMenu = new UI.ContextMenu.ContextMenu(event); const section = contextMenu.newSection(); section.appendItem(i18nString(UIStrings.showMore), showMore); contextMenu.show(); } sourceTreeElement.listItemElement.addEventListener('contextmenu', onContextMenuShowMore); sourceTextElement.appendChild(showMoreButton); } private refreshRequestHeaders(): void { const treeElement = this.requestHeadersCategory; const headers = this.request.requestHeaders().slice(); headers.sort(function(a, b) { return Platform.StringUtilities.compare(a.name.toLowerCase(), b.name.toLowerCase()); }); const headersText = this.request.requestHeadersText(); if (this.showRequestHeadersText && headersText) { this.refreshHeadersText(i18nString(UIStrings.requestHeaders), headers.length, headersText, treeElement); } else { this.refreshHeaders(i18nString(UIStrings.requestHeaders), headers, treeElement, headersText === undefined); } if (headersText) { const toggleButton = this.createHeadersToggleButton(this.showRequestHeadersText); toggleButton.addEventListener('click', this.toggleRequestHeadersText.bind(this), false); treeElement.listItemElement.appendChild(toggleButton); } } private refreshResponseHeaders(): void { const treeElement = this.responseHeadersCategory; const headers = this.request.sortedResponseHeaders.slice(); const headersText = this.request.responseHeadersText; if (this.showResponseHeadersText) { this.refreshHeadersText(i18nString(UIStrings.responseHeaders), headers.length, headersText, treeElement); } else { const headersWithIssues = []; if (this.request.wasBlocked()) { const headerWithIssues = BlockedReasonDetails.get((this.request.blockedReason() as Protocol.Network.BlockedReason)); if (headerWithIssues) { headersWithIssues.push(headerWithIssues); } } this.refreshHeaders( i18nString(UIStrings.responseHeaders), mergeHeadersWithIssues(headers, headersWithIssues), treeElement, /* provisional */ false, this.request.blockedResponseCookies()); } if (headersText) { const toggleButton = this.createHeadersToggleButton(this.showResponseHeadersText); toggleButton.addEventListener('click', this.toggleResponseHeadersText.bind(this), false); treeElement.listItemElement.appendChild(toggleButton); } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any function mergeHeadersWithIssues(headers: any[], headersWithIssues: any[]): any[] { let i = 0, j = 0; const result = []; while (i < headers.length || j < headersWithIssues.length) { if (i < headers.length && (j >= headersWithIssues.length || headers[i].name < headersWithIssues[j].name)) { result.push({...headers[i++], headerNotSet: false}); } else if ( j < headersWithIssues.length && (i >= headers.length || headers[i].name > headersWithIssues[j].name)) { result.push({...headersWithIssues[j++], headerNotSet: true}); } else if ( i < headers.length && j < headersWithIssues.length && headers[i].name === headersWithIssues[j].name) { result.push({...headersWithIssues[j++], ...headers[i++], headerNotSet: false}); } } return result; } } private refreshHTTPInformation(): void { const requestMethodElement = this.requestMethodItem; requestMethodElement.hidden = !this.request.statusCode; const statusCodeElement = this.statusCodeItem; statusCodeElement.hidden = !this.request.statusCode; if (this.request.statusCode) { const statusCodeFragment = document.createDocumentFragment(); statusCodeFragment.createChild('div', 'header-name').textContent = i18nString(UIStrings.statusCode) + ': '; statusCodeFragment.createChild('span', 'header-separator'); const statusCodeImage = (statusCodeFragment.createChild('span', 'resource-status-image', 'dt-icon-label') as UI.UIUtils.DevToolsIconLabel); UI.Tooltip.Tooltip.install(statusCodeImage, this.request.statusCode + ' ' + this.request.statusText); if (this.request.statusCode < 300 || this.request.statusCode === 304) { statusCodeImage.type = 'smallicon-green-ball'; } else if (this.request.statusCode < 400) { statusCodeImage.type = 'smallicon-orange-ball'; } else { statusCodeImage.type = 'smallicon-red-ball'; } requestMethodElement.title = this.formatHeader(i18nString(UIStrings.requestMethod), this.request.requestMethod); const statusTextElement = statusCodeFragment.createChild('div', 'header-value source-code'); let statusText = this.request.statusCode + ' ' + this.request.statusText; if (this.request.cachedInMemory()) { statusText += ' ' + i18nString(UIStrings.fromMemoryCache); statusTextElement.classList.add('status-from-cache'); } else if (this.request.fetchedViaServiceWorker) { statusText += ' ' + i18nString(UIStrings.fromServiceWorker); statusTextElement.classList.add('status-from-cache'); } else if (this.request.redirectSourceSignedExchangeInfoHasNoErrors()) { statusText += ' ' + i18nString(UIStrings.fromSignedexchange); statusTextElement.classList.add('status-from-cache'); } else if (this.request.webBundleInnerRequestInfo()) { statusText += ' ' + i18nString(UIStrings.fromWebBundle); statusTextElement.classList.add('status-from-cache'); } else if (this.request.fromPrefetchCache()) { statusText += ' ' + i18nString(UIStrings.fromPrefetchCache); statusTextElement.classList.add('status-from-cache'); } else if (this.request.cached()) { statusText += ' ' + i18nString(UIStrings.fromDiskCache); statusTextElement.classList.add('status-from-cache'); } statusTextElement.textContent = statusText; statusCodeElement.title = statusCodeFragment; } } private refreshHeadersTitle(title: string, headersTreeElement: UI.TreeOutline.TreeElement, headersLength: number): void { headersTreeElement.listItemElement.removeChildren(); headersTreeElement.listItemElement.createChild('div', 'selection fill'); UI.UIUtils.createTextChild(headersTreeElement.listItemElement, title); const headerCount = `\xA0(${headersLength})`; headersTreeElement.listItemElement.createChild('span', 'header-count').textContent = headerCount; } private refreshHeaders( title: string, headers: SDK.NetworkRequest.NameValue[], headersTreeElement: UI.TreeOutline.TreeElement, provisionalHeaders?: boolean, blockedResponseCookies?: SDK.NetworkRequest.BlockedSetCookieWithReason[]): void { headersTreeElement.removeChildren(); const length = headers.length; this.refreshHeadersTitle(title, headersTreeElement, length); if (provisionalHeaders) { let cautionText; let cautionTitle = ''; if (this.request.cachedInMemory() || this.request.cached()) { cautionText = i18nString(UIStrings.provisionalHeadersAreShownS); cautionTitle = i18nString(UIStrings.onlyProvisionalHeadersAre); } else { cautionText = i18nString(UIStrings.provisionalHeadersAreShown); } const cautionElement = document.createElement('div'); cautionElement.classList.add('request-headers-caution'); UI.Tooltip.Tooltip.install(cautionElement, cautionTitle); (cautionElement.createChild('span', '', 'dt-icon-label') as UI.UIUtils.DevToolsIconLabel).type = 'smallicon-warning'; cautionElement.createChild('div', 'caution').textContent = cautionText; const cautionTreeElement = new UI.TreeOutline.TreeElement(cautionElement); cautionElement.createChild('div', 'learn-more') .appendChild(UI.XLink.XLink.create( 'https://developer.chrome.com/docs/devtools/network/reference/#provisional-headers', i18nString(UIStrings.learnMore))); headersTreeElement.appendChild(cautionTreeElement); } const blockedCookieLineToReasons = new Map<string, Protocol.Network.SetCookieBlockedReason[]>(); if (blockedResponseCookies) { blockedResponseCookies.forEach(blockedCookie => { blockedCookieLineToReasons.set(blockedCookie.cookieLine, blockedCookie.blockedReasons); }); } headersTreeElement.hidden = !length && !provisionalHeaders; for (const header of headers) { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any const headerTreeElement = new UI.TreeOutline.TreeElement(this.formatHeaderObject((header as any))); headerNames.set(headerTreeElement, header.name); const headerId = header.name.toLowerCase(); if (headerId === 'set-cookie') { const matchingBlockedReasons = blockedCookieLineToReasons.get(header.value); if (matchingBlockedReasons) { const icon = UI.Icon.Icon.create('smallicon-warning', ''); headerTreeElement.listItemElement.appendChild(icon); let titleText = ''; for (const blockedReason of matchingBlockedReasons) { if (titleText) { titleText += '\n'; } titleText += SDK.NetworkRequest.setCookieBlockedReasonToUiString(blockedReason); } UI.Tooltip.Tooltip.install(icon, titleText); } } this.addEntryContextMenuHandler(headerTreeElement, header.value); headersTreeElement.appendChild(headerTreeElement); if (headerId === 'x-client-data') { const data = ClientVariations.parseClientVariations(header.value); const output = ClientVariations.formatClientVariations( data, i18nString(UIStrings.activeClientExperimentVariation), i18nString(UIStrings.activeClientExperimentVariationIds)); const wrapper = document.createElement('div'); wrapper.classList.add('x-client-data-details'); UI.UIUtils.createTextChild(wrapper, i18nString(UIStrings.decoded)); const div = wrapper.createChild('div'); div.classList.add('source-code'); div.textContent = output; headerTreeElement.listItemElement.appendChild(wrapper); } } } private refreshHeadersText( title: string, count: number, headersText: string, headersTreeElement: UI.TreeOutline.TreeElement): void { this.populateTreeElementWithSourceText(headersTreeElement, headersText); this.refreshHeadersTitle(title, headersTreeElement, count); } private refreshRemoteAddress(): void { const remoteAddress = this.request.remoteAddress(); const treeElement = this.remoteAddressItem; treeElement.hidden = !remoteAddress; if (remoteAddress) { treeElement.title = this.formatHeader(i18nString(UIStrings.remoteAddress), remoteAddress); } } private refreshReferrerPolicy(): void { const referrerPolicy = this.request.referrerPolicy(); const treeElement = this.referrerPolicyItem; treeElement.hidden = !referrerPolicy; if (referrerPolicy) { treeElement.title = this.formatHeader(i18nString(UIStrings.referrerPolicy), referrerPolicy); } } private toggleRequestHeadersText(event: Event): void { this.showRequestHeadersText = !this.showRequestHeadersText; this.refreshRequestHeaders(); event.consume(); } private toggleResponseHeadersText(event: Event): void { this.showResponseHeadersText = !this.showResponseHeadersText; this.refreshResponseHeaders(); event.consume(); } private createToggleButton(title: string): Element { const button = document.createElement('span'); button.classList.add('header-toggle'); button.textContent = title; return button; } private createHeadersToggleButton(isHeadersTextShown: boolean): Element { const toggleTitle = isHeadersTextShown ? i18nString(UIStrings.viewParsed) : i18nString(UIStrings.viewSource); return this.createToggleButton(toggleTitle); } private clearHighlight(): void { if (this.highlightedElement) { this.highlightedElement.listItemElement.classList.remove('header-highlight'); } this.highlightedElement = null; } private revealAndHighlight(category: UI.TreeOutline.TreeElement|null, name?: string): void { this.clearHighlight(); if (!category) { return; } if (name) { for (const element of category.children()) { // HTTP headers are case insensitive. if (headerNames.get(element)?.toUpperCase() !== name.toUpperCase()) { continue; } this.highlightedElement = element; element.reveal(); element.listItemElement.classList.add('header-highlight'); return; } } // If there wasn't a match, reveal the first element of the category (without highlighting it). if (category.childCount() > 0) { category.childAt(0)?.reveal(); } } private getCategoryForSection(section: NetworkForward.UIRequestLocation.UIHeaderSection): Category { switch (section) { case NetworkForward.UIRequestLocation.UIHeaderSection.General: return this.root; case NetworkForward.UIRequestLocation.UIHeaderSection.Request: return this.requestHeadersCategory; case NetworkForward.UIRequestLocation.UIHeaderSection.Response: return this.responseHeadersCategory; } } revealHeader(section: NetworkForward.UIRequestLocation.UIHeaderSection, header?: string): void { this.revealAndHighlight(this.getCategoryForSection(section), header); } } const headerNames = new WeakMap<UI.TreeOutline.TreeElement, string>(); export class Category extends UI.TreeOutline.TreeElement { toggleOnClick: boolean; private readonly expandedSetting: Common.Settings.Setting<boolean>; expanded: boolean; constructor(root: UI.TreeOutline.TreeOutline, name: string, title?: string) { super(title || '', true); this.toggleOnClick = true; this.hidden = true; this.expandedSetting = Common.Settings.Settings.instance().createSetting('request-info-' + name + '-category-expanded', true); this.expanded = this.expandedSetting.get(); root.appendChild(this); } createLeaf(): UI.TreeOutline.TreeElement { const leaf = new UI.TreeOutline.TreeElement(); this.appendChild(leaf); return leaf; } onexpand(): void { this.expandedSetting.set(true); } oncollapse(): void { this.expandedSetting.set(false); } } /** * Returns the value for the `trigger-data` search parameter iff the provided * url is a valid attribution redirect as specified by the Attribution * Reporting API. */ function getTriggerDataFromAttributionRedirect(url: URL): string|null { if (url.pathname === '/.well-known/attribution-reporting/trigger-attribution' && url.searchParams.has('trigger-data')) { return url.searchParams.get('trigger-data'); } return null; } interface BlockedReasonDetailDescriptor { name: string; value: Object|null; headerValueIncorrect: boolean|null; details: { explanation: () => string, examples: Array<{ codeSnippet: string, comment?: (() => string), }>, link: { url: string, }|null, }; headerNotSet: boolean|null; } const BlockedReasonDetails = new Map<Protocol.Network.BlockedReason, BlockedReasonDetailDescriptor>([ [ Protocol.Network.BlockedReason.CoepFrameResourceNeedsCoepHeader, { name: 'cross-origin-embedder-policy', value: null, headerValueIncorrect: null, details: { explanation: i18nLazyString(UIStrings.toEmbedThisFrameInYourDocument), examples: [{codeSnippet: 'Cross-Origin-Embedder-Policy: require-corp', comment: undefined}], link: {url: 'https://web.dev/coop-coep/'}, }, headerNotSet: null, }, ], [ Protocol.Network.BlockedReason.CorpNotSameOriginAfterDefaultedToSameOriginByCoep, { name: 'cross-origin-resource-policy', value: null, headerValueIncorrect: null, details: { explanation: i18nLazyString(UIStrings.toUseThisResourceFromADifferent), examples: [ { codeSnippet: 'Cross-Origin-Resource-Policy: same-site', comment: i18nLazyString(UIStrings.chooseThisOptionIfTheResourceAnd), }, { codeSnippet: 'Cross-Origin-Resource-Policy: cross-origin', comment: i18nLazyString(UIStrings.onlyChooseThisOptionIfAn), }, ], link: {url: 'https://web.dev/coop-coep/'}, }, headerNotSet: null, }, ], [ Protocol.Network.BlockedReason.CoopSandboxedIframeCannotNavigateToCoopPage, { name: 'cross-origin-opener-policy', value: null, headerValueIncorrect: false, details: { explanation: i18nLazyString(UIStrings.thisDocumentWasBlockedFrom), examples: [], link: {url: 'https://web.dev/coop-coep/'}, }, headerNotSet: null, }, ], [ Protocol.Network.BlockedReason.CorpNotSameSite, { name: 'cross-origin-resource-policy', value: null, headerValueIncorrect: true, details: { explanation: i18nLazyString(UIStrings.toUseThisResourceFromADifferentSite), examples: [ { codeSnippet: 'Cross-Origin-Resource-Policy: cross-origin', comment: i18nLazyString(UIStrings.onlyChooseThisOptionIfAn), }, ], link: null, }, headerNotSet: null, }, ], [ Protocol.Network.BlockedReason.CorpNotSameOrigin, { name: 'cross-origin-resource-policy', value: null, headerValueIncorrect: true, details: { explanation: i18nLazyString(UIStrings.toUseThisResourceFromADifferentOrigin), examples: [ { codeSnippet: 'Cross-Origin-Resource-Policy: same-site', comment: i18nLazyString(UIStrings.chooseThisOptionIfTheResourceAnd), }, { codeSnippet: 'Cross-Origin-Resource-Policy: cross-origin', comment: i18nLazyString(UIStrings.onlyChooseThisOptionIfAn), }, ], link: null, }, headerNotSet: null, }, ], ]);
the_stack
import * as tape from 'tape'; import * as sinon from 'sinon'; import {join} from 'path'; import {readFileSync} from 'fs'; import {TwingTokenParser} from "../../../../../src/lib/token-parser"; import {Token, TokenType} from "twig-lexer"; import {TwingNode, TwingNodeType} from "../../../../../src/lib/node"; import {TwingEnvironment, TwingTemplatesModule} from "../../../../../src/lib/environment"; import {TwingExtension} from "../../../../../src/lib/extension"; import {TwingFilter} from "../../../../../src/lib/filter"; import {TwingOperator, TwingOperatorAssociativity, TwingOperatorType} from "../../../../../src/lib/operator"; import {TwingFunction} from "../../../../../src/lib/function"; import {TwingTest} from "../../../../../src/lib/test"; import {TwingBaseNodeVisitor} from "../../../../../src/lib/base-node-visitor"; import {TwingParser} from "../../../../../src/lib/parser"; import {TwingTokenStream} from "../../../../../src/lib/token-stream"; import {TwingLexer} from "../../../../../src/lib/lexer"; import {MockLoader} from "../../../../mock/loader"; import {TwingNodeModule} from "../../../../../src/lib/node/module"; import {TwingSource} from "../../../../../src/lib/source"; import {TwingLoaderArray} from "../../../../../src/lib/loader/array"; import {TwingEnvironmentNode} from "../../../../../src/lib/environment/node"; import {TwingCacheFilesystem} from "../../../../../src/lib/cache/filesystem"; import {MockEnvironment} from "../../../../mock/environment"; import {MockCache} from "../../../../mock/cache"; import {MockTemplate} from "../../../../mock/template"; import {TwingCacheNull} from "../../../../../src/lib/cache/null"; import {TwingTemplate} from "../../../../../src/lib/template"; import {MappingItem, SourceMapConsumer} from "source-map"; import {TwingLoaderFilesystem} from "../../../../../src/lib/loader/filesystem"; import {TwingNodeText} from "../../../../../src/lib/node/text"; const tmp = require('tmp'); function escapingStrategyCallback(name: string) { return name; } class TwingTestsEnvironmentTestTokenParser extends TwingTokenParser { parse(token: Token): TwingNode { return null; } getTag() { return 'test'; } } class TwingTestsEnvironmentTestNodeVisitor extends TwingBaseNodeVisitor { getPriority() { return 0; } protected doEnterNode(node: TwingNode, env: TwingEnvironment): TwingNode { return node; } protected doLeaveNode(node: TwingNode, env: TwingEnvironment): TwingNode { return node; } } class TwingTestsEnvironmentTestExtension extends TwingExtension { constructor() { super(); } getTokenParsers() { return [ new TwingTestsEnvironmentTestTokenParser(), ]; } getNodeVisitors() { return [ new TwingTestsEnvironmentTestNodeVisitor(), ]; } getFilters() { return [ new TwingFilter('foo_filter', () => { return Promise.resolve(); }, []) ]; } getTests() { return [ new TwingTest('foo_test', () => { return Promise.resolve(true); }, []), ]; } getFunctions() { return [ new TwingFunction('foo_function', () => Promise.resolve(), []), ]; } getOperators() { return [ new TwingOperator('foo_unary', TwingOperatorType.UNARY, 10, () => null, TwingOperatorAssociativity.LEFT), new TwingOperator('foo_binary', TwingOperatorType.BINARY, 10, () => null, TwingOperatorAssociativity.LEFT), ]; } } class TwingTestsEnvironmentTestExtensionRegression extends TwingTestsEnvironmentTestExtension { getFilters() { return [ new TwingFilter('foo_filter', () => Promise.resolve(), []) ]; } getFunctions() { return [ new TwingFunction('foo_function', () => Promise.resolve(), []) ]; } } class TwingTestsEnvironmentParserBar extends TwingParser { parse(stream: TwingTokenStream, test: any, dropNeedle: any): TwingNodeModule { return new TwingNodeModule( new TwingNodeText('bar', 1, 1), new TwingNode(), new TwingNode(), new TwingNode(), new TwingNode(), [], new TwingSource('', 'index') ); } } class TwingTestsEnvironmentLexerBar extends TwingLexer { tokenize(source: string) { return [new Token(TokenType.TEXT, 'bar', 1, 1)]; } } class TwingTestsEnvironmentParserError extends TwingParser { parse(stream: TwingTokenStream, test: any, dropNeedle: any): TwingNodeModule { throw new Error('Parser error "foo".'); } } function getMockLoader(templateName: string, templateContent: string) { let loader = new MockLoader(); sinon.stub(loader, 'getSourceContext').withArgs(templateName).returns(Promise.resolve(new TwingSource(templateContent, templateName))); sinon.stub(loader, 'getCacheKey').withArgs(templateName).returns(Promise.resolve(templateName)); return loader; } tape('environment', (test) => { test.test('autoescapeOption', async (test) => { let loader = new TwingLoaderArray({ 'html': '{{ foo }} {{ foo }}', 'js': '{{ bar }} {{ bar }}', }); let twing = new TwingEnvironmentNode(loader, { debug: true, cache: false, autoescape: escapingStrategyCallback }); test.same(await twing.render('html', {'foo': 'foo<br/ >'}), 'foo&lt;br/ &gt; foo&lt;br/ &gt;'); test.same(await twing.render('js', {'bar': 'foo<br/ >'}), 'foo\\u003Cbr\\/\\u0020\\u003E foo\\u003Cbr\\/\\u0020\\u003E'); test.end(); }); test.test('globals', async (test) => { let loader = new MockLoader(); sinon.stub(loader, 'getSourceContext').returns(Promise.resolve(new TwingSource('', ''))); // globals can be added after calling getGlobals let twing = new TwingEnvironmentNode(loader); twing.addGlobal('foo', 'foo'); twing.getGlobals(); twing.addGlobal('foo', 'bar'); let globals = twing.getGlobals(); test.same(globals.get('foo'), 'bar'); // globals can be modified after a template has been loaded twing = new TwingEnvironmentNode(loader); twing.addGlobal('foo', 'foo'); twing.getGlobals(); await twing.loadTemplate('index'); twing.addGlobal('foo', 'bar'); globals = twing.getGlobals(); test.same(globals.get('foo'), 'bar'); // globals can be modified after extensions init twing = new TwingEnvironmentNode(loader); twing.addGlobal('foo', 'foo'); twing.getGlobals(); twing.getFunctions(); twing.addGlobal('foo', 'bar'); globals = twing.getGlobals(); test.same(globals.get('foo'), 'bar'); // globals can be modified after extensions and a template has been loaded let arrayLoader = new TwingLoaderArray({index: '{{foo}}'}); twing = new TwingEnvironmentNode(arrayLoader); twing.addGlobal('foo', 'foo'); twing.getGlobals(); twing.getFunctions(); await twing.loadTemplate('index'); twing.addGlobal('foo', 'bar'); globals = twing.getGlobals(); test.same(globals.get('foo'), 'bar'); twing = new TwingEnvironmentNode(arrayLoader); twing.getGlobals(); twing.addGlobal('foo', 'bar'); let template = await twing.loadTemplate('index'); test.same(await template.render({}), 'bar'); // globals cannot be added after a template has been loaded twing = new TwingEnvironmentNode(loader); twing.addGlobal('foo', 'foo'); twing.getGlobals(); twing.addGlobal('foo', 'bar'); await twing.loadTemplate('index'); try { twing.addGlobal('bar', 'bar'); test.fail(); } catch (e) { test.false(twing.getGlobals().get('bar')); } // globals cannot be added after extensions init twing = new TwingEnvironmentNode(loader); twing.addGlobal('foo', 'foo'); twing.getGlobals(); twing.getFunctions(); try { twing.addGlobal('bar', 'bar'); test.fail(); } catch (e) { test.false(twing.getGlobals().get('bar')); } // globals cannot be added after extensions and a template has been loaded twing = new TwingEnvironmentNode(loader); twing.addGlobal('foo', 'foo'); twing.getGlobals(); twing.getFunctions(); await twing.loadTemplate('index'); try { twing.addGlobal('bar', 'bar'); test.fail(); } catch (e) { test.false(twing.getGlobals().get('bar')); } // test adding globals after a template has been loaded without call to getGlobals twing = new TwingEnvironmentNode(loader); await twing.loadTemplate('index'); try { twing.addGlobal('bar', 'bar'); test.fail(); } catch (e) { test.false(twing.getGlobals().get('bar')); } test.end(); }); test.test('testExtensionsAreNotInitializedWhenRenderingACompiledTemplate', async (test) => { let cache = new TwingCacheFilesystem(tmp.dirSync().name); let options = {cache: cache, auto_reload: false, debug: false}; // force compilation let loader = new TwingLoaderArray({index: '{{ foo }}'}); let twing = new MockEnvironment(loader, options); let key = await cache.generateKey('index', await twing.getTemplateHash('index')); await cache.write(key, twing.compileSource(new TwingSource('{{ foo }}', 'index'))); // render template let output = await twing.render('index', {foo: 'bar'}); test.same(output, 'bar'); test.end(); }); test.test('autoReloadCacheMiss', async (test) => { let templateName = 'autoReloadCacheMiss'; let templateContent = 'autoReloadCacheMiss'; let cache = new MockCache(); let loader = getMockLoader(templateName, templateContent); let twing = new MockEnvironment(loader, { cache: cache, auto_reload: true, debug: false }); let generateKeyStub = sinon.stub(cache, 'generateKey').returns(Promise.resolve('key')); let getTimestampStub = sinon.stub(cache, 'getTimestamp').returns(Promise.resolve(0)); let writeSpy = sinon.spy(cache, 'write'); let loadSpy = sinon.spy(cache, 'load'); let isFreshStub = sinon.stub(loader, 'isFresh').returns(Promise.resolve(false)); await twing.loadTemplate(templateName); sinon.assert.calledOnce(generateKeyStub); sinon.assert.calledOnce(getTimestampStub); sinon.assert.calledOnce(isFreshStub); test.same(writeSpy.callCount, 1); test.same(loadSpy.callCount, 1); test.end(); }); test.test('autoReloadCacheHit', async (test) => { let templateName = 'autoReloadCacheHit'; let templateContent = 'autoReloadCacheHit'; let cache = new MockCache(); let loader = getMockLoader(templateName, templateContent); let twing = new MockEnvironment(loader, {cache: cache, auto_reload: true, debug: false}); let generateKeyStub = sinon.stub(cache, 'generateKey').returns(Promise.resolve('key')); let getTimestampStub = sinon.stub(cache, 'getTimestamp').returns(Promise.resolve(0)); let writeSpy = sinon.spy(cache, 'write'); let loadSpy = sinon.spy(cache, 'load'); let isFreshStub = sinon.stub(loader, 'isFresh').returns(Promise.resolve(true)); await twing.loadTemplate(templateName); test.same(generateKeyStub.callCount, 1, 'generateKey should be called once'); test.same(getTimestampStub.callCount, 1, 'getTimestamp should be called once'); test.same(isFreshStub.callCount, 1, 'isFresh should be called once'); test.same(writeSpy.callCount, 0, 'write should not be called'); test.true(loadSpy.callCount >= 1, 'load should be called at least once'); test.end(); }); test.test('autoReloadOutdatedCacheHit', async (test) => { let templateName = 'autoReloadOutdatedCacheHit'; let templateContent = 'autoReloadOutdatedCacheHit'; let cache = new MockCache(); let loader = getMockLoader(templateName, templateContent); let twing = new MockEnvironment(loader, {cache: cache, auto_reload: true, debug: false}); let now = new Date(); let generateKeyStub = sinon.stub(cache, 'generateKey').returns(Promise.resolve('key')); let getTimestampStub = sinon.stub(cache, 'getTimestamp').returns(Promise.resolve(now)); let writeSpy = sinon.spy(cache, 'write'); let loadSpy = sinon.spy(cache, 'load'); let isFreshStub = sinon.stub(loader, 'isFresh').returns(Promise.resolve(false)); await twing.loadTemplate(templateName); sinon.assert.calledOnce(generateKeyStub); sinon.assert.calledOnce(getTimestampStub); sinon.assert.calledOnce(isFreshStub); test.same(writeSpy.callCount, 1, 'write should be called once'); test.same(loadSpy.callCount, 1, 'load should be called once'); test.end(); }); test.test('sourceMapChangeCacheMiss', async (test) => { let templateName = 'sourceMapChangeCacheMiss'; let templateContent = 'sourceMapChangeCacheMiss'; let cache = new MockCache(); let loader = getMockLoader(templateName, templateContent); let twing = new TwingEnvironmentNode(loader, { cache: cache, source_map: true }); let firstKey: string = null; let secondKey: string = null; sinon.stub(cache, 'generateKey').callsFake((name, className) => { return Promise.resolve(className); }); sinon.stub(cache, 'load').callsFake((key) => { if (firstKey) { secondKey = key; } else { firstKey = key; } return Promise.resolve(() => { return new Map(); }); }); await twing.loadTemplate(templateName); twing = new TwingEnvironmentNode(loader, { cache: cache, source_map: false }); await twing.loadTemplate(templateName); test.notEquals(firstKey, secondKey); test.end(); }); test.test('autoescapeChangeCacheMiss', async (test) => { let templateName = 'autoescapeChangeCacheMiss'; let templateContent = 'autoescapeChangeCacheMiss'; let cache = new MockCache(); let loader = getMockLoader(templateName, templateContent); let twing = new TwingEnvironmentNode(loader, { cache: cache, autoescape: 'html' }); let firstKey: string = null; let secondKey: string = null; sinon.stub(cache, 'generateKey').callsFake((name, className) => { return Promise.resolve(className); }); sinon.stub(cache, 'load').callsFake((key) => { if (firstKey) { secondKey = key; } else { firstKey = key; } return Promise.resolve(() => { return new Map() }); }); await twing.loadTemplate(templateName); twing = new TwingEnvironmentNode(loader, { cache: cache, autoescape: false }); await twing.loadTemplate(templateName); test.notEquals(firstKey, secondKey); test.end(); }); test.test('addExtension', (test) => { let twing = new TwingEnvironmentNode(new MockLoader()); let ext = new TwingTestsEnvironmentTestExtension(); twing.addExtension(ext, 'TwingTestsEnvironmentTestExtension'); test.true(twing.hasExtension('TwingTestsEnvironmentTestExtension')); test.true(twing.getTags().has('test')); test.true(twing.getFilters().has('foo_filter')); test.true(twing.getFunctions().has('foo_function')); test.true(twing.getTests().has('foo_test')); test.true(twing.getUnaryOperators().has('foo_unary')); test.true(twing.getBinaryOperators().has('foo_binary')); let visitors = twing.getNodeVisitors(); let found = false; for (let visitor of visitors) { if (visitor instanceof TwingTestsEnvironmentTestNodeVisitor) { found = true; } } test.true(found); test.test('with explicit name', (test) => { let twing = new TwingEnvironmentNode(new MockLoader()); let ext1 = new TwingTestsEnvironmentTestExtension(); let ext2 = new TwingTestsEnvironmentTestExtension(); twing.addExtension(ext1, 'ext1'); twing.addExtension(ext2, 'ext2'); test.equals(twing.getExtension('ext1'), ext1); test.equals(twing.getExtension('ext2'), ext2); test.end(); }); test.test('support pre-1.2.0 API', (test) => { let twing = new TwingEnvironmentNode(new MockLoader()); let ext = new TwingTestsEnvironmentTestExtensionRegression(); twing.addExtension(ext, 'TwingTestsEnvironmentTestExtensionRegression'); test.true(twing.getFilters().has('foo_filter')); test.true(twing.getFunctions().has('foo_function')); test.end(); }); test.end(); }); test.test('addMockExtension', (test) => { let extension = new TwingTestsEnvironmentTestExtension(); let loader = new TwingLoaderArray({page: 'hey'}); let twing = new TwingEnvironmentNode(loader); twing.addExtension(extension, 'foo'); test.same(twing.getExtension('foo'), extension); test.end(); }); test.test('overrideExtension', (test) => { let twing = new TwingEnvironmentNode(new TwingLoaderArray({})); twing.addExtension(new TwingTestsEnvironmentTestExtension(), 'TwingTestsEnvironmentTestExtension'); try { twing.addExtension(new TwingTestsEnvironmentTestExtension(), 'TwingTestsEnvironmentTestExtension'); test.fail(); } catch (e) { test.same(e.message, 'Unable to register extension "TwingTestsEnvironmentTestExtension" as it is already registered.') } test.end(); }); test.test('debug', async (test) => { class CustomEnvironment extends TwingEnvironmentNode { getTemplateHash(name: string, index: number, from: TwingSource) { return super.getTemplateHash(name, index, from); } } let env = new CustomEnvironment(new MockLoader(), { debug: false }); let templateClass = await env.getTemplateHash('foo', undefined, undefined); test.test('enable', async (test) => { env.enableDebug(); test.true(env.isDebug()); test.notSame(await env.getTemplateHash('foo', undefined, undefined), templateClass); test.end(); }); test.test('disable', async (test) => { env.disableDebug(); test.false(env.isDebug()); test.same(await env.getTemplateHash('foo', undefined, undefined), templateClass); test.end(); }); test.end(); }); test.test('autoreload', (test) => { let env = new TwingEnvironmentNode(new MockLoader(), { auto_reload: false }); test.test('enable', (test) => { env.enableAutoReload(); test.true(env.isAutoReload()); test.end(); }); test.test('disable', (test) => { env.disableAutoReload(); test.false(env.isAutoReload()); test.end(); }); test.end(); }); test.test('strict_variables', async (test) => { class CustomEnvironment extends TwingEnvironmentNode { getTemplateHash(name: string, index: number, from: TwingSource) { return super.getTemplateHash(name, index, from); } } let env = new CustomEnvironment(new MockLoader(), { strict_variables: false }); let templateClass = await env.getTemplateHash('foo', undefined, undefined); test.test('enable', async (test) => { env.enableStrictVariables(); test.true(env.isStrictVariables()); test.notSame(await env.getTemplateHash('foo', undefined, undefined), templateClass); test.end(); }); test.test('disable', async (test) => { env.disableStrictVariables(); test.false(env.isStrictVariables()); test.same(await env.getTemplateHash('foo', undefined, undefined), templateClass); test.end(); }); test.end(); }); test.test('cache', (test) => { test.test('set', (test) => { let env = new TwingEnvironmentNode(new MockLoader(), { cache: false }); env.setCache('bar'); test.same(env.getCache(), 'bar'); test.true(env.getCache(false) instanceof TwingCacheFilesystem); env.setCache(new MockCache()); test.true(env.getCache(false) instanceof MockCache); test.end(); }); test.end(); }); test.test('display', async (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({ index: 'bar' })); let data; let originalWrite = process.stdout.write; process.stdout.write = function (chunk: Buffer | string): boolean { data = chunk; process.stdout.write = originalWrite; test.same(data, 'bar'); test.end(); return true; }; await env.display('index'); }); test.test('load', async (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({ index: 'bar' })); let template = new MockTemplate(env); test.true(await env.load(template)); test.true(await env.load('index')); test.end(); }); test.test('loadTemplate', async (test) => { let env = new MockEnvironment(new TwingLoaderArray({index: 'foo'}), { cache: new MockCache() }); let template = await env.loadTemplate('index'); test.true(template instanceof MockTemplate); test.end(); }); test.test('resolveTemplate', async (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({ index: '{{ foo' })); try { await env.resolveTemplate('index', new TwingSource('', 'index')); test.fail(); } catch (e) { test.same(e.message, 'Unclosed variable opened at {1:1} in "index" at line 1.'); } try { await env.resolveTemplate('missing', new TwingSource('', 'index')); test.fail(); } catch (e) { test.same(e.message, 'Template "missing" is not defined in "index".'); } test.end(); }); test.test('parse', (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({ index: 'foo' })); env.setParser(new TwingTestsEnvironmentParserBar(env)); test.true(env.parse(env.tokenize(new TwingSource('foo', 'index')))); test.end(); }); test.test('lexer', (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({ index: 'foo' })); env.setLexer(new TwingTestsEnvironmentLexerBar(env)); test.true(env.tokenize(new TwingSource('foo', 'index')).getCurrent().test(TokenType.TEXT, 'bar')); test.end(); }); test.test('compileSource', (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({ index: 'foo' })); let source = new TwingSource('{{ foo', 'index'); try { env.compileSource(source); test.fail(); } catch (e) { test.same(e.message, 'Unclosed variable opened at {1:1} in "index" at line 1.'); } env.setParser(new TwingTestsEnvironmentParserError(env)); source = new TwingSource('{{ foo.bar }}', 'index'); try { env.compileSource(source); test.fail(); } catch (e) { test.same(e.message, 'An exception has been thrown during the compilation of a template ("Parser error "foo".") in "index".'); } test.end(); }); test.test('extensions', (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({ index: 'foo' })); let extension = new TwingTestsEnvironmentTestExtension(); env.addExtensions(new Map([['TwingTestsEnvironmentTestExtension', extension]])); test.true(env.getExtensions().has('TwingTestsEnvironmentTestExtension')); test.end(); }); test.test('nodeVisitors', (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({ index: 'foo' })); let nodeVisitor = new TwingTestsEnvironmentTestNodeVisitor(); env.addNodeVisitor(nodeVisitor); test.true(env.getNodeVisitors().includes(nodeVisitor)); test.end(); }); test.test('should emit events', (test) => { test.test('template', async (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({ index: '{% include "foo" %}', foo: 'Foo' })); let templates: string[] = []; env.on('template', (name) => { templates.push(name); }); await env.render('index'); test.same(templates, [ 'index', 'foo' ]); test.end(); }); test.end(); }); test.test('source map support', (test) => { let fixturesPath = 'test/tests/unit/lib/environment/fixtures'; let loader = new TwingLoaderFilesystem(fixturesPath); loader.addPath(join(fixturesPath, 'css'), 'Css'); let indexSource = join(fixturesPath, 'css', 'index.css.twig'); let colorSource = join(fixturesPath, 'css', 'partial/color.css.twig'); let backgroundSource = join(fixturesPath, 'css', 'partial/background.css.twig'); test.test('when source_map is set to true', async (test) => { let env = new TwingEnvironmentNode(loader, { source_map: true, cache: 'tmp/sm' }); // 1.foo { // 2 text-align: right; // 3 color: whitesmoke; // 4 background-color: brown; // 5background-image: url("foo.png"); // 6 display: block; // 7} await env.render('css/index.css.twig', { align: 'right' }); let map = env.getSourceMap(); test.same(typeof map, 'string'); let consumer = new SourceMapConsumer(JSON.parse(map)); let mappings: MappingItem[] = []; consumer.eachMapping((mapping: MappingItem) => { console.warn(mapping); mappings.push({ source: mapping.source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name }); }); let sourceContent = consumer.sourceContentFor(indexSource, true); test.same(sourceContent, readFileSync(indexSource, 'UTF-8')); test.same( mappings, [ { source: indexSource, generatedLine: 1, generatedColumn: 0, originalLine: 1, originalColumn: 0, name: 'text' }, { source: indexSource, generatedLine: 2, generatedColumn: 0, originalLine: 1, originalColumn: 0, name: 'text' }, { source: indexSource, generatedLine: 2, generatedColumn: 16, originalLine: 2, originalColumn: 16, name: 'print' }, { source: indexSource, generatedLine: 2, generatedColumn: 21, originalLine: 2, originalColumn: 27, name: 'text' }, { source: indexSource, generatedLine: 3, generatedColumn: 0, originalLine: 2, originalColumn: 27, name: 'text' }, { source: colorSource, generatedLine: 3, generatedColumn: 11, originalLine: 1, originalColumn: 0, name: 'text' }, { source: indexSource, generatedLine: 3, generatedColumn: 21, originalLine: 3, originalColumn: 53, name: 'text' }, { source: indexSource, generatedLine: 4, generatedColumn: 0, originalLine: 3, originalColumn: 53, name: 'text' }, { source: backgroundSource, generatedLine: 4, generatedColumn: 4, originalLine: 1, originalColumn: 0, name: 'text' }, { source: backgroundSource, generatedLine: 5, generatedColumn: 0, originalLine: 1, originalColumn: 0, name: 'text' }, { source: indexSource, generatedLine: 6, generatedColumn: 0, originalLine: 5, originalColumn: 0, name: 'text' }, { source: indexSource, generatedLine: 7, generatedColumn: 0, originalLine: 5, originalColumn: 0, name: 'text' } ] ); test.end(); }); test.test('when source_map is set to false', async (test) => { let env = new TwingEnvironmentNode(loader, { source_map: false }); await env.render('css/index.css.twig', { align: 'right' }); let map = env.getSourceMap(); test.equals(map, null); test.end(); }); test.test('handle templates compiled without source map support', async (test) => { class CustomTemplate extends TwingTemplate { getTemplateName() { return 'foo'; } doDisplay() { return Promise.resolve(); } } class CustomCache extends TwingCacheNull { generateKey(name: string, className: string) { return Promise.resolve(className); } load(key: string): Promise<TwingTemplatesModule> { return Promise.resolve(() => { return new Map([ [0, CustomTemplate] ]); }); } } let env = new TwingEnvironmentNode(loader, { source_map: true, cache: new CustomCache() }); await env.render('css/index.css.twig'); let sourceMap = env.getSourceMap(); test.false(sourceMap); test.end(); }); test.test('with spaceless tag', async (test) => { let env = new TwingEnvironmentNode(loader, { source_map: true }); indexSource = join(fixturesPath, 'spaceless', 'index.html.twig'); // 1.foo // 2.<foo></foo> // 3.bar // 5. <foo><FOO>FOO // 5.BAROOF</FOO></foo>oof let render = await env.render('spaceless/index.html.twig', { bar: 'bar' }); test.same(render, `foo <foo></foo> bar <foo><FOO>FOO BAROOF</FOO></foo>oof`); let map = env.getSourceMap(); test.same(typeof map, 'string'); let consumer = new SourceMapConsumer(JSON.parse(map)); let mappings: MappingItem[] = []; consumer.eachMapping((mapping: MappingItem) => { mappings.push({ source: mapping.source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name }); }); test.same( mappings, [ { source: 'test/tests/unit/lib/environment/fixtures/spaceless/index.html.twig', generatedLine: 1, generatedColumn: 0, originalLine: 1, originalColumn: 0, name: 'text' }, { source: 'test/tests/unit/lib/environment/fixtures/spaceless/index.html.twig', generatedLine: 2, generatedColumn: 0, originalLine: 3, originalColumn: 0, name: 'text' }, { source: 'test/tests/unit/lib/environment/fixtures/spaceless/index.html.twig', generatedLine: 3, generatedColumn: 0, originalLine: 6, originalColumn: 0, name: 'print' }, { source: 'test/tests/unit/lib/environment/fixtures/spaceless/index.html.twig', generatedLine: 3, generatedColumn: 3, originalLine: 6, originalColumn: 9, name: 'text' }, { source: 'test/tests/unit/lib/environment/fixtures/spaceless/index.html.twig', generatedLine: 4, generatedColumn: 0, originalLine: 6, originalColumn: 9, name: 'text' }, { source: 'test/tests/unit/lib/environment/fixtures/spaceless/partials/foo.html.twig', generatedLine: 4, generatedColumn: 9, originalLine: 1, originalColumn: 0, name: 'text' }, { source: 'test/tests/unit/lib/environment/fixtures/spaceless/partials/foo.html.twig', generatedLine: 5, generatedColumn: 0, originalLine: 3, originalColumn: 4, name: 'print' }, { source: 'test/tests/unit/lib/environment/fixtures/spaceless/partials/foo.html.twig', generatedLine: 5, generatedColumn: 3, originalLine: 5, originalColumn: 0, name: 'text' }, { source: 'test/tests/unit/lib/environment/fixtures/spaceless/index.html.twig', generatedLine: 5, generatedColumn: 12, originalLine: 9, originalColumn: 0, name: 'text' }, { source: 'test/tests/unit/lib/environment/fixtures/spaceless/index.html.twig', generatedLine: 5, generatedColumn: 18, originalLine: 11, originalColumn: 0, name: 'text' } ] ); test.end(); }); test.test('handle templates coming from non-filesystem loader', async (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({ index: 'FOO' }), { source_map: true }); await env.render('index'); let sourceMap = env.getSourceMap(); test.true(sourceMap); test.end(); }); test.end(); }); test.test('createTemplate', async (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({})); let template = await env.createTemplate('foo'); test.same(template.getTemplateName(), '__string_template__2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'); template = await env.createTemplate('foo', 'foo.twig'); test.same(template.getTemplateName(), 'foo.twig (string template 2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae)'); test.end(); }); test.test('registerTemplatesModule', async (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({ foo: '' })); let loaderSpy = sinon.spy(env.getLoader(), 'getSourceContext'); env.registerTemplatesModule((c) => { return new Map([ [0, class extends c { doDisplay(context: {}, blocks: Map<string, Array<any>>): Promise<void> { return Promise.resolve(); } getTemplateName() { return 'main'; } }], [1, class extends c { doDisplay(context: {}, blocks: Map<string, Array<any>>): Promise<void> { return Promise.resolve(); } getTemplateName() { return 'embedded'; } }] ]) }, 'foo'); let actualTemplate = await env.loadTemplate('foo'); let actualEmbeddedTemplate = await env.loadTemplate('foo', 1); test.true(loaderSpy.notCalled, 'Loader should not be queried'); test.equal(actualTemplate.getTemplateName(), 'main', 'Main template should be loaded successfully'); test.equal(actualEmbeddedTemplate.getTemplateName(), 'embedded', 'Embedded template should be loaded successfully'); test.end(); }); test.test('getSourceMapNodeFactories', (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({})); let factories = env.getSourceMapNodeFactories(); test.true(factories.has(TwingNodeType.SPACELESS)); test.end(); }); test.test('checkMethodAllowed', (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({})); let obj = {}; try { env.checkMethodAllowed(obj, 'foo'); test.pass(); } catch (e) { test.fail(); } env = new TwingEnvironmentNode(new TwingLoaderArray({}), { sandboxed: true }); try { env.checkMethodAllowed(obj, 'foo'); test.fail(); } catch (e) { test.same(e.message, 'Calling "foo" method on a "Object" is not allowed.'); } test.end(); }); test.test('checkPropertyAllowed', (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({})); let obj = {}; try { env.checkPropertyAllowed(obj, 'foo'); test.pass(); } catch (e) { test.fail(); } env = new TwingEnvironmentNode(new TwingLoaderArray({}), { sandboxed: true }); try { env.checkPropertyAllowed(obj, 'foo'); test.fail(); } catch (e) { test.same(e.message, 'Calling "foo" property on a "Object" is not allowed.'); } test.end(); }); test.test('disabling the sandbox actually...disable the sandbox', async (test) => { let env = new TwingEnvironmentNode(new TwingLoaderArray({ index: '{{foo}}' }), { sandboxed: false }); let ensureToStringAllowedSpy = sinon.spy(env, 'ensureToStringAllowed'); let checkSecuritySpy = sinon.spy(env, 'checkSecurity'); let actual = await env.render('index', { foo: 'foo' }); test.true(ensureToStringAllowedSpy.notCalled, 'ensureToStringAllowed is not called'); test.true(checkSecuritySpy.notCalled, 'checkSecurity is not called'); test.same(actual, `foo`); test.end(); }); test.end(); });
the_stack
import { OperationParameter, OperationURLParameter, OperationQueryParameter } from "@azure/core-client"; import { DatabaseAccountUpdateParameters as DatabaseAccountUpdateParametersMapper, DatabaseAccountCreateUpdateParameters as DatabaseAccountCreateUpdateParametersMapper, FailoverPolicies as FailoverPoliciesMapper, RegionForOnlineOffline as RegionForOnlineOfflineMapper, DatabaseAccountRegenerateKeyParameters as DatabaseAccountRegenerateKeyParametersMapper, SqlDatabaseCreateUpdateParameters as SqlDatabaseCreateUpdateParametersMapper, ThroughputSettingsUpdateParameters as ThroughputSettingsUpdateParametersMapper, SqlContainerCreateUpdateParameters as SqlContainerCreateUpdateParametersMapper, SqlStoredProcedureCreateUpdateParameters as SqlStoredProcedureCreateUpdateParametersMapper, SqlUserDefinedFunctionCreateUpdateParameters as SqlUserDefinedFunctionCreateUpdateParametersMapper, SqlTriggerCreateUpdateParameters as SqlTriggerCreateUpdateParametersMapper, SqlRoleDefinitionCreateUpdateParameters as SqlRoleDefinitionCreateUpdateParametersMapper, SqlRoleAssignmentCreateUpdateParameters as SqlRoleAssignmentCreateUpdateParametersMapper, ContinuousBackupRestoreLocation as ContinuousBackupRestoreLocationMapper, MongoDBDatabaseCreateUpdateParameters as MongoDBDatabaseCreateUpdateParametersMapper, MongoDBCollectionCreateUpdateParameters as MongoDBCollectionCreateUpdateParametersMapper, TableCreateUpdateParameters as TableCreateUpdateParametersMapper, CassandraKeyspaceCreateUpdateParameters as CassandraKeyspaceCreateUpdateParametersMapper, CassandraTableCreateUpdateParameters as CassandraTableCreateUpdateParametersMapper, GremlinDatabaseCreateUpdateParameters as GremlinDatabaseCreateUpdateParametersMapper, GremlinGraphCreateUpdateParameters as GremlinGraphCreateUpdateParametersMapper, NotebookWorkspaceCreateUpdateParameters as NotebookWorkspaceCreateUpdateParametersMapper, PrivateEndpointConnection as PrivateEndpointConnectionMapper, ClusterResource as ClusterResourceMapper, CommandPostBody as CommandPostBodyMapper, DataCenterResource as DataCenterResourceMapper } from "../models/mappers"; export const accept: OperationParameter = { parameterPath: "accept", mapper: { defaultValue: "application/json", isConstant: true, serializedName: "Accept", type: { name: "String" } } }; export const $host: OperationURLParameter = { parameterPath: "$host", mapper: { serializedName: "$host", required: true, type: { name: "String" } }, skipEncoding: true }; export const subscriptionId: OperationURLParameter = { parameterPath: "subscriptionId", mapper: { constraints: { MinLength: 1 }, serializedName: "subscriptionId", required: true, type: { name: "String" } } }; export const resourceGroupName: OperationURLParameter = { parameterPath: "resourceGroupName", mapper: { constraints: { MaxLength: 90, MinLength: 1 }, serializedName: "resourceGroupName", required: true, type: { name: "String" } } }; export const accountName: OperationURLParameter = { parameterPath: "accountName", mapper: { constraints: { Pattern: new RegExp("^[a-z0-9]+(-[a-z0-9]+)*"), MaxLength: 50, MinLength: 3 }, serializedName: "accountName", required: true, type: { name: "String" } } }; export const apiVersion: OperationQueryParameter = { parameterPath: "apiVersion", mapper: { defaultValue: "2021-10-15", isConstant: true, serializedName: "api-version", type: { name: "String" } } }; export const contentType: OperationParameter = { parameterPath: ["options", "contentType"], mapper: { defaultValue: "application/json", isConstant: true, serializedName: "Content-Type", type: { name: "String" } } }; export const updateParameters: OperationParameter = { parameterPath: "updateParameters", mapper: DatabaseAccountUpdateParametersMapper }; export const createUpdateParameters: OperationParameter = { parameterPath: "createUpdateParameters", mapper: DatabaseAccountCreateUpdateParametersMapper }; export const failoverParameters: OperationParameter = { parameterPath: "failoverParameters", mapper: FailoverPoliciesMapper }; export const regionParameterForOffline: OperationParameter = { parameterPath: "regionParameterForOffline", mapper: RegionForOnlineOfflineMapper }; export const regionParameterForOnline: OperationParameter = { parameterPath: "regionParameterForOnline", mapper: RegionForOnlineOfflineMapper }; export const keyToRegenerate: OperationParameter = { parameterPath: "keyToRegenerate", mapper: DatabaseAccountRegenerateKeyParametersMapper }; export const filter: OperationQueryParameter = { parameterPath: "filter", mapper: { serializedName: "$filter", required: true, type: { name: "String" } } }; export const filter1: OperationQueryParameter = { parameterPath: ["options", "filter"], mapper: { serializedName: "$filter", type: { name: "String" } } }; export const nextLink: OperationURLParameter = { parameterPath: "nextLink", mapper: { serializedName: "nextLink", required: true, type: { name: "String" } }, skipEncoding: true }; export const databaseRid: OperationURLParameter = { parameterPath: "databaseRid", mapper: { serializedName: "databaseRid", required: true, type: { name: "String" } } }; export const collectionRid: OperationURLParameter = { parameterPath: "collectionRid", mapper: { serializedName: "collectionRid", required: true, type: { name: "String" } } }; export const region: OperationURLParameter = { parameterPath: "region", mapper: { serializedName: "region", required: true, type: { name: "String" } } }; export const sourceRegion: OperationURLParameter = { parameterPath: "sourceRegion", mapper: { serializedName: "sourceRegion", required: true, type: { name: "String" } } }; export const targetRegion: OperationURLParameter = { parameterPath: "targetRegion", mapper: { serializedName: "targetRegion", required: true, type: { name: "String" } } }; export const partitionKeyRangeId: OperationURLParameter = { parameterPath: "partitionKeyRangeId", mapper: { serializedName: "partitionKeyRangeId", required: true, type: { name: "String" } } }; export const databaseName: OperationURLParameter = { parameterPath: "databaseName", mapper: { serializedName: "databaseName", required: true, type: { name: "String" } } }; export const createUpdateSqlDatabaseParameters: OperationParameter = { parameterPath: "createUpdateSqlDatabaseParameters", mapper: SqlDatabaseCreateUpdateParametersMapper }; export const updateThroughputParameters: OperationParameter = { parameterPath: "updateThroughputParameters", mapper: ThroughputSettingsUpdateParametersMapper }; export const containerName: OperationURLParameter = { parameterPath: "containerName", mapper: { serializedName: "containerName", required: true, type: { name: "String" } } }; export const createUpdateSqlContainerParameters: OperationParameter = { parameterPath: "createUpdateSqlContainerParameters", mapper: SqlContainerCreateUpdateParametersMapper }; export const storedProcedureName: OperationURLParameter = { parameterPath: "storedProcedureName", mapper: { serializedName: "storedProcedureName", required: true, type: { name: "String" } } }; export const createUpdateSqlStoredProcedureParameters: OperationParameter = { parameterPath: "createUpdateSqlStoredProcedureParameters", mapper: SqlStoredProcedureCreateUpdateParametersMapper }; export const userDefinedFunctionName: OperationURLParameter = { parameterPath: "userDefinedFunctionName", mapper: { serializedName: "userDefinedFunctionName", required: true, type: { name: "String" } } }; export const createUpdateSqlUserDefinedFunctionParameters: OperationParameter = { parameterPath: "createUpdateSqlUserDefinedFunctionParameters", mapper: SqlUserDefinedFunctionCreateUpdateParametersMapper }; export const triggerName: OperationURLParameter = { parameterPath: "triggerName", mapper: { serializedName: "triggerName", required: true, type: { name: "String" } } }; export const createUpdateSqlTriggerParameters: OperationParameter = { parameterPath: "createUpdateSqlTriggerParameters", mapper: SqlTriggerCreateUpdateParametersMapper }; export const roleDefinitionId: OperationURLParameter = { parameterPath: "roleDefinitionId", mapper: { serializedName: "roleDefinitionId", required: true, type: { name: "String" } } }; export const createUpdateSqlRoleDefinitionParameters: OperationParameter = { parameterPath: "createUpdateSqlRoleDefinitionParameters", mapper: SqlRoleDefinitionCreateUpdateParametersMapper }; export const roleAssignmentId: OperationURLParameter = { parameterPath: "roleAssignmentId", mapper: { serializedName: "roleAssignmentId", required: true, type: { name: "String" } } }; export const createUpdateSqlRoleAssignmentParameters: OperationParameter = { parameterPath: "createUpdateSqlRoleAssignmentParameters", mapper: SqlRoleAssignmentCreateUpdateParametersMapper }; export const location: OperationParameter = { parameterPath: "location", mapper: ContinuousBackupRestoreLocationMapper }; export const createUpdateMongoDBDatabaseParameters: OperationParameter = { parameterPath: "createUpdateMongoDBDatabaseParameters", mapper: MongoDBDatabaseCreateUpdateParametersMapper }; export const collectionName: OperationURLParameter = { parameterPath: "collectionName", mapper: { serializedName: "collectionName", required: true, type: { name: "String" } } }; export const createUpdateMongoDBCollectionParameters: OperationParameter = { parameterPath: "createUpdateMongoDBCollectionParameters", mapper: MongoDBCollectionCreateUpdateParametersMapper }; export const tableName: OperationURLParameter = { parameterPath: "tableName", mapper: { serializedName: "tableName", required: true, type: { name: "String" } } }; export const createUpdateTableParameters: OperationParameter = { parameterPath: "createUpdateTableParameters", mapper: TableCreateUpdateParametersMapper }; export const keyspaceName: OperationURLParameter = { parameterPath: "keyspaceName", mapper: { serializedName: "keyspaceName", required: true, type: { name: "String" } } }; export const createUpdateCassandraKeyspaceParameters: OperationParameter = { parameterPath: "createUpdateCassandraKeyspaceParameters", mapper: CassandraKeyspaceCreateUpdateParametersMapper }; export const createUpdateCassandraTableParameters: OperationParameter = { parameterPath: "createUpdateCassandraTableParameters", mapper: CassandraTableCreateUpdateParametersMapper }; export const createUpdateGremlinDatabaseParameters: OperationParameter = { parameterPath: "createUpdateGremlinDatabaseParameters", mapper: GremlinDatabaseCreateUpdateParametersMapper }; export const graphName: OperationURLParameter = { parameterPath: "graphName", mapper: { serializedName: "graphName", required: true, type: { name: "String" } } }; export const createUpdateGremlinGraphParameters: OperationParameter = { parameterPath: "createUpdateGremlinGraphParameters", mapper: GremlinGraphCreateUpdateParametersMapper }; export const location1: OperationURLParameter = { parameterPath: "location", mapper: { serializedName: "location", required: true, type: { name: "String" } } }; export const notebookWorkspaceName: OperationURLParameter = { parameterPath: "notebookWorkspaceName", mapper: { serializedName: "notebookWorkspaceName", required: true, type: { name: "String" } } }; export const notebookCreateUpdateParameters: OperationParameter = { parameterPath: "notebookCreateUpdateParameters", mapper: NotebookWorkspaceCreateUpdateParametersMapper }; export const privateEndpointConnectionName: OperationURLParameter = { parameterPath: "privateEndpointConnectionName", mapper: { serializedName: "privateEndpointConnectionName", required: true, type: { name: "String" } } }; export const parameters: OperationParameter = { parameterPath: "parameters", mapper: PrivateEndpointConnectionMapper }; export const groupName: OperationURLParameter = { parameterPath: "groupName", mapper: { serializedName: "groupName", required: true, type: { name: "String" } } }; export const instanceId: OperationURLParameter = { parameterPath: "instanceId", mapper: { serializedName: "instanceId", required: true, type: { name: "String" } } }; export const restorableSqlDatabaseRid: OperationQueryParameter = { parameterPath: ["options", "restorableSqlDatabaseRid"], mapper: { serializedName: "restorableSqlDatabaseRid", type: { name: "String" } } }; export const startTime: OperationQueryParameter = { parameterPath: ["options", "startTime"], mapper: { serializedName: "startTime", type: { name: "String" } } }; export const endTime: OperationQueryParameter = { parameterPath: ["options", "endTime"], mapper: { serializedName: "endTime", type: { name: "String" } } }; export const restoreLocation: OperationQueryParameter = { parameterPath: ["options", "restoreLocation"], mapper: { serializedName: "restoreLocation", type: { name: "String" } } }; export const restoreTimestampInUtc: OperationQueryParameter = { parameterPath: ["options", "restoreTimestampInUtc"], mapper: { serializedName: "restoreTimestampInUtc", type: { name: "String" } } }; export const restorableMongodbDatabaseRid: OperationQueryParameter = { parameterPath: ["options", "restorableMongodbDatabaseRid"], mapper: { serializedName: "restorableMongodbDatabaseRid", type: { name: "String" } } }; export const clusterName: OperationURLParameter = { parameterPath: "clusterName", mapper: { constraints: { Pattern: new RegExp("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$"), MaxLength: 100, MinLength: 1 }, serializedName: "clusterName", required: true, type: { name: "String" } } }; export const body: OperationParameter = { parameterPath: "body", mapper: ClusterResourceMapper }; export const body1: OperationParameter = { parameterPath: "body", mapper: CommandPostBodyMapper }; export const dataCenterName: OperationURLParameter = { parameterPath: "dataCenterName", mapper: { constraints: { Pattern: new RegExp("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$"), MaxLength: 100, MinLength: 1 }, serializedName: "dataCenterName", required: true, type: { name: "String" } } }; export const body2: OperationParameter = { parameterPath: "body", mapper: DataCenterResourceMapper };
the_stack
import { assert, expect } from "chai"; import * as path from "path"; import * as Semver from "semver"; import * as sinon from "sinon"; import { DbResult, Guid, Id64, Id64String, Logger, LogLevel, OpenMode } from "@itwin/core-bentley"; import { Point3d, Range3d, StandardViewIndex, Transform, YawPitchRollAngles } from "@itwin/core-geometry"; import { CategorySelector, DisplayStyle3d, DocumentListModel, Drawing, DrawingCategory, DrawingGraphic, DrawingModel, ECSqlStatement, Element, ElementMultiAspect, ElementOwnsChildElements, ElementOwnsExternalSourceAspects, ElementOwnsUniqueAspect, ElementRefersToElements, ElementUniqueAspect, ExternalSourceAspect, GenericPhysicalMaterial, GeometricElement, IModelCloneContext, IModelDb, IModelHost, IModelJsFs, IModelSchemaLoader, InformationRecordModel, InformationRecordPartition, LinkElement, Model, ModelSelector, OrthographicViewDefinition, PhysicalModel, PhysicalObject, PhysicalPartition, PhysicalType, Relationship, RepositoryLink, Schema, SnapshotDb, SpatialCategory, StandaloneDb, SubCategory, Subject, } from "@itwin/core-backend"; import * as BackendTestUtils from "@itwin/core-backend/lib/cjs/test"; import { AxisAlignedBox3d, BriefcaseIdValue, Code, CodeScopeSpec, CodeSpec, ColorDef, CreateIModelProps, DefinitionElementProps, ElementProps, ExternalSourceAspectProps, IModel, IModelError, PhysicalElementProps, Placement3d, QueryRowFormat, RelatedElement, RelationshipProps, } from "@itwin/core-common"; import { IModelExporter, IModelExportHandler, IModelTransformer, IModelTransformOptions, TransformerLoggerCategory } from "../../core-transformer"; import { assertIdentityTransformation, ClassCounter, FilterByViewTransformer, IModelToTextFileExporter, IModelTransformer3d, IModelTransformerTestUtils, PhysicalModelConsolidator, RecordingIModelImporter, TestIModelTransformer, TransformerExtensiveTestScenario, } from "../IModelTransformerUtils"; import { KnownTestLocations } from "../KnownTestLocations"; describe("IModelTransformer", () => { const outputDir = path.join(KnownTestLocations.outputDir, "IModelTransformer"); before(async () => { if (!IModelJsFs.existsSync(KnownTestLocations.outputDir)) { IModelJsFs.mkdirSync(KnownTestLocations.outputDir); } if (!IModelJsFs.existsSync(outputDir)) { IModelJsFs.mkdirSync(outputDir); } // initialize logging if (false) { Logger.initializeToConsole(); Logger.setLevelDefault(LogLevel.Error); Logger.setLevel(TransformerLoggerCategory.IModelExporter, LogLevel.Trace); Logger.setLevel(TransformerLoggerCategory.IModelImporter, LogLevel.Trace); Logger.setLevel(TransformerLoggerCategory.IModelTransformer, LogLevel.Trace); } }); it("should transform changes from source to target", async () => { // Source IModelDb const sourceDbFile = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "TestIModelTransformer-Source.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbFile, { rootSubject: { name: "TestIModelTransformer-Source" } }); await BackendTestUtils.ExtensiveTestScenario.prepareDb(sourceDb); BackendTestUtils.ExtensiveTestScenario.populateDb(sourceDb); sourceDb.saveChanges(); // Target IModelDb const targetDbFile = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "TestIModelTransformer-Target.bim"); const targetDb = SnapshotDb.createEmpty(targetDbFile, { rootSubject: { name: "TestIModelTransformer-Target" } }); await TransformerExtensiveTestScenario.prepareTargetDb(targetDb); targetDb.saveChanges(); const numSourceUniqueAspects = count(sourceDb, ElementUniqueAspect.classFullName); const numSourceMultiAspects = count(sourceDb, ElementMultiAspect.classFullName); const numSourceRelationships = count(sourceDb, ElementRefersToElements.classFullName); assert.isAtLeast(numSourceUniqueAspects, 1); assert.isAtLeast(numSourceMultiAspects, 1); assert.isAtLeast(numSourceRelationships, 1); if (true) { // initial import Logger.logInfo(TransformerLoggerCategory.IModelTransformer, "=============="); Logger.logInfo(TransformerLoggerCategory.IModelTransformer, "Initial Import"); Logger.logInfo(TransformerLoggerCategory.IModelTransformer, "=============="); const targetImporter = new RecordingIModelImporter(targetDb); const transformer = new TestIModelTransformer(sourceDb, targetImporter); assert.isTrue(transformer.context.isBetweenIModels); await transformer.processAll(); assert.isAtLeast(targetImporter.numModelsInserted, 1); assert.equal(targetImporter.numModelsUpdated, 0); assert.isAtLeast(targetImporter.numElementsInserted, 1); assert.isAtLeast(targetImporter.numElementsUpdated, 1); assert.equal(targetImporter.numElementsDeleted, 0); assert.isAtLeast(targetImporter.numElementAspectsInserted, 1); assert.equal(targetImporter.numElementAspectsUpdated, 0); assert.isAtLeast(targetImporter.numRelationshipsInserted, 1); assert.equal(targetImporter.numRelationshipsUpdated, 0); assert.isAtLeast(count(targetDb, ElementRefersToElements.classFullName), 1); assert.isAtLeast(count(targetDb, InformationRecordPartition.classFullName), 1); assert.isAtLeast(count(targetDb, InformationRecordModel.classFullName), 1); assert.isAtLeast(count(targetDb, "ExtensiveTestScenarioTarget:PhysicalPartitionIsTrackedByRecords"), 1); assert.isAtLeast(count(targetDb, "ExtensiveTestScenarioTarget:AuditRecord"), 1); assert.equal(3, count(targetDb, "ExtensiveTestScenarioTarget:TargetInformationRecord")); targetDb.saveChanges(); TransformerExtensiveTestScenario.assertTargetDbContents(sourceDb, targetDb); transformer.context.dump(`${targetDbFile}.context.txt`); transformer.dispose(); } const numTargetElements = count(targetDb, Element.classFullName); const numTargetUniqueAspects = count(targetDb, ElementUniqueAspect.classFullName); const numTargetMultiAspects = count(targetDb, ElementMultiAspect.classFullName); const numTargetExternalSourceAspects = count(targetDb, ExternalSourceAspect.classFullName); const numTargetRelationships = count(targetDb, ElementRefersToElements.classFullName); assert.isAtLeast(numTargetUniqueAspects, 1); assert.isAtLeast(numTargetMultiAspects, 1); assert.isAtLeast(numTargetRelationships, 1); if (true) { // tests of IModelExporter // test #1 - export structure const exportFileName: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "TestIModelTransformer-Source-Export.txt"); assert.isFalse(IModelJsFs.existsSync(exportFileName)); const exporter = new IModelToTextFileExporter(sourceDb, exportFileName); await exporter.export(); assert.isTrue(IModelJsFs.existsSync(exportFileName)); // test #2 - count occurrences of classFullNames const classCountsFileName: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "TestIModelTransformer-Source-Counts.txt"); assert.isFalse(IModelJsFs.existsSync(classCountsFileName)); const classCounter = new ClassCounter(sourceDb, classCountsFileName); await classCounter.count(); assert.isTrue(IModelJsFs.existsSync(classCountsFileName)); } if (true) { // second import with no changes to source, should be a no-op Logger.logInfo(TransformerLoggerCategory.IModelTransformer, ""); Logger.logInfo(TransformerLoggerCategory.IModelTransformer, "================="); Logger.logInfo(TransformerLoggerCategory.IModelTransformer, "Reimport (no-op)"); Logger.logInfo(TransformerLoggerCategory.IModelTransformer, "================="); const targetImporter = new RecordingIModelImporter(targetDb); const transformer = new TestIModelTransformer(sourceDb, targetImporter); await transformer.processAll(); assert.equal(targetImporter.numModelsInserted, 0); assert.equal(targetImporter.numModelsUpdated, 0); assert.equal(targetImporter.numElementsInserted, 0); assert.equal(targetImporter.numElementsUpdated, 0); assert.equal(targetImporter.numElementsDeleted, 0); assert.equal(targetImporter.numElementAspectsInserted, 0); assert.equal(targetImporter.numElementAspectsUpdated, 0); assert.equal(targetImporter.numRelationshipsInserted, 0); assert.equal(targetImporter.numRelationshipsUpdated, 0); assert.equal(targetImporter.numRelationshipsDeleted, 0); assert.equal(numTargetElements, count(targetDb, Element.classFullName), "Second import should not add elements"); assert.equal(numTargetExternalSourceAspects, count(targetDb, ExternalSourceAspect.classFullName), "Second import should not add aspects"); assert.equal(numTargetRelationships, count(targetDb, ElementRefersToElements.classFullName), "Second import should not add relationships"); assert.equal(3, count(targetDb, "ExtensiveTestScenarioTarget:TargetInformationRecord")); transformer.dispose(); } if (true) { // update source db, then import again BackendTestUtils.ExtensiveTestScenario.updateDb(sourceDb); sourceDb.saveChanges(); Logger.logInfo(TransformerLoggerCategory.IModelTransformer, ""); Logger.logInfo(TransformerLoggerCategory.IModelTransformer, "==============================="); Logger.logInfo(TransformerLoggerCategory.IModelTransformer, "Reimport after sourceDb update"); Logger.logInfo(TransformerLoggerCategory.IModelTransformer, "==============================="); const targetImporter = new RecordingIModelImporter(targetDb); const transformer = new TestIModelTransformer(sourceDb, targetImporter); await transformer.processAll(); assert.equal(targetImporter.numModelsInserted, 0); assert.equal(targetImporter.numModelsUpdated, 0); assert.equal(targetImporter.numElementsInserted, 1); assert.equal(targetImporter.numElementsUpdated, 5); assert.equal(targetImporter.numElementsDeleted, 2); assert.equal(targetImporter.numElementAspectsInserted, 0); assert.equal(targetImporter.numElementAspectsUpdated, 2); assert.equal(targetImporter.numRelationshipsInserted, 2); assert.equal(targetImporter.numRelationshipsUpdated, 1); assert.equal(targetImporter.numRelationshipsDeleted, 1); targetDb.saveChanges(); BackendTestUtils.ExtensiveTestScenario.assertUpdatesInDb(targetDb); assert.equal(numTargetRelationships + targetImporter.numRelationshipsInserted - targetImporter.numRelationshipsDeleted, count(targetDb, ElementRefersToElements.classFullName)); assert.equal(2, count(targetDb, "ExtensiveTestScenarioTarget:TargetInformationRecord")); transformer.dispose(); } IModelTransformerTestUtils.dumpIModelInfo(sourceDb); IModelTransformerTestUtils.dumpIModelInfo(targetDb); sourceDb.close(); targetDb.close(); }); it("should synchronize changes from master to branch and back", async () => { // Simulate branching workflow by initializing branchDb to be a copy of the populated masterDb const masterDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "Master.bim"); const masterDb = SnapshotDb.createEmpty(masterDbFile, { rootSubject: { name: "Branching Workflow" }, createClassViews: true }); await BackendTestUtils.ExtensiveTestScenario.prepareDb(masterDb); BackendTestUtils.ExtensiveTestScenario.populateDb(masterDb); masterDb.saveChanges(); const branchDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "Branch.bim"); const branchDb = SnapshotDb.createFrom(masterDb, branchDbFile, { createClassViews: true }); const numMasterElements = count(masterDb, Element.classFullName); const numMasterRelationships = count(masterDb, ElementRefersToElements.classFullName); assert.isAtLeast(numMasterElements, 12); assert.isAtLeast(numMasterRelationships, 1); assert.equal(numMasterElements, count(branchDb, Element.classFullName)); assert.equal(numMasterRelationships, count(branchDb, ElementRefersToElements.classFullName)); assert.equal(0, count(branchDb, ExternalSourceAspect.classFullName)); // Ensure that master to branch synchronization did not add any new Elements or Relationships, but did add ExternalSourceAspects const masterToBranchTransformer = new IModelTransformer(masterDb, branchDb, { wasSourceIModelCopiedToTarget: true }); // Note use of `wasSourceIModelCopiedToTarget` flag await masterToBranchTransformer.processAll(); masterToBranchTransformer.dispose(); branchDb.saveChanges(); assert.equal(numMasterElements, count(branchDb, Element.classFullName)); assert.equal(numMasterRelationships, count(branchDb, ElementRefersToElements.classFullName)); assert.isAtLeast(count(branchDb, ExternalSourceAspect.classFullName), numMasterElements + numMasterRelationships - 1); // provenance not recorded for the root Subject // Confirm that provenance (captured in ExternalSourceAspects) was set correctly const sql = `SELECT aspect.Identifier,aspect.Element.Id FROM ${ExternalSourceAspect.classFullName} aspect WHERE aspect.Kind=:kind`; branchDb.withPreparedStatement(sql, (statement: ECSqlStatement): void => { statement.bindString("kind", ExternalSourceAspect.Kind.Element); while (DbResult.BE_SQLITE_ROW === statement.step()) { const masterElementId = statement.getValue(0).getString(); // ExternalSourceAspect.Identifier is of type string const branchElementId = statement.getValue(1).getId(); assert.equal(masterElementId, branchElementId); } }); // Make changes to simulate working on the branch BackendTestUtils.ExtensiveTestScenario.updateDb(branchDb); BackendTestUtils.ExtensiveTestScenario.assertUpdatesInDb(branchDb); branchDb.saveChanges(); const numBranchElements = count(branchDb, Element.classFullName); const numBranchRelationships = count(branchDb, ElementRefersToElements.classFullName); assert.notEqual(numBranchElements, numMasterElements); assert.notEqual(numBranchRelationships, numMasterRelationships); // Synchronize changes from branch back to master const branchToMasterTransformer = new IModelTransformer(branchDb, masterDb, { isReverseSynchronization: true, noProvenance: true }); await branchToMasterTransformer.processAll(); branchToMasterTransformer.dispose(); masterDb.saveChanges(); BackendTestUtils.ExtensiveTestScenario.assertUpdatesInDb(masterDb, false); assert.equal(numBranchElements, count(masterDb, Element.classFullName) - 2); // processAll cannot detect deletes when isReverseSynchronization=true assert.equal(numBranchRelationships, count(masterDb, ElementRefersToElements.classFullName) - 1); // processAll cannot detect deletes when isReverseSynchronization=true assert.equal(0, count(masterDb, ExternalSourceAspect.classFullName)); masterDb.close(); branchDb.close(); }); function count(iModelDb: IModelDb, classFullName: string): number { return iModelDb.withPreparedStatement(`SELECT COUNT(*) FROM ${classFullName}`, (statement: ECSqlStatement): number => { return DbResult.BE_SQLITE_ROW === statement.step() ? statement.getValue(0).getInteger() : 0; }); } it("should import everything below a Subject", async () => { // Source IModelDb const sourceDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "SourceImportSubject.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbFile, { rootSubject: { name: "SourceImportSubject" } }); await BackendTestUtils.ExtensiveTestScenario.prepareDb(sourceDb); BackendTestUtils.ExtensiveTestScenario.populateDb(sourceDb); const sourceSubjectId = sourceDb.elements.queryElementIdByCode(Subject.createCode(sourceDb, IModel.rootSubjectId, "Subject"))!; assert.isTrue(Id64.isValidId64(sourceSubjectId)); sourceDb.saveChanges(); // Target IModelDb const targetDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "TargetImportSubject.bim"); const targetDb = SnapshotDb.createEmpty(targetDbFile, { rootSubject: { name: "TargetImportSubject" } }); await TransformerExtensiveTestScenario.prepareTargetDb(targetDb); const targetSubjectId = Subject.insert(targetDb, IModel.rootSubjectId, "Target Subject", "Target Subject Description"); assert.isTrue(Id64.isValidId64(targetSubjectId)); targetDb.saveChanges(); // Import from beneath source Subject into target Subject const transformer = new TestIModelTransformer(sourceDb, targetDb); await transformer.processFonts(); await transformer.processSubject(sourceSubjectId, targetSubjectId); await transformer.processRelationships(ElementRefersToElements.classFullName); transformer.dispose(); targetDb.saveChanges(); TransformerExtensiveTestScenario.assertTargetDbContents(sourceDb, targetDb, "Target Subject"); const targetSubject: Subject = targetDb.elements.getElement<Subject>(targetSubjectId); assert.equal(targetSubject.description, "Target Subject Description"); // Close sourceDb.close(); targetDb.close(); }); it.skip("should clone Model within same iModel", async () => { // Set up the IModelDb with a populated source Subject and an "empty" target Subject const iModelFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "CloneModel.bim"); const iModelDb = SnapshotDb.createEmpty(iModelFile, { rootSubject: { name: "CloneModel" } }); await BackendTestUtils.ExtensiveTestScenario.prepareDb(iModelDb); BackendTestUtils.ExtensiveTestScenario.populateDb(iModelDb); const sourceSubjectId = iModelDb.elements.queryElementIdByCode(Subject.createCode(iModelDb, IModel.rootSubjectId, "Subject"))!; assert.isTrue(Id64.isValidId64(sourceSubjectId)); const targetSubjectId = Subject.insert(iModelDb, IModel.rootSubjectId, "Target Subject"); assert.isTrue(Id64.isValidId64(targetSubjectId)); iModelDb.saveChanges(); // Import from beneath source Subject into target Subject const transformer = new IModelTransformer(iModelDb, iModelDb); await transformer.processSubject(sourceSubjectId, targetSubjectId); transformer.dispose(); iModelDb.saveChanges(); iModelDb.close(); }); /** @note For debugging/testing purposes, you can use `it.only` and hard-code `sourceFileName` to test cloning of a particular iModel. */ it("should clone test file", async () => { // open source iModel const sourceFileName = BackendTestUtils.IModelTestUtils.resolveAssetFile("CompatibilityTestSeed.bim"); const sourceDb = SnapshotDb.openFile(sourceFileName); const numSourceElements = count(sourceDb, Element.classFullName); assert.exists(sourceDb); assert.isAtLeast(numSourceElements, 12); // create target iModel const targetDbFile = path.join(KnownTestLocations.outputDir, "IModelTransformer", "Clone-Target.bim"); if (IModelJsFs.existsSync(targetDbFile)) { IModelJsFs.removeSync(targetDbFile); } const targetDbProps: CreateIModelProps = { rootSubject: { name: `Cloned target of ${sourceDb.elements.getRootSubject().code.value}` }, ecefLocation: sourceDb.ecefLocation, }; const targetDb = SnapshotDb.createEmpty(targetDbFile, targetDbProps); assert.exists(targetDb); // import const transformer = new IModelTransformer(sourceDb, targetDb); await transformer.processSchemas(); await transformer.processAll(); transformer.dispose(); const numTargetElements = count(targetDb, Element.classFullName); assert.isAtLeast(numTargetElements, numSourceElements); assert.deepEqual(sourceDb.ecefLocation, targetDb.ecefLocation); // clean up sourceDb.close(); targetDb.close(); }); it("should include source provenance", async () => { // create source iModel const sourceDbFile = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "SourceProvenance.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbFile, { rootSubject: { name: "Source Provenance Test" } }); const sourceRepositoryId = IModelTransformerTestUtils.insertRepositoryLink(sourceDb, "master.dgn", "https://test.bentley.com/folder/master.dgn", "DGN"); const sourceExternalSourceId = IModelTransformerTestUtils.insertExternalSource(sourceDb, sourceRepositoryId, "Default Model"); const sourceCategoryId = SpatialCategory.insert(sourceDb, IModel.dictionaryId, "SpatialCategory", { color: ColorDef.green.toJSON() }); const sourceModelId = PhysicalModel.insert(sourceDb, IModel.rootSubjectId, "Physical"); for (const x of [1, 2, 3]) { const physicalObjectProps: PhysicalElementProps = { classFullName: PhysicalObject.classFullName, model: sourceModelId, category: sourceCategoryId, code: Code.createEmpty(), userLabel: `PhysicalObject(${x})`, geom: IModelTransformerTestUtils.createBox(Point3d.create(1, 1, 1)), placement: Placement3d.fromJSON({ origin: { x }, angles: {} }), }; const physicalObjectId = sourceDb.elements.insertElement(physicalObjectProps); const aspectProps: ExternalSourceAspectProps = { // simulate provenance from a Connector classFullName: ExternalSourceAspect.classFullName, element: { id: physicalObjectId, relClassName: ElementOwnsExternalSourceAspects.classFullName }, scope: { id: sourceExternalSourceId }, source: { id: sourceExternalSourceId }, identifier: `ID${x}`, kind: ExternalSourceAspect.Kind.Element, }; sourceDb.elements.insertAspect(aspectProps); } sourceDb.saveChanges(); // create target iModel const targetDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "SourceProvenance-Target.bim"); const targetDb = SnapshotDb.createEmpty(targetDbFile, { rootSubject: { name: "Source Provenance Test (Target)" } }); // clone const transformer = new IModelTransformer(sourceDb, targetDb, { includeSourceProvenance: true }); await transformer.processAll(); targetDb.saveChanges(); // verify target contents assert.equal(1, count(sourceDb, RepositoryLink.classFullName)); const targetRepositoryId = targetDb.elements.queryElementIdByCode(LinkElement.createCode(targetDb, IModel.repositoryModelId, "master.dgn"))!; assert.isTrue(Id64.isValidId64(targetRepositoryId)); const targetExternalSourceId = IModelTransformerTestUtils.queryByUserLabel(targetDb, "Default Model"); assert.isTrue(Id64.isValidId64(targetExternalSourceId)); const targetCategoryId = targetDb.elements.queryElementIdByCode(SpatialCategory.createCode(targetDb, IModel.dictionaryId, "SpatialCategory"))!; assert.isTrue(Id64.isValidId64(targetCategoryId)); const targetPhysicalObjectIds = [ IModelTransformerTestUtils.queryByUserLabel(targetDb, "PhysicalObject(1)"), IModelTransformerTestUtils.queryByUserLabel(targetDb, "PhysicalObject(2)"), IModelTransformerTestUtils.queryByUserLabel(targetDb, "PhysicalObject(3)"), ]; for (const targetPhysicalObjectId of targetPhysicalObjectIds) { assert.isTrue(Id64.isValidId64(targetPhysicalObjectId)); const physicalObject = targetDb.elements.getElement<PhysicalObject>(targetPhysicalObjectId, PhysicalObject); assert.equal(physicalObject.category, targetCategoryId); const aspects = targetDb.elements.getAspects(targetPhysicalObjectId, ExternalSourceAspect.classFullName); assert.equal(2, aspects.length, "Expect original source provenance + provenance generated by IModelTransformer"); for (const aspect of aspects) { const externalSourceAspect = aspect as ExternalSourceAspect; if (externalSourceAspect.scope.id === transformer.targetScopeElementId) { // provenance added by IModelTransformer assert.equal(externalSourceAspect.kind, ExternalSourceAspect.Kind.Element); } else { // provenance carried over from the source iModel assert.equal(externalSourceAspect.scope.id, targetExternalSourceId); assert.equal(externalSourceAspect.source!.id, targetExternalSourceId); assert.isTrue(externalSourceAspect.identifier.startsWith("ID")); assert.isTrue(physicalObject.userLabel!.includes(externalSourceAspect.identifier[2])); assert.equal(externalSourceAspect.kind, ExternalSourceAspect.Kind.Element); } } } // clean up transformer.dispose(); sourceDb.close(); targetDb.close(); }); it("should transform 3d elements in target iModel", async () => { // create source iModel const sourceDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "Transform3d-Source.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbFile, { rootSubject: { name: "Transform3d-Source" } }); const categoryId: Id64String = SpatialCategory.insert(sourceDb, IModel.dictionaryId, "SpatialCategory", { color: ColorDef.green.toJSON() }); const sourceModelId: Id64String = PhysicalModel.insert(sourceDb, IModel.rootSubjectId, "Physical"); const xArray: number[] = [1, 3, 5, 7, 9]; const yArray: number[] = [0, 2, 4, 6, 8]; for (const x of xArray) { for (const y of yArray) { const physicalObjectProps1: PhysicalElementProps = { classFullName: PhysicalObject.classFullName, model: sourceModelId, category: categoryId, code: Code.createEmpty(), userLabel: `PhysicalObject(${x},${y})`, geom: IModelTransformerTestUtils.createBox(Point3d.create(1, 1, 1)), placement: Placement3d.fromJSON({ origin: { x, y }, angles: {} }), }; sourceDb.elements.insertElement(physicalObjectProps1); } } const sourceModel: PhysicalModel = sourceDb.models.getModel<PhysicalModel>(sourceModelId); const sourceModelExtents: AxisAlignedBox3d = sourceModel.queryExtents(); assert.deepEqual(sourceModelExtents, new Range3d(1, 0, 0, 10, 9, 1)); // create target iModel const targetDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "Transform3d-Target.bim"); const targetDb = SnapshotDb.createEmpty(targetDbFile, { rootSubject: { name: "Transform3d-Target" } }); // transform const transform3d: Transform = Transform.createTranslation(new Point3d(100, 200)); const transformer = new IModelTransformer3d(sourceDb, targetDb, transform3d); await transformer.processAll(); const targetModelId: Id64String = transformer.context.findTargetElementId(sourceModelId); const targetModel: PhysicalModel = targetDb.models.getModel<PhysicalModel>(targetModelId); const targetModelExtents: AxisAlignedBox3d = targetModel.queryExtents(); assert.deepEqual(targetModelExtents, new Range3d(101, 200, 0, 110, 209, 1)); assert.deepEqual(targetModelExtents, transform3d.multiplyRange(sourceModelExtents)); // clean up transformer.dispose(); sourceDb.close(); targetDb.close(); }); it("should combine models", async () => { const sourceDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "source-separate-models.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbFile, { rootSubject: { name: "Separate Models" } }); const sourceCategoryId = SpatialCategory.insert(sourceDb, IModel.dictionaryId, "Category", {}); const sourceModelId1 = PhysicalModel.insert(sourceDb, IModel.rootSubjectId, "M1"); const sourceModelId2 = PhysicalModel.insert(sourceDb, IModel.rootSubjectId, "M2"); const elementProps11: PhysicalElementProps = { classFullName: PhysicalObject.classFullName, model: sourceModelId1, code: Code.createEmpty(), userLabel: "PhysicalObject-M1-E1", category: sourceCategoryId, geom: IModelTransformerTestUtils.createBox(new Point3d(1, 1, 1)), placement: Placement3d.fromJSON({ origin: { x: 1, y: 1 }, angles: {} }), }; const sourceElementId11 = sourceDb.elements.insertElement(elementProps11); const elementProps21: PhysicalElementProps = { classFullName: PhysicalObject.classFullName, model: sourceModelId2, code: Code.createEmpty(), userLabel: "PhysicalObject-M2-E1", category: sourceCategoryId, geom: IModelTransformerTestUtils.createBox(new Point3d(2, 2, 2)), placement: Placement3d.fromJSON({ origin: { x: 2, y: 2 }, angles: {} }), }; const sourceElementId21 = sourceDb.elements.insertElement(elementProps21); sourceDb.saveChanges(); assert.equal(count(sourceDb, PhysicalPartition.classFullName), 2); assert.equal(count(sourceDb, PhysicalModel.classFullName), 2); assert.equal(count(sourceDb, PhysicalObject.classFullName), 2); const targetDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "target-combined-model.bim"); const targetDb = SnapshotDb.createEmpty(targetDbFile, { rootSubject: { name: "Combined Model" } }); const targetModelId = PhysicalModel.insert(targetDb, IModel.rootSubjectId, "PhysicalModel-Combined"); const transformer = new PhysicalModelConsolidator(sourceDb, targetDb, targetModelId); await transformer.processAll(); targetDb.saveChanges(); const targetElement11 = targetDb.elements.getElement(transformer.context.findTargetElementId(sourceElementId11)); assert.equal(targetElement11.userLabel, "PhysicalObject-M1-E1"); assert.equal(targetElement11.model, targetModelId); const targetElement21 = targetDb.elements.getElement(transformer.context.findTargetElementId(sourceElementId21)); assert.equal(targetElement21.userLabel, "PhysicalObject-M2-E1"); assert.equal(targetElement21.model, targetModelId); const targetPartition = targetDb.elements.getElement(targetModelId); assert.equal(targetPartition.code.value, "PhysicalModel-Combined", "Original CodeValue should be retained"); assert.equal(count(targetDb, PhysicalPartition.classFullName), 1); assert.equal(count(targetDb, PhysicalModel.classFullName), 1); assert.equal(count(targetDb, PhysicalObject.classFullName), 2); transformer.dispose(); sourceDb.close(); targetDb.close(); }); it("should consolidate PhysicalModels", async () => { const sourceDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "MultiplePhysicalModels.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbFile, { rootSubject: { name: "Multiple PhysicalModels" } }); const categoryId: Id64String = SpatialCategory.insert(sourceDb, IModel.dictionaryId, "SpatialCategory", { color: ColorDef.green.toJSON() }); for (let i = 0; i < 5; i++) { const sourceModelId: Id64String = PhysicalModel.insert(sourceDb, IModel.rootSubjectId, `PhysicalModel${i}`); const xArray: number[] = [20 * i + 1, 20 * i + 3, 20 * i + 5, 20 * i + 7, 20 * i + 9]; const yArray: number[] = [0, 2, 4, 6, 8]; for (const x of xArray) { for (const y of yArray) { const physicalObjectProps1: PhysicalElementProps = { classFullName: PhysicalObject.classFullName, model: sourceModelId, category: categoryId, code: Code.createEmpty(), userLabel: `M${i}-PhysicalObject(${x},${y})`, geom: IModelTransformerTestUtils.createBox(Point3d.create(1, 1, 1)), placement: Placement3d.fromJSON({ origin: { x, y }, angles: {} }), }; sourceDb.elements.insertElement(physicalObjectProps1); } } } sourceDb.saveChanges(); assert.equal(5, count(sourceDb, PhysicalModel.classFullName)); assert.equal(125, count(sourceDb, PhysicalObject.classFullName)); const targetDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "OnePhysicalModel.bim"); const targetDb = SnapshotDb.createEmpty(targetDbFile, { rootSubject: { name: "One PhysicalModel" }, createClassViews: true }); const targetModelId: Id64String = PhysicalModel.insert(targetDb, IModel.rootSubjectId, "PhysicalModel"); assert.isTrue(Id64.isValidId64(targetModelId)); targetDb.saveChanges(); const consolidator = new PhysicalModelConsolidator(sourceDb, targetDb, targetModelId); await consolidator.processAll(); consolidator.dispose(); assert.equal(1, count(targetDb, PhysicalModel.classFullName)); const targetPartition = targetDb.elements.getElement<PhysicalPartition>(targetModelId); assert.equal(targetPartition.code.value, "PhysicalModel", "Target PhysicalModel name should not be overwritten during consolidation"); assert.equal(125, count(targetDb, PhysicalObject.classFullName)); const aspects = targetDb.elements.getAspects(targetPartition.id, ExternalSourceAspect.classFullName); assert.isAtLeast(aspects.length, 5, "Provenance should be recorded for each source PhysicalModel"); const sql = `SELECT ECInstanceId FROM ${PhysicalObject.classFullName}`; targetDb.withPreparedStatement(sql, (statement: ECSqlStatement) => { while (DbResult.BE_SQLITE_ROW === statement.step()) { const targetElementId = statement.getValue(0).getId(); const targetElement = targetDb.elements.getElement<PhysicalObject>({ id: targetElementId, wantGeometry: true }); assert.exists(targetElement.geom); assert.isFalse(targetElement.calculateRange3d().isNull); } }); sourceDb.close(); targetDb.close(); }); it("should sync Team iModels into Shared", async () => { const iModelShared: SnapshotDb = IModelTransformerTestUtils.createSharedIModel(outputDir, ["A", "B"]); if (true) { const iModelA: SnapshotDb = IModelTransformerTestUtils.createTeamIModel(outputDir, "A", Point3d.create(0, 0, 0), ColorDef.green); IModelTransformerTestUtils.assertTeamIModelContents(iModelA, "A"); const iModelExporterA = new IModelExporter(iModelA); iModelExporterA.excludeElement(iModelA.elements.queryElementIdByCode(Subject.createCode(iModelA, IModel.rootSubjectId, "Context"))!); const subjectId: Id64String = IModelTransformerTestUtils.querySubjectId(iModelShared, "A"); const transformerA2S = new IModelTransformer(iModelExporterA, iModelShared, { targetScopeElementId: subjectId }); transformerA2S.context.remapElement(IModel.rootSubjectId, subjectId); await transformerA2S.processAll(); transformerA2S.dispose(); IModelTransformerTestUtils.dumpIModelInfo(iModelA); iModelA.close(); iModelShared.saveChanges("Imported A"); IModelTransformerTestUtils.assertSharedIModelContents(iModelShared, ["A"]); } if (true) { const iModelB: SnapshotDb = IModelTransformerTestUtils.createTeamIModel(outputDir, "B", Point3d.create(0, 10, 0), ColorDef.blue); IModelTransformerTestUtils.assertTeamIModelContents(iModelB, "B"); const iModelExporterB = new IModelExporter(iModelB); iModelExporterB.excludeElement(iModelB.elements.queryElementIdByCode(Subject.createCode(iModelB, IModel.rootSubjectId, "Context"))!); const subjectId: Id64String = IModelTransformerTestUtils.querySubjectId(iModelShared, "B"); const transformerB2S = new IModelTransformer(iModelExporterB, iModelShared, { targetScopeElementId: subjectId }); transformerB2S.context.remapElement(IModel.rootSubjectId, subjectId); await transformerB2S.processAll(); transformerB2S.dispose(); IModelTransformerTestUtils.dumpIModelInfo(iModelB); iModelB.close(); iModelShared.saveChanges("Imported B"); IModelTransformerTestUtils.assertSharedIModelContents(iModelShared, ["A", "B"]); } if (true) { const iModelConsolidated: SnapshotDb = IModelTransformerTestUtils.createConsolidatedIModel(outputDir, "Consolidated"); const transformerS2C = new IModelTransformer(iModelShared, iModelConsolidated); const subjectA: Id64String = IModelTransformerTestUtils.querySubjectId(iModelShared, "A"); const subjectB: Id64String = IModelTransformerTestUtils.querySubjectId(iModelShared, "B"); const definitionA: Id64String = IModelTransformerTestUtils.queryDefinitionPartitionId(iModelShared, subjectA, "A"); const definitionB: Id64String = IModelTransformerTestUtils.queryDefinitionPartitionId(iModelShared, subjectB, "B"); const definitionC: Id64String = IModelTransformerTestUtils.queryDefinitionPartitionId(iModelConsolidated, IModel.rootSubjectId, "Consolidated"); transformerS2C.context.remapElement(definitionA, definitionC); transformerS2C.context.remapElement(definitionB, definitionC); const physicalA: Id64String = IModelTransformerTestUtils.queryPhysicalPartitionId(iModelShared, subjectA, "A"); const physicalB: Id64String = IModelTransformerTestUtils.queryPhysicalPartitionId(iModelShared, subjectB, "B"); const physicalC: Id64String = IModelTransformerTestUtils.queryPhysicalPartitionId(iModelConsolidated, IModel.rootSubjectId, "Consolidated"); transformerS2C.context.remapElement(physicalA, physicalC); transformerS2C.context.remapElement(physicalB, physicalC); await transformerS2C.processModel(definitionA); await transformerS2C.processModel(definitionB); await transformerS2C.processModel(physicalA); await transformerS2C.processModel(physicalB); await transformerS2C.processDeferredElements(); // eslint-disable-line deprecation/deprecation await transformerS2C.processRelationships(ElementRefersToElements.classFullName); transformerS2C.dispose(); IModelTransformerTestUtils.assertConsolidatedIModelContents(iModelConsolidated, "Consolidated"); IModelTransformerTestUtils.dumpIModelInfo(iModelConsolidated); iModelConsolidated.close(); } IModelTransformerTestUtils.dumpIModelInfo(iModelShared); iModelShared.close(); }); it("should detect conflicting provenance scopes", async () => { const sourceDb1 = IModelTransformerTestUtils.createTeamIModel(outputDir, "S1", Point3d.create(0, 0, 0), ColorDef.green); const sourceDb2 = IModelTransformerTestUtils.createTeamIModel(outputDir, "S2", Point3d.create(0, 10, 0), ColorDef.blue); assert.notEqual(sourceDb1.iModelId, sourceDb2.iModelId); // iModelId must be different to detect provenance scope conflicts const targetDbFile = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "ConflictingScopes.bim"); const targetDb = SnapshotDb.createEmpty(targetDbFile, { rootSubject: { name: "Conflicting Scopes Test" } }); const transformer1 = new IModelTransformer(sourceDb1, targetDb); // did not set targetScopeElementId const transformer2 = new IModelTransformer(sourceDb2, targetDb); // did not set targetScopeElementId await transformer1.processAll(); // first one succeeds using IModel.rootSubjectId as the default targetScopeElementId try { await transformer2.processAll(); // expect IModelError to be thrown because of the targetScopeElementId conflict with second transformation assert.fail("Expected provenance scope conflict"); } catch (e) { assert.isTrue(e instanceof IModelError); } finally { transformer1.dispose(); transformer2.dispose(); sourceDb1.close(); sourceDb2.close(); targetDb.close(); } }); it("IModelCloneContext remap tests", async () => { const iModelDb: SnapshotDb = IModelTransformerTestUtils.createTeamIModel(outputDir, "Test", Point3d.create(0, 0, 0), ColorDef.green); const cloneContext = new IModelCloneContext(iModelDb); const sourceId: Id64String = Id64.fromLocalAndBriefcaseIds(1, 1); const targetId: Id64String = Id64.fromLocalAndBriefcaseIds(1, 2); cloneContext.remapElement(sourceId, targetId); assert.equal(targetId, cloneContext.findTargetElementId(sourceId)); assert.equal(Id64.invalid, cloneContext.findTargetElementId(targetId)); assert.equal(Id64.invalid, cloneContext.findTargetCodeSpecId(targetId)); assert.throws(() => cloneContext.remapCodeSpec("SourceNotFound", "TargetNotFound")); cloneContext.dispose(); iModelDb.close(); }); it("should clone across schema versions", async () => { // NOTE: schema differences between 01.00.00 and 01.00.01 were crafted to reproduce a cloning bug. The goal of this test is to prevent regressions. const cloneTestSchema100 = BackendTestUtils.IModelTestUtils.resolveAssetFile("CloneTest.01.00.00.ecschema.xml"); const cloneTestSchema101 = BackendTestUtils.IModelTestUtils.resolveAssetFile("CloneTest.01.00.01.ecschema.xml"); const seedDb = SnapshotDb.openFile(BackendTestUtils.IModelTestUtils.resolveAssetFile("CompatibilityTestSeed.bim")); const sourceDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "CloneWithSchemaChanges-Source.bim"); const sourceDb = SnapshotDb.createFrom(seedDb, sourceDbFile); await sourceDb.importSchemas([cloneTestSchema100]); const sourceElementProps = { classFullName: "CloneTest:PhysicalType", model: IModel.dictionaryId, code: PhysicalType.createCode(sourceDb, IModel.dictionaryId, "Type1"), string1: "a", string2: "b", }; const sourceElementId = sourceDb.elements.insertElement(sourceElementProps); const sourceElement = sourceDb.elements.getElement(sourceElementId); assert.equal(sourceElement.asAny.string1, "a"); assert.equal(sourceElement.asAny.string2, "b"); sourceDb.saveChanges(); const targetDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "CloneWithSchemaChanges-Target.bim"); const targetDb = SnapshotDb.createEmpty(targetDbFile, { rootSubject: { name: "CloneWithSchemaChanges-Target" } }); await targetDb.importSchemas([cloneTestSchema101]); const transformer = new IModelTransformer(sourceDb, targetDb); await transformer.processElement(sourceElementId); targetDb.saveChanges(); const targetElementId = transformer.context.findTargetElementId(sourceElementId); const targetElement = targetDb.elements.getElement(targetElementId); assert.equal(targetElement.asAny.string1, "a"); assert.equal(targetElement.asAny.string2, "b"); seedDb.close(); sourceDb.close(); targetDb.close(); }); it("Should not visit elements or relationships", async () => { // class that asserts if it encounters an element or relationship class TestExporter extends IModelExportHandler { public iModelExporter: IModelExporter; public modelCount = 0; public constructor(iModelDb: IModelDb) { super(); this.iModelExporter = new IModelExporter(iModelDb); this.iModelExporter.registerHandler(this); } public override onExportModel(_model: Model, _isUpdate: boolean | undefined): void { ++this.modelCount; } public override onExportElement(_element: Element, _isUpdate: boolean | undefined): void { assert.fail("Should not visit element when visitElements=false"); } public override onExportRelationship(_relationship: Relationship, _isUpdate: boolean | undefined): void { assert.fail("Should not visit relationship when visitRelationship=false"); } } const sourceFileName = BackendTestUtils.IModelTestUtils.resolveAssetFile("CompatibilityTestSeed.bim"); const sourceDb: SnapshotDb = SnapshotDb.openFile(sourceFileName); const exporter = new TestExporter(sourceDb); exporter.iModelExporter.visitElements = false; exporter.iModelExporter.visitRelationships = false; // call various methods to make sure the onExport* callbacks don't assert await exporter.iModelExporter.exportAll(); await exporter.iModelExporter.exportElement(IModel.rootSubjectId); await exporter.iModelExporter.exportChildElements(IModel.rootSubjectId); await exporter.iModelExporter.exportModelContents(IModel.repositoryModelId); await exporter.iModelExporter.exportRelationships(ElementRefersToElements.classFullName); // make sure the exporter actually visited something assert.isAtLeast(exporter.modelCount, 4); sourceDb.close(); }); it("Should filter by ViewDefinition", async () => { const sourceDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "FilterByView-Source.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbFile, { rootSubject: { name: "FilterByView-Source" } }); const categoryNames: string[] = ["C1", "C2", "C3", "C4", "C5"]; categoryNames.forEach((categoryName) => { const categoryId = SpatialCategory.insert(sourceDb, IModel.dictionaryId, categoryName, {}); CategorySelector.insert(sourceDb, IModel.dictionaryId, categoryName, [categoryId]); }); const modelNames: string[] = ["MA", "MB", "MC", "MD"]; modelNames.forEach((modelName) => { const modelId = PhysicalModel.insert(sourceDb, IModel.rootSubjectId, modelName); ModelSelector.insert(sourceDb, IModel.dictionaryId, modelName, [modelId]); }); const projectExtents = new Range3d(); const displayStyleId = DisplayStyle3d.insert(sourceDb, IModel.dictionaryId, "DisplayStyle"); for (let x = 0; x < categoryNames.length; x++) { // eslint-disable-line @typescript-eslint/prefer-for-of const categoryId = sourceDb.elements.queryElementIdByCode(SpatialCategory.createCode(sourceDb, IModel.dictionaryId, categoryNames[x]))!; const categorySelectorId = sourceDb.elements.queryElementIdByCode(CategorySelector.createCode(sourceDb, IModel.dictionaryId, categoryNames[x]))!; for (let y = 0; y < modelNames.length; y++) { // eslint-disable-line @typescript-eslint/prefer-for-of const modelId = sourceDb.elements.queryElementIdByCode(PhysicalPartition.createCode(sourceDb, IModel.rootSubjectId, modelNames[y]))!; const modelSelectorId = sourceDb.elements.queryElementIdByCode(ModelSelector.createCode(sourceDb, IModel.dictionaryId, modelNames[y]))!; const physicalObjectProps: PhysicalElementProps = { classFullName: PhysicalObject.classFullName, model: modelId, category: categoryId, code: Code.createEmpty(), userLabel: `${PhysicalObject.className}-${categoryNames[x]}-${modelNames[y]}`, geom: IModelTransformerTestUtils.createBox(Point3d.create(1, 1, 1), categoryId), placement: { origin: Point3d.create(x * 2, y * 2, 0), angles: YawPitchRollAngles.createDegrees(0, 0, 0), }, }; const physicalObjectId = sourceDb.elements.insertElement(physicalObjectProps); const physicalObject = sourceDb.elements.getElement<PhysicalObject>(physicalObjectId, PhysicalObject); const viewExtents = physicalObject.placement.calculateRange(); OrthographicViewDefinition.insert( sourceDb, IModel.dictionaryId, `View-${categoryNames[x]}-${modelNames[y]}`, modelSelectorId, categorySelectorId, displayStyleId, viewExtents, StandardViewIndex.Iso ); projectExtents.extendRange(viewExtents); } } sourceDb.updateProjectExtents(projectExtents); const exportCategorySelectorId = CategorySelector.insert(sourceDb, IModel.dictionaryId, "Export", [ sourceDb.elements.queryElementIdByCode(SpatialCategory.createCode(sourceDb, IModel.dictionaryId, categoryNames[0]))!, sourceDb.elements.queryElementIdByCode(SpatialCategory.createCode(sourceDb, IModel.dictionaryId, categoryNames[2]))!, sourceDb.elements.queryElementIdByCode(SpatialCategory.createCode(sourceDb, IModel.dictionaryId, categoryNames[4]))!, ]); const exportModelSelectorId = ModelSelector.insert(sourceDb, IModel.dictionaryId, "Export", [ sourceDb.elements.queryElementIdByCode(PhysicalPartition.createCode(sourceDb, IModel.rootSubjectId, modelNames[1]))!, sourceDb.elements.queryElementIdByCode(PhysicalPartition.createCode(sourceDb, IModel.rootSubjectId, modelNames[3]))!, ]); const exportViewId = OrthographicViewDefinition.insert( sourceDb, IModel.dictionaryId, "Export", exportModelSelectorId, exportCategorySelectorId, displayStyleId, projectExtents, StandardViewIndex.Iso ); sourceDb.saveChanges(); const targetDbFile: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "FilterByView-Target.bim"); const targetDb = SnapshotDb.createEmpty(targetDbFile, { rootSubject: { name: "FilterByView-Target" } }); targetDb.updateProjectExtents(sourceDb.projectExtents); const transformer = new FilterByViewTransformer(sourceDb, targetDb, exportViewId); await transformer.processSchemas(); await transformer.processAll(); transformer.dispose(); targetDb.saveChanges(); targetDb.close(); sourceDb.close(); }); // WIP: Included as skipped until test file management strategy can be refined. it.skip("Merge test", async () => { const mergedIModelFileName: string = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "MergeTest.bim"); const mergedDb = SnapshotDb.createEmpty(mergedIModelFileName, { rootSubject: { name: "Merge Test" } }); const campusSubjectId: Id64String = Subject.insert(mergedDb, IModel.rootSubjectId, "Campus"); assert.isTrue(Id64.isValidId64(campusSubjectId)); const garageSubjectId: Id64String = Subject.insert(mergedDb, IModel.rootSubjectId, "Garage"); assert.isTrue(Id64.isValidId64(garageSubjectId)); const buildingSubjectId: Id64String = Subject.insert(mergedDb, IModel.rootSubjectId, "Building"); assert.isTrue(Id64.isValidId64(buildingSubjectId)); mergedDb.saveChanges("Create Subject hierarchy"); IModelTransformerTestUtils.flushTxns(mergedDb); // subsequent calls to importSchemas will fail if this is not called to flush local changes // Import campus if (true) { const campusIModelFileName = "D:/data/bim/MergeTest/Campus.bim"; const campusDb = SnapshotDb.openFile(campusIModelFileName); IModelTransformerTestUtils.dumpIModelInfo(campusDb); const transformer = new IModelTransformer(campusDb, mergedDb, { targetScopeElementId: campusSubjectId }); await transformer.processSchemas(); transformer.context.remapElement(IModel.rootSubjectId, campusSubjectId); await transformer.processAll(); transformer.dispose(); mergedDb.saveChanges("Imported Campus"); IModelTransformerTestUtils.flushTxns(mergedDb); // subsequent calls to importSchemas will fail if this is not called to flush local changes campusDb.close(); } // Import garage if (true) { const garageIModelFileName = "D:/data/bim/MergeTest/Garage.bim"; const garageDb = SnapshotDb.openFile(garageIModelFileName); IModelTransformerTestUtils.dumpIModelInfo(garageDb); const transformer = new IModelTransformer(garageDb, mergedDb, { targetScopeElementId: garageSubjectId }); transformer.context.remapElement(IModel.rootSubjectId, garageSubjectId); await transformer.processAll(); transformer.dispose(); mergedDb.saveChanges("Imported Garage"); IModelTransformerTestUtils.flushTxns(mergedDb); // subsequent calls to importSchemas will fail if this is not called to flush local changes garageDb.close(); } // Import building if (true) { const buildingIModelFileName = "D:/data/bim/MergeTest/Building.bim"; const buildingDb = SnapshotDb.openFile(buildingIModelFileName); IModelTransformerTestUtils.dumpIModelInfo(buildingDb); const transformer = new IModelTransformer(buildingDb, mergedDb, { targetScopeElementId: buildingSubjectId }); await transformer.processSchemas(); transformer.context.remapElement(IModel.rootSubjectId, buildingSubjectId); await transformer.processAll(); transformer.dispose(); mergedDb.saveChanges("Imported Building"); IModelTransformerTestUtils.flushTxns(mergedDb); // subsequent calls to importSchemas will fail if this is not called to flush local changes buildingDb.close(); } IModelTransformerTestUtils.dumpIModelInfo(mergedDb); mergedDb.close(); }); it("processSchemas should handle out-of-order exported schemas", async () => { const testSchema1Path = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "TestSchema1.ecschema.xml"); IModelJsFs.writeFileSync(testSchema1Path, `<?xml version="1.0" encoding="UTF-8"?> <ECSchema schemaName="TestSchema1" alias="ts1" version="01.00" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.1"> <ECSchemaReference name="BisCore" version="01.00" alias="bis"/> <ECEntityClass typeName="TestElement1"> <BaseClass>bis:PhysicalElement</BaseClass> <ECProperty propertyName="MyProp1" typeName="string"/> </ECEntityClass> </ECSchema>` ); const testSchema2Path = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "TestSchema2.ecschema.xml"); IModelJsFs.writeFileSync(testSchema2Path, `<?xml version="1.0" encoding="UTF-8"?> <ECSchema schemaName="TestSchema2" alias="ts2" version="01.00.00" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECSchemaReference name="BisCore" version="01.00.00" alias="bis"/> <ECSchemaReference name="TestSchema1" version="01.00.00" alias="ts1"/> <ECEntityClass typeName="TestElement2"> <BaseClass>ts1:TestElement1</BaseClass> <ECProperty propertyName="MyProp2" typeName="string"/> </ECEntityClass> </ECSchema>` ); const sourceDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "OrderTestSource.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbPath, { rootSubject: { name: "Order Test" } }); await sourceDb.importSchemas([testSchema1Path, testSchema2Path]); sourceDb.saveChanges(); class OrderedExporter extends IModelExporter { public override async exportSchemas() { const schemaLoader = new IModelSchemaLoader(this.sourceDb); const schema1 = schemaLoader.getSchema("TestSchema1"); const schema2 = schemaLoader.getSchema("TestSchema2"); // by importing schema2 (which references schema1) first, we // prove that the import order in processSchemas does not matter await this.handler.onExportSchema(schema2); await this.handler.onExportSchema(schema1); } } const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "OrderTestTarget.bim"); const targetDb = SnapshotDb.createEmpty(targetDbPath, { rootSubject: { name: "Order Test" } }); const transformer = new IModelTransformer(new OrderedExporter(sourceDb), targetDb); let error: any; try { await transformer.processSchemas(); } catch (_error) { error = _error; } assert.isUndefined(error); targetDb.saveChanges(); const targetImportedSchemasLoader = new IModelSchemaLoader(targetDb); const schema1InTarget = targetImportedSchemasLoader.getSchema("TestSchema1"); assert.isDefined(schema1InTarget); const schema2InTarget = targetImportedSchemasLoader.getSchema("TestSchema2"); assert.isDefined(schema2InTarget); sourceDb.close(); targetDb.close(); }); it("processSchemas should wait for the schema import to finish to delete the export directory", async () => { const cloneTestSchema100 = BackendTestUtils.IModelTestUtils.resolveAssetFile("CloneTest.01.00.00.ecschema.xml"); const sourceDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "FinallyFirstTest.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbPath, { rootSubject: { name: "FinallyFirstTest" } }); await sourceDb.importSchemas([cloneTestSchema100]); sourceDb.saveChanges(); const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "FinallyFirstTestOut.bim"); const targetDb = SnapshotDb.createEmpty(targetDbPath, { rootSubject: { name: "FinallyFirstTest" } }); const transformer = new IModelTransformer(sourceDb, targetDb); const importSchemasResolved = sinon.spy(); let importSchemasPromise: Promise<void>; sinon.replace(targetDb, "importSchemas", sinon.fake(async () => { importSchemasPromise = new Promise((resolve) => setImmediate(() => { importSchemasResolved(); resolve(undefined); })); return importSchemasPromise; })); const removeSyncSpy = sinon.spy(IModelJsFs, "removeSync"); await transformer.processSchemas(); assert(removeSyncSpy.calledAfter(importSchemasResolved)); sinon.restore(); sourceDb.close(); targetDb.close(); }); it("handles definition element scoped by non-definitional element", async () => { const sourceDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "BadPredecessorsExampleSource.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbPath, { rootSubject: { name: "BadPredecessorExampleSource" } }); // create a document partition in our iModel's root const documentListModelId = DocumentListModel.insert(sourceDb, IModelDb.rootSubjectId, "DocumentList"); // add a drawing to the document partition's model const drawingId = sourceDb.elements.insertElement({ classFullName: Drawing.classFullName, model: documentListModelId, code: Drawing.createCode(sourceDb, documentListModelId, "Drawing"), }); expect(Id64.isValidId64(drawingId)).to.be.true; // submodel our drawing with a DrawingModel const model = sourceDb.models.createModel({ classFullName: DrawingModel.classFullName, modeledElement: { id: drawingId }, }); sourceDb.models.insertModel(model.toJSON()); const myCodeSpecId = sourceDb.codeSpecs.insert(CodeSpec.create(sourceDb, "MyCodeSpec", CodeScopeSpec.Type.RelatedElement)); // insert a definition element which is scoped by a non-definition element (the drawing) const _physicalMaterialId = sourceDb.elements.insertElement({ classFullName: GenericPhysicalMaterial.classFullName, model: IModel.dictionaryId, code: new Code({ spec: myCodeSpecId, scope: drawingId, value: "physical material" }), } as DefinitionElementProps); sourceDb.saveChanges(); const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "BadPredecessorExampleTarget.bim"); const targetDb = SnapshotDb.createEmpty(targetDbPath, { rootSubject: { name: sourceDb.rootSubject.name } }); const transformer = new IModelTransformer(sourceDb, targetDb); await expect(transformer.processSchemas()).to.eventually.be.fulfilled; await expect(transformer.processAll()).to.eventually.be.fulfilled; // check if target imodel has the elements that source imodel had expect(targetDb.codeSpecs.hasName("MyCodeSpec")).to.be.true; const myCodeSpecIdTarget = targetDb.codeSpecs.getByName("MyCodeSpec").id; expect(myCodeSpecIdTarget).to.not.be.undefined; const drawingIdTarget = targetDb.elements.queryElementIdByCode(Drawing.createCode(targetDb, documentListModelId, "Drawing")) as string; expect(Id64.isValidId64(drawingIdTarget)).to.be.true; const physicalMaterialIdTarget = targetDb.elements.queryElementIdByCode(new Code({ spec: myCodeSpecIdTarget, scope: drawingIdTarget, value: "physical material" })); expect(physicalMaterialIdTarget).to.not.be.undefined; expect(Id64.isValidId64((physicalMaterialIdTarget as string))).to.be.true; sourceDb.close(); targetDb.close(); }); it("handle backwards related-instance code in model", async () => { const sourceDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "BadPredecessorsExampleSource.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbPath, { rootSubject: { name: "BadPredecessorExampleSource" } }); // create a document partition in our iModel's root const documentListModelId = DocumentListModel.insert(sourceDb, IModelDb.rootSubjectId, "DocumentList"); // add a drawing to the document partition's model const drawing1Id = sourceDb.elements.insertElement({ classFullName: Drawing.classFullName, model: documentListModelId, code: Drawing.createCode(sourceDb, documentListModelId, "Drawing1"), }); const drawing2Id = sourceDb.elements.insertElement({ classFullName: Drawing.classFullName, model: documentListModelId, code: Drawing.createCode(sourceDb, documentListModelId, "Drawing2"), }); const drawingModel1 = sourceDb.models.createModel({ classFullName: DrawingModel.classFullName, modeledElement: { id: drawing1Id }, }); const drawingModel1Id = sourceDb.models.insertModel(drawingModel1.toJSON()); const drawingModel2 = sourceDb.models.createModel({ classFullName: DrawingModel.classFullName, modeledElement: { id: drawing2Id }, }); const drawingModel2Id = sourceDb.models.insertModel(drawingModel2.toJSON()); const modelCodeSpec = sourceDb.codeSpecs.insert(CodeSpec.create(sourceDb, "ModelCodeSpec", CodeScopeSpec.Type.Model)); const relatedCodeSpecId = sourceDb.codeSpecs.insert(CodeSpec.create(sourceDb, "RelatedCodeSpec", CodeScopeSpec.Type.RelatedElement)); const categoryId = DrawingCategory.insert(sourceDb, IModel.dictionaryId, "DrawingCategory", { color: ColorDef.green.toJSON() }); // we make drawingGraphic2 in drawingModel2 first const drawingGraphic2Id = new DrawingGraphic({ classFullName: DrawingGraphic.classFullName, model: drawingModel2Id, code: new Code({ spec: modelCodeSpec, scope: drawingModel2Id, value: "drawing graphic 2" }), category: categoryId, }, sourceDb).insert(); const _drawingGraphic1Id = new DrawingGraphic({ classFullName: DrawingGraphic.classFullName, model: drawingModel1Id, code: new Code({ spec: relatedCodeSpecId, scope: drawingGraphic2Id, value: "drawing graphic 1" }), category: categoryId, }, sourceDb).insert(); sourceDb.saveChanges(); const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "BadPredecessorExampleTarget.bim"); const targetDb = SnapshotDb.createEmpty(targetDbPath, { rootSubject: { name: sourceDb.rootSubject.name } }); const transformer = new IModelTransformer(sourceDb, targetDb); await expect(transformer.processSchemas()).to.eventually.be.fulfilled; await expect(transformer.processAll()).to.eventually.be.fulfilled; // check if target imodel has the elements that source imodel had expect(targetDb.codeSpecs.hasName("ModelCodeSpec")).to.be.true; expect(targetDb.codeSpecs.hasName("RelatedCodeSpec")).to.be.true; const drawingIdTarget1 = targetDb.elements.queryElementIdByCode(Drawing.createCode(targetDb, documentListModelId, "Drawing1")); expect(drawingIdTarget1).to.not.be.undefined; expect(Id64.isValidId64((drawingIdTarget1 as string))).to.be.true; const drawingIdTarget2 = targetDb.elements.queryElementIdByCode(Drawing.createCode(targetDb, documentListModelId, "Drawing2")); expect(drawingIdTarget2).to.not.be.undefined; expect(Id64.isValidId64((drawingIdTarget2 as string))).to.be.true; const drawingGraphicIdTarget2Props = targetDb.elements.getElementProps(drawingGraphic2Id); expect(targetDb.elements.queryElementIdByCode(new Code(drawingGraphicIdTarget2Props.code))).to.not.be.undefined; expect(Id64.isValidId64((targetDb.elements.queryElementIdByCode(new Code(drawingGraphicIdTarget2Props.code)) as string))).to.be.true; const drawingGraphicIdTarget1Props = targetDb.elements.getElementProps(_drawingGraphic1Id); expect(targetDb.elements.queryElementIdByCode(new Code(drawingGraphicIdTarget1Props.code))).to.not.be.undefined; expect(Id64.isValidId64((targetDb.elements.queryElementIdByCode(new Code(drawingGraphicIdTarget1Props.code)) as string))).to.be.true; sourceDb.close(); targetDb.close(); }); // for testing purposes only, based on SetToStandalone.ts, force a snapshot to mimic a standalone iModel function setToStandalone(iModelName: string) { const nativeDb = new IModelHost.platform.DgnDb(); nativeDb.openIModel(iModelName, OpenMode.ReadWrite); nativeDb.setITwinId(Guid.empty); // empty iTwinId means "standalone" nativeDb.saveChanges(); // save change to iTwinId nativeDb.deleteAllTxns(); // necessary before resetting briefcaseId nativeDb.resetBriefcaseId(BriefcaseIdValue.Unassigned); // standalone iModels should always have BriefcaseId unassigned nativeDb.saveLocalValue("StandaloneEdit", JSON.stringify({ txns: true })); nativeDb.saveChanges(); // save change to briefcaseId nativeDb.closeIModel(); } it("biscore update is valid", async () => { const sourceDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "BisCoreUpdateSource.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbPath, { rootSubject: { name: "BisCoreUpdate" } }); // this seed has an old biscore, so we know that transforming an empty source (which starts with a fresh, updated biscore) // will cause an update to the old biscore in this target const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "BisCoreUpdateTarget.bim"); const seedDb = SnapshotDb.openFile(BackendTestUtils.IModelTestUtils.resolveAssetFile("CompatibilityTestSeed.bim")); const targetDbTestCopy = SnapshotDb.createFrom(seedDb, targetDbPath); targetDbTestCopy.close(); seedDb.close(); setToStandalone(targetDbPath); const targetDb = StandaloneDb.openFile(targetDbPath); assert( Semver.lt( Schema.toSemverString(targetDb.querySchemaVersion("BisCore")!), Schema.toSemverString(sourceDb.querySchemaVersion("BisCore")!)), "The targetDb must have a less up-to-date version of the BisCore schema than the source" ); const transformer = new IModelTransformer(sourceDb, targetDb); await transformer.processSchemas(); targetDb.saveChanges(); assert( Semver.eq( Schema.toSemverString(targetDb.querySchemaVersion("BisCore")!), Schema.toSemverString(sourceDb.querySchemaVersion("BisCore")!)), "The targetDb must now have an equivalent BisCore schema because it was updated" ); sourceDb.close(); targetDb.close(); }); /** gets a mapping of element ids to their invariant content */ async function getAllElementsInvariants(db: IModelDb, filterPredicate?: (element: Element) => boolean) { const result: Record<Id64String, any> = {}; for await (const row of db.query("SELECT * FROM bis.Element", undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) { if (!filterPredicate || filterPredicate(db.elements.getElement(row.id))) { const { lastMod: _lastMod, ...invariantPortion } = row; result[row.id] = invariantPortion; } } return result; } /** gets the ordered list of the relationships inserted earlier */ async function getInvariantRelationsContent( db: IModelDb, filterPredicate?: (rel: {sourceId: string, targetId: string}) => boolean ): Promise<{ sourceId: Id64String, targetId: Id64String }[]> { const result = []; for await (const row of db.query("SELECT * FROM bis.ElementRefersToElements", undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) { if (!filterPredicate || filterPredicate(row)) { const { id: _id, ...invariantPortion } = row; result.push(invariantPortion); } } return result; } it("preserveId option preserves element ids, not other entity ids", async () => { const sourceDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "PreserveIdSource.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbPath, { rootSubject: { name: "PreserveId" } }); const spatialCateg1Id = SpatialCategory.insert(sourceDb, IModelDb.dictionaryId, "spatial-category1", { color: ColorDef.blue.toJSON() }); const spatialCateg2Id = SpatialCategory.insert(sourceDb, IModelDb.dictionaryId, "spatial-category2", { color: ColorDef.red.toJSON() }); const myPhysModelId = PhysicalModel.insert(sourceDb, IModelDb.rootSubjectId, "myPhysicalModel"); const _physicalObjectIds = [spatialCateg1Id, spatialCateg2Id, spatialCateg2Id, spatialCateg2Id, spatialCateg2Id].map((categoryId, x) => { const physicalObjectProps: PhysicalElementProps = { classFullName: PhysicalObject.classFullName, model: myPhysModelId, category: categoryId, code: Code.createEmpty(), userLabel: `PhysicalObject(${x})`, geom: IModelTransformerTestUtils.createBox(Point3d.create(1, 1, 1)), placement: Placement3d.fromJSON({ origin: { x }, angles: {} }), }; const physicalObjectId = sourceDb.elements.insertElement(physicalObjectProps); return physicalObjectId; }); // these link table relationships (ElementRefersToElements > PartitionOriginatesFromRepository) are examples of non-element entities const physicalPartitions = new Array(3).fill(null).map((_, index) => new PhysicalPartition({ classFullName: PhysicalPartition.classFullName, model: IModelDb.rootSubjectId, parent: { id: IModelDb.rootSubjectId, relClassName: ElementOwnsChildElements.classFullName, }, code: PhysicalPartition.createCode(sourceDb, IModelDb.rootSubjectId, `physical-partition-${index}`), }, sourceDb), ).map((partition) => { const partitionId = partition.insert(); const model = new PhysicalModel({ classFullName: PhysicalPartition.classFullName, modeledElement: { id: partitionId }, }, sourceDb); const modelId = model.insert(); return { modelId, partitionId }; // these are the same id because of submodeling }); const linksIds = new Array(2).fill(null).map((_, index) => { const link = new RepositoryLink({ classFullName: RepositoryLink.classFullName, code: RepositoryLink.createCode(sourceDb, IModelDb.rootSubjectId, `repo-link-${index}`), model: IModelDb.rootSubjectId, repositoryGuid: `2fd0e5ed-a4d7-40cd-be8a-57552f5736b${index}`, // random, doesn't matter, works for up to 10 of course format: "my-format", }, sourceDb); const linkId = link.insert(); return linkId; }); const _nonElementEntityIds = [ [physicalPartitions[1].partitionId, linksIds[0]], [physicalPartitions[1].partitionId, linksIds[1]], [physicalPartitions[2].partitionId, linksIds[0]], [physicalPartitions[2].partitionId, linksIds[1]], ].map(([sourceId, targetId]) => sourceDb.relationships.insertInstance({ classFullName: "BisCore:PartitionOriginatesFromRepository", sourceId, targetId, })); sourceDb.saveChanges(); const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "PreserveIdTarget.bim"); const targetDb = SnapshotDb.createEmpty(targetDbPath, { rootSubject: { name: "PreserveId" } }); const spatialCateg2 = sourceDb.elements.getElement<SpatialCategory>(spatialCateg2Id); /** filter the category and all related elements from the source for transformation */ function filterCategoryTransformationPredicate(elem: Element): boolean { // if we don't filter out the elements, the transformer will see that the category is a predecessor // and re-add it to the transformation. if (elem instanceof GeometricElement && elem.category === spatialCateg2Id) return false; if (elem.id === spatialCateg2Id) return false; return true; } /** filter the category and all related elements from the source for transformation */ function filterRelationshipsToChangeIds({sourceId, targetId}: {sourceId: Id64String, targetId: Id64String}): boolean { // matches source+target of _nonElementEntityIds[0] if (sourceId === physicalPartitions[1].partitionId && targetId === linksIds[0]) return false; return true; } /** filter the category and all related and child elements from the source for comparison, not transformation */ function filterCategoryContentsPredicate(elem: Element): boolean { if (elem instanceof GeometricElement && elem.category === spatialCateg2Id) return false; if (elem.id === spatialCateg2Id) return false; if (elem.id === spatialCateg2.myDefaultSubCategoryId()) return false; return true; } class FilterCategoryTransformer extends IModelTransformer { public override shouldExportElement(elem: Element): boolean { if (!filterCategoryTransformationPredicate(elem)) return false; return super.shouldExportElement(elem); } public override shouldExportRelationship(rel: Relationship): boolean { if (!filterRelationshipsToChangeIds(rel)) return false; return super.shouldExportRelationship(rel); } } const transformer = new FilterCategoryTransformer(sourceDb, targetDb, { preserveElementIdsForFiltering: true }); await transformer.processAll(); targetDb.saveChanges(); const sourceContent = await getAllElementsInvariants(sourceDb, filterCategoryContentsPredicate); const targetContent = await getAllElementsInvariants(targetDb); expect(targetContent).to.deep.equal(sourceContent); const sourceRelations = await getInvariantRelationsContent(sourceDb, filterRelationshipsToChangeIds); const targetRelations = await getInvariantRelationsContent(targetDb); expect(sourceRelations).to.deep.equal(targetRelations); // now try inserting both an element and a relationship into the target to check the two entity id sequences are fine const spatialCateg3Id = SpatialCategory.insert( targetDb, IModelDb.dictionaryId, "spatial-category3", { color: ColorDef.black.toJSON() } ); expect(Id64.isValid(spatialCateg3Id)).to.be.true; const spatialCateg3Subcateg1Id = SubCategory.insert( targetDb, spatialCateg3Id, "spatial-categ-subcateg-1", { color: ColorDef.white.toJSON() } ); expect(Id64.isValid(spatialCateg3Subcateg1Id)).to.be.true; const insertedInstance = targetDb.relationships.insertInstance({ classFullName: "BisCore:PartitionOriginatesFromRepository", sourceId: physicalPartitions[1].partitionId, targetId: linksIds[0], }); expect(Id64.isValid(insertedInstance)).to.be.true; sourceDb.close(); targetDb.close(); }); it("preserveId on test model", async () => { const seedDb = SnapshotDb.openFile(BackendTestUtils.IModelTestUtils.resolveAssetFile("CompatibilityTestSeed.bim")); const sourceDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "PreserveIdOnTestModel-Source.bim"); // transforming the seed to an empty will update it to the latest bis from the new target // which minimizes differences we'd otherwise need to filter later const sourceDb = SnapshotDb.createEmpty(sourceDbPath, { rootSubject: seedDb.rootSubject }); const seedTransformer = new IModelTransformer(seedDb, sourceDb); await seedTransformer.processAll(); sourceDb.saveChanges(); const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "PreserveIdOnTestModel-Target.bim"); const targetDb = SnapshotDb.createEmpty(targetDbPath, { rootSubject: sourceDb.rootSubject }); const transformer = new IModelTransformer(sourceDb, targetDb, { preserveElementIdsForFiltering: true }); await transformer.processAll(); targetDb.saveChanges(); const sourceContent = await getAllElementsInvariants(sourceDb); const targetContent = await getAllElementsInvariants(targetDb); expect(targetContent).to.deep.equal(sourceContent); sourceDb.close(); targetDb.close(); }); function createIModelWithDanglingPredecessor(opts: {name: string, path: string}) { const sourceDb = SnapshotDb.createEmpty(opts.path, { rootSubject: { name: opts.name } }); const sourceCategoryId = SpatialCategory.insert(sourceDb, IModel.dictionaryId, "SpatialCategory", { color: ColorDef.green.toJSON() }); const sourceModelId = PhysicalModel.insert(sourceDb, IModel.rootSubjectId, "Physical"); const myPhysObjCodeSpec = CodeSpec.create(sourceDb, "myPhysicalObjects", CodeScopeSpec.Type.ParentElement); const myPhysObjCodeSpecId = sourceDb.codeSpecs.insert(myPhysObjCodeSpec); const physicalObjects = [1, 2].map((x) => { const code = new Code({ spec: myPhysObjCodeSpecId, scope: sourceModelId, value: `PhysicalObject(${x})`, }); const props: PhysicalElementProps = { classFullName: PhysicalObject.classFullName, model: sourceModelId, category: sourceCategoryId, code, userLabel: `PhysicalObject(${x})`, geom: IModelTransformerTestUtils.createBox(Point3d.create(1, 1, 1)), placement: Placement3d.fromJSON({ origin: { x }, angles: {} }), }; const id = sourceDb.elements.insertElement(props); return { code, id }; }); const displayStyleId = DisplayStyle3d.insert( sourceDb, IModel.dictionaryId, "MyDisplayStyle", { excludedElements: physicalObjects.map((o) => o.id), } ); const displayStyleCode = sourceDb.elements.getElement(displayStyleId).code; const physObjId2 = physicalObjects[1].id; // this deletion makes the display style have an reference to a now-gone element sourceDb.elements.deleteElement(physObjId2); sourceDb.saveChanges(); return [ sourceDb, { sourceCategoryId, sourceModelId, physicalObjects, displayStyleId, displayStyleCode, myPhysObjCodeSpec, }, ] as const; } /** * A transformer that inserts an element at the beginning to ensure the target doesn't end up with the same ids as the source. * Useful if you need to check that some source/target element references match and want to be sure it isn't a coincidence, * which can happen deterministically in several cases, as well as just copy-paste errors where you accidentally test a * source or target db against itself * @note it modifies the target so there are side effects */ class ShiftElemIdsTransformer extends IModelTransformer { constructor(...args: ConstructorParameters<typeof IModelTransformer>) { super(...args); try { // the choice of element to insert is arbitrary, anything easy works PhysicalModel.insert(this.targetDb, IModel.rootSubjectId, "MyShiftElemIdsPhysicalModel"); } catch (_err) {} // ignore error in case someone tries to transform the same target multiple times with this } } it("predecessor deletion is considered invalid when danglingPredecessorsBehavior='reject' and that is the default", async () => { const sourceDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "DanglingPredecessorSource.bim"); const [ sourceDb, { displayStyleId, physicalObjects }, ] = createIModelWithDanglingPredecessor({ name: "DanglingPredecessors", path: sourceDbPath }); const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "DanglingPredecessorTarget-reject.bim"); const targetDbForRejected = SnapshotDb.createEmpty(targetDbPath, { rootSubject: sourceDb.rootSubject }); const defaultTransformer = new ShiftElemIdsTransformer(sourceDb, targetDbForRejected); await expect(defaultTransformer.processAll()).to.be.rejectedWith( /Found a reference to an element "[^"]*" that doesn't exist/ ); const rejectDanglingPredecessorsTransformer = new ShiftElemIdsTransformer(sourceDb, targetDbForRejected, { danglingPredecessorsBehavior: "reject" }); await expect(rejectDanglingPredecessorsTransformer.processAll()).to.be.rejectedWith( /Found a reference to an element "[^"]*" that doesn't exist/ ); const runTransform = async (opts: Pick<IModelTransformOptions, "danglingPredecessorsBehavior">) => { const thisTransformTargetPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", `DanglingPredecessorTarget-${opts.danglingPredecessorsBehavior}.bim`); const targetDb = SnapshotDb.createEmpty(thisTransformTargetPath, { rootSubject: sourceDb.rootSubject }); const transformer = new ShiftElemIdsTransformer(sourceDb, targetDb, opts); await expect(transformer.processAll()).not.to.be.rejected; targetDb.saveChanges(); expect(sourceDb.elements.tryGetElement(physicalObjects[1].id)).to.be.undefined; const displayStyleInSource = sourceDb.elements.getElement<DisplayStyle3d>(displayStyleId); expect([...displayStyleInSource.settings.excludedElementIds]).to.include(physicalObjects[1].id); const displayStyleInTargetId = transformer.context.findTargetElementId(displayStyleId); const displayStyleInTarget = targetDb.elements.getElement<DisplayStyle3d>(displayStyleInTargetId); const physObjsInTarget = physicalObjects.map((physObjInSource) => { const physObjInTargetId = transformer.context.findTargetElementId(physObjInSource.id); return { ...physObjInSource, id: physObjInTargetId }; }); expect(Id64.isValidId64(physObjsInTarget[0].id)).to.be.true; expect(Id64.isValidId64(physObjsInTarget[1].id)).not.to.be.true; return { displayStyleInTarget, physObjsInTarget }; }; const ignoreResult = await runTransform({danglingPredecessorsBehavior: "ignore"}); expect( [...ignoreResult.displayStyleInTarget.settings.excludedElementIds] ).to.deep.equal( ignoreResult.physObjsInTarget .filter(({id}) => Id64.isValidId64(id)) .map(({id}) => id) ); sourceDb.close(); targetDbForRejected.close(); }); it("exports aspects of deferred elements", async () => { const sourceDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "DeferredElementWithAspects-Source.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbPath, { rootSubject: { name: "deferred-element-with-aspects"} }); const testSchema1Path = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "TestSchema1.ecschema.xml"); // the only two ElementUniqueAspect's in bis are ignored by the transformer, so we add our own to test their export IModelJsFs.writeFileSync(testSchema1Path, `<?xml version="1.0" encoding="UTF-8"?> <ECSchema schemaName="TestSchema1" alias="ts1" version="01.00" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.1"> <ECSchemaReference name="BisCore" version="01.00" alias="bis"/> <ECEntityClass typeName="MyUniqueAspect" description="A test unique aspect" displayLabel="a test unique aspect" modifier="Sealed"> <BaseClass>bis:ElementUniqueAspect</BaseClass> <ECProperty propertyName="MyProp1" typeName="string"/> </ECEntityClass> </ECSchema>` ); await sourceDb.importSchemas([testSchema1Path]); const myPhysicalModelId = PhysicalModel.insert(sourceDb, IModelDb.rootSubjectId, "MyPhysicalModel"); const mySpatialCategId = SpatialCategory.insert(sourceDb, IModelDb.dictionaryId, "MySpatialCateg", { color: ColorDef.black.toJSON() }); const myPhysicalObjId = sourceDb.elements.insertElement({ classFullName: PhysicalObject.classFullName, model: myPhysicalModelId, category: mySpatialCategId, code: Code.createEmpty(), userLabel: `MyPhysicalObject`, geom: IModelTransformerTestUtils.createBox(Point3d.create(1, 1, 1)), placement: Placement3d.fromJSON({ origin: { x: 1 }, angles: {} }), } as PhysicalElementProps); // because they are definition elements, display styles will be transformed first, but deferred until the excludedElements // (which are predecessors) are inserted const myDisplayStyleId = DisplayStyle3d.insert(sourceDb, IModelDb.dictionaryId, "MyDisplayStyle3d", { excludedElements: [myPhysicalObjId], }); const sourceRepositoryId = IModelTransformerTestUtils.insertRepositoryLink(sourceDb, "external.repo", "https://external.example.com/folder/external.repo", "TEST"); const sourceExternalSourceId = IModelTransformerTestUtils.insertExternalSource(sourceDb, sourceRepositoryId, "HypotheticalDisplayConfigurer"); // simulate provenance from a connector as an example of a copied over element multi aspect const multiAspectProps: ExternalSourceAspectProps = { classFullName: ExternalSourceAspect.classFullName, element: { id: myDisplayStyleId, relClassName: ElementOwnsExternalSourceAspects.classFullName }, scope: { id: sourceExternalSourceId }, source: { id: sourceExternalSourceId }, identifier: "ID", kind: ExternalSourceAspect.Kind.Element, }; sourceDb.elements.insertAspect(multiAspectProps); const uniqueAspectProps = { classFullName: "TestSchema1:MyUniqueAspect", element: { id: myDisplayStyleId, relClassName: ElementOwnsUniqueAspect.classFullName }, // eslint-disable-next-line @typescript-eslint/naming-convention myProp1: "prop_value", }; sourceDb.elements.insertAspect(uniqueAspectProps); sourceDb.saveChanges(); const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "PreserveIdOnTestModel-Target.bim"); const targetDb = SnapshotDb.createEmpty(targetDbPath, { rootSubject: sourceDb.rootSubject }); const transformer = new IModelTransformer(sourceDb, targetDb, { includeSourceProvenance: true, noProvenance: true, // don't add transformer provenance aspects, makes querying for aspects later simpler }); await transformer.processSchemas(); await transformer.processAll(); targetDb.saveChanges(); const targetExternalSourceAspects = new Array<any>(); const targetMyUniqueAspects = new Array<any>(); targetDb.withStatement("SELECT * FROM bis.ExternalSourceAspect", (stmt) => targetExternalSourceAspects.push(...stmt)); targetDb.withStatement("SELECT * FROM TestSchema1.MyUniqueAspect", (stmt) => targetMyUniqueAspects.push(...stmt)); expect(targetMyUniqueAspects).to.have.lengthOf(1); expect(targetMyUniqueAspects[0].myProp1).to.equal(uniqueAspectProps.myProp1); expect(targetExternalSourceAspects).to.have.lengthOf(1); expect(targetExternalSourceAspects[0].identifier).to.equal(multiAspectProps.identifier); sinon.restore(); sourceDb.close(); targetDb.close(); }); it("IModelTransformer processes nav property predecessors even in generated classes", async () => { const sourceDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "GeneratedNavPropPredecessors-Source.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbPath, { rootSubject: { name: "GeneratedNavPropPredecessors" } }); const testSchema1Path = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "TestSchema1.ecschema.xml"); IModelJsFs.writeFileSync(testSchema1Path, `<?xml version="1.0" encoding="UTF-8"?> <ECSchema schemaName="TestGeneratedClasses" alias="tgc" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.1"> <ECSchemaReference name="BisCore" version="01.00" alias="bis"/> <ECEntityClass typeName="TestEntity" description="a sample entity for the end of the test relationships"> <BaseClass>bis:DefinitionElement</BaseClass> <ECProperty propertyName="prop" typeName="string" description="a sample property"/> </ECEntityClass> <ECRelationshipClass typeName="ElemRel" strength="referencing" description="elem rel 1" modifier="sealed"> <Source multiplicity="(0..*)" roleLabel="refers to" polymorphic="false"> <Class class="TestElementWithNavProp"/> </Source> <Target multiplicity="(0..1)" roleLabel="is referenced by" polymorphic="false"> <Class class="TestEntity"/> </Target> </ECRelationshipClass> <ECEntityClass typeName="TestElementWithNavProp"> <BaseClass>bis:DefinitionElement</BaseClass> <ECNavigationProperty propertyName="navProp" relationshipName="ElemRel" direction="Forward" /> </ECEntityClass> </ECSchema>` ); await sourceDb.importSchemas([testSchema1Path]); const navPropTargetId = sourceDb.elements.insertElement({ classFullName: "TestGeneratedClasses:TestEntity", prop: "sample-value", model: IModelDb.dictionaryId, code: Code.createEmpty(), } as ElementProps); const elemWithNavPropId = sourceDb.elements.insertElement({ classFullName: "TestGeneratedClasses:TestElementWithNavProp", navProp: { id: navPropTargetId, relClassName: "TestGeneratedClasses:ElemRel", }, model: IModelDb.dictionaryId, code: Code.createEmpty(), } as ElementProps); const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "GeneratedNavPropPredecessors-Target.bim"); const targetDb = SnapshotDb.createEmpty(targetDbPath, { rootSubject: sourceDb.rootSubject }); class ProcessTargetLastTransformer extends IModelTransformer { public constructor(source: IModelDb, target: IModelDb, opts?: IModelTransformOptions) { super( new ( class extends IModelExporter { public override async exportElement(elementId: string) { if (elementId === navPropTargetId) { // don't export it, we'll export it later, after the holder } else if (elementId === elemWithNavPropId) { await super.exportElement(elemWithNavPropId); await super.exportElement(navPropTargetId); } else { await super.exportElement(elementId); } } } )(source), target, opts ); } } const transformer = new ProcessTargetLastTransformer(sourceDb, targetDb); await transformer.processSchemas(); await transformer.processAll(); targetDb.saveChanges(); function getNavPropContent(db: IModelDb) { let results = new Array<{ id: Id64String, navProp: RelatedElement }>(); db.withPreparedStatement( "SELECT ECInstanceId, navProp FROM TestGeneratedClasses.TestElementWithNavProp", (stmt) => { results = [...stmt]; } ); return results; } for (const navPropHolderInSource of getNavPropContent(sourceDb)) { const navPropHolderInTargetId = transformer.context.findTargetElementId(navPropHolderInSource.id); const navPropHolderInTarget = targetDb.elements.getElement(navPropHolderInTargetId); const navPropTargetInTarget = transformer.context.findTargetElementId(navPropHolderInSource.navProp.id); // cast to any to access untyped instance properties expect((navPropHolderInTarget as any)?.navProp?.id).to.equal(navPropTargetInTarget); expect((navPropHolderInTarget as any)?.navProp?.id).not.to.equal(Id64.invalid); expect((navPropHolderInTarget as any)?.navProp?.id).not.to.be.undefined; } expect(getNavPropContent(sourceDb)).to.have.length(1); expect(getNavPropContent(targetDb)).to.have.length(1); sourceDb.close(); targetDb.close(); }); it("exhaustive identity transform", async () => { const seedDb = SnapshotDb.openFile(BackendTestUtils.IModelTestUtils.resolveAssetFile("CompatibilityTestSeed.bim")); const sourceDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "ExhaustiveIdentityTransformSource.bim"); const sourceDb = SnapshotDb.createFrom(seedDb, sourceDbPath); // previously there was a bug where json display properties of models would not be transformed. This should expose that const [physicalModelId] = sourceDb.queryEntityIds({ from: "BisCore.PhysicalModel", limit: 1 }); const physicalModel = sourceDb.models.getModel(physicalModelId); physicalModel.jsonProperties.formatter.fmtFlags.linPrec = 100; physicalModel.update(); sourceDb.saveChanges(); const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "ExhaustiveIdentityTransformTarget.bim"); const targetDb = SnapshotDb.createEmpty(targetDbPath, { rootSubject: sourceDb.rootSubject }); const transformer = new IModelTransformer(sourceDb, targetDb); await transformer.processSchemas(); await transformer.processAll(); targetDb.saveChanges(); await assertIdentityTransformation(sourceDb, targetDb, transformer, { compareElemGeom: true }); const physicalModelInTargetId = transformer.context.findTargetElementId(physicalModelId); const physicalModelInTarget = targetDb.models.getModel(physicalModelInTargetId); expect(physicalModelInTarget.jsonProperties.formatter.fmtFlags.linPrec).to.equal(100); sourceDb.close(); targetDb.close(); }); it("deferred element relationships get exported", async () => { const sourceDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "DeferredElementWithRelationships-Source.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbPath, { rootSubject: { name: "deferred-element-with-relationships"} }); const testSchema1Path = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "TestSchema1.ecschema.xml"); // the only two ElementUniqueAspect's in bis are ignored by the transformer, so we add our own to test their export IModelJsFs.writeFileSync(testSchema1Path, `<?xml version="1.0" encoding="UTF-8"?> <ECSchema schemaName="TestSchema1" alias="ts1" version="01.00" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.1"> <ECSchemaReference name="BisCore" version="01.00" alias="bis"/> <ECRelationshipClass typeName="MyElemRefersToElem" strength="referencing" modifier="None"> <BaseClass>bis:ElementRefersToElements</BaseClass> <ECProperty propertyName="prop" typeName="string" description="a sample property"/> <Source multiplicity="(0..*)" roleLabel="refers to" polymorphic="true"> <Class class="bis:Element"/> </Source> <Target multiplicity="(0..*)" roleLabel="is referenced by" polymorphic="true"> <Class class="bis:Element"/> </Target> </ECRelationshipClass> </ECSchema>` ); await sourceDb.importSchemas([testSchema1Path]); const myPhysicalModelId = PhysicalModel.insert(sourceDb, IModelDb.rootSubjectId, "MyPhysicalModel"); const mySpatialCategId = SpatialCategory.insert(sourceDb, IModelDb.dictionaryId, "MySpatialCateg", { color: ColorDef.black.toJSON() }); const myPhysicalObjId = sourceDb.elements.insertElement({ classFullName: PhysicalObject.classFullName, model: myPhysicalModelId, category: mySpatialCategId, code: Code.createEmpty(), userLabel: `MyPhysicalObject`, geom: IModelTransformerTestUtils.createBox(Point3d.create(1, 1, 1)), placement: Placement3d.fromJSON({ origin: { x: 1 }, angles: {} }), } as PhysicalElementProps); // because they are definition elements, display styles will be transformed first, but deferred until the excludedElements // (which are predecessors) are inserted const myDisplayStyleId = DisplayStyle3d.insert(sourceDb, IModelDb.dictionaryId, "MyDisplayStyle3d", { excludedElements: [myPhysicalObjId], }); const relProps = { sourceId: myDisplayStyleId, targetId: myPhysicalObjId, classFullName: "TestSchema1:MyElemRefersToElem", prop: "prop", }; const _relInstId = sourceDb.relationships.insertInstance(relProps as RelationshipProps); sourceDb.saveChanges(); const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "DeferredElementWithRelationships-Target.bim"); const targetDb = SnapshotDb.createEmpty(targetDbPath, { rootSubject: sourceDb.rootSubject }); const transformer = new IModelTransformer(sourceDb, targetDb); await transformer.processSchemas(); await transformer.processAll(); targetDb.saveChanges(); const targetRelationships = new Array<any>(); targetDb.withStatement("SELECT * FROM ts1.MyElemRefersToElem", (stmt) => targetRelationships.push(...stmt)); expect(targetRelationships).to.have.lengthOf(1); expect(targetRelationships[0].prop).to.equal(relProps.prop); sinon.restore(); sourceDb.close(); targetDb.close(); }); it("IModelTransformer handles generated class nav property cycle", async () => { const sourceDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "NavPropCycleSource.bim"); const sourceDb = SnapshotDb.createEmpty(sourceDbPath, { rootSubject: { name: "GeneratedNavPropPredecessors" } }); const testSchema1Path = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "TestSchema1.ecschema.xml"); IModelJsFs.writeFileSync(testSchema1Path, `<?xml version="1.0" encoding="UTF-8"?> <ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.1"> <ECSchemaReference name="BisCore" version="01.00" alias="bis"/> <ECEntityClass typeName="A" description="an A"> <BaseClass>bis:DefinitionElement</BaseClass> <ECNavigationProperty propertyName="anotherA" relationshipName="AtoA" direction="Forward" displayLabel="Horizontal Alignment" /> </ECEntityClass> <ECRelationshipClass typeName="AtoA" strength="referencing" description="a to a" modifier="sealed"> <Source multiplicity="(0..*)" roleLabel="refers to" polymorphic="false"> <Class class="A"/> </Source> <Target multiplicity="(0..1)" roleLabel="is referenced by" polymorphic="false"> <Class class="A"/> </Target> </ECRelationshipClass> </ECSchema>` ); await sourceDb.importSchemas([testSchema1Path]); const a1Id = sourceDb.elements.insertElement({ classFullName: "TestSchema:A", // will be updated later to include this // anotherA: { id: a3Id, relClassName: "TestSchema:AtoA", }, model: IModelDb.dictionaryId, code: Code.createEmpty(), } as ElementProps); const a2Id = sourceDb.elements.insertElement({ classFullName: "TestSchema:A", anotherA: { id: a1Id, relClassName: "TestSchema:AtoA" }, model: IModelDb.dictionaryId, code: Code.createEmpty(), } as ElementProps); sourceDb.elements.updateElement({id: a1Id, anotherA: {id: a2Id, relClassName: "TestSchema:AtoA"}} as any); const a4Id = sourceDb.elements.insertElement({ classFullName: "TestSchema:A", // will be updated later to include this // anotherA: { id: a4Id, relClassName: "TestSchema:AtoA", }, model: IModelDb.dictionaryId, code: Code.createEmpty(), } as ElementProps); sourceDb.elements.updateElement({id: a4Id, anotherA: {id: a4Id, relClassName: "TestSchema:AtoA"}} as any); sourceDb.saveChanges(); const targetDbPath = IModelTransformerTestUtils.prepareOutputFile("IModelTransformer", "NavPropCycleTarget.bim"); const targetDb = SnapshotDb.createEmpty(targetDbPath, { rootSubject: sourceDb.rootSubject }); const transformer = new IModelTransformer(sourceDb, targetDb); await transformer.processSchemas(); await transformer.processAll(); targetDb.saveChanges(); await assertIdentityTransformation(sourceDb, targetDb, transformer); sourceDb.close(); targetDb.close(); }); });
the_stack
import { expect, use } from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as sinon from 'sinon'; import * as sinonChai from 'sinon-chai'; import { PopupRedirectResolver } from '../../model/public_types'; import { OperationType, ProviderId } from '../../model/enums'; import { FirebaseError } from '@firebase/util'; import { delay } from '../../../test/helpers/delay'; import { BASE_AUTH_EVENT } from '../../../test/helpers/iframe_event'; import { testAuth, testUser, TestAuth } from '../../../test/helpers/mock_auth'; import { makeMockPopupRedirectResolver } from '../../../test/helpers/mock_popup_redirect_resolver'; import { stubTimeouts, TimerMap } from '../../../test/helpers/timeout_stub'; import { AuthEvent, AuthEventType } from '../../model/popup_redirect'; import { UserInternal } from '../../model/user'; import { AuthEventManager } from '../../core/auth/auth_event_manager'; import { AuthErrorCode } from '../../core/errors'; import { OAuthProvider } from '../../core/providers/oauth'; import { UserCredentialImpl } from '../../core/user/user_credential_impl'; import * as eid from '../../core/util/event_id'; import { AuthPopup } from '../util/popup'; import * as idpTasks from '../../core/strategies/idp'; import { _Timeout, _POLL_WINDOW_CLOSE_TIMEOUT, linkWithPopup, reauthenticateWithPopup, signInWithPopup } from './popup'; import { _getInstance } from '../../../internal'; import { _createError } from '../../core/util/assert'; use(sinonChai); use(chaiAsPromised); const MATCHING_EVENT_ID = 'matching-event-id'; const OTHER_EVENT_ID = 'wrong-id'; describe('platform_browser/strategies/popup', () => { let resolver: PopupRedirectResolver; let provider: OAuthProvider; let eventManager: AuthEventManager; let authPopup: AuthPopup; let underlyingWindow: { closed: boolean }; let auth: TestAuth; let idpStubs: sinon.SinonStubbedInstance<typeof idpTasks>; let pendingTimeouts: TimerMap; beforeEach(async () => { auth = await testAuth(); eventManager = new AuthEventManager(auth); underlyingWindow = { closed: false }; authPopup = new AuthPopup(underlyingWindow as Window); provider = new OAuthProvider(ProviderId.GOOGLE); resolver = makeMockPopupRedirectResolver(eventManager, authPopup); idpStubs = sinon.stub(idpTasks); sinon.stub(eid, '_generateEventId').returns(MATCHING_EVENT_ID); pendingTimeouts = stubTimeouts(); sinon.stub(window, 'clearTimeout'); }); afterEach(() => { sinon.restore(); }); function iframeEvent(event: Partial<AuthEvent>): void { // Push the dispatch out of the synchronous flow delay(() => { eventManager.onEvent({ ...BASE_AUTH_EVENT, eventId: MATCHING_EVENT_ID, ...event }); }); } context('signInWithPopup', () => { it('completes the full flow', async () => { const cred = new UserCredentialImpl({ user: testUser(auth, 'uid'), providerId: ProviderId.GOOGLE, operationType: OperationType.SIGN_IN }); idpStubs._signIn.returns(Promise.resolve(cred)); const promise = signInWithPopup(auth, provider, resolver); iframeEvent({ type: AuthEventType.SIGN_IN_VIA_POPUP }); expect(await promise).to.eq(cred); }); it('completes the full flow with default resolver', async () => { const cred = new UserCredentialImpl({ user: testUser(auth, 'uid'), providerId: ProviderId.GOOGLE, operationType: OperationType.SIGN_IN }); auth._popupRedirectResolver = _getInstance(resolver); idpStubs._signIn.returns(Promise.resolve(cred)); const promise = signInWithPopup(auth, provider); iframeEvent({ type: AuthEventType.SIGN_IN_VIA_POPUP }); expect(await promise).to.eq(cred); }); it('errors if resolver not provided and not on auth', async () => { const cred = new UserCredentialImpl({ user: testUser(auth, 'uid'), providerId: ProviderId.GOOGLE, operationType: OperationType.SIGN_IN }); idpStubs._signIn.returns(Promise.resolve(cred)); await expect(signInWithPopup(auth, provider)).to.be.rejectedWith( FirebaseError, 'auth/argument-error' ); }); it('ignores events for another event id', async () => { const cred = new UserCredentialImpl({ user: testUser(auth, 'uid'), providerId: ProviderId.GOOGLE, operationType: OperationType.SIGN_IN }); idpStubs._signIn.returns(Promise.resolve(cred)); const promise = signInWithPopup(auth, provider, resolver); iframeEvent({ type: AuthEventType.SIGN_IN_VIA_POPUP, eventId: OTHER_EVENT_ID, error: { code: 'auth/internal-error', message: '', name: '' } }); iframeEvent({ type: AuthEventType.SIGN_IN_VIA_POPUP, eventId: MATCHING_EVENT_ID }); expect(await promise).to.eq(cred); }); it('does not call idp tasks if event is error', async () => { const cred = new UserCredentialImpl({ user: testUser(auth, 'uid'), providerId: ProviderId.GOOGLE, operationType: OperationType.SIGN_IN }); idpStubs._signIn.returns(Promise.resolve(cred)); const promise = signInWithPopup(auth, provider, resolver); iframeEvent({ type: AuthEventType.SIGN_IN_VIA_POPUP, eventId: MATCHING_EVENT_ID, error: { code: 'auth/invalid-app-credential', message: '', name: '' } }); await expect(promise).to.be.rejectedWith( FirebaseError, 'auth/invalid-app-credential' ); expect(idpStubs._signIn).not.to.have.been.called; }); it('does not error if the poll timeout trips', async () => { const cred = new UserCredentialImpl({ user: testUser(auth, 'uid'), providerId: ProviderId.GOOGLE, operationType: OperationType.SIGN_IN }); idpStubs._signIn.returns(Promise.resolve(cred)); const promise = signInWithPopup(auth, provider, resolver); delay(() => { underlyingWindow.closed = true; pendingTimeouts[_POLL_WINDOW_CLOSE_TIMEOUT.get()](); }); iframeEvent({ type: AuthEventType.SIGN_IN_VIA_POPUP }); expect(await promise).to.eq(cred); }); it('does error if the poll timeout and event timeout trip', async () => { const cred = new UserCredentialImpl({ user: testUser(auth, 'uid'), providerId: ProviderId.GOOGLE, operationType: OperationType.SIGN_IN }); idpStubs._signIn.returns(Promise.resolve(cred)); const promise = signInWithPopup(auth, provider, resolver); delay(() => { underlyingWindow.closed = true; pendingTimeouts[_POLL_WINDOW_CLOSE_TIMEOUT.get()](); pendingTimeouts[_Timeout.AUTH_EVENT](); }); iframeEvent({ type: AuthEventType.SIGN_IN_VIA_POPUP }); await expect(promise).to.be.rejectedWith( FirebaseError, 'auth/popup-closed-by-user' ); }); it('errors if webstorage support comes back negative', async () => { resolver = makeMockPopupRedirectResolver(eventManager, authPopup, false); await expect( signInWithPopup(auth, provider, resolver) ).to.be.rejectedWith(FirebaseError, 'auth/web-storage-unsupported'); }); it('passes any errors from idp task', async () => { idpStubs._signIn.returns( Promise.reject(_createError(auth, AuthErrorCode.INVALID_APP_ID)) ); const promise = signInWithPopup(auth, provider, resolver); iframeEvent({ eventId: MATCHING_EVENT_ID, type: AuthEventType.SIGN_IN_VIA_POPUP }); await expect(promise).to.be.rejectedWith( FirebaseError, 'auth/invalid-app-id' ); }); it('cancels the task if called consecutively', async () => { const cred = new UserCredentialImpl({ user: testUser(auth, 'uid'), providerId: ProviderId.GOOGLE, operationType: OperationType.SIGN_IN }); idpStubs._signIn.returns(Promise.resolve(cred)); const firstPromise = signInWithPopup(auth, provider, resolver); const secondPromise = signInWithPopup(auth, provider, resolver); iframeEvent({ type: AuthEventType.SIGN_IN_VIA_POPUP }); await expect(firstPromise).to.be.rejectedWith( FirebaseError, 'auth/cancelled-popup-request' ); expect(await secondPromise).to.eq(cred); }); }); context('linkWithPopup', () => { let user: UserInternal; beforeEach(() => { user = testUser(auth, 'uid'); }); it('completes the full flow', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.LINK }); idpStubs._link.returns(Promise.resolve(cred)); const promise = linkWithPopup(user, provider, resolver); iframeEvent({ type: AuthEventType.LINK_VIA_POPUP }); expect(await promise).to.eq(cred); }); it('completes the full flow with default resolver', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.LINK }); user.auth._popupRedirectResolver = _getInstance(resolver); idpStubs._link.returns(Promise.resolve(cred)); const promise = linkWithPopup(user, provider); iframeEvent({ type: AuthEventType.LINK_VIA_POPUP }); expect(await promise).to.eq(cred); }); it('errors if resolver not provided and not on auth', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.LINK }); idpStubs._link.returns(Promise.resolve(cred)); await expect(linkWithPopup(user, provider)).to.be.rejectedWith( FirebaseError, 'auth/argument-error' ); }); it('ignores events for another event id', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.LINK }); idpStubs._link.returns(Promise.resolve(cred)); const promise = linkWithPopup(user, provider, resolver); iframeEvent({ type: AuthEventType.LINK_VIA_POPUP, eventId: OTHER_EVENT_ID, error: { code: 'auth/internal-error', message: '', name: '' } }); iframeEvent({ type: AuthEventType.LINK_VIA_POPUP, eventId: MATCHING_EVENT_ID }); expect(await promise).to.eq(cred); }); it('does not call idp tasks if event is error', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.LINK }); idpStubs._link.returns(Promise.resolve(cred)); const promise = linkWithPopup(user, provider, resolver); iframeEvent({ type: AuthEventType.LINK_VIA_POPUP, eventId: MATCHING_EVENT_ID, error: { code: 'auth/invalid-app-credential', message: '', name: '' } }); await expect(promise).to.be.rejectedWith( FirebaseError, 'auth/invalid-app-credential' ); expect(idpStubs._link).not.to.have.been.called; }); it('does not error if the poll timeout trips', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.LINK }); idpStubs._link.returns(Promise.resolve(cred)); const promise = linkWithPopup(user, provider, resolver); delay(() => { underlyingWindow.closed = true; pendingTimeouts[_POLL_WINDOW_CLOSE_TIMEOUT.get()](); }); iframeEvent({ type: AuthEventType.LINK_VIA_POPUP }); expect(await promise).to.eq(cred); }); it('does error if the poll timeout and event timeout trip', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.LINK }); idpStubs._link.returns(Promise.resolve(cred)); const promise = linkWithPopup(user, provider, resolver); delay(() => { underlyingWindow.closed = true; pendingTimeouts[_POLL_WINDOW_CLOSE_TIMEOUT.get()](); pendingTimeouts[_Timeout.AUTH_EVENT](); }); iframeEvent({ type: AuthEventType.LINK_VIA_POPUP }); await expect(promise).to.be.rejectedWith( FirebaseError, 'auth/popup-closed-by-user' ); }); it('errors if webstorage support comes back negative', async () => { resolver = makeMockPopupRedirectResolver(eventManager, authPopup, false); await expect(linkWithPopup(user, provider, resolver)).to.be.rejectedWith( FirebaseError, 'auth/web-storage-unsupported' ); }); it('passes any errors from idp task', async () => { idpStubs._link.returns( Promise.reject(_createError(auth, AuthErrorCode.INVALID_APP_ID)) ); const promise = linkWithPopup(user, provider, resolver); iframeEvent({ eventId: MATCHING_EVENT_ID, type: AuthEventType.LINK_VIA_POPUP }); await expect(promise).to.be.rejectedWith( FirebaseError, 'auth/invalid-app-id' ); }); it('cancels the task if called consecutively', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.LINK }); idpStubs._link.returns(Promise.resolve(cred)); const firstPromise = linkWithPopup(user, provider, resolver); const secondPromise = linkWithPopup(user, provider, resolver); iframeEvent({ type: AuthEventType.LINK_VIA_POPUP }); await expect(firstPromise).to.be.rejectedWith( FirebaseError, 'auth/cancelled-popup-request' ); expect(await secondPromise).to.eq(cred); }); }); context('reauthenticateWithPopup', () => { let user: UserInternal; beforeEach(() => { user = testUser(auth, 'uid'); }); it('completes the full flow', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.REAUTHENTICATE }); idpStubs._reauth.returns(Promise.resolve(cred)); const promise = reauthenticateWithPopup(user, provider, resolver); iframeEvent({ type: AuthEventType.REAUTH_VIA_POPUP }); expect(await promise).to.eq(cred); }); it('completes the full flow with default resolver', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.REAUTHENTICATE }); user.auth._popupRedirectResolver = _getInstance(resolver); idpStubs._reauth.returns(Promise.resolve(cred)); const promise = reauthenticateWithPopup(user, provider); iframeEvent({ type: AuthEventType.REAUTH_VIA_POPUP }); expect(await promise).to.eq(cred); }); it('errors if resolver not provided and not on auth', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.REAUTHENTICATE }); idpStubs._reauth.returns(Promise.resolve(cred)); await expect(reauthenticateWithPopup(user, provider)).to.be.rejectedWith( FirebaseError, 'auth/argument-error' ); }); it('ignores events for another event id', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.REAUTHENTICATE }); idpStubs._reauth.returns(Promise.resolve(cred)); const promise = reauthenticateWithPopup(user, provider, resolver); iframeEvent({ type: AuthEventType.REAUTH_VIA_POPUP, eventId: OTHER_EVENT_ID, error: { code: 'auth/internal-error', message: '', name: '' } }); iframeEvent({ type: AuthEventType.REAUTH_VIA_POPUP, eventId: MATCHING_EVENT_ID }); expect(await promise).to.eq(cred); }); it('does not call idp tasks if event is error', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.REAUTHENTICATE }); idpStubs._reauth.returns(Promise.resolve(cred)); const promise = reauthenticateWithPopup(user, provider, resolver); iframeEvent({ type: AuthEventType.REAUTH_VIA_POPUP, eventId: MATCHING_EVENT_ID, error: { code: 'auth/invalid-app-credential', message: '', name: '' } }); await expect(promise).to.be.rejectedWith( FirebaseError, 'auth/invalid-app-credential' ); expect(idpStubs._reauth).not.to.have.been.called; }); it('does not error if the poll timeout trips', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.REAUTHENTICATE }); idpStubs._reauth.returns(Promise.resolve(cred)); const promise = reauthenticateWithPopup(user, provider, resolver); delay(() => { underlyingWindow.closed = true; pendingTimeouts[_POLL_WINDOW_CLOSE_TIMEOUT.get()](); }); iframeEvent({ type: AuthEventType.REAUTH_VIA_POPUP }); expect(await promise).to.eq(cred); }); it('errors if webstorage support comes back negative', async () => { resolver = makeMockPopupRedirectResolver(eventManager, authPopup, false); await expect( reauthenticateWithPopup(user, provider, resolver) ).to.be.rejectedWith(FirebaseError, 'auth/web-storage-unsupported'); }); it('does error if the poll timeout and event timeout trip', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.REAUTHENTICATE }); idpStubs._reauth.returns(Promise.resolve(cred)); const promise = reauthenticateWithPopup(user, provider, resolver); delay(() => { underlyingWindow.closed = true; pendingTimeouts[_POLL_WINDOW_CLOSE_TIMEOUT.get()](); pendingTimeouts[_Timeout.AUTH_EVENT](); }); iframeEvent({ type: AuthEventType.REAUTH_VIA_POPUP }); await expect(promise).to.be.rejectedWith( FirebaseError, 'auth/popup-closed-by-user' ); }); it('passes any errors from idp task', async () => { idpStubs._reauth.returns( Promise.reject(_createError(auth, AuthErrorCode.INVALID_APP_ID)) ); const promise = reauthenticateWithPopup(user, provider, resolver); iframeEvent({ eventId: MATCHING_EVENT_ID, type: AuthEventType.REAUTH_VIA_POPUP }); await expect(promise).to.be.rejectedWith( FirebaseError, 'auth/invalid-app-id' ); }); it('cancels the task if called consecutively', async () => { const cred = new UserCredentialImpl({ user, providerId: ProviderId.GOOGLE, operationType: OperationType.REAUTHENTICATE }); idpStubs._reauth.returns(Promise.resolve(cred)); const firstPromise = reauthenticateWithPopup(user, provider, resolver); const secondPromise = reauthenticateWithPopup(user, provider, resolver); iframeEvent({ type: AuthEventType.REAUTH_VIA_POPUP }); await expect(firstPromise).to.be.rejectedWith( FirebaseError, 'auth/cancelled-popup-request' ); expect(await secondPromise).to.eq(cred); }); }); });
the_stack
import { unlinkSync, existsSync } from 'fs'; import { buildSchema } from 'graphql'; import { PubSub } from 'graphql-subscriptions'; import * as Knex from 'knex'; import { CRUDService, GraphbackCoreMetadata } from '@graphback/core'; import { migrateDB, removeNonSafeOperationsFilter } from 'graphql-migrations'; import { SQLiteKnexDBDataProvider } from '../../src/SQLiteKnexDBDataProvider'; const dbPath = `${__dirname}/db.sqlite`; const pubSub = new PubSub(); afterEach(() => { if (existsSync(dbPath)) { unlinkSync(dbPath) } }) const setup = async ({ schemaSDL, seedData }: { schemaSDL?: string, seedData?: { [tableName: string]: any | any[] } } = {}) => { if (!schemaSDL) { schemaSDL = `""" @model """ type Todo { id: ID! text: String }` } const dbConfig: Knex.Config = { client: 'sqlite3', connection: { filename: dbPath, }, useNullAsDefault: true } const schema = buildSchema(schemaSDL) const defautCrudConfig = { "create": true, "update": true, "findOne": true, "find": true, "delete": true, "subCreate": true, "subUpdate": true, "subDelete": true } const metadata = new GraphbackCoreMetadata({ crudMethods: defautCrudConfig }, schema); await migrateDB(dbConfig, schema, { operationFilter: removeNonSafeOperationsFilter }) const db = Knex(dbConfig) if (seedData) { for (const [tableName, data] of Object.entries(seedData)) { await db(tableName).insert(data) } } const services: { [name: string]: CRUDService } = {} const models = metadata.getModelDefinitions(); for (const model of models) { const modelProvider = new SQLiteKnexDBDataProvider(model, db); const publishConfig = { subCreate: true, subDelete: true, subUpdate: true } services[model.graphqlType.name] = new CRUDService(model, modelProvider, { pubSub, crudOptions: publishConfig }) } return { schema, services } } test('create Todo', async (done) => { const { services } = await setup() const subId = await pubSub.subscribe("CREATE_TODO", ({ newTodo }) => { expect(newTodo).toEqual({ id: 1, text: "create a todo" }); done(); pubSub.unsubscribe(subId); }); const todo = await services.Todo.create({ text: 'create a todo' }); expect(todo.id).toEqual(1); expect(todo.text).toEqual('create a todo'); }); test('update Todo', async (done) => { const { services } = await setup({ seedData: { todo: { text: 'my first todo' } } }); const subId = await pubSub.subscribe("UPDATE_TODO", ({ updatedTodo }) => { expect(updatedTodo).toEqual({ id: 1, text: 'my updated first todo' }); done(); pubSub.unsubscribe(subId); }); const todo = await services.Todo.update({ id: 1, text: 'my updated first todo', }); expect(todo.id).toEqual(1); expect(todo.text).toEqual('my updated first todo'); }); test('delete Todo', async (done) => { const { services } = await setup({ seedData: { todo: [{ text: 'my first todo' }, { text: 'my second todo' }] } }); const subId = await pubSub.subscribe("DELETE_TODO", ({ deletedTodo }) => { expect(deletedTodo).toEqual({ id: 2, text: "my second todo" }); done(); pubSub.unsubscribe(subId); }); const data = await services.Todo.delete({ id: 2 }); expect(data.id).toEqual(2); }); test('find Todo by text', async () => { const { services } = await setup({ seedData: { todo: [{ text: 'my first todo' }, { text: 'the second todo' }] } }) const todoResults = await services.Todo.findBy({ filter: { text: { eq: 'the second todo' }, } }); expect(todoResults.items.length).toEqual(1); expect(todoResults.items[0].id).toEqual(2); }); test('findBy with no arguments should work', async () => { const { services } = await setup({ seedData: { todo: [{ text: 'my first todo' }, { text: 'the second todo' }] } }) const todoResults = await services.Todo.findBy(); expect(todoResults.items).toHaveLength(2); }) test('delete User by custom ID field', async () => { const { services } = await setup({ schemaSDL: ` """ @model """ type User { """ @id """ email: String name: String } `, seedData: { user: [{ email: 'johndoe@email.com' }, { email: 'test@test.com' }] } }) const result = await services.User.delete({ email: 'test@test.com' }); expect(result.email).toEqual('test@test.com') }); test('insertion of User with same custom ID field more than once should fail', async () => { const { services } = await setup({ schemaSDL: ` """ @model """ type User { """ @id """ email: String name: String } `, seedData: { user: [{ email: 'johndoe@email.com', name: 'John Doe' }] } }); try { const result = await services.User.create({ email: 'johndoe@email.com', name: 'John doe' }); expect(result).toBeFalsy(); // should not reach here because an error should have been thrown by line above } catch (e) { expect(e.code).toBe("SQLITE_CONSTRAINT"); expect(e.message).toBe("insert into `user` (`email`, `name`) values ('johndoe@email.com', 'John doe') - SQLITE_CONSTRAINT: UNIQUE constraint failed: user.email"); } }); test('update User by custom ID field', async () => { const { services } = await setup({ schemaSDL: ` """ @model """ type User { """ @id """ email: String name: String } `, seedData: { user: [{ email: 'johndoe@email.com' }] } }) const result = await services.User.update({ email: 'johndoe@email.com', name: 'John Doe' }) expect(result.name).toEqual('John Doe') }); test('find users where name starts with "John"', async () => { const { services } = await setup({ schemaSDL: ` """ @model """ type User { id: ID name: String } `, seedData: { user: [ { name: 'John Doe' }, { name: 'Johnny Doe' }, { name: 'James Doe' } ] } }) const result = await services.User.findBy({ filter: { name: { startsWith: 'John' } } }) expect(result.items).toHaveLength(2) }) test('find users where name ends with "Jones"', async () => { const { services } = await setup({ schemaSDL: ` """ @model """ type User { id: ID name: String } `, seedData: { user: [ { name: 'John Doe' }, { name: 'Johnny Jones' }, { name: 'James Doe' } ] } }) const result = await services.User.findBy({ filter: { name: { endsWith: 'Jones' } } }) expect(result.items).toHaveLength(1) }) test('find users where name not eq "John"', async () => { const { services } = await setup({ schemaSDL: ` """ @model """ type User { id: ID name: String } `, seedData: { user: [ { name: 'John' }, { name: 'John' }, { name: 'James' } ] } }) const result = await services.User.findBy({ filter: { name: { ne: 'John' } } }) expect(result.items).toHaveLength(1) expect(result.items[0].name).toBe('James') }) test('find users where name in array', async () => { const { services } = await setup({ schemaSDL: ` """ @model """ type User { id: ID name: String } `, seedData: { user: [ { name: 'John' }, { name: 'Sarah' }, { name: 'James' } ] } }) const result = await services.User.findBy({ filter: { name: { in: ['Sarah', 'John'] } } }) expect(result.items).toHaveLength(2) }) test('find users where name contains "John"', async () => { const { services } = await setup({ schemaSDL: ` """ @model """ type User { id: ID name: String } `, seedData: { user: [ { name: 'Mr. John Jones' }, { name: 'Ms. Sarah Johnson' }, { name: 'Ms. Sarah Jones' }, { name: 'Mr. James Johnston' } ] } }) const result = await services.User.findBy({ filter: { name: { contains: 'John' } } }) expect(result.items).toHaveLength(3) }) test('find users where friends == 1', async () => { const { services } = await setup({ schemaSDL: ` """ @model """ type User { id: ID name: String friends: Int } `, seedData: { user: [ { name: 'John', friends: 1 }, { name: 'Sarah', friends: 20 }, { name: 'Sandra', friends: 30 }, { name: 'Enda', friends: 50 }, { name: 'Eamon', friends: 0 }, { name: 'Isabelle', friends: 100 } ] } }) const result = await services.User.findBy({ filter: { friends: { eq: 1 } } }) expect(result.items).toHaveLength(1) }) test('find users where friends < 1', async () => { const { services } = await setup({ schemaSDL: ` """ @model """ type User { id: ID name: String friends: Int } `, seedData: { user: [ { name: 'John', friends: 1 }, { name: 'Sarah', friends: 20 }, { name: 'Sandra', friends: 30 }, { name: 'Enda', friends: 50 }, { name: 'Eamon', friends: 0 }, { name: 'Isabelle', friends: 100 } ] } }) const result = await services.User.findBy({ filter: { friends: { lt: 20 } } }) expect(result.items).toHaveLength(2) }) test('find users where friends <= 1', async () => { const { services } = await setup({ schemaSDL: ` """ @model """ type User { id: ID name: String friends: Int } `, seedData: { user: [ { name: 'John', friends: 1 }, { name: 'Sarah', friends: 20 }, { name: 'Sandra', friends: 30 }, { name: 'Enda', friends: 50 }, { name: 'Eamon', friends: 0 }, { name: 'Isabelle', friends: 100 } ] } }) const result = await services.User.findBy({ filter: { friends: { le: 1 } } }) expect(result.items).toHaveLength(2) }) test('find users where friends > 30', async () => { const { services } = await setup({ schemaSDL: ` """ @model """ type User { id: ID name: String friends: Int } `, seedData: { user: [ { name: 'John', friends: 1 }, { name: 'Sarah', friends: 20 }, { name: 'Sandra', friends: 30 }, { name: 'Enda', friends: 50 }, { name: 'Eamon', friends: 0 }, { name: 'Isabelle', friends: 100 } ] } }) const result = await services.User.findBy({ filter: { friends: { gt: 30 } } }) expect(result.items).toHaveLength(2) }) test('find users where friends >= 50', async () => { const { services } = await setup({ schemaSDL: ` """ @model """ type User { id: ID name: String friends: Int } `, seedData: { user: [ { name: 'John', friends: 1 }, { name: 'Sarah', friends: 20 }, { name: 'Sandra', friends: 30 }, { name: 'Enda', friends: 50 }, { name: 'Eamon', friends: 0 }, { name: 'Isabelle', friends: 100 } ] } }) const result = await services.User.findBy({ filter: { friends: { ge: 50 } } }) expect(result.items).toHaveLength(2) })
the_stack
import { AddressInfo } from "net"; import { Server } from "http"; import { exportPKCS8, generateKeyPair, KeyLike, exportSPKI, SignJWT, } from "jose"; import expressJwt from "express-jwt"; import { v4 as uuidv4 } from "uuid"; import exitHook, { IAsyncExitHookDoneCallback } from "async-exit-hook"; import { CactusNode, Consortium, ConsortiumDatabase, ConsortiumMember, IPluginKeychain, Ledger, LedgerType, } from "@hyperledger/cactus-core-api"; import { PluginRegistry } from "@hyperledger/cactus-core"; import { LogLevelDesc, Logger, LoggerProvider, Servers, } from "@hyperledger/cactus-common"; import { ApiServer, AuthorizationProtocol, ConfigService, IAuthorizationConfig, } from "@hyperledger/cactus-cmd-api-server"; import { PluginConsortiumManual } from "@hyperledger/cactus-plugin-consortium-manual"; import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; import { PluginLedgerConnectorQuorum, Web3SigningCredentialType, DefaultApi as QuorumApi, } from "@hyperledger/cactus-plugin-ledger-connector-quorum"; import { PluginLedgerConnectorBesu, DefaultApi as BesuApi, } from "@hyperledger/cactus-plugin-ledger-connector-besu"; import { PluginLedgerConnectorFabric, DefaultApi as FabricApi, DefaultEventHandlerStrategy, } from "@hyperledger/cactus-plugin-ledger-connector-fabric"; import { SupplyChainAppDummyInfrastructure, org1Env, } from "./infrastructure/supply-chain-app-dummy-infrastructure"; import { Configuration, DefaultApi as SupplyChainApi, } from "@hyperledger/cactus-example-supply-chain-business-logic-plugin"; import { SupplyChainCactusPlugin } from "@hyperledger/cactus-example-supply-chain-business-logic-plugin"; import { DiscoveryOptions } from "fabric-network"; export interface ISupplyChainAppOptions { disableSignalHandlers?: true; logLevel?: LogLevelDesc; keychain?: IPluginKeychain; } export type ShutdownHook = () => Promise<void>; //TODO: Generate fabric connector and set in the pluginRegistry export class SupplyChainApp { private readonly log: Logger; private readonly shutdownHooks: ShutdownHook[]; private readonly ledgers: SupplyChainAppDummyInfrastructure; public readonly keychain: IPluginKeychain; private _besuApiClient?: BesuApi; private _quorumApiClient?: QuorumApi; private _fabricApiClient?: FabricApi; private authorizationConfig?: IAuthorizationConfig; private token?: string; public get besuApiClientOrThrow(): BesuApi { if (this._besuApiClient) { return this._besuApiClient; } else { throw new Error("Invalid state: ledgers were not started yet."); } } public get quorumApiClientOrThrow(): QuorumApi { if (this._quorumApiClient) { return this._quorumApiClient; } else { throw new Error("Invalid state: ledgers were not started yet."); } } public get fabricApiClientOrThrow(): FabricApi { if (this._fabricApiClient) { return this._fabricApiClient; } else { throw new Error("Invalid state: ledgers were not started yet."); } } public constructor(public readonly options: ISupplyChainAppOptions) { const fnTag = "SupplyChainApp#constructor()"; if (!options) { throw new Error(`${fnTag} options parameter is falsy`); } const { logLevel } = options; const level = logLevel || "INFO"; const label = "supply-chain-app"; this.log = LoggerProvider.getOrCreate({ level, label }); if (this.options.keychain) { this.keychain = this.options.keychain; this.log.info("Reusing the provided keychain plugin..."); } else { this.log.info("Instantiating new keychain plugin..."); this.keychain = new PluginKeychainMemory({ instanceId: uuidv4(), keychainId: uuidv4(), logLevel: this.options.logLevel || "INFO", }); } this.log.info("KeychainID=%o", this.keychain.getKeychainId()); this.ledgers = new SupplyChainAppDummyInfrastructure({ logLevel, keychain: this.keychain, }); this.shutdownHooks = []; } async getOrCreateToken(): Promise<string> { if (!this.token) { await this.createAuthorizationConfig(); } return this.token as string; } async getOrCreateAuthorizationConfig(): Promise<IAuthorizationConfig> { if (!this.authorizationConfig) { await this.createAuthorizationConfig(); } return this.authorizationConfig as IAuthorizationConfig; } async createAuthorizationConfig(): Promise<void> { const jwtKeyPair = await generateKeyPair("RS256", { modulusLength: 4096 }); const jwtPrivateKeyPem = await exportPKCS8(jwtKeyPair.privateKey); const expressJwtOptions: expressJwt.Options = { algorithms: ["RS256"], secret: jwtPrivateKeyPem, audience: uuidv4(), issuer: uuidv4(), }; const jwtPayload = { name: "Peter", location: "London" }; this.token = await new SignJWT(jwtPayload) .setProtectedHeader({ alg: "RS256", }) .setIssuer(expressJwtOptions.issuer) .setAudience(expressJwtOptions.audience) .sign(jwtKeyPair.privateKey); this.authorizationConfig = { unprotectedEndpointExemptions: [], expressJwtOptions, socketIoJwtOptions: { secret: jwtPrivateKeyPem, }, }; } public async start(): Promise<IStartInfo> { this.log.debug(`Starting SupplyChainApp...`); if (!this.options.disableSignalHandlers) { exitHook((callback: IAsyncExitHookDoneCallback) => { this.stop().then(callback); }); this.log.debug(`Registered signal handlers for graceful auto-shutdown`); } await this.ledgers.start(); this.onShutdown(() => this.ledgers.stop()); const contractsInfo = await this.ledgers.deployContracts(); const besuAccount = await this.ledgers.besu.createEthTestAccount(); await this.keychain.set(besuAccount.address, besuAccount.privateKey); const quorumAccount = await this.ledgers.quorum.createEthTestAccount(); await this.keychain.set(quorumAccount.address, quorumAccount.privateKey); const enrollAdminOut = await this.ledgers.fabric.enrollAdmin(); const adminWallet = enrollAdminOut[1]; const [userIdentity] = await this.ledgers.fabric.enrollUser(adminWallet); const fabricUserKeychainKey = "user2"; const fabricUserKeychainValue = JSON.stringify(userIdentity); await this.keychain.set(fabricUserKeychainKey, fabricUserKeychainValue); // Reserve the ports where the Cactus nodes will run API servers, GUI const httpApiA = await Servers.startOnPort(4000, "0.0.0.0"); const httpApiB = await Servers.startOnPort(4100, "0.0.0.0"); const httpApiC = await Servers.startOnPort(4200, "0.0.0.0"); const httpGuiA = await Servers.startOnPort(3000, "0.0.0.0"); const httpGuiB = await Servers.startOnPort(3100, "0.0.0.0"); const httpGuiC = await Servers.startOnPort(3200, "0.0.0.0"); const addressInfoA = httpApiA.address() as AddressInfo; const nodeApiHostA = `http://localhost:${addressInfoA.port}`; const addressInfoB = httpApiB.address() as AddressInfo; const nodeApiHostB = `http://localhost:${addressInfoB.port}`; const addressInfoC = httpApiC.address() as AddressInfo; const nodeApiHostC = `http://localhost:${addressInfoC.port}`; const token = await this.getOrCreateToken(); const baseOptions = { headers: { Authorization: `Bearer ${token}` } }; const besuConfig = new Configuration({ basePath: nodeApiHostA, baseOptions, }); const quorumConfig = new Configuration({ basePath: nodeApiHostB, baseOptions, }); const fabricConfig = new Configuration({ basePath: nodeApiHostC, baseOptions, }); const besuApiClient = new BesuApi(besuConfig); const quorumApiClient = new QuorumApi(quorumConfig); const fabricApiClient = new FabricApi(fabricConfig); const keyPairA = await generateKeyPair("ES256K"); const keyPairPemA = await exportPKCS8(keyPairA.privateKey); const keyPairB = await generateKeyPair("ES256K"); const keyPairPemB = await exportPKCS8(keyPairB.privateKey); const keyPairC = await generateKeyPair("ES256K"); const keyPairPemC = await exportPKCS8(keyPairC.privateKey); const consortiumDatabase = await this.createConsortium( httpApiA, httpApiB, httpApiC, keyPairA.publicKey, keyPairB.publicKey, keyPairC.publicKey, ); const consortiumPrettyJson = JSON.stringify(consortiumDatabase, null, 4); this.log.info(`Created Consortium definition: %o`, consortiumPrettyJson); this.log.info(`Configuring Cactus Node for Ledger A...`); const rpcApiHostA = await this.ledgers.besu.getRpcApiHttpHost(); const rpcApiWsHostA = await this.ledgers.besu.getRpcApiWsHost(); const rpcApiHostB = await this.ledgers.quorum.getRpcApiHttpHost(); const connectionProfile = await this.ledgers.fabric.getConnectionProfileOrg1(); const sshConfig = await this.ledgers.fabric.getSshConfig(); const registryA = new PluginRegistry({ plugins: [ new PluginConsortiumManual({ instanceId: "PluginConsortiumManual_A", consortiumDatabase, keyPairPem: keyPairPemA, logLevel: this.options.logLevel, ctorArgs: { baseOptions: { headers: { Authorization: `Bearer ${token}` }, }, }, }), new SupplyChainCactusPlugin({ logLevel: this.options.logLevel, contracts: contractsInfo, instanceId: uuidv4(), besuApiClient, quorumApiClient, fabricApiClient, web3SigningCredential: { keychainEntryKey: besuAccount.address, keychainId: this.keychain.getKeychainId(), type: Web3SigningCredentialType.CactusKeychainRef, }, }), this.keychain, ], }); const connectorBesu = new PluginLedgerConnectorBesu({ instanceId: "PluginLedgerConnectorBesu_A", rpcApiHttpHost: rpcApiHostA, rpcApiWsHost: rpcApiWsHostA, pluginRegistry: registryA, logLevel: this.options.logLevel, }); registryA.add(connectorBesu); const apiServerA = await this.startNode(httpApiA, httpGuiA, registryA); this.log.info(`Configuring Cactus Node for Ledger B...`); const registryB = new PluginRegistry({ plugins: [ new PluginConsortiumManual({ instanceId: "PluginConsortiumManual_B", consortiumDatabase, keyPairPem: keyPairPemB, logLevel: this.options.logLevel, ctorArgs: { baseOptions: { headers: { Authorization: `Bearer ${token}` }, }, }, }), new SupplyChainCactusPlugin({ logLevel: this.options.logLevel, contracts: contractsInfo, instanceId: uuidv4(), besuApiClient, quorumApiClient, fabricApiClient, web3SigningCredential: { keychainEntryKey: quorumAccount.address, keychainId: this.keychain.getKeychainId(), type: Web3SigningCredentialType.CactusKeychainRef, }, }), this.keychain, ], }); const quorumConnector = new PluginLedgerConnectorQuorum({ instanceId: "PluginLedgerConnectorQuorum_B", rpcApiHttpHost: rpcApiHostB, logLevel: this.options.logLevel, pluginRegistry: registryB, }); registryB.add(quorumConnector); const apiServerB = await this.startNode(httpApiB, httpGuiB, registryB); this.log.info(`Configuring Cactus Node for Ledger C...`); const registryC = new PluginRegistry({ plugins: [ new PluginConsortiumManual({ instanceId: "PluginConsortiumManual_C", consortiumDatabase, keyPairPem: keyPairPemC, logLevel: "INFO", ctorArgs: { baseOptions: { headers: { Authorization: `Bearer ${token}` }, }, }, }), new SupplyChainCactusPlugin({ logLevel: "INFO", contracts: contractsInfo, instanceId: uuidv4(), besuApiClient, quorumApiClient, fabricApiClient, fabricEnvironment: org1Env, }), this.keychain, ], }); const discoveryOptions: DiscoveryOptions = { enabled: true, asLocalhost: true, }; const fabricConnector = new PluginLedgerConnectorFabric({ instanceId: "PluginLedgerConnectorFabric_C", dockerBinary: "/usr/local/bin/docker", peerBinary: "peer", cliContainerEnv: org1Env, connectionProfile: connectionProfile, sshConfig: sshConfig, logLevel: "INFO", pluginRegistry: registryC, discoveryOptions, eventHandlerOptions: { strategy: DefaultEventHandlerStrategy.NetworkScopeAllfortx, commitTimeout: 300, }, }); registryC.add(fabricConnector); const apiServerC = await this.startNode(httpApiC, httpGuiC, registryC); this.log.info(`JWT generated by the application: ${token}`); return { apiServerA, apiServerB, apiServerC, besuApiClient, fabricApiClient, quorumApiClient, supplyChainApiClientA: new SupplyChainApi( new Configuration({ basePath: nodeApiHostA, baseOptions }), ), supplyChainApiClientB: new SupplyChainApi( new Configuration({ basePath: nodeApiHostA, baseOptions }), ), supplyChainApiClientC: new SupplyChainApi( new Configuration({ basePath: nodeApiHostA, baseOptions }), ), }; } public async stop(): Promise<void> { for (const hook of this.shutdownHooks) { await hook(); // FIXME add timeout here so that shutdown does not hang } } public onShutdown(hook: ShutdownHook): void { this.shutdownHooks.push(hook); } public async createConsortium( serverA: Server, serverB: Server, serverC: Server, keyPairA: KeyLike, keyPairB: KeyLike, keyPairC: KeyLike, ): Promise<ConsortiumDatabase> { const consortiumName = "Example Supply Chain Consortium"; const consortiumId = uuidv4(); const memberIdA = uuidv4(); const nodeIdA = uuidv4(); const addressInfoA = serverA.address() as AddressInfo; const nodeApiHostA = `http://localhost:${addressInfoA.port}`; const publickKeyPemA = await exportSPKI(keyPairA); const cactusNodeA: CactusNode = { nodeApiHost: nodeApiHostA, memberId: memberIdA, publicKeyPem: publickKeyPemA, consortiumId, id: nodeIdA, pluginInstanceIds: [], ledgerIds: [], }; const memberA: ConsortiumMember = { id: memberIdA, nodeIds: [cactusNodeA.id], name: "Example Manufacturer Corp", }; const ledger1 = { id: "BesuDemoLedger", ledgerType: LedgerType.Besu1X, }; cactusNodeA.ledgerIds.push(ledger1.id); const memberIdB = uuidv4(); const nodeIdB = uuidv4(); const addressInfoB = serverB.address() as AddressInfo; const nodeApiHostB = `http://localhost:${addressInfoB.port}`; const publickKeyPemB = await exportSPKI(keyPairB); const cactusNodeB: CactusNode = { nodeApiHost: nodeApiHostB, memberId: memberIdB, publicKeyPem: publickKeyPemB, consortiumId, id: nodeIdB, pluginInstanceIds: [], ledgerIds: [], }; const memberB: ConsortiumMember = { id: memberIdB, nodeIds: [cactusNodeB.id], name: "Example Retailer Corp", }; const ledger2: Ledger = { id: "QuorumDemoLedger", ledgerType: LedgerType.Quorum2X, }; cactusNodeB.ledgerIds.push(ledger2.id); const memberIdC = uuidv4(); const nodeIdC = uuidv4(); const addressInfoC = serverC.address() as AddressInfo; const nodeApiHostC = `http://localhost:${addressInfoC.port}`; const publickKeyPemC = await exportSPKI(keyPairC); const cactusNodeC: CactusNode = { nodeApiHost: nodeApiHostC, memberId: memberIdC, publicKeyPem: publickKeyPemC, consortiumId, id: nodeIdC, pluginInstanceIds: [], ledgerIds: [], }; const memberC: ConsortiumMember = { id: memberIdC, nodeIds: [cactusNodeC.id], name: "TODO", }; const ledger3: Ledger = { id: "FabricDemoLedger", ledgerType: LedgerType.Fabric14X, }; cactusNodeC.ledgerIds.push(ledger3.id); const consortium: Consortium = { id: consortiumId, name: consortiumName, mainApiHost: nodeApiHostA, memberIds: [memberA.id, memberB.id, memberC.id], }; const consortiumDatabase: ConsortiumDatabase = { cactusNode: [cactusNodeA, cactusNodeB, cactusNodeC], consortium: [consortium], consortiumMember: [memberA, memberB, memberC], ledger: [ledger1, ledger2, ledger3], pluginInstance: [], }; return consortiumDatabase; } public async startNode( httpServerApi: Server, httpServerCockpit: Server, pluginRegistry: PluginRegistry, ): Promise<ApiServer> { const addressInfoApi = httpServerApi.address() as AddressInfo; const addressInfoCockpit = httpServerCockpit.address() as AddressInfo; const configService = new ConfigService(); const config = await configService.getOrCreate(); const properties = config.getProperties(); properties.plugins = []; properties.configFile = ""; properties.apiPort = addressInfoApi.port; properties.apiHost = addressInfoApi.address; properties.cockpitEnabled = true; properties.cockpitHost = addressInfoCockpit.address; properties.cockpitPort = addressInfoCockpit.port; properties.grpcPort = 0; // TODO - make this configurable as well properties.logLevel = this.options.logLevel || "INFO"; properties.authorizationProtocol = AuthorizationProtocol.JSON_WEB_TOKEN; properties.authorizationConfigJson = await this.getOrCreateAuthorizationConfig(); const apiServer = new ApiServer({ config: properties, httpServerApi, httpServerCockpit, pluginRegistry, }); this.onShutdown(() => apiServer.shutdown()); await apiServer.start(); return apiServer; } } export interface IStartInfo { readonly apiServerA: ApiServer; readonly apiServerB: ApiServer; readonly apiServerC: ApiServer; readonly besuApiClient: BesuApi; readonly quorumApiClient: QuorumApi; readonly fabricApiClient: FabricApi; readonly supplyChainApiClientA: SupplyChainApi; readonly supplyChainApiClientB: SupplyChainApi; readonly supplyChainApiClientC: SupplyChainApi; }
the_stack
import * as pb_1 from "google-protobuf"; export namespace common.query { export class Query extends pb_1.Message { constructor(data?: any[] | { policy?: string[]; address?: string; requesting_relay?: string; requesting_network?: string; certificate?: string; requestor_signature?: string; nonce?: string; request_id?: string; requesting_org?: string; }) { super(); pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], []); if (!Array.isArray(data) && typeof data == "object") { if ("policy" in data && data.policy != undefined) { this.policy = data.policy; } if ("address" in data && data.address != undefined) { this.address = data.address; } if ("requesting_relay" in data && data.requesting_relay != undefined) { this.requesting_relay = data.requesting_relay; } if ("requesting_network" in data && data.requesting_network != undefined) { this.requesting_network = data.requesting_network; } if ("certificate" in data && data.certificate != undefined) { this.certificate = data.certificate; } if ("requestor_signature" in data && data.requestor_signature != undefined) { this.requestor_signature = data.requestor_signature; } if ("nonce" in data && data.nonce != undefined) { this.nonce = data.nonce; } if ("request_id" in data && data.request_id != undefined) { this.request_id = data.request_id; } if ("requesting_org" in data && data.requesting_org != undefined) { this.requesting_org = data.requesting_org; } } } get policy() { return pb_1.Message.getField(this, 1) as string[]; } set policy(value: string[]) { pb_1.Message.setField(this, 1, value); } get address() { return pb_1.Message.getField(this, 2) as string; } set address(value: string) { pb_1.Message.setField(this, 2, value); } get requesting_relay() { return pb_1.Message.getField(this, 3) as string; } set requesting_relay(value: string) { pb_1.Message.setField(this, 3, value); } get requesting_network() { return pb_1.Message.getField(this, 4) as string; } set requesting_network(value: string) { pb_1.Message.setField(this, 4, value); } get certificate() { return pb_1.Message.getField(this, 5) as string; } set certificate(value: string) { pb_1.Message.setField(this, 5, value); } get requestor_signature() { return pb_1.Message.getField(this, 6) as string; } set requestor_signature(value: string) { pb_1.Message.setField(this, 6, value); } get nonce() { return pb_1.Message.getField(this, 7) as string; } set nonce(value: string) { pb_1.Message.setField(this, 7, value); } get request_id() { return pb_1.Message.getField(this, 8) as string; } set request_id(value: string) { pb_1.Message.setField(this, 8, value); } get requesting_org() { return pb_1.Message.getField(this, 9) as string; } set requesting_org(value: string) { pb_1.Message.setField(this, 9, value); } static fromObject(data: { policy?: string[]; address?: string; requesting_relay?: string; requesting_network?: string; certificate?: string; requestor_signature?: string; nonce?: string; request_id?: string; requesting_org?: string; }) { const message = new Query({}); if (data.policy != null) { message.policy = data.policy; } if (data.address != null) { message.address = data.address; } if (data.requesting_relay != null) { message.requesting_relay = data.requesting_relay; } if (data.requesting_network != null) { message.requesting_network = data.requesting_network; } if (data.certificate != null) { message.certificate = data.certificate; } if (data.requestor_signature != null) { message.requestor_signature = data.requestor_signature; } if (data.nonce != null) { message.nonce = data.nonce; } if (data.request_id != null) { message.request_id = data.request_id; } if (data.requesting_org != null) { message.requesting_org = data.requesting_org; } return message; } toObject() { const data: { policy?: string[]; address?: string; requesting_relay?: string; requesting_network?: string; certificate?: string; requestor_signature?: string; nonce?: string; request_id?: string; requesting_org?: string; } = {}; if (this.policy != null) { data.policy = this.policy; } if (this.address != null) { data.address = this.address; } if (this.requesting_relay != null) { data.requesting_relay = this.requesting_relay; } if (this.requesting_network != null) { data.requesting_network = this.requesting_network; } if (this.certificate != null) { data.certificate = this.certificate; } if (this.requestor_signature != null) { data.requestor_signature = this.requestor_signature; } if (this.nonce != null) { data.nonce = this.nonce; } if (this.request_id != null) { data.request_id = this.request_id; } if (this.requesting_org != null) { data.requesting_org = this.requesting_org; } return data; } serialize(): Uint8Array; serialize(w: pb_1.BinaryWriter): void; serialize(w?: pb_1.BinaryWriter): Uint8Array | void { const writer = w || new pb_1.BinaryWriter(); if (this.policy !== undefined) writer.writeRepeatedString(1, this.policy); if (typeof this.address === "string" && this.address.length) writer.writeString(2, this.address); if (typeof this.requesting_relay === "string" && this.requesting_relay.length) writer.writeString(3, this.requesting_relay); if (typeof this.requesting_network === "string" && this.requesting_network.length) writer.writeString(4, this.requesting_network); if (typeof this.certificate === "string" && this.certificate.length) writer.writeString(5, this.certificate); if (typeof this.requestor_signature === "string" && this.requestor_signature.length) writer.writeString(6, this.requestor_signature); if (typeof this.nonce === "string" && this.nonce.length) writer.writeString(7, this.nonce); if (typeof this.request_id === "string" && this.request_id.length) writer.writeString(8, this.request_id); if (typeof this.requesting_org === "string" && this.requesting_org.length) writer.writeString(9, this.requesting_org); if (!w) return writer.getResultBuffer(); } static deserialize(bytes: Uint8Array | pb_1.BinaryReader): Query { const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new Query(); while (reader.nextField()) { if (reader.isEndGroup()) break; switch (reader.getFieldNumber()) { case 1: pb_1.Message.addToRepeatedField(message, 1, reader.readString()); break; case 2: message.address = reader.readString(); break; case 3: message.requesting_relay = reader.readString(); break; case 4: message.requesting_network = reader.readString(); break; case 5: message.certificate = reader.readString(); break; case 6: message.requestor_signature = reader.readString(); break; case 7: message.nonce = reader.readString(); break; case 8: message.request_id = reader.readString(); break; case 9: message.requesting_org = reader.readString(); break; default: reader.skipField(); } } return message; } serializeBinary(): Uint8Array { return this.serialize(); } static deserializeBinary(bytes: Uint8Array): Query { return Query.deserialize(bytes); } } }
the_stack
module dragonBones { /** * @class dragonBones.SlotTimelineState * @classdesc * SlotTimelineState 负责计算 Slot 的时间轴动画。 * SlotTimelineState 实例隶属于 AnimationState. AnimationState在创建时会为每个包含动作的 Slot生成一个 SlotTimelineState 实例. * @see dragonBones.Animation * @see dragonBones.AnimationState * @see dragonBones.Slot */ export class SlotTimelineState{ private static HALF_PI:number = Math.PI * 0.5; private static DOUBLE_PI:number = Math.PI * 2; private static _pool:Array<SlotTimelineState> =[]; /** @private */ public static _borrowObject():SlotTimelineState{ if(SlotTimelineState._pool.length == 0){ return new SlotTimelineState(); } return SlotTimelineState._pool.pop(); } /** @private */ public static _returnObject(timeline:SlotTimelineState):void{ if(SlotTimelineState._pool.indexOf(timeline) < 0){ SlotTimelineState._pool[SlotTimelineState._pool.length] = timeline; } timeline.clear(); } /** @private */ public static _clear():void{ var i:number = SlotTimelineState._pool.length; while(i --){ SlotTimelineState._pool[i].clear(); } SlotTimelineState._pool.length = 0; } public name:string; /** @private */ public _weight:number; /** @private */ public _blendEnabled:boolean; /** @private */ public _isComplete:boolean; /** @private */ public _animationState:AnimationState; private _totalTime:number = 0; //duration private _currentTime:number = 0; private _currentFrameIndex:number = 0; private _currentFramePosition:number = 0; private _currentFrameDuration:number = 0; private _tweenEasing:number; private _tweenCurve:CurveData; private _tweenColor:boolean; private _rawAnimationScale:number; //-1: frameLength>1, 0:frameLength==0, 1:frameLength==1 private _updateMode:number = 0; private _armature:Armature; private _animation:Animation; private _slot:Slot; private _timelineData:SlotTimeline; private _durationColor:ColorTransform; public constructor(){ this._durationColor = new ColorTransform(); } private clear():void{ if(this._slot){ this._slot._removeState(this); this._slot = null; } this._armature = null; this._animation = null; this._animationState = null; this._timelineData = null; } //动画开始结束 /** @private */ public _fadeIn(slot:Slot, animationState:AnimationState, timelineData:SlotTimeline):void{ this._slot = slot; this._armature = this._slot.armature; this._animation = this._armature.animation; this._animationState = animationState; this._timelineData = timelineData; this.name = timelineData.name; this._totalTime = this._timelineData.duration; this._rawAnimationScale = this._animationState.clip.scale; this._isComplete = false; this._blendEnabled = false; this._tweenColor = false; this._currentFrameIndex = -1; this._currentTime = -1; this._tweenEasing = NaN; this._weight = 1; switch(this._timelineData.frameList.length){ case 0: this._updateMode = 0; break; case 1: this._updateMode = 1; break; default: this._updateMode = -1; break; } this._slot._addState(this); } /** @private */ public _fadeOut():void{ } //动画进行中 /** @private */ public _update(progress:number):void{ if(this._updateMode == -1){ this.updateMultipleFrame(progress); } else if(this._updateMode == 1){ this._updateMode = 0; this.updateSingleFrame(); } } private updateMultipleFrame(progress:number):void{ var currentPlayTimes:number = 0; progress /= this._timelineData.scale; progress += this._timelineData.offset; var currentTime:number = this._totalTime * progress; var playTimes:number = this._animationState.playTimes; if(playTimes == 0){ this._isComplete = false; currentPlayTimes = Math.ceil(Math.abs(currentTime) / this._totalTime) || 1; if(currentTime>=0) { currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime; } else { currentTime -= Math.ceil(currentTime / this._totalTime) * this._totalTime; } if(currentTime < 0){ currentTime += this._totalTime; } } else{ var totalTimes:number = playTimes * this._totalTime; if(currentTime >= totalTimes){ currentTime = totalTimes; this._isComplete = true; } else if(currentTime <= -totalTimes){ currentTime = -totalTimes; this._isComplete = true; } else{ this._isComplete = false; } if(currentTime < 0){ currentTime += totalTimes; } currentPlayTimes = Math.ceil(currentTime / this._totalTime) || 1; if(this._isComplete){ currentTime = this._totalTime; } else { if(currentTime>=0) { currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime; } else { currentTime -= Math.ceil(currentTime / this._totalTime) * this._totalTime; } } } if(this._currentTime != currentTime){ this._currentTime = currentTime; var frameList:Array<Frame> = this._timelineData.frameList; var prevFrame:SlotFrame; var currentFrame:SlotFrame; for (var i:number = 0, l:number = this._timelineData.frameList.length; i < l; ++i){ if(this._currentFrameIndex < 0){ this._currentFrameIndex = 0; } else if(this._currentTime < this._currentFramePosition || this._currentTime >= this._currentFramePosition + this._currentFrameDuration){ this._currentFrameIndex ++; if(this._currentFrameIndex >= frameList.length){ if(this._isComplete){ this._currentFrameIndex --; break; } else{ this._currentFrameIndex = 0; } } } else{ break; } currentFrame = <SlotFrame><any> (frameList[this._currentFrameIndex]); if(prevFrame){ this._slot._arriveAtFrame(prevFrame, this, this._animationState, true); } this._currentFrameDuration = currentFrame.duration; this._currentFramePosition = currentFrame.position; prevFrame = currentFrame; } if(currentFrame){ this._slot._arriveAtFrame(currentFrame, this, this._animationState, false); this._blendEnabled = currentFrame.displayIndex >= 0; if(this._blendEnabled){ this.updateToNextFrame(currentPlayTimes); } else{ this._tweenEasing = NaN; this._tweenColor = false; } } if(this._blendEnabled){ this.updateTween(); } } } private updateToNextFrame(currentPlayTimes:number = 0):void{ var nextFrameIndex:number = this._currentFrameIndex + 1; if(nextFrameIndex >= this._timelineData.frameList.length){ nextFrameIndex = 0; } var currentFrame:SlotFrame = <SlotFrame><any> (this._timelineData.frameList[this._currentFrameIndex]); var nextFrame:SlotFrame = <SlotFrame><any> (this._timelineData.frameList[nextFrameIndex]); var tweenEnabled:boolean = false; if( nextFrameIndex == 0 && ( !this._animationState.lastFrameAutoTween || ( this._animationState.playTimes && this._animationState.currentPlayTimes >= this._animationState.playTimes && ((this._currentFramePosition + this._currentFrameDuration) / this._totalTime + currentPlayTimes - this._timelineData.offset) * this._timelineData.scale > 0.999999 ) ) ){ this._tweenEasing = NaN; tweenEnabled = false; } else if(currentFrame.displayIndex < 0 || nextFrame.displayIndex < 0){ this._tweenEasing = NaN; tweenEnabled = false; } else if(this._animationState.autoTween){ this._tweenEasing = this._animationState.clip.tweenEasing; if(isNaN(this._tweenEasing)){ this._tweenEasing = currentFrame.tweenEasing; this._tweenCurve = currentFrame.curve; if(isNaN(this._tweenEasing) && this._tweenCurve == null) //frame no tween { tweenEnabled = false; } else{ if(this._tweenEasing == 10){ this._tweenEasing = 0; } //_tweenEasing [-1, 0) 0 (0, 1] (1, 2] tweenEnabled = true; } } else //animationData overwrite tween { //_tweenEasing [-1, 0) 0 (0, 1] (1, 2] tweenEnabled = true; } } else{ this._tweenEasing = currentFrame.tweenEasing; this._tweenCurve = currentFrame.curve; if((isNaN(this._tweenEasing) || this._tweenEasing == 10) && this._tweenCurve == null) //frame no tween { this._tweenEasing = NaN; tweenEnabled = false; } else{ //_tweenEasing [-1, 0) 0 (0, 1] (1, 2] tweenEnabled = true; } } if(tweenEnabled){ //color if(currentFrame.color && nextFrame.color){ this._durationColor.alphaOffset = nextFrame.color.alphaOffset - currentFrame.color.alphaOffset; this._durationColor.redOffset = nextFrame.color.redOffset - currentFrame.color.redOffset; this._durationColor.greenOffset = nextFrame.color.greenOffset - currentFrame.color.greenOffset; this._durationColor.blueOffset = nextFrame.color.blueOffset - currentFrame.color.blueOffset; this._durationColor.alphaMultiplier = nextFrame.color.alphaMultiplier - currentFrame.color.alphaMultiplier; this._durationColor.redMultiplier = nextFrame.color.redMultiplier - currentFrame.color.redMultiplier; this._durationColor.greenMultiplier = nextFrame.color.greenMultiplier - currentFrame.color.greenMultiplier; this._durationColor.blueMultiplier = nextFrame.color.blueMultiplier - currentFrame.color.blueMultiplier; if( this._durationColor.alphaOffset || this._durationColor.redOffset || this._durationColor.greenOffset || this._durationColor.blueOffset || this._durationColor.alphaMultiplier || this._durationColor.redMultiplier || this._durationColor.greenMultiplier || this._durationColor.blueMultiplier ){ this._tweenColor = true; } else{ this._tweenColor = false; } } else if(currentFrame.color){ this._tweenColor = true; this._durationColor.alphaOffset = -currentFrame.color.alphaOffset; this._durationColor.redOffset = -currentFrame.color.redOffset; this._durationColor.greenOffset = -currentFrame.color.greenOffset; this._durationColor.blueOffset = -currentFrame.color.blueOffset; this._durationColor.alphaMultiplier = 1 - currentFrame.color.alphaMultiplier; this._durationColor.redMultiplier = 1 - currentFrame.color.redMultiplier; this._durationColor.greenMultiplier = 1 - currentFrame.color.greenMultiplier; this._durationColor.blueMultiplier = 1 - currentFrame.color.blueMultiplier; } else if(nextFrame.color){ this._tweenColor = true; this._durationColor.alphaOffset = nextFrame.color.alphaOffset; this._durationColor.redOffset = nextFrame.color.redOffset; this._durationColor.greenOffset = nextFrame.color.greenOffset; this._durationColor.blueOffset = nextFrame.color.blueOffset; this._durationColor.alphaMultiplier = nextFrame.color.alphaMultiplier - 1; this._durationColor.redMultiplier = nextFrame.color.redMultiplier - 1; this._durationColor.greenMultiplier = nextFrame.color.greenMultiplier - 1; this._durationColor.blueMultiplier = nextFrame.color.blueMultiplier - 1; } else{ this._tweenColor = false; } } else{ this._tweenColor = false; } if(!this._tweenColor && this._animationState.displayControl){ if(currentFrame.color){ this._slot._updateDisplayColor( currentFrame.color.alphaOffset, currentFrame.color.redOffset, currentFrame.color.greenOffset, currentFrame.color.blueOffset, currentFrame.color.alphaMultiplier, currentFrame.color.redMultiplier, currentFrame.color.greenMultiplier, currentFrame.color.blueMultiplier, true ); } else if(this._slot._isColorChanged){ this._slot._updateDisplayColor(0, 0, 0, 0, 1, 1, 1, 1, false); } } } private updateTween():void{ var currentFrame:SlotFrame = <SlotFrame><any> (this._timelineData.frameList[this._currentFrameIndex]); if(this._tweenColor && this._animationState.displayControl){ var progress:number = (this._currentTime - this._currentFramePosition) / this._currentFrameDuration; if(this._tweenCurve != null) { progress = this._tweenCurve.getValueByProgress(progress); } else if(this._tweenEasing){ progress = MathUtil.getEaseValue(progress, this._tweenEasing); } if(currentFrame.color){ this._slot._updateDisplayColor( currentFrame.color.alphaOffset + this._durationColor.alphaOffset * progress, currentFrame.color.redOffset + this._durationColor.redOffset * progress, currentFrame.color.greenOffset + this._durationColor.greenOffset * progress, currentFrame.color.blueOffset + this._durationColor.blueOffset * progress, currentFrame.color.alphaMultiplier + this._durationColor.alphaMultiplier * progress, currentFrame.color.redMultiplier + this._durationColor.redMultiplier * progress, currentFrame.color.greenMultiplier + this._durationColor.greenMultiplier * progress, currentFrame.color.blueMultiplier + this._durationColor.blueMultiplier * progress, true ); } else{ this._slot._updateDisplayColor( this._durationColor.alphaOffset * progress, this._durationColor.redOffset * progress, this._durationColor.greenOffset * progress, this._durationColor.blueOffset * progress, 1 + this._durationColor.alphaMultiplier * progress, 1 + this._durationColor.redMultiplier * progress, 1 + this._durationColor.greenMultiplier * progress, 1 + this._durationColor.blueMultiplier * progress, true ); } } } private updateSingleFrame():void{ var currentFrame:SlotFrame = <SlotFrame><any> (this._timelineData.frameList[0]); this._slot._arriveAtFrame(currentFrame, this, this._animationState, false); this._isComplete = true; this._tweenEasing = NaN; this._tweenColor = false; this._blendEnabled = currentFrame.displayIndex >= 0; if(this._blendEnabled){ /** * <使用绝对数据> * 单帧的timeline,第一个关键帧的transform为0 * timeline.originTransform = firstFrame.transform; * eachFrame.transform = eachFrame.transform - timeline.originTransform; * firstFrame.transform == 0; * * <使用相对数据> * 使用相对数据时,timeline.originTransform = 0,第一个关键帧的transform有可能不为 0 */ if(this._animationState.displayControl){ if(currentFrame.color){ this._slot._updateDisplayColor( currentFrame.color.alphaOffset, currentFrame.color.redOffset, currentFrame.color.greenOffset, currentFrame.color.blueOffset, currentFrame.color.alphaMultiplier, currentFrame.color.redMultiplier, currentFrame.color.greenMultiplier, currentFrame.color.blueMultiplier, true); } else if(this._slot._isColorChanged){ this._slot._updateDisplayColor(0,0,0,0,1,1,1,1,false); } } } } } }
the_stack
export type Position = { physical: PhysicalPosition } | { logical: LogicalPosition; }; /** A position represented in physical pixels. */ export type PhysicalPosition = { x: number; y: number }; /** A position represented in logical pixels. */ export type LogicalPosition = { x: number; y: number }; /** A size that's either physical or logical. */ export type Size = { physical: PhysicalSize } | { logical: LogicalSize }; /** A size represented in physical pixels. */ export type PhysicalSize = { width: number; height: number }; /** A size represented in logical pixels. */ export type LogicalSize = { width: number; height: number }; /** Describes the appearance of the mouse cursor. */ export type CursorIcon = /** The platform-dependent default cursor. */ | "default" /** A simple crosshair. */ | "crosshair" /** A hand (often used to indicate links in web browsers). */ | "hand" /** Self explanatory. */ | "arrow" /** Indicates something is to be moved. */ | "move" /** Indicates text that may be selected or edited. */ | "text" /** Program busy indicator. */ | "wait" /** Help indicator (often rendered as a "?") */ | "help" /** * Progress indicator. Shows that processing is being done. But in contrast * with "Wait" the user may still interact with the program. Often rendered * as a spinning beach ball, or an arrow with a watch or hourglass. */ | "progress" /** Cursor showing that something cannot be done. */ | "notAllowed" | "contextMenu" | "cell" | "verticalText" | "alias" | "copy" | "noDrop" /** Indicates something can be grabbed. */ | "grab" /** Indicates something is grabbed. */ | "grabbing" | "allScroll" | "zoomIn" | "zoomOut" | "eResize" | "nResize" | "neResize" | "nwResize" | "sResize" | "seResize" | "swResize" | "wResize" | "ewResize" | "nsResize" | "neswResize" | "nwseResize" | "colResize" | "rowResize"; /** Describes a generic event. */ export type PaneEvent = | { /** Emitted when new events arrive from the OS to be processed. */ type: "newEvents"; value: StartCause; } | { /** Emitted when the OS sends an event to a winit window. */ type: "windowEvent"; value: { windowId: number; event: WindowEvent }; } | { /** Emitted when the OS sends an event to a device. */ type: "deviceEvent"; value: { deviceId: number; event: DeviceEvent }; } | { /** Unused in pane. */ type: "userEvent"; } | { /** Emitted when the application has been suspended. */ type: "suspended"; } | { /** Emitted when the application has been resumed. */ type: "resumed"; } | { /** * Emitted when all of the event loop's input events have been processed and * redraw processing is about to begin. */ type: "mainEventsCleared"; } | { /** Emitted after `mainEventsCleared` when a window should be redrawn. */ type: "redrawRequested"; } | { /** * Emitted after all `redrawRequested` events have been processed and control * flow is about to be taken away from the program. If there are no `redrawRequested` * events, it is emitted immediately after `mainEventsCleared`. */ type: "redrawEventsCleared"; } | { /** * Emitted when the event loop is being shut down. Beware! This event is emitted * every step in the event loop as the last thing that happens each step. */ type: "loopDestroyed"; }; /** Describes the reason the event loop is resuming. */ export type StartCause = /** Unused in pane. */ | { type: "resumeTimeReached"; value: { start: number; requestedResume: number }; } /** * Sent if the OS has new events to send to the window, after a wait was requested. * Contains the moment the wait was requested and the resume time, if requested. */ | { type: "waitCancelled"; value: { start: number; requestedResume?: number }; } /** Unused in pane. */ | { type: "poll"; } /** Emitted every step in the event loop as the first event. */ | { type: "init"; }; /** Describes an event from a `Pane` window. */ export type WindowEvent = | { /** The size of the window has changed. Contains the client area's new dimensions. */ type: "resized"; value: PhysicalSize; } | { /** The position of the window has changed. Contains the window's new position. */ type: "moved"; value: PhysicalPosition; } | { /** The window has been requested to close. */ type: "closeRequested"; } | { /** The window has been destroyed. */ type: "destroyed"; } | { /** A file has been dropped into the window. */ type: "droppedFile"; value: string; } | { /** A file is being hovered over the window. */ type: "hoveredFile"; value: string; } | { /** A file was hovered, but has exited the window. */ type: "hoveredFileCancelled"; } | { /** The window received a unicode character. */ type: "receivedCharacter"; value: string; } | { /** * The window gained or lost focus. The parameter is true if the window has gained * focus, and false if it has lost focus. */ type: "focused"; value: boolean; } | { /** * An event from the keyboard has been received. */ type: "keyboardInput"; value: { deviceId: number; input: KeyboardInput; /** * If `true`, the event was generated synthetically by winit * in one of the following circumstances: * * * Synthetic key press events are generated for all keys pressed * when a window gains focus. Likewise, synthetic key release events * are generated for all keys pressed when a window goes out of focus. * ***Currently, this is only functional on X11 and Windows*** * * Otherwise, this value is always `false`. */ isSynthetic: boolean; }; } | { /** The keyboard modifiers have changed. */ type: "modifiersChanged"; value: ModifiersState; } | { /** The cursor has moved on the window. */ type: "cursorMoved"; value: { deviceId: number; position: PhysicalPosition }; } | { /** The cursor has entered the window. */ type: "cursorEntered"; value: { deviceId: number }; } | { /** The cursor has left the window. */ type: "cursorLeft"; value: { deviceId: number }; } | { /** A mouse wheel movement or touchpad scroll occurred. */ type: "mouseWheel"; value: { deviceId: number; delta: MouseScrollDelta; phase: TouchPhase }; } | { /** An mouse button press has been received. */ type: "mouseInput"; value: { deviceId: number; state: ElementState; button: MouseButton }; } | { /** Touchpad pressure event. * * At the moment, only supported on Apple forcetouch-capable macbooks. */ type: "touchpadPressure"; value: { deviceId: number; /** A value between 0 and 1 representing how hard the touchpad is being pressed. */ pressure: number; /** An integer representing the click level */ stage: number; }; } | { /** * Motion on some analog axis. May report data redundant to other, more specific * events. */ type: "axisMotion"; value: { deviceId: number; axis: AxisId; value: number }; } | { /** Touch event has been received */ type: "touch"; value: Touch; } | { /** * The window's scale factor has changed. * * The following user actions can cause DPI changes: * * Changing the display's resolution. * * Changing the display's scale factor (e.g. in Control Panel on Windows). * * Moving the window to a display with a different scale factor. */ type: "scaleFactorChanged"; value: { scaleFactor: number; newInnerSize: PhysicalSize }; } | { /** * The system window theme has changed. * * Applications might wish to react to this to change the theme of the content of the window * when the system changes the window theme. * * At the moment this is only supported on Windows. */ type: "themeChanged"; value: Theme; }; /** Hardware-dependent keyboard scan code. */ export type ScanCode = number; /** Identifier for a specific analog axis on some device. */ export type AxisId = number; /** Identifier for a specific button on some device. */ export type ButtonId = number; /** The os theme. */ export type Theme = "light" | "dark"; /** Describes a keyboard input event. */ export type KeyboardInput = { /** Identifies the physical key pressed. */ scancode: ScanCode; state: ElementState; /** Identifies the semantic meaning of the key. */ virtualKeycode?: VirtualKeyCode; }; export type VirtualKeyCode = /** The "1" key over the letters. */ | "Key1" /** The "2" key over the letters. */ | "Key2" /** The "3" key over the letters. */ | "Key3" /** The "4" key over the letters. */ | "Key4" /** The "5" key over the letters. */ | "Key5" /** The "6" key over the letters. */ | "Key6" /** The "7" key over the letters. */ | "Key7" /** The "8" key over the letters. */ | "Key8" /** The "9" key over the letters. */ | "Key9" /** The "0" key over the "O" and "P" keys. */ | "Key0" | "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" /** The Escape key, next to F1. */ | "Escape" | "F1" | "F2" | "F3" | "F4" | "F5" | "F6" | "F7" | "F8" | "F9" | "F10" | "F11" | "F12" | "F13" | "F14" | "F15" | "F16" | "F17" | "F18" | "F19" | "F20" | "F21" | "F22" | "F23" | "F24" /** Print Screen/SysRq. */ | "Snapshot" /** Scroll Lock. */ | "Scroll" /** Pause/Break key, next to Scroll lock. */ | "Pause" /** Insert, next to Backspace. */ | "Insert" | "Home" | "Delete" | "End" | "PageDown" | "PageUp" | "Left" | "Up" | "Right" | "Down" /** The Backspace key, right over Enter. */ | "Back" /** The Enter key. */ | "Return" /** The space bar. */ | "Space" /** The "Compose" key on Linux. */ | "Compose" | "Caret" | "Numlock" | "Numpad0" | "Numpad1" | "Numpad2" | "Numpad3" | "Numpad4" | "Numpad5" | "Numpad6" | "Numpad7" | "Numpad8" | "Numpad9" | "NumpadAdd" | "NumpadDivide" | "NumpadDecimal" | "NumpadComma" | "NumpadEnter" | "NumpadEquals" | "NumpadMultiply" | "NumpadSubtract" | "AbntC1" | "AbntC2" | "Apostrophe" | "Apps" | "Asterisk" | "At" | "Ax" | "Backslash" | "Calculator" | "Capital" | "Colon" | "Comma" | "Convert" | "Equals" | "Grave" | "Kana" | "Kanji" | "LAlt" | "LBracket" | "LControl" | "LShift" | "LWin" | "Mail" | "MediaSelect" | "MediaStop" | "Minus" | "Mute" | "MyComputer" | "NavigateForward" | "NavigateBackward" | "NextTrack" | "NoConvert" | "OEM102" | "Period" | "PlayPause" | "Plus" | "Power" | "PrevTrack" | "RAlt" | "RBracket" | "RControl" | "RShift" | "RWin" | "Semicolon" | "Slash" | "Sleep" | "Stop" | "Sysrq" | "Tab" | "Underline" | "Unlabeled" | "VolumeDown" | "VolumeUp" | "Wake" | "WebBack" | "WebFavorites" | "WebForward" | "WebHome" | "WebRefresh" | "WebSearch" | "WebStop" | "Yen" | "Copy" | "Paste" | "Cut"; /** Describes the input state of a key. */ export type ElementState = "pressed" | "released"; /** Describes a button of a mouse controller. */ export type MouseButton = "left" | "right" | "middle" | { other: number }; /** Describes a difference in the mouse scroll wheel state. */ export type MouseScrollDelta = | { type: "lineDelta"; /** * Amount in lines or rows to scroll in the horizontal and vertical directions. * * Positive values indicate movement forward (away from the user) or rightwards. */ value: [number, number]; } | { type: "pixelDelta"; /** * Amount in pixels to scroll in the horizontal and vertical direction. * * Scroll events are expressed as a PixelDelta if supported by the device * (eg. a touchpad) and platform. */ value: PhysicalPosition; }; /** Describes touch-screen input state. */ export type TouchPhase = "started" | "moved" | "ended" | "cancelled"; export type UserAttentionType = /** * * macOS: Bounces the dock icon until the application is in focus. * * Windows: Flashes both the window and the taskbar button until the application is in focus. */ | "critical" /** * * macOS: Bounces the dock icon once. * * Windows: Flashes the taskbar button until the application is in focus. */ | "informational"; /** * Represents a touch event. * * Every time the user touches the screen, a new `started` event with an unique * identifier for the finger is generated. When the finger is lifted, an * `ended` event is generated with the same finger id. * * After a `started` event has been emitted, there may be zero or more `moved` * events when the finger is moved or the touch pressure changes. * * The finger id may be reused by the system after an `ended` event. The user should * assume that a new `started` event received with the same id has nothing to do * with the old finger and is a new finger. * * A `cancelled` event is emitted when the system has canceled tracking this touch, * such as when the window loses focus. */ export type Touch = { deviceId: number; phase: TouchPhase; location: PhysicalPosition; /** * Describes how hard the screen was pressed. May be `unknown` if the platform * does not support pressure sensitivity. */ force?: Force; id: bigint; }; /** Describes the force of a touch event. */ export type Force = | { /** Currently unused in pane as this is an ios specific event. */ type: "calibrated"; value: { force: number; maxPossibleForce: number; altitudeAngle?: number; }; } | { /** * If the platform reports the force as normalized, we have no way of * knowing how much pressure 1.0 corresponds to – we know it's the maximum * amount of force, but as to how much force, you might either have to * press really really hard, or not hard at all, depending on the device. */ type: "normalized"; value: number; }; /** Represents the current state of the keyboard modifiers. */ export type ModifiersState = { shift: boolean; ctrl: boolean; alt: boolean; logo: boolean; }; /** * Represents raw hardware events that are not associated with any particular window. * * Useful for interactions that diverge significantly from a conventional 2D GUI, * such as 3D camera or first-person game controls. Many physical actions, such * as mouse movement, can produce both device and window events. Because window * events typically arise from virtual devices (corresponding to GUI cursors and * keyboard focus) the device IDs may not match. * * Note that these events are delivered regardless of input focus. */ export type DeviceEvent = | { type: "added" } | { type: "removed" } | { /** * Change in physical position of a pointing device. * * This represents raw, unfiltered physical motion. Not to be confused with * the `WindowEvent`. */ type: "mouseMotion"; value: { /** * [x, y] change in position in unspecified units. * * Different devices may use different units. */ delta: [number, number]; }; } | { /** Physical scroll event. */ type: "mouseWheel"; value: { delta: MouseScrollDelta }; } | { /** * Motion on some analog axis. This event will be reported for all arbitrary * input devices that winit supports on this platform, including mouse devices. * If the device is a mouse device then this will be reported alongside the * `mouseMotion` event. */ type: "motion"; value: { axis: AxisId; value: number }; } | { type: "button"; value: { button: ButtonId; state: ElementState } } | { type: "key"; value: KeyboardInput } | { type: "text"; value: { codepoint: string } };
the_stack
import { Allocation, ChannelResult, CreateChannelParams, Uint256, } from '@statechannels/client-api-schema'; import _ from 'lodash'; import EventEmitter from 'eventemitter3'; import { calculateObjectiveId, makeAddress, makeDestination, Address, makePrivateKey, } from '@statechannels/wallet-core'; import {utils} from 'ethers'; import {setIntervalAsync, clearIntervalAsync} from 'set-interval-async/dynamic'; import P from 'pino'; import { MessageHandler, MessageServiceFactory, MessageServiceInterface, } from '../message-service/types'; import {getMessages} from '../message-service/utils'; import { defaultConfig, Engine, extractDBConfigFromWalletConfig, hasNewObjective, EngineConfig, IncomingWalletConfig, isMultipleChannelOutput, MultipleChannelOutput, SingleChannelOutput, validateEngineConfig, SyncConfiguration, } from '../engine'; import { AllocationUpdatedArg, ChainEventSubscriberInterface, ChainService, ChainServiceInterface, ChallengeRegisteredArg, ChannelFinalizedArg, HoldingUpdatedArg, MockChainService, } from '../chain-service'; import * as ChannelState from '../protocols/state'; import {createLogger} from '../logger'; import {ConfigValidationError, SingleThreadedEngine} from '../engine/engine'; import { ObjectiveResult, WalletEvents, ObjectiveDoneResult, UpdateChannelResult, CreateLedgerChannelParams, } from './types'; export class Wallet extends EventEmitter<WalletEvents> { /** * Constructs a channel manager that will ensure objectives get accomplished by resending messages if needed. * @param incomingConfig The configuration object that specifies various options. * @param messageServiceFactory A function that returns a message service when passed in a handler. * @returns A channel manager. */ public static async create( incomingConfig: IncomingWalletConfig, messageServiceFactory: MessageServiceFactory ): Promise<Wallet> { const populatedConfig = _.assign({}, defaultConfig, incomingConfig); // Even though the config hasn't been validated we attempt to create a logger // This allows us to log out any config validation errors const logger = createLogger(populatedConfig); logger.trace({engineConfig: populatedConfig}, 'Wallet initializing'); const {errors, valid} = validateEngineConfig(populatedConfig); if (!valid) { errors.forEach(error => logger.error({error}, `Validation error occurred ${error.message}`)); throw new ConfigValidationError(errors); } const {skipEvmValidation, metricsConfiguration} = populatedConfig; const engineConfig: EngineConfig = { skipEvmValidation, dbConfig: extractDBConfigFromWalletConfig(populatedConfig), metrics: metricsConfiguration, chainNetworkID: utils.hexlify(populatedConfig.networkConfiguration.chainNetworkID), workerThreadAmount: 0, // Disable threading for now }; const engine = await SingleThreadedEngine.create(engineConfig, logger); if (populatedConfig.privateKey) { await engine.addSigningKey(makePrivateKey(populatedConfig.privateKey)); } const chainService = populatedConfig.chainServiceConfiguration.attachChainService ? new ChainService({ ...populatedConfig.chainServiceConfiguration, logger, }) : new MockChainService(); await chainService.checkChainId(populatedConfig.networkConfiguration.chainNetworkID); const networkId = utils.hexlify(populatedConfig.networkConfiguration.chainNetworkID); const wallet = new Wallet( messageServiceFactory, engine, chainService, networkId, logger, populatedConfig.syncConfiguration ); await wallet.registerExistingChannelsWithChainService(); return wallet; } private _messageService: MessageServiceInterface; private _syncInterval = setIntervalAsync(async () => { await this.syncObjectives(); }, this._syncOptions.pollInterval); private _chainListener: ChainEventSubscriberInterface; private constructor( messageServiceFactory: MessageServiceFactory, private _engine: Engine, private _chainService: ChainServiceInterface, private _chainNetworkId: string, private _logger: P.Logger, private _syncOptions: SyncConfiguration ) { super(); const handler: MessageHandler = async message => { const result = await this._engine.pushMessage(message.data); await this.handleEngineOutput(result); }; this._messageService = messageServiceFactory(handler); this._chainListener = { holdingUpdated: this.createChainEventlistener('holdingUpdated', e => this._engine.store.updateFunding(e.channelId, e.amount, e.asset) ), allocationUpdated: this.createChainEventlistener('allocationUpdated', async e => { const transferredOut = e.externalPayouts.map(ai => ({ toAddress: makeDestination(ai.destination), amount: ai.amount as Uint256, })); await this._engine.store.updateTransferredOut( e.channelId, e.asset, transferredOut, e.newHoldings ); }), challengeRegistered: this.createChainEventlistener('challengeRegistered', e => this._engine.store.insertAdjudicatorStatus(e.channelId, e.finalizesAt, e.challengeStates) ), channelFinalized: this.createChainEventlistener('channelFinalized', e => this._engine.store.markAdjudicatorStatusAsFinalized( e.channelId, e.blockNumber, e.blockTimestamp, e.finalizedAt ) ), }; } /** * Pulls and stores the ForceMoveApp definition bytecode at the supplied blockchain address. * * @remarks * Storing the bytecode is necessary for the engine to verify ForceMoveApp transitions. * * @param appDefinition - An ethereum address where ForceMoveApp rules are deployed. * @returns A promise that resolves when the bytecode has been successfully stored. */ public async registerAppDefinition(appDefinition: string): Promise<void> { const bytecode = await this._chainService.fetchBytecode(appDefinition); await this._engine.store.upsertBytecode( utils.hexlify(this._chainNetworkId), makeAddress(appDefinition), bytecode ); } /** * Creates a ledger channel * @param channelParams The parameters for the ledger channel * @param fundingStrategy The funding strategy to use * @returns An ObjectiveResult indicating success or the error that occured */ public async createLedgerChannel( channelParams: CreateLedgerChannelParams ): Promise<ObjectiveResult> { try { const createResult = await this._engine.createLedgerChannel( channelParams, channelParams.fundingStrategy ); await this.registerChannels([createResult.channelResult]); const {newObjective, channelResult} = createResult; const done = this.createObjectiveDoneResult(newObjective.objectiveId); await this.handleEngineOutput(createResult); return { channelId: channelResult.channelId, currentStatus: newObjective.status, objectiveId: newObjective.objectiveId, done, }; } catch (error) { this._logger.error({err: error}, 'Uncaught InternalError in CreateLedgerChannel'); // TODO: This is slightly hacky but it's less painful then having to narrow the type down every time // you get a result back from the createChannels method // This should be looked at in https://github.com/statechannels/statechannels/issues/3461 return { channelId: 'ERROR', currentStatus: 'failed' as const, objectiveId: 'ERROR', done: Promise.resolve({type: 'InternalError' as const, error}), }; } } /** * Approves an objective that has been proposed by another participant. * Once the objective has been approved progress can be made to completing the objective. * @remarks * This is used to "join" channels by approving a CreateChannel Objective. * @param objectiveIds The ids of the objective you want to approve. * @returns A promise that resolves to a collection of ObjectiveResult. */ public async approveObjectives(objectiveIds: string[]): Promise<ObjectiveResult[]> { const { objectives, messages, chainRequests, channelResults, } = await this._engine.approveObjectives(objectiveIds); await this.registerChannels(channelResults); const results = objectives.map(async o => ({ objectiveId: o.objectiveId, currentStatus: o.status, channelId: o.data.targetChannelId, done: this.createObjectiveDoneResult(o.objectiveId), })); // TODO: ApproveObjective should probably just return a MultipleChannelOuput const completedObjectives = objectives.filter(o => o.status === 'succeeded'); completedObjectives.forEach(o => this.emit('ObjectiveCompleted', o)); await this._chainService.handleChainRequests(chainRequests); await this.messageService.send(messages); return Promise.all(results); } /** Creates channels using the given parameters. * @param channelParameters The parameters to use for channel creation. A channel will be created for each entry in the array. * @returns A promise that resolves to a collection of ObjectiveResult. */ public async createChannels( channelParameters: CreateChannelParams[] ): Promise<ObjectiveResult[]> { return Promise.all( channelParameters.map(async p => { try { const createResult = await this._engine.createChannel(p); await this.registerChannels([createResult.channelResult]); const {newObjective, channelResult} = createResult; const done = this.createObjectiveDoneResult(newObjective.objectiveId); await this.handleEngineOutput(createResult); return { channelId: channelResult.channelId, currentStatus: newObjective.status, objectiveId: newObjective.objectiveId, done, }; } catch (error) { this._logger.error({err: error}, 'Uncaught InternalError in CreateChannel'); // TODO: This is slightly hacky but it's less painful then having to narrow the type down every time // you get a result back from the createChannels method // This should be looked at in https://github.com/statechannels/statechannels/issues/3461 return { channelId: 'ERROR', currentStatus: 'failed' as const, objectiveId: 'ERROR', done: Promise.resolve({type: 'InternalError' as const, error}), }; } }) ); } /** * Updates a channel with the given allocations and app data. * @param channelId The id of the channel to update. * @param allocations The updated allocations for the channel. * @param appData The updated appData for the channel. * @returns A promise that resolves to either a sucess result (which includes the updated channel) or * an error type that contains more information about the error. */ public async updateChannel( channelId: string, allocations: Allocation[], appData: string ): Promise<UpdateChannelResult> { try { const updateResponse = await this._engine.updateChannel({channelId, allocations, appData}); await this.handleEngineOutput(updateResponse); return {type: 'Success', channelId, result: updateResponse.channelResult}; } catch (error) { return {type: 'InternalError', error, channelId}; } } private async syncObjectives() { const staleDate = Date.now() - this._syncOptions.staleThreshold; const timeOutDate = Date.now() - this._syncOptions.timeOutThreshold; const objectives = await this._engine.store.getApprovedObjectives(); const timedOutObjectives = objectives.filter(o => o.progressLastMadeAt.getTime() < timeOutDate); for (const o of timedOutObjectives) { this.emit('ObjectiveTimedOut', o); } const staleObjectives = objectives .filter(o => o.progressLastMadeAt.getTime() < staleDate) .map(o => o.objectiveId); const syncMessages = await this._engine.syncObjectives(staleObjectives); await this._messageService.send(syncMessages); } /** Closes the specified channels * @param channelIds The ids of the channels to close. * @returns A promise that resolves to a collection of ObjectiveResult. */ public async closeChannels(channelIds: string[]): Promise<ObjectiveResult[]> { return Promise.all( channelIds.map(async channelId => { const objectiveId = calculateObjectiveId('CloseChannel', channelId); const done = this.createObjectiveDoneResult(objectiveId); const closeResult = await this._engine.closeChannel({channelId}); const {newObjective, channelResult} = closeResult; // create the promise before we send anything out // TODO: We just refetch to get the latest status // Long term we should make sure the engine returns the latest objectives const latest = await this._engine.getObjective(newObjective.objectiveId); await this.handleEngineOutput(closeResult); return { channelId: channelResult.channelId, currentStatus: latest.status, objectiveId: newObjective.objectiveId, done, }; }) ); } /** * Finds any approved objectives and attempts to make progress on them. * This is useful for restarting progress after a restart or crash. * @returns A collection of ObjectiveResults. There will be an ObjectiveResult for each approved objective found. */ public async jumpStartObjectives(): Promise<ObjectiveResult[]> { const objectives = await this._engine.getApprovedObjectives(); const objectiveIds = objectives.map(o => o.objectiveId); await this._engine.store.updateObjectiveProgressDate(objectiveIds); const syncMessages = await this._engine.syncObjectives(objectiveIds); const results = objectives.map(async o => { const done = this.createObjectiveDoneResult(o.objectiveId); return { objectiveId: o.objectiveId, currentStatus: o.status, channelId: o.data.targetChannelId, done, }; }); await this.messageService.send(syncMessages); return Promise.all(results); } private emitEvents(result: MultipleChannelOutput | SingleChannelOutput): void { if (isMultipleChannelOutput(result)) { for (const c of result.channelResults) { this.emit('ChannelUpdated', c); } // Receiving messages from other participants may have resulted in completed objectives for (const o of result.completedObjectives) { this.emit('ObjectiveCompleted', o); } // Receiving messages from other participants may have resulted in new proposed objectives for (const o of result.newObjectives) { if (o.status === 'pending') { this.emit('ObjectiveProposed', o); } } } else { this.emit('ChannelUpdated', result.channelResult); if (hasNewObjective(result)) { if (result.newObjective.status === 'pending') { this.emit('ObjectiveProposed', result.newObjective); } } } } /** * Emits events, sends messages and requests transactions based on the output of the engine. * @param output */ private async handleEngineOutput( output: MultipleChannelOutput | SingleChannelOutput ): Promise<void> { this.emitEvents(output); await this._messageService.send(getMessages(output)); await this._chainService.handleChainRequests(output.chainRequests); } public get messageService(): MessageServiceInterface { return this._messageService; } private async createObjectiveDoneResult(objectiveId: string): Promise<ObjectiveDoneResult> { return new Promise<ObjectiveDoneResult>(resolve => { this.on('ObjectiveTimedOut', o => { if (o.objectiveId === objectiveId) { this._logger.trace({objective: o}, 'Objective Timed out'); resolve({ type: 'ObjectiveTimedOutError', objectiveId: o.objectiveId, lastProgressMadeAt: o.progressLastMadeAt, }); } }); this.on('ObjectiveCompleted', o => { if (o.objectiveId === objectiveId) { this._logger.trace({objective: o}, 'Objective Suceeded'); resolve({type: 'Success', channelId: o.data.targetChannelId}); } }); }); } /** * Registers any channels existing in the database with the chain service. * * @remarks * Enables the chain service to alert the engine of of any blockchain events for existing channels. * * @returns A promise that resolves when the channels have been successfully registered. */ private async registerExistingChannelsWithChainService(): Promise<void> { const channelsToRegister = (await this._engine.store.getNonFinalizedChannels()).map( ChannelState.toChannelResult ); await this.registerChannels(channelsToRegister); } private async registerChannels(channelsToRegister: ChannelResult[]): Promise<void> { const channelsWithAssetHolders = channelsToRegister.map(cr => ({ assetHolderAddresses: cr.allocations.map(a => makeAddress(a.asset)), channelId: cr.channelId, })); for (const {channelId, assetHolderAddresses} of channelsWithAssetHolders) { this._chainService.registerChannel(channelId, assetHolderAddresses, this._chainListener); } } private createChainEventlistener< K extends keyof ChainEventSubscriberInterface, EH extends ChainEventSubscriberInterface[K] >(eventName: K, storeUpdater: EH) { return async ( event: HoldingUpdatedArg & AllocationUpdatedArg & ChannelFinalizedArg & ChallengeRegisteredArg ) => { const {channelId} = event; this._logger.trace({event}, `${eventName} being handled`); try { await storeUpdater(event); const result = await this._engine.crank([channelId]); await this.handleEngineOutput(result); } catch (err) { this._logger.error({err, event}, `Error handling ${eventName}`); throw err; } }; } public async getSigningAddress(): Promise<Address> { return this._engine.getSigningAddress(); } public async getChannels(): Promise<ChannelResult[]> { const {channelResults} = await this._engine.getChannels(); return channelResults; } /** * Registers a peer with the message service so messages can be sent to the peer. * @param peerUrl The endpoint for the peer. */ public async registerPeerMessageService(peerUrl: string): Promise<void> { await this.messageService.registerPeer(peerUrl); } async destroy(): Promise<void> { await clearIntervalAsync(this._syncInterval); this._chainService.destructor(); await this._messageService.destroy(); await this._engine.destroy(); } }
the_stack
import type * as Genie from 'genie-toolkit'; /* eslint prefer-const: off, @typescript-eslint/no-inferrable-types: off */ /** Database URL. This must be the URL of the MySQL server shared by all almond-cloud components. The format is: ``` mysql://<user>:<password>@<hostname>/<db_name>?<options> ``` See the documentation of node-mysql for options. If you use Amazon RDS, you should say so with `ssl=Amazon%20RDS`. It is recommended you set `timezone=Z` in the options (telling the database to store dates and times in UTC timezone). For legacy reasons, this defaults to the `DATABASE_URL` environment variable. Using environment variables is currently secure but deprecated (because it can lead to security bugs). Note: do not set this in `custom_config.js`, only in `/etc/almond-cloud/config.js`. */ export let DATABASE_URL : string|undefined = process.env.DATABASE_URL; /** Database Proxy URL. This the URL of the dbproxy server setup in the kubernetes cluster. If set, worker engine will use the cloud database through the proxy. Otherwise, a local sqlitedb is used. */ export let DATABASE_PROXY_URL : string|null = null; /** Secret key for cookie signing. This can be an arbitrary secret string. It is recommended to choose 64 random HEX characters (256 bit security). Choose a secure secret to prevent session hijacking. For legacy reasons, this defaults to the `SECRET_KEY` environment variable. Using environment variables is currently secure but deprecated (because it can lead to security bugs). The server will refuse to start if this option is not set. */ export let SECRET_KEY : string = process.env.SECRET_KEY!; /** Secret key for JsonWebToken signing (OAuth 2.0 tokens) This can be an arbitrary secret string. It is recommended to choose 64 random HEX characters (256 bit security). Choose a secure secret to prevent forging OAuth access tokens. For legacy reasons, this defaults to the `JWT_SIGNING_KEY` environment variable. Using environment variables is currently secure but deprecated (because it can lead to security bugs). The server will refuse to start if this option is not set. */ export let JWT_SIGNING_KEY : string = process.env.JWT_SIGNING_KEY!; /** Symmetric encryption key for user authentication material This key is used whenever user-authentication-related secret material must be encrypted symmetrically, rather than simply hashed. In particular, it is used to encrypt and decrypt per-user 2-factor keys. This secret must be exactly 32 hex characters (128 bits). For legacy reasons, this defaults to the `AES_SECRET_KEY` environment variable. Using environment variables is currently secure but deprecated (because it can lead to security bugs). The server will refuse to start if this option is not set. */ export let AES_SECRET_KEY : string = process.env.AES_SECRET_KEY!; /** Address of each master process. Each address must be specified in sockaddr form: - absolute or relative path for Unix socket - hostname:port for TCP Multiple addresses can be provided, in which case the users will be sharded across multiple masters based on their ID (using a simple hashing scheme). The number of shards can be changed dynamically, provided all processes use a consistent configuration (they must be all stopped when the configuration is changed), and all shards have access to shared storage (e.g. NFS). If the storage is not shared, use the `get-user-shards` to compute which user is assigned to which shard, and transfer the user's folder appropriately. */ export let THINGENGINE_MANAGER_ADDRESS : string[] = ['./control']; /** Access token to communicate with the master process. This **must** be set if communication happens over to TCP, but can be left to the default `null` value if communication happens over Unix domain sockets, in which case file system permissions are used to restrict access. */ export let THINGENGINE_MANAGER_AUTHENTICATION : string|null = null; /** Thingpedia configuration. Set this option to 'embedded' to enable the embedded Thingpedia, to 'external' to use the Thingpedia at THINGPEDIA_URL. */ export let WITH_THINGPEDIA : 'external'|'embedded' = 'external'; /** Thingpedia URL This is used by the Almond backend to communicate with the external Thingpedia, and it is also used to construct links to Thingpedia from My Almond. It **must** be set to `'/thingpedia'` to use the embedded Thingpedia. */ export let THINGPEDIA_URL : string = 'https://thingpedia.stanford.edu/thingpedia'; /** Default Thingpedia developer key to use for Web Almond. In external Thingpedia mode, this Thingpedia key will be made available to all users that do not have another key configured, so they can access private devices from the external Thingpedia. The developer program must be disabled for this key to have any effect (ENABLE_DEVELOPER_PROGRAM = false), and this key has no effect in embedded Thingpedia mode. This key only affects users running Web Almond. To configure the key used by the embedded NLP server, set NL_THINGPEDIA_DEVELOPER_KEY. */ export let THINGPEDIA_DEVELOPER_KEY : string|null = null; /** Thingpedia developer key to use for the root user in Web Almond. In external Thingpedia mode, the initially created root user and all users in the root organization will use this developer key. If unset, the root user will use a randomly generated Thingpedia key. This key has no effect in embedded Thingpedia mode. */ export let ROOT_THINGPEDIA_DEVELOPER_KEY : string|null = null; /** Where to store icons and zip files. This can be a relative or absolute path, or a file: or s3: URI. The location must be writable by the frontend Almond processes. Relative paths are interpreted relative to the current working directory, or the `THINGENGINE_ROOTDIR` environment variable if set. NOTE: correct operation requires file: URIs to use the local hostname, that is, they should be of the form `file:///`, with 3 consecutive slashes. */ export let FILE_STORAGE_DIR : string = './shared/download'; /** Where to cache entity icons and contact avatars. This can be a relative or absolute path. The location must be writable by the frontend Almond processes. Relative paths are interpreted relative to the current working directory, or the `THINGENGINE_ROOTDIR` environment variable if set. Note: unlike other _DIR configuration keys, this key cannot be a URL. The cache directory is always on the local machine where the Almond process runs. */ export let CACHE_DIR : string = './shared/cache'; /** The location where icons and zip files can be retrieved. If using S3 storage, this could be the S3 website URL, or the URL of a CloudFront distribution mapping to the S3 bucket. If using local storage, or if no CDN is available, it must be the exact string `"/download"`. */ export let CDN_HOST : string = '/download'; /** The CDN to use for website assets (javascript, css, images files contained in public/ ) You should configure your CDN to map the URL you specify here to the /assets path on the frontend server (SERVER_ORIGIN setting). Use a fully qualified URL (including https://) and omit the trailing slash. Use the default `/assets` if you do not want to use a CDN, in which case assets will be loaded directly from your configured frontend server. */ export let ASSET_CDN : string = '/assets'; /** Which branding to use for the website. Valid values are "generic" (no branding) or "stanford" (Stanford University logo and footer). Note that the Stanford University logo is a registered trademark, and therefore using "stanford" branding requires permission. */ export let USE_BRAND : string = 'generic'; /** An optional warning message to show on the registration page. This can be used on testing versions of Genie to inform people that they are accessing an unstable system. HTML is allowed in this configuration key. */ module.exports.REGISTRATION_WARNING = null; /** The origin (scheme, hostname, port) where the server is reachable. This is used for redirects and CORS checks. */ export let SERVER_ORIGIN : string = 'http://127.0.0.1:8080'; /** Enable redirection to SERVER_ORIGIN for requests with different hostname or scheme. Use this to enable transparent HTTP to HTTPS redirection. */ export let ENABLE_REDIRECT : boolean = true; /** Enable HTTPs security headers. Enable Strict-Transport-Security, Content-Security-Policy and other headers. This option has no effect if the server is not available over TLS. */ export let ENABLE_SECURITY_HEADERS : boolean = false; /** Override which pug file to use for about pages. Use this option to customize the index, terms-of-service, etc. pages The key should be the page name (part of path after /about), the value should be the name of a pug file in views, without the .pug extension. If unspecified, defaults to "about_" + page_name, eg. for `privacy` it defaults to showing `about_privacy.pug`. If you plan to serve Web Almond to users and allow registration, at the minimum you must override the `tos` page (terms of service) and the `privacy` page (privacy policy), as they are empty in the default installation. Use ABOUT_OVERRIDE['index'] to override the whole website index. Note that "/about" with no page unconditionally redirects to "/", */ export let ABOUT_OVERRIDE : Record<string, string> = {}; /** Adds new pages to the /about hierarchy This option is an array of objects. The format should be: ``` { url: path name, excluding /about part title: page title view: name of pug file } ``` */ export let EXTRA_ABOUT_PAGES : Array<{ url : string, title : string, view : string }> = []; /** Adds new links to the navbar This option is an array of objects. The format should be: ``` { url: link URL title: link title } ``` */ export let EXTRA_NAVBAR : Array<{ url : string, title : string }> = []; /** Registration warning This is a bit of HTML that can be shown on the registration page. It can be useful to warn about development or unstable servers. If set, it must be valid HTML. It will be shown inside a Boostrap alert component. *No sanitization is applied!* */ export let REGISTRATION_WARNING : string|null = null; /** Additional origins that should be allowed to make Cookie-authenticated API requests. Note: this is a very unsafe option, and can easily lead to credential leaks. Use this at your own risk. */ export let EXTRA_ORIGINS : string[] = []; /** The base URL used for OAuth redirects This is used by the OAuth configuration mechanism for accounts/devices in Web Almond. It is used by Login With Google. The full OAuth redirect URI for Google is OAUTH_REDIRECT_ORIGIN + `/user/oauth2/google/callback` By default, it is the same as SERVER_ORIGIN, but you can change it if you put a different value in the developer console / redirect URI fields of the various services. */ export let OAUTH_REDIRECT_ORIGIN : string = SERVER_ORIGIN; /** Enable anonymous user. Set this option to true to let users try out Almond without logging in. They will operate as the user "anonymous". */ export let ENABLE_ANONYMOUS_USER : boolean = false; /** Enable developer program. Set this option to allow users to become Almond developers, and create OAuth apps that access the Web Almond APIs, as well as new Thingpedia devices or LUInet models. */ export let ENABLE_DEVELOPER_PROGRAM : boolean = false; /** Enable developer backend. Use dedicated pod to host trusted developer backend. For security, it is recommended to enable this feature when ENABLE_DEVELOPER_PROGRAM is set to true. This, however, will increase startup time of developer's backend as a new pod will be created. */ export let ENABLE_DEVELOPER_BACKEND : boolean = false; /** LUInet (Natural Language model/server) configuration Set this to 'external' for a configuration using a public Natural Language server, and 'embedded' if you manage your own NLP server. Setting this to 'embedded' enables the configuration UI to manage models and train. */ export let WITH_LUINET : 'embedded'|'external' = 'external'; /** The URL of a genie-compatible Natural Language inference server. This must be set to the full URL both if you use the public NL inference server, and if you use the embedded server. */ export let NL_SERVER_URL : string = 'https://almond-nl.stanford.edu'; /** Access token for administrative operations in the NLP inference server. This tokens controls the ability to reload models from disk. It should be shared between the NLP training server and NLP inference server. This must be not null if `WITH_LUINET` is set to 'embedded'. */ export let NL_SERVER_ADMIN_TOKEN : string|null = null; /** Developer key to use from the NLP server to access Thingpedia. Set this key to your Thingpedia developer key if you're configuring a custom NLP server but you want to use the public Thingpedia. This key only affects the embedded NLP server. To configure the key used by users running Web Almond and talking to this NLP server, set THINGPEDIA_DEVELOPER_KEY. */ export let NL_THINGPEDIA_DEVELOPER_KEY : string|null = null; /** Deployed models. This contains the list of models that should be served by the NLP inference server. Each model has a tag (which works as a prefix of the URL) and a locale. The model with tag "org.thingpedia.models.default" will be also served without a tag prefix. Models are served based on the given URL, which can be a relative or absolute path, a kf+http: URI (for a KFserving deployment), or a file: or s3: URI. Relative paths are interpreted relative to the current working directory, or the `THINGENGINE_ROOTDIR` environment variable if set. */ export let NL_MODELS : Array<{ tag : string, locale : string, owner : number|undefined, model_url : string, access_token : string|undefined, contextual : boolean, use_exact : boolean, }> = []; /** Directory for exact match files. This is the path containing the binary format files for the exact matcher. It can be a relative or absolute path, or a file: or s3: URI. Relative paths are interpreted relative to the current working directory, or the `THINGENGINE_ROOTDIR` environment variable if set. */ export let NL_EXACT_MATCH_DIR : string = './exact'; /** NLP Service name. The kubernetes service name for NLP server. */ export let NL_SERVICE_NAME : string = 'nlp'; /** Training server URL. This URL will be called from the Thingpedia web server when a new device is updated. */ export let TRAINING_URL : string|null = null; /** Access token for the training server. This token protects all requests to the training server. */ export let TRAINING_ACCESS_TOKEN : string|null = null; /** Maximum memory usage for training processes. In megabytes. */ export let TRAINING_MEMORY_USAGE : number = 24000; /** The directory to use to store training jobs (datasets, working directories and trained models). This can be a relative or absolute path, or a file: or s3: URI. Relative paths are interpreted relative to the current working directory, or the `THINGENGINE_ROOTDIR` environment variable if set. NOTE: correct operation requires file: URIs to use the local hostname, that is, they should be of the form `file:///`, with 3 consecutive slashes. */ export let TRAINING_DIR : string = './training'; /** Which backend to use to run compute-intensive training tasks. Valid options are `local`, which spawns a local process, and `kubernetes`, which creates a Kubernetes Job. If `kubernetes` is chosen, the training controller must be executed in a training cluster and must run a service account with sufficient privileges to create and watch Jobs. */ export let TRAINING_TASK_BACKEND : 'local'|'kubernetes' = 'local'; /** The Docker image to use for training using Kubernetes. The suffix `-cuda` will be appended to the version for GPU training. */ export let TRAINING_KUBERNETES_IMAGE : string = 'stanfordoval/almond-cloud:latest-decanlp'; /** The namespace for Kubernetes Jobs created for training. */ export let TRAINING_KUBERNETES_NAMESPACE : string = 'default'; /** Prefix to add to the Kubernetes Jobs and Pods created for training. */ export let TRAINING_KUBERNETES_JOB_NAME_PREFIX : string = ''; /** Additional labels to add to the Kubernetes Jobs and Pods created for training. @type {Record<string, unknown>} */ export let TRAINING_KUBERNETES_EXTRA_METADATA_LABELS = {}; /** Additional annotations to add to the Kubernetes Jobs and Pods created for training. */ export let TRAINING_KUBERNETES_EXTRA_ANNOTATIONS : Record<string, unknown> = {}; /** Additional fields to add to the Kubernetes Pods created for training. */ export let TRAINING_KUBERNETES_POD_SPEC_OVERRIDE : Record<string, unknown> = {}; /** Additional fields to add to the Kubernetes Pods created for training. */ export let TRAINING_KUBERNETES_CONTAINER_SPEC_OVERRIDE : Record<string, unknown> = {}; /** Number of tries to watch k8s job status. Setting to a negative number will try indefinitely. */ export let TRAINING_WATCH_NUM_TRIES : number = 5; /** Directory in s3:// or file:// URI, where tensorboard events are synced to during training. */ export let TENSORBOARD_DIR : string|null = null; /** OAuth Client ID to support Login With Google */ export let GOOGLE_CLIENT_ID : string|null = null; /** OAuth Client secret to support Login With Google */ export let GOOGLE_CLIENT_SECRET : string|null = null; /** OAuth Client ID to support Login With Github */ export let GITHUB_CLIENT_ID : string|null = null; /** OAuth Client secret to support Login With Github */ export let GITHUB_CLIENT_SECRET : string|null = null; /** Mailgun user name For emails sent from Almond */ export let MAILGUN_USER : string|null = null; /** Mailgun password For emails sent from Almond */ export let MAILGUN_PASSWORD : string|null = null; /** From: field of user emails (email verification, password reset, etc.) */ export let EMAIL_FROM_USER : string = 'Genie <noreply@almond.stanford.edu>'; /** From: field of admin emails (review requests, developer requests, etc.) */ export let EMAIL_FROM_ADMIN : string = 'Genie <root@almond.stanford.edu>'; /** From: field of admin-training notifications */ export let EMAIL_FROM_TRAINING : string = 'Genie Training Service <genie-training@almond.stanford.edu>'; /** To: field of admin emails Automatically generated email notifications (such as training failures) will be sent to this address. */ export let EMAIL_TO_ADMIN : string = 'thingpedia-admins@lists.stanford.edu'; /** The primary "messaging" device. This is offered as the default device to configure for communicating assistants, if no other messaging device is available. */ export let MESSAGING_DEVICE : string = 'org.thingpedia.builtin.matrix'; /** Enable metric collection using Prometheus. If set to `true`, all web servers will expose a Prometheus-compatible `/metrics` endpoint. */ export let ENABLE_PROMETHEUS : boolean = false; /** Access token to use for /metrics endpoint. If null, the endpoint will have no authentication, and metric data will be publicly readable. This value should match the "bearer_token" prometheus configuration value. */ export let PROMETHEUS_ACCESS_TOKEN : string|null = null; /** Secret for Discourse Single-Sign-On See https://meta.discourse.org/t/official-single-sign-on-for-discourse-sso/13045 for the protocol. SSO will be disabled (404 error) if SSO_SECRET or SSO_REDIRECT is null. Unlike OAuth, there is no "confirm" step before user's data is sent to the requesting service, hence this secret REALLY must be secret. */ export let DISCOURSE_SSO_SECRET : string|null = null; /** Redirect URL for Discourse Single-Sign-On. Set this to the URL of your Discourse installation. This should be the origin (scheme-hostname-port) only, `/session/sso_login` will be appended. */ export let DISCOURSE_SSO_REDIRECT : string|null = null; /** What natural languages are enabled, as BCP47 locale tags. Defaults to American English only Note that this must contain at least one language, or the server will fail to start. */ export let SUPPORTED_LANGUAGES : string[] = ['en-US']; /** MapQuest API key. This is key is used to provide the location querying API. If unset, it will fallback to the public Nominatim API, which has a low API quota. */ export let MAPQUEST_KEY : string|null = null; /** URL of an [Ackee](https://github.com/electerious/Ackee) server to use for page tracking. This property must contain the full URL (protocol, hostname, optional port) of the server, and must not end with a slash. If null, tracking will be disabled. */ export let ACKEE_URL : string|null = null; /** Domain ID to use for [Ackee](https://github.com/electerious/Ackee) tracking. This must be set if `ACKEE_URL` is set. */ export let ACKEE_DOMAIN_ID : string|null = null; /** URL of a server supporting speech-to-text and text-to-speech. */ export let VOICE_SERVER_URL : string = 'https://voice.almond.stanford.edu'; /** Azure subscription key for Microsoft Speech Services SDK */ export let MS_SPEECH_SUBSCRIPTION_KEY : string|null = null; /** Azure region identifier for Microsoft Speech Services SDK */ export let MS_SPEECH_SERVICE_REGION : string|null = null; /** * FAQ models to enable. */ export let FAQ_MODELS : Record<string, { url : string, highConfidence ?: number, lowConfidence ?: number }> = {}; /** * Configuration parameters for builtin notification modules. */ export let NOTIFICATION_CONFIG : Genie.DialogueAgent.NotificationConfig = {}; /** * Additional environment variables to set for the almond workers. */ export let EXTRA_ENVIRONMENT : Record<string, string> = {}; /** * Optional Redis host used for caching. If this is not `null`, the app will try * to use the cache. */ export let REDIS_HOST : null | string = null; /** * User to connect to redis as. Must be defined if `REDIS_PASSWORD` is not * `null. */ export let REDIS_USER : null | string = null; /** * Optional Redis password. */ export let REDIS_PASSWORD : null | string = null;
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class Outposts extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: Outposts.Types.ClientConfiguration) config: Config & Outposts.Types.ClientConfiguration; /** * Creates an order for an Outpost. */ createOrder(params: Outposts.Types.CreateOrderInput, callback?: (err: AWSError, data: Outposts.Types.CreateOrderOutput) => void): Request<Outposts.Types.CreateOrderOutput, AWSError>; /** * Creates an order for an Outpost. */ createOrder(callback?: (err: AWSError, data: Outposts.Types.CreateOrderOutput) => void): Request<Outposts.Types.CreateOrderOutput, AWSError>; /** * Creates an Outpost. You can specify AvailabilityZone or AvailabilityZoneId. */ createOutpost(params: Outposts.Types.CreateOutpostInput, callback?: (err: AWSError, data: Outposts.Types.CreateOutpostOutput) => void): Request<Outposts.Types.CreateOutpostOutput, AWSError>; /** * Creates an Outpost. You can specify AvailabilityZone or AvailabilityZoneId. */ createOutpost(callback?: (err: AWSError, data: Outposts.Types.CreateOutpostOutput) => void): Request<Outposts.Types.CreateOutpostOutput, AWSError>; /** * Deletes the Outpost. */ deleteOutpost(params: Outposts.Types.DeleteOutpostInput, callback?: (err: AWSError, data: Outposts.Types.DeleteOutpostOutput) => void): Request<Outposts.Types.DeleteOutpostOutput, AWSError>; /** * Deletes the Outpost. */ deleteOutpost(callback?: (err: AWSError, data: Outposts.Types.DeleteOutpostOutput) => void): Request<Outposts.Types.DeleteOutpostOutput, AWSError>; /** * Deletes the site. */ deleteSite(params: Outposts.Types.DeleteSiteInput, callback?: (err: AWSError, data: Outposts.Types.DeleteSiteOutput) => void): Request<Outposts.Types.DeleteSiteOutput, AWSError>; /** * Deletes the site. */ deleteSite(callback?: (err: AWSError, data: Outposts.Types.DeleteSiteOutput) => void): Request<Outposts.Types.DeleteSiteOutput, AWSError>; /** * Gets information about the specified Outpost. */ getOutpost(params: Outposts.Types.GetOutpostInput, callback?: (err: AWSError, data: Outposts.Types.GetOutpostOutput) => void): Request<Outposts.Types.GetOutpostOutput, AWSError>; /** * Gets information about the specified Outpost. */ getOutpost(callback?: (err: AWSError, data: Outposts.Types.GetOutpostOutput) => void): Request<Outposts.Types.GetOutpostOutput, AWSError>; /** * Lists the instance types for the specified Outpost. */ getOutpostInstanceTypes(params: Outposts.Types.GetOutpostInstanceTypesInput, callback?: (err: AWSError, data: Outposts.Types.GetOutpostInstanceTypesOutput) => void): Request<Outposts.Types.GetOutpostInstanceTypesOutput, AWSError>; /** * Lists the instance types for the specified Outpost. */ getOutpostInstanceTypes(callback?: (err: AWSError, data: Outposts.Types.GetOutpostInstanceTypesOutput) => void): Request<Outposts.Types.GetOutpostInstanceTypesOutput, AWSError>; /** * Create a list of the Outposts for your AWS account. Add filters to your request to return a more specific list of results. Use filters to match an Outpost lifecycle status, Availibility Zone (us-east-1a), and AZ ID (use1-az1). If you specify multiple filters, the filters are joined with an AND, and the request returns only results that match all of the specified filters. */ listOutposts(params: Outposts.Types.ListOutpostsInput, callback?: (err: AWSError, data: Outposts.Types.ListOutpostsOutput) => void): Request<Outposts.Types.ListOutpostsOutput, AWSError>; /** * Create a list of the Outposts for your AWS account. Add filters to your request to return a more specific list of results. Use filters to match an Outpost lifecycle status, Availibility Zone (us-east-1a), and AZ ID (use1-az1). If you specify multiple filters, the filters are joined with an AND, and the request returns only results that match all of the specified filters. */ listOutposts(callback?: (err: AWSError, data: Outposts.Types.ListOutpostsOutput) => void): Request<Outposts.Types.ListOutpostsOutput, AWSError>; /** * Lists the sites for the specified AWS account. */ listSites(params: Outposts.Types.ListSitesInput, callback?: (err: AWSError, data: Outposts.Types.ListSitesOutput) => void): Request<Outposts.Types.ListSitesOutput, AWSError>; /** * Lists the sites for the specified AWS account. */ listSites(callback?: (err: AWSError, data: Outposts.Types.ListSitesOutput) => void): Request<Outposts.Types.ListSitesOutput, AWSError>; /** * Lists the tags for the specified resource. */ listTagsForResource(params: Outposts.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: Outposts.Types.ListTagsForResourceResponse) => void): Request<Outposts.Types.ListTagsForResourceResponse, AWSError>; /** * Lists the tags for the specified resource. */ listTagsForResource(callback?: (err: AWSError, data: Outposts.Types.ListTagsForResourceResponse) => void): Request<Outposts.Types.ListTagsForResourceResponse, AWSError>; /** * Adds tags to the specified resource. */ tagResource(params: Outposts.Types.TagResourceRequest, callback?: (err: AWSError, data: Outposts.Types.TagResourceResponse) => void): Request<Outposts.Types.TagResourceResponse, AWSError>; /** * Adds tags to the specified resource. */ tagResource(callback?: (err: AWSError, data: Outposts.Types.TagResourceResponse) => void): Request<Outposts.Types.TagResourceResponse, AWSError>; /** * Removes tags from the specified resource. */ untagResource(params: Outposts.Types.UntagResourceRequest, callback?: (err: AWSError, data: Outposts.Types.UntagResourceResponse) => void): Request<Outposts.Types.UntagResourceResponse, AWSError>; /** * Removes tags from the specified resource. */ untagResource(callback?: (err: AWSError, data: Outposts.Types.UntagResourceResponse) => void): Request<Outposts.Types.UntagResourceResponse, AWSError>; } declare namespace Outposts { export type AccountId = string; export type Arn = string; export type AvailabilityZone = string; export type AvailabilityZoneId = string; export type AvailabilityZoneIdList = AvailabilityZoneId[]; export type AvailabilityZoneList = AvailabilityZone[]; export interface CreateOrderInput { /** * The ID or the Amazon Resource Name (ARN) of the Outpost. */ OutpostIdentifier: OutpostIdentifier; /** * The line items that make up the order. */ LineItems: LineItemRequestListDefinition; /** * The payment option for the order. */ PaymentOption: PaymentOption; /** * The payment terms for the order. */ PaymentTerm?: PaymentTerm; } export interface CreateOrderOutput { /** * Information about this order. */ Order?: Order; } export interface CreateOutpostInput { Name: OutpostName; Description?: OutpostDescription; SiteId: SiteId; AvailabilityZone?: AvailabilityZone; AvailabilityZoneId?: AvailabilityZoneId; /** * The tags to apply to the Outpost. */ Tags?: TagMap; } export interface CreateOutpostOutput { Outpost?: Outpost; } export interface DeleteOutpostInput { /** * The ID of the Outpost. */ OutpostId: OutpostId; } export interface DeleteOutpostOutput { } export interface DeleteSiteInput { SiteId: SiteId; } export interface DeleteSiteOutput { } export interface GetOutpostInput { /** * The ID of the Outpost. */ OutpostId: OutpostId; } export interface GetOutpostInstanceTypesInput { /** * The ID of the Outpost. */ OutpostId: OutpostId; NextToken?: Token; MaxResults?: MaxResults1000; } export interface GetOutpostInstanceTypesOutput { InstanceTypes?: InstanceTypeListDefinition; NextToken?: Token; /** * The ID of the Outpost. */ OutpostId?: OutpostId; OutpostArn?: OutpostArn; } export interface GetOutpostOutput { Outpost?: Outpost; } export type ISO8601Timestamp = Date; export type InstanceType = string; export interface InstanceTypeItem { InstanceType?: InstanceType; } export type InstanceTypeListDefinition = InstanceTypeItem[]; export type LifeCycleStatus = string; export type LifeCycleStatusList = LifeCycleStatus[]; export interface LineItem { /** * The ID of the catalog item. */ CatalogItemId?: SkuCode; /** * The ID of the line item. */ LineItemId?: LineItemId; /** * The quantity of the line item. */ Quantity?: LineItemQuantity; /** * The status of the line item. */ Status?: Status; } export type LineItemId = string; export type LineItemListDefinition = LineItem[]; export type LineItemQuantity = number; export interface LineItemRequest { /** * The ID of the catalog item. */ CatalogItemId?: SkuCode; /** * The quantity of a line item request. */ Quantity?: LineItemQuantity; } export type LineItemRequestListDefinition = LineItemRequest[]; export interface ListOutpostsInput { NextToken?: Token; MaxResults?: MaxResults1000; /** * A filter for the lifecycle status of the Outpost. Filter values are case sensitive. If you specify multiple values for a filter, the values are joined with an OR, and the request returns all results that match any of the specified values. */ LifeCycleStatusFilter?: LifeCycleStatusList; /** * A filter for the Availibility Zone (us-east-1a) of the Outpost. Filter values are case sensitive. If you specify multiple values for a filter, the values are joined with an OR, and the request returns all results that match any of the specified values. */ AvailabilityZoneFilter?: AvailabilityZoneList; /** * A filter for the AZ IDs (use1-az1) of the Outpost. Filter values are case sensitive. If you specify multiple values for a filter, the values are joined with an OR, and the request returns all results that match any of the specified values. */ AvailabilityZoneIdFilter?: AvailabilityZoneIdList; } export interface ListOutpostsOutput { Outposts?: outpostListDefinition; NextToken?: Token; } export interface ListSitesInput { NextToken?: Token; MaxResults?: MaxResults1000; } export interface ListSitesOutput { Sites?: siteListDefinition; NextToken?: Token; } export interface ListTagsForResourceRequest { /** * The Amazon Resource Name (ARN) of the resource. */ ResourceArn: Arn; } export interface ListTagsForResourceResponse { /** * The resource tags. */ Tags?: TagMap; } export type MaxResults1000 = number; export interface Order { /** * The ID of the Outpost. */ OutpostId?: OutpostIdOnly; /** * The ID of the order. */ OrderId?: OrderId; /** * The status of the order */ Status?: OrderStatus; /** * The line items for the order */ LineItems?: LineItemListDefinition; /** * The payment option for the order. */ PaymentOption?: PaymentOption; /** * The submission date for the order. */ OrderSubmissionDate?: ISO8601Timestamp; /** * The fulfillment date of the order. */ OrderFulfilledDate?: ISO8601Timestamp; } export type OrderId = string; export type OrderStatus = "RECEIVED"|"PENDING"|"PROCESSING"|"INSTALLING"|"FULFILLED"|"CANCELLED"|string; export interface Outpost { /** * The ID of the Outpost. */ OutpostId?: OutpostId; OwnerId?: OwnerId; OutpostArn?: OutpostArn; SiteId?: SiteId; Name?: OutpostName; Description?: OutpostDescription; LifeCycleStatus?: LifeCycleStatus; AvailabilityZone?: AvailabilityZone; AvailabilityZoneId?: AvailabilityZoneId; /** * The Outpost tags. */ Tags?: TagMap; SiteArn?: SiteArn; } export type OutpostArn = string; export type OutpostDescription = string; export type OutpostId = string; export type OutpostIdOnly = string; export type OutpostIdentifier = string; export type OutpostName = string; export type OwnerId = string; export type PaymentOption = "ALL_UPFRONT"|"NO_UPFRONT"|"PARTIAL_UPFRONT"|string; export type PaymentTerm = "THREE_YEARS"|string; export interface Site { SiteId?: SiteId; AccountId?: AccountId; Name?: SiteName; Description?: SiteDescription; /** * The site tags. */ Tags?: TagMap; SiteArn?: SiteArn; } export type SiteArn = string; export type SiteDescription = string; export type SiteId = string; export type SiteName = string; export type SkuCode = string; export type Status = string; export type TagKey = string; export type TagKeyList = TagKey[]; export type TagMap = {[key: string]: TagValue}; export interface TagResourceRequest { /** * The Amazon Resource Name (ARN) of the resource. */ ResourceArn: Arn; /** * The tags to add to the resource. */ Tags: TagMap; } export interface TagResourceResponse { } export type TagValue = string; export type Token = string; export interface UntagResourceRequest { /** * The Amazon Resource Name (ARN) of the resource. */ ResourceArn: Arn; /** * The tag keys. */ TagKeys: TagKeyList; } export interface UntagResourceResponse { } export type outpostListDefinition = Outpost[]; export type siteListDefinition = Site[]; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2019-12-03"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the Outposts client. */ export import Types = Outposts; } export = Outposts;
the_stack
import m from "mithril"; import Stream from "mithril/stream"; import * as Icons from "views/components/icons"; import {ErrorResponse} from "../../../helpers/api_request_builder"; import {MithrilComponent} from "../../../jsx/mithril-component"; import {FlashMessage, FlashMessageModelWithTimeout, MessageType} from "../../components/flash_message"; import {SelectField, SelectFieldOptions} from "../../components/forms/input_fields"; import {Link} from "../../components/link"; import * as styles from "./index.scss"; import {StageInstance} from "./models/stage_instance"; import {StageOverviewViewModel} from "./models/stage_overview_view_model"; import {StageState} from "./models/types"; interface StageHeaderAttrs { stageName: string; stageCounter: string | number; pipelineName: string; pipelineCounter: string | number; stageInstanceFromDashboard: any; canAdminister: boolean; templateName: string | undefined | null; pollingInterval?: number; status: Stream<string>; flashMessage: FlashMessageModelWithTimeout; stageInstance: Stream<StageInstance>; inProgressStageFromPipeline: Stream<any | undefined>; stageOverviewVM: Stream<StageOverviewViewModel>; userSelectedStageCounter: Stream<string | number>; shouldSelectLatestStageCounterOnUpdate: Stream<boolean>; latestStageCounter: Stream<string>; isLoading: Stream<boolean>; } interface StageHeaderState { isSettingsHover: Stream<boolean>; onStageCounterDropdownChange: (vnode: m.Vnode<StageHeaderAttrs, StageHeaderState>) => any; } export class StageHeaderWidget extends MithrilComponent<StageHeaderAttrs, StageHeaderState> { oninit(vnode: m.Vnode<StageHeaderAttrs, StageHeaderState>) { vnode.state.isSettingsHover = Stream<boolean>(false); vnode.state.onStageCounterDropdownChange = (vnode: m.Vnode<StageHeaderAttrs, StageHeaderState>) => { vnode.attrs.isLoading(true); // pass in the stage state as passed/failed, this value is just to denote whether the current stage instance has completed. StageOverviewViewModel.initialize(vnode.attrs.pipelineName, vnode.attrs.pipelineCounter, vnode.attrs.stageName, vnode.attrs.userSelectedStageCounter(), StageState.Passed, vnode.attrs.pollingInterval) .then((result) => { let stageResult = result.stageInstance().result(); if (stageResult === "Unknown") { stageResult = "Building"; } vnode.attrs.stageOverviewVM().stopRepeater(); vnode.attrs.status(stageResult.toLowerCase()); vnode.attrs.stageOverviewVM(result); }).finally(() => { vnode.attrs.isLoading(false); }); }; } view(vnode: m.Vnode<StageHeaderAttrs, StageHeaderState>): m.Children | void | null { const stageDetailsPageLink = `/go/pipelines/${vnode.attrs.pipelineName}/${vnode.attrs.pipelineCounter}/${vnode.attrs.stageName}/${vnode.attrs.userSelectedStageCounter()}`; let canceledBy: m.Child, dummyContainer; if (vnode.attrs.stageInstance().isCancelled()) { canceledBy = (<div class={styles.cancelledByWrapper} data-test-id="cancelled-by-wrapper"> <div data-test-id="cancelled-by-container" className={styles.triggeredByContainer}> Cancelled by <span className={styles.triggeredByAndOn}>{vnode.attrs.stageInstance().cancelledBy()}</span> </div> <div data-test-id="cancelled-on-container" className={styles.triggeredByContainer}> on <span title={vnode.attrs.stageInstance().cancelledOnServerTime()} className={styles.triggeredByAndOn}>{vnode.attrs.stageInstance().cancelledOn()}</span> Local Time </div> </div>); dummyContainer = <div className={styles.dummyContainerAboveStageDetailsLink}/>; } let optionalFlashMessage: m.Child; if (vnode.attrs.flashMessage.hasMessage()) { optionalFlashMessage = ( <FlashMessage dataTestId="stage-overview-flash-message" message={vnode.attrs.flashMessage.message} type={vnode.attrs.flashMessage.type}/>); } const stageSettingsUrl = vnode.attrs.templateName ? `/go/admin/templates/${vnode.attrs.templateName}/edit#!${vnode.attrs.templateName}/${vnode.attrs.stageName}/stage_settings` : `/go/admin/pipelines/${vnode.attrs.pipelineName}/edit#!${vnode.attrs.pipelineName}/${vnode.attrs.stageName}/stage_settings`; let stageSettings: m.Child; if (vnode.attrs.canAdminister) { stageSettings = (<div className={styles.stageSettings}> <Icons.Settings iconOnly={true} data-test-url={stageSettingsUrl} onclick={() => window.open(stageSettingsUrl)}/> </div>); } else { const disabledEditMessage = `You dont have permissions to edit the stage.`; stageSettings = (<div className={styles.stageSettings}> <Icons.Settings iconOnly={true} disabled={true} onmouseover={() => vnode.state.isSettingsHover(true)} onmouseout={() => vnode.state.isSettingsHover(false)}/> <span class={`${styles.tooltipMessage} ${!vnode.state.isSettingsHover() && styles.hidden}`}>{disabledEditMessage}</span> </div>); } let stageCounterView: m.Children; if ((+vnode.attrs.stageCounter) > 1) { const items = []; for (let i = 1; i <= (+vnode.attrs.stageCounter); i++) { items.push(`${i}`); } if (vnode.attrs.shouldSelectLatestStageCounterOnUpdate() && items[items.length - 1] !== vnode.attrs.latestStageCounter()) { vnode.attrs.userSelectedStageCounter(items[items.length - 1]); vnode.attrs.shouldSelectLatestStageCounterOnUpdate(false); vnode.attrs.isLoading(false); } vnode.attrs.latestStageCounter(items[items.length - 1]); let spinner: m.Children; if (vnode.attrs.isLoading()) { spinner = <Icons.Spinner iconOnly={true}/>; } stageCounterView = (<div class={styles.stageCounterDropdownWrapper} data-test-id="stage-counter-dropdown"> <SelectField property={vnode.attrs.userSelectedStageCounter as Stream<string>} onchange={vnode.state.onStageCounterDropdownChange.bind(vnode.state, vnode)}> <SelectFieldOptions selected={`${vnode.attrs.userSelectedStageCounter()}`} items={items}/> </SelectField> {spinner} </div>); } else { stageCounterView = ( <div data-test-id="stage-counter" className={styles.stageName}>{vnode.attrs.stageCounter}</div>); } return <div data-test-id="stage-overview-header" class={styles.stageHeaderContainer}> {optionalFlashMessage} <div data-test-id="stage-name-and-operations-container" class={styles.flexBox}> <div class={styles.stageNameContainer}> <div data-test-id="pipeline-name-container"> <div className={styles.stageNameTitle}>Pipeline</div> <div className={styles.stageName}>{vnode.attrs.pipelineName}</div> </div> <Icons.AngleDoubleRight iconOnly={true}/> <div data-test-id="pipeline-instance-container"> <div className={styles.stageNameTitle}>Instance</div> <div className={styles.stageName}>{vnode.attrs.pipelineCounter}</div> </div> <Icons.AngleDoubleRight iconOnly={true}/> <div data-test-id="stage-name-container"> <div className={styles.stageNameTitle}>Stage</div> <div className={styles.stageName}>{vnode.attrs.stageName}</div> </div> <Icons.AngleDoubleRight iconOnly={true}/> <div data-test-id="stage-instance-container"> <div className={styles.stageNameTitle}>Instance</div> {stageCounterView} </div> </div> <div data-test-id="stage-operations-container" class={styles.stageOperationButtonGroup}> <StageTriggerOrCancelButtonWidget stageInstance={vnode.attrs.stageInstance} userSelectedStageCounter={vnode.attrs.userSelectedStageCounter} inProgressStageFromPipeline={vnode.attrs.inProgressStageFromPipeline} shouldSelectLatestStageCounterOnUpdate={vnode.attrs.shouldSelectLatestStageCounterOnUpdate} isLoading={vnode.attrs.isLoading} flashMessage={vnode.attrs.flashMessage} stageInstanceFromDashboard={vnode.attrs.stageInstanceFromDashboard}/> {stageSettings} </div> </div> <div data-test-id="stage-trigger-and-timing-container" class={`${styles.flexBox} ${styles.stageTriggerAndTimingContainer}`}> <div data-test-id="stage-trigger-by-container"> {canceledBy} <div data-test-id="triggered-by-container" class={styles.triggeredByContainer}> Triggered by <span class={styles.triggeredByAndOn}>{vnode.attrs.stageInstance().triggeredBy()}</span> </div> <div data-test-id="triggered-on-container" className={styles.triggeredByContainer}> on <span title={vnode.attrs.stageInstance().triggeredOnServerTime()} className={styles.triggeredByAndOn}>{vnode.attrs.stageInstance().triggeredOn()}</span> Local Time <span className={styles.durationSeparator}>|</span> Duration: <span className={styles.triggeredByAndOn}>{vnode.attrs.stageInstance().stageDuration()}</span> </div> </div> <div data-test-id="stage-details-page-link" class={styles.stageDetailsPageLink}> {dummyContainer} <Link href={stageDetailsPageLink} externalLinkIcon={true} target={"_blank"}>Go to Stage Details Page</Link> </div> </div> </div>; } } interface StageTriggerOrCancelButtonAttrs { stageInstance: Stream<StageInstance>; stageInstanceFromDashboard: any; flashMessage: FlashMessageModelWithTimeout; inProgressStageFromPipeline: Stream<any | undefined>; shouldSelectLatestStageCounterOnUpdate: Stream<boolean>; isLoading: Stream<boolean>; } interface StageTriggerOrCancelButtonState { getResultHandler: (attrs: StageTriggerOrCancelButtonAttrs, shouldIncrement: boolean) => any; isTriggerHover: Stream<boolean>; } class StageTriggerOrCancelButtonWidget extends MithrilComponent<StageTriggerOrCancelButtonAttrs, StageTriggerOrCancelButtonState> { oninit(vnode: m.Vnode<StageTriggerOrCancelButtonAttrs, StageTriggerOrCancelButtonState>) { vnode.state.isTriggerHover = Stream<boolean>(false); vnode.state.getResultHandler = (attrs, shouldIncrement: boolean) => { return (result: any) => { result.do((successResponse: any) => { attrs.flashMessage.setMessage(MessageType.success, JSON.parse(successResponse.body).message); if (shouldIncrement) { vnode.attrs.shouldSelectLatestStageCounterOnUpdate(true); vnode.attrs.isLoading(true); } }, (errorResponse: ErrorResponse) => { attrs.flashMessage.setMessage(MessageType.alert, JSON.parse(errorResponse.body!).message); }); }; }; } view(vnode: m.Vnode<StageTriggerOrCancelButtonAttrs, StageTriggerOrCancelButtonState>): m.Children | void | null { let disabled = !vnode.attrs.stageInstanceFromDashboard.canOperate; let disabledClass = (vnode.state.isTriggerHover() && disabled) ? '' : styles.hidden; if (vnode.attrs.stageInstance().isCompleted()) { let disabledMessage = `You dont have permissions to rerun the stage.`; if (vnode.attrs.inProgressStageFromPipeline()) { disabled = true; disabledClass = (vnode.state.isTriggerHover() && disabled) ? '' : styles.hidden; disabledMessage = `Can not rerun current stage. Stage '${vnode.attrs.inProgressStageFromPipeline().name}' from the pipeline is still in progress.`; } return <div class={styles.cancelOrRerunStageIcon} data-test-id="rerun-stage"> <Icons.Repeat iconOnly={true} disabled={disabled} title="Rerun stage" onmouseover={() => vnode.state.isTriggerHover(true)} onmouseout={() => vnode.state.isTriggerHover(false)} onclick={() => { vnode.attrs.stageInstance().runStage().then(vnode.state.getResultHandler(vnode.attrs, true)); }}/> <span className={`${styles.tooltipMessage} ${disabledClass}`}>{disabledMessage}</span> </div>; } const disabledMessage = `You dont have permissions to cancel the stage.`; return <div class={styles.cancelOrRerunStageIcon} data-test-id="cancel-stage"> <Icons.CancelStage iconOnly={true} disabled={disabled} title="Cancel stage" onmouseover={() => vnode.state.isTriggerHover(true)} onmouseout={() => vnode.state.isTriggerHover(false)} onclick={() => { vnode.attrs.stageInstance().cancelStage().then(vnode.state.getResultHandler(vnode.attrs, false)); }}/> <span className={`${styles.tooltipMessage} ${disabledClass}`}>{disabledMessage}</span> </div>; } }
the_stack
// Change [0]: 2015/06/14 - Marcelo Camargo <https://github.com/haskellcamargo> declare namespace PreludeLS { export function id<A>(x: A): A; export function isType<A>(type: string): (x: A) => boolean; export function isType<A>(type: string, x: A): boolean; export function replicate<A>(n: number): (x: A) => A[]; export function replicate<A>(n: number, x: A): A[]; // List export function each<A>(f: (x: A) => void): (xs: A[]) => A[]; export function each<A>(f: (x: A) => void, xs: A[]): A[]; export function map<A, B>(f: (x: A) => B): (xs: A[]) => B[]; export function map<A, B>(f: (x: A) => B, xs: A[]): B[]; export function compact<A>(xs: A[]): A[]; export function filter<A>(f: (x: A) => boolean): (xs: A[]) => A[]; export function filter<A>(f: (x: A) => boolean, xs: A[]): A[]; export function reject<A>(f: (x: A) => boolean): (xs: A[]) => A[]; export function reject<A>(f: (x: A) => boolean, xs: A[]): A[]; export function partition<A>(f: (x: A) => Boolean): (xs: A[]) => [A[], A[]]; export function partition<A>(f: (x: A) => Boolean, xs: A[]): [A[], A[]]; export function find<A>(f: (x: A) => Boolean): (xs: A[]) => A; export function find<A>(f: (x: A) => Boolean, xs: A[]): A; export function head<A>(xs: A[]): A; export function tail<A>(xs: A[]): A[]; export function last<A>(xs: A[]): A; export function initial<A>(xs: A[]): A[]; export function empty<A>(xs: A[]): boolean; export function reverse<A>(xs: A[]): A[]; export function unique<A>(xs: A[]): A[]; export function uniqueBy<A, B>(f: (x: A) => B): (xs: A[]) => A[]; export function uniqueBy<A, B>(f: (x: A) => B, xs: A[]): A[]; export function fold<A, B>(f: (x: A) => (y: B) => A): (memo: A) => (xs: B[]) => A; export function fold<A, B>(f: (x: A) => (y: B) => A, memo: A): (xs: B[]) => A; export function fold<A, B>(f: (x: A) => (y: B) => A, memo: A, xs: B[]): A; export function foldl<A, B>(f: (x: A) => (y: B) => A): (memo: A) => (xs: B[]) => A; export function foldl<A, B>(f: (x: A) => (y: B) => A, memo: A): (xs: B[]) => A; export function foldl<A, B>(f: (x: A) => (y: B) => A, memo: A, xs: B[]): A; export function fold1<A>(f: (x: A) => (y: A) => A): (xs: A[]) => A; export function fold1<A>(f: (x: A) => (y: A) => A, xs: A[]): A; export function foldl1<A>(f: (x: A) => (y: A) => A): (xs: A[]) => A; export function foldl1<A>(f: (x: A) => (y: A) => A, xs: A[]): A; export function foldr<A, B>(f: (x: A) => (y: B) => B): (memo: B) => (xs: A[]) => B; export function foldr<A, B>(f: (x: A) => (y: B) => B, memo: B): (xs: A[]) => B; export function foldr<A, B>(f: (x: A) => (y: B) => B, memo: B, xs: A[]): B; export function foldr1<A>(f: (x: A) => (y: A) => A): (xs: A[]) => A; export function foldr1<A>(f: (x: A) => (y: A) => A, xs: A[]): A; export function unfoldr<A, B>(f: (x: B) => ([A, B] | void)): (x: B) => A[]; export function unfoldr<A, B>(f: (x: B) => ([A, B] | void), x: B): A[]; export function concat<A>(xss: A[][]): A[]; export function concatMap<A, B>(f: (x: A) => B[]): (xs: A[]) => B[]; export function concatMap<A, B>(f: (x: A) => B[], xs: A[]): B[]; export function flatten(xs: any[]): any[]; export function difference<A>(...xss: A[][]): A[]; export function intersection<A>(...xss: A[][]): A[]; export function union<A>(...xss: A[][]): A[]; export function countBy<A, B>(f: (x: A) => B): (xs: A[]) => any; export function countBy<A, B>(f: (x: A) => B, xs: A[]): any; export function groupBy<A, B>(f: (x: A) => B): (xs: A[]) => any; export function groupBy<A, B>(f: (x: A) => B, xs: A[]): any; export function andList<A>(xs: A[]): boolean; export function orList<A>(xs: A[]): boolean; export function any<A>(f: (x: A) => boolean): (xs: A[]) => boolean; export function any<A>(f: (x: A) => boolean, xs: A[]): boolean; export function all<A>(f: (x: A) => boolean): (xs: A[]) => boolean; export function all<A>(f: (x: A) => boolean, xs: A[]): boolean; export function sort<A>(xs: A[]): A[]; export function sortWith<A>(f: (x: A) => (y: A) => number): (xs: A[]) => A[]; export function sortWith<A>(f: (x: A) => (y: A) => number, xs: A[]): A[]; export function sortBy<A, B>(f: (x: A) => B): (xs: A[]) => A[]; export function sortBy<A, B>(f: (x: A) => B, xs: A[]): A[]; export function sum(xs: number[]): number; export function product(xs: number[]): number; export function mean(xs: number[]): number; export function maximum<A>(xs: A[]): A; export function minimum<A>(xs: A[]): A; export function maximumBy<A, B>(f: (x: A) => B): (xs: A[]) => A; export function maximumBy<A, B>(f: (x: A) => B, xs: A[]): A; export function minimumBy<A, B>(f: (x: A) => B): (xs: A[]) => A; export function minimumBy<A, B>(f: (x: A) => B, xs: A[]): A; export function scan<A, B>(f: (x: A) => (y: B) => A): (memo: A) => (xs: B[]) => A[]; export function scan<A, B>(f: (x: A) => (y: B) => A, memo: A): (xs: B[]) => A[]; export function scan<A, B>(f: (x: A) => (y: B) => A, memo: A, xs: B[]): A[]; export function scanl<A, B>(f: (x: A) => (y: B) => A): (memo: A) => (xs: B[]) => A[]; export function scanl<A, B>(f: (x: A) => (y: B) => A, memo: A): (xs: B[]) => A[]; export function scanl<A, B>(f: (x: A) => (y: B) => A, memo: A, xs: B[]): A[]; export function scan1<A>(f: (x: A) => (y: A) => A): (xs: A[]) => A[]; export function scan1<A>(f: (x: A) => (y: A) => A, xs: A[]): A[]; export function scanl1<A>(f: (x: A) => (y: A) => A): (xs: A[]) => A[]; export function scanl1<A>(f: (x: A) => (y: A) => A, xs: A[]): A[]; export function scanr<A, B>(f: (x: A) => (y: B) => B): (memo: B) => (xs: A[]) => B[]; export function scanr<A, B>(f: (x: A) => (y: B) => B, memo: B): (xs: A[]) => B[]; export function scanr<A, B>(f: (x: A) => (y: B) => B, memo: B, xs: A[]): B[]; export function scanr1<A>(f: (x: A) => (y: A) => A): (xs: A[]) => A[]; export function scanr1<A>(f: (x: A) => (y: A) => A, xs: A[]): A[]; export function slice<A>(x: number): (y: number) => (xs: A[]) => A[]; export function slice<A>(x: number, y: number): (xs: A[]) => A[]; export function slice<A>(x: number, y: number, xs: A[]): A[]; export function take<A>(n: number): (xs: A[]) => A[]; export function take<A>(n: number, xs: A[]): A[]; export function drop<A>(n: number): (xs: A[]) => A[]; export function drop<A>(n: number, xs: A[]): A[]; export function splitAt<A>(n: number): (xs: A[]) => [A[], A[]]; export function splitAt<A>(n: number, xs: A[]): [A[], A[]]; export function takeWhile<A>(p: (x: A) => boolean): (xs: A[]) => A[]; export function takeWhile<A>(p: (x: A) => boolean, xs: A[]): A[]; export function dropWhile<A>(p: (x: A) => boolean): (xs: A[]) => A[]; export function dropWhile<A>(p: (x: A) => boolean, xs: A[]): A[]; export function span<A>(p: (x: A) => boolean): (xs: A[]) => [A[], A[]]; export function span<A>(p: (x: A) => boolean, xs: A[]): [A[], A[]]; export function breakList<A>(p: (x: A) => boolean): (xs: A[]) => [A[], A[]]; export function breakList<A>(p: (x: A) => boolean, xs: A[]): [A[], A[]]; export function zip<A, B>(xs: A[]): (ys: B[]) => [A, B][]; export function zip<A, B>(xs: A[], ys: B[]): [A, B][]; export function zipWith<A, B, C>(f: (x: A) => (y: B) => C): (xs: A[]) => (ys: B[]) => C[]; export function zipWith<A, B, C>(f: (x: A) => (y: B) => C, xs: A[]): (ys: B[]) => C[]; export function zipWith<A, B, C>(f: (x: A) => (y: B) => C, xs: A[], ys: B[]): C[]; export function zipAll<A>(...xss: A[][]): A[][]; export function zipAllWith<A, B>(f: (...xs: A[]) => B, ...xss: A[][]): B[]; export function at<A>(n: number): (xs: A[]) => A; export function at<A>(n: number, xs: A[]): A; export function elemIndex<A>(x: A): (xs: A[]) => number; export function elemIndex<A>(x: A, xs: A[]): number; export function elemIndices<A>(x: A): (xs: A[]) => number[]; export function elemIndices<A>(x: A, xs: A[]): number[]; export function findIndex<A>(f: (x: A) => boolean): (xs: A[]) => number; export function findIndex<A>(f: (x: A) => boolean, xs: A[]): number; export function findIndices<A>(f: (x: A) => boolean): (xs: A[]) => number[]; export function findIndices<A>(f: (x: A) => boolean, xs: A[]): number[]; // Obj export function keys<A>(object: { [key: string]: A }): string[]; export function keys<A>(object: { [key: number]: A }): number[]; export function values<A>(object: { [key: string]: A }): A[]; export function values<A>(object: { [key: number]: A }): A[]; export function pairsToObj<A>(object: [string, A][]): { [key: string]: A }; export function pairsToObj<A>(object: [number, A][]): { [key: number]: A }; export function objToPairs<A>(object: { [key: string]: A }): [string, A][]; export function objToPairs<A>(object: { [key: number]: A }): [number, A][]; export function listsToObj<A>(keys: string[]): (values: A[]) => { [key: string]: A }; export function listsToObj<A>(keys: string[], values: A[]): { [key: string]: A }; export function listsToObj<A>(keys: number[]): (values: A[]) => { [key: number]: A }; export function listsToObj<A>(keys: number[], values: A[]): { [key: number]: A }; export function objToLists<A>(object: { [key: string]: A }): [string[], A[]]; export function objToLists<A>(object: { [key: number]: A }): [number[], A[]]; export function empty<A>(object: any): boolean; export function each<A>(f: (x: A) => void): (object: { [key: string]: A }) => { [key: string]: A }; export function each<A>(f: (x: A) => void, object: { [key: string]: A }): { [key: string]: A }; export function each<A>(f: (x: A) => void): (object: { [key: number]: A }) => { [key: number]: A }; export function each<A>(f: (x: A) => void, object: { [key: number]: A }): { [key: number]: A }; export function map<A, B>(f: (x: A) => B): (object: { [key: string]: A }) => { [key: string]: B }; export function map<A, B>(f: (x: A) => B, object: { [key: string]: A }): { [key: string]: B }; export function map<A, B>(f: (x: A) => B): (object: { [key: number]: A }) => { [key: number]: B }; export function map<A, B>(f: (x: A) => B, object: { [key: number]: A }): { [key: number]: B }; export function compact<A>(object: { [key: string]: A }): { [key: string]: A }; export function compact<A>(object: { [key: number]: A }): { [key: number]: A }; export function filter<A>(f: (x: A) => boolean): (object: { [key: string]: A }) => { [key: string]: A }; export function filter<A>(f: (x: A) => boolean, object: { [key: string]: A }): { [key: string]: A }; export function filter<A>(f: (x: A) => boolean): (object: { [key: number]: A }) => { [key: number]: A }; export function filter<A>(f: (x: A) => boolean, object: { [key: number]: A }): { [key: number]: A }; export function reject<A>(f: (x: A) => boolean): (object: { [key: string]: A }) => { [key: string]: A }; export function reject<A>(f: (x: A) => boolean, object: { [key: string]: A }): { [key: string]: A }; export function reject<A>(f: (x: A) => boolean): (object: { [key: number]: A }) => { [key: number]: A }; export function reject<A>(f: (x: A) => boolean, object: { [key: number]: A }): { [key: number]: A }; export function partition<A>(f: (x: A) => boolean): (object: { [key: string]: A }) => [{ [key: string]: A }, { [key: string]: A }]; export function partition<A>(f: (x: A) => boolean, object: { [key: string]: A }): [{ [key: string]: A }, { [key: string]: A }]; export function partition<A>(f: (x: A) => boolean): (object: { [key: number]: A }) => [{ [key: number]: A }, { [key: number]: A }]; export function partition<A>(f: (x: A) => boolean, object: { [key: number]: A }): [{ [key: number]: A }, { [key: number]: A }]; export function find<A>(f: (x: A) => boolean): (object: { [key: string]: A }) => A; export function find<A>(f: (x: A) => boolean, object: { [key: string]: A }): A; export function find<A>(f: (x: A) => boolean): (object: { [key: number]: A }) => A; export function find<A>(f: (x: A) => boolean, object: { [key: number]: A }): A; export module Obj { export function empty<A>(object: any): boolean; export function each<A>(f: (x: A) => void): (object: { [key: string]: A }) => { [key: string]: A }; export function each<A>(f: (x: A) => void, object: { [key: string]: A }): { [key: string]: A }; export function each<A>(f: (x: A) => void): (object: { [key: number]: A }) => { [key: number]: A }; export function each<A>(f: (x: A) => void, object: { [key: number]: A }): { [key: number]: A }; export function map<A, B>(f: (x: A) => B): (object: { [key: string]: A }) => { [key: string]: B }; export function map<A, B>(f: (x: A) => B, object: { [key: string]: A }): { [key: string]: B }; export function map<A, B>(f: (x: A) => B): (object: { [key: number]: A }) => { [key: number]: B }; export function map<A, B>(f: (x: A) => B, object: { [key: number]: A }): { [key: number]: B }; export function compact<A>(object: { [key: string]: A }): { [key: string]: A }; export function compact<A>(object: { [key: number]: A }): { [key: number]: A }; export function filter<A>(f: (x: A) => boolean): (object: { [key: string]: A }) => { [key: string]: A }; export function filter<A>(f: (x: A) => boolean, object: { [key: string]: A }): { [key: string]: A }; export function filter<A>(f: (x: A) => boolean): (object: { [key: number]: A }) => { [key: number]: A }; export function filter<A>(f: (x: A) => boolean, object: { [key: number]: A }): { [key: number]: A }; export function reject<A>(f: (x: A) => boolean): (object: { [key: string]: A }) => { [key: string]: A }; export function reject<A>(f: (x: A) => boolean, object: { [key: string]: A }): { [key: string]: A }; export function reject<A>(f: (x: A) => boolean): (object: { [key: number]: A }) => { [key: number]: A }; export function reject<A>(f: (x: A) => boolean, object: { [key: number]: A }): { [key: number]: A }; export function partition<A>(f: (x: A) => boolean): (object: { [key: string]: A }) => [{ [key: string]: A }, { [key: string]: A }]; export function partition<A>(f: (x: A) => boolean, object: { [key: string]: A }): [{ [key: string]: A }, { [key: string]: A }]; export function partition<A>(f: (x: A) => boolean): (object: { [key: number]: A }) => [{ [key: number]: A }, { [key: number]: A }]; export function partition<A>(f: (x: A) => boolean, object: { [key: number]: A }): [{ [key: number]: A }, { [key: number]: A }]; export function find<A>(f: (x: A) => boolean): (object: { [key: string]: A }) => A; export function find<A>(f: (x: A) => boolean, object: { [key: string]: A }): A; export function find<A>(f: (x: A) => boolean): (object: { [key: number]: A }) => A; export function find<A>(f: (x: A) => boolean, object: { [key: number]: A }): A; } // Str export function split(separator: string): (str: string) => string[]; export function split(separator: string, str: string): string[]; export function join(separator: string): (xs: string[]) => string; export function join(separator: string, xs: string[]): string; export function lines(str: string): string[]; export function unlines(xs: string[]): string; export function words(str: string): string[]; export function unwords(xs: string[]): string; export function chars(str: string): string[]; export function unchars(xs: string[]): string; export function repeat(n: number): (str: string) => string; export function repeat(n: number, str: string): string; export function capitalize(str: string): string; export function camelize(str: string): string; export function dasherize(str: string): string; export function empty(str: string): boolean; export function reverse(str: string): string; export function slice(x: number): (y: number) => (str: string) => string; export function slice(x: number, y: number): (str: string) => string; export function slice(x: number, y: number, str: string): string; export function take(n: number): (str: string) => string; export function take(n: number, str: string): string; export function drop(n: number): (str: string) => string; export function drop(n: number, str: string): string; export function splitAt(n: number): (str: string) => [string, string]; export function splitAt(n: number, str: string): [string, string]; export function takeWhile(f: (str: string) => boolean): (str: string) => string; export function takeWhile(f: (str: string) => boolean, str: string): string; export function dropWhile(f: (str: string) => boolean): (str: string) => string; export function dropWhile(f: (str: string) => boolean, str: string): string; export function span(f: (str: string) => boolean): (str: string) => [string, string]; export function span(f: (str: string) => boolean, str: string): [string, string]; export function breakStr(f: (str: string) => boolean): (str: string) => [string, string]; export function breakStr(f: (str: string) => boolean, str: string): [string, string]; export module Str { export function empty(str: string): boolean; export function reverse(str: string): string; export function slice(x: number): (y: number) => (str: string) => string; export function slice(x: number, y: number): (str: string) => string; export function slice(x: number, y: number, str: string): string; export function take(n: number): (str: string) => string; export function take(n: number, str: string): string; export function drop(n: number): (str: string) => string; export function drop(n: number, str: string): string; export function splitAt(n: number): (str: string) => [string, string]; export function splitAt(n: number, str: string): [string, string]; export function takeWhile(f: (str: string) => boolean): (str: string) => string; export function takeWhile(f: (str: string) => boolean, str: string): string; export function dropWhile(f: (str: string) => boolean): (str: string) => string; export function dropWhile(f: (str: string) => boolean, str: string): string; export function span(f: (str: string) => boolean): (str: string) => [string, string]; export function span(f: (str: string) => boolean, str: string): [string, string]; export function breakStr(f: (str: string) => boolean): (str: string) => [string, string]; export function breakStr(f: (str: string) => boolean, str: string): [string, string]; } // Func export function apply<A, B>(f: (...args: A[]) => B): (args: A[]) => B; export function apply<A, B>(f: (...args: A[]) => B, args: A[]): B; export function curry(f: Function): Function; export function flip<A, B, C>(f: (x: A) => (y: B) => C): (y: B) => (x: A) => C; export function flip<A, B, C>(f: (x: A) => (y: B) => C, y: B): (x: A) => C; export function flip<A, B, C>(f: (x: A) => (y: B) => C, y: B, x: A): C; export function fix(f: Function): Function; export function over<A, B, C>(f: (x: B) => (y: B) => C | ((x: B, y: B) => C), g: (x: A) => B, x: A, y: A): C; export function over<A, B, C>(f: (x: B, y: B) => C | ((x: B) => (y: B) => C), g: (x: A) => B, x: A): (y: A) => C; export function over<A, B, C>(f: (x: B, y: B) => C, g: (x: A) => B): (x: A, y: A) => C; export function over<A, B, C>(f: (x: B) => (y: B) => C, g: (x: A) => B): (x: A) => (y: A) => C; export function over<A, B, C>(f: (x: B, y: B) => C): (g: (x: A) => B) => (x: A, y: A) => C; export function over<A, B, C>(f: (x: B) => (y: B) => C): (g: (x: A) => B) => (x: A) => (y: A) => C; // Num export function max<Comparable>(x: Comparable): (y: Comparable) => Comparable; export function max<Comparable>(x: Comparable, y: Comparable): Comparable; export function min<Comparable>(x: Comparable): (y: Comparable) => Comparable; export function min<Comparable>(x: Comparable, y: Comparable): Comparable; export function negate(x: number): number; export function abs(x: number): number; export function signum(x: number): number; export function quot(x: number): (y: number) => number; export function quot(x: number, y: number): number; export function rem(x: number): (y: number) => number; export function rem(x: number, y: number): number; export function div(x: number): (y: number) => number; export function div(x: number, y: number): number; export function mod(x: number): (y: number) => number; export function mod(x: number, y: number): number; export function recip(x: number): number; export var pi: number; export var tau: number; export function exp(x: number): number; export function sqrt(x: number): number; export function ln(x: number): number; export function pow(x: number): (y: number) => number; export function pow(x: number, y: number): number; export function sin(x: number): number; export function cos(x: number): number; export function tan(x: number): number; export function asin(x: number): number; export function acos(x: number): number; export function atan(x: number): number; export function atan2(x: number, y: number): number; export function truncate(x: number): number; export function round(x: number): number; export function ceiling(x: number): number; export function floor(x: number): number; export function isItNaN(x: number): boolean; export function even(x: number): boolean; export function odd(x: number): boolean; export function gcd(x: number): (y: number) => number; export function gcd(x: number, y: number): number; export function lcm(x: number): (y: number) => number; export function lcm(x: number, y: number): number; } export = PreludeLS;
the_stack
import React from "react"; import { Global } from "@emotion/core"; import RView from "emotion-native-media-query"; import { Post } from "helpers/wpapi"; import { FONTS } from "helpers/constants"; import { SectionStyle } from "components/Section"; import { Article, ArticleHeader } from "components/Article"; import LoadingView from "components/Loading"; import WPHead from "components/webHelpers/WPHead"; import WPFooter from "components/webHelpers/WPFooter"; import styled from "@emotion/styled"; import { AuthorsTextWithLink } from "./AuthorView"; import AuthorBox from "./AuthorBox"; import { CategoryLink } from "./CategoryLink"; import { DateWithAbbr } from "./DateView"; import HumorGlobal from "./HumorGlobal"; import DataVizGlobal from "./DataVizGlobal"; import FooterDonationBanner from "components/PostFooterBox"; import css from "@emotion/css"; import Size1ContentViewStyles, { centerOuterContentStyle, centerContentStyle, } from "./Size1ContentViewStyles"; // PostTitle is headline if post is an article const PostTitle = styled.h1({ ...centerContentStyle, ...FONTS.ARTICLE_TITLE, textAlign: "center", fontSize: "2.3rem", lineHeight: "1.4", }); // PostSubtitle is subheadline if post is an article const PostSubtitle = styled.h2({ ...centerContentStyle, ...FONTS.ARTICLE_TITLE, textAlign: "center", fontSize: "1.2rem", lineHeight: "1.6", color: "gray", }); // e.g. "By Firstname Lastname on July 25, 2020" const Byline = styled.p({ ...FONTS.AUXILIARY, fontWeight: "bold", textTransform: "none", marginTop: "1em", }); // Describes requirement of various properties of specific types // https://www.typescriptlang.org/docs/handbook/interfaces.html interface ContentViewProps { post: Post; } // Component containing body of post and other relevant information const ContentView: React.ElementType<ContentViewProps> = ({ post, }: ContentViewProps) => { if (!post) { return <LoadingView />; } const { id: postId, postTitle, postSubtitle, tagsInput, thumbnailInfo, tsdAuthors, tsdCategories = [], // e.g. News tsdPrimaryCategory, // for articles with more than one, selected in WordPress tsdUrlParameters, postContent, postDateGmt, postType, commentStatus, // determines whether Disqus appears below article guid, } = post; const { urls: { full: thumbnailUrl = null } = {}, caption: thumbnailCaption = null, alt: thumbnailAlt = thumbnailCaption, } = thumbnailInfo || {}; const isPost = postType === "post"; const isHumor = // Need to know this so we can put "Humor by" in byline and do humor styling tsdCategories && tsdCategories.find(category => category.slug === "humor"); let isDataViz = false; // Also need to know whether to apply special styling for data coverage if ( tsdCategories && tsdCategories.find(category => category.slug === "94305") ) { isDataViz = true; } let mainCategory = tsdPrimaryCategory && tsdPrimaryCategory.name; for (let i = 0; i < tsdCategories.length; i++) { if ( tsdCategories[i].name === "News" || tsdCategories[i].name === "Sports" || tsdCategories[i].name === "Opinions" || tsdCategories[i].name === "Arts & Life" || tsdCategories[i].name === "The Grind" || tsdCategories[i].name === "Humor" || tsdCategories[i].name === "Cartoons" || tsdCategories[i].name === "Equity Project" || tsdCategories[i].name === "Data" || tsdCategories[i].name === "Podcasts" || tsdCategories[i].name === "Video" ) { mainCategory = tsdCategories[i].name; break; } } return ( <SectionStyle> <WPHead base={post} /> {isHumor && <HumorGlobal />} {isDataViz && <DataVizGlobal />} <Article> <ArticleHeader> {isPost && ( <div css={{ ...centerContentStyle, textAlign: "center", }} > <CategoryLink category={tsdPrimaryCategory} style={{ fontSize: 20, }} /> </div> )} <PostTitle>{postTitle}</PostTitle> {postSubtitle ? ( <PostSubtitle>{postSubtitle}</PostSubtitle> ) : ( undefined )} </ArticleHeader> <Global styles={Size1ContentViewStyles} /> <RView WebTag="main" id="main-article-content" css={css` @media print { a { text-decoration: none !important; border-bottom: none !important; color: #2e2d29; } } `} > {thumbnailUrl ? ( <figure id="featured-image" css={css` @media print { display: none; } `} > <img src={thumbnailUrl} alt={thumbnailAlt} /> {thumbnailCaption ? ( <figcaption style={{ marginBottom: 0 }}> {thumbnailCaption} </figcaption> ) : ( undefined )} </figure> ) : ( undefined )} {isPost && ( <Byline> <span>{isHumor ? "Humor by" : "By"}</span>{" "} <AuthorsTextWithLink authors={tsdAuthors} aStyle={{ textDecoration: "underline", }} />{" "} <span> <DateWithAbbr post={post} format="on MMMM D, YYYY" /> </span> </Byline> )} <div id="ad-auris-tracker" dangerouslySetInnerHTML={{ __html: `<iframe style="width: 100%; height: 175px; border: none; display: none" data-org=2f0700ad80cb3d0ced1b7fdb6b0eb9e2.5163f1 allowfullscreen="false" allowtransparency frameborder="0" id="ad-auris-iframe" scrolling="no"></iframe>`, }} /> <div id="main-article-text" /> {/* TODO: UNKNOWN WHY THIS IS NECESSARY FOR SOME POSTS TO SHOW UP: E.G. https://www.stanforddaily.com/2019/11/20/the-disappearance-of-financial-aid-how-stanford-consumes-outside-scholarships-when-need-based-aid-doesnt-fulfill-student-needs/ */} <div id="main-article-text2" // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: postContent.replace( /Contact(.)*(')*(‘*)at(’)*(')*( )*stanford.edu(.)*/i, "", ), }} /> </RView> {isPost && ( // For article/content posts, we want donation box and author box at bottom <footer css={centerOuterContentStyle} style={{ marginTop: 30 }}> <FooterDonationBanner currentPageUrl={"https://www.stanforddaily.com"} /> {tsdAuthors.map(author => ( <AuthorBox key={author.id} author={author} /> ))} </footer> )} </Article> {commentStatus === "open" && ( <div css={css` @media print { display: none; } `} > <div css={{ ...centerContentStyle }}> {/* We have to embed disqus this way (and not through disqus-react) because disqus-react requires Next JS's javascript code to be running -- and we had to turn off the Next JS javascript code on article pages in order to fix some integration issues with Ezoic. */} <div id="disqus_thread"></div> <div dangerouslySetInnerHTML={{ __html: ` <script id="tsd-disqus-data" type="application/json">${JSON.stringify( { url: guid, identifier: `${postId} ${guid}`, // From `dsq_identifier_for_post` in Disqus WordPress plugin }, )}</script> <script> var disqus_config = function () { var disqus_data = JSON.parse(document.getElementById("tsd-disqus-data").innerHTML); this.page.url = disqus_data.url; this.page.identifier = disqus_data.identifier; }; (function() { var d = document, s = d.createElement('script'); // IMPORTANT: Replace EXAMPLE with your forum shortname! s.src = 'https://stanforddaily.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> `, }} /> <div dangerouslySetInnerHTML={{ __html: `<script type="application/ld+json">${JSON.stringify({ "@context": "http://schema.org", "@type": isPost ? "NewsArticle" : "WebPage", headline: postTitle, url: isPost ? `https://stanforddaily.com/${tsdUrlParameters.year}/${tsdUrlParameters.month}/${tsdUrlParameters.day}/${tsdUrlParameters.slug}` : `https://stanforddaily.com/${tsdUrlParameters.slug}`, thumbnailUrl: (thumbnailInfo && thumbnailInfo.urls && thumbnailInfo.urls.full) || "https://stanforddaily.com/static/cardinal-red-daily-s-logo.png", datePublished: postDateGmt, articleSection: mainCategory, creator: tsdAuthors.map(author => author.displayName), keywords: tagsInput.concat( tsdCategories .filter( category => category.name !== tsdPrimaryCategory.name, ) .map(category => category.name), ), })}</script>`, }} /> </div> </div> )} {/* Parse.ly analytics tracking */} <script id="parsely-cfg" src="//cdn.parsely.com/keys/stanforddaily.com/p.js" /> {/* Ad Auris Tracker */} <script src="https://cdn.jsdelivr.net/npm/ad-auris-iframe-distribution@latest/script.js" /> <WPFooter base={post} /> </SectionStyle> ); }; export default ContentView;
the_stack
import { b2_epsilon, b2_maxFloat, b2_linearSlop, b2_polygonRadius } from "../common/b2_settings.js"; import { b2Vec2, b2Rot, b2Transform, XY } from "../common/b2_math.js"; import { b2AABB, b2RayCastInput, b2RayCastOutput } from "./b2_collision.js"; import { b2DistanceProxy } from "./b2_distance.js"; import { b2MassData } from "./b2_shape.js"; import { b2Shape, b2ShapeType } from "./b2_shape.js"; /// A solid convex polygon. It is assumed that the interior of the polygon is to /// the left of each edge. /// In most cases you should not need many vertices for a convex polygon. export class b2PolygonShape extends b2Shape { public readonly m_centroid: b2Vec2 = new b2Vec2(0, 0); public m_vertices: b2Vec2[] = []; public m_normals: b2Vec2[] = []; public m_count: number = 0; constructor() { super(b2ShapeType.e_polygonShape, b2_polygonRadius); } /// Implement b2Shape. public Clone(): b2PolygonShape { return new b2PolygonShape().Copy(this); } public override Copy(other: b2PolygonShape): this { super.Copy(other); // DEBUG: b2Assert(other instanceof b2PolygonShape); this.m_centroid.Copy(other.m_centroid); this.m_count = other.m_count; this.m_vertices = b2Vec2.MakeArray(this.m_count); this.m_normals = b2Vec2.MakeArray(this.m_count); for (let i: number = 0; i < this.m_count; ++i) { this.m_vertices[i].Copy(other.m_vertices[i]); this.m_normals[i].Copy(other.m_normals[i]); } return this; } /// @see b2Shape::GetChildCount public GetChildCount(): number { return 1; } /// Create a convex hull from the given array of points. /// @warning the points may be re-ordered, even if they form a convex polygon /// @warning collinear points are handled but not removed. Collinear points /// may lead to poor stacking behavior. private static Set_s_r = new b2Vec2(); private static Set_s_v = new b2Vec2(); public Set(vertices: XY[]): b2PolygonShape; public Set(vertices: XY[], count: number): b2PolygonShape; public Set(vertices: number[]): b2PolygonShape; public Set(...args: any[]): b2PolygonShape { if (typeof args[0][0] === "number") { const vertices: number[] = args[0]; if (vertices.length % 2 !== 0) { throw new Error(); } return this._Set((index: number): XY => ({ x: vertices[index * 2], y: vertices[index * 2 + 1] }), vertices.length / 2); } else { const vertices: XY[] = args[0]; const count: number = args[1] || vertices.length; return this._Set((index: number): XY => vertices[index], count); } } public _Set(vertices: (index: number) => XY, count: number): b2PolygonShape { // DEBUG: b2Assert(3 <= count); if (count < 3) { return this.SetAsBox(1, 1); } let n: number = count; // Perform welding and copy vertices into local buffer. const ps: XY[] = []; for (let i = 0; i < n; ++i) { const /*b2Vec2*/ v = vertices(i); let /*bool*/ unique = true; for (let /*int32*/ j = 0; j < ps.length; ++j) { if (b2Vec2.DistanceSquaredVV(v, ps[j]) < ((0.5 * b2_linearSlop) * (0.5 * b2_linearSlop))) { unique = false; break; } } if (unique) { ps.push(v); } } n = ps.length; if (n < 3) { // Polygon is degenerate. // DEBUG: b2Assert(false); return this.SetAsBox(1.0, 1.0); } // Create the convex hull using the Gift wrapping algorithm // http://en.wikipedia.org/wiki/Gift_wrapping_algorithm // Find the right most point on the hull let i0: number = 0; let x0: number = ps[0].x; for (let i: number = 1; i < n; ++i) { const x: number = ps[i].x; if (x > x0 || (x === x0 && ps[i].y < ps[i0].y)) { i0 = i; x0 = x; } } const hull: number[] = []; let m: number = 0; let ih: number = i0; for (; ;) { hull[m] = ih; let ie: number = 0; for (let j: number = 1; j < n; ++j) { if (ie === ih) { ie = j; continue; } const r: b2Vec2 = b2Vec2.SubVV(ps[ie], ps[hull[m]], b2PolygonShape.Set_s_r); const v: b2Vec2 = b2Vec2.SubVV(ps[j], ps[hull[m]], b2PolygonShape.Set_s_v); const c: number = b2Vec2.CrossVV(r, v); if (c < 0) { ie = j; } // Collinearity check if (c === 0 && v.LengthSquared() > r.LengthSquared()) { ie = j; } } ++m; ih = ie; if (ie === i0) { break; } } this.m_count = m; this.m_vertices = b2Vec2.MakeArray(this.m_count); this.m_normals = b2Vec2.MakeArray(this.m_count); // Copy vertices. for (let i: number = 0; i < m; ++i) { this.m_vertices[i].Copy(ps[hull[i]]); } // Compute normals. Ensure the edges have non-zero length. for (let i: number = 0; i < m; ++i) { const vertexi1: b2Vec2 = this.m_vertices[i]; const vertexi2: b2Vec2 = this.m_vertices[(i + 1) % m]; const edge: b2Vec2 = b2Vec2.SubVV(vertexi2, vertexi1, b2Vec2.s_t0); // edge uses s_t0 // DEBUG: b2Assert(edge.LengthSquared() > b2_epsilon_sq); b2Vec2.CrossVOne(edge, this.m_normals[i]).SelfNormalize(); } // Compute the polygon centroid. b2PolygonShape.ComputeCentroid(this.m_vertices, m, this.m_centroid); return this; } /// Build vertices to represent an axis-aligned box or an oriented box. /// @param hx the half-width. /// @param hy the half-height. /// @param center the center of the box in local coordinates. /// @param angle the rotation of the box in local coordinates. public SetAsBox(hx: number, hy: number, center?: XY, angle: number = 0): b2PolygonShape { this.m_count = 4; this.m_vertices = b2Vec2.MakeArray(this.m_count); this.m_normals = b2Vec2.MakeArray(this.m_count); this.m_vertices[0].Set((-hx), (-hy)); this.m_vertices[1].Set(hx, (-hy)); this.m_vertices[2].Set(hx, hy); this.m_vertices[3].Set((-hx), hy); this.m_normals[0].Set(0, (-1)); this.m_normals[1].Set(1, 0); this.m_normals[2].Set(0, 1); this.m_normals[3].Set((-1), 0); this.m_centroid.SetZero(); if (center) { this.m_centroid.Copy(center); const xf: b2Transform = new b2Transform(); xf.SetPosition(center); xf.SetRotationAngle(angle); // Transform vertices and normals. for (let i: number = 0; i < this.m_count; ++i) { b2Transform.MulXV(xf, this.m_vertices[i], this.m_vertices[i]); b2Rot.MulRV(xf.q, this.m_normals[i], this.m_normals[i]); } } return this; } /// @see b2Shape::TestPoint private static TestPoint_s_pLocal = new b2Vec2(); public TestPoint(xf: b2Transform, p: XY): boolean { const pLocal: b2Vec2 = b2Transform.MulTXV(xf, p, b2PolygonShape.TestPoint_s_pLocal); for (let i: number = 0; i < this.m_count; ++i) { const dot: number = b2Vec2.DotVV(this.m_normals[i], b2Vec2.SubVV(pLocal, this.m_vertices[i], b2Vec2.s_t0)); if (dot > 0) { return false; } } return true; } // #if B2_ENABLE_PARTICLE /// @see b2Shape::ComputeDistance private static ComputeDistance_s_pLocal = new b2Vec2(); private static ComputeDistance_s_normalForMaxDistance = new b2Vec2(); private static ComputeDistance_s_minDistance = new b2Vec2(); private static ComputeDistance_s_distance = new b2Vec2(); public ComputeDistance(xf: b2Transform, p: b2Vec2, normal: b2Vec2, childIndex: number): number { const pLocal = b2Transform.MulTXV(xf, p, b2PolygonShape.ComputeDistance_s_pLocal); let maxDistance = -b2_maxFloat; const normalForMaxDistance = b2PolygonShape.ComputeDistance_s_normalForMaxDistance.Copy(pLocal); for (let i = 0; i < this.m_count; ++i) { const dot = b2Vec2.DotVV(this.m_normals[i], b2Vec2.SubVV(pLocal, this.m_vertices[i], b2Vec2.s_t0)); if (dot > maxDistance) { maxDistance = dot; normalForMaxDistance.Copy(this.m_normals[i]); } } if (maxDistance > 0) { const minDistance = b2PolygonShape.ComputeDistance_s_minDistance.Copy(normalForMaxDistance); let minDistance2 = maxDistance * maxDistance; for (let i = 0; i < this.m_count; ++i) { const distance = b2Vec2.SubVV(pLocal, this.m_vertices[i], b2PolygonShape.ComputeDistance_s_distance); const distance2 = distance.LengthSquared(); if (minDistance2 > distance2) { minDistance.Copy(distance); minDistance2 = distance2; } } b2Rot.MulRV(xf.q, minDistance, normal); normal.Normalize(); return Math.sqrt(minDistance2); } else { b2Rot.MulRV(xf.q, normalForMaxDistance, normal); return maxDistance; } } // #endif /// Implement b2Shape. /// @note because the polygon is solid, rays that start inside do not hit because the normal is /// not defined. private static RayCast_s_p1 = new b2Vec2(); private static RayCast_s_p2 = new b2Vec2(); private static RayCast_s_d = new b2Vec2(); public RayCast(output: b2RayCastOutput, input: b2RayCastInput, xf: b2Transform, childIndex: number): boolean { // Put the ray into the polygon's frame of reference. const p1: b2Vec2 = b2Transform.MulTXV(xf, input.p1, b2PolygonShape.RayCast_s_p1); const p2: b2Vec2 = b2Transform.MulTXV(xf, input.p2, b2PolygonShape.RayCast_s_p2); const d: b2Vec2 = b2Vec2.SubVV(p2, p1, b2PolygonShape.RayCast_s_d); let lower: number = 0, upper = input.maxFraction; let index: number = -1; for (let i: number = 0; i < this.m_count; ++i) { // p = p1 + a * d // dot(normal, p - v) = 0 // dot(normal, p1 - v) + a * dot(normal, d) = 0 const numerator: number = b2Vec2.DotVV(this.m_normals[i], b2Vec2.SubVV(this.m_vertices[i], p1, b2Vec2.s_t0)); const denominator: number = b2Vec2.DotVV(this.m_normals[i], d); if (denominator === 0) { if (numerator < 0) { return false; } } else { // Note: we want this predicate without division: // lower < numerator / denominator, where denominator < 0 // Since denominator < 0, we have to flip the inequality: // lower < numerator / denominator <==> denominator * lower > numerator. if (denominator < 0 && numerator < lower * denominator) { // Increase lower. // The segment enters this half-space. lower = numerator / denominator; index = i; } else if (denominator > 0 && numerator < upper * denominator) { // Decrease upper. // The segment exits this half-space. upper = numerator / denominator; } } // The use of epsilon here causes the assert on lower to trip // in some cases. Apparently the use of epsilon was to make edge // shapes work, but now those are handled separately. // if (upper < lower - b2_epsilon) if (upper < lower) { return false; } } // DEBUG: b2Assert(0 <= lower && lower <= input.maxFraction); if (index >= 0) { output.fraction = lower; b2Rot.MulRV(xf.q, this.m_normals[index], output.normal); return true; } return false; } /// @see b2Shape::ComputeAABB private static ComputeAABB_s_v = new b2Vec2(); public ComputeAABB(aabb: b2AABB, xf: b2Transform, childIndex: number): void { const lower: b2Vec2 = b2Transform.MulXV(xf, this.m_vertices[0], aabb.lowerBound); const upper: b2Vec2 = aabb.upperBound.Copy(lower); for (let i: number = 0; i < this.m_count; ++i) { const v: b2Vec2 = b2Transform.MulXV(xf, this.m_vertices[i], b2PolygonShape.ComputeAABB_s_v); b2Vec2.MinV(v, lower, lower); b2Vec2.MaxV(v, upper, upper); } const r: number = this.m_radius; lower.SelfSubXY(r, r); upper.SelfAddXY(r, r); } /// @see b2Shape::ComputeMass private static ComputeMass_s_center = new b2Vec2(); private static ComputeMass_s_s = new b2Vec2(); private static ComputeMass_s_e1 = new b2Vec2(); private static ComputeMass_s_e2 = new b2Vec2(); public ComputeMass(massData: b2MassData, density: number): void { // Polygon mass, centroid, and inertia. // Let rho be the polygon density in mass per unit area. // Then: // mass = rho * int(dA) // centroid.x = (1/mass) * rho * int(x * dA) // centroid.y = (1/mass) * rho * int(y * dA) // I = rho * int((x*x + y*y) * dA) // // We can compute these integrals by summing all the integrals // for each triangle of the polygon. To evaluate the integral // for a single triangle, we make a change of variables to // the (u,v) coordinates of the triangle: // x = x0 + e1x * u + e2x * v // y = y0 + e1y * u + e2y * v // where 0 <= u && 0 <= v && u + v <= 1. // // We integrate u from [0,1-v] and then v from [0,1]. // We also need to use the Jacobian of the transformation: // D = cross(e1, e2) // // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) // // The rest of the derivation is handled by computer algebra. // DEBUG: b2Assert(this.m_count >= 3); const center: b2Vec2 = b2PolygonShape.ComputeMass_s_center.SetZero(); let area: number = 0; let I: number = 0; // Get a reference point for forming triangles. // Use the first vertex to reduce round-off errors. const s: b2Vec2 = b2PolygonShape.ComputeMass_s_s.Copy(this.m_vertices[0]); const k_inv3: number = 1 / 3; for (let i: number = 0; i < this.m_count; ++i) { // Triangle vertices. const e1: b2Vec2 = b2Vec2.SubVV(this.m_vertices[i], s, b2PolygonShape.ComputeMass_s_e1); const e2: b2Vec2 = b2Vec2.SubVV(this.m_vertices[(i + 1) % this.m_count], s, b2PolygonShape.ComputeMass_s_e2); const D: number = b2Vec2.CrossVV(e1, e2); const triangleArea: number = 0.5 * D; area += triangleArea; // Area weighted centroid center.SelfAdd(b2Vec2.MulSV(triangleArea * k_inv3, b2Vec2.AddVV(e1, e2, b2Vec2.s_t0), b2Vec2.s_t1)); const ex1: number = e1.x; const ey1: number = e1.y; const ex2: number = e2.x; const ey2: number = e2.y; const intx2: number = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; const inty2: number = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; I += (0.25 * k_inv3 * D) * (intx2 + inty2); } // Total mass massData.mass = density * area; // Center of mass // DEBUG: b2Assert(area > b2_epsilon); center.SelfMul(1 / area); b2Vec2.AddVV(center, s, massData.center); // Inertia tensor relative to the local origin (point s). massData.I = density * I; // Shift to center of mass then to original body origin. massData.I += massData.mass * (b2Vec2.DotVV(massData.center, massData.center) - b2Vec2.DotVV(center, center)); } private static Validate_s_e = new b2Vec2(); private static Validate_s_v = new b2Vec2(); public Validate(): boolean { for (let i: number = 0; i < this.m_count; ++i) { const i1 = i; const i2 = (i + 1) % this.m_count; const p: b2Vec2 = this.m_vertices[i1]; const e: b2Vec2 = b2Vec2.SubVV(this.m_vertices[i2], p, b2PolygonShape.Validate_s_e); for (let j: number = 0; j < this.m_count; ++j) { if (j === i1 || j === i2) { continue; } const v: b2Vec2 = b2Vec2.SubVV(this.m_vertices[j], p, b2PolygonShape.Validate_s_v); const c: number = b2Vec2.CrossVV(e, v); if (c < 0) { return false; } } } return true; } public SetupDistanceProxy(proxy: b2DistanceProxy, index: number): void { proxy.m_vertices = this.m_vertices; proxy.m_count = this.m_count; proxy.m_radius = this.m_radius; } private static ComputeSubmergedArea_s_normalL = new b2Vec2(); private static ComputeSubmergedArea_s_md = new b2MassData(); private static ComputeSubmergedArea_s_intoVec = new b2Vec2(); private static ComputeSubmergedArea_s_outoVec = new b2Vec2(); private static ComputeSubmergedArea_s_center = new b2Vec2(); public ComputeSubmergedArea(normal: b2Vec2, offset: number, xf: b2Transform, c: b2Vec2): number { // Transform plane into shape co-ordinates const normalL: b2Vec2 = b2Rot.MulTRV(xf.q, normal, b2PolygonShape.ComputeSubmergedArea_s_normalL); const offsetL: number = offset - b2Vec2.DotVV(normal, xf.p); const depths: number[] = []; let diveCount: number = 0; let intoIndex: number = -1; let outoIndex: number = -1; let lastSubmerged: boolean = false; for (let i: number = 0; i < this.m_count; ++i) { depths[i] = b2Vec2.DotVV(normalL, this.m_vertices[i]) - offsetL; const isSubmerged: boolean = depths[i] < (-b2_epsilon); if (i > 0) { if (isSubmerged) { if (!lastSubmerged) { intoIndex = i - 1; diveCount++; } } else { if (lastSubmerged) { outoIndex = i - 1; diveCount++; } } } lastSubmerged = isSubmerged; } switch (diveCount) { case 0: if (lastSubmerged) { // Completely submerged const md: b2MassData = b2PolygonShape.ComputeSubmergedArea_s_md; this.ComputeMass(md, 1); b2Transform.MulXV(xf, md.center, c); return md.mass; } else { // Completely dry return 0; } case 1: if (intoIndex === (-1)) { intoIndex = this.m_count - 1; } else { outoIndex = this.m_count - 1; } break; } const intoIndex2: number = ((intoIndex + 1) % this.m_count); const outoIndex2: number = ((outoIndex + 1) % this.m_count); const intoLamdda: number = (0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex]); const outoLamdda: number = (0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex]); const intoVec: b2Vec2 = b2PolygonShape.ComputeSubmergedArea_s_intoVec.Set( this.m_vertices[intoIndex].x * (1 - intoLamdda) + this.m_vertices[intoIndex2].x * intoLamdda, this.m_vertices[intoIndex].y * (1 - intoLamdda) + this.m_vertices[intoIndex2].y * intoLamdda); const outoVec: b2Vec2 = b2PolygonShape.ComputeSubmergedArea_s_outoVec.Set( this.m_vertices[outoIndex].x * (1 - outoLamdda) + this.m_vertices[outoIndex2].x * outoLamdda, this.m_vertices[outoIndex].y * (1 - outoLamdda) + this.m_vertices[outoIndex2].y * outoLamdda); // Initialize accumulator let area: number = 0; const center: b2Vec2 = b2PolygonShape.ComputeSubmergedArea_s_center.SetZero(); let p2: b2Vec2 = this.m_vertices[intoIndex2]; let p3: b2Vec2; // An awkward loop from intoIndex2+1 to outIndex2 let i: number = intoIndex2; while (i !== outoIndex2) { i = (i + 1) % this.m_count; if (i === outoIndex2) { p3 = outoVec; } else { p3 = this.m_vertices[i]; } const triangleArea: number = 0.5 * ((p2.x - intoVec.x) * (p3.y - intoVec.y) - (p2.y - intoVec.y) * (p3.x - intoVec.x)); area += triangleArea; // Area weighted centroid center.x += triangleArea * (intoVec.x + p2.x + p3.x) / 3; center.y += triangleArea * (intoVec.y + p2.y + p3.y) / 3; p2 = p3; } // Normalize and transform centroid center.SelfMul(1 / area); b2Transform.MulXV(xf, center, c); return area; } public Dump(log: (format: string, ...args: any[]) => void): void { log(" const shape: b2PolygonShape = new b2PolygonShape();\n"); log(" const vs: b2Vec2[] = [];\n"); for (let i: number = 0; i < this.m_count; ++i) { log(" vs[%d] = new b2Vec2(%.15f, %.15f);\n", i, this.m_vertices[i].x, this.m_vertices[i].y); } log(" shape.Set(vs, %d);\n", this.m_count); } private static ComputeCentroid_s_s = new b2Vec2(); private static ComputeCentroid_s_p1 = new b2Vec2(); private static ComputeCentroid_s_p2 = new b2Vec2(); private static ComputeCentroid_s_p3 = new b2Vec2(); private static ComputeCentroid_s_e1 = new b2Vec2(); private static ComputeCentroid_s_e2 = new b2Vec2(); public static ComputeCentroid(vs: b2Vec2[], count: number, out: b2Vec2): b2Vec2 { // DEBUG: b2Assert(count >= 3); const c: b2Vec2 = out; c.SetZero(); let area: number = 0; // Get a reference point for forming triangles. // Use the first vertex to reduce round-off errors. const s: b2Vec2 = b2PolygonShape.ComputeCentroid_s_s.Copy(vs[0]); const inv3: number = 1 / 3; for (let i: number = 0; i < count; ++i) { // Triangle vertices. const p1: b2Vec2 = b2Vec2.SubVV(vs[0], s, b2PolygonShape.ComputeCentroid_s_p1); const p2: b2Vec2 = b2Vec2.SubVV(vs[i], s, b2PolygonShape.ComputeCentroid_s_p2); const p3: b2Vec2 = b2Vec2.SubVV(vs[(i + 1) % count], s, b2PolygonShape.ComputeCentroid_s_p3); const e1: b2Vec2 = b2Vec2.SubVV(p2, p1, b2PolygonShape.ComputeCentroid_s_e1); const e2: b2Vec2 = b2Vec2.SubVV(p3, p1, b2PolygonShape.ComputeCentroid_s_e2); const D: number = b2Vec2.CrossVV(e1, e2); const triangleArea: number = 0.5 * D; area += triangleArea; // Area weighted centroid c.x += triangleArea * inv3 * (p1.x + p2.x + p3.x); c.y += triangleArea * inv3 * (p1.y + p2.y + p3.y); } // Centroid // DEBUG: b2Assert(area > b2_epsilon); // c = (1.0f / area) * c + s; c.x = (1 / area) * c.x + s.x; c.y = (1 / area) * c.y + s.y; return c; } /* public static ComputeOBB(obb, vs, count) { const i: number = 0; const p: Array = [count + 1]; for (i = 0; i < count; ++i) { p[i] = vs[i]; } p[count] = p[0]; const minArea = b2_maxFloat; for (i = 1; i <= count; ++i) { const root = p[i - 1]; const uxX = p[i].x - root.x; const uxY = p[i].y - root.y; const length = b2Sqrt(uxX * uxX + uxY * uxY); uxX /= length; uxY /= length; const uyX = (-uxY); const uyY = uxX; const lowerX = b2_maxFloat; const lowerY = b2_maxFloat; const upperX = (-b2_maxFloat); const upperY = (-b2_maxFloat); for (let j: number = 0; j < count; ++j) { const dX = p[j].x - root.x; const dY = p[j].y - root.y; const rX = (uxX * dX + uxY * dY); const rY = (uyX * dX + uyY * dY); if (rX < lowerX) lowerX = rX; if (rY < lowerY) lowerY = rY; if (rX > upperX) upperX = rX; if (rY > upperY) upperY = rY; } const area = (upperX - lowerX) * (upperY - lowerY); if (area < 0.95 * minArea) { minArea = area; obb.R.ex.x = uxX; obb.R.ex.y = uxY; obb.R.ey.x = uyX; obb.R.ey.y = uyY; const center_x: number = 0.5 * (lowerX + upperX); const center_y: number = 0.5 * (lowerY + upperY); const tMat = obb.R; obb.center.x = root.x + (tMat.ex.x * center_x + tMat.ey.x * center_y); obb.center.y = root.y + (tMat.ex.y * center_x + tMat.ey.y * center_y); obb.extents.x = 0.5 * (upperX - lowerX); obb.extents.y = 0.5 * (upperY - lowerY); } } } */ }
the_stack