text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { assert } from 'chai'; import _set from 'lodash/set'; import configApp from '../helpers/config-app'; import getInitDb from '../helpers/get-init-db'; import { populate } from '../../src'; let provider: any; ['array', 'obj'].forEach(type => { describe(`services populate - include 1:1 - ${type}`, () => { let hookAfter: any; let hookAfterArray: any; let app: any; let recommendation; beforeEach(() => { app = configApp(['posts', 'recommendation']); recommendation = clone(getInitDb('recommendation').store); app.service('posts').hooks({ before: { all: [ (hook: any) => { provider = hook.params.provider; } ] } }); hookAfter = { type: 'after', method: 'create', params: { provider: 'rest' }, path: 'recommendations', result: recommendation['1'] }; hookAfterArray = { type: 'after', method: 'create', params: { provider: 'rest' }, path: 'recommendations', result: [recommendation['1'], recommendation['2'], recommendation['3']] }; }); describe('root is one item', () => { it('saves in nameAs without dot notation', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const schema = { include: makeInclude(type, { service: 'posts', nameAs: 'post', parentField: 'postId', // we have no test for dot notation 'cause no such data childField: 'id' }) }; return populate({ schema })(hook) // @ts-ignore .then((hook1: any) => { const expected = recommendationPosts('post'); assert.deepEqual(hook1.result, expected); }); }); it('saves in nameAs using dot notation', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const schema = { include: makeInclude(type, { service: 'posts', nameAs: 'post.items', parentField: 'postId', // we have no test for dot notation 'cause no such data childField: 'id' }) }; return populate({ schema })(hook) // @ts-ignore .then((hook1: any) => { const expected = recommendationPosts('post.items'); assert.deepEqual(hook1.result, expected); }); }); it('saves in service as default', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const schema = { include: makeInclude(type, { service: 'posts', parentField: 'postId', childField: 'id' }) }; return populate({ schema })(hook) // @ts-ignore .then((hook1: any) => { const expected = recommendationPosts('posts'); assert.deepEqual(hook1.result, expected); }); }); it('ignores undefined parentField', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned delete hook.result.postId; const schema = { include: makeInclude(type, { service: 'posts', parentField: 'postId', childField: 'id' }) }; return populate({ schema })(hook) // @ts-ignore .then((hook1: any) => { const expected = recommendationPosts('posts'); delete expected.postId; delete expected.posts; expected._include = []; assert.deepEqual(hook1.result, expected); }); }); it('uses asArray', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const schema = { include: makeInclude(type, { service: 'posts', parentField: 'postId', childField: 'id', asArray: true }) }; return populate({ schema })(hook) // @ts-ignore .then((hook1: any) => { const expected = recommendationPosts('posts', true); assert.deepEqual(hook1.result, expected); }); }); it('Stores null when no joined records and !asArray', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned hook.result.postId = '999'; const schema = { include: makeInclude(type, { service: 'posts', parentField: 'postId', childField: 'id' }) }; return populate({ schema })(hook) // @ts-ignore .then((hook1: any) => { const expected = recommendationPosts('posts'); expected.postId = '999'; expected.posts = null; assert.deepEqual(hook1.result, expected); }); }); it('Stores [] when no joined records and asArray', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned hook.result.postId = '999'; const schema = { include: makeInclude(type, { service: 'posts', parentField: 'postId', childField: 'id', asArray: true }) }; return populate({ schema })(hook) // @ts-ignore .then((hook1: any) => { const expected = recommendationPosts('posts'); expected.postId = '999'; expected.posts = []; assert.deepEqual(hook1.result, expected); }); }); it('query overridden by childField', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const schema = { include: makeInclude(type, { service: 'posts', parentField: 'postId', childField: 'id', query: { id: 'aaaaaa' } }) }; return populate({ schema })(hook) // @ts-ignore .then((hook1: any) => { const expected = recommendationPosts('posts'); assert.deepEqual(hook1.result, expected); }); }); it('Provider in joins defaults to method call', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const schema = { include: makeInclude(type, { service: 'posts', parentField: 'postId', childField: 'id', query: { id: 'aaaaaa' } }) }; return populate({ schema })(hook) // @ts-ignore .then((hook1: any) => { const expected = recommendationPosts('posts'); assert.deepEqual(hook1.result, expected); assert.equal(provider, 'rest'); // Feathers default if not from WebSocket }); }); it('Provider in joins can be overridden', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const schema = { include: makeInclude(type, { service: 'posts', parentField: 'postId', childField: 'id', query: { id: 'aaaaaa' }, provider: undefined }) }; return populate({ schema })(hook) // @ts-ignore .then((hook1: any) => { const expected = recommendationPosts('posts'); assert.deepEqual(hook1.result, expected); assert.equal(provider, undefined); }); }); it('Provider can be passed down from top level', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const schema = { provider: 'global', include: makeInclude(type, { service: 'posts', parentField: 'postId', childField: 'id', query: { id: 'aaaaaa' } }) }; return populate({ schema })(hook) // @ts-ignore .then((hook1: any) => { const expected = recommendationPosts('posts'); assert.deepEqual(hook1.result, expected); assert.equal(provider, 'global'); }); }); it('Global provider can be overwritten at schema level', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const schema = { provider: 'global', include: makeInclude(type, { service: 'posts', parentField: 'postId', childField: 'id', query: { id: 'aaaaaa' }, provider: 'socketio' }) }; return populate({ schema })(hook) // @ts-ignore .then((hook1: any) => { const expected = recommendationPosts('posts'); assert.deepEqual(hook1.result, expected); assert.equal(provider, 'socketio'); }); }); it('Falsy providers override default provider', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned hook.params.provider = 'rest'; // Set up default provider const schema: any = { provider: undefined, include: makeInclude(type, { service: 'posts', parentField: 'postId', childField: 'id', query: { id: 'aaaaaa' } }) }; return populate({ schema })(hook) // @ts-ignore .then((hook1: any) => { const expected = recommendationPosts('posts'); assert.deepEqual(hook1.result, expected); assert.equal(provider, undefined); }); }); it('childField overridden by select', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const schema = { include: makeInclude(type, { service: 'posts', parentField: 'updatedAt', childField: 'id', select: (_hook: any, parent: any) => ({ id: parent.postId }) }) }; return populate({ schema })(hook) // @ts-ignore .then((hook1: any) => { const expected = recommendationPosts('posts'); assert.deepEqual(hook1.result, expected); }); }); it('checks permissions', () => { const spy: any = []; const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const checkPermissions = (_hook: any, service: any, permissions: any, depth: any) => { spy.push({ service, permissions, depth }); return true; }; const schema = { permissions: 'for root', include: makeInclude(type, { service: 'posts', nameAs: 'post', parentField: 'postId', childField: 'id', permissions: 'for posts' }) }; // @ts-ignore return populate({ schema, checkPermissions })(hook) // @ts-ignore .then((hook1: any) => { let expected = recommendationPosts('post'); assert.deepEqual(hook1.result, expected); expected = [ { service: 'recommendations', permissions: 'for root', depth: 0 }, { service: 'posts', permissions: 'for posts', depth: 1 } ]; assert.deepEqual(spy, expected); }); }); it('throws on invalid permissions', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const checkPermissions = (_hook: any, _service: any, _permissions: any, depth: any) => { return depth === 0; }; const schema = { permissions: 'for root', include: makeInclude(type, { service: 'posts', nameAs: 'post', parentField: 'postId', childField: 'id', permissions: 'for posts' }) }; // @ts-ignore return populate({ schema, checkPermissions })(hook) // @ts-ignore .then(() => { throw new Error('was not supposed to succeed'); }) .catch((err: any) => { assert.notEqual(err, undefined); }); }); it('stores elapsed time', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const schema = { include: makeInclude(type, { service: 'posts', nameAs: 'post', parentField: 'postId', childField: 'id' }) }; return populate({ schema, profile: true })(hook) // @ts-ignore .then((hook1: any) => { const elapsed = hook1.result._elapsed; assert.deepEqual(Object.keys(elapsed), ['post', 'total']); assert.isAbove(elapsed.total, 999); assert.isAtLeast(elapsed.total, elapsed.post); }); }); it('allow non related field joins if query', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const schema = { include: makeInclude(type, { service: 'posts', nameAs: 'post', query: { id: hookAfter.result.postId } }) }; return populate({ schema, profile: true })(hook) // @ts-ignore .then((hook1: any) => { const elapsed = hook1.result._elapsed; assert.deepEqual(Object.keys(elapsed), ['post', 'total']); assert.isAbove(elapsed.total, 999); assert.isAtLeast(elapsed.total, elapsed.post); }); }); it('allow non related field joins if select', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const schema = { include: makeInclude(type, { service: 'posts', nameAs: 'post', select: (_hook: any, parentItem: any) => ({ id: parentItem.postId }) }) }; return populate({ schema, profile: true })(hook) // @ts-ignore .then((hook1: any) => { const elapsed = hook1.result._elapsed; assert.deepEqual(Object.keys(elapsed), ['post', 'total']); assert.isAbove(elapsed.total, 999); assert.isAtLeast(elapsed.total, elapsed.post); }); }); it('throws if no parentField option in related field join', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned const schema = { include: makeInclude(type, { service: 'posts', nameAs: 'post', childField: 'id' }) }; return populate({ schema, profile: true })(hook) // @ts-ignore .then(() => { assert(false, 'unexpectedly succeeeded'); }) .catch((err: any) => { assert.isObject(err, 'no error object'); }); }); it('throws if no parentField defined in related field join', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned delete hook.result.postId; const schema = { include: makeInclude(type, { service: 'posts', nameAs: 'post', parentField: 'postId', childField: 'id' }) }; return populate({ schema, profile: true })(hook) // @ts-ignore .then(() => { assert(false, 'unexpectedly succeeded'); }) .catch((err: any) => { assert.isObject(err, 'no error object'); }); }); }); describe('root is item array', () => { it('populates each item', () => { const hook = clone(hookAfterArray); hook.app = app; // app is a func and wouldn't be cloned const schema = { include: makeInclude(type, { service: 'posts', nameAs: 'post', parentField: 'postId', childField: 'id' }) }; return populate({ schema, profile: true })(hook) // @ts-ignore .then((hook1: any) => { assert.equal(hook1.result.length, 3); }); }); }); describe('populate does not change original schema object', () => { it('check include field', () => { const hook = clone(hookAfterArray); hook.app = app; const includeOptions = () => ({ service: 'posts', nameAs: 'post', parentField: 'postId', childField: 'id' }); const include = makeInclude(type, includeOptions()); const expected = makeInclude(type, includeOptions()); return populate({ schema: { include }, profile: true })(hook) // @ts-ignore .then((hook1: any) => { assert.deepEqual(include, expected); }); }); }); }); }); // Helpers function makeInclude (type: any, obj: any) { return type === 'obj' ? obj : [obj]; } function recommendationPosts (nameAs: any, asArray?: any, recommendation?: any, posts?: any) { recommendation = recommendation || clone(getInitDb('recommendation').store['1']); posts = posts || clone(getInitDb('posts').store['1']); const expected = clone(recommendation); expected._include = [nameAs]; // expected[nameAs] = asArray ? [clone(posts)] : clone(posts); _set(expected, nameAs, asArray ? [clone(posts)] : clone(posts)); return expected; } function clone (obj: any) { return JSON.parse(JSON.stringify(obj)); }
the_stack
import { KTX2ChannelETC1S, KTX2ChannelUASTC, KTX2Container, KTX2DataFormatDescriptorBasicFormat, KTX2GlobalDataBasisLZ, KTX2Model, KTX2SupercompressionScheme, KTX2Transfer, read, } from 'ktx-parse'; import CGAPIResourceRepository from '../../foundation/renderer/CGAPIResourceRepository'; import WebGLContextWrapper from '../WebGLContextWrapper'; import {TextureData} from '../WebGLResourceRepository'; import { CompressionTextureType, CompressionTextureTypeEnum, } from '../../foundation/definitions/CompressionTextureType'; import {ZSTDDecoder} from 'zstddec'; import { BasisLzEtc1sImageTranscoder, MscTranscoderModule, MSC_TRANSCODER, TranscodedImage, UastcImageTranscoder, } from '../../types/KTX2Texture'; const CompressedTextureFormat = { ETC1S: 0, UASTC4x4: 1, } as const; type CompressedTextureFormat = typeof CompressedTextureFormat[keyof typeof CompressedTextureFormat]; const TranscodeTarget = { ETC1_RGB: 'ETC1_RGB', BC1_RGB: 'BC1_RGB', BC4_R: 'BC4_R', BC5_RG: 'BC5_RG', BC3_RGBA: 'BC3_RGBA', PVRTC1_4_RGB: 'PVRTC1_4_RGB', PVRTC1_4_RGBA: 'PVRTC1_4_RGBA', BC7_RGBA: 'BC7_RGBA', BC7_M6_RGB: 'BC7_M6_RGB', BC7_M5_RGBA: 'BC7_M5_RGBA', ETC2_RGBA: 'ETC2_RGBA', ASTC_4x4_RGBA: 'ASTC_4x4_RGBA', RGBA32: 'RGBA32', RGB565: 'RGB565', BGR565: 'BGR565', RGBA4444: 'RGBA4444', PVRTC2_4_RGB: 'PVRTC2_4_RGB', PVRTC2_4_RGBA: 'PVRTC2_4_RGBA', EAC_R11: 'EAC_R11', EAC_RG11: 'EAC_RG11', } as const; type TranscodeTarget = typeof TranscodeTarget[keyof typeof TranscodeTarget]; interface KTX2GlobalDataBasisLZImageDesc { imageFlags: number; rgbSliceByteOffset: number; rgbSliceByteLength: number; alphaSliceByteOffset: number; alphaSliceByteLength: number; } declare const MSC_TRANSCODER: MSC_TRANSCODER; export default class KTX2TextureLoader { private static __instance: KTX2TextureLoader; // TODO: create type of __mscTranscoderModule private static __mscTranscoderModule: MscTranscoderModule; private static __zstdDecoder: ZSTDDecoder; private __mscTranscoderPromise: Promise<void>; constructor() { if (typeof MSC_TRANSCODER === 'undefined') { console.error( 'Failed to call MSC_TRANSCODER() function. Please check to import msc_basis_transcoder.js.' ); } this.__mscTranscoderPromise = this.__loadMSCTranscoder(); } // ----- Public Methods ----------------------------------------------------- static getInstance() { if (!this.__instance) { this.__instance = new KTX2TextureLoader(); } return this.__instance; } transcode(uint8Array: Uint8Array) { const ktx2Container = this.__parse(uint8Array); if (ktx2Container.pixelDepth > 0) { throw new Error('Only 2D textures are currently supported'); } if (ktx2Container.layerCount > 1) { throw new Error('Array textures are not currently supported'); } if (ktx2Container.faceCount > 1) { throw new Error('Cube textures are not currently supported'); } if ( ktx2Container.supercompressionScheme === KTX2SupercompressionScheme.ZSTD ) { if (KTX2TextureLoader.__zstdDecoder == null) { KTX2TextureLoader.__zstdDecoder = new ZSTDDecoder(); } return KTX2TextureLoader.__zstdDecoder.init().then(() => { return this.__mscTranscoderPromise.then(() => { return this.__transcodeData(ktx2Container); }); }); } else { return this.__mscTranscoderPromise.then(() => { return this.__transcodeData(ktx2Container); }); } } // ----- Private Methods ---------------------------------------------------- private __loadMSCTranscoder(): Promise<void> { // load msc_basis_transcoder once return new Promise(resolve => { if (KTX2TextureLoader.__mscTranscoderModule) { resolve(); } MSC_TRANSCODER().then((transcoderModule: MscTranscoderModule) => { transcoderModule.initTranscoders(); KTX2TextureLoader.__mscTranscoderModule = transcoderModule; resolve(); }); }); } private __getDeviceDependentParameters(hasAlpha: boolean) { const webGLResourceRepository = CGAPIResourceRepository.getWebGLResourceRepository(); const glw = webGLResourceRepository.currentWebGLContextWrapper as WebGLContextWrapper; const astc = glw.webgl2ExtCTAstc || glw.webgl1ExtCTAstc; const bptc = glw.webgl2ExtCTBptc || glw.webgl1ExtCTBptc; const s3tc = glw.webgl2ExtCTS3tc || glw.webgl1ExtCTS3tc; const pvrtc = glw.webgl2ExtCTPvrtc || glw.webgl1ExtCTPvrtc; const etc2 = glw.webgl2ExtCTEtc || glw.webgl1ExtCTEtc; const etc1 = glw.webgl2ExtCTEtc1 || glw.webgl1ExtCTEtc1; let transcodeTargetStr: TranscodeTarget; let compressionTextureType: CompressionTextureTypeEnum; if (astc) { transcodeTargetStr = TranscodeTarget.ASTC_4x4_RGBA; compressionTextureType = CompressionTextureType.ASTC_RGBA_4x4; } else if (bptc) { transcodeTargetStr = TranscodeTarget.BC7_RGBA; compressionTextureType = CompressionTextureType.BPTC_RGBA; } else if (s3tc) { if (hasAlpha) { transcodeTargetStr = TranscodeTarget.BC3_RGBA; compressionTextureType = CompressionTextureType.S3TC_RGBA_DXT5; } else { transcodeTargetStr = TranscodeTarget.BC1_RGB; compressionTextureType = CompressionTextureType.S3TC_RGB_DXT1; } } else if (pvrtc) { if (hasAlpha) { transcodeTargetStr = TranscodeTarget.PVRTC1_4_RGBA; compressionTextureType = CompressionTextureType.PVRTC_RGBA_4BPPV1; } else { transcodeTargetStr = TranscodeTarget.PVRTC1_4_RGB; compressionTextureType = CompressionTextureType.PVRTC_RGB_4BPPV1; } } else if (etc2) { if (hasAlpha) { transcodeTargetStr = TranscodeTarget.ETC2_RGBA; compressionTextureType = CompressionTextureType.ETC2_RGBA8_EAC; } else { transcodeTargetStr = TranscodeTarget.ETC1_RGB; compressionTextureType = CompressionTextureType.ETC2_RGB8; } } else if (etc1) { transcodeTargetStr = TranscodeTarget.ETC1_RGB; compressionTextureType = CompressionTextureType.ETC1_RGB; } else { transcodeTargetStr = TranscodeTarget.RGBA32; compressionTextureType = CompressionTextureType.RGBA8_EXT; } return {transcodeTargetStr, compressionTextureType}; } private __parse(uint8Array: Uint8Array): KTX2Container { // The parser can detect an invalid identifier. return read(uint8Array); } private __transcodeData(ktx2Container: KTX2Container) { const width = ktx2Container.pixelWidth; const height = ktx2Container.pixelHeight; const faceCount = ktx2Container.faceCount; // faceCount is 6 if the transcoded data is a cube map (not support yet) const imageDescs = ktx2Container.globalData?.imageDescs; const dfd = ktx2Container.dataFormatDescriptor[0]; const compressedTextureFormat = dfd.colorModel === KTX2Model.UASTC ? CompressedTextureFormat.UASTC4x4 : CompressedTextureFormat.ETC1S; const hasAlpha = this.__hasAlpha(dfd, compressedTextureFormat); const isVideo = false; const transcoderModule = KTX2TextureLoader.__mscTranscoderModule; const transcoder = compressedTextureFormat === CompressedTextureFormat.UASTC4x4 ? new transcoderModule.UastcImageTranscoder() : new transcoderModule.BasisLzEtc1sImageTranscoder(); const textureFormat = compressedTextureFormat === CompressedTextureFormat.UASTC4x4 ? transcoderModule.TextureFormat.UASTC4x4 : transcoderModule.TextureFormat.ETC1S; const {transcodeTargetStr, compressionTextureType} = this.__getDeviceDependentParameters(hasAlpha); const transcodeTarget = transcoderModule.TranscodeTarget[transcodeTargetStr]; const mipmapData: TextureData[] = []; const transcodedData = { width, height, compressionTextureType, mipmapData, needGammaCorrection: dfd.transferFunction !== KTX2Transfer.SRGB, }; for (let level = 0; level < ktx2Container.levels.length; level++) { const levelWidth = Math.max(1, width >> level); const levelHeight = Math.max(1, height >> level); const imageInfo = new transcoderModule.ImageInfo( textureFormat, levelWidth, levelHeight, level ); let levelBuffer = ktx2Container.levels[level].levelData; const levelUncompressedByteLength = ktx2Container.levels[level].uncompressedByteLength; const levelBufferByteLength = imageInfo.numBlocksX * imageInfo.numBlocksY * dfd.bytesPlane[0]; if ( ktx2Container.supercompressionScheme === KTX2SupercompressionScheme.ZSTD ) { levelBuffer = KTX2TextureLoader.__zstdDecoder.decode( levelBuffer, levelUncompressedByteLength ); } let faceBufferByteOffset = 0; const firstImageDescIndexInLevel = level * Math.max(ktx2Container.layerCount, 1) * faceCount * Math.max(ktx2Container.pixelDepth, 1); for (let faceIndex = 0; faceIndex < faceCount; faceIndex++) { let imageDesc: KTX2GlobalDataBasisLZImageDesc | null = null; let faceBuffer: Uint8Array; if ( ktx2Container.supercompressionScheme === KTX2SupercompressionScheme.BASISLZ ) { imageDesc = imageDescs?.[ firstImageDescIndexInLevel + faceIndex ] as KTX2GlobalDataBasisLZImageDesc; faceBuffer = new Uint8Array( levelBuffer, imageDesc.rgbSliceByteOffset, imageDesc.rgbSliceByteLength + imageDesc.alphaSliceByteLength ); } else { faceBuffer = new Uint8Array( levelBuffer, faceBufferByteOffset, levelBufferByteLength ); faceBufferByteOffset += levelBufferByteLength; } let result: TranscodedImage | undefined; if (compressedTextureFormat === CompressedTextureFormat.UASTC4x4) { imageInfo.flags = 0; imageInfo.rgbByteOffset = 0; imageInfo.rgbByteLength = levelUncompressedByteLength; imageInfo.alphaByteOffset = 0; imageInfo.alphaByteLength = 0; result = (transcoder as UastcImageTranscoder).transcodeImage( transcodeTarget, faceBuffer, imageInfo, 0, hasAlpha, isVideo ); } else { const sgd = ktx2Container.globalData as KTX2GlobalDataBasisLZ; const basisTranscoder = transcoder as BasisLzEtc1sImageTranscoder; basisTranscoder.decodePalettes( sgd.endpointCount, sgd.endpointsData, sgd.selectorCount, sgd.selectorsData ); basisTranscoder.decodeTables(sgd.tablesData); imageInfo.flags = imageDesc!.imageFlags; imageInfo.rgbByteOffset = 0; imageInfo.rgbByteLength = imageDesc!.rgbSliceByteLength; imageInfo.alphaByteOffset = imageDesc!.alphaSliceByteOffset > 0 ? imageDesc!.rgbSliceByteLength : 0; imageInfo.alphaByteLength = imageDesc!.alphaSliceByteLength; result = basisTranscoder.transcodeImage( transcodeTarget, faceBuffer, imageInfo, 0, isVideo ); } if (result?.transcodedImage != null) { const transcodedTextureBuffer = result.transcodedImage .get_typed_memory_view() .slice(); result.transcodedImage.delete(); const mipmap = { level, width: levelWidth, height: levelHeight, buffer: transcodedTextureBuffer, } as TextureData; mipmapData.push(mipmap); } } } return transcodedData; } private __hasAlpha( dfd: KTX2DataFormatDescriptorBasicFormat, compressedTextureFormat: CompressedTextureFormat ) { if (compressedTextureFormat === CompressedTextureFormat.UASTC4x4) { return dfd.samples[0].channelID === KTX2ChannelUASTC.RGBA; } else { return ( dfd.samples.length === 2 && (dfd.samples[0].channelID === KTX2ChannelETC1S.AAA || dfd.samples[1].channelID === KTX2ChannelETC1S.AAA) ); } } }
the_stack
import { d3, setMouseEvent, initChart } from './c3-helper' describe('c3 chart interaction', function() { 'use strict' var chart, args const moveMouseOut = () => setMouseEvent(chart, 'mouseout', 0, 0, d3.select('.c3-event-rect').node()) const moveMouse = (x = 0, y = 0) => setMouseEvent(chart, 'mousemove', x, y, d3.select('.c3-event-rect').node()) const clickMouse = (x = 0, y = 0) => setMouseEvent(chart, 'click', x, y, d3.select('.c3-event-rect').node()) beforeEach(function(done) { chart = initChart(chart, args, done) }) describe('generate event rects', function() { describe('custom x', function() { beforeAll(function() { args = { data: { x: 'x', columns: [ ['x', 0, 1000, 3000, 10000], ['data', 10, 10, 10, 10] ], type: 'bar' } } }) it('should have only 1 event rect properly', function() { var eventRects = d3.selectAll('.c3-event-rect') expect(eventRects.size()).toBe(1) eventRects.each(function() { var box = (d3.select(this).node() as any).getBoundingClientRect() expect(box.left).toBeCloseTo(40.5, -2) expect(box.width).toBeCloseTo(598, -2) }) }) describe('mouseover', function() { let mouseoutCounter = 0 let mouseoverCounter = 0 beforeAll(function() { args = { data: { columns: [ ['data1', 30, 200, 100, 400, -150, 250], ['data2', 50, 20, 10, 40, 15, 25], ['data3', -150, 120, 110, 140, 115, 125] ], type: 'bar', onmouseout: function() { mouseoutCounter += 1 }, onmouseover: function() { mouseoverCounter += 1 } }, axis: { rotated: false } } }) beforeEach(function() { mouseoverCounter = 0 mouseoutCounter = 0 }) it('should be undefined when not within bar', function() { moveMouseOut() expect(mouseoutCounter).toEqual(0) expect(mouseoverCounter).toEqual(0) expect(chart.internal.mouseover).toBeUndefined() }) it('should be data value when within bar', function() { moveMouse(31, 280) expect(mouseoutCounter).toEqual(0) expect(mouseoverCounter).toEqual(1) expect(chart.internal.mouseover).toEqual({ x: 0, value: 30, index: 0, id: 'data1', name: 'data1' }) }) it('should be undefined after leaving chart', function() { moveMouse(31, 280) moveMouseOut() expect(mouseoutCounter).toEqual(1) expect(mouseoverCounter).toEqual(1) expect(chart.internal.mouseover).toBeUndefined() }) it('should retrigger mouseover event when returning to same value', function() { moveMouse(31, 280) moveMouseOut() moveMouse(31, 280) expect(mouseoutCounter).toEqual(1) expect(mouseoverCounter).toEqual(2) expect(chart.internal.mouseover).toEqual({ x: 0, value: 30, index: 0, id: 'data1', name: 'data1' }) }) }) describe('should generate bar chart with only one data', function() { beforeAll(function() { args = { data: { x: 'x', columns: [ ['x', 0], ['data', 10] ], type: 'bar' } } }) it('should have 1 event rects properly', function() { var eventRects = d3.selectAll('.c3-event-rect') expect(eventRects.size()).toBe(1) eventRects.each(function() { var box = (d3.select(this).node() as any).getBoundingClientRect() expect(box.left).toBeCloseTo(40.5, -2) expect(box.width).toBeCloseTo(598, -2) }) }) }) }) describe('timeseries', function() { beforeAll(function() { args = { data: { x: 'x', columns: [ ['x', '20140101', '20140201', '20140210', '20140301'], ['data', 10, 10, 10, 10] ] } } }) it('should have only 1 event rect properly', function() { var eventRects = d3.selectAll('.c3-event-rect') expect(eventRects.size()).toBe(1) eventRects.each(function() { var box = (d3.select(this).node() as any).getBoundingClientRect() expect(box.left).toBeCloseTo(40.5, -2) expect(box.width).toBeCloseTo(598, -2) }) }) describe('should generate line chart with only 1 data timeseries', function() { beforeAll(function() { args = { data: { x: 'x', columns: [ ['x', '20140101'], ['data', 10] ] } } }) it('should have 1 event rects properly', function() { var eventRects = d3.selectAll('.c3-event-rect') expect(eventRects.size()).toBe(1) eventRects.each(function() { var box = (d3.select(this).node() as any).getBoundingClientRect() expect(box.left).toBeCloseTo(40.5, -2) expect(box.width).toBeCloseTo(598, -2) }) }) }) }) }) describe('bar chart', function() { describe('tooltip_grouped=true', function() { beforeAll(() => { args = { data: { columns: [ ['data1', 30, 200, 200, 400, 150, -250], ['data2', 130, -100, 100, 200, 150, 50], ['data3', 230, -200, 200, 0, 250, 250] ], type: 'bar', groups: [['data1', 'data2']], hide: ['data1'] }, tooltip: { grouped: true }, axis: { x: { type: 'category' }, rotated: true }, interaction: { enabled: true } } }) it('generate a single rect', () => { const eventRectList = d3.selectAll('.c3-event-rect') expect(eventRectList.size()).toBe(1) expect(eventRectList.attr('x')).toEqual('0') expect(eventRectList.attr('y')).toEqual('0') expect(eventRectList.attr('height')).toEqual('' + chart.internal.height) expect(eventRectList.attr('width')).toEqual('' + chart.internal.width) }) it('shows tooltip with visible data of currently hovered category', () => { moveMouse(20, 20) expect( (document.querySelector('.c3-tooltip-container') as any).style.display ).toEqual('block') const tooltipData = [ ...(document.querySelectorAll('.c3-tooltip tr') as any) ] expect(tooltipData.length).toBe(3) // header + data[123] expect(tooltipData[1].querySelector('.name').textContent).toBe('data3') expect(tooltipData[2].querySelector('.name').textContent).toBe('data2') }) it('shows cursor:pointer only if hovering bar', () => { const eventRect = d3.select('.c3-event-rect') moveMouse(1, 1) expect(eventRect.style('cursor')).toEqual('auto') moveMouse(360, 48) expect(eventRect.style('cursor')).toEqual('pointer') moveMouse(1, 1) expect(eventRect.style('cursor')).toEqual('auto') }) it('expands all bars of currently hovered category', () => { moveMouse(20, 20) const barList = d3.selectAll('.c3-bar') expect(barList.size()).toBeGreaterThan(0) barList.each(function() { if ( (this as any).classList.contains('c3-bar-0') && !(this as any).parentElement.classList.contains('c3-bars-data1') ) { expect((this as any).classList.contains('_expanded_')).toBeTruthy() } else { expect((this as any).classList.contains('_expanded_')).toBeFalsy() } }) moveMouse(20, 170) barList.each(function() { if ( (this as any).classList.contains('c3-bar-2') && !(this as any).parentElement.classList.contains('c3-bars-data1') ) { expect((this as any).classList.contains('_expanded_')).toBeTruthy() } else { expect((this as any).classList.contains('_expanded_')).toBeFalsy() } }) }) }) describe('tooltip_grouped=false', function() { beforeAll(() => { args = { data: { columns: [ ['data1', 30, 200, 200, 400, 150, -250], ['data2', 130, -100, 100, 200, 150, 50], ['data3', 230, -200, 200, 0, 250, 250] ], type: 'bar', groups: [['data1', 'data2']] }, tooltip: { grouped: false }, axis: { x: { type: 'category' } }, interaction: { enabled: true } } }) it('generate a single rect', () => { const eventRectList = d3.selectAll('.c3-event-rect') expect(eventRectList.size()).toBe(1) expect(eventRectList.attr('x')).toEqual('0') expect(eventRectList.attr('y')).toEqual('0') expect(eventRectList.attr('height')).toEqual('' + chart.internal.height) expect(eventRectList.attr('width')).toEqual('' + chart.internal.width) }) it('shows tooltip with only hovered data', () => { moveMouse(1, 1) expect( (document.querySelector('.c3-tooltip-container') as any).style.display ).toEqual('none') moveMouse(35, 268) expect( (document.querySelector('.c3-tooltip-container') as any).style.display ).toEqual('block') const tooltipData = [ ...(document.querySelectorAll('.c3-tooltip tr') as any) ] expect(tooltipData.length).toBe(2) // header + data2 expect(tooltipData[1].querySelector('.name').textContent).toBe('data2') expect(tooltipData[1].querySelector('.value').textContent).toBe('130') }) it('expands only hovered bar', () => { moveMouse(20, 20) const barList = d3.selectAll('.c3-bar') expect(barList.size()).toBeGreaterThan(0) // nothing expanded barList.each(function() { expect((this as any).classList.contains('_expanded_')).toBeFalsy() }) moveMouse(38, 258) barList.each(function() { if ( (this as any).classList.contains('c3-bar-0') && (this as any).parentElement.classList.contains('c3-bars-data2') ) { expect((this as any).classList.contains('_expanded_')).toBeTruthy() } else { expect((this as any).classList.contains('_expanded_')).toBeFalsy() } }) }) }) }) describe('line chart', function() { describe('tooltip_grouped=false', function() { let clickedData = [] beforeAll(() => { args = { data: { columns: [ ['data1', 30, 200, 200, 400, 150, -250], ['data2', 130, -100, 100, 200, 150, 50], ['data3', 230, -200, 200, 0, 250, 250] ], type: 'line', groups: [['data1', 'data2']], onclick: function(d) { clickedData.push(d) } }, tooltip: { grouped: false }, axis: { x: { type: 'category' } }, interaction: { enabled: true }, point: { r: 2, sensitivity: 10, focus: { expand: { enabled: true, r: 8 } } } } }) beforeEach(function() { clickedData = [] }) it('shows tooltip with only hovered data', () => { moveMouse(1, 1) expect( (document.querySelector('.c3-tooltip-container') as any).style.display ).toEqual('none') moveMouse(48, 184) expect( (document.querySelector('.c3-tooltip-container') as any).style.display ).toEqual('block') const tooltipData = [ ...(document.querySelectorAll('.c3-tooltip tr') as any) ] expect(tooltipData.length).toBe(2) // header + data3 expect(tooltipData[1].querySelector('.name').textContent).toBe('data3') expect(tooltipData[1].querySelector('.value').textContent).toBe('230') }) it('expands only hovered point', () => { moveMouse(1, 1) const circleList = d3.selectAll('.c3-circle') expect(circleList.size()).toBeGreaterThan(0) // nothing expanded circleList.each(function() { expect((this as any).classList.contains('_expanded_')).toBeFalsy() }) moveMouse(45, 233) circleList.each(function() { expect((this as any).classList.contains('_expanded_')).toEqual( (this as any).classList.contains('c3-circle-0') && (this as any).parentElement.classList.contains('c3-circles-data2') ) }) }) it('shows cursor:pointer only if hovering point', () => { const eventRect = d3.select('.c3-event-rect') moveMouse(1, 1) expect(eventRect.style('cursor')).toEqual('auto') moveMouse(49, 219) expect(eventRect.style('cursor')).toEqual('pointer') moveMouse(1, 1) expect(eventRect.style('cursor')).toEqual('auto') }) it('clicks only on hovered point', () => { clickMouse(144, 201) expect(clickedData).toEqual([ { x: 1, index: 1, value: 200, id: 'data1', name: 'data1' } ]) }) describe('with selection enabled', () => { beforeAll(() => { args.data.selection = { enabled: true, isselectable: function(d) { return d.id !== 'data3' } } }) it('can toggle selection', () => { expect(d3.selectAll('.c3-circle _selected_').size()).toEqual(0) clickMouse(144, 201) // index 1 @ data1 expect(d3.selectAll('.c3-circle._selected_').size()).toEqual(1) expect( d3.select('.c3-circles-data1 .c3-circle-1._selected_').size() ).toEqual(1) // data3 is not selectable clickMouse(391, 283) // index 3 @ data3 expect(d3.selectAll('.c3-circle._selected_').size()).toEqual(1) expect( d3.select('.c3-circles-data3 .c3-circle-3._selected_').size() ).toEqual(0) expect( d3.select('.c3-circles-data1 .c3-circle-1._selected_').size() ).toEqual(1) clickMouse(343, 204) // index 3 @ data2 expect(d3.selectAll('.c3-circle._selected_').size()).toEqual(2) expect( d3.select('.c3-circles-data2 .c3-circle-3._selected_').size() ).toEqual(1) expect( d3.select('.c3-circles-data1 .c3-circle-1._selected_').size() ).toEqual(1) clickMouse(144, 201) // index 1 @ data1 expect(d3.selectAll('.c3-circle._selected_').size()).toEqual(1) expect( d3.select('.c3-circles-data2 .c3-circle-3._selected_').size() ).toEqual(1) }) }) describe('with tooltip_horizontal=true', () => { beforeAll(() => { args.tooltip.horizontal = true }) it('can clicks on points', () => { // out of point sensitivity clickMouse(146, 46) clickMouse(343, 263) // click 3 data point clickMouse(147, 370) clickMouse(340, 203) clickMouse(537, 386) expect(clickedData).toEqual([ { x: 1, value: -200, id: 'data3', index: 1, name: 'data3' }, { x: 3, value: 200, id: 'data2', index: 3, name: 'data2' }, { x: 5, value: -250, id: 'data1', index: 5, name: 'data1' } ]) }) it('shows tooltip with only closest data', () => { moveMouse(1, 1) expect( (document.querySelector('.c3-tooltip-container') as any).style .display ).toEqual('none') moveMouse(146, 46) expect( (document.querySelector('.c3-tooltip-container') as any).style .display ).toEqual('block') let tooltipData = [ ...(document.querySelectorAll('.c3-tooltip tr') as any) ] expect(tooltipData.length).toBe(2) // header + data1 expect(tooltipData[1].querySelector('.name').textContent).toBe( 'data1' ) expect(tooltipData[1].querySelector('.value').textContent).toBe('200') moveMouse(343, 263) expect( (document.querySelector('.c3-tooltip-container') as any).style .display ).toEqual('block') tooltipData = [ ...(document.querySelectorAll('.c3-tooltip tr') as any) ] expect(tooltipData.length).toBe(2) // header + data3 expect(tooltipData[1].querySelector('.name').textContent).toBe( 'data3' ) expect(tooltipData[1].querySelector('.value').textContent).toBe('0') }) }) }) describe('tooltip_grouped=true', function() { let clickedData = [] beforeAll(() => { args = { data: { columns: [ ['data1', 30, 200, 200, 400, 150, -250], ['data2', 130, -100, 100, 200, 150, 50], ['data3', 230, -200, 200, 0, 250, 250] ], type: 'line', groups: [['data1', 'data2']], onclick: function(d) { clickedData.push(d) } }, tooltip: { grouped: true }, axis: { x: { type: 'category' } }, interaction: { enabled: true }, point: { r: 2, sensitivity: 10, focus: { expand: { enabled: true, r: 8 } } } } }) beforeEach(function() { clickedData = [] }) describe('with tooltip_horizontal=true', () => { beforeAll(() => { args.tooltip.horizontal = true }) it('can clicks on points', () => { // out of point sensitivity clickMouse(146, 46) clickMouse(343, 263) // click 3 data point clickMouse(147, 370) clickMouse(340, 203) clickMouse(537, 386) expect(clickedData).toEqual([ { x: 1, value: -200, id: 'data3', index: 1, name: 'data3' }, { x: 3, value: 200, id: 'data2', index: 3, name: 'data2' }, { x: 5, value: -250, id: 'data1', index: 5, name: 'data1' } ]) }) it('shows tooltip with all data', () => { moveMouse(1, 1) expect( (document.querySelector('.c3-tooltip-container') as any).style .display ).toEqual('block') let tooltipData = [ ...(document.querySelectorAll('.c3-tooltip tr') as any) ] expect(tooltipData.length).toBe(4) // header + data[123] expect(tooltipData[1].querySelector('.name').textContent).toBe( 'data1' ) expect(tooltipData[1].querySelector('.value').textContent).toBe('30') expect(tooltipData[2].querySelector('.name').textContent).toBe( 'data3' ) expect(tooltipData[2].querySelector('.value').textContent).toBe('230') expect(tooltipData[3].querySelector('.name').textContent).toBe( 'data2' ) expect(tooltipData[3].querySelector('.value').textContent).toBe('130') moveMouse(146, 46) expect( (document.querySelector('.c3-tooltip-container') as any).style .display ).toEqual('block') tooltipData = [ ...(document.querySelectorAll('.c3-tooltip tr') as any) ] expect(tooltipData.length).toBe(4) // header + data[123] expect(tooltipData[1].querySelector('.name').textContent).toBe( 'data1' ) expect(tooltipData[1].querySelector('.value').textContent).toBe('200') expect(tooltipData[2].querySelector('.name').textContent).toBe( 'data3' ) expect(tooltipData[2].querySelector('.value').textContent).toBe( '-200' ) expect(tooltipData[3].querySelector('.name').textContent).toBe( 'data2' ) expect(tooltipData[3].querySelector('.value').textContent).toBe( '-100' ) }) }) }) }) describe('line chart (multiple xs)', function() { let clickedData = [] beforeAll(() => { args = { data: { xs: { data1: 'x1', data2: 'x2' }, columns: [ ['x1', 10, 30, 45, 50, 70, 100], ['x2', 30, 50, 75, 100, 120], ['data1', 30, 200, 100, 400, 150, 250], ['data2', 20, 180, 240, 100, 190] ], type: 'line', onclick: function(d) { clickedData.push(d) } }, tooltip: { grouped: true, horizontal: true }, interaction: { enabled: true } } }) beforeEach(function() { clickedData = [] }) it('shows tooltip with all data', () => { moveMouse(1, 1) expect( (document.querySelector('.c3-tooltip-container') as any).style.display ).toEqual('block') let tooltipData = [ ...(document.querySelectorAll('.c3-tooltip tr') as any) ] expect(tooltipData.length).toBe(2) // header + data[1] expect(tooltipData[1].querySelector('.name').textContent).toBe('data1') expect(tooltipData[1].querySelector('.value').textContent).toBe('30') moveMouse(107, 95) expect( (document.querySelector('.c3-tooltip-container') as any).style.display ).toEqual('block') tooltipData = [...(document.querySelectorAll('.c3-tooltip tr') as any)] expect(tooltipData.length).toBe(3) // header + data[12] expect(tooltipData[1].querySelector('.name').textContent).toBe('data1') expect(tooltipData[1].querySelector('.value').textContent).toBe('200') expect(tooltipData[2].querySelector('.name').textContent).toBe('data2') expect(tooltipData[2].querySelector('.value').textContent).toBe('20') moveMouse(430, 140) expect( (document.querySelector('.c3-tooltip-container') as any).style.display ).toEqual('block') tooltipData = [...(document.querySelectorAll('.c3-tooltip tr') as any)] expect(tooltipData.length).toBe(3) // header + data[12] expect(tooltipData[1].querySelector('.name').textContent).toBe('data1') expect(tooltipData[1].querySelector('.value').textContent).toBe('250') expect(tooltipData[2].querySelector('.name').textContent).toBe('data2') expect(tooltipData[2].querySelector('.value').textContent).toBe('100') }) }) describe('scatter chart', function() { describe('tooltip_grouped=true', function() { beforeAll(() => { args = { data: { columns: [ ['data1', 30, null, 100, 400, -150, 250], ['data2', 50, 20, 10, 40, 15, 25], ['data3', -150, 120, 110, 140, 115, 125] ], type: 'scatter' }, tooltip: { grouped: true }, interaction: { enabled: true } } }) it('shows tooltip with visible data of currently hovered category', () => { moveMouse(20, 20) let tooltipData = [ ...(document.querySelectorAll('.c3-tooltip tr') as any) ] expect(tooltipData.length).toBe(4) // header + data[123] expect(tooltipData[1].querySelector('.name').textContent).toBe('data2') expect(tooltipData[1].querySelector('.value').textContent).toBe('50') expect(tooltipData[2].querySelector('.name').textContent).toBe('data1') expect(tooltipData[2].querySelector('.value').textContent).toBe('30') expect(tooltipData[3].querySelector('.name').textContent).toBe('data3') expect(tooltipData[3].querySelector('.value').textContent).toBe('-150') moveMouse(350, 354) tooltipData = [...(document.querySelectorAll('.c3-tooltip tr') as any)] expect(tooltipData.length).toBe(4) // header + data[123] expect(tooltipData[1].querySelector('.name').textContent).toBe('data1') expect(tooltipData[1].querySelector('.value').textContent).toBe('400') expect(tooltipData[2].querySelector('.name').textContent).toBe('data3') expect(tooltipData[2].querySelector('.value').textContent).toBe('140') expect(tooltipData[3].querySelector('.name').textContent).toBe('data2') expect(tooltipData[3].querySelector('.value').textContent).toBe('40') }) it('shows x grid', () => { moveMouse(20, 20) expect(d3.select('.c3-xgrid-focus').style('visibility')).toBe('visible') }) }) }) describe('area chart (timeseries)', function() { describe('tooltip_grouped=true', function() { beforeAll(() => { args = { data: { x: 'x', columns: [ [ 'x', '2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04', '2018-01-05', '2018-01-06' ], ['data1', 30, 200, 200, 400, 150, 250], ['data2', 130, 100, 100, 200, 150, 50], ['data3', 230, 200, 200, 0, 250, 250] ], type: 'area', groups: [['data1', 'data2', 'data3']] }, tooltip: { grouped: true }, axis: { x: { type: 'timeseries' } }, interaction: { enabled: true } } }) it('shows tooltip with visible data of currently hovered category', () => { moveMouse(20, 20) expect( (document.querySelector('.c3-tooltip-container') as any).style.display ).toEqual('block') const tooltipData = [ ...(document.querySelectorAll('.c3-tooltip tr') as any) ] expect(tooltipData.length).toBe(4) // header + data[123] expect(tooltipData[1].querySelector('.name').textContent).toBe('data1') expect(tooltipData[2].querySelector('.name').textContent).toBe('data3') expect(tooltipData[3].querySelector('.name').textContent).toBe('data2') }) it('shows cursor:pointer only if hovering area', () => { const eventRect = d3.select('.c3-event-rect') moveMouse(1, 1) expect(eventRect.style('cursor')).toEqual('auto') moveMouse(360, 48) expect(eventRect.style('cursor')).toEqual('pointer') moveMouse(1, 1) expect(eventRect.style('cursor')).toEqual('auto') }) }) describe('tooltip_grouped=false', function() { beforeAll(() => { args = { data: { x: 'x', columns: [ [ 'x', '2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04', '2018-01-05', '2018-01-06' ], ['data1', 30, 200, 200, 400, 150, 250], ['data2', 130, 100, 100, 200, 150, 50], ['data3', 230, 200, 200, 0, 250, 250] ], type: 'area', groups: [['data1', 'data2', 'data3']] }, tooltip: { grouped: false }, axis: { x: { type: 'timeseries' }, rotated: false }, interaction: { enabled: true } } }) it('shows tooltip with only hovered data', () => { moveMouse(1, 1) expect( (document.querySelector('.c3-tooltip-container') as any).style.display ).toEqual('none') moveMouse(5, 174) expect( (document.querySelector('.c3-tooltip-container') as any).style.display ).toEqual('block') const tooltipData = [ ...(document.querySelectorAll('.c3-tooltip tr') as any) ] expect(tooltipData.length).toBe(2) // header + data1 expect(tooltipData[1].querySelector('.name').textContent).toBe('data1') expect(tooltipData[1].querySelector('.value').textContent).toBe('30') }) }) }) describe('disabled', function() { beforeAll(() => { args = { data: { columns: [ ['data1', 30, 200, 200, 400, 150, -250], ['data2', 130, -100, 100, 200, 150, 50], ['data3', 230, -200, 200, 0, 250, 250] ], type: 'bar', groups: [['data1', 'data2']] }, axis: { x: { type: 'category' } }, interaction: { enabled: false } } }) it('generate a single rect', () => { const eventRectList = d3.selectAll('.c3-event-rect') expect(eventRectList.size()).toBe(1) expect(eventRectList.attr('x')).toEqual('0') expect(eventRectList.attr('y')).toEqual('0') expect(eventRectList.attr('height')).toEqual('' + chart.internal.height) expect(eventRectList.attr('width')).toEqual('' + chart.internal.width) }) it('does not show tooltip when hovering data', () => { moveMouse(40, 260) expect( (document.querySelector('.c3-tooltip-container') as any).style.display ).toEqual('none') }) it('does not show cursor:pointer when hovering data', () => { moveMouse(40, 260) expect(d3.select('.c3-event-rect').style('cursor')).toEqual('auto') }) }) })
the_stack
import { Installation, Subscription } from "../../models"; import getAxiosInstance from "./axios"; import { getJiraId } from "../util/id"; import { AxiosInstance, AxiosResponse } from "axios"; import Logger from "bunyan"; import issueKeyParser from "jira-issue-key-parser"; import { JiraCommit, JiraIssue } from "../../interfaces/jira"; import { getLogger } from "../../config/logger"; // Max number of issue keys we can pass to the Jira API export const ISSUE_KEY_API_LIMIT = 100; const issueKeyLimitWarning = "Exceeded issue key reference limit. Some issues may not be linked."; export interface DeploymentsResult { status: number; rejectedDeployments?: any[]; } /* * Similar to the existing Octokit rest.js instance included in probot * apps by default, this client adds a Jira client that allows us to * abstract away the underlying HTTP requests made for each action. In * general, the client should match the Octokit rest.js design for clear * interoperability. */ async function getJiraClient( jiraHost: string, gitHubInstallationId: number, logger: Logger = getLogger("jira-client") ): Promise<any> { const installation = await Installation.getForHost(jiraHost); if (installation == null) { return undefined; } const instance = getAxiosInstance( installation.jiraHost, installation.sharedSecret, logger ); // TODO: need to create actual class for this const client = { baseURL: instance.defaults.baseURL, issues: { get: (issueId: string, query = { fields: "summary" }): Promise<AxiosResponse<JiraIssue>> => instance.get("/rest/api/latest/issue/:issue_id", { urlParams: { ...query, issue_id: issueId } }), getAll: async (issueIds: string[], query?: { fields: string }): Promise<JiraIssue[]> => { const responses = await Promise.all<AxiosResponse<JiraIssue> | undefined>( issueIds.map((issueId) => client.issues.get(issueId, query) // Ignore any errors .catch(() => undefined)) ); return responses.reduce((acc: JiraIssue[], response) => { if (response?.status === 200 && !!response?.data) { acc.push(response.data); } return acc; }, []); }, parse: (text: string): string[] | undefined => { if (!text) return undefined; return issueKeyParser().parse(text) || undefined; }, comments: { // eslint-disable-next-line camelcase getForIssue: (issue_id: string) => instance.get("/rest/api/latest/issue/:issue_id/comment", { urlParams: { issue_id } }), // eslint-disable-next-line camelcase addForIssue: (issue_id: string, payload) => instance.post("/rest/api/latest/issue/:issue_id/comment", payload, { urlParams: { issue_id } }) }, transitions: { // eslint-disable-next-line camelcase getForIssue: (issue_id: string) => instance.get("/rest/api/latest/issue/:issue_id/transitions", { urlParams: { issue_id } }), // eslint-disable-next-line camelcase updateForIssue: (issue_id: string, transition_id: string) => instance.post( "/rest/api/latest/issue/:issue_id/transitions", { transition: { id: transition_id } }, { urlParams: { issue_id } } ) }, worklogs: { // eslint-disable-next-line camelcase getForIssue: (issue_id: string) => instance.get("/rest/api/latest/issue/:issue_id/worklog", { urlParams: { issue_id } }), // eslint-disable-next-line camelcase addForIssue: (issue_id: string, payload) => instance.post("/rest/api/latest/issue/:issue_id/worklog", payload, { urlParams: { issue_id } }) } }, devinfo: { branch: { delete: (repositoryId: string, branchRef: string) => instance.delete( "/rest/devinfo/0.10/repository/:repositoryId/branch/:branchJiraId", { urlParams: { _updateSequenceId: Date.now().toString(), repositoryId, branchJiraId: getJiraId(branchRef) } } ) }, // Add methods for handling installationId properties that exist in Jira installation: { exists: (gitHubInstallationId: string) => instance.get( `/rest/devinfo/0.10/existsByProperties?installationId=${gitHubInstallationId}` ), delete: (gitHubInstallationId: string) => instance.delete( `/rest/devinfo/0.10/bulkByProperties?installationId=${gitHubInstallationId}` ) }, pullRequest: { delete: (repositoryId: string, pullRequestId: string) => instance.delete( "/rest/devinfo/0.10/repository/:repositoryId/pull_request/:pullRequestId", { urlParams: { _updateSequenceId: Date.now().toString(), repositoryId, pullRequestId } } ) }, repository: { get: (repositoryId: string) => instance.get("/rest/devinfo/0.10/repository/:repositoryId", { urlParams: { repositoryId } }), delete: (repositoryId: string) => instance.delete("/rest/devinfo/0.10/repository/:repositoryId", { urlParams: { _updateSequenceId: Date.now().toString(), repositoryId } }), update: async (data, options?: { preventTransitions: boolean }) => { dedupIssueKeys(data); if ( !withinIssueKeyLimit(data.commits) || !withinIssueKeyLimit(data.branches) ) { logger.warn({ truncatedCommits: getTruncatedIssuekeys(data.commits), truncatedBranches: getTruncatedIssuekeys(data.branches) }, issueKeyLimitWarning); truncateIssueKeys(data); const subscription = await Subscription.getSingleInstallation( jiraHost, gitHubInstallationId ); await subscription?.update({ syncWarning: issueKeyLimitWarning }); } return await batchedBulkUpdate( data, instance, gitHubInstallationId, logger, options ); } } }, workflow: { submit: async (data) => { updateIssueKeysFor(data.builds, dedup); if (!withinIssueKeyLimit(data.builds)) { logger.warn({ truncatedBuilds: getTruncatedIssuekeys(data.builds) }, issueKeyLimitWarning); updateIssueKeysFor(data.builds, truncate); const subscription = await Subscription.getSingleInstallation(jiraHost, gitHubInstallationId); await subscription?.update({ syncWarning: issueKeyLimitWarning }); } const payload = { builds: data.builds, properties: { gitHubInstallationId }, providerMetadata: { product: data.product } }; logger?.debug(`Sending builds payload to jira. Payload: ${payload}`); logger?.info("Sending builds payload to jira."); return await instance.post("/rest/builds/0.1/bulk", payload); } }, deployment: { submit: async (data): Promise<DeploymentsResult> => { updateIssueKeysFor(data.deployments, dedup); if (!withinIssueKeyLimit(data.deployments)) { logger.warn({ truncatedDeployments: getTruncatedIssuekeys(data.deployments) }, issueKeyLimitWarning); updateIssueKeysFor(data.deployments, truncate); const subscription = await Subscription.getSingleInstallation(jiraHost, gitHubInstallationId); await subscription?.update({ syncWarning: issueKeyLimitWarning }); } const payload = { deployments: data.deployments, properties: { gitHubInstallationId } }; logger?.debug(`Sending deployments payload to jira. Payload: ${payload}`); logger?.info("Sending deployments payload to jira."); const response: AxiosResponse = await instance.post("/rest/deployments/0.1/bulk", payload); return { status: response.status, rejectedDeployments: response.data?.rejectedDeployments }; } } }; return client; } export default async ( jiraHost: string, gitHubInstallationId: number, logger?: Logger ) => { return getJiraClient(jiraHost, gitHubInstallationId, logger); }; /** * Splits commits in data payload into chunks of 400 and makes separate requests * to avoid Jira API limit */ const batchedBulkUpdate = async ( data, instance: AxiosInstance, installationId: number, logger?: Logger, options?: { preventTransitions: boolean } ) => { const dedupedCommits = dedupCommits(data.commits); // Initialize with an empty chunk of commits so we still process the request if there are no commits in the payload const commitChunks: JiraCommit[][] = []; do { commitChunks.push(dedupedCommits.splice(0, 400)); } while (dedupedCommits.length); const batchedUpdates = commitChunks.map((commitChunk) => { if (commitChunk.length) { data.commits = commitChunk; } const body = { preventTransitions: options?.preventTransitions || false, repositories: [data], properties: { installationId } }; return instance.post("/rest/devinfo/0.10/bulk", body).catch((err) => { logger?.error({ ...err, body, data }, "Jira Client Error: Cannot update Repository"); return Promise.reject(err); }); }); return Promise.all(batchedUpdates); }; /** * Returns if the max length of the issue * key field is within the limit */ const withinIssueKeyLimit = (resources: { issueKeys: string[] }[]): boolean => { if (!resources) return true; const issueKeyCounts = resources.map((resource) => resource.issueKeys.length); return Math.max(...issueKeyCounts) <= ISSUE_KEY_API_LIMIT; }; /** * Deduplicates commits by ID field for a repository payload */ const dedupCommits = (commits: JiraCommit[] = []): JiraCommit[] => commits.filter( (obj, pos, arr) => arr.map((mapCommit) => mapCommit.id).indexOf(obj.id) === pos ); /** * Deduplicates issueKeys field for branches and commits */ const dedupIssueKeys = (repositoryObj) => { updateRepositoryIssueKeys(repositoryObj, dedup); }; /** * Truncates branches and commits to first 100 issue keys for branch or commit */ const truncateIssueKeys = (repositoryObj) => { updateRepositoryIssueKeys(repositoryObj, truncate); }; interface IssueKeyObject { issueKeys?: string[] } export const getTruncatedIssuekeys = (data: IssueKeyObject[] = []): IssueKeyObject[] => data.reduce((acc:IssueKeyObject[], value:IssueKeyObject) => { // Filter out anything that doesn't have issue keys or are not over the limit if(value.issueKeys && value.issueKeys.length > ISSUE_KEY_API_LIMIT) { // Create copy of object and add the issue keys that are truncated acc.push({ ...value, issueKeys: value.issueKeys.slice(ISSUE_KEY_API_LIMIT) }); } return acc; }, []); /** * Runs a mutating function on all branches and commits * with issue keys in a Jira Repository object */ const updateRepositoryIssueKeys = (repositoryObj, mutatingFunc) => { if (repositoryObj.commits) { repositoryObj.commits = updateIssueKeysFor( repositoryObj.commits, mutatingFunc ); } if (repositoryObj.branches) { repositoryObj.branches = updateIssueKeysFor( repositoryObj.branches, mutatingFunc ); repositoryObj.branches.forEach((branch) => { if (branch.lastCommit) { branch.lastCommit = updateIssueKeysFor( [branch.lastCommit], mutatingFunc )[0]; } }); } }; /** * Runs the mutatingFunc on the issue keys field for each branch or commit */ const updateIssueKeysFor = (resources, mutatingFunc) => { resources.forEach((resource) => { resource.issueKeys = mutatingFunc(resource.issueKeys); }); return resources; }; /** * Deduplicates elements in an array */ const dedup = (array) => [...new Set(array)]; /** * Truncates to 100 elements in an array */ const truncate = (array) => array.slice(0, ISSUE_KEY_API_LIMIT);
the_stack
import * as d3Array from 'd3-array'; import * as d3Scale from 'd3-scale'; const d3 = { ...d3Array, ...d3Scale, }; import { Unit } from '../definitions'; import {Plot} from '../charts/tau.plot'; interface JSONSelector { type: string; isLeaf: boolean; isLeafParent: boolean; } export function traverseJSON( srcObject, byProperty: string, fnSelectorPredicates: (obj) => JSONSelector, funcTransformRules: (selector: JSONSelector, obj) => any) { var rootRef = funcTransformRules(fnSelectorPredicates(srcObject), srcObject); (rootRef[byProperty] || []).forEach((unit) => traverseJSON( unit, byProperty, fnSelectorPredicates, funcTransformRules) ); return rootRef; } export function traverseSpec( root: Unit, enterFn: (node: Unit, level?: number) => any, exitFn: (node: Unit, level?: number) => any, level = 0 ) { var shouldContinue = enterFn(root, level); if (shouldContinue) { (root.units || []).map((rect) => traverseSpec(rect, enterFn, exitFn, level + 1)); } exitFn(root, level); } var deepClone = (function () { // clone objects, skip other types. function clone(target) { if (typeof target == 'object') { return JSON.parse(JSON.stringify(target)); } else { return target; } } // Deep Copy var deepCopiers = []; function DeepCopier(config) { for (var key in config) { this[key] = config[key]; } } DeepCopier.prototype = { constructor: DeepCopier, // determines if this DeepCopier can handle the given object. canCopy: function (source) { // eslint-disable-line return false; }, // starts the deep copying process by creating the copy object. You // can initialize any properties you want, but you can't call recursively // into the DeeopCopyAlgorithm. create: function (source) { // eslint-disable-line }, // Completes the deep copy of the source object by populating any properties // that need to be recursively deep copied. You can do this by using the // provided deepCopyAlgorithm instance's deepCopy() method. This will handle // cyclic references for objects already deepCopied, including the source object // itself. The "result" passed in is the object returned from create(). populate: function (deepCopyAlgorithm, source, result) { // eslint-disable-line } }; function DeepCopyAlgorithm() { // copiedObjects keeps track of objects already copied by this // deepCopy operation, so we can correctly handle cyclic references. this.copiedObjects = []; var thisPass = this; this.recursiveDeepCopy = function (source) { return thisPass.deepCopy(source); }; this.depth = 0; } DeepCopyAlgorithm.prototype = { constructor: DeepCopyAlgorithm, maxDepth: 256, // add an object to the cache. No attempt is made to filter duplicates; // we always check getCachedResult() before calling it. cacheResult: function (source, result) { this.copiedObjects.push([source, result]); }, // Returns the cached copy of a given object, or undefined if it's an // object we haven't seen before. getCachedResult: function (source) { var copiedObjects = this.copiedObjects; var length = copiedObjects.length; for (var i = 0; i < length; i++) { if (copiedObjects[i][0] === source) { return copiedObjects[i][1]; } } return undefined; }, // deepCopy handles the simple cases itself: non-objects and object's we've seen before. // For complex cases, it first identifies an appropriate DeepCopier, then calls // applyDeepCopier() to delegate the details of copying the object to that DeepCopier. deepCopy: function (source) { // null is a special case: it's the only value of type 'object' without properties. if (source === null) { return null; } // All non-objects use value semantics and don't need explict copying. if (typeof source !== 'object') { return source; } var cachedResult = this.getCachedResult(source); // we've already seen this object during this deep copy operation // so can immediately return the result. This preserves the cyclic // reference structure and protects us from infinite recursion. if (cachedResult) { return cachedResult; } // objects may need special handling depending on their class. There is // a class of handlers call "DeepCopiers" that know how to copy certain // objects. There is also a final, generic deep copier that can handle any object. for (var i = 0; i < deepCopiers.length; i++) { var deepCopier = deepCopiers[i]; if (deepCopier.canCopy(source)) { return this.applyDeepCopier(deepCopier, source); } } // the generic copier can handle anything, so we should never reach this line. throw new Error('no DeepCopier is able to copy ' + source); }, // once we've identified which DeepCopier to use, we need to call it in a very // particular order: create, cache, populate. This is the key to detecting cycles. // We also keep track of recursion depth when calling the potentially recursive // populate(): this is a fail-fast to prevent an infinite loop from consuming all // available memory and crashing or slowing down the browser. applyDeepCopier: function (deepCopier, source) { // Start by creating a stub object that represents the copy. var result = deepCopier.create(source); // we now know the deep copy of source should always be result, so if we encounter // source again during this deep copy we can immediately use result instead of // descending into it recursively. this.cacheResult(source, result); // only DeepCopier::populate() can recursively deep copy. So, to keep track // of recursion depth, we increment this shared counter before calling it, // and decrement it afterwards. this.depth++; if (this.depth > this.maxDepth) { throw new Error('Exceeded max recursion depth in deep copy.'); } // It's now safe to let the deepCopier recursively deep copy its properties. deepCopier.populate(this.recursiveDeepCopy, source, result); this.depth--; return result; } }; // entry point for deep copy. // source is the object to be deep copied. // maxDepth is an optional recursion limit. Defaults to 256. function deepCopy(source, maxDepth?) { var deepCopyAlgorithm = new DeepCopyAlgorithm(); if (maxDepth) { deepCopyAlgorithm.maxDepth = maxDepth; } return deepCopyAlgorithm.deepCopy(source); } // publicly expose the DeepCopier class. (<any>deepCopy).DeepCopier = DeepCopier; // publicly expose the list of deepCopiers. (<any>deepCopy).deepCopiers = deepCopiers; // make deepCopy() extensible by allowing others to // register their own custom DeepCopiers. (<any>deepCopy).register = function (deepCopier) { if (!(deepCopier instanceof DeepCopier)) { deepCopier = new DeepCopier(deepCopier); } deepCopiers.unshift(deepCopier); }; // Generic Object copier // the ultimate fallback DeepCopier, which tries to handle the generic case. This // should work for base Objects and many user-defined classes. (<any>deepCopy).register({ canCopy: function () { return true; }, create: function (source) { if (source instanceof source.constructor) { return clone(source.constructor.prototype); } else { return {}; } }, populate: function (deepCopy, source, result) { for (var key in source) { if (source.hasOwnProperty(key)) { result[key] = deepCopy(source[key]); } } return result; } }); // Array copier (<any>deepCopy).register({ canCopy: function (source) { return (source instanceof Array); }, create: function (source) { return new source.constructor(); }, populate: function (deepCopy, source, result) { for (var i = 0; i < source.length; i++) { result.push(deepCopy(source[i])); } return result; } }); // Date copier (<any>deepCopy).register({ canCopy: function (source) { return (source instanceof Date); }, create: function (source) { return new Date(source); } }); return deepCopy; })(); var testColorCode = ((x) => (/^(#|rgb\(|rgba\()/.test(x))); // TODO Remove this configs and its associated methods // which are just for templating in some plugins var noMatch = /(.)^/; let map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&#x27;', '`': '&#x60;' }; let escapes = { '\'': '\'', '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; let escaper = /\\|'|\r|\n|\u2028|\u2029/g; let source = '(?:' + Object.keys(map).join('|') + ')'; let testRegexp = RegExp(source); let replaceRegexp = RegExp(source, 'g'); let templateSettings = { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g, escape: /<%-([\s\S]+?)%>/g }; export function clone<T>(obj: T): T { return deepClone(obj); } export function isDate(obj) { return obj instanceof Date && !isNaN(Number(obj)); } export function isObject(obj) { return obj != null && typeof obj === 'object'; } export function niceZeroBased(domain: number[]) { var m = 10; var low = parseFloat(Math.min(...domain).toFixed(15)); var top = parseFloat(Math.max(...domain).toFixed(15)); if (low === top) { let k = (top >= 0) ? -1 : 1; let d = (top || 1); top = top - k * d / m; } // include 0 by default low = Math.min(0, low); top = Math.max(0, top); var extent = [low, top]; var span = extent[1] - extent[0]; var step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)); var err = m / span * step; var correction = [ [0.15, 10], [0.35, 5], [0.75, 2], [1.00, 1], [2.00, 1] ]; var i = -1; /*eslint-disable */ while (err > correction[++i][0]) { }// jscs:ignore disallowEmptyBlocks /*eslint-enable */ step *= correction[i][1]; extent[0] = Math.floor(extent[0] / step) * step; extent[1] = Math.ceil(extent[1] / step) * step; var deltaLow = low - extent[0]; var deltaTop = extent[1] - top; var limit = (step / 2); if (low < 0) { var koeffLow = (deltaLow >= limit) ? -deltaLow : 0; extent[0] = (extent[0] - koeffLow); } if (top > 0) { var koeffTop = (deltaTop >= limit) ? -deltaTop : 0; extent[1] = extent[1] + koeffTop; } return [ parseFloat(extent[0].toFixed(15)), parseFloat(extent[1].toFixed(15)) ]; } export function niceTimeDomain(domain: Date[], niceIntervalFn: d3.CountableTimeInterval, {utc} = {utc: false}) { var [low, top] = (d3.extent(domain) as [Date, Date]); var span = (+top - +low); var d3TimeScale = (utc ? d3.scaleUtc : d3.scaleTime); if (span === 0) { var oneDay = 24 * 60 * 60 * 1000; low = new Date(low.getTime() - oneDay); top = new Date(top.getTime() + oneDay); return d3TimeScale().domain([low, top]).nice(niceIntervalFn).domain(); } var niceScale = d3TimeScale().domain([low, top]).nice(niceIntervalFn); if (niceIntervalFn) { return niceScale.domain(); } var [niceLow, niceTop] = d3TimeScale().domain([low, top]).nice(niceIntervalFn).domain(); var ticks = niceScale.ticks(); var last = ticks.length - 1; if ((+low - +niceLow) / (+ticks[1] - +niceLow) < 0.5) { low = niceLow; } if ((+niceTop - +top) / (+niceTop - +ticks[last - 1]) < 0.5) { top = niceTop; } return [low, top]; } var hashGen = 0; var hashMap: {[key: string]: string} = {}; export function generateHash(str: string) { var r = btoa(encodeURIComponent(str)).replace(/=/g, '_'); if (!hashMap.hasOwnProperty(r)) { hashMap[r] = (`H${++hashGen}`); } return hashMap[r]; } export function generateRatioFunction(dimPropName: string, paramsList: string[], chartInstanceRef: Plot) { var unify = (v) => isDate(v) ? v.getTime() : v; var dataNewSnap = 0; var dataPrevRef = null; var xHash = memoize( (data: any[], keys: string[]) => { return unique( data.map((row) => (keys.reduce((r, k) => (r.concat(unify(row[k]))), []))), (t) => JSON.stringify(t)) .reduce((memo, t) => { var k = t[0]; memo[k] = memo[k] || 0; memo[k] += 1; return memo; }, {}); }, (data, keys) => { let seed = (dataPrevRef === data) ? dataNewSnap : (++dataNewSnap); dataPrevRef = data; return `${keys.join('')}-${seed}`; }); return (key: string, size: number, varSet: any[]) => { var facetSize = varSet.length; var chartSpec = chartInstanceRef.getSpec(); var data = chartSpec.sources['/'].data; var level2Guide = chartSpec.unit.units[0].guide || {}; level2Guide.padding = level2Guide.padding || {l: 0, r: 0, t: 0, b: 0}; var pad = 0; if (dimPropName === 'x') { pad = level2Guide.padding.l + level2Guide.padding.r; } else if (dimPropName === 'y') { pad = level2Guide.padding.t + level2Guide.padding.b; } var xTotal = (keys: string[]) => { var arr = xHash(data, keys); return Object.keys(arr).reduce((sum, k) => (sum + arr[k]), 0); }; var xPart = ((keys: string[], k: string) => (xHash(data, keys)[k])); var totalItems = xTotal(paramsList); var tickPxSize = (size - (facetSize * pad)) / totalItems; var countOfTicksInTheFacet = xPart(paramsList, key); return (countOfTicksInTheFacet * tickPxSize + pad) / size; }; } export function isSpecRectCoordsOnly(root: Unit) { var isApplicable = true; try { traverseSpec( (root), (unit) => { if ((unit.type.indexOf('COORDS.') === 0) && (unit.type !== 'COORDS.RECT')) { throw new Error('Not applicable'); } }, (unit) => (unit) ); } catch (e) { if (e.message === 'Not applicable') { isApplicable = false; } } return isApplicable; } export function throttleLastEvent( last: {e?: string, ts?: number}, eventType: string, handler: (...args) => void, limitFromPrev: 'requestAnimationFrame' | number = 0 ) { if (limitFromPrev === 'requestAnimationFrame') { var frameRequested = false; return function (...args) { if (!frameRequested) { requestAnimationFrame(() => { frameRequested = false; }); // NOTE: Have to call sync cause // D3 event info disappears later. handler.apply(this, args); frameRequested = true; } last.e = eventType; last.ts = Date.now(); }; } return function (...args) { var curr = {e: eventType, ts: Date.now()}; var diff = ((last.e && (last.e === curr.e)) ? (curr.ts - last.ts) : (limitFromPrev)); if (diff >= limitFromPrev) { handler.apply(this, args); } last.e = curr.e; last.ts = curr.ts; }; } export function splitEvenly(domain: [number, number], parts: number): number[] { var min = domain[0]; var max = domain[1]; var segment = ((max - min) / (parts - 1)); var chunks = parts >= 2 ? range(parts - 2).map((n) => (min + segment * (n + 1))) : []; return [min, ...chunks, max]; } export function extRGBColor(x: string) { return (testColorCode(x) ? x : ''); } export function extCSSClass(x: string) { return (testColorCode(x) ? '' : x); } export function toRadian(degree: number) { return (degree / 180) * Math.PI; } export function normalizeAngle(angle: number) { if (Math.abs(angle) >= 360) { angle = (angle % 360); } if (angle < 0) { angle = (360 + angle); } return angle; } export function range(start: number, end?: number) { if (arguments.length === 1) { end = start; start = 0; } const arr: number[] = []; for (let i = start; i < end; i++) { arr.push(i); } return arr; } export function hasXOverflow(x: number, size: number, angle: number, maxX: number) { var allowedOverflow = 100; var direction = angle === 90 ? -1 : 1; return (x + size * direction) - maxX > allowedOverflow; } export function hasYOverflow(y: number, size: number, angle: number, maxY: number) { var allowedOverflow = 20; var direction = angle === -90 ? -1 : 1; return (y + size * direction) - maxY > allowedOverflow; } export function flatten<T>(array: Array<T | T[]>): T[]; export function flatten(array: any): any[] { if (!Array.isArray(array)) { return array; } return [].concat(...array.map(x => flatten(x))); } export function unique<T>(array: T[], func?: (T) => string): T[] { var hash = {}; var result = []; var len = array.length; var hasher = func || ((x) => String(x)); for (var i = 0; i < len; ++i) { var item = array[i]; var key = hasher(item); if (!hash.hasOwnProperty(key)) { hash[key] = true; result.push(item); } } return result; } export function groupBy<T>(array: T[], func?: (item: T) => string): {[key: string]: T[]} { return array.reduce((obj, v) => { var group = func(v); obj[group] = obj[group] || []; obj[group].push(v); return obj; }, {}); } export function union<T>(arr1: T[], arr2: T[]): T[] { return unique(arr1.concat(arr2)); } export function intersection<T>(arr1: T[], arr2: T[]) { return arr1.filter(x => arr2.indexOf(x) !== -1); } export function defaults<T, K, V, Q, R>(obj: T, obj1?: K): T & K; export function defaults<T, K, V, Q, R>(obj: T, obj1?: K, obj2?: V): T & K & V; export function defaults<T, K, V, Q, R>(obj: T, obj1?: K, obj2?: V, obj3?: Q): T & K & V & Q; export function defaults<T, K, V, Q, R>(obj: T, obj1?: K, obj2?: V, obj3?: Q, obj4?: R): T & K & V & Q & R; export function defaults<T>(obj: T, ...defaultObjs: T[]): T { var length = defaultObjs.length; if (length === 0 || !obj) { return obj; } for (var index = 0; index < length; index++) { var source = defaultObjs[index], keys = isObject(source) ? Object.keys(source) : [], l = keys.length; for (var i = 0; i < l; i++) { var key = keys[i]; if (obj[key] === undefined) { obj[key] = source[key]; } } } return obj; } export function omit<T>(obj: T, ...props: string[]): T { let newObj = Object.assign({}, obj); props.forEach((prop) => { delete newObj[prop]; }); return newObj; } export function memoize<R>(func: () => R, hasher?: () => string): () => R; export function memoize<A, R>(func: (a: A) => R, hasher?: (a: A) => string): (a: A) => R; export function memoize<A, B, R>(func: (a: A, b: B) => R, hasher?: (a: A, b: B) => string): (a: A, b: B) => R; export function memoize<A, B, C, R>( func: (a: A, b: B, c: C) => R, hasher?: (a: A, b: B, c: C) => string ): (a: A, b: B, c: C) => R; export function memoize<R>( func: (...args: any[]) => R, hasher?: (...args: any[]) => string ): (...args: any[]) => R; export function memoize(func, hasher) { const memoize = <any>function (key) { const cache = memoize.cache; const address = String(hasher ? hasher.apply(this, arguments) : key); if (!cache.hasOwnProperty(address)) { cache[address] = func.apply(this, arguments); } return cache[address]; }; memoize.cache = {}; return memoize; } export function createMultiSorter<T>(...sorters: ((a: T, b: T) => number)[]) { return (a, b) => { var result = 0; sorters.every((s) => { result = s(a, b); return (result === 0); }); return result; }; } // TODO Remove this methods and its associated configs // which are just for templating in some plugins export function pick(object: Object, ...props: string[]): Object { var result = {}; if (object == null) { return result; } return props.reduce((result, prop) => { let value = object[prop]; if (value) { result[prop] = value; } return result; }, {}); } export function escape(string: string) { string = string == null ? '' : String(string); return testRegexp.test(string) ? string.replace(replaceRegexp, match => map[match]) : string; } export function template(text: string, settings?, oldSettings?): (data?) => string { if (!settings && oldSettings) { settings = oldSettings; } settings = defaults({}, settings, templateSettings); var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); var index = 0; var source = '__p+=\''; text.replace(matcher, function (match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escaper, match => '\\' + escapes[match]); index = offset + match.length; if (escape) { source += '\'+\n((__t=(' + escape + '))==null?\'\':utils.escape(__t))+\n\''; } else if (interpolate) { source += '\'+\n((__t=(' + interpolate + '))==null?\'\':__t)+\n\''; } else if (evaluate) { source += '\';\n' + evaluate + '\n__p+=\''; } return match; }); source += '\';\n'; if (!settings.variable) { source = 'with(obj||{}){\n' + source + '}\n'; } source = 'var __t,__p=\'\',__j=Array.prototype.join,' + 'print=function(){__p+=__j.call(arguments,\'\');};\n' + source + 'return __p;\n'; try { var render = new Function(settings.variable || 'obj', source); } catch (e) { e.source = source; throw e; } var template: any = function (data) { return render.call(this, data); }; var argument = settings.variable || 'obj'; template.source = 'function(' + argument + '){\n' + source + '}'; return template; } export function escapeHtml(x: string) { return String(x) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#039;'); } const XML_INDENT = ' '; const XML_ATTR_WRAP = 32; const VOID_TAGS = [ 'img', 'input', 'br', 'embed', 'link', 'meta', 'area', 'base', 'basefont', 'bgsound', 'col', 'command', 'frame', 'hr', 'image', 'isindex', 'keygen', 'menuitem', 'nextid', 'param', 'source', 'track', 'wbr', 'circle', 'ellipse', 'line', 'path', 'polygon', 'rect' ].reduce((map, tag) => (map[tag] = true, map), {} as {[tag: string]: boolean}); type StringOrArray = (string | string[]); export function xml(tag: string, ...children: StringOrArray[]): string; export function xml(tag: string, attrs: {[attr: string]: any}, ...children: StringOrArray[]): string; export function xml(tag: string) { var childrenArgIndex = 2; var attrs = arguments[1]; if (typeof arguments[1] !== 'object' || Array.isArray(arguments[1])) { childrenArgIndex = 1; attrs = {}; } const children = flatten(Array.prototype.slice.call(arguments, childrenArgIndex) as StringOrArray[]); const hasSingleTextChild = (children.length === 1 && children[0].trim()[0] !== '<'); const isVoidTag = VOID_TAGS[tag]; if (isVoidTag && children.length > 0) { throw new Error(`Tag "${tag}" is void but content is assigned to it`); } const tagBeginning = `<${tag}`; var attrsString = Object.keys(attrs).map(function (key) { return ` ${key}="${attrs[key]}"`; }).join(''); if (attrsString.length > XML_ATTR_WRAP) { attrsString = Object.keys(attrs).map(function (key) { return `\n${XML_INDENT}${key}="${attrs[key]}"`; }).join(''); } const childrenString = (hasSingleTextChild ? children[0] : ('\n' + children .map((c) => { const content = String(c); return content .split('\n') .map((line) => `${XML_INDENT}${line}`) .join('\n'); }) .join('\n') + '\n') ); const tagEnding = (isVoidTag ? '/>' : (`>${childrenString}</${tag}>`)); return `${tagBeginning}${attrsString}${tagEnding}`; } interface NextObj<T> { then<K>(fn: (x: T) => K): NextObj<K>; result(): T; } export function take<T>(src?: T) { var result: any = src; const obj: NextObj<T> = { then<K>(fn: (x: T) => K) { result = fn(result); return (<any>obj) as NextObj<K>; }, result() { return result as T; }, }; return obj; } import {GenericCartesian} from '../elements/element.generic.cartesian'; const chartElements = [ GenericCartesian ]; export function isChartElement(element) { return chartElements.some((E) => element instanceof E); } export function isFacetUnit(unit: Unit) { return (unit.units || []).some((c) => c.hasOwnProperty('units')); }
the_stack
import {Settings} from 'luxon'; import {applyRules} from 'utils/validate'; import {readFile} from 'fs/promises'; import {join} from 'path'; import rulesJson from '../../__mocks__/ruleset.json'; const rules = rulesJson as any; describe('RuleInterpretor', () => { // Verified test('One dose, valid - oneDoseValid', () => { const qrCode = require('../../__mocks__/qr-codes/oneDoseValid.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); test('Two dose, valid - twoDoseValidMix', () => { let qrCode = require('../../__mocks__/qr-codes/twoDoseValidMix.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); test('Two dose, valid - twoDoseValidModerna', () => { const qrCode = require('../../__mocks__/qr-codes/twoDoseValidModerna.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); test('Two dose, valid - twoDoseValidPfizer', () => { const qrCode = require('../../__mocks__/qr-codes/twoDoseValidPfizer.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); test('Two dose, valid - twoDoseValidAstrazeneca', () => { const qrCode = require('../../__mocks__/qr-codes/twoDoseValidAstrazeneca.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); test('Two dose, valid - twoDoseValidOneNonHCOnePfizer', () => { const qrCode = require('../../__mocks__/qr-codes/twoDoseValidOneNonHCOnePfizer.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); test('Three dose, valid - threeDoseAllValid', () => { const qrCode = require('../../__mocks__/qr-codes/threeDoseAllValid.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); test('Two dose, valid - threeDoseAllNonHC', () => { const qrCode = require('../../__mocks__/qr-codes/threeDoseAllNonHC.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); test('Two dose, valid - threeDoseTwoValidOneNonHC', () => { const qrCode = require('../../__mocks__/qr-codes/threeDoseTwoValidOneNonHC.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); test('Two dose, valid - threeDoseOneValidTwoNonHC', () => { const qrCode = require('../../__mocks__/qr-codes/threeDoseOneValidTwoNonHC.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); // Not Verified test('One dose, invalid - oneDoseInvalid', () => { const qrCode = require('../../__mocks__/qr-codes/oneDoseInvalid.json'); expect(applyRules(rules, qrCode)).toBeFalsy(); }); test('One dose, valid normally but actually invalid - less than 14 days', () => { const oldNow = Settings.now; Settings.now = () => new Date(2021, 2, 16).valueOf(); // March 16, 2021 - on the 14th day from March 2, 2021 when this example dose was administered try { const qrCode = require('../../__mocks__/qr-codes/oneDoseValid.json'); expect(applyRules(rules, qrCode)).toBe(false); } finally { Settings.now = oldNow; } }); test('One dose, valid normally but actually invalid - it was given in the future', () => { const oldNow = Settings.now; Settings.now = () => new Date(2021, 1, 2).valueOf(); // invalid, in the future - "today" is February 2, 2021 but the vaccine was administered on March 2, 2021 try { const qrCode = require('../../__mocks__/qr-codes/oneDoseValid.json'); expect(applyRules(rules, qrCode)).toBe(false); } finally { Settings.now = oldNow; } }); test('One dose, valid normally - after 14 days', () => { const oldNow = Settings.now; Settings.now = () => new Date(2021, 2, 17).valueOf(); // March 17, 2021 - on the 15th day from March 2, 2021 when this example dose was administered try { const qrCode = require('../../__mocks__/qr-codes/oneDoseValid.json'); expect(applyRules(rules, qrCode)).toBe(true); } finally { Settings.now = oldNow; } }); test('Two dose, invalid - twoDoseInvalidTwo', () => { const qrCode = require('../../__mocks__/qr-codes/twoDoseInvalidTwo.json'); expect(applyRules(rules, qrCode)).toBeFalsy(); }); test('Two dose, invalid - twoDoseInvalidOne', () => { const qrCode = require('../../__mocks__/qr-codes/twoDoseInvalidOne.json'); expect(applyRules(rules, qrCode)).toBeFalsy(); }); test('Two dose, invalid - twoDoseValidOnePfizerOneNonHC', () => { const qrCode = require('../../__mocks__/qr-codes/twoDoseValidOnePfizerOneNonHC.json'); expect(applyRules(rules, qrCode)).toBeFalsy(); }); test('Three dose, invalid - threeDoseAllInvalid', () => { const qrCode = require('../../__mocks__/qr-codes/threeDoseAllInvalid.json'); expect(applyRules(rules, qrCode)).toBeFalsy(); }); test('Two dose, valid - threeDoseInvalidTwoOnePfizer', () => { const qrCode = require('../../__mocks__/qr-codes/threeDoseInvalidTwoOnePfizer.json'); expect(applyRules(rules, qrCode)).toBeFalsy(); }); test('Two dose, valid - threeDoseInvalidOneTwoNonHC', () => { const qrCode = require('../../__mocks__/qr-codes/threeDoseInvalidOneTwoNonHC.json'); expect(applyRules(rules, qrCode)).toBeFalsy(); }); test('One dose, valid - missingCVX', () => { const qrCode = require('../../__mocks__/qr-codes/missingCVX.json'); expect(applyRules(rules, qrCode)).toBeFalsy(); }); test('One dose, valid - misplacedCVX', () => { const qrCode = require('../../__mocks__/qr-codes/misplacedCVX.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); // Snomed SCT test // Missing CVX Only valid SCT 1 dose test('One dose, valid - oneDoseValidSCTMissingCVX', () => { const qrCode = require('../../__mocks__/qr-codes/oneDoseValidSCTMissingCVX.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); // Wrong CVX Only valid SCT 1 dose test('One dose, valid - oneDoseValidSCTWrongCVX', () => { const qrCode = require('../../__mocks__/qr-codes/oneDoseValidSCTWrongCVX.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); // Missing CVX Only valid SCT 2 dose test('Two dose, valid - twoDoseValidMixMissingCVX', () => { const qrCode = require('../../__mocks__/qr-codes/twoDoseValidMixMissingCVX.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); // Wrong CVX Only valid SCT 2 dose test('Two dose, valid - twoDoseValidMixWrongCVX', () => { const qrCode = require('../../__mocks__/qr-codes/twoDoseValidMixWrongCVX.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); // 3 NON HC ONLY SCT test('Three dose, valid - threeDoseAllNonHCMissingCVX', () => { const qrCode = require('../../__mocks__/qr-codes/threeDoseAllNonHCMissingCVX.json'); expect(applyRules(rules, qrCode)).toBeTruthy(); }); test('Vaccine exemption with expiry, valid - within exemption expiry', async () => { const oldNow = Settings.now; Settings.now = () => new Date(2022, 2, 7).valueOf(); // March 7, 2022. try { const qrCode = JSON.parse( await readFile( join(__dirname, '../../__mocks__/qr-codes/vaccineExemption.json'), {encoding: 'utf-8'}, ), ); const condition = qrCode.vc.credentialSubject.fhirBundle.entry[2].resource; condition.recordedDate = '2021-12-07'; condition.abatementDateTime = '2022-06-07'; expect(applyRules(rules, qrCode)).toBe(true); } finally { Settings.now = oldNow; } }); test('Vaccine exemption with expiry, invalid - invalid resourceType', async () => { const oldNow = Settings.now; Settings.now = () => new Date(2022, 2, 7).valueOf(); // March 7, 2022. try { const qrCode = JSON.parse( await readFile( join(__dirname, '../../__mocks__/qr-codes/vaccineExemption.json'), {encoding: 'utf-8'}, ), ); const condition = qrCode.vc.credentialSubject.fhirBundle.entry[2].resource; condition.recordedDate = '2021-12-07'; condition.abatementDateTime = '2022-06-07'; condition.resourceType = 'NotACondition'; expect(applyRules(rules, qrCode)).toBe(false); } finally { Settings.now = oldNow; } }); test('Vaccine exemption with expiry, invalid - invalid condition category coding system', async () => { const oldNow = Settings.now; Settings.now = () => new Date(2022, 2, 7).valueOf(); // March 7, 2022. try { const qrCode = JSON.parse( await readFile( join(__dirname, '../../__mocks__/qr-codes/vaccineExemption.json'), {encoding: 'utf-8'}, ), ); const condition = qrCode.vc.credentialSubject.fhirBundle.entry[2].resource; condition.recordedDate = '2021-12-07'; condition.abatementDateTime = '2022-06-07'; condition.category[0].coding[0].system = 'https://example.com'; expect(applyRules(rules, qrCode)).toBe(false); } finally { Settings.now = oldNow; } }); test('Vaccine exemption with expiry, invalid - invalid condition category code', async () => { const oldNow = Settings.now; Settings.now = () => new Date(2022, 2, 7).valueOf(); // March 7, 2022. try { const qrCode = JSON.parse( await readFile( join(__dirname, '../../__mocks__/qr-codes/vaccineExemption.json'), {encoding: 'utf-8'}, ), ); const condition = qrCode.vc.credentialSubject.fhirBundle.entry[2].resource; condition.recordedDate = '2021-12-07'; condition.abatementDateTime = '2022-06-07'; condition.category[0].coding[0].code = 'not-a-vaccine-exemption'; expect(applyRules(rules, qrCode)).toBe(false); } finally { Settings.now = oldNow; } }); test('Vaccine exemption with expiry, invalid - on abatement date', async () => { const oldNow = Settings.now; Settings.now = () => new Date(2022, 5, 7).valueOf(); // June 7, 2022. try { const qrCode = JSON.parse( await readFile( join(__dirname, '../../__mocks__/qr-codes/vaccineExemption.json'), {encoding: 'utf-8'}, ), ); const condition = qrCode.vc.credentialSubject.fhirBundle.entry[2].resource; condition.recordedDate = '2021-12-07'; condition.abatementDateTime = '2022-06-07'; expect(applyRules(rules, qrCode)).toBe(false); } finally { Settings.now = oldNow; } }); test('Vaccine exemption with expiry, invalid - after exemption expiry', async () => { const oldNow = Settings.now; Settings.now = () => new Date(2022, 5, 8).valueOf(); // June 8, 2022. try { const qrCode = JSON.parse( await readFile( join(__dirname, '../../__mocks__/qr-codes/vaccineExemption.json'), {encoding: 'utf-8'}, ), ); const condition = qrCode.vc.credentialSubject.fhirBundle.entry[2].resource; condition.recordedDate = '2021-12-07'; condition.abatementDateTime = '2022-06-07'; expect(applyRules(rules, qrCode)).toBe(false); } finally { Settings.now = oldNow; } }); test('Vaccine exemption with short expiry, invalid - within 6 months but after exemption expiry', async () => { const oldNow = Settings.now; Settings.now = () => new Date(2022, 3, 8).valueOf(); // March 8, 2022. try { const qrCode = JSON.parse( await readFile( join(__dirname, '../../__mocks__/qr-codes/vaccineExemption.json'), {encoding: 'utf-8'}, ), ); const condition = qrCode.vc.credentialSubject.fhirBundle.entry[2].resource; condition.recordedDate = '2021-12-07'; condition.abatementDateTime = '2022-03-07'; expect(applyRules(rules, qrCode)).toBe(false); } finally { Settings.now = oldNow; } }); test('Vaccine exemption without expiry, valid - within six months', async () => { const oldNow = Settings.now; Settings.now = () => new Date(2022, 3, 8).valueOf(); // March 8, 2022. try { const qrCode = JSON.parse( await readFile( join(__dirname, '../../__mocks__/qr-codes/vaccineExemption.json'), {encoding: 'utf-8'}, ), ); const condition = qrCode.vc.credentialSubject.fhirBundle.entry[2].resource; condition.recordedDate = '2021-12-07'; delete condition.abatementDateTime; expect(applyRules(rules, qrCode)).toBe(true); } finally { Settings.now = oldNow; } }); test('Vaccine exemption without expiry, invalid - exactly six months later', async () => { const oldNow = Settings.now; Settings.now = () => new Date(2022, 5, 7).valueOf(); // June 7, 2022. try { const qrCode = JSON.parse( await readFile( join(__dirname, '../../__mocks__/qr-codes/vaccineExemption.json'), {encoding: 'utf-8'}, ), ); const condition = qrCode.vc.credentialSubject.fhirBundle.entry[2].resource; condition.recordedDate = '2021-12-07'; delete condition.abatementDateTime; expect(applyRules(rules, qrCode)).toBe(false); } finally { Settings.now = oldNow; } }); test('Vaccine exemption without expiry or recorded date, invalid', async () => { const oldNow = Settings.now; Settings.now = () => new Date(2022, 3, 8).valueOf(); // March 8, 2022. try { const qrCode = JSON.parse( await readFile( join(__dirname, '../../__mocks__/qr-codes/vaccineExemption.json'), {encoding: 'utf-8'}, ), ); const condition = qrCode.vc.credentialSubject.fhirBundle.entry[2].resource; delete condition.recordedDate; delete condition.abatementDateTime; expect(applyRules(rules, qrCode)).toBe(false); } finally { Settings.now = oldNow; } }); test('Vaccine exemption with empty Condition resource, invalid', async () => { const oldNow = Settings.now; Settings.now = () => new Date(2022, 3, 8).valueOf(); // March 8, 2022. try { const qrCode = JSON.parse( await readFile( join(__dirname, '../../__mocks__/qr-codes/vaccineExemption.json'), {encoding: 'utf-8'}, ), ); const entry = qrCode.vc.credentialSubject.fhirBundle.entry[2]; entry.resource = {resourceType: 'Condition'}; expect(applyRules(rules, qrCode)).toBe(false); } finally { Settings.now = oldNow; } }); });
the_stack
import { ethers, network, upgrades, waffle } from "hardhat"; import { BigNumber, Signer } from "ethers"; import chai from "chai"; import { solidity } from "ethereum-waffle"; import "@openzeppelin/test-helpers"; import { MockERC20, MockERC20__factory, MdexRestrictedStrategyPartialCloseLiquidate, MdexRestrictedStrategyPartialCloseLiquidate__factory, WETH, WETH__factory, MdexFactory, MdexRouter, MdexPair, MdexFactory__factory, MdexRouter__factory, Oracle__factory, SwapMining__factory, SwapMining, Oracle, MdexPair__factory, } from "../../../../../typechain"; import { MockMdexWorker__factory } from "../../../../../typechain/factories/MockMdexWorker__factory"; import { MockMdexWorker } from "../../../../../typechain/MockMdexWorker"; import { assertAlmostEqual } from "../../../../helpers/assert"; import { MdxToken } from "../../../../../typechain/MdxToken"; import { MdxToken__factory } from "../../../../../typechain/factories/MdxToken__factory"; import * as TimeHelpers from "../../../../helpers/time"; chai.use(solidity); const { expect } = chai; describe("MdexRestrictedStrategyPartialCloseLiquidate", () => { const FOREVER = "2000000000"; const mdxPerBlock = "51600000000000000000"; /// Mdex-related instance(s) let factory: MdexFactory; let router: MdexRouter; let swapMining: SwapMining; let oracle: Oracle; /// MockMdexWorker-related instance(s) let mockMdexWorker: MockMdexWorker; let mockMdexEvilWorker: MockMdexWorker; /// Token-related instance(s) let mdxToken: MdxToken; let wbnb: WETH; let baseToken: MockERC20; let farmingToken: MockERC20; /// Strategy instance(s) let strat: MdexRestrictedStrategyPartialCloseLiquidate; // Accounts let deployer: Signer; let alice: Signer; let bob: Signer; let deployerAddress: string; let aliceAddress: string; let bobAddress: string; // Contract Signer let baseTokenAsAlice: MockERC20; let baseTokenAsBob: MockERC20; let lpAsAlice: MdexPair; let lpAsBob: MdexPair; let farmingTokenAsAlice: MockERC20; let farmingTokenAsBob: MockERC20; let routerAsAlice: MdexRouter; let routerAsBob: MdexRouter; let stratAsAlice: MdexRestrictedStrategyPartialCloseLiquidate; let stratAsBob: MdexRestrictedStrategyPartialCloseLiquidate; let mockMdexWorkerAsBob: MockMdexWorker; let mockMdexEvilWorkerAsBob: MockMdexWorker; let lp: MdexPair; const setupFullFlowTest = async () => { /// Setup token stuffs const MockERC20 = (await ethers.getContractFactory("MockERC20", deployer)) as MockERC20__factory; baseToken = (await upgrades.deployProxy(MockERC20, ["BTOKEN", "BTOKEN", 18])) as MockERC20; await baseToken.deployed(); await baseToken.mint(await deployer.getAddress(), ethers.utils.parseEther("100")); await baseToken.mint(await alice.getAddress(), ethers.utils.parseEther("100")); await baseToken.mint(await bob.getAddress(), ethers.utils.parseEther("100")); farmingToken = (await upgrades.deployProxy(MockERC20, ["FTOKEN", "FTOKEN", 18])) as MockERC20; await farmingToken.deployed(); await farmingToken.mint(aliceAddress, ethers.utils.parseEther("10")); await farmingToken.mint(bobAddress, ethers.utils.parseEther("10")); const WBNB = (await ethers.getContractFactory("WETH", deployer)) as WETH__factory; wbnb = await WBNB.deploy(); const MdxToken = (await ethers.getContractFactory("MdxToken", deployer)) as MdxToken__factory; mdxToken = await MdxToken.deploy(); await mdxToken.deployed(); await mdxToken.addMinter(await deployer.getAddress()); await mdxToken.mint(await deployer.getAddress(), ethers.utils.parseEther("100")); // Setup Mdex const MdexFactory = (await ethers.getContractFactory("MdexFactory", deployer)) as MdexFactory__factory; factory = await MdexFactory.deploy(await deployer.getAddress()); await factory.deployed(); const MdexRouter = (await ethers.getContractFactory("MdexRouter", deployer)) as MdexRouter__factory; router = await MdexRouter.deploy(factory.address, wbnb.address); await router.deployed(); const Oracle = (await ethers.getContractFactory("Oracle", deployer)) as Oracle__factory; oracle = await Oracle.deploy(factory.address); await oracle.deployed(); // Mdex SwapMinig const blockNumber = await TimeHelpers.latestBlockNumber(); const SwapMining = (await ethers.getContractFactory("SwapMining", deployer)) as SwapMining__factory; swapMining = await SwapMining.deploy( mdxToken.address, factory.address, oracle.address, router.address, farmingToken.address, mdxPerBlock, blockNumber ); await swapMining.deployed(); // set swapMining to router await router.setSwapMining(swapMining.address); /// Setup BTOKEN-FTOKEN pair on Mdex await factory.createPair(farmingToken.address, baseToken.address); lp = MdexPair__factory.connect(await factory.getPair(farmingToken.address, baseToken.address), deployer); await lp.deployed(); await factory.addPair(lp.address); await mdxToken.addMinter(swapMining.address); await swapMining.addPair(100, lp.address, false); await swapMining.addWhitelist(baseToken.address); await swapMining.addWhitelist(farmingToken.address); }; async function fixture() { [deployer, alice, bob] = await ethers.getSigners(); [deployerAddress, aliceAddress, bobAddress] = await Promise.all([ deployer.getAddress(), alice.getAddress(), bob.getAddress(), ]); await setupFullFlowTest(); /// Setup MockMdexWorker const MockMdexWorker = (await ethers.getContractFactory("MockMdexWorker", deployer)) as MockMdexWorker__factory; mockMdexWorker = (await MockMdexWorker.deploy( lp.address, baseToken.address, farmingToken.address )) as MockMdexWorker; await mockMdexWorker.deployed(); mockMdexEvilWorker = (await MockMdexWorker.deploy( lp.address, baseToken.address, farmingToken.address )) as MockMdexWorker; await mockMdexEvilWorker.deployed(); const MdexRestrictedStrategyPartialCloseLiquidate = (await ethers.getContractFactory( "MdexRestrictedStrategyPartialCloseLiquidate", deployer )) as MdexRestrictedStrategyPartialCloseLiquidate__factory; strat = (await upgrades.deployProxy(MdexRestrictedStrategyPartialCloseLiquidate, [ router.address, mdxToken.address, ])) as MdexRestrictedStrategyPartialCloseLiquidate; await strat.deployed(); await strat.setWorkersOk([mockMdexWorker.address], true); // Assign contract signer baseTokenAsAlice = MockERC20__factory.connect(baseToken.address, alice); baseTokenAsBob = MockERC20__factory.connect(baseToken.address, bob); farmingTokenAsAlice = MockERC20__factory.connect(farmingToken.address, alice); farmingTokenAsBob = MockERC20__factory.connect(farmingToken.address, bob); routerAsAlice = MdexRouter__factory.connect(router.address, alice); routerAsBob = MdexRouter__factory.connect(router.address, bob); lpAsAlice = MdexPair__factory.connect(lp.address, alice); lpAsBob = MdexPair__factory.connect(lp.address, bob); stratAsAlice = MdexRestrictedStrategyPartialCloseLiquidate__factory.connect(strat.address, alice); stratAsBob = MdexRestrictedStrategyPartialCloseLiquidate__factory.connect(strat.address, bob); mockMdexWorkerAsBob = MockMdexWorker__factory.connect(mockMdexWorker.address, bob); mockMdexEvilWorkerAsBob = MockMdexWorker__factory.connect(mockMdexEvilWorker.address, bob); // Setting up liquidity // Alice adds 0.1 FTOKEN + 1 BTOKEN await baseTokenAsAlice.approve(router.address, ethers.utils.parseEther("1")); await farmingTokenAsAlice.approve(router.address, ethers.utils.parseEther("0.1")); await routerAsAlice.addLiquidity( baseToken.address, farmingToken.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("0.1"), "0", "0", aliceAddress, FOREVER ); // Bob tries to add 1 FTOKEN + 1 BTOKEN (but obviously can only add 0.1 FTOKEN) await baseTokenAsBob.approve(router.address, ethers.utils.parseEther("1")); await farmingTokenAsBob.approve(router.address, ethers.utils.parseEther("1")); await routerAsBob.addLiquidity( baseToken.address, farmingToken.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("1"), "0", "0", bobAddress, FOREVER ); expect(await baseToken.balanceOf(bobAddress)).to.be.eq(ethers.utils.parseEther("99")); expect(await farmingToken.balanceOf(bobAddress)).to.be.eq(ethers.utils.parseEther("9.9")); expect(await lp.balanceOf(bobAddress)).to.be.eq(ethers.utils.parseEther("0.316227766016837933")); // Set block base fee per gas to 0 await network.provider.send("hardhat_setNextBlockBaseFeePerGas", ["0x0"]); } beforeEach(async () => { await waffle.loadFixture(fixture); }); context("When bad calldata", async () => { it("should revert", async () => { // Bob passes some bad calldata that can't be decoded await expect(stratAsBob.execute(bobAddress, "0", "0x1234")).to.be.reverted; }); }); context("When the setOkWorkers caller is not an owner", async () => { it("should be reverted", async () => { await expect(stratAsBob.setWorkersOk([mockMdexEvilWorkerAsBob.address], true)).to.reverted; }); }); context("When non-worker call the strat", async () => { it("should revert", async () => { await expect( stratAsBob.execute( bobAddress, "0", ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256"], [ethers.utils.parseEther("0.5"), ethers.utils.parseEther("0.5")] ) ) ).to.be.reverted; }); }); context("When caller worker hasn't been whitelisted", async () => { it("should revert as bad worker", async () => { await baseTokenAsBob.transfer(mockMdexEvilWorkerAsBob.address, ethers.utils.parseEther("0.05")); await expect( mockMdexEvilWorkerAsBob.work( 0, bobAddress, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256"], [ethers.utils.parseEther("0.5"), ethers.utils.parseEther("0.5")] ), ] ) ) ).to.be.revertedWith("MdexRestrictedStrategyPartialCloseLiquidate::onlyWhitelistedWorkers:: bad worker"); }); }); context("when revoking whitelist workers", async () => { it("should revert as bad worker", async () => { await strat.setWorkersOk([mockMdexWorker.address], false); await expect( mockMdexWorkerAsBob.work( 0, bobAddress, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256"], [ethers.utils.parseEther("0.5"), ethers.utils.parseEther("0.5")] ), ] ) ) ).to.be.revertedWith("MdexRestrictedStrategyPartialCloseLiquidate::onlyWhitelistedWorkers:: bad worker"); }); }); context("when maxLpToLiquidate >= LPs from worker", async () => { it("should use all LP (fee 20)", async () => { // set lp pair fee await factory.setPairFees(lp.address, 20); // Bob transfer LP to strategy first const bobBTokenBefore = await baseToken.balanceOf(bobAddress); await lpAsBob.transfer(strat.address, ethers.utils.parseEther("0.316227766016837933")); // Bob's position: 0.316227766016837933 LP // lpToLiquidate: Math.min(888, 0.316227766016837933) = 0.316227766016837933 LP (0.1 FTOKEN + 1 FTOKEN) // After execute strategy. The following conditions must be satisfied // - LPs in Strategy contract must be 0 // - Worker should have 0 LP left as all LP is liquidated // - Bob should have: // bobBtokenBefore + 1 BTOKEN + [((0.1*998)*1)/(0.1*1000+(0.1*998))] = 0.499499499499499499 BTOKEN] (from swap 0.1 FTOKEN to BTOKEN) in his account // - BTOKEN in reserve should be 1-0.499499499499499499 = 0.500500500500500501 BTOKEN // - FTOKEN in reserve should be 0.1+0.1 = 0.2 FTOKEN await expect( mockMdexWorkerAsBob.work( 0, bobAddress, ethers.utils.parseEther("0"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [ ethers.utils.parseEther("8888"), ethers.utils.parseEther("0"), ethers.utils.parseEther("1.499499499499499499"), ] ), ] ) ) ) .to.emit(strat, "MdexRestrictedStrategyPartialCloseLiquidateEvent") .withArgs(baseToken.address, farmingToken.address, ethers.utils.parseEther("0.316227766016837933"), "0"); expect(await lp.balanceOf(strat.address), "Strategy should has 0 LP").to.be.eq(ethers.utils.parseEther("0")); expect( await lp.balanceOf(mockMdexWorkerAsBob.address), "Worker should has 0 LP as all LP is liquidated" ).to.be.eq("0"); expect( await baseToken.balanceOf(bobAddress), "Bob's BTOKEN should increase by 1.499499499499499499 BTOKEN" ).to.be.eq( bobBTokenBefore.add(ethers.utils.parseEther("1")).add(ethers.utils.parseEther("0.499499499499499499")) ); expect(await baseToken.balanceOf(lp.address), "FTOKEN-BTOKEN LP should has 0.500500500500500501 BTOKEN").to.be.eq( ethers.utils.parseEther("0.500500500500500501") ); expect(await farmingToken.balanceOf(lp.address), "FTOKEN-BTOKEN LP should as 0.2 FTOKEN").to.be.eq( ethers.utils.parseEther("0.2") ); }); it("should use all LP (fee 25)", async () => { // set lp pair fee await factory.setPairFees(lp.address, 25); // Bob transfer LP to strategy first const bobBTokenBefore = await baseToken.balanceOf(bobAddress); await lpAsBob.transfer(strat.address, ethers.utils.parseEther("0.316227766016837933")); // Bob's position: 0.316227766016837933 LP // lpToLiquidate: Math.min(888, 0.316227766016837933) = 0.316227766016837933 LP (0.1 FTOKEN + 1 FTOKEN) // After execute strategy. The following conditions must be satisfied // - LPs in Strategy contract must be 0 // - Worker should have 0 LP left as all LP is liquidated // - Bob should have: // bobBtokenBefore + 1 BTOKEN + [((0.1*9975)*1)/(0.1*10000+(0.1*9975))] = 0.499374217772215269 BTOKEN] (from swap 0.1 FTOKEN to BTOKEN) in his account // - BTOKEN in reserve should be 1-0.499374217772215269 = 0.500625782227784731 BTOKEN // - FTOKEN in reserve should be 0.1+0.1 = 0.2 FTOKEN await expect( mockMdexWorkerAsBob.work( 0, bobAddress, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [ ethers.utils.parseEther("8888"), ethers.utils.parseEther("0"), ethers.utils.parseEther("1.499374217772215269"), ] ), ] ) ) ) .to.emit(strat, "MdexRestrictedStrategyPartialCloseLiquidateEvent") .withArgs(baseToken.address, farmingToken.address, ethers.utils.parseEther("0.316227766016837933"), "0"); expect(await lp.balanceOf(strat.address), "Strategy should has 0 LP").to.be.eq(ethers.utils.parseEther("0")); expect(await lp.balanceOf(mockMdexWorker.address), "Worker should has 0 LP as all LP is liquidated").to.be.eq( "0" ); expect( await baseToken.balanceOf(bobAddress), "Bob's BTOKEN should increase by 1.499374217772215269 BTOKEN" ).to.be.eq( bobBTokenBefore.add(ethers.utils.parseEther("1")).add(ethers.utils.parseEther("0.499374217772215269")) ); expect(await baseToken.balanceOf(lp.address), "FTOKEN-BTOKEN LP should has 0.500625782227784731 BTOKEN").to.be.eq( ethers.utils.parseEther("0.500625782227784731") ); expect(await farmingToken.balanceOf(lp.address), "FTOKEN-BTOKEN LP should as 0.2 FTOKEN").to.be.eq( ethers.utils.parseEther("0.2") ); }); }); context("when maxLpToLiquidate < LPs from worker", async () => { it("should liquidate portion LPs back to BTOKEN (fee 20)", async () => { // set lp pair fee await factory.setPairFees(lp.address, 20); // Bob transfer LP to strategy first const bobLpBefore = await lp.balanceOf(bobAddress); const bobBTokenBefore = await baseToken.balanceOf(bobAddress); await lpAsBob.transfer(strat.address, ethers.utils.parseEther("0.316227766016837933")); // Bob uses partial close liquidate strategy to turn the 50% LPs back to BTOKEN with the same minimum value and the same maxReturn const returnLp = bobLpBefore.div(2); await expect( mockMdexWorkerAsBob.work( 0, bobAddress, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [returnLp, ethers.utils.parseEther("0"), ethers.utils.parseEther("0.5")] ), ] ) ) ) .to.emit(strat, "MdexRestrictedStrategyPartialCloseLiquidateEvent") .withArgs(baseToken.address, farmingToken.address, returnLp, "0"); // After execute strategy successfully. The following conditions must be satisfied // - LPs in Strategy contract must be 0 // - Bob should have bobLpBefore - returnLp left in his account // - Bob should have bobBtokenBefore + 0.5 BTOKEN + [((0.05*998)*1.5)/(0.15*1000+(0.05*998))] = 0.374437218609304652 BTOKEN] (from swap 0.05 FTOKEN to BTOKEN) in his account // - BTOKEN in reserve should be 1.5-0.374437218609304652 = 1.125562781390695348 BTOKEN // - FTOKEN in reserve should be 0.15+0.05 = 0.2 FTOKEN expect(await lp.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0")); expect(await lp.balanceOf(mockMdexWorkerAsBob.address)).to.be.eq(bobLpBefore.sub(returnLp)); assertAlmostEqual( bobBTokenBefore .add(ethers.utils.parseEther("0.5")) .add(ethers.utils.parseEther("0.374437218609304652")) .toString(), (await baseToken.balanceOf(bobAddress)).toString() ); assertAlmostEqual( ethers.utils.parseEther("1.125562781390695348").toString(), (await baseToken.balanceOf(lp.address)).toString() ); assertAlmostEqual( ethers.utils.parseEther("0.2").toString(), (await farmingToken.balanceOf(lp.address)).toString() ); }); it("should liquidate portion LPs back to BTOKEN (fee 25)", async () => { // set lp pair fee await factory.setPairFees(lp.address, 25); // Bob transfer LP to strategy first const bobLpBefore = await lp.balanceOf(bobAddress); const bobBTokenBefore = await baseToken.balanceOf(bobAddress); await lpAsBob.transfer(strat.address, ethers.utils.parseEther("0.316227766016837933")); // Bob uses partial close liquidate strategy to turn the 50% LPs back to BTOKEN with the same minimum value and the same maxReturn const returnLp = bobLpBefore.div(2); await expect( mockMdexWorkerAsBob.work( 0, bobAddress, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [returnLp, ethers.utils.parseEther("0"), ethers.utils.parseEther("0.5")] ), ] ) ) ) .to.emit(strat, "MdexRestrictedStrategyPartialCloseLiquidateEvent") .withArgs(baseToken.address, farmingToken.address, returnLp, "0"); // After execute strategy successfully. The following conditions must be satisfied // - LPs in Strategy contract must be 0 // - Bob should have bobLpBefore - returnLp left in his account // - Bob should have bobBtokenBefore + 0.5 BTOKEN + [((0.05*9975)*1.5)/(0.15*10000+(0.05*9975))] = ~0.374296435272045028 BTOKEN] (from swap 0.05 FTOKEN to BTOKEN) in his account // - BTOKEN in reserve should be 1.5-0.374296435272045028 = 1.12570356 BTOKEN // - FTOKEN in reserve should be 0.15+0.05 = 0.2 FTOKEN expect(await lp.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0")); expect(await lp.balanceOf(mockMdexWorker.address)).to.be.eq(bobLpBefore.sub(returnLp)); assertAlmostEqual( bobBTokenBefore .add(ethers.utils.parseEther("0.5")) .add(ethers.utils.parseEther("0.374296435272045028")) .toString(), (await baseToken.balanceOf(bobAddress)).toString() ); assertAlmostEqual( ethers.utils.parseEther("1.12570356").toString(), (await baseToken.balanceOf(lp.address)).toString() ); assertAlmostEqual( ethers.utils.parseEther("0.2").toString(), (await farmingToken.balanceOf(lp.address)).toString() ); }); }); context("when maxDebtRepayment >= debt", async () => { it("should compare slippage by taking convertingPostionValue - debt (fee 20)", async () => { // set lp pair fee await factory.setPairFees(lp.address, 20); // Bob transfer LP to strategy first const bobBTokenBefore = await baseToken.balanceOf(bobAddress); await lpAsBob.transfer(strat.address, ethers.utils.parseEther("0.316227766016837933")); // Bob's position: 0.316227766016837933 LP // Debt: 1 BTOKEN // lpToLiquidate: Math.min(888, 0.316227766016837933) = 0.316227766016837933 LP (0.1 FTOKEN + 1 FTOKEN) // maxDebtRepayment: Math.min(888, 1) = 1 BTOKEN // The following conditions are expected: // - LPs in Strategy contract must be 0 // - Worker should have 0 LP left as all LP is liquidated // - Bob should have: // bobBtokenBefore + 1 BTOKEN + [((0.1*998)*1)/(0.1*10000+(0.1*998))] = 0.499499499499499499 BTOKEN] (from swap 0.1 FTOKEN to BTOKEN) in his account // - BTOKEN in reserve should be 1-0.499499499499499499 = 0.500500500500500501 BTOKEN // - FTOKEN in reserve should be 0.1+0.1 = 0.2 FTOKEN // - minBaseToken <= 1.499499499499499499 - 1 (debt) = 0.499499499499499499 BTOKEN must pass slippage check // Expect to be reverted if slippage is set at 0.499499499499499499 + 1 wei BTOKEN await expect( mockMdexWorkerAsBob.work( 0, bobAddress, ethers.utils.parseEther("1"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [ ethers.utils.parseEther("8888"), ethers.utils.parseEther("8888"), ethers.utils.parseEther("0.499499499499499499").add(1), ] ), ] ) ) ).to.be.revertedWith("MdexRestrictedStrategyPartialCloseLiquidate::execute:: insufficient baseToken received"); await expect( mockMdexWorkerAsBob.work( 0, bobAddress, ethers.utils.parseEther("1"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [ ethers.utils.parseEther("8888"), ethers.utils.parseEther("8888"), ethers.utils.parseEther("0.499499499499499499"), ] ), ] ) ) ) .to.emit(strat, "MdexRestrictedStrategyPartialCloseLiquidateEvent") .withArgs( baseToken.address, farmingToken.address, ethers.utils.parseEther("0.316227766016837933"), ethers.utils.parseEther("1") ); expect(await lp.balanceOf(strat.address), "Strategy should has 0 LP").to.be.eq(ethers.utils.parseEther("0")); expect(await lp.balanceOf(mockMdexWorker.address), "Worker should has 0 LP as all LP is liquidated").to.be.eq( "0" ); expect( await baseToken.balanceOf(bobAddress), "Bob's BTOKEN should increase by 1.499499499499499499 BTOKEN" ).to.be.eq( bobBTokenBefore.add(ethers.utils.parseEther("1")).add(ethers.utils.parseEther("0.499499499499499499")) ); expect(await baseToken.balanceOf(lp.address), "FTOKEN-BTOKEN LP should has 0.500500500500500501 BTOKEN").to.be.eq( ethers.utils.parseEther("0.500500500500500501") ); expect(await farmingToken.balanceOf(lp.address), "FTOKEN-BTOKEN LP should as 0.2 FTOKEN").to.be.eq( ethers.utils.parseEther("0.2") ); }); it("should compare slippage by taking convertingPostionValue - debt (fee 25)", async () => { // set lp pair fee await factory.setPairFees(lp.address, 25); // Bob transfer LP to strategy first const bobBTokenBefore = await baseToken.balanceOf(bobAddress); await lpAsBob.transfer(strat.address, ethers.utils.parseEther("0.316227766016837933")); // Bob's position: 0.316227766016837933 LP // Debt: 1 BTOKEN // lpToLiquidate: Math.min(888, 0.316227766016837933) = 0.316227766016837933 LP (0.1 FTOKEN + 1 FTOKEN) // maxDebtRepayment: Math.min(888, 1) = 1 BTOKEN // The following conditions are expected: // - LPs in Strategy contract must be 0 // - Worker should have 0 LP left as all LP is liquidated // - Bob should have: // bobBtokenBefore + 1 BTOKEN + [((0.1*9975)*1)/(0.1*10000+(0.1*9975))] = 0.499374217772215269 BTOKEN] (from swap 0.1 FTOKEN to BTOKEN) in his account // - BTOKEN in reserve should be 1-0.499374217772215269 = 0.500625782227784731 BTOKEN // - FTOKEN in reserve should be 0.1+0.1 = 0.2 FTOKEN // - minBaseToken <= 1.499374217772215269 - 1 (debt) = 0.499374217772215269 BTOKEN must pass slippage check // Expect to be reverted if slippage is set at 0.499374217772215270 BTOKEN await expect( mockMdexWorkerAsBob.work( 0, bobAddress, ethers.utils.parseEther("1"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [ ethers.utils.parseEther("8888"), ethers.utils.parseEther("8888"), ethers.utils.parseEther("0.499374217772215270"), ] ), ] ) ) ).to.be.revertedWith("MdexRestrictedStrategyPartialCloseLiquidate::execute:: insufficient baseToken received"); await expect( mockMdexWorkerAsBob.work( 0, bobAddress, ethers.utils.parseEther("1"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [ ethers.utils.parseEther("8888"), ethers.utils.parseEther("8888"), ethers.utils.parseEther("0.499374217772215269"), ] ), ] ) ) ) .to.emit(strat, "MdexRestrictedStrategyPartialCloseLiquidateEvent") .withArgs( baseToken.address, farmingToken.address, ethers.utils.parseEther("0.316227766016837933"), ethers.utils.parseEther("1") ); expect(await lp.balanceOf(strat.address), "Strategy should has 0 LP").to.be.eq(ethers.utils.parseEther("0")); expect(await lp.balanceOf(mockMdexWorker.address), "Worker should has 0 LP as all LP is liquidated").to.be.eq( "0" ); expect( await baseToken.balanceOf(bobAddress), "Bob's BTOKEN should increase by 1.499374217772215269 BTOKEN" ).to.be.eq( bobBTokenBefore.add(ethers.utils.parseEther("1")).add(ethers.utils.parseEther("0.499374217772215269")) ); expect(await baseToken.balanceOf(lp.address), "FTOKEN-BTOKEN LP should has 0.500625782227784731 BTOKEN").to.be.eq( ethers.utils.parseEther("0.500625782227784731") ); expect(await farmingToken.balanceOf(lp.address), "FTOKEN-BTOKEN LP should as 0.2 FTOKEN").to.be.eq( ethers.utils.parseEther("0.2") ); }); }); context("when maxDebtRepayment < debt", async () => { it("should compare slippage by taking convertingPostionValue - maxDebtRepayment (fee 20)", async () => { // set lp pair fee await factory.setPairFees(lp.address, 20); // Bob transfer LP to strategy first const bobBTokenBefore = await baseToken.balanceOf(bobAddress); await lpAsBob.transfer(strat.address, ethers.utils.parseEther("0.316227766016837933")); // Bob's position: 0.316227766016837933 LP // Debt: 1 BTOKEN // lpToLiquidate: Math.min(888, 0.316227766016837933) = 0.316227766016837933 LP (0.1 FTOKEN + 1 FTOKEN) // maxDebtRepayment: Math.min(888, 0.1) = 0.1 BTOKEN // The following conditions are expected: // - LPs in Strategy contract must be 0 // - Worker should have 0 LP left as all LP is liquidated // - Bob should have: // bobBtokenBefore + 1 BTOKEN + [((0.1*998)*1)/(0.1*10000+(0.1*998))] = 0.499499499499499499 BTOKEN] (from swap 0.1 FTOKEN to BTOKEN) in his account // - BTOKEN in reserve should be 1-0.499499499499499499 = 0.500500500500500501 BTOKEN // - FTOKEN in reserve should be 0.1+0.1 = 0.2 FTOKEN // - minBaseToken <= 1.499499499499499499 - 0.1 (debt) = 1.399499499499499499 BTOKEN must pass slippage check // Expect to be reverted if slippage is set at 1.399499499499499499 + 1 wei BTOKEN await expect( mockMdexWorkerAsBob.work( 0, bobAddress, ethers.utils.parseEther("1"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [ ethers.utils.parseEther("8888"), ethers.utils.parseEther("0.1"), ethers.utils.parseEther("1.399499499499499499").add(1), ] ), ] ) ) ).to.be.revertedWith("MdexRestrictedStrategyPartialCloseLiquidate::execute:: insufficient baseToken received"); await expect( mockMdexWorkerAsBob.work( 0, bobAddress, ethers.utils.parseEther("1"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [ ethers.utils.parseEther("8888"), ethers.utils.parseEther("0.1"), ethers.utils.parseEther("1.399499499499499499"), ] ), ] ) ) ) .to.emit(strat, "MdexRestrictedStrategyPartialCloseLiquidateEvent") .withArgs( baseToken.address, farmingToken.address, ethers.utils.parseEther("0.316227766016837933"), ethers.utils.parseEther("0.1") ); expect(await lp.balanceOf(strat.address), "Strategy should has 0 LP").to.be.eq(ethers.utils.parseEther("0")); expect( await lp.balanceOf(mockMdexWorkerAsBob.address), "Worker should has 0 LP as all LP is liquidated" ).to.be.eq("0"); expect( await baseToken.balanceOf(bobAddress), "Bob's BTOKEN should increase by 1.499499499499499499 BTOKEN" ).to.be.eq( bobBTokenBefore.add(ethers.utils.parseEther("1")).add(ethers.utils.parseEther("0.499499499499499499")) ); expect(await baseToken.balanceOf(lp.address), "FTOKEN-BTOKEN LP should has 0.500500500500500501 BTOKEN").to.be.eq( ethers.utils.parseEther("0.500500500500500501") ); expect(await farmingToken.balanceOf(lp.address), "FTOKEN-BTOKEN LP should as 0.2 FTOKEN").to.be.eq( ethers.utils.parseEther("0.2") ); }); it("should compare slippage by taking convertingPostionValue - maxDebtRepayment (fee 25)", async () => { // set lp pair fee await factory.setPairFees(lp.address, 25); // Bob transfer LP to strategy first const bobBTokenBefore = await baseToken.balanceOf(bobAddress); await lpAsBob.transfer(strat.address, ethers.utils.parseEther("0.316227766016837933")); // Bob's position: 0.316227766016837933 LP // Debt: 1 BTOKEN // lpToLiquidate: Math.min(888, 0.316227766016837933) = 0.316227766016837933 LP (0.1 FTOKEN + 1 FTOKEN) // maxDebtRepayment: 0.1 BTOKEN // The following conditions are expected // - LPs in Strategy contract must be 0 // - Worker should have 0 LP left as all LP is liquidated // - Bob should have: // bobBtokenBefore + 1 BTOKEN + [((0.1*9975)*1)/(0.1*10000+(0.1*9975))] = 0.499374217772215269 BTOKEN] (from swap 0.1 FTOKEN to BTOKEN) in his account // - BTOKEN in reserve should be 1-0.499374217772215269 = 0.500625782227784731 BTOKEN // - FTOKEN in reserve should be 0.1+0.1 = 0.2 FTOKEN // - minBaseToken <= 1.399374217772215269 BTOKEN should pass slippage check // Expect to be reverted if slippage is set at 1.399374217772215270 BTOKEN await expect( mockMdexWorkerAsBob.work( 0, bobAddress, ethers.utils.parseEther("1"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [ ethers.utils.parseEther("8888"), ethers.utils.parseEther("0.1"), ethers.utils.parseEther("1.399374217772215270"), ] ), ] ) ) ).to.be.revertedWith("MdexRestrictedStrategyPartialCloseLiquidate::execute:: insufficient baseToken received"); await expect( mockMdexWorkerAsBob.work( 0, bobAddress, ethers.utils.parseEther("1"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [ ethers.utils.parseEther("8888"), ethers.utils.parseEther("0.1"), ethers.utils.parseEther("1.399374217772215269"), ] ), ] ) ) ) .to.emit(strat, "MdexRestrictedStrategyPartialCloseLiquidateEvent") .withArgs( baseToken.address, farmingToken.address, ethers.utils.parseEther("0.316227766016837933"), ethers.utils.parseEther("0.1") ); expect(await lp.balanceOf(strat.address), "Strategy should has 0 LP").to.be.eq(ethers.utils.parseEther("0")); expect(await lp.balanceOf(mockMdexWorker.address), "Worker should has 0 LP as all LP is liquidated").to.be.eq( "0" ); expect( await baseToken.balanceOf(bobAddress), "Bob's BTOKEN should increase by 1.499374217772215269 BTOKEN" ).to.be.eq( bobBTokenBefore.add(ethers.utils.parseEther("1")).add(ethers.utils.parseEther("0.499374217772215269")) ); expect(await baseToken.balanceOf(lp.address), "FTOKEN-BTOKEN LP should has 0.500625782227784731 BTOKEN").to.be.eq( ethers.utils.parseEther("0.500625782227784731") ); expect(await farmingToken.balanceOf(lp.address), "FTOKEN-BTOKEN LP should as 0.2 FTOKEN").to.be.eq( ethers.utils.parseEther("0.2") ); }); }); describe("#withdrawTradingRewards", async () => { context("When the withdrawTradingRewards caller is not an owner", async () => { it("should be reverted", async () => { await expect(stratAsBob.withdrawTradingRewards(bobAddress)).to.reverted; }); }); context("When withdrawTradingRewards caller is the owner", async () => { it("should be able to withdraw trading rewards", async () => { // set lp pair fee await factory.setPairFees(lp.address, 25); // Bob transfer LP to strategy first const bobLpBefore = await lp.balanceOf(bobAddress); await lpAsBob.transfer(strat.address, ethers.utils.parseEther("0.316227766016837933")); // Bob uses partial close liquidate strategy to turn the 50% LPs back to BTOKEN with the same minimum value and the same maxReturn const returnLp = bobLpBefore.div(2); await mockMdexWorkerAsBob.work( 0, bobAddress, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [returnLp, ethers.utils.parseEther("0"), ethers.utils.parseEther("0.5")] ), ] ) ); const mdxBefore = await mdxToken.balanceOf(deployerAddress); // withdraw trading reward to deployer const withDrawTx = await strat.withdrawTradingRewards(deployerAddress); const mdxAfter = await mdxToken.balanceOf(deployerAddress); // get trading reward of the previos block const pIds = [0]; const totalRewardPrev = await strat.getMiningRewards(pIds, { blockTag: Number(withDrawTx.blockNumber) - 1 }); const withDrawBlockReward = await swapMining["reward()"]({ blockTag: withDrawTx.blockNumber }); const totalReward = totalRewardPrev.add(withDrawBlockReward); expect(mdxAfter.sub(mdxBefore)).to.eq(totalReward); }); }); }); });
the_stack
import { ForeignColumn, Relationship, getClient, _csvSeed, csvExtractor, generateMethods, query, Relation, } from "./base"; import { readdirSync, statSync } from "fs"; // @ts-ignore import OSPoint from "ospoint"; // @ts-ignore import QueryStream from "pg-query-stream"; import escapeRegex from "escape-string-regexp"; import { unaccent } from "../lib/unaccent"; import { getConfig } from "../../config/config"; const { defaults } = getConfig(); const searchDefaults = defaults.placesSearch; const nearestDefaults = defaults.placesNearest; const containsDefaults = defaults.placesContained; export interface PlaceInterface { code: number; longitude: number; latitude: number; eastings: number; northings: number; min_eastings: number; min_northings: number; max_eastings: number; max_northings: number; local_type: string; outcode: string; name_1: string; name_1_lang: string; name_2: string; name_2_lang: string; county_unitary: string; county_unitary_type: string; district_borough: string; district_borough_type: string; region: string; country: string; } interface PlaceTuple extends PlaceInterface { id: number; location: string; bounding_polygon: string; name_1_search: string; name_1_search_ts: string; name_2_search: string; name_2_search_ts: string; } const schema = { id: "SERIAL PRIMARY KEY", code: "VARCHAR(255)", longitude: "DOUBLE PRECISION", latitude: "DOUBLE PRECISION", location: "GEOGRAPHY(Point, 4326)", eastings: "INTEGER", northings: "INTEGER", min_eastings: "INTEGER", min_northings: "INTEGER", max_eastings: "INTEGER", max_northings: "INTEGER", bounding_polygon: "GEOGRAPHY(Polygon, 4326)", local_type: "VARCHAR(128)", outcode: "VARCHAR(5)", name_1: "VARCHAR(128)", name_1_lang: "VARCHAR(10)", name_1_search: "VARCHAR(128)", name_1_search_ts: "tsvector", name_2: "VARCHAR(128)", name_2_lang: "VARCHAR(10)", name_2_search: "VARCHAR(128)", name_2_search_ts: "tsvector", county_unitary: "VARCHAR(128)", county_unitary_type: "VARCHAR(128)", district_borough: "VARCHAR(128)", district_borough_type: "VARCHAR(128)", region: "VARCHAR(32)", country: "VARCHAR(16)", }; const indexes = [ { unique: true, column: "code", }, { column: "name_1_search", opClass: "varchar_pattern_ops", }, { column: "name_1_search_ts", type: "GIN", }, { column: "name_2_search", opClass: "varchar_pattern_ops", }, { column: "name_2_search_ts", type: "GIN", }, { type: "GIST", column: "location", }, { type: "GIST", column: "bounding_polygon", }, ]; const relation: Relation = { relation: "places", schema, indexes, }; const methods = generateMethods(relation); const returnAttributes = `*, ST_AsText(bounding_polygon) AS polygon`; const findByCodeQuery = ` SELECT ${returnAttributes} FROM places WHERE code=$1 `; // Return place by `code` const findByCode = async (code: string): Promise<PlaceTuple | null> => { if (typeof code !== "string") return null; const result = await query<PlaceTuple>(findByCodeQuery, [code.toLowerCase()]); if (result.rowCount === 0) return null; return result.rows[0]; }; interface SearchOptions { name?: string; limit?: number; } /** * Executes a name search for a place. For now this delegates straight to * prefixQuery * This method will also: * - Check validity inbound query * - Format inbound query (e.g. lowercase, replace \' and \-) */ const search = async ({ name, limit = searchDefaults.limit.DEFAULT, }: SearchOptions): Promise<PlaceTuple[] | null> => { if (name === undefined) return null; if (name.length === 0) return null; const searchTerm = name .toLowerCase() .trim() .replace(/'/g, "") .replace(/-/g, " "); if (limit < 1) limit = searchDefaults.limit.DEFAULT; if (limit > searchDefaults.limit.MAX) limit = searchDefaults.limit.MAX; const searchOptions = { name: searchTerm, limit }; const termsResult = await termsSearch(searchOptions); if (termsResult !== null) return termsResult; // first do terms search, if that fails or does not find anything return await prefixSearch(searchOptions); }; // Replacing postgres unaccent due to indexing issues // https://stackoverflow.com/questions/28899042/unaccent-preventing-index-usage-in-postgres/28899610#28899610 const searchQuery = ` SELECT ${returnAttributes} FROM places WHERE name_1_search ~ $1 OR name_2_search ~ $1 LIMIT $2 `; /** * Search method which will produce a fast prefix search for places. Inputs are * unchecked and so cannot be exposed directly as an HTTP endpoint * +ve fast on exact prefix matches (good for autocomplete) * +ve fast on exact name matches * -ve does not support terms matching (e.g. out of order or missing terms) * -ve does not support fuzzy matching (e.g. typos) */ const prefixSearch = async ( options: SearchOptions ): Promise<PlaceTuple[] | null> => { const regex = `^${unaccent(escapeRegex(options.name))}.*`; const limit = options.limit; const result = await query(searchQuery, [regex, limit]); if (result.rows.length === 0) return null; return result.rows; }; const termsSearchQuery = ` SELECT ${returnAttributes} FROM places WHERE name_1_search_ts @@ phraseto_tsquery('simple', $1) OR name_2_search_ts @@ phraseto_tsquery('simple', $1) ORDER BY GREATEST( ts_rank_cd(name_1_search_ts, phraseto_tsquery('simple', $1), 1), coalesce(ts_rank_cd(name_2_search_ts, phraseto_tsquery('simple', $1), 1), 0) ) DESC LIMIT $2 `; /** * Search method which will match terms. Inputs are unchecked and so cannot * be exposed directly as an HTTP endpoint * +ve supports terms matching (e.g. out of order, missing terms, one term misspelt) * -ve does not support fuzzy matching (e.g. typos) * -ve no partial query matching */ const termsSearch = async ({ name, limit, }: SearchOptions): Promise<PlaceTuple[] | null> => { const result = await query(termsSearchQuery, [name, limit]); if (result.rows.length === 0) return null; return result.rows; }; let idCache: void | number[]; // Retrieve random place const random = async (): Promise<PlaceTuple> => { if (!idCache) idCache = await loadPlaceIds(); const result = await loadPlaceIds(); return randomFromIds(idCache); }; interface Ids { id: number; } const loadPlaceIds = async (): Promise<number[]> => { const result = await query<Ids>(`SELECT id FROM ${relation.relation}`); return result.rows.map((r) => r.id); }; const findByIdQuery = ` SELECT ${returnAttributes} FROM places WHERE id=$1 `; const randomFromIds = async (ids: number[]): Promise<PlaceTuple> => { const length = ids.length; const randomId = ids[Math.floor(Math.random() * length)]; const result = await query(findByIdQuery, [randomId]); if (result.rows.length === 0) return null; return result.rows[0]; }; interface PlaceDistanceTuple extends PlaceTuple { distance: number; } // Returns places that are contained by specified geolocation const containsQuery = ` SELECT ${returnAttributes}, ST_Distance( location, ST_GeographyFromText('POINT(' || $1 || ' ' || $2 || ')') ) AS distance FROM places WHERE ST_Intersects( bounding_polygon, ST_GeographyFromText('SRID=4326;POINT(' || $1 || ' ' || $2 || ')') ) ORDER BY distance ASC LIMIT $3 `; interface ContainsOptions { longitude: string; latitude: string; limit?: string; } const contains = async ( options: ContainsOptions ): Promise<PlaceDistanceTuple[] | null> => { const longitude = parseFloat(options.longitude); if (isNaN(longitude)) throw new Error("Invalid longitude"); const latitude = parseFloat(options.latitude); if (isNaN(latitude)) throw new Error("Invalid latitude"); let limit = parseInt(options.limit, 10) || containsDefaults.limit.DEFAULT; if (limit > containsDefaults.limit.MAX) limit = containsDefaults.limit.DEFAULT; const result = await query<PlaceDistanceTuple>(containsQuery, [ longitude, latitude, limit, ]); if (result.rows.length === 0) return null; return result.rows; }; // Returns nearest places with polygons that intersect geolocation incl. radius const nearestQuery = ` SELECT ${returnAttributes}, ST_Distance( bounding_polygon, ST_GeographyFromText('POINT(' || $1 || ' ' || $2 || ')') ) AS distance FROM places WHERE ST_DWithin( bounding_polygon, ST_GeographyFromText('POINT(' || $1 || ' ' || $2 || ')'), $3 ) ORDER BY distance ASC, name_1 ASC LIMIT $4 `; interface NearestOptions extends ContainsOptions { radius?: string; } const nearest = async ( options: NearestOptions ): Promise<PlaceDistanceTuple[] | null> => { const longitude = parseFloat(options.longitude); if (isNaN(longitude)) throw new Error("Invalid longitude"); const latitude = parseFloat(options.latitude); if (isNaN(latitude)) new Error("Invalid latitude"); let limit = parseInt(options.limit, 10) || nearestDefaults.limit.DEFAULT; if (limit > nearestDefaults.limit.MAX) limit = nearestDefaults.limit.DEFAULT; let radius = parseFloat(options.radius) || nearestDefaults.radius.DEFAULT; if (radius > nearestDefaults.radius.MAX) radius = nearestDefaults.radius.MAX; const result = await query<PlaceDistanceTuple>(nearestQuery, [ longitude, latitude, radius, limit, ]); if (result.rows.length === 0) return null; return result.rows; }; const toJson = (place: PlaceTuple): PlaceInterface => { return { code: place.code, name_1: place.name_1, name_1_lang: place.name_1_lang, name_2: place.name_2, name_2_lang: place.name_2_lang, local_type: place.local_type, outcode: place.outcode, county_unitary: place.county_unitary, county_unitary_type: place.county_unitary_type, district_borough: place.district_borough, district_borough_type: place.district_borough_type, region: place.region, country: place.country, longitude: place.longitude, latitude: place.latitude, eastings: place.eastings, northings: place.northings, min_eastings: place.min_eastings, min_northings: place.min_northings, max_eastings: place.max_eastings, max_northings: place.max_northings, }; }; const csvColumns = { code: 0, names_uri: 1, name_1: 2, name_1_lang: 3, name_2: 4, name_2_lang: 5, type: 6, local_type: 7, eastings: 8, northings: 9, most_detail_view_res: 10, least_detail_view_res: 11, min_eastings: 12, min_northings: 13, max_eastings: 14, max_northings: 15, outcode: 16, postcode_district_uri: 17, populated_place: 18, populated_place_uri: 19, populated_place_type: 20, district_borough: 21, district_borough_uri: 22, district_borough_type: 23, county_unitary: 24, county_unitary_uri: 25, county_unitary_type: 26, region: 27, region_uri: 28, country: 29, country_uri: 30, related_spatial_object: 31, same_as_dbpedia: 32, same_as_geonames: 33, }; // Populates places table given OS data directory const setupTable = async (directory: string) => { await query("CREATE EXTENSION IF NOT EXISTS unaccent"); await methods.createRelation(); await methods.clear(); await seedData(directory); await populateLocation(); await generateSearchFields(); await generateTsSearchFields(); await methods.createIndexes(); }; // Pipe OS places data into places table const seedData = async (directory: string) => { if (!statSync(directory).isDirectory()) throw new Error("Data directory should be supplied for OS places update"); const typeIndex = csvColumns.type; const columnWhitelist = [ "id", "location", "bounding_polygon", "name_1_search", "name_1_search_ts", "name_2_search", "name_2_search_ts", ]; const columns = Object.keys(relation.schema).filter( (col) => columnWhitelist.indexOf(col) === -1 ); const typeRegex = /^.*\//; const parseOsgb = (val: string) => parseInt(val, 10) || ""; const transformExceptions = { northings: parseOsgb, eastings: parseOsgb, min_eastings: parseOsgb, min_northings: parseOsgb, max_eastings: parseOsgb, max_northings: parseOsgb, county_unitary_type: (val: string) => val.replace(typeRegex, ""), district_borough_type: (val: string) => val.replace(typeRegex, ""), }; const transform = (row: string[]) => { // Skip if not a "place" if (row[typeIndex] !== "populatedPlace") return null; const northings = row[csvColumns.northings]; const eastings = row[csvColumns.eastings]; let location: any; if (northings.length * eastings.length === 0) { location = { longitude: "", latitude: "", }; } else { location = new OSPoint("" + northings, "" + eastings).toWGS84(); } return columns.map((colName: string) => { if (colName === "latitude") return location.latitude; if (colName === "longitude") return location.longitude; //@ts-ignore const columnIndex = csvColumns[colName]; const value = row[columnIndex]; //@ts-ignore const exception = transformExceptions[colName]; return exception ? exception(value) : value; }); }; const files = readdirSync(directory) .filter((f: string) => f.match(/\.csv$/)) .map((f: string) => `${directory}${f}`); return methods.csvSeed({ filepath: files, transform, columns }); }; // Generates folded search fields name_*_search const generateSearchFields = async () => { const updates = ["name_1", "name_2"].map((field) => query(` UPDATE ${relation.relation} SET ${field}_search=replace( replace( lower( unaccent(${field}) ), '-', ' ') , '''', '') `) ); return Promise.all(updates); }; const generateTsSearchFields = async () => { const updates = ["name_1", "name_2"].map((field) => query(` UPDATE ${relation.relation} SET ${field}_search_ts=to_tsvector('simple', ${field}) `) ); return Promise.all(updates); }; const generatePolygonQuery = (place: PlaceTuple): string => { const locations = []; if ( place.min_eastings * place.min_northings * place.max_eastings * place.max_northings === 0 ) return; const initialLocation = new OSPoint( "" + place.min_northings, "" + place.min_eastings ).toWGS84(); locations.push(initialLocation); locations.push( new OSPoint("" + place.max_northings, "" + place.min_eastings).toWGS84() ); locations.push( new OSPoint("" + place.max_northings, "" + place.max_eastings).toWGS84() ); locations.push( new OSPoint("" + place.min_northings, "" + place.max_eastings).toWGS84() ); locations.push(initialLocation); return ` UPDATE ${relation.relation} SET bounding_polygon=ST_GeogFromText('SRID=4326; POLYGON((${locations.map((l) => `${l.longitude} ${l.latitude}`).join(",")}))') WHERE id=${place.id} `; }; const createPolygons = () => { return new Promise<void>((resolve) => { (async () => { const client = await getClient(); const updateBuffer: string[] = []; const cleanup = (error: any) => { client.release(); throw error; }; const drainBuffer = async (done?: boolean) => { stream.pause(); for (const update of updateBuffer) { await query(update); } updateBuffer.length = 0; if (stream.isPaused()) stream.resume(); if (done) { client.release(); resolve(); } }; const streamQuery = new QueryStream(` SELECT id, min_eastings, min_northings, max_eastings, max_northings FROM ${relation.relation} `); const stream = client.query(streamQuery); stream .on("data", (place: PlaceTuple) => { updateBuffer.push(generatePolygonQuery(place)); if (updateBuffer.length > 1000) drainBuffer(); }) .on("error", cleanup) .on("end", () => drainBuffer(true)); })(); }); }; const createLocations = async () => query(` UPDATE ${relation.relation} SET location=ST_GeogFromText( 'SRID=4326;POINT(' || longitude || ' ' || latitude || ')' ) WHERE northings!=0 AND eastings!=0 `); // Generates location data including centroid and bounding box const populateLocation = async () => { await createPolygons(); await createLocations(); }; export const Place = { ...methods, populateLocation, seedData, setupTable, toJson, contains, random, search, findByCode, nearest, prefixSearch, termsSearch, };
the_stack
* CloudFormation spec validator * * "Why not JSON Schema?", you might ask, and it's a fair question. The answer is: * because the error reporting from JSON schema is pretty bad, and I want the validation * errors reported from this check to be blindingly obvious, as non-spec-experts * are going to have to consume and understand them. * * I tried JSON Schema validation and its errors look like: * * ``` * - instance.PropertyTypes["..."].Properties.Xyz does not match allOf schema <#/definitions/Typed> with 7 error[s]: * - instance.PropertyTypes["..."].Properties.Xyz requires property "PrimitiveType" * - instance.PropertyTypes["..."].Properties.Xyz requires property "Type" * - instance.PropertyTypes["..."].Properties.Xyz requires property "Type" * - instance.PropertyTypes["..."].Properties.Xyz requires property "ItemType" * - instance.PropertyTypes["..."].Properties.Xyz requires property "Type" * - instance.PropertyTypes["..."].Properties.Xyz requires property "PrimitiveItemType" * - instance.PropertyTypes["..."].Properties.Xyz is not exactly one from "Primitive","Complex Type","Collection of Primitives","Collection of Complex Types" * ``` * * No bueno. In contrast, this script prints: * * ``` * { * "ResourceTypes": { * "AWS::SageMaker::Device": { * "Properties": { * "Device": { * * !!! must have exactly one of 'Type', 'PrimitiveType', found: {"Type":"Device","PrimitiveType":"Json"} !!! * * "Documentation": "http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sagemaker-device.html#cfn-sagemaker-device-device", * "UpdateType": "Mutable", * "Required": false, * "PrimitiveType": "Json", * "Type": "Device" * } * } * } * } * } * ``` */ import * as fs from 'fs-extra'; export interface CfnSpec { PropertyTypes: Record<string, any>; ResourceTypes: Record<string, any>; ResourceSpecificationVersion: string; } export interface ValidationError { readonly value: JsonValue<any>; readonly message: string; } export class CfnSpecValidator { public static validate(spec: CfnSpec) { const ret = new CfnSpecValidator(spec); ret.validateSpec(); return ret.errors; } public readonly errors = new Array<ValidationError>(); private readonly root: JsonValue<CfnSpec>; constructor(spec: CfnSpec) { this.root = JsonValue.of(spec); } public validateSpec() { this.assert(this.root.get('PropertyTypes'), isObject, (propTypes) => { this.validateMap(propTypes, (propType) => this.validatePropertyType(propType)); }); this.assert(this.root.get('ResourceTypes'), isObject, (resTypes) => { this.validateMap(resTypes, (propType) => this.validateResourceType(propType)); }); } /** * Property types are extremely weird * * Nominally, they define "records" that have a `Properties` field with the defined * properties. * * However, they are also commonly used as aliases for other types, meaning they have * the same type-indicating fields as individual property *fields* would have. * * Also also, it seems to be quite common to have them empty--have no fields at all. * This seems to be taken as an alias for an unstructured `Json` type. It's probably * just a mistake, but unfortunately a mistake that S3 is participating in, so if we * fail on that we won't be able to consume updates to S3's schema. Our codegen is * ready to deal with this and just renders it to an empty struct. */ private validatePropertyType(propType: JsonValue<Record<string, any>>) { // If the only set of properties is "Documentation", we take this to be an alias // for an empty struct and allow it. I feel icky allowing this, but it seems to // be pragmatic for now. if (Object.keys(propType.value).join(',') === 'Documentation') { return; } const properties = propType.get('Properties'); if (properties.hasValue) { this.assert(properties, isObject, (props) => { this.validateProperties(props); }); } else { this.validateType(propType, 'if a property type doesn\'t have "Properties", it '); } } private validateResourceType(resType: JsonValue<any>) { this.assertOptional(resType.get('Properties'), isObject, (props) => { this.validateProperties(props); }); this.assertOptional(resType.get('Attributes'), isObject, (attrs) => { this.validateMap(attrs, attr => { this.validateType(attr); }); }); } private validateProperties(properties: JsonValue<Record<string, any>>) { this.validateMap(properties, prop => { this.validateType(prop); this.assertOptional(prop.get('UpdateType'), (x: any) => { if (!['Mutable', 'Immutable', 'Conditional'].includes(x)) { throw new Error(`invalid value for enum: '${x}'`); } }); }); } /** * Validate the type * * There must be: * - Either Type or PrimitiveType * - Only if Type is List or Map, there will be either an ItemType or a PrimitiveItemType * - Non-primitive Types must correspond to a property type */ private validateType(typedObject: JsonValue<Record<string, any>>, errorPrefix = '') { const type = typedObject.get('Type'); const primitiveType = typedObject.get('PrimitiveType'); if (type.hasValue === primitiveType.hasValue) { this.report(typedObject, `${errorPrefix}must have exactly one of 'Type', 'PrimitiveType', found: ${JSON.stringify({ Type: type.valueOrUndefined, PrimitiveType: primitiveType.valueOrUndefined, })}`); } this.assertOptional(primitiveType, isValidPrimitive); let isCollectionType = false; const itemType = typedObject.get('ItemType'); const primitiveItemType = typedObject.get('PrimitiveItemType'); if (type.hasValue) { isCollectionType = COLLECTION_TYPES.includes(type.value); if (isCollectionType) { if (itemType.hasValue === primitiveItemType.hasValue) { this.report(typedObject, `must have exactly one of 'ItemType', 'PrimitiveItemType', found: ${JSON.stringify({ ItemType: itemType.valueOrUndefined, PrimitiveItemType: primitiveItemType.valueOrUndefined, })}`); } this.assertOptional(primitiveItemType, isValidPrimitive); if (itemType.hasValue) { this.assertValidPropertyTypeReference(itemType); } } else { this.assertValidPropertyTypeReference(type); } } if (!isCollectionType) { if (itemType.hasValue || primitiveItemType.hasValue) { this.report(typedObject, 'only \'List\' or \'Map\' types can have \'ItemType\', \'PrimitiveItemType\''); } } const dupes = typedObject.get('DuplicatesAllowed'); if (dupes.hasValue && !isCollectionType) { this.report(dupes, 'occurs on non-collection type'); } } private assertValidPropertyTypeReference(typeName: JsonValue<string>) { if (BUILTIN_COMPLEX_TYPES.includes(typeName.value)) { return; } const cfnName = typeName.path[1]; // AWS::Xyz::Resource[.Property] const namespace = cfnName.split('.')[0]; const propTypeName = `${namespace}.${typeName.value}`; if (!this.root.get('PropertyTypes').get(propTypeName).hasValue) { this.report(typeName, `unknown property type name '${typeName.value}' (missing definition for '${propTypeName}')`); } } private assertOptional<A, B extends A>(x: JsonValue<A>, pred: (x: A) => asserts x is B, block?: (x: JsonValue<B>) => void): boolean { return x.hasValue ? this.assert(x, pred, block) : true; } private assert<A, B extends A>(x: JsonValue<A>, pred: (x: A) => asserts x is B, block?: (x: JsonValue<B>) => void): boolean { try { pred(x.value); if (block) { block(new JsonValue(x.value, x.path)); } return true; } catch (e) { this.report(x, e.message); return false; } } private validateMap<A>(x: JsonValue<Record<string, A>>, block: (x: JsonValue<A>) => void) { for (const key in x.value) { block(x.get(key)); } } private report(value: JsonValue<any>, message: string) { this.errors.push({ value, message }); } } function isObject(x: any): asserts x is Record<string, any> { if (x == null || typeof x !== 'object' || Array.isArray(x)) { throw new Error(`expected object, found '${x}'`); } } const COLLECTION_TYPES = ['List', 'Map']; const BUILTIN_COMPLEX_TYPES = ['Tag']; function isValidPrimitive(x: any): asserts x is string { const primitives = ['String', 'Long', 'Integer', 'Double', 'Boolean', 'Timestamp', 'Json']; if (!primitives.includes(x)) { throw new Error(`must be one of ${primitives.join(', ')}, got: ${x}`); } } interface JsonValue<A> { readonly path: string[]; readonly pathValue: any; readonly hasValue: boolean; readonly value: A; readonly valueOrUndefined: A | undefined; get<K extends keyof A>(k: K): JsonValue<A[K]>; } class JsonValue<A> implements JsonValue<A> { public static of<B>(x: B): JsonValue<B> { return new JsonValue(x, []); } public readonly hasValue: boolean = true; public readonly valueOrUndefined: A | undefined = this.value; public readonly pathValue: any = this.value; constructor(public readonly value: A, public readonly path: string[]) { } public get<K extends keyof A>(k: K): JsonValue<A[K]> { if (!this.value || typeof this.value !== 'object' || Array.isArray(this.value)) { return new ErrorValue(`expected object, found ${this.value}`, this.path, this.value); } const ret = this.value[k]; if (ret === undefined) { return new ErrorValue(`missing required key '${k}'`, this.path, this.value); } return new JsonValue(ret, [...this.path, `${k}`]); } } class ErrorValue<A> implements JsonValue<A> { public readonly hasValue = false; public readonly valueOrUndefined: A | undefined = undefined; constructor(private readonly error: string, public readonly path: string[], public readonly pathValue: any) { } public get<K extends keyof A>(_k: K): JsonValue<A[K]> { return this as any; } public get value(): A { throw new Error(this.error); } } export function formatErrorInContext(error: ValidationError) { let reportValue = error.value.pathValue; for (let i = error.value.path.length; i > 0; i--) { reportValue = { [error.value.path[i - 1]]: reportValue }; } const formattedLines = JSON.stringify(reportValue, undefined, 2).split('\n'); const indent = 2 * (error.value.path.length + 1); // Insert the error message at line N with an appropriate indent formattedLines.splice(error.value.path.length + 1, 0, `\n!!!${' '.repeat(indent - 3)}${error.message} !!!\n`); return formattedLines.join('\n'); } async function main(args: string[]) { const spec = await fs.readJson(args[0]); const errors = CfnSpecValidator.validate(spec); if (errors.length !== 0) { for (const error of errors) { console.error(formatErrorInContext(error)); } process.exitCode = 1; } } if (require.main === module) { main(process.argv.slice(2)).catch(e => { process.exitCode = 1; // eslint-disable-next-line no-console console.error(e.message); }); }
the_stack
import { ApprovalRequestData } from "../../../ComplexProperties/ApprovalRequestData"; import { BoolPropertyDefinition } from "../../../PropertyDefinitions/BoolPropertyDefinition"; import { ByteArrayPropertyDefinition } from "../../../PropertyDefinitions/ByteArrayPropertyDefinition"; import { ComplexPropertyDefinition } from "../../../PropertyDefinitions/ComplexPropertyDefinition"; import { ContainedPropertyDefinition } from "../../../PropertyDefinitions/ContainedPropertyDefinition"; import { EmailAddress } from "../../../ComplexProperties/EmailAddress"; import { EmailAddressCollection } from "../../../ComplexProperties/EmailAddressCollection"; import { ExchangeVersion } from "../../../Enumerations/ExchangeVersion"; import { PropertyDefinition } from "../../../PropertyDefinitions/PropertyDefinition"; import { PropertyDefinitionFlags } from "../../../Enumerations/PropertyDefinitionFlags"; import { StringPropertyDefinition } from "../../../PropertyDefinitions/StringPropertyDefinition"; import { VotingInformation } from "../../../ComplexProperties/VotingInformation"; import { XmlElementNames } from "../../XmlElementNames"; import { ItemSchema } from "./ItemSchema"; /** * Field URIs for EmailMessage. */ module FieldUris { export var ConversationIndex: string = "message:ConversationIndex"; export var ConversationTopic: string = "message:ConversationTopic"; export var InternetMessageId: string = "message:InternetMessageId"; export var IsRead: string = "message:IsRead"; export var IsResponseRequested: string = "message:IsResponseRequested"; export var IsReadReceiptRequested: string = "message:IsReadReceiptRequested"; export var IsDeliveryReceiptRequested: string = "message:IsDeliveryReceiptRequested"; export var References: string = "message:References"; export var ReplyTo: string = "message:ReplyTo"; export var From: string = "message:From"; export var Sender: string = "message:Sender"; export var ToRecipients: string = "message:ToRecipients"; export var CcRecipients: string = "message:CcRecipients"; export var BccRecipients: string = "message:BccRecipients"; export var ReceivedBy: string = "message:ReceivedBy"; export var ReceivedRepresenting: string = "message:ReceivedRepresenting"; export var ApprovalRequestData: string = "message:ApprovalRequestData"; export var VotingInformation: string = "message:VotingInformation"; } /** * Represents the schema for e-mail messages. */ export class EmailMessageSchema extends ItemSchema { /** * Defines the **ToRecipients** property. */ public static ToRecipients: PropertyDefinition = new ComplexPropertyDefinition<EmailAddressCollection>( "ToRecipients", XmlElementNames.ToRecipients, FieldUris.ToRecipients, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete, ExchangeVersion.Exchange2007_SP1, () => { return new EmailAddressCollection(); } ); /** * Defines the **BccRecipients** property. */ public static BccRecipients: PropertyDefinition = new ComplexPropertyDefinition<EmailAddressCollection>( "BccRecipients", XmlElementNames.BccRecipients, FieldUris.BccRecipients, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete, ExchangeVersion.Exchange2007_SP1, () => { return new EmailAddressCollection(); } ); /** * Defines the **CcRecipients** property. */ public static CcRecipients: PropertyDefinition = new ComplexPropertyDefinition<EmailAddressCollection>( "CcRecipients", XmlElementNames.CcRecipients, FieldUris.CcRecipients, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete, ExchangeVersion.Exchange2007_SP1, () => { return new EmailAddressCollection(); } ); /** * Defines the **ConversationIndex** property. */ public static ConversationIndex: PropertyDefinition = new ByteArrayPropertyDefinition( "ConversationIndex", XmlElementNames.ConversationIndex, FieldUris.ConversationIndex, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **ConversationTopic** property. */ public static ConversationTopic: PropertyDefinition = new StringPropertyDefinition( "ConversationTopic", XmlElementNames.ConversationTopic, FieldUris.ConversationTopic, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **From** property. */ public static From: PropertyDefinition = new ContainedPropertyDefinition<EmailAddress>( "From", XmlElementNames.From, FieldUris.From, XmlElementNames.Mailbox, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new EmailAddress(); } ); /** * Defines the **IsDeliveryReceiptRequested** property. */ public static IsDeliveryReceiptRequested: PropertyDefinition = new BoolPropertyDefinition( "IsDeliveryReceiptRequested", XmlElementNames.IsDeliveryReceiptRequested, FieldUris.IsDeliveryReceiptRequested, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsRead** property. */ public static IsRead: PropertyDefinition = new BoolPropertyDefinition( "IsRead", XmlElementNames.IsRead, FieldUris.IsRead, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsReadReceiptRequested** property. */ public static IsReadReceiptRequested: PropertyDefinition = new BoolPropertyDefinition( "IsReadReceiptRequested", XmlElementNames.IsReadReceiptRequested, FieldUris.IsReadReceiptRequested, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsResponseRequested** property. */ public static IsResponseRequested: PropertyDefinition = new BoolPropertyDefinition( "IsResponseRequested", XmlElementNames.IsResponseRequested, FieldUris.IsResponseRequested, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, true ); /** * Defines the **InternetMessageId** property. */ public static InternetMessageId: PropertyDefinition = new StringPropertyDefinition( "InternetMessageId", XmlElementNames.InternetMessageId, FieldUris.InternetMessageId, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **References** property. */ public static References: PropertyDefinition = new StringPropertyDefinition( "References", XmlElementNames.References, FieldUris.References, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **ReplyTo** property. */ public static ReplyTo: PropertyDefinition = new ComplexPropertyDefinition<EmailAddressCollection>( "ReplyTo", XmlElementNames.ReplyTo, FieldUris.ReplyTo, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete, ExchangeVersion.Exchange2007_SP1, () => { return new EmailAddressCollection(); } ); /** * Defines the **Sender** property. */ public static Sender: PropertyDefinition = new ContainedPropertyDefinition<EmailAddress>( "Sender", XmlElementNames.Sender, FieldUris.Sender, XmlElementNames.Mailbox, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new EmailAddress(); } ); /** * Defines the **ReceivedBy** property. */ public static ReceivedBy: PropertyDefinition = new ContainedPropertyDefinition<EmailAddress>( "ReceivedBy", XmlElementNames.ReceivedBy, FieldUris.ReceivedBy, XmlElementNames.Mailbox, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new EmailAddress(); } ); /** * Defines the **ReceivedRepresenting** property. */ public static ReceivedRepresenting: PropertyDefinition = new ContainedPropertyDefinition<EmailAddress>( "ReceivedRepresenting", XmlElementNames.ReceivedRepresenting, FieldUris.ReceivedRepresenting, XmlElementNames.Mailbox, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new EmailAddress(); } ); /** * Defines the **ApprovalRequestData** property. */ public static ApprovalRequestData: PropertyDefinition = new ComplexPropertyDefinition<ApprovalRequestData>( "ApprovalRequestData", XmlElementNames.ApprovalRequestData, FieldUris.ApprovalRequestData, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2013, () => { return new ApprovalRequestData(); } ); /** * Defines the **VotingInformation** property. */ public static VotingInformation: PropertyDefinition = new ComplexPropertyDefinition<VotingInformation>( "VotingInformation", XmlElementNames.VotingInformation, FieldUris.VotingInformation, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2013, () => { return new VotingInformation(); } ); /** * @internal Instance of **EmailMessageSchema** */ static Instance: EmailMessageSchema = new EmailMessageSchema(); /** * Registers properties. * * /remarks/ IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the same order as they are defined in types.xsd) */ RegisterProperties(): void { super.RegisterProperties(); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.Sender); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.ToRecipients); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.CcRecipients); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.BccRecipients); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.IsReadReceiptRequested); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.IsDeliveryReceiptRequested); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.ConversationIndex); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.ConversationTopic); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.From); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.InternetMessageId); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.IsRead); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.IsResponseRequested); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.References); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.ReplyTo); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.ReceivedBy); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.ReceivedRepresenting); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.ApprovalRequestData); this.RegisterProperty(EmailMessageSchema, EmailMessageSchema.VotingInformation); } } /** * Represents the schema for e-mail messages. */ export interface EmailMessageSchema { /** * Defines the **ToRecipients** property. */ ToRecipients: PropertyDefinition; /** * Defines the **BccRecipients** property. */ BccRecipients: PropertyDefinition; /** * Defines the **CcRecipients** property. */ CcRecipients: PropertyDefinition; /** * Defines the **ConversationIndex** property. */ ConversationIndex: PropertyDefinition; /** * Defines the **ConversationTopic** property. */ ConversationTopic: PropertyDefinition; /** * Defines the **From** property. */ From: PropertyDefinition; /** * Defines the **IsDeliveryReceiptRequested** property. */ IsDeliveryReceiptRequested: PropertyDefinition; /** * Defines the **IsRead** property. */ IsRead: PropertyDefinition; /** * Defines the **IsReadReceiptRequested** property. */ IsReadReceiptRequested: PropertyDefinition; /** * Defines the **IsResponseRequested** property. */ IsResponseRequested: PropertyDefinition; /** * Defines the **InternetMessageId** property. */ InternetMessageId: PropertyDefinition; /** * Defines the **References** property. */ References: PropertyDefinition; /** * Defines the **ReplyTo** property. */ ReplyTo: PropertyDefinition; /** * Defines the **Sender** property. */ Sender: PropertyDefinition; /** * Defines the **ReceivedBy** property. */ ReceivedBy: PropertyDefinition; /** * Defines the **ReceivedRepresenting** property. */ ReceivedRepresenting: PropertyDefinition; /** * Defines the **ApprovalRequestData** property. */ ApprovalRequestData: PropertyDefinition; /** * Defines the **VotingInformation** property. */ VotingInformation: PropertyDefinition; /** * @internal Instance of **EmailMessageSchema** */ Instance: EmailMessageSchema; } /** * Represents the schema for e-mail messages. */ export interface EmailMessageSchemaStatic extends EmailMessageSchema { }
the_stack
import { nextTick } from 'process' import dedent from 'dedent' import { Disposable, Position, Range, TextEditor, window, workspace, } from 'vscode' import { LanguageParser } from './parser' jest.mock('lodash.debounce') jest.mock('vscode') describe('Language parser', () => { describe('constructor', () => { const textEditorMock: TextEditor = { document: {} } as any beforeEach(() => { window.activeTextEditor = textEditorMock }) it('subscribes VS Code events to manage the state of parsing Marp Markdown', () => { jest .spyOn(window, 'onDidChangeActiveTextEditor') .mockReturnValue('onDidChangeActiveTextEditor' as any) jest .spyOn(workspace, 'onDidChangeTextDocument') .mockReturnValue('onDidChangeTextDocument' as any) jest .spyOn(workspace, 'onDidCloseTextDocument') .mockReturnValue('onDidCloseTextDocument' as any) const subscriptons: Disposable[] = [] const parser = new LanguageParser(subscriptons) expect(subscriptons).toContain(parser) expect(subscriptons).toContain('onDidChangeActiveTextEditor') expect(subscriptons).toContain('onDidChangeTextDocument') expect(subscriptons).toContain('onDidCloseTextDocument') expect(parser.activeEditor).toBe(textEditorMock) }) it('notifies to parse active text editor initially', () => { const notifyToParse = jest .spyOn(LanguageParser.prototype as any, 'notifyToParse') .mockImplementation() new LanguageParser([]) expect(notifyToParse).toHaveBeenCalledTimes(1) expect(notifyToParse).toHaveBeenCalledWith(textEditorMock.document) }) }) it('parses Marp Markdown in managed documents', async () => { const document = { languageId: 'markdown', getText: () => dedent(` --- marp: true theme: default test: test --- <!-- paginate: true --> <!-- _paginate: false --> `), positionAt(offset: number) { const lines = this.getText().slice(0, offset).split('\n') // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return new Position(lines.length - 1, lines.pop()!.length) }, } window.activeTextEditor = { document } as any const parser = new LanguageParser([]) const data = await parser.getParseData(document as any) expect(data).toBeTruthy() expect(data?.commentRanges).toHaveLength(2) expect(data?.frontMatterRange).toBeInstanceOf(Range) expect(data?.directvies).toHaveLength(4) // Range data expect(data?.directvies[0].range.start).toMatchObject({ line: 1, character: 0, }) expect(data?.directvies[0].range.end).toMatchObject({ line: 1, character: 10, }) expect(data?.directvies[1].range.start).toMatchObject({ line: 2, character: 0, }) expect(data?.directvies[1].range.end).toMatchObject({ line: 2, character: 14, }) expect(data?.directvies[2].range.start).toMatchObject({ line: 7, character: 0, }) expect(data?.directvies[2].range.end).toMatchObject({ line: 7, character: 14, }) expect(data?.directvies[3].range.start).toMatchObject({ line: 9, character: 5, }) expect(data?.directvies[3].range.end).toMatchObject({ line: 9, character: 21, }) }) it('has correct source map even if used CR+LF newline', async () => { const document = { languageId: 'markdown', getText: () => { const baseDoc = dedent(` --- marp: true theme: default test: test --- <!-- paginate: true --> <!-- _paginate: false --> `) return baseDoc.split('\n').join('\r\n') }, positionAt(offset: number) { const lines = this.getText().slice(0, offset).split('\n') // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return new Position(lines.length - 1, lines.pop()!.length) }, } window.activeTextEditor = { document } as any const parser = new LanguageParser([]) const data = await parser.getParseData(document as any) expect(data).toBeTruthy() expect(data?.directvies[0].range.start).toMatchObject({ line: 1, character: 0, }) expect(data?.directvies[0].range.end).toMatchObject({ line: 1, character: 10, }) expect(data?.directvies[1].range.start).toMatchObject({ line: 2, character: 0, }) expect(data?.directvies[1].range.end).toMatchObject({ line: 2, character: 14, }) expect(data?.directvies[2].range.start).toMatchObject({ line: 7, character: 0, }) expect(data?.directvies[2].range.end).toMatchObject({ line: 7, character: 14, }) expect(data?.directvies[3].range.start).toMatchObject({ line: 9, character: 5, }) expect(data?.directvies[3].range.end).toMatchObject({ line: 9, character: 21, }) }) it('does not parse Markdown when it is not Marp Markdown', async () => { const document = { languageId: 'markdown', getText: () => '', positionAt: (idx: number) => new Position(0, idx), } window.activeTextEditor = { document } as any const parser = new LanguageParser([]) // Bypass the check while getting parsed data jest.spyOn(parser as any, 'isEnabledLanguageFor').mockReturnValue(true) const data = await parser.getParseData(document as any) expect(data).toBeUndefined() }) it('parses the Marp document when it was updated', async () => { const eventSpy = jest.spyOn(workspace, 'onDidChangeTextDocument') const parser = new LanguageParser([]) expect(eventSpy).toHaveBeenCalledTimes(1) expect(eventSpy).toHaveBeenCalledWith(expect.any(Function)) const [onDidChangeTextDocument] = eventSpy.mock.calls[0] const mockEvent = { document: { languageId: 'markdown', getText: () => '---\nmarp: true\n---', positionAt: (idx: number) => new Position(0, idx), }, } onDidChangeTextDocument(mockEvent as any) const data = await parser.getParseData(mockEvent.document as any) expect(data).toBeTruthy() expect(data?.directvies).toHaveLength(1) }) it('emits activeEditorUpdated event if updated the content of active editor', () => { expect.hasAssertions() const document = { languageId: 'markdown', getText: () => '---\nmarp: true\n---', positionAt: (idx: number) => new Position(0, idx), } window.activeTextEditor = { document } as any const eventSpy = jest.spyOn(workspace, 'onDidChangeTextDocument') const parser = new LanguageParser([]) parser.on('activeEditorUpdated', (editor, data) => { expect(editor).toStrictEqual(window.activeTextEditor) expect(data).toBeTruthy() expect(data?.directvies).toHaveLength(1) }) const [onDidChangeTextDocument] = eventSpy.mock.calls[0] onDidChangeTextDocument({ document } as any) }) it('emits activeEditorDisposed event when a managed active editor was closed', () => { expect.hasAssertions() const document: any = {} window.activeTextEditor = { document } as any const eventSpy = jest.spyOn(workspace, 'onDidCloseTextDocument') const parser = new LanguageParser([]) parser.on('activeEditorDisposed', (editor) => { expect(editor).toStrictEqual(window.activeTextEditor) }) const [onDidCloseTextDocument] = eventSpy.mock.calls[0] onDidCloseTextDocument(document) }) describe('#getParseData', () => { describe('with ensureLatest option', () => { beforeEach(() => jest.useFakeTimers()) afterEach(() => jest.useRealTimers()) const wait = () => new Promise<void>((res) => { // Modern fake timers will mock nextTick function. We have to use // original function through _nextTick in Clock instance. // // https://github.com/facebook/jest/issues/10221 // https://github.com/sinonjs/fake-timers/blob/master/src/fake-timers-src.js ;(nextTick as any).clock._nextTick(res) }) it('tries to wait for a time to call debounce function if the data ws not yet ready', async () => { expect.assertions(3) const parser = new LanguageParser([]) jest.spyOn(parser as any, 'isEnabledLanguageFor').mockReturnValue(true) let resolved = false parser.getParseData({} as any, true).then(() => { resolved = true }) await wait() expect(resolved).toBe(false) // Check whether #getParseData has margin time jest.advanceTimersByTime(parser.waitForDebounce) await wait() expect(resolved).toBe(false) jest.advanceTimersByTime(50) await wait() expect(resolved).toBe(true) }) it('also makes delay if a passed document has different version from parsed document', async () => { expect.assertions(2) const document = { languageId: 'markdown', getText: () => '---\nmarp: true\n---', positionAt: (idx: number) => new Position(0, idx), version: 0, } window.activeTextEditor = { document } as any const parser = new LanguageParser([]) // Update version document.version = 1 let resolved = false parser.getParseData(document as any, true).then(() => { resolved = true }) await wait() expect(resolved).toBe(false) jest.advanceTimersByTime(parser.waitForDebounce + 50) await wait() expect(resolved).toBe(true) }) }) }) describe('#dispose', () => { it('disposes mapped datas', () => { const mapClearSpy = jest.spyOn(Map.prototype, 'clear') const document = { languageId: 'markdown', getText: () => '---\nmarp: true\n---', positionAt: (idx: number) => new Position(0, idx), } window.activeTextEditor = { document } as any new LanguageParser([]).dispose() expect(mapClearSpy).toHaveBeenCalled() }) }) })
the_stack
import { IncomingMessage } from "http"; import * as http from "http"; import * as https from "https"; import { get } from "lodash"; import * as parseLinkHeader from "parse-link-header"; import * as url from "url"; import { UrlObject } from "url"; import * as createUrlRegex from "url-regex"; import { ASJsonLdProfileContentType } from "./activitystreams"; import { activitySubtypes, ASValue, isASLink, isASObject, } from "./activitystreams/types"; import { Activity, ASObject, Extendable, isActivity, JSONLD, LDValue, } from "./types"; import { jsonld } from "./util"; import { debuglog, flatten } from "./util"; import { request } from "./util"; import { rdfaToJsonLd } from "./util"; import { ensureArray, followRedirects, jsonldAppend, makeErrorClass, readableToString, sendRequest, } from "./util"; import fetch from "node-fetch"; import { createLogger } from "../src/logger"; const logger = createLogger("activitypub"); export const publicCollectionId = "https://www.w3.org/ns/activitystreams#Public"; // Given an AS2 Object, return whether it appears to be an "subtype of Activity" // as required for https://w3c.github.io/activitypub/#object-without-create // #TODO - What if it's an extension activity that describes itself via // rdfs as a subtype of Activity? export const as2ObjectIsActivity = (obj: ASObject) => { return ensureArray(obj.type).some(t => activitySubtypes.includes(t)); }; export const getASId = (o: LDValue<ASObject>) => { if (typeof o === "string") { return o; } if (typeof o === "object") { return o.id; } // tslint:disable-next-line:no-unused-expression o as never; }; const flattenAnyArrays = <T = any>(arr: Array<T | T[]>): T[] => { const flattened: T[] = arr.reduce<T[]>((all, o): T[] => { if (o instanceof Array) { return all.concat(o); } return all.concat([o]); }, []); return flattened; }; /** * Get the targets of an AS Object. Those who might be interested about getting notified. * @param o * @param shouldFetch - whether to fetch related objects that are only mentioned by URL */ export const objectTargets = async ( o: ASObject, recursionLimit: number, shouldFetch: boolean = false, urlRewriter: (u: string) => string, ): Promise<ASValue[]> => { logger.debug("start objectTargets", recursionLimit, o); const audience = [ ...(await objectTargetsNoRecurse(o, shouldFetch, urlRewriter)), ...objectProvenanceAudience(o), ...targetedAudience(o), ]; logger.debug("objectTargets got audience", audience); const recursedAudience = recursionLimit ? flattenAnyArrays( await Promise.all( audience.map(async (audienceMember: ASObject) => { const recursedTargets = await objectTargets( audienceMember, recursionLimit - 1, shouldFetch, urlRewriter, ); return recursedTargets; }), ), ) : []; // logger.debug('objectTargets', { audience, recursedAudience, recursionLimit, activity }) const targets = [...audience, ...recursedAudience]; const deduped = Array.from(new Set(targets)); return deduped; }; /** * Get the targets of a single level of an AS Object. Don't recurse (see objectTargets) * @param o * @param shouldFetch - whether to fetch related objects that are only mentioned by URL */ export const objectTargetsNoRecurse = async ( o: ASObject, shouldFetch: boolean = false, urlRewriter: (u: string) => string, // relatedObjectTargetedAudience is a MAY in the spec. // And if you leave it on and start replying to long chains, // you'll end up having to deliver to every ancestor, which takes a long time in // big threads. So you might want to disable it to get a smaller result set { relatedObjectTargetedAudience = true, }: { relatedObjectTargetedAudience?: boolean } = {}, ): Promise<ASValue[]> => { /* Clients SHOULD look at any objects attached to the new Activity via the object, target, inReplyTo and/or tag fields, retrieve their actor or attributedTo properties, and MAY also retrieve their addressing properties, and add these to the to or cc fields of the new Activity being created. */ // logger.debug('isActivity(o)', isActivity(o), o) const related = flattenAnyArrays([ isActivity(o) && o.object, isActivity(o) && o.target, // this isn't really mentioned in the spec but required to get working how I'd expect. isActivity(o) && o.type === "Create" && get(o, "object.inReplyTo"), o.inReplyTo, o.tag, ]).filter(Boolean); logger.debug("o.related", related); const relatedObjects = (await Promise.all( related.map(async objOrUrl => { if (typeof objOrUrl === "object") { return objOrUrl; } if (!shouldFetch) { return; } // fetch url to get an object const audienceUrl: string = objOrUrl; // need to fetch it by url logger.debug("about to fetch for audienceUrl", { audienceUrl, rewritten: urlRewriter(audienceUrl), }); const res = await sendRequest( request( Object.assign(url.parse(urlRewriter(audienceUrl)), { headers: { accept: ASJsonLdProfileContentType, }, }), ), ); logger.debug("fetched audienceUrl", audienceUrl); if (res.statusCode !== 200) { logger.warn( "got non-200 response when fetching ${obj} as part of activityAudience()", ); return; } const body = await readableToString(res); const resContentType = res.headers["content-type"]; switch (resContentType) { case ASJsonLdProfileContentType: case "application/json": try { return JSON.parse(body); } catch (error) { logger.error( "Couldn't parse fetched response body as JSON when determining activity audience", { body }, error, ); return; } default: logger.warn( `Unexpected contentType=${resContentType} of response when fetching ` + `${audienceUrl} to determine activityAudience`, ); return; } }), )).filter(Boolean); // logger.debug('o.relatedObjects', relatedObjects) const relatedCreators: ASValue[] = flattenAnyArrays( relatedObjects.map(objectProvenanceAudience), ).filter(Boolean); const relatedAudience: ASValue[] = relatedObjectTargetedAudience ? flattenAnyArrays( relatedObjects.map(ro => isASObject(ro) && targetedAudience(ro)), ).filter(Boolean) : []; const targets: ASValue[] = [...relatedCreators, ...relatedAudience]; return targets; }; /** * Given a resource, return a list of other resources that helped create the original one * @param o - AS Object to get provenance audience for */ const objectProvenanceAudience = (o: ASObject): ASValue[] => { const actor = isActivity(o) && o.actor; const attributedTo = isASObject(o) && o.attributedTo; return [actor, attributedTo].filter(Boolean); }; /** * Given a resource, return a list of other resources that are explicitly targeted using audience targeting properties * @param o - AS Object to get targeted audience for */ export const targetedAudience = (object: ASObject | Activity) => { const targeted = flattenAnyArrays([ object.to, object.bto, object.cc, object.bcc, ]).filter(Boolean); const deduped = Array.from(new Set([].concat(targeted))); return deduped; }; /** * Given an activity, return an updated version of that activity that has been client-addressed. * So then you can submit the addressed activity to an outbox and make sure it's delivered to everyone who might care. * @param activity */ export const clientAddressedActivity = async ( activity: Activity, recursionLimit: number, shouldFetch: boolean = false, urlRewriter: (urlToFetch: string) => string, ): Promise<Activity> => { const audience = await objectTargets( activity, recursionLimit, shouldFetch, urlRewriter, ); const audienceIds = audience.map(getASId); return Object.assign({}, activity, { cc: Array.from(new Set(jsonldAppend(activity.cc, audienceIds))).filter( Boolean, ), }); }; // Create a headers map for http.request() incl. any specced requirements for ActivityPub Client requests export const clientHeaders = (headers = {}) => { const requirements = { // The client MUST specify an Accept header with the // application/ld+json; profile="https://www.w3.org/ns/activitystreams" media type // in order to retrieve the activity. // #critique: This is weird because AS2's official mimetype is // application/activity+json, and the ld+json + profile is only a SHOULD, // but in ActivityPub this is switched accept: `${ASJsonLdProfileContentType}"`, }; if ( Object.keys(headers) .map(h => h.toLowerCase()) .includes("accept") ) { throw new Error( `ActivityPub Client requests can't include custom Accept header. ` + `Must always be the same value of "${requirements.accept}"`, ); } return Object.assign(requirements, headers); }; const deliveryErrors = (exports.deliveryErrors = { // Succeeded in delivering, but response was an error DeliveryErrorResponse: makeErrorClass("DeliveryErrorResponse"), // Found an inbox, but failed to POST delivery to it DeliveryRequestFailed: makeErrorClass("DeliveryRequestFailed"), // Target could be fetched, but couldn't determine any .inbox InboxDiscoveryFailed: makeErrorClass("InboxDiscoveryFailed"), // At least one delivery did not succeed. Try again later? SomeDeliveriesFailed: makeErrorClass("SomeDeliveriesFailed", function( msg: string, failures: Error[], successes: string[], ) { this.failures = failures; this.successes = successes; }), // Failed to parse target HTTP response as JSON TargetParseFailed: makeErrorClass("TargetParseFailed"), // Failed to send HTTP request to a target TargetRequestFailed: makeErrorClass("TargetRequestFailed"), }); const fetchProfile = (exports.fetchProfile = async (target: string) => { const targetProfileRequest = request( Object.assign(url.parse(target), { headers: { accept: `${ASJsonLdProfileContentType},text/html`, }, }), ); logger.debug("fetchProfile " + target); let targetProfileResponse; try { targetProfileResponse = await sendRequest(targetProfileRequest); } catch (e) { throw new deliveryErrors.TargetRequestFailed(e.message); } logger.debug( `res ${targetProfileResponse.statusCode} fetchProfile for ${target}`, ); switch (targetProfileResponse.statusCode) { case 200: // cool break; default: throw new deliveryErrors.TargetRequestFailed( `Got unexpected status code ${ targetProfileResponse.statusCode } when requesting ${target} to fetchProfile`, ); } return targetProfileResponse; }); export const discoverOutbox = async (target: string) => { const profileResponse = await fetchProfile(target); const outbox = url.resolve(target, await outboxFromResponse(profileResponse)); return outbox; }; async function outboxFromResponse(res: IncomingMessage) { const contentTypeHeaders = ensureArray(res.headers["content-type"]); const contentType = contentTypeHeaders .map((contentTypeValue: string) => contentTypeValue.split(";")[0]) .filter(Boolean)[0]; const body = await readableToString(res); switch (contentType) { case "application/json": const targetProfile = (() => { try { return JSON.parse(body); } catch (e) { throw new deliveryErrors.TargetParseFailed(e.message); } })(); // #TODO be more JSON-LD aware when looking for outbox return targetProfile.outbox; default: throw new Error( `Don't know how to parse ${contentType} to determine outbox URL`, ); } } // deliver an activity to a target const deliverActivity = async ( activity: Activity, target: string, { deliverToLocalhost }: { deliverToLocalhost: boolean }, ) => { // discover inbox logger.debug("req inbox discovery " + target); const targetProfileResponse = await (async () => { try { return await followRedirects( Object.assign(url.parse(target), { headers: { accept: `${ASJsonLdProfileContentType}, text/html`, }, }), ); } catch (error) { logger.error( `Error delivering activity to target=${target}. ` + `This is normal if the target doesnt speak great ActivityPub.`, error, ); throw new deliveryErrors.TargetRequestFailed(error.message); } })(); logger.debug( `res ${targetProfileResponse.statusCode} inbox discovery for ${target}`, ); switch (targetProfileResponse.statusCode) { case 200: // cool break; default: throw new deliveryErrors.TargetRequestFailed( `Got unexpected status code ${ targetProfileResponse.statusCode } when requesting ` + `${target} to determine inbox URL`, ); } logger.debug(`deliverActivity to target ${target}`); const body = await readableToString(targetProfileResponse); const contentType = ensureArray(targetProfileResponse.headers["content-type"]) .map((contentTypeValue: string) => contentTypeValue.split(";")[0]) .filter(Boolean)[0]; let inbox: string = inboxFromHeaders(targetProfileResponse) || (await inboxFromBody(body, contentType)); if (inbox) { inbox = url.resolve(target, inbox); } if (!inbox) { throw new deliveryErrors.InboxDiscoveryFailed( "No .inbox found for target " + target, ); } // post to inbox const parsedInboxUrl = url.parse(inbox); // https://w3c.github.io/activitypub/#security-localhost if (parsedInboxUrl.hostname === "localhost" && !deliverToLocalhost) { throw new Error( "I will not deliver to localhost (protocol feature server:security-considerations:do-not-post-to-localhost)", ); } const deliveryRequest = request( Object.assign(parsedInboxUrl, { headers: { "content-type": ASJsonLdProfileContentType, }, method: "post", }), ); deliveryRequest.write(JSON.stringify(activity)); let deliveryResponse; try { deliveryResponse = await sendRequest(deliveryRequest); } catch (e) { throw new deliveryErrors.DeliveryRequestFailed(e.message); } const deliveryResponseBody = await readableToString(deliveryResponse); logger.debug( `ldn notify res ${ deliveryResponse.statusCode } ${inbox} ${deliveryResponseBody.slice(0, 100)}`, ); if ( deliveryResponse.statusCode >= 400 && deliveryResponse.statusCode <= 599 ) { // client or server error throw new deliveryErrors.DeliveryErrorResponse( `${ deliveryResponse.statusCode } response from ${inbox}\nResponse Body:\n${deliveryResponseBody}`, ); } // #TODO handle retry/timeout? return target; }; // Given an activity, determine its targets and deliver to the inbox of each // target export const targetAndDeliver = async ( activity: Activity, targets: string[], deliverToLocalhost: boolean, urlRewriter: (u: string) => string, modifyTargets: (targets: string[]) => string[] = (ts) => ts, ) => { logger.debug("start targetAndDeliver"); targets = modifyTargets( targets || (await objectTargets(activity, 0, false, urlRewriter)) .map(t => { const targetUrl = getASId(t); if (!targetUrl) { logger.debug( "Cant determine URL to deliver to for target, so skipping", t, ); } return targetUrl; }) .filter(Boolean) ); logger.debug("targetAndDeliver targets", targets); const deliveries: string[] = []; const failures: Error[] = []; await Promise.all( targets.map( (target): Promise<any> => { // Don't actually deliver to publicCollection URI as it is 'special' if (target === exports.publicCollectionId) { return Promise.resolve(target); } return deliverActivity(activity, urlRewriter(target), { deliverToLocalhost, }) .then(d => deliveries.push(d)) .catch(e => failures.push(e)); }, ), ); logger.debug("finished targetAndDeliver", { failures, deliveries }); if (failures.length) { logger.debug("failures delivering " + failures.map(e => e.stack)); throw new deliveryErrors.SomeDeliveriesFailed( "SomeDeliveriesFailed", failures, deliveries, ); } return deliveries; }; export const inboxUrl = async (subjectUrl: string) => { const subjectResponse = await fetch(subjectUrl); const subject = await subjectResponse.json(); const inbox = subject.inbox; if (!inbox) { return inbox; } const iurl = url.resolve(subjectUrl, inbox); return iurl; }; function inboxFromHeaders(res: IncomingMessage) { // look in res Link header const linkHeaders = ensureArray(res.headers.link); const inboxLinks = linkHeaders .map(parseLinkHeader) .filter(Boolean) .map((parsed: any) => { return parsed["http://www.w3.org/ns/ldp#inbox"]; }) .filter(Boolean); let inboxLink; if (Array.isArray(inboxLinks)) { if (inboxLinks.length > 1) { logger.warn( "More than 1 LDN inbox found, but only using 1 for now", inboxLinks, ); inboxLink = inboxLinks[0]; } } else { inboxLink = inboxLinks; } return inboxLink; } /** * Determine the ActivityPub Inbox of a fetched resource * @param body - The fetched resource * @param contentType - HTTP Content Type header of fetched resource * * This will look for the following kinds of inboxes, and return the first one it finds: * * a 'direct' inbox * * an actor, which is a separate resource, that has an inbox for activities related to * objects that actor is related to * * @TODO (bengo): Allow returning all inboxes we can find */ async function inboxFromBody(body: string, contentType: string) { try { const directInbox = await directInboxFromBody(body, contentType); if (directInbox) { return directInbox; } } catch (error) { logger.debug("Error looking for directInbox (Moving on).", error); } const actorInboxes = await actorInboxesFromBody(body, contentType); if (actorInboxes.length > 1) { logger.warn( "Got more than one actorInboxes. Only using first.", actorInboxes, ); } if (actorInboxes.length) { return actorInboxes[0]; } } /** * Given a resource as a string, determine the inboxes for any actors of the resource */ async function actorInboxesFromBody( body: string, contentType: string, ): Promise<string[]> { const bodyData = bodyToJsonLd(body, contentType); const compacted = await jsonld.compact(bodyData, { "@context": "https://www.w3.org/ns/activitystreams", }); const actorUrls = flatten( ensureArray(bodyData.actor) .filter(Boolean) .map(actor => { if (typeof actor === "string") { return [actor]; } else if (actor.url) { return ensureArray(actor.url); } else { logger.debug("Could not determine url from actor", { actor }); return []; } }), ); logger.debug("Actor URLs", actorUrls); const actorInboxes = flatten( await Promise.all( actorUrls.map(async actorUrl => { try { const res = await fetch(actorUrl, { headers: { accept: ASJsonLdProfileContentType, }, }); const actor = await res.json(); const inbox = actor.inbox; logger.debug("Actor inbox", inbox); return ensureArray(inbox).map(inboxRelativeUrl => url.resolve(actorUrl, inboxRelativeUrl), ); } catch (error) { logger.warn("Error fetching actor to lookup inbox", error); } }), ), ); return actorInboxes; } const UnexpectedContentTypeError = makeErrorClass("UnexpectedContentTypeError"); /** * Given a resource as a string + contentType, return a representation of it's linked data as a JSON-LD Object */ function bodyToJsonLd(body: string, contentType: string) { logger.debug("bodyToJsonLd", { contentType }); switch (contentType) { case "application/json": case "application/ld+json": case "application/activity+json": const data = JSON.parse(body); return data; default: logger.warn("Unable to bodyToJsonLd due to unexpected contentType", { contentType, }); throw new UnexpectedContentTypeError( `Dont know how to parse contentType=${contentType}`, ); } } /** * Given a resource as a string, return it's ActivityPub inbox URL (if any) */ async function directInboxFromBody(body: string, contentType: string) { let inboxes; logger.debug(`inboxFromBody got response contentType=${contentType}`); switch (contentType) { case "application/json": const object = (() => { try { return JSON.parse(body); } catch (e) { throw new deliveryErrors.TargetParseFailed(e.message); } })(); logger.debug("object", object); inboxes = ensureArray(object.inbox).filter(Boolean); break; case "text/html": const ld: Array<Extendable<JSONLD>> = await rdfaToJsonLd(body); const targetSubject = ld.find(x => x["@id"] === "http://localhost/"); if (!targetSubject) { logger.debug( "no targetSubject so no ldb:inbox after checking text/html for ld. got ld", ld, ); inboxes = []; } else { inboxes = targetSubject["http://www.w3.org/ns/ldp#inbox"].map( (i: JSONLD) => i["@id"], ); } break; case "application/ld+json": case "application/activity+json": const obj = JSON.parse(body); const compacted = await jsonld.compact(obj, { "@context": [ "https://www.w3.org/ns/activitystreams", { "distbin:inbox": { "@container": "@set", "@id": "ldp:inbox", }, }, ], }); const compactedInbox = (compacted["distbin:inbox"] || []).map( (o: { id: string }) => (typeof o === "object" ? o.id : o), ); inboxes = compactedInbox.length ? compactedInbox : ensureArray(obj.inbox); break; default: throw new Error( `Don't know how to parse ${contentType} to determine inbox URL`, ); } if (!inboxes || !inboxes.length) { logger.debug( `Could not determine ActivityPub inbox from ${contentType} response`, ); return; } if (inboxes.length > 1) { logger.warn( `Using only first inbox, but there were ${inboxes.length}: ${inboxes}`, ); } const inbox: string = inboxes[0]; return inbox; }
the_stack
import * as Langs from '../definitions/languages'; import * as Graph from '../definitions/graph'; import * as Values from '../definitions/values'; import {createOutputPreview} from '../editors/editor'; import { h } from 'maquette'; import { Md5 } from 'ts-md5'; import axios from 'axios'; import { AsyncLazy } from '../common/lazy'; import { Log } from "../common/log" // declare var DATASTORE_URI: string; interface AiaBlock extends Langs.Block { language: string assistant: AiAssistant | null code: Completion[] inputs: AiaInputs newFrame: string } type AiaExpandEvent = { kind:"expand", expanded:boolean } type AiaCompletionsEvent = { kind:"completions" } type AiaEvent = AiaExpandEvent | AiaCompletionsEvent type AiaInputs = { [input: string]: string } type AiaState = { id: number block: AiaBlock expanded: boolean assistants: AiAssistant[] } type Completion = { name: string path: string[] } function format(aiAssistant:AiAssistant | null, inputs:AiaInputs, newFrame:string, chain:Completion[]) { if (aiAssistant == null) return ""; let ins = Object.keys(inputs).map(k => k + "=" + inputs[k]).join(",") var code = aiAssistant.name + ((ins != "") ? (":" + ins) : "") + "\n" + newFrame + "\n" for(var c of chain) { code += c.name + ":" + c.path.join("/") + "\n" } return code.substr(0, code.length-1) } /* ai-assistant-name ai-assistant-name:input1-name=frame1,input2-name=frame2 new-frame member1:some/path member2:some/path/more member3:some/path/more/even */ function parse(code:string) : { assistant:string|null, chain:Completion[], inputs:AiaInputs, frame:string } { code = code.split("\r\n").join("\n") if (code == "") return { assistant: null, chain: [], inputs: {}, frame: "" } let lines = code.split('\n') let head = lines[0].split(':') let frame = (lines.length > 1) ? lines[1] : "" let chain = lines.slice(2).map(line => { let split = line.split(':') return { name:split[0], path:split[1].split('/') } }) let inputs : AiaInputs = { } if (head.length > 1) { for(let inp of head[1].split(',')) { let kvp = inp.split('=') inputs[kvp[0]] = kvp[1] } } return { assistant: head[0], chain:chain, inputs:inputs, frame:frame }; } async function getCompletions(root:string, inputs:AiaInputs, path:string[]) : Promise<Completion[]> { let url = root + "/completions/" + path.join("/") let header = Object.keys(inputs).map(k => k + "=" + inputs[k]).join(",") let response = await axios.get(url, {headers:{Inputs:header}}); return response.data.map((r:any) => ({ name: r.name, path:r.path.split("/").filter((p:string) => p != "") })); } async function getValue(blob:string, preview:boolean, datastoreURI:string) : Promise<any> { var pathname = new URL(blob).pathname; Log.trace("aiassistant", "getValue pathname: %s datastoreURI: %s ", pathname, datastoreURI) let headers = {'Accept': 'application/json'} let url = datastoreURI.concat(pathname) if (preview) url = url.concat("?nrow=10") Log.trace("aiassistant", "getValue Getting dataframe from: %s", url) let response = await axios.get(url, {headers: headers}); Log.trace("aiassistant", "getValue Got data frame (%s rows): %s", response.data.length, url) return response.data } async function getResult(root:string, hash:string, name:string, inputs:AiaInputs, path:string[], datastoreURI:string) : Promise<Values.DataFrame> { Log.trace("aiassistant", "getResult Datastore URL: %s", datastoreURI) let url = root + "/data/" + hash + "/" + name + "/" + path.join("/") Log.trace("aiassistant","getResult DatastoreURI:%s", datastoreURI) Log.trace("aiassistant","getResult url:%s", url) let header = Object.keys(inputs).map(k => k + "=" + inputs[k]).join(",") Log.trace("aiassistant","getResult headers:%s", JSON.stringify(header)) let response = await axios.get(url, {headers:{Inputs:header}}); let frameString = response.data Log.trace("aiassistant","getResult to get value from url:%s", JSON.stringify(frameString)) return { kind: "dataframe", url: frameString, preview: await getValue(frameString, true, datastoreURI), data: new AsyncLazy<any>(() => getValue(frameString,false, datastoreURI)) } } /* async function mergeDataFrames(variableName:string, hash:string, vals:Values.KnownValue[]) : Promise<Values.DataFrame> { var allData : any[] = [] for(let v of vals) { if (v.kind=='dataframe') allData = allData.concat(await v.data.getValue()) } let lazyData = new AsyncLazy<any[]>(async () => allData) let preview = allData.slice(0, 100) let url = await putValue(variableName, hash, allData) return { kind: "dataframe", url: url, data: lazyData, preview: preview } } */ let createAiaEditor = (assistants:AiAssistant[]) : Langs.Editor<AiaState, AiaEvent> => ({ initialize: (id:number, block:Langs.Block) => { let aiaBlock = <AiaBlock>block return { id: id, block: aiaBlock, chain: [], expanded: false, assistants: assistants, inputs: {}, frame: "" } }, update: (state:AiaState, event:AiaEvent) => { switch(event.kind) { case "completions": return state; case "expand": return { ...state, expanded:event.expanded } } }, render: (cell:Langs.BlockState, state:AiaState, ctx:Langs.EditorContext<AiaEvent>) => { let aiaNode = <AiaCodeNode>cell.code function triggerRemove() { let newCode = format(aiaNode.assistant, aiaNode.inputs, state.block.newFrame, aiaNode.chain.slice(0, aiaNode.chain.length-1)) ctx.rebindSubsequent(cell, newCode); ctx.evaluate(cell.editor.id) } function triggerComplete(completion:Completion) { let newCode = format(aiaNode.assistant, aiaNode.inputs, state.block.newFrame, aiaNode.chain.concat(completion)) ctx.rebindSubsequent(cell, newCode); ctx.evaluate(cell.editor.id) } function triggerAssistant(name:string|null, inputs:AiaInputs) { Log.trace("aiaworkflow", "render: triggerAssistant") let ins = Object.keys(inputs).map(k => k + "=" + inputs[k]).join(",") ctx.rebindSubsequent(cell, name==null?"":(name + (ins != "" ? (":" + ins) : "") + "\n" + state.block.newFrame)) if (name != null && Object.keys(inputs).length > 0) ctx.evaluate(cell.editor.id) } function triggerFrameName(name:string) { let newCode = format(aiaNode.assistant, aiaNode.inputs, name, aiaNode.chain) ctx.rebindSubsequent(cell, newCode); ctx.evaluate(cell.editor.id) } if (aiaNode.assistant == null || Object.keys(aiaNode.inputs).length != aiaNode.assistant.inputs.length) { Log.trace("aiaworkflow", "render: not enough inputs") return h('div', {class:'aia'}, [ h('ul', {}, state.assistants.map(as => { let dropdowns = as.inputs.map(inp => h('div', {}, [ h('span', {}, [ inp+": " ]), h('select', { onchange:(e) => { let inps = { ...aiaNode.inputs } if ((<any>e.target).value == "") delete inps[inp] else inps[inp] = (<any>e.target).value Log.trace('aiaworkflow', "render New Frame Name: ", state.block.newFrame) triggerAssistant(aiaNode.assistant == null?null:aiaNode.assistant.name, inps) } }, [""].concat(aiaNode.framesInScope).map(f => h('option', aiaNode.inputs[inp] == f ? { key:f, value:f, selected:true } : { key:f, value:f }, [f==""?"(no frame selected)":f]) )) ]) ) let link = (aiaNode.assistant != null && aiaNode.assistant.name == as.name) ? h('strong', {}, [ as.name ]) : h('strong', {}, [ h('a', { href: "javascript:;", onclick: () => triggerAssistant(as.name, {}) }, [ as.name ]) ]) let tools = (aiaNode.assistant != null && aiaNode.assistant.name == as.name) ? [ h('div', {class:'tools'}, dropdowns) ] : [] return h('li', {}, [ link, " - ", as.description, h('br', {}, []) ].concat(tools)) })) ]) } else { Log.trace("aiaworkflow", "render: enough inputs") var i = 0; let chain = aiaNode.chain.map(item => { var body : any[] = [ item.name ] if (++i == aiaNode.chain.length) body.push(h('button', { onclick:() => triggerRemove() }, [ h('i', { class:'fa fa-times'}) ])) return h('span', {key:'e'+i.toString(), class:'chain'}, body) }) var plusBody = [ h('button', {}, [ h('i', { class:'fa fa-plus'}) ]) ]; if (state.expanded) { if (aiaNode.completions) { plusBody.push( h('div', {class:'completion'}, aiaNode.completions.map(compl => h('a', {key:compl.name, class:'item', onclick:() => triggerComplete(compl) }, [ compl.name ]) ) ) ); } else { var path: string[] = [] if (aiaNode.chain.length > 0) path = aiaNode.chain[aiaNode.chain.length-1].path; let allValues = Object.keys(aiaNode.inputNodes).reduce((b, n) => b && null != aiaNode.inputNodes[n].value, true) if (allValues) { var inputs : AiaInputs = {} for(let k of Object.keys(aiaNode.inputNodes)) inputs[k] = (<Values.DataFrame>aiaNode.inputNodes[k].value).url getCompletions(aiaNode.assistant.root, inputs, path).then(completions => { aiaNode.completions = completions; ctx.trigger({kind:"completions"}) }) plusBody.push(h('div', {class:'completion'}, [ h('span', {class:'item'}, [ "loading..." ]) ])); } else { plusBody.push(h('div', {class:'completion'}, [ h('span', {class:'item'}, [ "evaluating..." ]) ])); } } } let plus = h('div', {class:'plus', onclick:(e) => { e.cancelBubble = true ctx.evaluate(cell.editor.id) ctx.trigger({ kind:"expand", expanded:!state.expanded }) } }, plusBody) let ins = Object.keys(aiaNode.inputs).map(k => k + ": " + aiaNode.inputs[k]).join(", ") let aiaBody: any[] = [ aiaNode.assistant.name + "(" + ins + ")" ] if (aiaNode.chain.length == 0) aiaBody.push(h('button', { onclick:() => triggerAssistant(null, {}) }, [ h('i', { class:'fa fa-times'}) ])) let aia = h('span', {key:'e', class:'chain'}, aiaBody) let def = [ h('span', {class:'text'}, ["output"]), h('input', { value:state.block.newFrame, placeholder:'<name>', onchange: (e) => triggerFrameName((<any>e.target).value) }, []), h('span', {class:'text'}, [ " = " ]) ] let previewButton = h('button', { class:'preview-button', onclick:() => { Log.trace("editor", "Evaluate button clicked in external language plugin") ctx.evaluate(cell.editor.id) } }, ["Evaluate!"] ) let spinner = h('i', {class: 'fa fa-spinner fa-spin' }, []) let preview = h('div', {class:'preview'}, [ (cell.code.value == undefined) ? (cell.evaluationState == 'pending') ? spinner : previewButton : (createOutputPreview(cell, () => {}, 0, <Values.ExportsValue>cell.code.value))]); return h('div', { class:'aia', onclick:() => ctx.trigger({kind:"expand", expanded:false}) }, [ h('div', { key:'body', class:'body' }, def.concat(aia,chain,plus)), preview ]); } } }) interface AiaCodeNode extends Graph.Node { kind: 'code' chain: Completion[] assistant: AiAssistant | null completions: Completion[] | null framesInScope: string[] inputNodes: { [input:string]:Graph.Node } //newFrame: string inputs: AiaInputs } interface AiaExportNode extends Graph.ExportNode { kind: 'export' aiaNode: AiaCodeNode } type AiaNode = AiaCodeNode | AiaExportNode export interface AiAssistant { name: string description: string inputs: string[] root: string } export class AiaLanguagePlugin implements Langs.LanguagePlugin { readonly language: string = "ai assistant" readonly iconClassName: string = "fa fa-magic" readonly editor: Langs.Editor<Langs.EditorState, any> private readonly assistants:AiAssistant[]; readonly datastoreURI: string; constructor (assistants:AiAssistant[], datastoreUri: string) { this.assistants = assistants this.editor = createAiaEditor(assistants) this.datastoreURI = datastoreUri Log.trace("aiassistant", "Constructor Datastore URL: %s", this.datastoreURI) } getDefaultCode(id:number) { return "" } parse (code:string) : Langs.Block { let parsed = parse(code) var block: AiaBlock = { language: "ai assistant", code: [], assistant: null, inputs: {}, newFrame: "" } for(var a of this.assistants) if (a.name == parsed.assistant) block = { language: "ai assistant", code: parsed.chain, assistant: a, inputs:parsed.inputs, newFrame:parsed.frame } return <Langs.Block>block } async bind(context: Langs.BindingContext, block: Langs.Block) : Promise<Langs.BindingResult> { let aiaBlock = <AiaBlock>block Log.trace("aiaworkflow", "Bind: block: %O", block) let ants : Graph.Node[] = [] let ins : {[input:string]:Graph.Node} = {} for(let k of Object.keys(aiaBlock.inputs)) { let nd = context.scope[aiaBlock.inputs[k]] ants.push(nd) ins[k] = nd; } Log.trace("aiaworkflow", "Bind: inputs: %O", ins) let antsHash = Md5.hashStr(ants.map(a => a.hash).join("-")) let anonBlock:AiaBlock = { ...aiaBlock, newFrame:"" } let initialNode:AiaCodeNode = { kind: 'code', language: this.language, antecedents: ants, hash: <string>Md5.hashStr(antsHash + this.save(anonBlock)), chain: aiaBlock.code, assistant: aiaBlock.assistant, completions: null, inputs: aiaBlock.inputs, inputNodes: ins, framesInScope: Object.keys(context.scope), //newFrame: aiaBlock.newFrame, value: null, errors: [] } let node = <AiaCodeNode>context.cache.tryFindNode(initialNode) Log.trace("aiaworkflow", "Bind: hash: %s (ant hash: %s), block:", node.hash, antsHash, this.save(anonBlock)) var exps : AiaExportNode[] = [] if (aiaBlock.newFrame != "") { let initialExpNode: AiaExportNode = { kind: 'export', language: this.language, antecedents: [node], hash: <string>Md5.hashStr(antsHash + aiaBlock.newFrame + this.save(block)), aiaNode: node, variableName: aiaBlock.newFrame, value: null, errors: [] } let exp = <AiaExportNode>context.cache.tryFindNode(initialExpNode) exps.push(exp); } return { code: node, exports: exps, resources: [] }; } async evaluate(context:Langs.EvaluationContext, node:Graph.Node) : Promise<Langs.EvaluationResult> { let aiaNode = <AiaNode>node switch(aiaNode.kind) { case 'code': Log.trace('aiaworkflow', "evaluate code Evaluation started") let res : { [key:string]: Values.KnownValue } = {} //let newFrame = aiaNode.newFrame == "" ? "<name>" : aiaNode.newFrame; if (aiaNode.assistant != null) { //&&(newFrame != "<name>")) { if (aiaNode.assistant.inputs.length == Object.keys(aiaNode.inputNodes).length) { let path = aiaNode.chain.length > 0 ? aiaNode.chain[aiaNode.chain.length-1].path : [] var inputs : AiaInputs = {} for(let k of Object.keys(aiaNode.inputNodes)) { inputs[k] = (<Values.DataFrame>aiaNode.inputNodes[k].value).url // Log.trace("aiassistant", "evaluate Evaluate input [%s]: %s", k, JSON.stringify(aiaNode.inputNodes[k].value)) } // Log.trace("aiassistant", "evaluate Evaluate root: %s", aiaNode.assistant.root) // Log.trace("aiassistant", "evaluate Evaluate hash: %s", aiaNode.hash) // Log.trace("aiassistant", "evaluate Evaluate newFrame: %s", newFrame) // Log.trace("aiassistant", "evaluate Evaluate inputs: %s", JSON.stringify(inputs)) // Log.trace("aiassistant", "evaluate Evaluate path: %s", path) // Log.trace("aiassistant", "evaluate Evaluate Datastore URL: %s", this.datastoreURI) let merged = await getResult(aiaNode.assistant.root, aiaNode.hash, "result", inputs, path, this.datastoreURI) res["result"] = merged } } let exps : Values.ExportsValue = { kind:"exports", exports: res } // Log.trace('aiassistant', "evaluate code Evaluation success") return { kind: "success", value: exps } case 'export': let expsVal = <Values.ExportsValue>aiaNode.aiaNode.value // Log.trace('aiassistant', "evaluate export Evaluation success") return { kind: "success", value: expsVal.exports["result"] } //aiaNode.aiaNode.newFrame] } } } save(block:Langs.Block) { let aiaBlock = <AiaBlock>block return format(aiaBlock.assistant, aiaBlock.inputs, aiaBlock.newFrame, aiaBlock.code) } } export async function createAiaPlugin(url:string, datastoreURI:string) : Promise<AiaLanguagePlugin> { let response = await axios.get(url); let aia : AiAssistant[] = response.data; for(var i = 0; i< aia.length; i++) aia[i].root = url + "/" + aia[i].root; Log.trace("aiassistant","createAiaPlugin DatastoreURI:%s", datastoreURI) return new AiaLanguagePlugin(aia, datastoreURI); }
the_stack
import { DOCUMENT_PERMISSION_LEVELS } from '../constants.mjs'; import { hasImageExtension, isColorString, isJSON } from './validators.mjs'; import { Document } from '../abstract/module.mjs'; import { FieldReturnType } from '../../../types/helperTypes'; /** * A required boolean field which may be used in a Document. */ export const BOOLEAN_FIELD: BooleanField; /** * Property type: `boolean` * Constructor type: `boolean | null | undefined` * Default: `false` */ interface BooleanField extends DocumentField<boolean> { type: typeof Boolean; required: true; default: false; } /** * A standard string color field which may be used in a Document. */ export const COLOR_FIELD: ColorField; /** * Property type: `string | null | undefined` * Constructor type: `string | null | undefined` */ interface ColorField extends DocumentField<string> { type: typeof String; required: false; nullable: true; validate: typeof isColorString; validationError: '{name} {field} "{value}" is not a valid hexadecimal color string'; } /** * A standard string field for an image file path which may be used in a Document. */ export const IMAGE_FIELD: ImageField; /** * Property type: `string | null | undefined` * Constructor type: `string | null | undefined` */ interface ImageField extends DocumentField<string> { type: typeof String; required: false; nullable: true; validate: typeof hasImageExtension; validationError: '{name} {field} "{value}" does not have a valid image file extension'; } /** * A standard string field for a video or image file path may be used in a Document. */ export const VIDEO_FIELD: VideoField; /** * Property type: `string | null | undefined` * Constructor type: `string | null | undefined` */ interface VideoField extends DocumentField<string> { type: typeof String; required: false; nullable: true; validate: (src: string | null) => boolean; validationError: '{name} {field} "{value}" does not have a valid image or video file extension'; } /** * A standard string field for an audio file path which may be used in a Document. */ export const AUDIO_FIELD: AudioField; /** * Property type: `string | null | undefined` * Constructor type: `string | null | undefined` */ interface AudioField extends DocumentField<string> { type: typeof String; required: false; nullable: true; validate: (src: string | null) => boolean; validationError: '{name} {field} "{value}" does not have a valid audio file extension'; } /** * A standard integer field which may be used in a Document. */ export const INTEGER_FIELD: IntegerField; /** * Property type: `number | undefined` * Constructor type: `number | null | undefined` */ interface IntegerField extends DocumentField<number> { type: typeof Number; required: false; validate: typeof Number.isInteger; validationError: '{name} {field} "{value}" does not have an integer value'; } /** * A string field which contains serialized JSON data that may be used in a Document. */ export const JSON_FIELD: JsonField; /** * Property type: `string | undefined` * Constructor type: `string | object | null | undefined` */ interface JsonField extends DocumentField<string> { type: typeof String; required: false; clean: (s: unknown) => string; validate: typeof isJSON; validationError: '{name} {field} "{value}" is not a valid JSON string'; } /** * A non-negative integer field which may be used in a Document. */ export const NONNEGATIVE_INTEGER_FIELD: NonnegativeIntegerField; /** * Property type: `number | undefined` * Constructor type: `number | null | undefined` */ interface NonnegativeIntegerField extends DocumentField<number> { type: typeof Number; required: false; validate: (n: unknown) => boolean; validationError: '{name} {field} "{value}" does not have an non-negative integer value'; } /** * A non-negative integer field which may be used in a Document. * * @remarks The validation actually checks for `> 0`, the JSDoc is incorrect in foundry. */ export const POSITIVE_INTEGER_FIELD: PositiveIntegerField; /** * Property type: `number | undefined` * Constructor type: `number | null | undefined` */ interface PositiveIntegerField extends DocumentField<number> { type: typeof Number; required: false; validate: (n: unknown) => boolean; validationError: '{name} {field} "{value}" does not have an non-negative integer value'; } /** * A template for a required inner-object field which may be used in a Document. */ export const OBJECT_FIELD: ObjectField; /** * Property type: `object` * Constructor type: `object | null | undefined` * Default `{}` */ interface ObjectField extends DocumentField<object> { type: typeof Object; default: Record<string, never>; required: true; } /** * An optional string field which may be included by a Document. */ export const STRING_FIELD: StringField; /** * Property type: `string | undefined` * Constructor type: `string | null | undefined` */ interface StringField extends DocumentField<string> { type: typeof String; required: false; nullable: false; } /** * An optional numeric field which may be included in a Document. */ export const NUMERIC_FIELD: NumericField; /** * Property type: `number | null | undefined` * Constructor type: `number | null | undefined` */ interface NumericField extends DocumentField<number> { type: typeof Number; required: false; nullable: true; } /** * A required numeric field which may be included in a Document and may not be null. */ export const REQUIRED_NUMBER: RequiredNumber; /** * Property type: `number` * Constructor type: `number | null | undefined` * Default: `0` */ interface RequiredNumber extends DocumentField<number> { type: typeof Number; required: true; nullable: false; default: 0; } /** * A field used to designate a non-negative number */ export const NONNEGATIVE_NUMBER_FIELD: NonnegativeNumberField; /** * Property type: `number` * Constructor type: `number | null | undefined` * Default: `0` */ interface NonnegativeNumberField extends DocumentField<number> { type: typeof Number; required: true; nullable: false; default: 0; validate: (n: unknown) => boolean; validationError: '{name} {field} "{value}" must be a non-negative number'; } /** * A required numeric field which must be a positive finite value that may be included in a Document. */ export const REQUIRED_POSITIVE_NUMBER: RequiredPositiveNumber; /** * Property type: `number` * Constructor type: `number` */ interface RequiredPositiveNumber extends DocumentField<number> { type: typeof Number; required: true; nullable: false; validate: (n: unknown) => boolean; validationError: '{name} {field} "{value}" is not a positive number'; } /** * A required numeric field which represents an angle of rotation in degrees between 0 and 360. */ export const ANGLE_FIELD: AngleField; /** * Property type: `number` * Constructor type: `number | null | undefined` * Default: `360` */ interface AngleField extends DocumentField<number> { type: typeof Number; required: true; nullable: false; default: 360; clean: (n: unknown) => number; validate: (n: number) => boolean; validationError: '{name} {field} "{value}" is not a number between 0 and 360'; } /** * A required numeric field which represents a uniform number between 0 and 1. */ export const ALPHA_FIELD: AlphaField; /** * Property type: `number` * Constructor type: `number | null | undefined` * Default: `1` */ interface AlphaField extends DocumentField<number> { type: typeof Number; required: true; nullable: false; default: 1; validate: (n: number) => boolean; validationError: '{name} {field} "{value}" is not a number between 0 and 1'; } /** * A string field which requires a non-blank value and may not be null. */ export const REQUIRED_STRING: RequiredString; /** * Property type: `string` * Constructor type: `string` */ interface RequiredString extends DocumentField<string> { type: typeof String; required: true; nullable: false; clean: <T>(v: T) => T extends undefined ? undefined : string; } /** * A string field which is required, but may be left blank as an empty string. */ export const BLANK_STRING: BlankString; /** * Property type: `string` * Constructor type: `string | null | undefined` * Default: `""` */ interface BlankString extends DocumentField<string> { type: typeof String; required: true; nullable: false; clean: (v: unknown) => string; default: ''; } /** * A field used for integer sorting of a Document relative to its siblings */ export const INTEGER_SORT_FIELD: IntegerSortField; /** * Property type: `number` * Constructor type: `number | null | undefined` * Default: `0` */ interface IntegerSortField extends DocumentField<number> { type: typeof Number; required: true; default: 0; validate: typeof Number.isInteger; validationError: '{name} {field} "{value}" is not an integer'; } /** * A numeric timestamp field which may be used in a Document. */ export const TIMESTAMP_FIELD: TimestampField; /** * Property type: `number | undefined` * Constructor type: `number | null | undefined` * Default: `Date.now()` */ interface TimestampField extends DocumentField<number> { type: typeof Number; required: false; default: typeof Date.now; nullable: false; } /** * Validate that the ID of a Document object is either null (not yet saved) or a valid string. * @param id - The _id to test * @returns Is it valid? */ declare function _validateId(id: string | null): boolean; /** * The standard identifier for a Document. */ export const DOCUMENT_ID: DocumentId; /** * Property type: `string | null` * Constructor type: `string | null | undefined` * Default: `null` */ interface DocumentId extends DocumentField<string | null> { type: typeof String; required: true; default: null; nullable: false; validate: typeof _validateId; validationError: '{name} {field} "{value}" is not a valid document ID string'; } /** * The standard permissions object which may be included by a Document. */ export const DOCUMENT_PERMISSIONS: DocumentPermissions; /** * Property type: `Partial<Record<string, DOCUMENT_PERMISSION_LEVELS>>` * Constructor type: `Partial<Record<string, DOCUMENT_PERMISSION_LEVELS>> | null | undefined` * Default: `{ default: DOCUMENT_PERMISSION_LEVELS.NONE }` */ interface DocumentPermissions extends DocumentField<Partial<Record<string, DOCUMENT_PERMISSION_LEVELS>>> { type: typeof Object; required: true; nullable: false; default: { default: typeof DOCUMENT_PERMISSION_LEVELS.NONE }; validate: typeof _validatePermissions; validationError: '{name} {field} "{value}" is not a mapping of user IDs and document permission levels'; } /** * Validate the structure of the permissions object: all keys are valid IDs and all values are permission levels * @param perms - The provided permissions object * @returns Is the object valid? */ declare function _validatePermissions(perms: object): boolean; interface ForeignDocumentFieldOptions { type: { readonly documentName: string; }; required?: boolean; nullable?: boolean; default?: any; } /** * Create a foreign key field which references a primary Document id */ export function foreignDocumentField<T extends ForeignDocumentFieldOptions>(options: T): ForeignDocumentField<T>; /** * Default config: * ``` * { * type: String, * required: false, * nullable: true, * default: null * } * ``` * With default config: * Property type: `string | null` * Constructor type: `ForeignDocument | string | null | undefined` * Default: `null` */ interface ForeignDocumentField<T extends ForeignDocumentFieldOptions> extends DocumentField<string | null> { type: typeof String; required: T extends { required: true; } ? true : false; nullable: T extends { nullable?: true; } ? true : T extends { nullable: false; } ? false : boolean; default: T extends { default: infer U; } ? U : null; clean: (d: unknown) => string | null; validate: typeof _validateId; validationError: `{name} {field} "{value}" is not a valid ${T['type']['documentName']} id`; } interface EmbeddedCollectionFieldOptions { required?: boolean; default?: any[]; } /** * Create a special field which contains a Collection of embedded Documents * @param document - The Document class definition * @param options - Additional field options * (default: `{}`) */ export function embeddedCollectionField< ConcreteDocumentConstructor extends { readonly documentName: string } & ConstructorOf<Document<any, any>>, Options extends EmbeddedCollectionFieldOptions >( document: ConcreteDocumentConstructor, options?: Options ): EmbeddedCollectionField<ConcreteDocumentConstructor, Options>; /** * Default config: * ``` * { * type: { * [documentName]: DocumentConstructor * }, * required: true, * default: [], * isCollection: true * } * ``` * With default config: * Property type: `EmbeddedCollection<DocumentConstructor, ParentDocumentData>` * Constructor type: `DocumentConstructorData[] | null | undefined` * Default: `new EmbeddedCollection(DocumentData, [], DocumentConstructor)` */ // TODO: Improve interface EmbeddedCollectionField< ConcreteDocumentConstructor extends ConstructorOf<Document<any, any>>, Options extends EmbeddedCollectionFieldOptions = {} > extends DocumentField<any> { type: Partial<Record<string, ConcreteDocumentConstructor>>; required: Options extends { required?: true } ? true : Options extends { required: false } ? false : boolean; default: Options extends { default?: Array<infer U> } ? Array<U> : unknown[]; isCollection: true; } /** * A special field which contains a data object defined from the game System model. * @param document - The Document class definition */ export function systemDataField< DocumentSpecifier extends { readonly documentName: keyof Game.SystemData<any>['model'] } >(document: DocumentSpecifier): SystemDataField; /** * Default config: * ``` * { * type: Object, * required: true, * default: object // template object of object type from template.json * } * ``` * Property type: `object` * Constructor type: `object | null | undefined` * Default: `{}` */ // TODO: Improve interface SystemDataField extends DocumentField<any> { type: typeof Object; default: (data: { type?: string }) => Record<string, Record<string, unknown>>; required: true; } /** * Return a document field which is a modification of a static field type */ export function field<T extends DocumentField<any>, U extends Partial<DocumentField<any>>>( field: T, options?: U ): FieldReturnType<T, U>;
the_stack
import { HttpSuccess } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { HttpInfrastructureClient } from "../httpInfrastructureClient"; import { HttpSuccessHead200OptionalParams, HttpSuccessGet200OptionalParams, HttpSuccessGet200Response, HttpSuccessOptions200OptionalParams, HttpSuccessOptions200Response, HttpSuccessPut200OptionalParams, HttpSuccessPatch200OptionalParams, HttpSuccessPost200OptionalParams, HttpSuccessDelete200OptionalParams, HttpSuccessPut201OptionalParams, HttpSuccessPost201OptionalParams, HttpSuccessPut202OptionalParams, HttpSuccessPatch202OptionalParams, HttpSuccessPost202OptionalParams, HttpSuccessDelete202OptionalParams, HttpSuccessHead204OptionalParams, HttpSuccessPut204OptionalParams, HttpSuccessPatch204OptionalParams, HttpSuccessPost204OptionalParams, HttpSuccessDelete204OptionalParams, HttpSuccessHead404OptionalParams } from "../models"; /** Class containing HttpSuccess operations. */ export class HttpSuccessImpl implements HttpSuccess { private readonly client: HttpInfrastructureClient; /** * Initialize a new instance of the class HttpSuccess class. * @param client Reference to the service client */ constructor(client: HttpInfrastructureClient) { this.client = client; } /** * Return 200 status code if successful * @param options The options parameters. */ head200(options?: HttpSuccessHead200OptionalParams): Promise<void> { return this.client.sendOperationRequest({ options }, head200OperationSpec); } /** * Get 200 success * @param options The options parameters. */ get200( options?: HttpSuccessGet200OptionalParams ): Promise<HttpSuccessGet200Response> { return this.client.sendOperationRequest({ options }, get200OperationSpec); } /** * Options 200 success * @param options The options parameters. */ options200( options?: HttpSuccessOptions200OptionalParams ): Promise<HttpSuccessOptions200Response> { return this.client.sendOperationRequest( { options }, options200OperationSpec ); } /** * Put boolean value true returning 200 success * @param options The options parameters. */ put200(options?: HttpSuccessPut200OptionalParams): Promise<void> { return this.client.sendOperationRequest({ options }, put200OperationSpec); } /** * Patch true Boolean value in request returning 200 * @param options The options parameters. */ patch200(options?: HttpSuccessPatch200OptionalParams): Promise<void> { return this.client.sendOperationRequest({ options }, patch200OperationSpec); } /** * Post bollean value true in request that returns a 200 * @param options The options parameters. */ post200(options?: HttpSuccessPost200OptionalParams): Promise<void> { return this.client.sendOperationRequest({ options }, post200OperationSpec); } /** * Delete simple boolean value true returns 200 * @param options The options parameters. */ delete200(options?: HttpSuccessDelete200OptionalParams): Promise<void> { return this.client.sendOperationRequest( { options }, delete200OperationSpec ); } /** * Put true Boolean value in request returns 201 * @param options The options parameters. */ put201(options?: HttpSuccessPut201OptionalParams): Promise<void> { return this.client.sendOperationRequest({ options }, put201OperationSpec); } /** * Post true Boolean value in request returns 201 (Created) * @param options The options parameters. */ post201(options?: HttpSuccessPost201OptionalParams): Promise<void> { return this.client.sendOperationRequest({ options }, post201OperationSpec); } /** * Put true Boolean value in request returns 202 (Accepted) * @param options The options parameters. */ put202(options?: HttpSuccessPut202OptionalParams): Promise<void> { return this.client.sendOperationRequest({ options }, put202OperationSpec); } /** * Patch true Boolean value in request returns 202 * @param options The options parameters. */ patch202(options?: HttpSuccessPatch202OptionalParams): Promise<void> { return this.client.sendOperationRequest({ options }, patch202OperationSpec); } /** * Post true Boolean value in request returns 202 (Accepted) * @param options The options parameters. */ post202(options?: HttpSuccessPost202OptionalParams): Promise<void> { return this.client.sendOperationRequest({ options }, post202OperationSpec); } /** * Delete true Boolean value in request returns 202 (accepted) * @param options The options parameters. */ delete202(options?: HttpSuccessDelete202OptionalParams): Promise<void> { return this.client.sendOperationRequest( { options }, delete202OperationSpec ); } /** * Return 204 status code if successful * @param options The options parameters. */ head204(options?: HttpSuccessHead204OptionalParams): Promise<void> { return this.client.sendOperationRequest({ options }, head204OperationSpec); } /** * Put true Boolean value in request returns 204 (no content) * @param options The options parameters. */ put204(options?: HttpSuccessPut204OptionalParams): Promise<void> { return this.client.sendOperationRequest({ options }, put204OperationSpec); } /** * Patch true Boolean value in request returns 204 (no content) * @param options The options parameters. */ patch204(options?: HttpSuccessPatch204OptionalParams): Promise<void> { return this.client.sendOperationRequest({ options }, patch204OperationSpec); } /** * Post true Boolean value in request returns 204 (no content) * @param options The options parameters. */ post204(options?: HttpSuccessPost204OptionalParams): Promise<void> { return this.client.sendOperationRequest({ options }, post204OperationSpec); } /** * Delete true Boolean value in request returns 204 (no content) * @param options The options parameters. */ delete204(options?: HttpSuccessDelete204OptionalParams): Promise<void> { return this.client.sendOperationRequest( { options }, delete204OperationSpec ); } /** * Return 404 status code * @param options The options parameters. */ head404(options?: HttpSuccessHead404OptionalParams): Promise<void> { return this.client.sendOperationRequest({ options }, head404OperationSpec); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const head200OperationSpec: coreClient.OperationSpec = { path: "/http/success/200", httpMethod: "HEAD", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const get200OperationSpec: coreClient.OperationSpec = { path: "/http/success/200", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Boolean" } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const options200OperationSpec: coreClient.OperationSpec = { path: "/http/success/200", httpMethod: "OPTIONS", responses: { 200: { bodyMapper: { type: { name: "Boolean" } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const put200OperationSpec: coreClient.OperationSpec = { path: "/http/success/200", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.booleanValue, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const patch200OperationSpec: coreClient.OperationSpec = { path: "/http/success/200", httpMethod: "PATCH", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.booleanValue, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const post200OperationSpec: coreClient.OperationSpec = { path: "/http/success/200", httpMethod: "POST", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.booleanValue, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const delete200OperationSpec: coreClient.OperationSpec = { path: "/http/success/200", httpMethod: "DELETE", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.booleanValue, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const put201OperationSpec: coreClient.OperationSpec = { path: "/http/success/201", httpMethod: "PUT", responses: { 201: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.booleanValue, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const post201OperationSpec: coreClient.OperationSpec = { path: "/http/success/201", httpMethod: "POST", responses: { 201: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.booleanValue, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const put202OperationSpec: coreClient.OperationSpec = { path: "/http/success/202", httpMethod: "PUT", responses: { 202: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.booleanValue, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const patch202OperationSpec: coreClient.OperationSpec = { path: "/http/success/202", httpMethod: "PATCH", responses: { 202: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.booleanValue, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const post202OperationSpec: coreClient.OperationSpec = { path: "/http/success/202", httpMethod: "POST", responses: { 202: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.booleanValue, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const delete202OperationSpec: coreClient.OperationSpec = { path: "/http/success/202", httpMethod: "DELETE", responses: { 202: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.booleanValue, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const head204OperationSpec: coreClient.OperationSpec = { path: "/http/success/204", httpMethod: "HEAD", responses: { 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const put204OperationSpec: coreClient.OperationSpec = { path: "/http/success/204", httpMethod: "PUT", responses: { 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.booleanValue, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const patch204OperationSpec: coreClient.OperationSpec = { path: "/http/success/204", httpMethod: "PATCH", responses: { 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.booleanValue, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const post204OperationSpec: coreClient.OperationSpec = { path: "/http/success/204", httpMethod: "POST", responses: { 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.booleanValue, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const delete204OperationSpec: coreClient.OperationSpec = { path: "/http/success/204", httpMethod: "DELETE", responses: { 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.booleanValue, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const head404OperationSpec: coreClient.OperationSpec = { path: "/http/success/404", httpMethod: "HEAD", responses: { 204: {}, 404: {}, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer };
the_stack
import * as cdk from '@aws-cdk/core'; import { EmrCreateCluster } from '../emr-create-cluster'; import { EmrModifyInstanceGroupByName } from '../emr-modify-instance-group-by-name'; /** * Render the KerberosAttributesProperty as JSON * * @param property */ export function KerberosAttributesPropertyToJson(property: EmrCreateCluster.KerberosAttributesProperty) { return { ADDomainJoinPassword: cdk.stringToCloudFormation(property.adDomainJoinPassword), ADDomainJoinUser: cdk.stringToCloudFormation(property.adDomainJoinUser), CrossRealmTrustPrincipalPassword: cdk.stringToCloudFormation(property.crossRealmTrustPrincipalPassword), KdcAdminPassword: cdk.stringToCloudFormation(property.kdcAdminPassword), Realm: cdk.stringToCloudFormation(property.realm), }; } /** * Render the InstancesConfigProperty to JSON * * @param property */ export function InstancesConfigPropertyToJson(property: EmrCreateCluster.InstancesConfigProperty) { return { AdditionalMasterSecurityGroups: cdk.listMapper(cdk.stringToCloudFormation)(property.additionalMasterSecurityGroups), AdditionalSlaveSecurityGroups: cdk.listMapper(cdk.stringToCloudFormation)(property.additionalSlaveSecurityGroups), Ec2KeyName: cdk.stringToCloudFormation(property.ec2KeyName), Ec2SubnetId: cdk.stringToCloudFormation(property.ec2SubnetId), Ec2SubnetIds: cdk.listMapper(cdk.stringToCloudFormation)(property.ec2SubnetIds), EmrManagedMasterSecurityGroup: cdk.stringToCloudFormation(property.emrManagedMasterSecurityGroup), EmrManagedSlaveSecurityGroup: cdk.stringToCloudFormation(property.emrManagedSlaveSecurityGroup), HadoopVersion: cdk.stringToCloudFormation(property.hadoopVersion), InstanceCount: cdk.numberToCloudFormation(property.instanceCount), InstanceFleets: cdk.listMapper(InstanceFleetConfigPropertyToJson)(property.instanceFleets), InstanceGroups: cdk.listMapper(InstanceGroupConfigPropertyToJson)(property.instanceGroups), KeepJobFlowAliveWhenNoSteps: true, MasterInstanceType: cdk.stringToCloudFormation(property.masterInstanceType), Placement: property.placement === undefined ? property.placement : PlacementTypePropertyToJson(property.placement), ServiceAccessSecurityGroup: cdk.stringToCloudFormation(property.serviceAccessSecurityGroup), SlaveInstanceType: cdk.stringToCloudFormation(property.slaveInstanceType), TerminationProtected: cdk.booleanToCloudFormation(property.terminationProtected), }; } /** * Render the ApplicationConfigProperty as JSON * * @param property */ export function ApplicationConfigPropertyToJson(property: EmrCreateCluster.ApplicationConfigProperty) { return { Name: cdk.stringToCloudFormation(property.name), Args: cdk.listMapper(cdk.stringToCloudFormation)(property.args), Version: cdk.stringToCloudFormation(property.version), AdditionalInfo: cdk.objectToCloudFormation(property.additionalInfo), }; } /** * Render the ConfigurationProperty as JSON * * @param property */ export function ConfigurationPropertyToJson(property: EmrCreateCluster.ConfigurationProperty) { return { Classification: cdk.stringToCloudFormation(property.classification), Properties: cdk.objectToCloudFormation(property.properties), Configurations: cdk.listMapper(ConfigurationPropertyToJson)(property.configurations), }; } /** * Render the EbsBlockDeviceConfigProperty as JSON * * @param property */ export function EbsBlockDeviceConfigPropertyToJson(property: EmrCreateCluster.EbsBlockDeviceConfigProperty) { return { VolumeSpecification: { Iops: cdk.numberToCloudFormation(property.volumeSpecification.iops), SizeInGB: property.volumeSpecification.volumeSize?.toGibibytes(), VolumeType: cdk.stringToCloudFormation(property.volumeSpecification.volumeType?.valueOf()), }, VolumesPerInstance: cdk.numberToCloudFormation(property.volumesPerInstance), }; } /** * Render the EbsConfigurationProperty to JSON * * @param property */ export function EbsConfigurationPropertyToJson(property: EmrCreateCluster.EbsConfigurationProperty) { return { EbsBlockDeviceConfigs: cdk.listMapper(EbsBlockDeviceConfigPropertyToJson)(property.ebsBlockDeviceConfigs), EbsOptimized: cdk.booleanToCloudFormation(property.ebsOptimized), }; } /** * Render the InstanceTypeConfigProperty to JSON] * * @param property */ export function InstanceTypeConfigPropertyToJson(property: EmrCreateCluster.InstanceTypeConfigProperty) { return { BidPrice: cdk.stringToCloudFormation(property.bidPrice), BidPriceAsPercentageOfOnDemandPrice: cdk.numberToCloudFormation(property.bidPriceAsPercentageOfOnDemandPrice), Configurations: cdk.listMapper(ConfigurationPropertyToJson)(property.configurations), EbsConfiguration: property.ebsConfiguration === undefined ? property.ebsConfiguration : EbsConfigurationPropertyToJson(property.ebsConfiguration), InstanceType: cdk.stringToCloudFormation(property.instanceType?.valueOf()), WeightedCapacity: cdk.numberToCloudFormation(property.weightedCapacity), }; } /** * Render the InstanceFleetProvisioningSpecificationsProperty to JSON * * @param property */ export function InstanceFleetProvisioningSpecificationsPropertyToJson(property: EmrCreateCluster.InstanceFleetProvisioningSpecificationsProperty) { return { SpotSpecification: { AllocationStrategy: cdk.stringToCloudFormation(property.spotSpecification.allocationStrategy), BlockDurationMinutes: cdk.numberToCloudFormation(property.spotSpecification.blockDurationMinutes), TimeoutAction: cdk.stringToCloudFormation(property.spotSpecification.timeoutAction?.valueOf()), TimeoutDurationMinutes: cdk.numberToCloudFormation(property.spotSpecification.timeoutDurationMinutes), }, }; } /** * Render the InstanceFleetConfigProperty as JSON * * @param property */ export function InstanceFleetConfigPropertyToJson(property: EmrCreateCluster.InstanceFleetConfigProperty) { return { InstanceFleetType: cdk.stringToCloudFormation(property.instanceFleetType?.valueOf()), InstanceTypeConfigs: cdk.listMapper(InstanceTypeConfigPropertyToJson)(property.instanceTypeConfigs), LaunchSpecifications: property.launchSpecifications === undefined ? property.launchSpecifications : InstanceFleetProvisioningSpecificationsPropertyToJson(property.launchSpecifications), Name: cdk.stringToCloudFormation(property.name), TargetOnDemandCapacity: cdk.numberToCloudFormation(property.targetOnDemandCapacity), TargetSpotCapacity: cdk.numberToCloudFormation(property.targetSpotCapacity), }; } /** * Render the MetricDimensionProperty as JSON * * @param property */ export function MetricDimensionPropertyToJson(property: EmrCreateCluster.MetricDimensionProperty) { return { Key: cdk.stringToCloudFormation(property.key), Value: cdk.stringToCloudFormation(property.value), }; } /** * Render the ScalingTriggerProperty to JSON * * @param property */ export function ScalingTriggerPropertyToJson(property: EmrCreateCluster.ScalingTriggerProperty) { return { CloudWatchAlarmDefinition: { ComparisonOperator: cdk.stringToCloudFormation(property.cloudWatchAlarmDefinition.comparisonOperator?.valueOf()), Dimensions: cdk.listMapper(MetricDimensionPropertyToJson)(property.cloudWatchAlarmDefinition.dimensions), EvaluationPeriods: cdk.numberToCloudFormation(property.cloudWatchAlarmDefinition.evaluationPeriods), MetricName: cdk.stringToCloudFormation(property.cloudWatchAlarmDefinition.metricName), Namespace: cdk.stringToCloudFormation(property.cloudWatchAlarmDefinition.namespace), Period: cdk.numberToCloudFormation(property.cloudWatchAlarmDefinition.period.toSeconds()), Statistic: cdk.stringToCloudFormation(property.cloudWatchAlarmDefinition.statistic?.valueOf()), Threshold: cdk.numberToCloudFormation(property.cloudWatchAlarmDefinition.threshold), Unit: cdk.stringToCloudFormation(property.cloudWatchAlarmDefinition.unit?.valueOf()), }, }; } /** * Render the ScalingActionProperty to JSON * * @param property */ export function ScalingActionPropertyToJson(property: EmrCreateCluster.ScalingActionProperty) { return { Market: cdk.stringToCloudFormation(property.market?.valueOf()), SimpleScalingPolicyConfiguration: { AdjustmentType: cdk.stringToCloudFormation(property.simpleScalingPolicyConfiguration.adjustmentType), CoolDown: cdk.numberToCloudFormation(property.simpleScalingPolicyConfiguration.coolDown), ScalingAdjustment: cdk.numberToCloudFormation(property.simpleScalingPolicyConfiguration.scalingAdjustment), }, }; } /** * Render the ScalingRuleProperty to JSON * * @param property */ export function ScalingRulePropertyToJson(property: EmrCreateCluster.ScalingRuleProperty) { return { Action: ScalingActionPropertyToJson(property.action), Description: cdk.stringToCloudFormation(property.description), Name: cdk.stringToCloudFormation(property.name), Trigger: ScalingTriggerPropertyToJson(property.trigger), }; } /** * Render the AutoScalingPolicyProperty to JSON * * @param property */ export function AutoScalingPolicyPropertyToJson(property: EmrCreateCluster.AutoScalingPolicyProperty) { return { Constraints: { MaxCapacity: cdk.numberToCloudFormation(property.constraints.maxCapacity), MinCapacity: cdk.numberToCloudFormation(property.constraints.minCapacity), }, Rules: cdk.listMapper(ScalingRulePropertyToJson)(property.rules), }; } /** * Render the InstanceGroupConfigProperty to JSON * * @param property */ export function InstanceGroupConfigPropertyToJson(property: EmrCreateCluster.InstanceGroupConfigProperty) { return { AutoScalingPolicy: property.autoScalingPolicy === undefined ? property.autoScalingPolicy : AutoScalingPolicyPropertyToJson(property.autoScalingPolicy), BidPrice: cdk.numberToCloudFormation(property.bidPrice), Configurations: cdk.listMapper(ConfigurationPropertyToJson)(property.configurations), EbsConfiguration: property.ebsConfiguration === undefined ? property.ebsConfiguration : EbsConfigurationPropertyToJson(property.ebsConfiguration), InstanceCount: cdk.numberToCloudFormation(property.instanceCount), InstanceRole: cdk.stringToCloudFormation(property.instanceRole?.valueOf()), InstanceType: cdk.stringToCloudFormation(property.instanceType), Market: cdk.stringToCloudFormation(property.market?.valueOf()), Name: cdk.stringToCloudFormation(property.name), }; } /** * Render the PlacementTypeProperty to JSON * * @param property */ export function PlacementTypePropertyToJson(property: EmrCreateCluster.PlacementTypeProperty) { return { AvailabilityZone: cdk.stringToCloudFormation(property.availabilityZone), AvailabilityZones: cdk.listMapper(cdk.stringToCloudFormation)(property.availabilityZones), }; } /** * Render the BootstrapActionProperty as JSON * * @param property */ export function BootstrapActionConfigToJson(property: EmrCreateCluster.BootstrapActionConfigProperty) { return { Name: cdk.stringToCloudFormation(property.name), ScriptBootstrapAction: { Path: cdk.stringToCloudFormation(property.scriptBootstrapAction.path), Args: cdk.listMapper(cdk.stringToCloudFormation)(property.scriptBootstrapAction.args), }, }; } /** * Render the InstanceGroupModifyConfigProperty to JSON * * @param property */ export function InstanceGroupModifyConfigPropertyToJson(property: EmrModifyInstanceGroupByName.InstanceGroupModifyConfigProperty) { return { Configurations: cdk.listMapper(ConfigurationPropertyToJson)(property.configurations), EC2InstanceIdsToTerminate: cdk.listMapper(cdk.stringToCloudFormation)(property.eC2InstanceIdsToTerminate), InstanceCount: cdk.numberToCloudFormation(property.instanceCount), ShrinkPolicy: property.shrinkPolicy === undefined ? property.shrinkPolicy : ShrinkPolicyPropertyToJson(property.shrinkPolicy), }; } /** * Render the ShrinkPolicyProperty to JSON * * @param property */ function ShrinkPolicyPropertyToJson(property: EmrModifyInstanceGroupByName.ShrinkPolicyProperty) { return { DecommissionTimeout: cdk.numberToCloudFormation(property.decommissionTimeout?.toSeconds()), InstanceResizePolicy: property.instanceResizePolicy ? InstanceResizePolicyPropertyToJson(property.instanceResizePolicy) : undefined, }; } /** * Render the InstanceResizePolicyProperty to JSON * * @param property */ function InstanceResizePolicyPropertyToJson(property: EmrModifyInstanceGroupByName.InstanceResizePolicyProperty) { return { InstancesToProtect: cdk.listMapper(cdk.stringToCloudFormation)(property.instancesToProtect), InstancesToTerminate: cdk.listMapper(cdk.stringToCloudFormation)(property.instancesToTerminate), InstanceTerminationTimeout: cdk.numberToCloudFormation(property.instanceTerminationTimeout?.toSeconds()), }; }
the_stack
// Generate and SLR parser, given a grammar // This is JavaScript version of almond-nnparser/grammar/slr.py const DEBUG = false; class ItemSetInfo { id : number; intransitions : Array<[number, string]>; outtransitions : Array<[number, string]>; constructor() { this.id = 0; this.intransitions = []; this.outtransitions = []; } } type EqualityComparable = { equals(other : unknown) : boolean; }; function arrayEquals(a : any[], b : any[]) : boolean { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (a[i] === b[i]) continue; if (Array.isArray(a[i])) { if (!arrayEquals(a[i], b[i])) return false; } else if (!a[i].equals || !a[i].equals(b[i])) { return false; } } return true; } function strictArrayEquals<T>(a : T[], b : T[]) : boolean { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) return false; } return true; } class ItemSet implements EqualityComparable { rules : Array<Tuple<[number, string[]]>>; info : ItemSetInfo; constructor(rules : Iterable<Tuple<[number, string[]]>>) { this.rules = Array.from(rules); this.info = new ItemSetInfo(); } equals(other : ItemSet) : boolean { return arrayEquals(this.rules, other.rules); } } // a python-like tuple, that compares .equals() if all elements compare equals class Tuple<ArgTypes extends unknown[]> implements EqualityComparable { stuff : ArgTypes; constructor(...args : ArgTypes) { this.stuff = args; } equals(other : Tuple<ArgTypes>) : boolean { return arrayEquals(this.stuff, other.stuff); } get<K extends number>(i : K) : ArgTypes[K] { return this.stuff[i]; } slice(from : number, to : number) : any[] { return this.stuff.slice(from, to); } } // A map that respects equals // Not asymptotically efficient class EqualsMap<K extends EqualityComparable, V> { private _keys : K[]; private _values : V[]; private _size : number; constructor(iterable ?: Iterable<[K, V]>) { this._keys = []; this._values = []; this._size = 0; if (!iterable) return; for (const [key, value] of iterable) this.set(key, value); } *[Symbol.iterator]() : Iterator<[K, V]> { for (let i = 0; i < this._keys.length; i++) yield [this._keys[i], this._values[i]]; } keys() : Iterable<K> { return this._keys; } values() : Iterable<V> { return this._values; } get size() : number { return this._size; } set(key : K, value : V) : this { for (let i = 0; i < this._keys.length; i++) { if (this._keys[i].equals(key)) { this._values[i] = value; return this; } } this._keys.push(key); this._values.push(value); this._size++; return this; } get(key : K) : V|undefined { for (let i = 0; i < this._keys.length; i++) { if (this._keys[i].equals(key)) return this._values[i]; } return undefined; } delete(key : K) : this { let idx = -1; for (let i = 0; i < this._keys.length; i++) { if (this._keys[i].equals(key)) { idx = i; break; } } if (idx < 0) return this; this._keys.splice(idx, 1); this._values.splice(idx, 1); this._size--; return this; } has(element : K) : boolean { for (let i = 0; i < this._keys.length; i++) { if (this._keys[i].equals(element)) return true; } return false; } } class EqualsSet<K extends EqualityComparable> { private _map : EqualsMap<K, undefined>; constructor(iterable ?: Iterable<K>) { this._map = new EqualsMap<K, undefined>(); if (!iterable) return; for (const v of iterable) this.add(v); } *[Symbol.iterator]() : Iterator<K> { for (const [key, ] of this._map) yield key; } get size() : number { return this._map.size; } add(v : K) : this { this._map.set(v, undefined); return this; } has(v : K) : boolean { return this._map.has(v); } delete(v : K) : this { this._map.delete(v); return this; } } interface SetLike<T> { size : number; values() : Iterable<T>; [Symbol.iterator]() : Iterator<T>; has(x : T) : boolean; } function setEquals<T>(one : SetLike<T>, two : SetLike<T>) : boolean { if (one.size !== two.size) return false; for (const elem of one.values()) { if (!two.has(elem)) return false; } return true; } const ITEM_SET_MARKER = '[ItemSetSep]'; export class Terminal implements EqualityComparable { isTerminal ! : boolean; isNonTerminal ! : boolean; symbol : string; isConstant : boolean; constructor(symbol : string, isConstant : boolean) { this.symbol = symbol; this.isConstant = isConstant; } equals(x : unknown) : boolean { return x instanceof Terminal && x.symbol === this.symbol; } toString() : string { return `T:${this.symbol}`; } toWSN() : string { if (this.isConstant) return '"' + this.symbol.replace(/"/g, '""') + '"'; else return this.symbol; } } Terminal.prototype.isTerminal = true; Terminal.prototype.isNonTerminal = false; export class NonTerminal implements EqualityComparable { isTerminal ! : boolean; isNonTerminal ! : boolean; symbol : string; constructor(symbol : string) { this.symbol = symbol; } equals(x : unknown) : boolean { return x instanceof NonTerminal && x.symbol === this.symbol; } toString() : string { return `NT:${this.symbol}`; } toWSN() : string { return this.symbol; } } NonTerminal.prototype.isTerminal = false; NonTerminal.prototype.isNonTerminal = true; const ROOT_NT = new NonTerminal('$ROOT'); // special tokens start with a space // so they sort earlier than all other tokens const PAD_TOKEN = new Terminal(' 0PAD', false); const EOF_TOKEN = new Terminal(' 1EOF', false); const START_TOKEN = new Terminal(' 2START', false); export type ProcessedRule = [Array<NonTerminal|Terminal>, string]; export type ProcessedGrammar = { [key : string] : ProcessedRule[] }; type ActionTable = Array<{ [key : string] : ['accept'|'shift'|'reduce', number] }>; type GotoTable = Array<{ [key : string] : number }>; /** * Construct a shift-reduce parser given an SLR grammar. */ export class SLRParserGenerator { private _startSymbol : string; rules ! : Array<[string, ...ProcessedRule]>; grammar ! : Map<string, number[]>; terminals ! : string[]; nonTerminals ! : string[]; gotoTable ! : GotoTable; actionTable ! : ActionTable; private _itemSets ! : ItemSet[]; private _nStates ! : number; private _firstSets ! : Map<string, Set<string>>; private _followSets ! : Map<string, Set<string>>; private _stateTransitionMatrix ! : Array<Map<string, number>>; constructor(grammar : ProcessedGrammar, startSymbol : string, rootType : string, optionType : string) { // optimizations first this._startSymbol = startSymbol; grammar[ROOT_NT.symbol] = [[[new NonTerminal(startSymbol), EOF_TOKEN], `($ : $runtime.ParserInterface<${optionType}>, $0 : ${rootType}) : ${rootType} => $0`]]; this._numberRules(grammar); this._extractTerminalsNonTerminals(); this._buildFirstSets(); this._buildFollowSets(); this._generateAllItemSets(); this._buildStateTransitionMatrix(); this._buildParseTables(); this._checkFirstSets(); this._checkFollowSets(); } get startSymbolId() { return this.terminals.length + this.nonTerminals.indexOf(this._startSymbol); } private _checkFirstSets() { for (const [lhs, firstSet] of this._firstSets) { if (firstSet.size === 0) console.log("WARNING: non-terminal " + lhs + " cannot start with any terminal"); } } private _checkFollowSets() { for (const [lhs, followSet] of this._followSets) { if (lhs === '$ROOT') continue; if (followSet.size === 0) console.log("WARNING: non-terminal " + lhs + " cannot be followed by any terminal"); } } private _extractTerminalsNonTerminals() { const terminals = new Set<string>(); terminals.add(PAD_TOKEN.symbol); terminals.add(EOF_TOKEN.symbol); terminals.add(START_TOKEN.symbol); const nonTerminals = new Set<string>(); for (const [lhs, rule,] of this.rules) { nonTerminals.add(lhs); for (const rhs of rule) { if (rhs.isTerminal) terminals.add(rhs.symbol); else nonTerminals.add(rhs.symbol); } } this.terminals = Array.from(terminals); this.terminals.sort(); this.nonTerminals = Array.from(nonTerminals); this.nonTerminals.sort(); if (DEBUG) { console.log('Terminals:', this.terminals); console.log('Non-Terminals:', this.nonTerminals); } } printRules() { for (const [lhs, rhs,] of this.rules) console.log(lhs, '->', rhs.join(' ')); } private _numberRules(grammar : ProcessedGrammar) { this.rules = []; this.grammar = new Map; for (const lhs in grammar) { const rules = grammar[lhs]; if (!Array.isArray(rules)) throw new TypeError('Invalid definition for non-terminal ' + lhs); if (rules.some((x) => !Array.isArray(x) || x.length !== 2)) throw new TypeError('Invalid definition for non-terminal ' + lhs); this.grammar.set(lhs, []); for (const [rule, action] of rules) { const ruleId = this.rules.length; for (const rhs of rule) { if (rhs.isNonTerminal && !(rhs.symbol in grammar)) throw new TypeError('Missing non-terminal ' + rhs); } this.rules.push([lhs, rule, action]); this.grammar.get(lhs)!.push(ruleId); if (DEBUG) console.log(ruleId, lhs, '->', rule); } } } private *_itemSetFollowers(itemSet : ItemSet) { const set = new Set<string>(); for (const rule of itemSet.rules) { const rhs = rule.get(1); for (let i = 0; i < rhs.length-1; i++) { if (rhs[i] === ITEM_SET_MARKER && rhs[i+1] !== EOF_TOKEN.toString()) set.add(rhs[i+1].toString()); } } yield* set; } private *_advance(itemSet : ItemSet, token : string) { for (const rule of itemSet.rules) { const [rule_id, rhs] = rule.stuff; for (let i = 0; i < rhs.length-1; i++) { if (rhs[i] === ITEM_SET_MARKER && rhs[i+1] === token) { yield new Tuple(rule_id, rhs.slice(0, i).concat([token, ITEM_SET_MARKER], rhs.slice(i+2))); break; } } } } private *_makeItemSet(lhs : string) : Generator<Tuple<[number, string[]]>, void> { for (const ruleId of this.grammar.get(lhs)!) { const [, rhs, ] = this.rules[ruleId]; yield new Tuple(ruleId, [ITEM_SET_MARKER].concat(rhs.map((h) => h.toString()))); } } private _close(items : Iterable<Tuple<[number, string[]]>>) { const itemSet = new EqualsSet(items); const stack = Array.from(itemSet); while (stack.length > 0) { const item = stack.pop()!; const rhs = item.get(1); for (let i = 0; i < rhs.length-1; i++) { if (rhs[i] === ITEM_SET_MARKER && rhs[i+1].startsWith('NT:')) { for (const newRule of this._makeItemSet(rhs[i+1].substring(3))) { if (!itemSet.has(newRule)) { itemSet.add(newRule); stack.push(newRule); } } break; } } } const itemSetArray = Array.from(itemSet); itemSetArray.sort(); return itemSetArray; } private _generateAllItemSets() { const itemSets = new EqualsMap<ItemSet, ItemSetInfo>(); let i = 0; const itemSet0 = new ItemSet(this._close(this._makeItemSet(ROOT_NT.symbol))); itemSets.set(itemSet0, itemSet0.info); i++; const queue = []; queue.push(itemSet0); while (queue.length > 0) { const itemSet = queue.shift()!; const myInfo = itemSets.get(itemSet)!; for (const nextToken of this._itemSetFollowers(itemSet)) { const newset : ItemSet = new ItemSet(this._close(this._advance(itemSet, nextToken))); let info; if (itemSets.has(newset)) { info = itemSets.get(newset)!; newset.info = info; } else { info = newset.info; info.id = i++; itemSets.set(newset, info); queue.push(newset); } info.intransitions.push([myInfo.id, nextToken]); myInfo.outtransitions.push([info.id, nextToken]); } } if (DEBUG) console.log(); for (const [itemSet, info] of itemSets) { itemSet.info = info; if (DEBUG) { console.log("Item Set", itemSet.info.id, itemSet.info.intransitions); for (const rule of itemSet.rules) { const [rule_id, rhs] = rule.stuff; const [lhs,,] = this.rules[rule_id]; console.log(rule_id, lhs, '->', rhs); } console.log(); } } const itemSetList = []; for (const [itemSet,] of itemSets) itemSetList[itemSet.info.id] = itemSet; this._itemSets = itemSetList; this._nStates = this._itemSets.length; } private _buildStateTransitionMatrix() { this._stateTransitionMatrix = []; for (let i = 0; i < this._nStates; i++) this._stateTransitionMatrix[i] = new Map; for (const itemSet of this._itemSets) { for (const [nextId, nextToken] of itemSet.info.outtransitions) { if (this._stateTransitionMatrix[itemSet.info.id].has(nextToken)) throw new Error("Ambiguous transition from " + itemSet.info.id + " through " + nextToken + " to " + this._stateTransitionMatrix[itemSet.info.id].get(nextToken) + " and " + nextId); this._stateTransitionMatrix[itemSet.info.id].set(nextToken, nextId); } } if (DEBUG) { console.log("State Transition Matrix"); for (let i = 0; i < this._nStates; i++) console.log(i, "->", this._stateTransitionMatrix[i]); } } private _buildFirstSets() { const firstSets = new Map<string, Set<string>>(); for (const nonterm of this.nonTerminals) firstSets.set(nonterm, new Set<string>()); let progress = true; while (progress) { progress = false; for (const [lhs, rules] of this.grammar) { const union = new Set<string>(); for (const rule_id of rules) { const [, rule,] = this.rules[rule_id]; let firstSetRule; // Note: our grammar doesn't include rules of the form A -> epsilon // because it's meant for an SLR parser not an LL parser, so this is // simpler than what Wikipedia describes in the LL parser article if (rule[0].isTerminal) firstSetRule = new Set([rule[0].symbol]); else firstSetRule = firstSets.get(rule[0].symbol) || new Set<string>(); for (const elem of firstSetRule) union.add(elem); } if (!setEquals(union, firstSets.get(lhs)!)) { firstSets.set(lhs, union); progress = true; } } } this._firstSets = firstSets; if (DEBUG) { console.log(); console.log("First sets"); for (const [nonterm, firstSet] of firstSets) console.log(nonterm, "->", firstSet); } } private _buildFollowSets() { const followSets = new Map<string, Set<string>>(); for (const nonterm of this.nonTerminals) followSets.set(nonterm, new Set<string>()); let progress = true; function _addAll<T>(fromSet : Set<T>, intoSet : Set<T>) : boolean { if (!fromSet) return false; let progress = false; for (const v of fromSet) { if (!intoSet.has(v)) { intoSet.add(v); progress = true; } } return progress; } while (progress) { progress = false; for (const [lhs, rule,] of this.rules) { for (let i = 0; i < rule.length-1; i++) { if (rule[i].isNonTerminal) { if (rule[i+1].isNonTerminal) { progress = _addAll(this._firstSets.get(rule[i+1].symbol)!, followSets.get(rule[i].symbol)!) || progress; } else { if (!followSets.get(rule[i].symbol)!.has(rule[i+1].symbol)) { followSets.get(rule[i].symbol)!.add(rule[i+1].symbol); progress = true; } } } } if (rule[rule.length-1].isNonTerminal) progress = _addAll(followSets.get(lhs)!, followSets.get(rule[rule.length-1].symbol)!) || progress; } } this._followSets = followSets; if (DEBUG) { console.log(); console.log("Follow sets"); for (const [nonterm, followSet] of followSets) console.log(nonterm, "->", followSet); } } private _recursivePrintItemSet(itemSetId : number, printed : Set<number>, recurse = 0) { if (printed.has(itemSetId)) return; printed.add(itemSetId); const itemSet = this._itemSets[itemSetId]; console.error("Item Set", itemSetId, itemSet.info.intransitions); for (const rule of itemSet.rules) { const [ruleId, rhs] = rule.stuff; const [lhs,,] = this.rules[ruleId]; console.error(ruleId, lhs, '->', rhs); } console.error(); if (recurse > 0) { for (const [from,] of itemSet.info.intransitions) this._recursivePrintItemSet(from, printed, recurse - 1); } } private _buildParseTables() { this.gotoTable = []; this.actionTable = []; for (let i = 0; i < this._nStates; i++) { this.gotoTable[i] = Object.create(null); this.actionTable[i] = Object.create(null); } for (const nonterm of this.nonTerminals) { for (let i = 0; i < this._nStates; i++) { if (this._stateTransitionMatrix[i].has('NT:' + nonterm)) this.gotoTable[i][nonterm] = this._stateTransitionMatrix[i].get('NT:' +nonterm)!; } } for (const term of this.terminals) { for (let i = 0; i < this._nStates; i++) { if (this._stateTransitionMatrix[i].has('T:' + term)) this.actionTable[i][term] = ['shift', this._stateTransitionMatrix[i].get('T:' + term)!]; } } for (const itemSet of this._itemSets) { for (const item of itemSet.rules) { const rhs = item.get(1); for (let i = 0; i < rhs.length-1; i++) { if (rhs[i] === ITEM_SET_MARKER && rhs[i+1] === EOF_TOKEN.toString()) this.actionTable[itemSet.info.id][EOF_TOKEN.symbol] = ['accept', 0]; } } } for (const itemSet of this._itemSets) { for (const item of itemSet.rules) { const [ruleId, rhs] : [number, string[]] = item.stuff; if (rhs[rhs.length-1] !== ITEM_SET_MARKER) continue; const [lhs,,] = this.rules[ruleId]; for (const term of this.terminals) { if (this._followSets.get(lhs)!.has(term)) { const existing = this.actionTable[itemSet.info.id][term]; if (existing) { if (strictArrayEquals(existing, ['reduce', ruleId])) continue; const printed = new Set<number>(); this._recursivePrintItemSet(itemSet.info.id, printed); if (existing[0] === 'shift') console.log(`WARNING: ignored shift-reduce conflict at state ${itemSet.info.id} terminal ${term} want ${["reduce", ruleId]} have ${existing}`); else throw new Error(`Conflict for state ${itemSet.info.id} terminal ${term} want ${["reduce", ruleId]} have ${existing}`); } else { this.actionTable[itemSet.info.id][term] = ['reduce', ruleId]; } } } } } } }
the_stack
import './invlerp.css'; import svg_arrowLeft from 'ikonate/icons/arrow-left.svg'; import svg_arrowRight from 'ikonate/icons/arrow-right.svg'; import {DisplayContext, IndirectRenderedPanel} from 'neuroglancer/display_context'; import {WatchableValueInterface} from 'neuroglancer/trackable_value'; import {animationFrameDebounce} from 'neuroglancer/util/animation_frame_debounce'; import {DataType} from 'neuroglancer/util/data_type'; import {RefCounted} from 'neuroglancer/util/disposable'; import {updateInputFieldWidth} from 'neuroglancer/util/dom'; import {EventActionMap, registerActionListener} from 'neuroglancer/util/event_action_map'; import {computeInvlerp, computeLerp, dataTypeCompare, DataTypeInterval, getClampedInterval, getClosestEndpoint, getIntervalBoundsEffectiveFraction, getIntervalBoundsEffectiveOffset, parseDataTypeValue} from 'neuroglancer/util/lerp'; import {MouseEventBinder} from 'neuroglancer/util/mouse_bindings'; import {startRelativeMouseDrag} from 'neuroglancer/util/mouse_drag'; import {Uint64} from 'neuroglancer/util/uint64'; import {getWheelZoomAmount} from 'neuroglancer/util/wheel_zoom'; import {WatchableVisibilityPriority} from 'neuroglancer/visibility_priority/frontend'; import {getMemoizedBuffer} from 'neuroglancer/webgl/buffer'; import {ParameterizedEmitterDependentShaderGetter, parameterizedEmitterDependentShaderGetter} from 'neuroglancer/webgl/dynamic_shader'; import {HistogramSpecifications} from 'neuroglancer/webgl/empirical_cdf'; import {defineLerpShaderFunction, enableLerpShaderFunction} from 'neuroglancer/webgl/lerp'; import {defineLineShader, drawLines, initializeLineShader, VERTICES_PER_LINE} from 'neuroglancer/webgl/lines'; import {ShaderBuilder} from 'neuroglancer/webgl/shader'; import {getShaderType} from 'neuroglancer/webgl/shader_lib'; import {InvlerpParameters} from 'neuroglancer/webgl/shader_ui_controls'; import {getSquareCornersBuffer} from 'neuroglancer/webgl/square_corners_buffer'; import {setRawTextureParameters} from 'neuroglancer/webgl/texture'; import {makeIcon} from 'neuroglancer/widget/icon'; import {LegendShaderOptions} from 'neuroglancer/widget/shader_controls'; import {Tab} from 'neuroglancer/widget/tab_view'; const inputEventMap = EventActionMap.fromObject({ 'shift?+mousedown0': {action: 'set'}, 'shift?+alt+mousedown0': {action: 'adjust-window-via-drag'}, 'shift?+wheel': {action: 'zoom-via-wheel'}, }); export class CdfController<T extends RangeAndWindowIntervals> extends RefCounted { constructor( public element: HTMLElement, public dataType: DataType, public getModel: () => T, public setModel: (value: T) => void) { super(); element.title = inputEventMap.describe(); this.registerDisposer(new MouseEventBinder(element, inputEventMap)); registerActionListener<MouseEvent>(element, 'set', actionEvent => { const mouseEvent = actionEvent.detail; const bounds = this.getModel(); const value = this.getTargetValue(mouseEvent); if (value === undefined) return; const clampedRange = getClampedInterval(bounds.window, bounds.range); const endpoint = getClosestEndpoint(clampedRange, value); const setEndpoint = (value: number|Uint64) => { const bounds = this.getModel(); this.setModel(getUpdatedRangeAndWindowParameters(bounds, 'range', endpoint, value)); }; setEndpoint(value); startRelativeMouseDrag(mouseEvent, (newEvent: MouseEvent) => { const value = this.getTargetValue(newEvent); if (value === undefined) return; setEndpoint(value); }); }); registerActionListener<MouseEvent>(element, 'adjust-window-via-drag', actionEvent => { // If user starts drag on left half, then right bound is fixed, and left bound is adjusted to // keep the value under the mouse fixed. If user starts drag on right half, the left bound is // fixed and right bound is adjusted. const mouseEvent = actionEvent.detail; const initialRelativeX = this.getTargetFraction(mouseEvent); const initialValue = this.getWindowLerp(initialRelativeX); const endpointIndex = (initialRelativeX < 0.5) ? 0 : 1; const setEndpoint = (value: number|Uint64) => { const bounds = this.getModel(); this.setModel(getUpdatedRangeAndWindowParameters(bounds, 'window', endpointIndex, value)); }; startRelativeMouseDrag(mouseEvent, (newEvent: MouseEvent) => { const window = this.getModel().window; const relativeX = this.getTargetFraction(newEvent); if (endpointIndex === 0) { // Need to find x such that: lerp([x, window[1]], relativeX) == initialValue // Equivalently: lerp([initialValue, window[1]], -relativeX / ( 1 - relativeX)) setEndpoint(computeLerp( [initialValue, window[1]] as DataTypeInterval, this.dataType, -relativeX / (1 - relativeX))); } else { // Need to find x such that: lerp([window[0], x], relativeX) == initialValue // Equivalently: lerp([window[0], initialValue], 1 / relativeX) setEndpoint(computeLerp( [window[0], initialValue] as DataTypeInterval, this.dataType, 1 / relativeX)); } }); }); registerActionListener<WheelEvent>(element, 'zoom-via-wheel', actionEvent => { const wheelEvent = actionEvent.detail; const zoomAmount = getWheelZoomAmount(wheelEvent); const relativeX = this.getTargetFraction(wheelEvent); const {dataType} = this; const bounds = this.getModel(); const newLower = computeLerp(bounds.window, dataType, relativeX * (1 - zoomAmount)); const newUpper = computeLerp(bounds.window, dataType, (1 - relativeX) * zoomAmount + relativeX); this.setModel({ ...bounds, window: [newLower, newUpper] as DataTypeInterval, range: bounds.range, }); }); } getTargetFraction(event: MouseEvent) { const clientRect = this.element.getBoundingClientRect(); return (event.clientX - clientRect.left) / clientRect.width; } getWindowLerp(relativeX: number) { return computeLerp(this.getModel().window, this.dataType, relativeX); } getTargetValue(event: MouseEvent): number|Uint64|undefined { const targetFraction = this.getTargetFraction(event); if (!Number.isFinite(targetFraction)) return undefined; return this.getWindowLerp(targetFraction); } } const histogramSamplerTextureUnit = Symbol('histogramSamplerTexture'); export interface RangeAndWindowIntervals { range: DataTypeInterval; window: DataTypeInterval; } export function getUpdatedRangeAndWindowParameters<T extends RangeAndWindowIntervals>( existingBounds: T, boundType: 'range'|'window', endpointIndex: number, newEndpoint: number|Uint64, fitRangeInWindow = false): T { const newBounds = {...existingBounds}; const existingInterval = existingBounds[boundType]; newBounds[boundType] = [existingInterval[0], existingInterval[1]] as DataTypeInterval; newBounds[boundType][endpointIndex] = newEndpoint; if (boundType === 'window' && dataTypeCompare(newEndpoint, existingInterval[1 - endpointIndex]) * (2 * endpointIndex - 1) < 0) { newBounds[boundType][1 - endpointIndex] = newEndpoint; } if (boundType === 'range' && fitRangeInWindow) { // Also adjust `window` endpoint to contain the new endpoint. const newWindowInterval = [existingBounds.window[0], existingBounds.window[1]] as DataTypeInterval; for (let i = 0; i < 2; ++i) { if (dataTypeCompare(newEndpoint, newWindowInterval[i]) * (2 * i - 1) > 0) { newWindowInterval[i] = newEndpoint; } } newBounds.window = newWindowInterval; } return newBounds; } // 256 bins in total. The first and last bin are for values below the lower bound/above the upper // bound. const NUM_HISTOGRAM_BINS_IN_RANGE = 254; const NUM_CDF_LINES = NUM_HISTOGRAM_BINS_IN_RANGE + 1; class CdfPanel extends IndirectRenderedPanel { get drawOrder() { return 100; } controller = this.registerDisposer(new CdfController( this.element, this.parent.dataType, () => this.parent.trackable.value, (value: InvlerpParameters) => { this.parent.trackable.value = value; })); constructor(public parent: InvlerpWidget) { super(parent.display, document.createElement('div'), parent.visibility); const {element} = this; element.classList.add('neuroglancer-invlerp-cdfpanel'); } private dataValuesBuffer = this.registerDisposer(getMemoizedBuffer(this.gl, WebGL2RenderingContext.ARRAY_BUFFER, () => { const array = new Uint8Array(NUM_CDF_LINES * VERTICES_PER_LINE); for (let i = 0; i < NUM_CDF_LINES; ++i) { for (let j = 0; j < VERTICES_PER_LINE; ++j) { array[i * VERTICES_PER_LINE + j] = i; } } return array; })).value; private lineShader = this.registerDisposer((() => { const builder = new ShaderBuilder(this.gl); defineLineShader(builder); builder.addTextureSampler('sampler2D', 'uHistogramSampler', histogramSamplerTextureUnit); builder.addOutputBuffer('vec4', 'out_color', 0); builder.addAttribute('uint', 'aDataValue'); builder.addUniform('float', 'uBoundsFraction'); builder.addVertexCode(` float getCount(int i) { return texelFetch(uHistogramSampler, ivec2(i, 0), 0).x; } vec4 getVertex(float cdf, int i) { float x; if (i == 0) { x = -1.0; } else if (i == 255) { x = 1.0; } else { x = float(i) / 254.0 * uBoundsFraction * 2.0 - 1.0; } return vec4(x, cdf * (2.0 - uLineParams.y) - 1.0 + uLineParams.y * 0.5, 0.0, 1.0); } `); builder.setVertexMain(` int lineNumber = int(aDataValue); int dataValue = lineNumber; float cumSum = 0.0; for (int i = 0; i <= dataValue; ++i) { cumSum += getCount(i); } float total = cumSum + getCount(dataValue + 1); float cumSumEnd = dataValue == ${NUM_CDF_LINES - 1} ? cumSum : total; if (dataValue == ${NUM_CDF_LINES - 1}) { cumSum + getCount(dataValue + 1); } for (int i = dataValue + 2; i < 256; ++i) { total += getCount(i); } total = max(total, 1.0); float cdf1 = cumSum / total; float cdf2 = cumSumEnd / total; emitLine(getVertex(cdf1, lineNumber), getVertex(cdf2, lineNumber + 1), 1.0); `); builder.setFragmentMain(` out_color = vec4(0.0, 1.0, 1.0, getLineAlpha()); `); return builder.build(); })()); private regionCornersBuffer = getSquareCornersBuffer(this.gl, 0, -1, 1, 1); private regionShader = this.registerDisposer((() => { const builder = new ShaderBuilder(this.gl); builder.addAttribute('vec2', 'aVertexPosition'); builder.addUniform('vec2', 'uBounds'); builder.addUniform('vec4', 'uColor'); builder.addOutputBuffer('vec4', 'out_color', 0); builder.setVertexMain(` gl_Position = vec4(mix(uBounds[0], uBounds[1], aVertexPosition.x) * 2.0 - 1.0, aVertexPosition.y, 0.0, 1.0); `); builder.setFragmentMain(` out_color = uColor; `); return builder.build(); })()); drawIndirect() { const {lineShader, gl, regionShader, parent: {dataType, trackable: {value: bounds}}} = this; this.setGLLogicalViewport(); gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT); gl.enable(WebGL2RenderingContext.BLEND); gl.blendFunc(WebGL2RenderingContext.SRC_ALPHA, WebGL2RenderingContext.ONE_MINUS_SRC_ALPHA); gl.disable(WebGL2RenderingContext.DEPTH_TEST); gl.disable(WebGL2RenderingContext.STENCIL_TEST); { regionShader.bind(); gl.uniform4f(regionShader.uniform('uColor'), 0.2, 0.2, 0.2, 1.0); const fraction0 = computeInvlerp(bounds.window, bounds.range[0]), fraction1 = computeInvlerp(bounds.window, bounds.range[1]); const effectiveFraction = getIntervalBoundsEffectiveFraction(dataType, bounds.window); gl.uniform2f( regionShader.uniform('uBounds'), Math.min(fraction0, fraction1) * effectiveFraction, Math.max(fraction0, fraction1) * effectiveFraction + (1 - effectiveFraction)); const aVertexPosition = regionShader.attribute('aVertexPosition'); this.regionCornersBuffer.bindToVertexAttrib( aVertexPosition, /*componentsPerVertexAttribute=*/ 2, /*attributeType=*/ WebGL2RenderingContext.FLOAT); gl.drawArrays(WebGL2RenderingContext.TRIANGLE_FAN, 0, 4); gl.disableVertexAttribArray(aVertexPosition); } if (this.parent.histogramSpecifications.producerVisibility.visible) { const {renderViewport} = this; lineShader.bind(); initializeLineShader( lineShader, {width: renderViewport.logicalWidth, height: renderViewport.logicalHeight}, /*featherWidthInPixels=*/ 1.0); const histogramTextureUnit = lineShader.textureUnit(histogramSamplerTextureUnit); gl.uniform1f( lineShader.uniform('uBoundsFraction'), getIntervalBoundsEffectiveFraction(dataType, bounds.window)); gl.activeTexture(WebGL2RenderingContext.TEXTURE0 + histogramTextureUnit); gl.bindTexture(WebGL2RenderingContext.TEXTURE_2D, this.parent.texture); setRawTextureParameters(gl); const aDataValue = lineShader.attribute('aDataValue'); this.dataValuesBuffer.bindToVertexAttribI( aDataValue, /*componentsPerVertexAttribute=*/ 1, /*attributeType=*/ WebGL2RenderingContext.UNSIGNED_BYTE); drawLines(gl, /*linesPerInstance=*/ NUM_CDF_LINES, /*numInstances=*/ 1); gl.disableVertexAttribArray(aDataValue); gl.bindTexture(WebGL2RenderingContext.TEXTURE_2D, null); } gl.disable(WebGL2RenderingContext.BLEND); } isReady() { return true; } } function dummyColorLegendShaderModule() {} class ColorLegendPanel extends IndirectRenderedPanel { private shaderOptions: LegendShaderOptions; constructor(public parent: InvlerpWidget) { super(parent.display, document.createElement('div'), parent.visibility); const {element} = this; element.classList.add('neuroglancer-invlerp-legend-panel'); const shaderOptions = this.shaderOptions = parent.legendShaderOptions!; this.shaderGetter = parameterizedEmitterDependentShaderGetter(this, this.gl, { ...shaderOptions, memoizeKey: {id: `colorLegendShader`, base: shaderOptions.memoizeKey}, defineShader: (builder, parameters, extraParameters) => { builder.addOutputBuffer('vec4', 'v4f_fragData0', 0); builder.addAttribute('vec2', 'aVertexPosition'); builder.addUniform('float', 'uLegendOffset'); builder.addVarying('float', 'vLinearPosition'); builder.setVertexMain(` gl_Position = vec4(aVertexPosition, 0.0, 1.0); vLinearPosition = -uLegendOffset + ((aVertexPosition.x + 1.0) * 0.5) * (1.0 + 2.0 * uLegendOffset); `); const dataType = this.parent.dataType; const shaderDataType = getShaderType(dataType); builder.addFragmentCode(defineLerpShaderFunction(builder, 'ng_colorLegendLerp', dataType)); builder.addFragmentCode(` void emit(vec4 v) { v4f_fragData0 = v; } ${shaderDataType} getDataValue() { return ng_colorLegendLerp(vLinearPosition); } ${shaderDataType} getDataValue(int dummyChannel) { return getDataValue(); } ${shaderDataType} getInterpolatedDataValue() { return getDataValue(); } ${shaderDataType} getInterpolatedDataValue(int dummyChannel) { return getDataValue(); } `); shaderOptions.defineShader(builder, parameters, extraParameters); }, }); } private shaderGetter: ParameterizedEmitterDependentShaderGetter; private cornersBuffer = getSquareCornersBuffer(this.gl, -1, -1, 1, 1); drawIndirect() { const shaderResult = this.shaderGetter(dummyColorLegendShaderModule); const {shader} = shaderResult; if (shader === null) return; this.setGLLogicalViewport(); const {gl} = this; gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT); shader.bind(); this.shaderOptions.initializeShader(shaderResult); gl.enable(WebGL2RenderingContext.BLEND); const {trackable: {value: {window}}, dataType} = this.parent; enableLerpShaderFunction(shader, 'ng_colorLegendLerp', this.parent.dataType, window); const legendOffset = getIntervalBoundsEffectiveOffset(dataType, window); gl.uniform1f(shader.uniform('uLegendOffset'), Number.isFinite(legendOffset) ? legendOffset : 0); gl.blendFunc(WebGL2RenderingContext.SRC_ALPHA, WebGL2RenderingContext.ONE_MINUS_SRC_ALPHA); gl.disable(WebGL2RenderingContext.DEPTH_TEST); gl.disable(WebGL2RenderingContext.STENCIL_TEST); const aVertexPosition = shader.attribute('aVertexPosition'); this.cornersBuffer.bindToVertexAttrib( aVertexPosition, /*componentsPerVertexAttribute=*/ 2, /*attributeType=*/ WebGL2RenderingContext.FLOAT); gl.drawArrays(WebGL2RenderingContext.TRIANGLE_FAN, 0, 4); gl.disableVertexAttribArray(aVertexPosition); } isReady() { return true; } } function createRangeBoundInput(boundType: 'range'|'window', endpoint: number) { const e = document.createElement('input'); e.addEventListener('focus', () => { e.select(); }); e.classList.add('neuroglancer-invlerp-widget-bound'); e.classList.add(`neuroglancer-invlerp-widget-${boundType}-bound`); e.type = 'text'; e.spellcheck = false; e.autocomplete = 'off'; e.title = boundType === 'range' ? `Data value that maps to ${endpoint}` : `${endpoint === 0 ? 'Lower' : 'Upper'} bound for distribution`; return e; } function createRangeBoundInputs( boundType: 'range'|'window', dataType: DataType, model: WatchableValueInterface<InvlerpParameters>) { const container = document.createElement('div'); container.classList.add('neuroglancer-invlerp-widget-bounds'); container.classList.add(`neuroglancer-invlerp-widget-${boundType}-bounds`); const inputs = [ createRangeBoundInput(boundType, 0), createRangeBoundInput(boundType, 1) ] as [HTMLInputElement, HTMLInputElement]; for (let endpointIndex = 0; endpointIndex < 2; ++endpointIndex) { const input = inputs[endpointIndex]; input.addEventListener('input', () => { updateInputBoundWidth(input); }); input.addEventListener('change', () => { const existingBounds = model.value; const existingInterval = existingBounds[boundType]; try { const value = parseDataTypeValue(dataType, input.value); model.value = getUpdatedRangeAndWindowParameters( existingBounds, boundType, endpointIndex, value, /*fitRangeInWindow=*/ true); } catch { updateInputBoundValue(input, existingInterval[endpointIndex]); } }); } let spacers: [HTMLElement, HTMLElement, HTMLElement]|undefined; container.appendChild(inputs[0]); container.appendChild(inputs[1]); if (boundType === 'range') { spacers = [ document.createElement('div'), document.createElement('div'), document.createElement('div'), ]; spacers[1].classList.add('neuroglancer-invlerp-widget-range-spacer'); container.insertBefore(spacers[0], inputs[0]); container.insertBefore(spacers[1], inputs[1]); container.appendChild(spacers[2]); } return {container, inputs, spacers}; } function updateInputBoundWidth(inputElement: HTMLInputElement) { updateInputFieldWidth(inputElement, Math.max(1, inputElement.value.length + 0.1)); } function updateInputBoundValue(inputElement: HTMLInputElement, bound: number|Uint64) { let boundString: string; if (bound instanceof Uint64 || Number.isInteger(bound)) { boundString = bound.toString(); } else { boundString = bound.toPrecision(6); } inputElement.value = boundString; updateInputBoundWidth(inputElement); } export function invertInvlerpRange(trackable: WatchableValueInterface<InvlerpParameters>) { const bounds = trackable.value; const {range} = bounds; trackable.value = {...bounds, range: [range[1], range[0]] as DataTypeInterval}; } export function adjustInvlerpContrast( dataType: DataType, trackable: WatchableValueInterface<InvlerpParameters>, scaleFactor: number) { const bounds = trackable.value; const newLower = computeLerp(bounds.range, dataType, 0.5 - scaleFactor / 2); const newUpper = computeLerp(bounds.range, dataType, 0.5 + scaleFactor / 2); trackable.value = {...bounds, range: [newLower, newUpper] as DataTypeInterval}; } export function adjustInvlerpBrightnessContrast( dataType: DataType, trackable: WatchableValueInterface<InvlerpParameters>, baseRange: DataTypeInterval, brightnessAmount: number, contrastAmount: number) { const scaleFactor = Math.exp(contrastAmount); const bounds = trackable.value; const newLower = computeLerp(baseRange, dataType, 0.5 - scaleFactor / 2 + brightnessAmount); const newUpper = computeLerp(baseRange, dataType, 0.5 + scaleFactor / 2 + brightnessAmount); trackable.value = {...bounds, range: [newLower, newUpper] as DataTypeInterval}; } export class InvlerpWidget extends Tab { cdfPanel = this.registerDisposer(new CdfPanel(this)); boundElements = { range: createRangeBoundInputs('range', this.dataType, this.trackable), window: createRangeBoundInputs('window', this.dataType, this.trackable), }; invertArrows: HTMLElement[]; get texture() { return this.histogramSpecifications.getFramebuffers(this.display.gl)[this.histogramIndex] .colorBuffers[0] .texture; } private invertRange() { invertInvlerpRange(this.trackable); } constructor( visibility: WatchableVisibilityPriority, public display: DisplayContext, public dataType: DataType, public trackable: WatchableValueInterface<InvlerpParameters>, public histogramSpecifications: HistogramSpecifications, public histogramIndex: number, public legendShaderOptions: LegendShaderOptions|undefined) { super(visibility); this.registerDisposer(histogramSpecifications.visibility.add(this.visibility)); const {element, boundElements} = this; if (legendShaderOptions !== undefined) { const legendPanel = this.registerDisposer(new ColorLegendPanel(this)); element.appendChild(legendPanel.element); } const makeArrow = (svg: string) => { const icon = makeIcon({ svg, title: 'Invert range', onClick: () => { this.invertRange(); }, }); boundElements.range.spacers![1].appendChild(icon); return icon; }; this.invertArrows = [makeArrow(svg_arrowRight), makeArrow(svg_arrowLeft)]; element.appendChild(boundElements.range.container); element.appendChild(this.cdfPanel.element); element.classList.add('neuroglancer-invlerp-widget'); element.appendChild(boundElements.window.container); this.updateView(); this.registerDisposer(trackable.changed.add( this.registerCancellable(animationFrameDebounce(() => this.updateView())))); } updateView() { const {boundElements} = this; const {trackable: {value: bounds}, dataType} = this; for (let i = 0; i < 2; ++i) { updateInputBoundValue(boundElements.range.inputs[i], bounds.range[i]); updateInputBoundValue(boundElements.window.inputs[i], bounds.window[i]); } const reversed = dataTypeCompare(bounds.range[0], bounds.range[1]) > 0; boundElements.range.container.style.flexDirection = !reversed ? 'row' : 'row-reverse'; const clampedRange = getClampedInterval(bounds.window, bounds.range); const spacers = boundElements.range.spacers!; const effectiveFraction = getIntervalBoundsEffectiveFraction(dataType, bounds.window); const leftOffset = computeInvlerp(bounds.window, clampedRange[reversed ? 1 : 0]) * effectiveFraction; const rightOffset = computeInvlerp(bounds.window, clampedRange[reversed ? 0 : 1]) * effectiveFraction + (1 - effectiveFraction); spacers[reversed ? 2 : 0].style.width = `${leftOffset * 100}%`; spacers[reversed ? 0 : 2].style.width = `${(1 - rightOffset) * 100}%`; const {invertArrows} = this; invertArrows[reversed ? 1 : 0].style.display = ''; invertArrows[reversed ? 0 : 1].style.display = 'none'; } }
the_stack
import * as React from "react" import { observer } from "mobx-react" import { observable, computed, action, runInAction, reaction, IReactionDisposer, } from "mobx" import parse from "csv-parse" import unidecode from "unidecode" import FuzzySet from "fuzzyset" import { AdminLayout } from "./AdminLayout" import { SelectField, SelectGroupsField, SelectGroup } from "./Forms" import { CountryNameFormat, CountryNameFormatDefs, CountryDefByKey, } from "../adminSiteClient/CountryNameFormat" import { uniq, toString, csvEscape, sortBy } from "../clientUtils/Util" import { AdminAppContext, AdminAppContextType } from "./AdminAppContext" import { faDownload } from "@fortawesome/free-solid-svg-icons/faDownload" import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" class CSV { @observable filename?: string @observable rows: string[][] @observable countryEntriesMap: Map<string, CountryEntry> @observable mapCountriesInputToOutput: Record<string, string> @observable autoMatchedCount: number = 0 @observable parseError?: string @observable findSimilarCountries: boolean = true constructor() { this.countryEntriesMap = new Map<string, CountryEntry>() this.rows = [] this.mapCountriesInputToOutput = {} } @computed get allCountries(): string[] { const standardNames = Object.values( this.mapCountriesInputToOutput ).filter((value: string | undefined) => value !== undefined) as string[] return uniq(sortBy(standardNames)) as string[] } @computed get countryColumnIndex() { const { rows } = this if (rows.length === 0) { return -1 } return rows[0].findIndex( (columnName) => columnName.toLowerCase() === "country" ) } @computed get showDownloadOption() { const { rows, validationError } = this if (rows.length > 0 && validationError === undefined) { return true } return false } @computed get numCountries() { return this.rows.length - 1 } @computed get validationError(): string | undefined { const { parseError } = this if (parseError !== undefined) { return `Could not parse file (error: ${parseError}). Check if it is a valid CSV file.` } const { rows, countryColumnIndex } = this if (rows.length === 0) return undefined if (countryColumnIndex < 0) { return "Could not find a column name with the header 'Country'" } return undefined } @action.bound onFileUpload( filename: string, rows: string[][], err: { message: string } | undefined, similarityMatch: boolean ) { this.filename = filename if (err) { this.parseError = err.message this.rows = [] } else { this.parseError = undefined this.rows = rows } this.findSimilarCountries = similarityMatch this.parseCSV() } @action.bound onFormatChange( countryMap: Record<string, string>, findSimilarCountries: boolean ) { this.mapCountriesInputToOutput = countryMap this.findSimilarCountries = findSimilarCountries this.parseCSV() } @action.bound parseCSV() { const { rows, countryColumnIndex, mapCountriesInputToOutput, findSimilarCountries, } = this if (countryColumnIndex < 0) { this.countryEntriesMap = new Map<string, CountryEntry>() this.autoMatchedCount = 0 return } const entriesByCountry = new Map<string, CountryEntry>() const countries = rows .slice(1) // remove header row .map((row: string[]) => unidecode(row[countryColumnIndex] as string) ) .filter( (country?: string) => country !== "" && country !== undefined ) // exclude empty strings // for fuzzy-match, use the input and output values as target to improve matching potential const inputCountries = Object.keys(mapCountriesInputToOutput).filter( (key) => mapCountriesInputToOutput[key] !== undefined ) const outputCountries = inputCountries.map( (key) => mapCountriesInputToOutput[key] ) as string[] const fuzz = FuzzySet(inputCountries.concat(outputCountries)) let autoMatched = 0 countries.map((country: string) => { const outputCountry = mapCountriesInputToOutput[country.toLowerCase()] let approximatedMatches: string[] = [] if (outputCountry === undefined) { if (findSimilarCountries) { const fuzzMatches = fuzz.get(country) ?? [] approximatedMatches = fuzzMatches .map( (fuzzyMatch: [number, string]) => mapCountriesInputToOutput[fuzzyMatch[1]] || fuzzyMatch[1] ) .filter((key) => key !== undefined) approximatedMatches = uniq(approximatedMatches) } } else { autoMatched += 1 } const entry: CountryEntry = { originalName: country, standardizedName: outputCountry || undefined, approximatedMatches: approximatedMatches, selectedMatch: "", customName: "", } entriesByCountry.set(country, entry) }) this.countryEntriesMap = entriesByCountry this.autoMatchedCount = autoMatched } } interface CountryEntry extends React.HTMLAttributes<HTMLTableRowElement> { originalName: string standardizedName?: string approximatedMatches: string[] selectedMatch?: string customName?: string } @observer class CountryEntryRowRenderer extends React.Component<{ entry: CountryEntry allCountries: string[] onUpdate: (value: string, inputCountry: string, isCustom: boolean) => void }> { @observable selectedStandardName!: string @computed get defaultOption() { return "Select one" } @computed get isMatched(): boolean { const { entry } = this.props if (entry.standardizedName || entry.selectedMatch || entry.customName) return true else return false } @computed get defaultValue() { const { entry } = this.props if ( entry.selectedMatch !== undefined && entry.selectedMatch.length > 0 ) { return entry.selectedMatch } return this.defaultOption } @action.bound onEntrySelected(selectedName: string) { const { entry, onUpdate } = this.props onUpdate(selectedName, entry.originalName, false) } render() { const { entry, allCountries, onUpdate } = this.props const { defaultOption, defaultValue, isMatched } = this const optgroups: SelectGroup[] = [] if (entry.approximatedMatches.length > 0) { const options = entry.approximatedMatches.map((countryName) => ({ value: countryName, label: countryName, })) optgroups.push({ title: "Likely matches", options: options }) } optgroups.push({ title: "All standard names", options: allCountries.map((countryName) => ({ value: countryName, label: countryName, })), }) return ( <tr> <td> <span style={{ color: isMatched ? "black" : "red" }}> {entry.originalName} </span> </td> <td>{entry.standardizedName}</td> <td> <SelectGroupsField value={defaultValue} onValue={this.onEntrySelected} options={[ { value: defaultOption, label: defaultOption }, ]} groups={optgroups} /> </td> <td> <input type="text" className="form-control" value={entry.customName} onChange={(e) => onUpdate( e.currentTarget.value, entry.originalName, true ) } /> </td> </tr> ) } } @observer export class CountryStandardizerPage extends React.Component { static contextType = AdminAppContext context!: AdminAppContextType fileUploader!: HTMLInputElement @observable countryList: CountryEntry[] = [] @observable inputFormat: string = CountryNameFormat.NonStandardCountryName @observable outputFormat: string = CountryNameFormat.OurWorldInDataName @observable csv: CSV = new CSV() @observable showAllRows: boolean = false @computed get shouldSaveSelection(): boolean { if ( this.inputFormat === CountryNameFormat.NonStandardCountryName && this.outputFormat === CountryNameFormat.OurWorldInDataName ) { return true } return false } @computed get displayMatchStatus() { const { autoMatchedCount, numCountries, showDownloadOption } = this.csv if (!showDownloadOption) return <div></div> const columnName = CountryDefByKey[this.outputFormat].label let text = "" let banner = "" if (autoMatchedCount === numCountries) { banner = "alert-success" text = " All countries were auto-matched!" } else { banner = "alert-warning" text = " Some countries could not be matched. Either select a similar candidate from the dropdown (which will be saved back in the database) or enter a custom name." } text += " The file you will download has a new column with the header '" + columnName + "'." return ( <div className={"alert " + banner} role="alert"> <strong>Status:</strong> {text} </div> ) } @action.bound onInputFormat(format: string) { this.inputFormat = format } @action.bound onOutputFormat(format: string) { this.outputFormat = format } @action.bound onChooseCSV({ target }: { target: HTMLInputElement }) { const file = target.files && target.files[0] if (!file) return const reader = new FileReader() reader.onload = (e) => { const csv = e?.target?.result if (csv && typeof csv === "string") parse( csv, { relax_column_count: true, skip_empty_lines: true, rtrim: true, }, (err, rows) => { this.csv.onFileUpload( file.name, rows, err, this.shouldSaveSelection ) } ) else console.error("Csv was not read correctly") } reader.readAsText(file) } dispose!: IReactionDisposer componentDidMount() { // Fetch mapping from server when the input or output format changes this.dispose = reaction( () => [this.inputFormat, this.outputFormat], () => this.fetchCountryMap() ) this.fetchCountryMap() } componentWillUnmount() { this.dispose() } async fetchCountryMap() { const { inputFormat, outputFormat } = this const { admin } = this.context const results = await admin.getJSON( `/api/countries.json?input=${inputFormat}&output=${outputFormat}` ) runInAction(() => { const countryMap: { [key: string]: string } = {} results.countries.forEach( (countryFormat: { input: string; output: unknown }) => { if (countryFormat.input === null) return countryMap[countryFormat.input.toLowerCase()] = toString( countryFormat.output ) } ) this.csv.onFormatChange(countryMap, this.shouldSaveSelection) }) } @computed get csvDataUri(): string { return window.URL.createObjectURL(this.outputCSV) } @computed get csvFilename(): string { const { csv } = this if (csv.filename === undefined) return "" return csv.filename.replace(".csv", "_country_standardized.csv") } @computed get downloadTooltip(): string { const { shouldSaveSelection } = this if (shouldSaveSelection) { return "Downloading will save any custom selection for future ease" } return "" } @computed get fileUploadLabel() { const { csv } = this if (csv === undefined || csv.filename === undefined) { return "Choose CSV file" } return csv.filename } @computed get outputCSV() { const { csv } = this if (csv === undefined || csv.validationError !== undefined) return undefined const columnName = CountryDefByKey[this.outputFormat].label const columnIndex = csv.countryColumnIndex + 1 const outputRows: string[][] = [] // add a new column with the output country name csv.rows.forEach((row, rowIndex) => { let columnValue: string = "" if (rowIndex === 0) { // Don't map header row columnValue = columnName } else { // prioritize user selected name const entry = csv.countryEntriesMap.get( unidecode(row[csv.countryColumnIndex]) ) if (entry !== undefined) { if ( entry.customName !== undefined && entry.customName.length > 0 ) { columnValue = entry.customName } else if (entry.standardizedName !== undefined) { columnValue = entry.standardizedName } else if ( entry.selectedMatch !== undefined && entry.selectedMatch.length > 0 ) { columnValue = entry.selectedMatch } } } const newRow = row.slice(0) newRow.splice(columnIndex, 0, columnValue) outputRows.push(newRow) }) const strRows = outputRows.map((row) => row.map((val) => csvEscape(val)).join(",") ) return new Blob([strRows.join("\n")], { type: "text/csv" }) } @action.bound onUpdateRow( value: string, inputCountry: string, isCustom: boolean ) { const { csv } = this const entry = csv.countryEntriesMap.get(inputCountry) as CountryEntry console.log("updating " + inputCountry + " with " + value) if (isCustom) { entry.customName = value === undefined ? "" : value } else { entry.selectedMatch = value } } // IE11 compatibility @action.bound onDownload(ev: React.MouseEvent<HTMLAnchorElement>) { const { shouldSaveSelection } = this if (shouldSaveSelection) { this.onSave() } } @action.bound onToggleRows() { this.showAllRows = !this.showAllRows } @action.bound onSave() { const { csv } = this const countries: Record<string, string> = {} let needToSave: boolean = false csv.countryEntriesMap.forEach((entry) => { // ignore if there was a user entered a new name if (entry.customName !== undefined && entry.customName.length > 0) { console.log( "not saving custom-name for entry " + entry.originalName ) } else if ( entry.selectedMatch !== undefined && entry.selectedMatch.length > 0 ) { needToSave = true countries[entry.originalName] = entry.selectedMatch } }) if (needToSave) { this.context.admin.requestJSON( `/api/countries`, { countries: countries }, "POST" ) } } @computed get entriesToShow(): CountryEntry[] { if (this.csv === undefined) return [] const countries: CountryEntry[] = [] this.csv.countryEntriesMap.forEach((entry) => { if (this.showAllRows) { countries.push(entry) } else if (entry.standardizedName === undefined) { countries.push(entry) } }) return countries } render() { const { csv, entriesToShow } = this const { showDownloadOption, validationError } = csv const allowedInputFormats = CountryNameFormatDefs.filter( (c) => c.use_as_input ) const allowedOutputFormats = CountryNameFormatDefs.filter( (c) => c.use_as_output ) return ( <AdminLayout title="CountryStandardizer"> <main className="CountryStandardizerPage"> <section> <h3>Country Standardizer Tool</h3> <p> Upload a CSV file with countries. Select the current input and desired output format. The tool will attempt to find a match automatically for all entries. If not, you will be able to select a similar entry or use a new name. After which, you can download the file that has a new column for your output countries. </p> <div className="form-group"> <div className="custom-file"> <input type="file" className="custom-file-input" id="customFile" onChange={this.onChooseCSV} /> <label htmlFor="customFile" className="custom-file-label" > {this.fileUploadLabel} </label> </div> <small id="custom-file-help-block" className="text-muted form-text" > Country has to be saved under a column named 'Country' </small> </div> <SelectField label="Input Format" value={this.inputFormat} onValue={this.onInputFormat} options={allowedInputFormats.map((def) => def.key)} optionLabels={allowedInputFormats.map( (def) => def.label )} helpText="Choose the current format of the country names. If input format is other than the default, the tool won't attempt to find similar countries when there is no exact match." data-step="1" /> <SelectField label="Output Format" value={this.outputFormat} onValue={this.onOutputFormat} options={allowedOutputFormats.map((def) => def.key)} optionLabels={allowedOutputFormats.map( (def) => def.label )} helpText="Choose the desired format of the country names. If the chosen format is other than OWID name, the tool won't attempt to find similar countries when there is no exact match." /> <div className="topbar"> {showDownloadOption ? ( <a href={this.csvDataUri} download={this.csvFilename} className="btn btn-secondary" onClick={this.onDownload} title={this.downloadTooltip} > <FontAwesomeIcon icon={faDownload} />{" "} Download {this.csvFilename} </a> ) : ( <button className="btn btn-secondary" disabled> <FontAwesomeIcon icon={faDownload} /> No file to download (upload a CSV to start) </button> )} <label> <input type="checkbox" checked={this.showAllRows} onChange={this.onToggleRows} />{" "} Show All Rows </label> </div> {validationError !== undefined ? ( <div className="alert alert-danger" role="alert"> <strong>CSV Error:</strong> {validationError} </div> ) : ( <div></div> )} {this.displayMatchStatus} </section> <div> <table className="table table-bordered"> <thead> <tr> <th>Original Name</th> <th>Standardized Name</th> <th>Potential Candidates (select below)</th> <th>Or enter a Custom Name</th> </tr> </thead> <tbody> {entriesToShow.map((entry, i) => ( <CountryEntryRowRenderer key={i} entry={entry} allCountries={this.csv.allCountries} onUpdate={this.onUpdateRow} /> ))} </tbody> </table> </div> </main> </AdminLayout> ) } }
the_stack
import { NodeTypes, ElementNode, TransformContext, TemplateChildNode, SimpleExpressionNode, createCallExpression, HoistTransform, CREATE_STATIC, ExpressionNode, ElementTypes, PlainElementNode, JSChildNode, TextCallNode, ConstantTypes } from '@vue/compiler-core' import { isVoidTag, isString, isSymbol, isKnownHtmlAttr, escapeHtml, toDisplayString, normalizeClass, normalizeStyle, stringifyStyle, makeMap, isKnownSvgAttr } from '@vue/shared' import { DOMNamespaces } from '../parserOptions' export const enum StringifyThresholds { ELEMENT_WITH_BINDING_COUNT = 5, NODE_COUNT = 20 } type StringifiableNode = PlainElementNode | TextCallNode /** * Regex for replacing placeholders for embedded constant variables * (e.g. import URL string constants generated by compiler-sfc) */ const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g /** * Turn eligible hoisted static trees into stringified static nodes, e.g. * * ```js * const _hoisted_1 = createStaticVNode(`<div class="foo">bar</div>`) * ``` * * A single static vnode can contain stringified content for **multiple** * consecutive nodes (element and plain text), called a "chunk". * `@vue/runtime-dom` will create the content via innerHTML in a hidden * container element and insert all the nodes in place. The call must also * provide the number of nodes contained in the chunk so that during hydration * we can know how many nodes the static vnode should adopt. * * The optimization scans a children list that contains hoisted nodes, and * tries to find the largest chunk of consecutive hoisted nodes before running * into a non-hoisted node or the end of the list. A chunk is then converted * into a single static vnode and replaces the hoisted expression of the first * node in the chunk. Other nodes in the chunk are considered "merged" and * therefore removed from both the hoist list and the children array. * * This optimization is only performed in Node.js. */ export const stringifyStatic: HoistTransform = (children, context, parent) => { // bail stringification for slot content if (context.scopes.vSlot > 0) { return } let nc = 0 // current node count let ec = 0 // current element with binding count const currentChunk: StringifiableNode[] = [] const stringifyCurrentChunk = (currentIndex: number): number => { if ( nc >= StringifyThresholds.NODE_COUNT || ec >= StringifyThresholds.ELEMENT_WITH_BINDING_COUNT ) { // combine all currently eligible nodes into a single static vnode call const staticCall = createCallExpression(context.helper(CREATE_STATIC), [ JSON.stringify( currentChunk.map(node => stringifyNode(node, context)).join('') ).replace(expReplaceRE, `" + $1 + "`), // the 2nd argument indicates the number of DOM nodes this static vnode // will insert / hydrate String(currentChunk.length) ]) // replace the first node's hoisted expression with the static vnode call replaceHoist(currentChunk[0], staticCall, context) if (currentChunk.length > 1) { for (let i = 1; i < currentChunk.length; i++) { // for the merged nodes, set their hoisted expression to null replaceHoist(currentChunk[i], null, context) } // also remove merged nodes from children const deleteCount = currentChunk.length - 1 children.splice(currentIndex - currentChunk.length + 1, deleteCount) return deleteCount } } return 0 } let i = 0 for (; i < children.length; i++) { const child = children[i] const hoisted = getHoistedNode(child) if (hoisted) { // presence of hoisted means child must be a stringifiable node const node = child as StringifiableNode const result = analyzeNode(node) if (result) { // node is stringifiable, record state nc += result[0] ec += result[1] currentChunk.push(node) continue } } // we only reach here if we ran into a node that is not stringifiable // check if currently analyzed nodes meet criteria for stringification. // adjust iteration index i -= stringifyCurrentChunk(i) // reset state nc = 0 ec = 0 currentChunk.length = 0 } // in case the last node was also stringifiable stringifyCurrentChunk(i) } const getHoistedNode = (node: TemplateChildNode) => ((node.type === NodeTypes.ELEMENT && node.tagType === ElementTypes.ELEMENT) || node.type == NodeTypes.TEXT_CALL) && node.codegenNode && node.codegenNode.type === NodeTypes.SIMPLE_EXPRESSION && node.codegenNode.hoisted const dataAriaRE = /^(data|aria)-/ const isStringifiableAttr = (name: string, ns: DOMNamespaces) => { return ( (ns === DOMNamespaces.HTML ? isKnownHtmlAttr(name) : ns === DOMNamespaces.SVG ? isKnownSvgAttr(name) : false) || dataAriaRE.test(name) ) } const replaceHoist = ( node: StringifiableNode, replacement: JSChildNode | null, context: TransformContext ) => { const hoistToReplace = (node.codegenNode as SimpleExpressionNode).hoisted! context.hoists[context.hoists.indexOf(hoistToReplace)] = replacement } const isNonStringifiable = /*#__PURE__*/ makeMap( `caption,thead,tr,th,tbody,td,tfoot,colgroup,col` ) /** * for a hoisted node, analyze it and return: * - false: bailed (contains non-stringifiable props or runtime constant) * - [nc, ec] where * - nc is the number of nodes inside * - ec is the number of element with bindings inside */ function analyzeNode(node: StringifiableNode): [number, number] | false { if (node.type === NodeTypes.ELEMENT && isNonStringifiable(node.tag)) { return false } if (node.type === NodeTypes.TEXT_CALL) { return [1, 0] } let nc = 1 // node count let ec = node.props.length > 0 ? 1 : 0 // element w/ binding count let bailed = false const bail = (): false => { bailed = true return false } // TODO: check for cases where using innerHTML will result in different // output compared to imperative node insertions. // probably only need to check for most common case // i.e. non-phrasing-content tags inside `<p>` function walk(node: ElementNode): boolean { for (let i = 0; i < node.props.length; i++) { const p = node.props[i] // bail on non-attr bindings if ( p.type === NodeTypes.ATTRIBUTE && !isStringifiableAttr(p.name, node.ns) ) { return bail() } if (p.type === NodeTypes.DIRECTIVE && p.name === 'bind') { // bail on non-attr bindings if ( p.arg && (p.arg.type === NodeTypes.COMPOUND_EXPRESSION || (p.arg.isStatic && !isStringifiableAttr(p.arg.content, node.ns))) ) { return bail() } if ( p.exp && (p.exp.type === NodeTypes.COMPOUND_EXPRESSION || p.exp.constType < ConstantTypes.CAN_STRINGIFY) ) { return bail() } } } for (let i = 0; i < node.children.length; i++) { nc++ const child = node.children[i] if (child.type === NodeTypes.ELEMENT) { if (child.props.length > 0) { ec++ } walk(child) if (bailed) { return false } } } return true } return walk(node) ? [nc, ec] : false } function stringifyNode( node: string | TemplateChildNode, context: TransformContext ): string { if (isString(node)) { return node } if (isSymbol(node)) { return `` } switch (node.type) { case NodeTypes.ELEMENT: return stringifyElement(node, context) case NodeTypes.TEXT: return escapeHtml(node.content) case NodeTypes.COMMENT: return `<!--${escapeHtml(node.content)}-->` case NodeTypes.INTERPOLATION: return escapeHtml(toDisplayString(evaluateConstant(node.content))) case NodeTypes.COMPOUND_EXPRESSION: return escapeHtml(evaluateConstant(node)) case NodeTypes.TEXT_CALL: return stringifyNode(node.content, context) default: // static trees will not contain if/for nodes return '' } } function stringifyElement( node: ElementNode, context: TransformContext ): string { let res = `<${node.tag}` for (let i = 0; i < node.props.length; i++) { const p = node.props[i] if (p.type === NodeTypes.ATTRIBUTE) { res += ` ${p.name}` if (p.value) { res += `="${escapeHtml(p.value.content)}"` } } else if (p.type === NodeTypes.DIRECTIVE && p.name === 'bind') { const exp = p.exp as SimpleExpressionNode if (exp.content[0] === '_') { // internally generated string constant references // e.g. imported URL strings via compiler-sfc transformAssetUrl plugin res += ` ${(p.arg as SimpleExpressionNode).content}="__VUE_EXP_START__${ exp.content }__VUE_EXP_END__"` continue } // constant v-bind, e.g. :foo="1" let evaluated = evaluateConstant(exp) if (evaluated != null) { const arg = p.arg && (p.arg as SimpleExpressionNode).content if (arg === 'class') { evaluated = normalizeClass(evaluated) } else if (arg === 'style') { evaluated = stringifyStyle(normalizeStyle(evaluated)) } res += ` ${(p.arg as SimpleExpressionNode).content}="${escapeHtml( evaluated )}"` } } } if (context.scopeId) { res += ` ${context.scopeId}` } res += `>` for (let i = 0; i < node.children.length; i++) { res += stringifyNode(node.children[i], context) } if (!isVoidTag(node.tag)) { res += `</${node.tag}>` } return res } // __UNSAFE__ // Reason: eval. // It's technically safe to eval because only constant expressions are possible // here, e.g. `{{ 1 }}` or `{{ 'foo' }}` // in addition, constant exps bail on presence of parens so you can't even // run JSFuck in here. But we mark it unsafe for security review purposes. // (see compiler-core/src/transformExpressions) function evaluateConstant(exp: ExpressionNode): string { if (exp.type === NodeTypes.SIMPLE_EXPRESSION) { return new Function(`return ${exp.content}`)() } else { // compound let res = `` exp.children.forEach(c => { if (isString(c) || isSymbol(c)) { return } if (c.type === NodeTypes.TEXT) { res += c.content } else if (c.type === NodeTypes.INTERPOLATION) { res += toDisplayString(evaluateConstant(c.content)) } else { res += evaluateConstant(c) } }) return res } }
the_stack
import * as GObject from "@gi-types/gobject"; import * as Gio from "@gi-types/gio"; import * as GLib from "@gi-types/glib"; export const INVALID: number; export const MAJOR_VERSION: number; export const MICRO_VERSION: number; export const MINOR_VERSION: number; export const URI_FOR_MODULE_WITH_VERSION: number; export const URI_FOR_OBJECT_ON_TOKEN: number; export const URI_FOR_OBJECT_ON_TOKEN_AND_MODULE: number; export const VENDOR_CODE: number; export function builder_unref(builder?: any | null): void; export function error_get_quark(): GLib.Quark; export function list_get_boxed_type(): GObject.GType; export function message_from_rv(rv: number): string; export function modules_enumerate_objects( modules: Module[], attrs: Attributes, session_options: SessionOptions ): Enumerator; export function modules_enumerate_uri(modules: Module[], uri: string, session_options: SessionOptions): Enumerator; export function modules_get_slots(modules: Module[], token_present: boolean): Slot[]; export function modules_initialize_registered(cancellable?: Gio.Cancellable | null): Module[]; export function modules_initialize_registered_async(cancellable?: Gio.Cancellable | null): Promise<Module[]>; export function modules_initialize_registered_async( cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<Gio.Cancellable | null> | null ): void; export function modules_initialize_registered_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<Gio.Cancellable | null> | null ): Promise<Module[]> | void; export function modules_initialize_registered_finish(result: Gio.AsyncResult): Module[]; export function modules_object_for_uri(modules: Module[], uri: string, session_options: SessionOptions): Object | null; export function modules_objects_for_uri(modules: Module[], uri: string, session_options: SessionOptions): Object[]; export function modules_token_for_uri(modules: Module[], uri: string): Slot; export function modules_tokens_for_uri(modules: Module[], uri: string): Slot[]; export function objects_from_handle_array(session: Session, object_handles: number[]): Object[]; export function slots_enumerate_objects(slots: Slot[], match: Attributes, options: SessionOptions): Enumerator; export function uri_build(uri_data: UriData, flags: UriFlags): string; export function uri_error_get_quark(): GLib.Quark; export function uri_parse(string: string, flags: UriFlags): UriData; export function value_to_boolean(value: Uint8Array | string, result: boolean): boolean; export function value_to_ulong(value: Uint8Array | string, result: number): boolean; export type Allocator = (data: any | null, length: number) => any | null; export namespace BuilderFlags { export const $gtype: GObject.GType<BuilderFlags>; } export enum BuilderFlags { NONE = 0, SECURE_MEMORY = 1, } export namespace Error { export const $gtype: GObject.GType<Error>; } export enum Error { PROBLEM = -951891199, } export namespace UriError { export const $gtype: GObject.GType<UriError>; } export enum UriError { BAD_SCHEME = 1, BAD_ENCODING = 2, BAD_SYNTAX = 3, BAD_VERSION = 4, NOT_FOUND = 5, } export namespace SessionOptions { export const $gtype: GObject.GType<SessionOptions>; } export enum SessionOptions { READ_ONLY = 0, READ_WRITE = 2, LOGIN_USER = 4, AUTHENTICATE = 8, } export namespace UriFlags { export const $gtype: GObject.GType<UriFlags>; } export enum UriFlags { FOR_OBJECT = 2, FOR_TOKEN = 4, FOR_MODULE = 8, WITH_VERSION = 16, FOR_ANY = 65535, } export module Enumerator { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; chained: Enumerator; interaction: Gio.TlsInteraction; } } export class Enumerator extends GObject.Object { static $gtype: GObject.GType<Enumerator>; constructor(properties?: Partial<Enumerator.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Enumerator.ConstructorProperties>, ...args: any[]): void; // Properties chained: Enumerator; interaction: Gio.TlsInteraction; // Members get_chained(): Enumerator | null; get_interaction(): Gio.TlsInteraction | null; get_object_type(): GObject.GType; next(cancellable?: Gio.Cancellable | null): Object | null; next_async(max_objects: number, cancellable?: Gio.Cancellable | null): Promise<Object[]>; next_async( max_objects: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; next_async( max_objects: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Object[]> | void; next_finish(result: Gio.AsyncResult): Object[]; next_n(max_objects: number, cancellable?: Gio.Cancellable | null): Object[]; set_chained(chained?: Enumerator | null): void; set_interaction(interaction?: Gio.TlsInteraction | null): void; set_object_type(object_type: GObject.GType, attr_types: number[]): void; } export module Module { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; functions: any; path: string; } } export class Module extends GObject.Object { static $gtype: GObject.GType<Module>; constructor(properties?: Partial<Module.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Module.ConstructorProperties>, ...args: any[]): void; // Properties functions: any; path: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "authenticate-object", callback: (_source: this, object: Object, label: string, password: any | null) => boolean ): number; connect_after( signal: "authenticate-object", callback: (_source: this, object: Object, label: string, password: any | null) => boolean ): number; emit(signal: "authenticate-object", object: Object, label: string, password: any | null): void; connect( signal: "authenticate-slot", callback: (_source: this, slot: Slot, string: string, password: any | null) => boolean ): number; connect_after( signal: "authenticate-slot", callback: (_source: this, slot: Slot, string: string, password: any | null) => boolean ): number; emit(signal: "authenticate-slot", slot: Slot, string: string, password: any | null): void; // Members equal(module2: Module): boolean; get_info(): ModuleInfo; get_path(): string; get_slots(token_present: boolean): Slot[]; hash(): number; match(uri: UriData): boolean; vfunc_authenticate_object(object: Object, label: string, password: string): boolean; vfunc_authenticate_slot(slot: Slot, label: string, password: string): boolean; static initialize(path: string, cancellable?: Gio.Cancellable | null): Module; static initialize_async(path: string, cancellable?: Gio.Cancellable | null): Promise<Module | null>; static initialize_async( path: string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<Module> | null ): void; static initialize_async( path: string, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<Module> | null ): Promise<Module | null> | void; static initialize_finish(result: Gio.AsyncResult): Module | null; } export module Object { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; handle: number; module: Module; session: Session; } } export class Object extends GObject.Object { static $gtype: GObject.GType<Object>; constructor(properties?: Partial<Object.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Object.ConstructorProperties>, ...args: any[]): void; // Properties handle: number; module: Module; session: Session; // Members cache_lookup(attr_types: number[], cancellable?: Gio.Cancellable | null): Attributes; cache_lookup_async(attr_types: number[], cancellable?: Gio.Cancellable | null): Promise<Attributes>; cache_lookup_async( attr_types: number[], cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; cache_lookup_async( attr_types: number[], cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Attributes> | void; cache_lookup_finish(result: Gio.AsyncResult): Attributes; destroy(cancellable?: Gio.Cancellable | null): boolean; destroy_async(cancellable?: Gio.Cancellable | null): Promise<boolean>; destroy_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; destroy_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; destroy_finish(result: Gio.AsyncResult): boolean; equal(object2: Object): boolean; get_async(attr_types: number[], cancellable?: Gio.Cancellable | null): Promise<Attributes>; get_async( attr_types: number[], cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; get_async( attr_types: number[], cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Attributes> | void; get_data(attr_type: number, cancellable?: Gio.Cancellable | null): Uint8Array; get_data(...args: never[]): never; get_data_async(attr_type: number, allocator: Allocator, cancellable?: Gio.Cancellable | null): Promise<Uint8Array>; get_data_async( attr_type: number, allocator: Allocator, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; get_data_async( attr_type: number, allocator: Allocator, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Uint8Array> | void; get_data_finish(result: Gio.AsyncResult): Uint8Array; get_finish(result: Gio.AsyncResult): Attributes; get_full(attr_types: number[], cancellable?: Gio.Cancellable | null): Attributes; get_handle(): number; get_module(): Module; get_session(): Session; get_template(attr_type: number, cancellable?: Gio.Cancellable | null): Attributes; get_template_async(attr_type: number, cancellable?: Gio.Cancellable | null): Promise<Attributes>; get_template_async( attr_type: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; get_template_async( attr_type: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Attributes> | void; get_template_finish(result: Gio.AsyncResult): Attributes; hash(): number; set(attrs: Attributes, cancellable?: Gio.Cancellable | null): boolean; set(...args: never[]): never; set_async(attrs: Attributes, cancellable?: Gio.Cancellable | null): Promise<boolean>; set_async( attrs: Attributes, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; set_async( attrs: Attributes, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; set_finish(result: Gio.AsyncResult): boolean; set_template(attr_type: number, attrs: Attributes, cancellable?: Gio.Cancellable | null): boolean; set_template_async(attr_type: number, attrs: Attributes, cancellable?: Gio.Cancellable | null): Promise<boolean>; set_template_async( attr_type: number, attrs: Attributes, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; set_template_async( attr_type: number, attrs: Attributes, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; set_template_finish(result: Gio.AsyncResult): boolean; static from_handle(session: Session, object_handle: number): Object; } export module Password { export interface ConstructorProperties extends Gio.TlsPassword.ConstructorProperties { [key: string]: any; key: Object; module: Module; token: Slot; } } export class Password extends Gio.TlsPassword { static $gtype: GObject.GType<Password>; constructor(properties?: Partial<Password.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Password.ConstructorProperties>, ...args: any[]): void; // Properties key: Object; module: Module; token: Slot; // Members get_key(): Object; get_module(): Module; get_token(): Slot; } export module Session { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; app_data: any; appData: any; handle: number; interaction: Gio.TlsInteraction; module: Module; opening_flags: number; openingFlags: number; options: SessionOptions; slot: Slot; } } export class Session extends GObject.Object implements Gio.AsyncInitable<Session>, Gio.Initable { static $gtype: GObject.GType<Session>; constructor(properties?: Partial<Session.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Session.ConstructorProperties>, ...args: any[]): void; // Properties app_data: any; appData: any; handle: number; interaction: Gio.TlsInteraction; module: Module; opening_flags: number; openingFlags: number; options: SessionOptions; slot: Slot; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "discard-handle", callback: (_source: this, handle: number) => boolean): number; connect_after(signal: "discard-handle", callback: (_source: this, handle: number) => boolean): number; emit(signal: "discard-handle", handle: number): void; // Members create_object(attrs: Attributes, cancellable?: Gio.Cancellable | null): Object; create_object_async(attrs: Attributes, cancellable?: Gio.Cancellable | null): Promise<Object>; create_object_async( attrs: Attributes, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; create_object_async( attrs: Attributes, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Object> | void; create_object_finish(result: Gio.AsyncResult): Object; decrypt( key: Object, mech_type: number, input: Uint8Array | string, cancellable?: Gio.Cancellable | null ): Uint8Array; decrypt_async( key: Object, mechanism: Mechanism, input: Uint8Array | string, cancellable?: Gio.Cancellable | null ): Promise<Uint8Array>; decrypt_async( key: Object, mechanism: Mechanism, input: Uint8Array | string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; decrypt_async( key: Object, mechanism: Mechanism, input: Uint8Array | string, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Uint8Array> | void; decrypt_finish(result: Gio.AsyncResult): Uint8Array; decrypt_full( key: Object, mechanism: Mechanism, input: Uint8Array | string, cancellable?: Gio.Cancellable | null ): Uint8Array; derive_key(base: Object, mech_type: number, attrs: Attributes, cancellable?: Gio.Cancellable | null): Object; derive_key_async( base: Object, mechanism: Mechanism, attrs: Attributes, cancellable?: Gio.Cancellable | null ): Promise<Object>; derive_key_async( base: Object, mechanism: Mechanism, attrs: Attributes, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; derive_key_async( base: Object, mechanism: Mechanism, attrs: Attributes, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Object> | void; derive_key_finish(result: Gio.AsyncResult): Object; derive_key_full( base: Object, mechanism: Mechanism, attrs: Attributes, cancellable?: Gio.Cancellable | null ): Object; encrypt( key: Object, mech_type: number, input: Uint8Array | string, cancellable?: Gio.Cancellable | null ): Uint8Array; encrypt_async( key: Object, mechanism: Mechanism, input: Uint8Array | string, cancellable?: Gio.Cancellable | null ): Promise<Uint8Array>; encrypt_async( key: Object, mechanism: Mechanism, input: Uint8Array | string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; encrypt_async( key: Object, mechanism: Mechanism, input: Uint8Array | string, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Uint8Array> | void; encrypt_finish(result: Gio.AsyncResult): Uint8Array; encrypt_full( key: Object, mechanism: Mechanism, input: Uint8Array | string, cancellable?: Gio.Cancellable | null ): Uint8Array; enumerate_objects(match: Attributes): Enumerator; find_handles(match: Attributes, cancellable?: Gio.Cancellable | null): number[] | null; find_handles_async(match: Attributes, cancellable?: Gio.Cancellable | null): Promise<number[] | null>; find_handles_async( match: Attributes, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; find_handles_async( match: Attributes, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<number[] | null> | void; find_handles_finish(result: Gio.AsyncResult): number[] | null; find_objects(match: Attributes, cancellable?: Gio.Cancellable | null): Object[]; find_objects_async(match: Attributes, cancellable?: Gio.Cancellable | null): Promise<Object[]>; find_objects_async( match: Attributes, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; find_objects_async( match: Attributes, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Object[]> | void; find_objects_finish(result: Gio.AsyncResult): Object[]; generate_key_pair( mech_type: number, public_attrs: Attributes, private_attrs: Attributes, cancellable?: Gio.Cancellable | null ): [boolean, Object | null, Object | null]; generate_key_pair_async( mechanism: Mechanism, public_attrs: Attributes, private_attrs: Attributes, cancellable?: Gio.Cancellable | null ): Promise<[Object | null, Object | null]>; generate_key_pair_async( mechanism: Mechanism, public_attrs: Attributes, private_attrs: Attributes, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; generate_key_pair_async( mechanism: Mechanism, public_attrs: Attributes, private_attrs: Attributes, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<[Object | null, Object | null]> | void; generate_key_pair_finish(result: Gio.AsyncResult): [boolean, Object | null, Object | null]; generate_key_pair_full( mechanism: Mechanism, public_attrs: Attributes, private_attrs: Attributes, cancellable?: Gio.Cancellable | null ): [boolean, Object | null, Object | null]; get_handle(): number; get_info(): SessionInfo; get_interaction(): Gio.TlsInteraction | null; get_module(): Module; get_options(): SessionOptions; get_slot(): Slot; get_state(): number; init_pin(pin?: Uint8Array | null, cancellable?: Gio.Cancellable | null): boolean; init_pin_async(pin?: Uint8Array | null, cancellable?: Gio.Cancellable | null): Promise<boolean>; init_pin_async( pin: Uint8Array | null, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; init_pin_async( pin?: Uint8Array | null, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; init_pin_finish(result: Gio.AsyncResult): boolean; login(user_type: number, pin?: Uint8Array | null, cancellable?: Gio.Cancellable | null): boolean; login_async(user_type: number, pin?: Uint8Array | null, cancellable?: Gio.Cancellable | null): Promise<boolean>; login_async( user_type: number, pin: Uint8Array | null, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; login_async( user_type: number, pin?: Uint8Array | null, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; login_finish(result: Gio.AsyncResult): boolean; login_interactive( user_type: number, interaction?: Gio.TlsInteraction | null, cancellable?: Gio.Cancellable | null ): boolean; login_interactive_async( user_type: number, interaction?: Gio.TlsInteraction | null, cancellable?: Gio.Cancellable | null ): Promise<boolean>; login_interactive_async( user_type: number, interaction: Gio.TlsInteraction | null, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; login_interactive_async( user_type: number, interaction?: Gio.TlsInteraction | null, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; login_interactive_finish(result: Gio.AsyncResult): boolean; logout(cancellable?: Gio.Cancellable | null): boolean; logout_async(cancellable?: Gio.Cancellable | null): Promise<boolean>; logout_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; logout_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; logout_finish(result: Gio.AsyncResult): boolean; set_interaction(interaction?: Gio.TlsInteraction | null): void; set_pin(old_pin?: Uint8Array | null, new_pin?: Uint8Array | null, cancellable?: Gio.Cancellable | null): boolean; set_pin_async( old_pin: Uint8Array | null, n_old_pin: number, new_pin?: Uint8Array | null, cancellable?: Gio.Cancellable | null ): Promise<boolean>; set_pin_async( old_pin: Uint8Array | null, n_old_pin: number, new_pin: Uint8Array | null, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; set_pin_async( old_pin: Uint8Array | null, n_old_pin: number, new_pin?: Uint8Array | null, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; set_pin_finish(result: Gio.AsyncResult): boolean; sign(key: Object, mech_type: number, input: Uint8Array | string, cancellable?: Gio.Cancellable | null): Uint8Array; sign_async( key: Object, mechanism: Mechanism, input: Uint8Array | string, cancellable?: Gio.Cancellable | null ): Promise<Uint8Array>; sign_async( key: Object, mechanism: Mechanism, input: Uint8Array | string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; sign_async( key: Object, mechanism: Mechanism, input: Uint8Array | string, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Uint8Array> | void; sign_finish(result: Gio.AsyncResult): Uint8Array; sign_full( key: Object, mechanism: Mechanism, input: Uint8Array | string, n_result: number, cancellable?: Gio.Cancellable | null ): number; unwrap_key( wrapper: Object, mech_type: number, input: Uint8Array | string, attrs: Attributes, cancellable?: Gio.Cancellable | null ): Object; unwrap_key_async( wrapper: Object, mechanism: Mechanism, input: Uint8Array | string, attrs: Attributes, cancellable?: Gio.Cancellable | null ): Promise<Object>; unwrap_key_async( wrapper: Object, mechanism: Mechanism, input: Uint8Array | string, attrs: Attributes, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; unwrap_key_async( wrapper: Object, mechanism: Mechanism, input: Uint8Array | string, attrs: Attributes, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Object> | void; unwrap_key_finish(result: Gio.AsyncResult): Object; unwrap_key_full( wrapper: Object, mechanism: Mechanism, input: Uint8Array | string, attrs: Attributes, cancellable?: Gio.Cancellable | null ): Object; verify( key: Object, mech_type: number, input: Uint8Array | string, signature: Uint8Array | string, cancellable?: Gio.Cancellable | null ): boolean; verify_async( key: Object, mechanism: Mechanism, input: Uint8Array | string, signature: Uint8Array | string, cancellable?: Gio.Cancellable | null ): Promise<boolean>; verify_async( key: Object, mechanism: Mechanism, input: Uint8Array | string, signature: Uint8Array | string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; verify_async( key: Object, mechanism: Mechanism, input: Uint8Array | string, signature: Uint8Array | string, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; verify_finish(result: Gio.AsyncResult): boolean; verify_full( key: Object, mechanism: Mechanism, input: Uint8Array | string, signature: Uint8Array | string, cancellable?: Gio.Cancellable | null ): boolean; wrap_key(wrapper: Object, mech_type: number, wrapped: Object, cancellable?: Gio.Cancellable | null): Uint8Array; wrap_key_async( wrapper: Object, mechanism: Mechanism, wrapped: Object, cancellable?: Gio.Cancellable | null ): Promise<Uint8Array>; wrap_key_async( wrapper: Object, mechanism: Mechanism, wrapped: Object, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; wrap_key_async( wrapper: Object, mechanism: Mechanism, wrapped: Object, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Uint8Array> | void; wrap_key_finish(result: Gio.AsyncResult): Uint8Array; wrap_key_full( wrapper: Object, mechanism: Mechanism, wrapped: Object, cancellable?: Gio.Cancellable | null ): Uint8Array; static from_handle(slot: Slot, session_handle: number, options: SessionOptions): Session; static open( slot: Slot, options: SessionOptions, interaction?: Gio.TlsInteraction | null, cancellable?: Gio.Cancellable | null ): Session; static open_async( slot: Slot, options: SessionOptions, interaction?: Gio.TlsInteraction | null, cancellable?: Gio.Cancellable | null ): Promise<Session>; static open_async( slot: Slot, options: SessionOptions, interaction: Gio.TlsInteraction | null, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<Session> | null ): void; static open_async( slot: Slot, options: SessionOptions, interaction?: Gio.TlsInteraction | null, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<Session> | null ): Promise<Session> | void; static open_finish(result: Gio.AsyncResult): Session; // Implemented Members init_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<boolean>; init_async( io_priority: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; init_async( io_priority: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; init_finish(res: Gio.AsyncResult): boolean; new_finish(res: Gio.AsyncResult): Session; vfunc_init_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<boolean>; vfunc_init_async( io_priority: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; vfunc_init_async( io_priority: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_init_finish(res: Gio.AsyncResult): boolean; init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; } export module Slot { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; handle: number; module: Module; } } export class Slot extends GObject.Object { static $gtype: GObject.GType<Slot>; constructor(properties?: Partial<Slot.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Slot.ConstructorProperties>, ...args: any[]): void; // Properties handle: number; module: Module; // Members enumerate_objects(match: Attributes, options: SessionOptions): Enumerator; equal(slot2: Slot): boolean; get_handle(): number; get_info(): SlotInfo; get_mechanism_info(mech_type: number): MechanismInfo; get_mechanisms(): number[]; get_module(): Module; get_token_info(): TokenInfo; has_flags(flags: number): boolean; hash(): number; match(uri: UriData): boolean; open_session(options: SessionOptions, cancellable?: Gio.Cancellable | null): Session; open_session_async(options: SessionOptions, cancellable?: Gio.Cancellable | null): Promise<Session>; open_session_async( options: SessionOptions, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; open_session_async( options: SessionOptions, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Session> | void; open_session_finish(result: Gio.AsyncResult): Session; static from_handle(module: Module, slot_id: number): Slot; } export class Attribute { static $gtype: GObject.GType<Attribute>; constructor(attr_type: number, value: number, length: number); constructor(copy: Attribute); // Fields type: number; value: Uint8Array; length: number; // Constructors static ["new"](attr_type: number, value: number, length: number): Attribute; static new_boolean(attr_type: number, value: boolean): Attribute; static new_date(attr_type: number, value: GLib.Date): Attribute; static new_empty(attr_type: number): Attribute; static new_invalid(attr_type: number): Attribute; static new_string(attr_type: number, value: string): Attribute; static new_ulong(attr_type: number, value: number): Attribute; // Members clear(): void; dump(): void; dup(): Attribute; equal(attr2: Attribute): boolean; free(): void; get_boolean(): boolean; get_data(): Uint8Array; get_date(value: GLib.Date): void; get_string(): string | null; get_ulong(): number; hash(): number; init_copy(src: Attribute): void; is_invalid(): boolean; } export class Attributes { static $gtype: GObject.GType<Attributes>; constructor(reserved: number); constructor(copy: Attributes); // Constructors static ["new"](reserved: number): Attributes; // Members at(index: number): Attribute; contains(match: Attribute): boolean; count(): number; dump(): void; find(attr_type: number): Attribute; find_boolean(attr_type: number): [boolean, boolean]; find_date(attr_type: number): [boolean, GLib.Date]; find_string(attr_type: number): [boolean, string]; find_ulong(attr_type: number): [boolean, number]; ref(): Attributes; ref_sink(): Attributes; to_string(): string; unref(): void; } export class Builder { static $gtype: GObject.GType<Builder>; constructor(flags: BuilderFlags); constructor(copy: Builder); // Fields x: number[]; // Constructors static ["new"](flags: BuilderFlags): Builder; // Members add_all(attrs: Attributes): void; add_attribute(attr: Attribute): void; add_boolean(attr_type: number, value: boolean): void; add_data(attr_type: number, value?: Uint8Array | null): void; add_date(attr_type: number, value: GLib.Date): void; add_empty(attr_type: number): void; add_invalid(attr_type: number): void; add_only(attrs: Attributes, only_types: number[]): void; add_string(attr_type: number, value?: string | null): void; add_ulong(attr_type: number, value: number): void; clear(): void; copy(): Builder; end(): Attributes; find(attr_type: number): Attribute; find_boolean(attr_type: number): [boolean, boolean]; find_date(attr_type: number): [boolean, GLib.Date]; find_string(attr_type: number): [boolean, string]; find_ulong(attr_type: number): [boolean, number]; init(): void; init_full(flags: BuilderFlags): void; ref(): Builder; set_all(attrs: Attributes): void; set_boolean(attr_type: number, value: boolean): void; set_data(attr_type: number, value?: Uint8Array | null): void; set_date(attr_type: number, value: GLib.Date): void; set_empty(attr_type: number): void; set_invalid(attr_type: number): void; set_string(attr_type: number, value: string): void; set_ulong(attr_type: number, value: number): void; steal(): Attributes; take_data(attr_type: number, value?: Uint8Array | null): void; static unref(builder?: any | null): void; } export class EnumeratorPrivate { static $gtype: GObject.GType<EnumeratorPrivate>; constructor(copy: EnumeratorPrivate); } export class Mechanism { static $gtype: GObject.GType<Mechanism>; constructor( properties?: Partial<{ type?: number; parameter?: any; n_parameter?: number; }> ); constructor(copy: Mechanism); // Fields type: number; parameter: any; n_parameter: number; } export class MechanismInfo { static $gtype: GObject.GType<MechanismInfo>; constructor( properties?: Partial<{ min_key_size?: number; max_key_size?: number; flags?: number; }> ); constructor(copy: MechanismInfo); // Fields min_key_size: number; max_key_size: number; flags: number; // Members copy(): MechanismInfo; free(): void; } export class ModuleInfo { static $gtype: GObject.GType<ModuleInfo>; constructor( properties?: Partial<{ pkcs11_version_major?: number; pkcs11_version_minor?: number; manufacturer_id?: string; flags?: number; library_description?: string; library_version_major?: number; library_version_minor?: number; }> ); constructor(copy: ModuleInfo); // Fields pkcs11_version_major: number; pkcs11_version_minor: number; manufacturer_id: string; flags: number; library_description: string; library_version_major: number; library_version_minor: number; // Members copy(): ModuleInfo; free(): void; } export class ModulePrivate { static $gtype: GObject.GType<ModulePrivate>; constructor(copy: ModulePrivate); } export class ObjectPrivate { static $gtype: GObject.GType<ObjectPrivate>; constructor(copy: ObjectPrivate); } export class PasswordPrivate { static $gtype: GObject.GType<PasswordPrivate>; constructor(copy: PasswordPrivate); } export class SessionInfo { static $gtype: GObject.GType<SessionInfo>; constructor( properties?: Partial<{ slot_id?: number; state?: number; flags?: number; device_error?: number; }> ); constructor(copy: SessionInfo); // Fields slot_id: number; state: number; flags: number; device_error: number; // Members copy(): SessionInfo; free(): void; } export class SessionPrivate { static $gtype: GObject.GType<SessionPrivate>; constructor(copy: SessionPrivate); } export class SlotInfo { static $gtype: GObject.GType<SlotInfo>; constructor( properties?: Partial<{ slot_description?: string; manufacturer_id?: string; flags?: number; hardware_version_major?: number; hardware_version_minor?: number; firmware_version_major?: number; firmware_version_minor?: number; }> ); constructor(copy: SlotInfo); // Fields slot_description: string; manufacturer_id: string; flags: number; hardware_version_major: number; hardware_version_minor: number; firmware_version_major: number; firmware_version_minor: number; // Members copy(): SlotInfo; free(): void; } export class SlotPrivate { static $gtype: GObject.GType<SlotPrivate>; constructor(copy: SlotPrivate); } export class TokenInfo { static $gtype: GObject.GType<TokenInfo>; constructor( properties?: Partial<{ label?: string; manufacturer_id?: string; model?: string; serial_number?: string; flags?: number; max_session_count?: number; session_count?: number; max_rw_session_count?: number; rw_session_count?: number; max_pin_len?: number; min_pin_len?: number; total_public_memory?: number; free_public_memory?: number; total_private_memory?: number; free_private_memory?: number; hardware_version_major?: number; hardware_version_minor?: number; firmware_version_major?: number; firmware_version_minor?: number; utc_time?: number; }> ); constructor(copy: TokenInfo); // Fields label: string; manufacturer_id: string; model: string; serial_number: string; flags: number; max_session_count: number; session_count: number; max_rw_session_count: number; rw_session_count: number; max_pin_len: number; min_pin_len: number; total_public_memory: number; free_public_memory: number; total_private_memory: number; free_private_memory: number; hardware_version_major: number; hardware_version_minor: number; firmware_version_major: number; firmware_version_minor: number; utc_time: number; // Members copy(): TokenInfo; free(): void; } export class UriData { static $gtype: GObject.GType<UriData>; constructor(); constructor(copy: UriData); // Fields any_unrecognized: boolean; module_info: ModuleInfo; token_info: TokenInfo; attributes: Attributes; dummy: any[]; // Constructors static ["new"](): UriData; // Members copy(): UriData; free(): void; } export interface ObjectCacheNamespace { $gtype: GObject.GType<ObjectCache>; prototype: ObjectCachePrototype; } export type ObjectCache = ObjectCachePrototype; export interface ObjectCachePrototype extends Object { // Properties attributes: Attributes; // Members fill(attrs: Attributes): void; set_attributes(attrs?: Attributes | null): void; update(attr_types: number[], cancellable?: Gio.Cancellable | null): boolean; update_async(attr_types: number[], cancellable?: Gio.Cancellable | null): Promise<boolean>; update_async( attr_types: number[], cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; update_async( attr_types: number[], cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; update_finish(result: Gio.AsyncResult): boolean; vfunc_fill(attrs: Attributes): void; } export const ObjectCache: ObjectCacheNamespace;
the_stack
namespace ts { /** * Partial interface of the System thats needed to support the caching of directory structure */ export interface DirectoryStructureHost { fileExists(path: string): boolean; readFile(path: string, encoding?: string): string | undefined; // TODO: GH#18217 Optional methods are frequently used as non-optional directoryExists?(path: string): boolean; getDirectories?(path: string): string[]; readDirectory?(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; realpath?(path: string): string; createDirectory?(path: string): void; writeFile?(path: string, data: string, writeByteOrderMark?: boolean): void; } interface FileAndDirectoryExistence { fileExists: boolean; directoryExists: boolean; } export interface CachedDirectoryStructureHost extends DirectoryStructureHost { useCaseSensitiveFileNames: boolean; getDirectories(path: string): string[]; readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; /** Returns the queried result for the file exists and directory exists if at all it was done */ addOrDeleteFileOrDirectory(fileOrDirectory: string, fileOrDirectoryPath: Path): FileAndDirectoryExistence | undefined; addOrDeleteFile(fileName: string, filePath: Path, eventKind: FileWatcherEventKind): void; clearCache(): void; } interface MutableFileSystemEntries { readonly files: string[]; readonly directories: string[]; } export function createCachedDirectoryStructureHost(host: DirectoryStructureHost, currentDirectory: string, useCaseSensitiveFileNames: boolean): CachedDirectoryStructureHost | undefined { if (!host.getDirectories || !host.readDirectory) { return undefined; } const cachedReadDirectoryResult = new Map<string, MutableFileSystemEntries | false>(); const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); return { useCaseSensitiveFileNames, fileExists, readFile: (path, encoding) => host.readFile(path, encoding), directoryExists: host.directoryExists && directoryExists, getDirectories, readDirectory, createDirectory: host.createDirectory && createDirectory, writeFile: host.writeFile && writeFile, addOrDeleteFileOrDirectory, addOrDeleteFile, clearCache, realpath: host.realpath && realpath }; function toPath(fileName: string) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function getCachedFileSystemEntries(rootDirPath: Path) { return cachedReadDirectoryResult.get(ensureTrailingDirectorySeparator(rootDirPath)); } function getCachedFileSystemEntriesForBaseDir(path: Path) { return getCachedFileSystemEntries(getDirectoryPath(path)); } function getBaseNameOfFileName(fileName: string) { return getBaseFileName(normalizePath(fileName)); } function createCachedFileSystemEntries(rootDir: string, rootDirPath: Path) { if (!host.realpath || ensureTrailingDirectorySeparator(toPath(host.realpath(rootDir))) === rootDirPath) { const resultFromHost: MutableFileSystemEntries = { files: map(host.readDirectory!(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/["*.*"]), getBaseNameOfFileName) || [], directories: host.getDirectories!(rootDir) || [] }; cachedReadDirectoryResult.set(ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); return resultFromHost; } // If the directory is symlink do not cache the result if (host.directoryExists?.(rootDir)) { cachedReadDirectoryResult.set(rootDirPath, false); return false; } // Non existing directory return undefined; } /** * If the readDirectory result was already cached, it returns that * Otherwise gets result from host and caches it. * The host request is done under try catch block to avoid caching incorrect result */ function tryReadDirectory(rootDir: string, rootDirPath: Path) { rootDirPath = ensureTrailingDirectorySeparator(rootDirPath); const cachedResult = getCachedFileSystemEntries(rootDirPath); if (cachedResult) { return cachedResult; } try { return createCachedFileSystemEntries(rootDir, rootDirPath); } catch (_e) { // If there is exception to read directories, dont cache the result and direct the calls to host Debug.assert(!cachedReadDirectoryResult.has(ensureTrailingDirectorySeparator(rootDirPath))); return undefined; } } function fileNameEqual(name1: string, name2: string) { return getCanonicalFileName(name1) === getCanonicalFileName(name2); } function hasEntry(entries: readonly string[], name: string) { return some(entries, file => fileNameEqual(file, name)); } function updateFileSystemEntry(entries: string[], baseName: string, isValid: boolean) { if (hasEntry(entries, baseName)) { if (!isValid) { return filterMutate(entries, entry => !fileNameEqual(entry, baseName)); } } else if (isValid) { return entries.push(baseName); } } function writeFile(fileName: string, data: string, writeByteOrderMark?: boolean): void { const path = toPath(fileName); const result = getCachedFileSystemEntriesForBaseDir(path); if (result) { updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); } return host.writeFile!(fileName, data, writeByteOrderMark); } function fileExists(fileName: string): boolean { const path = toPath(fileName); const result = getCachedFileSystemEntriesForBaseDir(path); return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || host.fileExists(fileName); } function directoryExists(dirPath: string): boolean { const path = toPath(dirPath); return cachedReadDirectoryResult.has(ensureTrailingDirectorySeparator(path)) || host.directoryExists!(dirPath); } function createDirectory(dirPath: string) { const path = toPath(dirPath); const result = getCachedFileSystemEntriesForBaseDir(path); const baseFileName = getBaseNameOfFileName(dirPath); if (result) { updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); } host.createDirectory!(dirPath); } function getDirectories(rootDir: string): string[] { const rootDirPath = toPath(rootDir); const result = tryReadDirectory(rootDir, rootDirPath); if (result) { return result.directories.slice(); } return host.getDirectories!(rootDir); } function readDirectory(rootDir: string, extensions?: readonly string[], excludes?: readonly string[], includes?: readonly string[], depth?: number): string[] { const rootDirPath = toPath(rootDir); const rootResult = tryReadDirectory(rootDir, rootDirPath); let rootSymLinkResult: FileSystemEntries | undefined; if (rootResult !== undefined) { return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory!(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir: string): FileSystemEntries { const path = toPath(dir); if (path === rootDirPath) { return rootResult || getFileSystemEntriesFromHost(dir, path); } const result = tryReadDirectory(dir, path); return result !== undefined ? result || getFileSystemEntriesFromHost(dir, path) : emptyFileSystemEntries; } function getFileSystemEntriesFromHost(dir: string, path: Path): FileSystemEntries { if (rootSymLinkResult && path === rootDirPath) return rootSymLinkResult; const result: FileSystemEntries = { files: map(host.readDirectory!(dir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/["*.*"]), getBaseNameOfFileName) || emptyArray, directories: host.getDirectories!(dir) || emptyArray }; if (path === rootDirPath) rootSymLinkResult = result; return result; } } function realpath(s: string) { return host.realpath ? host.realpath(s) : s; } function addOrDeleteFileOrDirectory(fileOrDirectory: string, fileOrDirectoryPath: Path) { const existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); if (existingResult !== undefined) { // Just clear the cache for now // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated clearCache(); return undefined; } const parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); if (!parentResult) { return undefined; } // This was earlier a file (hence not in cached directory contents) // or we never cached the directory containing it if (!host.directoryExists) { // Since host doesnt support directory exists, clear the cache as otherwise it might not be same clearCache(); return undefined; } const baseName = getBaseNameOfFileName(fileOrDirectory); const fsQueryResult: FileAndDirectoryExistence = { fileExists: host.fileExists(fileOrDirectoryPath), directoryExists: host.directoryExists(fileOrDirectoryPath) }; if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { // Folder added or removed, clear the cache instead of updating the folder and its structure clearCache(); } else { // No need to update the directory structure, just files updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); } return fsQueryResult; } function addOrDeleteFile(fileName: string, filePath: Path, eventKind: FileWatcherEventKind) { if (eventKind === FileWatcherEventKind.Changed) { return; } const parentResult = getCachedFileSystemEntriesForBaseDir(filePath); if (parentResult) { updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === FileWatcherEventKind.Created); } } function updateFilesOfFileSystemEntry(parentResult: MutableFileSystemEntries, baseName: string, fileExists: boolean) { updateFileSystemEntry(parentResult.files, baseName, fileExists); } function clearCache() { cachedReadDirectoryResult.clear(); } } export enum ConfigFileProgramReloadLevel { None, /** Update the file name list from the disk */ Partial, /** Reload completely by re-reading contents of config file from disk and updating program */ Full } export interface SharedExtendedConfigFileWatcher<T> extends FileWatcher { watcher: FileWatcher; projects: Set<T>; } /** * Updates the map of shared extended config file watches with a new set of extended config files from a base config file of the project */ export function updateSharedExtendedConfigFileWatcher<T>( projectPath: T, options: CompilerOptions | undefined, extendedConfigFilesMap: ESMap<Path, SharedExtendedConfigFileWatcher<T>>, createExtendedConfigFileWatch: (extendedConfigPath: string, extendedConfigFilePath: Path) => FileWatcher, toPath: (fileName: string) => Path, ) { const extendedConfigs = arrayToMap(options?.configFile?.extendedSourceFiles || emptyArray, toPath); // remove project from all unrelated watchers extendedConfigFilesMap.forEach((watcher, extendedConfigFilePath) => { if (!extendedConfigs.has(extendedConfigFilePath)) { watcher.projects.delete(projectPath); watcher.close(); } }); // Update the extended config files watcher extendedConfigs.forEach((extendedConfigFileName, extendedConfigFilePath) => { const existing = extendedConfigFilesMap.get(extendedConfigFilePath); if (existing) { existing.projects.add(projectPath); } else { // start watching previously unseen extended config extendedConfigFilesMap.set(extendedConfigFilePath, { projects: new Set([projectPath]), watcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), close: () => { const existing = extendedConfigFilesMap.get(extendedConfigFilePath); if (!existing || existing.projects.size !== 0) return; existing.watcher.close(); extendedConfigFilesMap.delete(extendedConfigFilePath); }, }); } }); } /** * Remove the project from the extended config file watchers and close not needed watches */ export function clearSharedExtendedConfigFileWatcher<T>( projectPath: T, extendedConfigFilesMap: ESMap<Path, SharedExtendedConfigFileWatcher<T>>, ) { extendedConfigFilesMap.forEach(watcher => { if (watcher.projects.delete(projectPath)) watcher.close(); }); } /** * Clean the extendsConfigCache when extended config file has changed */ export function cleanExtendedConfigCache( extendedConfigCache: ESMap<string, ExtendedConfigCacheEntry>, extendedConfigFilePath: Path, toPath: (fileName: string) => Path, ) { if (!extendedConfigCache.delete(extendedConfigFilePath)) return; extendedConfigCache.forEach(({ extendedResult }, key) => { if (extendedResult.extendedSourceFiles?.some(extendedFile => toPath(extendedFile) === extendedConfigFilePath)) { cleanExtendedConfigCache(extendedConfigCache, key as Path, toPath); } }); } /** * Updates watchers based on the package json files used in module resolution */ export function updatePackageJsonWatch( lookups: readonly (readonly [Path, object | boolean])[], packageJsonWatches: ESMap<Path, FileWatcher>, createPackageJsonWatch: (packageJsonPath: Path, data: object | boolean) => FileWatcher, ) { const newMap = new Map(lookups); mutateMap( packageJsonWatches, newMap, { createNewValue: createPackageJsonWatch, onDeleteValue: closeFileWatcher } ); } /** * Updates the existing missing file watches with the new set of missing files after new program is created */ export function updateMissingFilePathsWatch( program: Program, missingFileWatches: ESMap<Path, FileWatcher>, createMissingFileWatch: (missingFilePath: Path) => FileWatcher, ) { const missingFilePaths = program.getMissingFilePaths(); // TODO(rbuckton): Should be a `Set` but that requires changing the below code that uses `mutateMap` const newMissingFilePathMap = arrayToMap(missingFilePaths, identity, returnTrue); // Update the missing file paths watcher mutateMap( missingFileWatches, newMissingFilePathMap, { // Watch the missing files createNewValue: createMissingFileWatch, // Files that are no longer missing (e.g. because they are no longer required) // should no longer be watched. onDeleteValue: closeFileWatcher } ); } export interface WildcardDirectoryWatcher { watcher: FileWatcher; flags: WatchDirectoryFlags; } /** * Updates the existing wild card directory watches with the new set of wild card directories from the config file * after new program is created because the config file was reloaded or program was created first time from the config file * Note that there is no need to call this function when the program is updated with additional files without reloading config files, * as wildcard directories wont change unless reloading config file */ export function updateWatchingWildcardDirectories( existingWatchedForWildcards: ESMap<string, WildcardDirectoryWatcher>, wildcardDirectories: ESMap<string, WatchDirectoryFlags>, watchDirectory: (directory: string, flags: WatchDirectoryFlags) => FileWatcher ) { mutateMap( existingWatchedForWildcards, wildcardDirectories, { // Create new watch and recursive info createNewValue: createWildcardDirectoryWatcher, // Close existing watch thats not needed any more onDeleteValue: closeFileWatcherOf, // Close existing watch that doesnt match in the flags onExistingValue: updateWildcardDirectoryWatcher } ); function createWildcardDirectoryWatcher(directory: string, flags: WatchDirectoryFlags): WildcardDirectoryWatcher { // Create new watch and recursive info return { watcher: watchDirectory(directory, flags), flags }; } function updateWildcardDirectoryWatcher(existingWatcher: WildcardDirectoryWatcher, flags: WatchDirectoryFlags, directory: string) { // Watcher needs to be updated if the recursive flags dont match if (existingWatcher.flags === flags) { return; } existingWatcher.watcher.close(); existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); } } export interface IsIgnoredFileFromWildCardWatchingInput { watchedDirPath: Path; fileOrDirectory: string; fileOrDirectoryPath: Path; configFileName: string; options: CompilerOptions; program: BuilderProgram | Program | readonly string[] | undefined; extraFileExtensions?: readonly FileExtensionInfo[]; currentDirectory: string; useCaseSensitiveFileNames: boolean; writeLog: (s: string) => void; toPath: (fileName: string) => Path; } /* @internal */ export function isIgnoredFileFromWildCardWatching({ watchedDirPath, fileOrDirectory, fileOrDirectoryPath, configFileName, options, program, extraFileExtensions, currentDirectory, useCaseSensitiveFileNames, writeLog, toPath, }: IsIgnoredFileFromWildCardWatchingInput): boolean { const newPath = removeIgnoredPath(fileOrDirectoryPath); if (!newPath) { writeLog(`Project: ${configFileName} Detected ignored path: ${fileOrDirectory}`); return true; } fileOrDirectoryPath = newPath; if (fileOrDirectoryPath === watchedDirPath) return false; // If the the added or created file or directory is not supported file name, ignore the file // But when watched directory is added/removed, we need to reload the file list if (hasExtension(fileOrDirectoryPath) && !isSupportedSourceFileName(fileOrDirectory, options, extraFileExtensions)) { writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); return true; } if (isExcludedFile(fileOrDirectory, options.configFile!.configFileSpecs!, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) { writeLog(`Project: ${configFileName} Detected excluded file: ${fileOrDirectory}`); return true; } if (!program) return false; // We want to ignore emit file check if file is not going to be emitted next to source file // In that case we follow config file inclusion rules if (outFile(options) || options.outDir) return false; // File if emitted next to input needs to be ignored if (isDeclarationFileName(fileOrDirectoryPath)) { // If its declaration directory: its not ignored if not excluded by config if (options.declarationDir) return false; } else if (!fileExtensionIsOneOf(fileOrDirectoryPath, supportedJSExtensionsFlat)) { return false; } // just check if sourceFile with the name exists const filePathWithoutExtension = removeFileExtension(fileOrDirectoryPath); const realProgram = isArray(program) ? undefined : isBuilderProgram(program) ? program.getProgramOrUndefined() : program; const builderProgram = !realProgram && !isArray(program) ? program as BuilderProgram : undefined; if (hasSourceFile((filePathWithoutExtension + Extension.Ts) as Path) || hasSourceFile((filePathWithoutExtension + Extension.Tsx) as Path)) { writeLog(`Project: ${configFileName} Detected output file: ${fileOrDirectory}`); return true; } return false; function hasSourceFile(file: Path): boolean { return realProgram ? !!realProgram.getSourceFileByPath(file) : builderProgram ? builderProgram.getState().fileInfos.has(file) : !!find(program as readonly string[], rootFile => toPath(rootFile) === file); } } function isBuilderProgram<T extends BuilderProgram>(program: Program | T): program is T { return !!(program as T).getState; } export function isEmittedFileOfProgram(program: Program | undefined, file: string) { if (!program) { return false; } return program.isEmittedFile(file); } export enum WatchLogLevel { None, TriggerOnly, Verbose } export interface WatchFactoryHost { watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher; watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher; getCurrentDirectory?(): string; useCaseSensitiveFileNames: boolean | (() => boolean); } export interface WatchFactory<X, Y = undefined> { watchFile: (file: string, callback: FileWatcherCallback, pollingInterval: PollingInterval, options: WatchOptions | undefined, detailInfo1: X, detailInfo2?: Y) => FileWatcher; watchDirectory: (directory: string, callback: DirectoryWatcherCallback, flags: WatchDirectoryFlags, options: WatchOptions | undefined, detailInfo1: X, detailInfo2?: Y) => FileWatcher; } export type GetDetailWatchInfo<X, Y> = (detailInfo1: X, detailInfo2: Y | undefined) => string; export function getWatchFactory<X, Y = undefined>(host: WatchFactoryHost, watchLogLevel: WatchLogLevel, log: (s: string) => void, getDetailWatchInfo?: GetDetailWatchInfo<X, Y>): WatchFactory<X, Y> { setSysLog(watchLogLevel === WatchLogLevel.Verbose ? log : noop); const plainInvokeFactory: WatchFactory<X, Y> = { watchFile: (file, callback, pollingInterval, options) => host.watchFile(file, callback, pollingInterval, options), watchDirectory: (directory, callback, flags, options) => host.watchDirectory(directory, callback, (flags & WatchDirectoryFlags.Recursive) !== 0, options), }; const triggerInvokingFactory: WatchFactory<X, Y> | undefined = watchLogLevel !== WatchLogLevel.None ? { watchFile: createTriggerLoggingAddWatch("watchFile"), watchDirectory: createTriggerLoggingAddWatch("watchDirectory") } : undefined; const factory = watchLogLevel === WatchLogLevel.Verbose ? { watchFile: createFileWatcherWithLogging, watchDirectory: createDirectoryWatcherWithLogging } : triggerInvokingFactory || plainInvokeFactory; const excludeWatcherFactory = watchLogLevel === WatchLogLevel.Verbose ? createExcludeWatcherWithLogging : returnNoopFileWatcher; return { watchFile: createExcludeHandlingAddWatch("watchFile"), watchDirectory: createExcludeHandlingAddWatch("watchDirectory") }; function createExcludeHandlingAddWatch<T extends keyof WatchFactory<X, Y>>(key: T): WatchFactory<X, Y>[T] { return ( file: string, cb: FileWatcherCallback | DirectoryWatcherCallback, flags: PollingInterval | WatchDirectoryFlags, options: WatchOptions | undefined, detailInfo1: X, detailInfo2?: Y ) => !matchesExclude(file, key === "watchFile" ? options?.excludeFiles : options?.excludeDirectories, useCaseSensitiveFileNames(), host.getCurrentDirectory?.() || "") ? factory[key].call(/*thisArgs*/ undefined, file, cb, flags, options, detailInfo1, detailInfo2) : excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2); } function useCaseSensitiveFileNames() { return typeof host.useCaseSensitiveFileNames === "boolean" ? host.useCaseSensitiveFileNames : host.useCaseSensitiveFileNames(); } function createExcludeWatcherWithLogging( file: string, flags: PollingInterval | WatchDirectoryFlags, options: WatchOptions | undefined, detailInfo1: X, detailInfo2?: Y ) { log(`ExcludeWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); return { close: () => log(`ExcludeWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`) }; } function createFileWatcherWithLogging( file: string, cb: FileWatcherCallback, flags: PollingInterval, options: WatchOptions | undefined, detailInfo1: X, detailInfo2?: Y ): FileWatcher { log(`FileWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); const watcher = triggerInvokingFactory!.watchFile(file, cb, flags, options, detailInfo1, detailInfo2); return { close: () => { log(`FileWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); watcher.close(); } }; } function createDirectoryWatcherWithLogging( file: string, cb: DirectoryWatcherCallback, flags: WatchDirectoryFlags, options: WatchOptions | undefined, detailInfo1: X, detailInfo2?: Y ): FileWatcher { const watchInfo = `DirectoryWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; log(watchInfo); const start = timestamp(); const watcher = triggerInvokingFactory!.watchDirectory(file, cb, flags, options, detailInfo1, detailInfo2); const elapsed = timestamp() - start; log(`Elapsed:: ${elapsed}ms ${watchInfo}`); return { close: () => { const watchInfo = `DirectoryWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; log(watchInfo); const start = timestamp(); watcher.close(); const elapsed = timestamp() - start; log(`Elapsed:: ${elapsed}ms ${watchInfo}`); } }; } function createTriggerLoggingAddWatch<T extends keyof WatchFactory<X, Y>>(key: T): WatchFactory<X, Y>[T] { return ( file: string, cb: FileWatcherCallback | DirectoryWatcherCallback, flags: PollingInterval | WatchDirectoryFlags, options: WatchOptions | undefined, detailInfo1: X, detailInfo2?: Y ) => plainInvokeFactory[key].call(/*thisArgs*/ undefined, file, (...args: any[]) => { const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== undefined ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; log(triggerredInfo); const start = timestamp(); cb.call(/*thisArg*/ undefined, ...args); const elapsed = timestamp() - start; log(`Elapsed:: ${elapsed}ms ${triggerredInfo}`); }, flags, options, detailInfo1, detailInfo2); } function getWatchInfo<T>(file: string, flags: T, options: WatchOptions | undefined, detailInfo1: X, detailInfo2: Y | undefined, getDetailWatchInfo: GetDetailWatchInfo<X, Y> | undefined) { return `WatchInfo: ${file} ${flags} ${JSON.stringify(options)} ${getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`; } } export function getFallbackOptions(options: WatchOptions | undefined): WatchOptions { const fallbackPolling = options?.fallbackPolling; return { watchFile: fallbackPolling !== undefined ? fallbackPolling as unknown as WatchFileKind : WatchFileKind.PriorityPollingInterval }; } export function closeFileWatcherOf<T extends { watcher: FileWatcher; }>(objWithWatcher: T) { objWithWatcher.watcher.close(); } }
the_stack
declare module 'dns' { // Supported getaddrinfo flags. const ADDRCONFIG: number; const V4MAPPED: number; /** * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as * well as IPv4 mapped IPv6 addresses. */ const ALL: number; interface LookupOptions { family?: number | undefined; hints?: number | undefined; all?: boolean | undefined; verbatim?: boolean | undefined; } interface LookupOneOptions extends LookupOptions { all?: false | undefined; } interface LookupAllOptions extends LookupOptions { all: true; } interface LookupAddress { address: string; family: number; } function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void; function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void; function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. namespace lookup { function __promisify__(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>; function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<LookupAddress>; function __promisify__(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>; } function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void): void; namespace lookupService { function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>; } interface ResolveOptions { ttl: boolean; } interface ResolveWithTtlOptions extends ResolveOptions { ttl: true; } interface RecordWithTtl { address: string; ttl: number; } /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; interface AnyARecord extends RecordWithTtl { type: "A"; } interface AnyAaaaRecord extends RecordWithTtl { type: "AAAA"; } interface MxRecord { priority: number; exchange: string; } interface AnyMxRecord extends MxRecord { type: "MX"; } interface NaptrRecord { flags: string; service: string; regexp: string; replacement: string; order: number; preference: number; } interface AnyNaptrRecord extends NaptrRecord { type: "NAPTR"; } interface SoaRecord { nsname: string; hostmaster: string; serial: number; refresh: number; retry: number; expire: number; minttl: number; } interface AnySoaRecord extends SoaRecord { type: "SOA"; } interface SrvRecord { priority: number; weight: number; port: number; name: string; } interface AnySrvRecord extends SrvRecord { type: "SRV"; } interface AnyTxtRecord { type: "TXT"; entries: string[]; } interface AnyNsRecord { type: "NS"; value: string; } interface AnyPtrRecord { type: "PTR"; value: string; } interface AnyCnameRecord { type: "CNAME"; value: string; } type AnyRecord = AnyARecord | AnyAaaaRecord | AnyCnameRecord | AnyMxRecord | AnyNaptrRecord | AnyNsRecord | AnyPtrRecord | AnySoaRecord | AnySrvRecord | AnyTxtRecord; function resolve(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void): void; function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; function resolve( hostname: string, rrtype: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void, ): void; // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. namespace resolve { function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>; function __promisify__(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>; function __promisify__(hostname: string, rrtype: "MX"): Promise<MxRecord[]>; function __promisify__(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>; function __promisify__(hostname: string, rrtype: "SOA"): Promise<SoaRecord>; function __promisify__(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>; function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>; function __promisify__(hostname: string, rrtype: string): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>; } function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. namespace resolve4 { function __promisify__(hostname: string): Promise<string[]>; function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>; function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>; } function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. namespace resolve6 { function __promisify__(hostname: string): Promise<string[]>; function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>; function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>; } function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; namespace resolveCname { function __promisify__(hostname: string): Promise<string[]>; } function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; namespace resolveMx { function __promisify__(hostname: string): Promise<MxRecord[]>; } function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; namespace resolveNaptr { function __promisify__(hostname: string): Promise<NaptrRecord[]>; } function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; namespace resolveNs { function __promisify__(hostname: string): Promise<string[]>; } function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; namespace resolvePtr { function __promisify__(hostname: string): Promise<string[]>; } function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void; namespace resolveSoa { function __promisify__(hostname: string): Promise<SoaRecord>; } function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; namespace resolveSrv { function __promisify__(hostname: string): Promise<SrvRecord[]>; } function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; namespace resolveTxt { function __promisify__(hostname: string): Promise<string[][]>; } function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; namespace resolveAny { function __promisify__(hostname: string): Promise<AnyRecord[]>; } function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void; function setServers(servers: ReadonlyArray<string>): void; function getServers(): string[]; // Error codes const NODATA: string; const FORMERR: string; const SERVFAIL: string; const NOTFOUND: string; const NOTIMP: string; const REFUSED: string; const BADQUERY: string; const BADNAME: string; const BADFAMILY: string; const BADRESP: string; const CONNREFUSED: string; const TIMEOUT: string; const EOF: string; const FILE: string; const NOMEM: string; const DESTRUCTION: string; const BADSTR: string; const BADFLAGS: string; const NONAME: string; const BADHINTS: string; const NOTINITIALIZED: string; const LOADIPHLPAPI: string; const ADDRGETNETWORKPARAMS: string; const CANCELLED: string; interface ResolverOptions { timeout?: number | undefined; } class Resolver { constructor(options?: ResolverOptions); cancel(): void; getServers: typeof getServers; resolve: typeof resolve; resolve4: typeof resolve4; resolve6: typeof resolve6; resolveAny: typeof resolveAny; resolveCname: typeof resolveCname; resolveMx: typeof resolveMx; resolveNaptr: typeof resolveNaptr; resolveNs: typeof resolveNs; resolvePtr: typeof resolvePtr; resolveSoa: typeof resolveSoa; resolveSrv: typeof resolveSrv; resolveTxt: typeof resolveTxt; reverse: typeof reverse; setLocalAddress(ipv4?: string, ipv6?: string): void; setServers: typeof setServers; } namespace promises { function getServers(): string[]; function lookup(hostname: string, family: number): Promise<LookupAddress>; function lookup(hostname: string, options: LookupOneOptions): Promise<LookupAddress>; function lookup(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>; function lookup(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>; function lookup(hostname: string): Promise<LookupAddress>; function lookupService(address: string, port: number): Promise<{ hostname: string, service: string }>; function resolve(hostname: string): Promise<string[]>; function resolve(hostname: string, rrtype: "A"): Promise<string[]>; function resolve(hostname: string, rrtype: "AAAA"): Promise<string[]>; function resolve(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>; function resolve(hostname: string, rrtype: "CNAME"): Promise<string[]>; function resolve(hostname: string, rrtype: "MX"): Promise<MxRecord[]>; function resolve(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>; function resolve(hostname: string, rrtype: "NS"): Promise<string[]>; function resolve(hostname: string, rrtype: "PTR"): Promise<string[]>; function resolve(hostname: string, rrtype: "SOA"): Promise<SoaRecord>; function resolve(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>; function resolve(hostname: string, rrtype: "TXT"): Promise<string[][]>; function resolve(hostname: string, rrtype: string): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>; function resolve4(hostname: string): Promise<string[]>; function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>; function resolve4(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>; function resolve6(hostname: string): Promise<string[]>; function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>; function resolve6(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>; function resolveAny(hostname: string): Promise<AnyRecord[]>; function resolveCname(hostname: string): Promise<string[]>; function resolveMx(hostname: string): Promise<MxRecord[]>; function resolveNaptr(hostname: string): Promise<NaptrRecord[]>; function resolveNs(hostname: string): Promise<string[]>; function resolvePtr(hostname: string): Promise<string[]>; function resolveSoa(hostname: string): Promise<SoaRecord>; function resolveSrv(hostname: string): Promise<SrvRecord[]>; function resolveTxt(hostname: string): Promise<string[][]>; function reverse(ip: string): Promise<string[]>; function setServers(servers: ReadonlyArray<string>): void; class Resolver { constructor(options?: ResolverOptions); cancel(): void; getServers: typeof getServers; resolve: typeof resolve; resolve4: typeof resolve4; resolve6: typeof resolve6; resolveAny: typeof resolveAny; resolveCname: typeof resolveCname; resolveMx: typeof resolveMx; resolveNaptr: typeof resolveNaptr; resolveNs: typeof resolveNs; resolvePtr: typeof resolvePtr; resolveSoa: typeof resolveSoa; resolveSrv: typeof resolveSrv; resolveTxt: typeof resolveTxt; reverse: typeof reverse; setLocalAddress(ipv4?: string, ipv6?: string): void; setServers: typeof setServers; } } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * A Google Cloud IoT Core device. * * To get more information about Device, see: * * * [API documentation](https://cloud.google.com/iot/docs/reference/cloudiot/rest/) * * How-to Guides * * [Official Documentation](https://cloud.google.com/iot/docs/) * * ## Example Usage * ### Cloudiot Device Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const registry = new gcp.iot.Registry("registry", {}); * const test_device = new gcp.iot.Device("test-device", {registry: registry.id}); * ``` * ### Cloudiot Device Full * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * import * from "fs"; * * const registry = new gcp.iot.Registry("registry", {}); * const test_device = new gcp.iot.Device("test-device", { * registry: registry.id, * credentials: [{ * publicKey: { * format: "RSA_PEM", * key: fs.readFileSync("test-fixtures/rsa_public.pem"), * }, * }], * blocked: false, * logLevel: "INFO", * metadata: { * test_key_1: "test_value_1", * }, * gatewayConfig: { * gatewayType: "NON_GATEWAY", * }, * }); * ``` * * ## Import * * Device can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:iot/device:Device default {{registry}}/devices/{{name}} * ``` */ export class Device extends pulumi.CustomResource { /** * Get an existing Device resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: DeviceState, opts?: pulumi.CustomResourceOptions): Device { return new Device(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:iot/device:Device'; /** * Returns true if the given object is an instance of Device. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Device { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Device.__pulumiType; } /** * If a device is blocked, connections or requests from this device will fail. */ public readonly blocked!: pulumi.Output<boolean | undefined>; /** * The most recent device configuration, which is eventually sent from Cloud IoT Core to the device. */ public /*out*/ readonly configs!: pulumi.Output<outputs.iot.DeviceConfig[]>; /** * The credentials used to authenticate this device. * Structure is documented below. */ public readonly credentials!: pulumi.Output<outputs.iot.DeviceCredential[] | undefined>; /** * Gateway-related configuration and state. * Structure is documented below. */ public readonly gatewayConfig!: pulumi.Output<outputs.iot.DeviceGatewayConfig | undefined>; /** * The last time a cloud-to-device config version acknowledgment was received from the device. */ public /*out*/ readonly lastConfigAckTime!: pulumi.Output<string>; /** * The last time a cloud-to-device config version was sent to the device. */ public /*out*/ readonly lastConfigSendTime!: pulumi.Output<string>; /** * The error message of the most recent error, such as a failure to publish to Cloud Pub/Sub. */ public /*out*/ readonly lastErrorStatuses!: pulumi.Output<outputs.iot.DeviceLastErrorStatus[]>; /** * The time the most recent error occurred, such as a failure to publish to Cloud Pub/Sub. */ public /*out*/ readonly lastErrorTime!: pulumi.Output<string>; /** * The last time a telemetry event was received. */ public /*out*/ readonly lastEventTime!: pulumi.Output<string>; /** * The last time an MQTT PINGREQ was received. */ public /*out*/ readonly lastHeartbeatTime!: pulumi.Output<string>; /** * The last time a state event was received. */ public /*out*/ readonly lastStateTime!: pulumi.Output<string>; /** * The logging verbosity for device activity. * Possible values are `NONE`, `ERROR`, `INFO`, and `DEBUG`. */ public readonly logLevel!: pulumi.Output<string | undefined>; /** * The metadata key-value pairs assigned to the device. */ public readonly metadata!: pulumi.Output<{[key: string]: string} | undefined>; /** * A unique name for the resource. */ public readonly name!: pulumi.Output<string>; /** * A server-defined unique numeric ID for the device. This is a more compact way to identify devices, and it is globally * unique. */ public /*out*/ readonly numId!: pulumi.Output<string>; /** * The name of the device registry where this device should be created. */ public readonly registry!: pulumi.Output<string>; /** * The state most recently received from the device. */ public /*out*/ readonly states!: pulumi.Output<outputs.iot.DeviceState[]>; /** * Create a Device resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: DeviceArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: DeviceArgs | DeviceState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as DeviceState | undefined; inputs["blocked"] = state ? state.blocked : undefined; inputs["configs"] = state ? state.configs : undefined; inputs["credentials"] = state ? state.credentials : undefined; inputs["gatewayConfig"] = state ? state.gatewayConfig : undefined; inputs["lastConfigAckTime"] = state ? state.lastConfigAckTime : undefined; inputs["lastConfigSendTime"] = state ? state.lastConfigSendTime : undefined; inputs["lastErrorStatuses"] = state ? state.lastErrorStatuses : undefined; inputs["lastErrorTime"] = state ? state.lastErrorTime : undefined; inputs["lastEventTime"] = state ? state.lastEventTime : undefined; inputs["lastHeartbeatTime"] = state ? state.lastHeartbeatTime : undefined; inputs["lastStateTime"] = state ? state.lastStateTime : undefined; inputs["logLevel"] = state ? state.logLevel : undefined; inputs["metadata"] = state ? state.metadata : undefined; inputs["name"] = state ? state.name : undefined; inputs["numId"] = state ? state.numId : undefined; inputs["registry"] = state ? state.registry : undefined; inputs["states"] = state ? state.states : undefined; } else { const args = argsOrState as DeviceArgs | undefined; if ((!args || args.registry === undefined) && !opts.urn) { throw new Error("Missing required property 'registry'"); } inputs["blocked"] = args ? args.blocked : undefined; inputs["credentials"] = args ? args.credentials : undefined; inputs["gatewayConfig"] = args ? args.gatewayConfig : undefined; inputs["logLevel"] = args ? args.logLevel : undefined; inputs["metadata"] = args ? args.metadata : undefined; inputs["name"] = args ? args.name : undefined; inputs["registry"] = args ? args.registry : undefined; inputs["configs"] = undefined /*out*/; inputs["lastConfigAckTime"] = undefined /*out*/; inputs["lastConfigSendTime"] = undefined /*out*/; inputs["lastErrorStatuses"] = undefined /*out*/; inputs["lastErrorTime"] = undefined /*out*/; inputs["lastEventTime"] = undefined /*out*/; inputs["lastHeartbeatTime"] = undefined /*out*/; inputs["lastStateTime"] = undefined /*out*/; inputs["numId"] = undefined /*out*/; inputs["states"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Device.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Device resources. */ export interface DeviceState { /** * If a device is blocked, connections or requests from this device will fail. */ blocked?: pulumi.Input<boolean>; /** * The most recent device configuration, which is eventually sent from Cloud IoT Core to the device. */ configs?: pulumi.Input<pulumi.Input<inputs.iot.DeviceConfig>[]>; /** * The credentials used to authenticate this device. * Structure is documented below. */ credentials?: pulumi.Input<pulumi.Input<inputs.iot.DeviceCredential>[]>; /** * Gateway-related configuration and state. * Structure is documented below. */ gatewayConfig?: pulumi.Input<inputs.iot.DeviceGatewayConfig>; /** * The last time a cloud-to-device config version acknowledgment was received from the device. */ lastConfigAckTime?: pulumi.Input<string>; /** * The last time a cloud-to-device config version was sent to the device. */ lastConfigSendTime?: pulumi.Input<string>; /** * The error message of the most recent error, such as a failure to publish to Cloud Pub/Sub. */ lastErrorStatuses?: pulumi.Input<pulumi.Input<inputs.iot.DeviceLastErrorStatus>[]>; /** * The time the most recent error occurred, such as a failure to publish to Cloud Pub/Sub. */ lastErrorTime?: pulumi.Input<string>; /** * The last time a telemetry event was received. */ lastEventTime?: pulumi.Input<string>; /** * The last time an MQTT PINGREQ was received. */ lastHeartbeatTime?: pulumi.Input<string>; /** * The last time a state event was received. */ lastStateTime?: pulumi.Input<string>; /** * The logging verbosity for device activity. * Possible values are `NONE`, `ERROR`, `INFO`, and `DEBUG`. */ logLevel?: pulumi.Input<string>; /** * The metadata key-value pairs assigned to the device. */ metadata?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A unique name for the resource. */ name?: pulumi.Input<string>; /** * A server-defined unique numeric ID for the device. This is a more compact way to identify devices, and it is globally * unique. */ numId?: pulumi.Input<string>; /** * The name of the device registry where this device should be created. */ registry?: pulumi.Input<string>; /** * The state most recently received from the device. */ states?: pulumi.Input<pulumi.Input<inputs.iot.DeviceState>[]>; } /** * The set of arguments for constructing a Device resource. */ export interface DeviceArgs { /** * If a device is blocked, connections or requests from this device will fail. */ blocked?: pulumi.Input<boolean>; /** * The credentials used to authenticate this device. * Structure is documented below. */ credentials?: pulumi.Input<pulumi.Input<inputs.iot.DeviceCredential>[]>; /** * Gateway-related configuration and state. * Structure is documented below. */ gatewayConfig?: pulumi.Input<inputs.iot.DeviceGatewayConfig>; /** * The logging verbosity for device activity. * Possible values are `NONE`, `ERROR`, `INFO`, and `DEBUG`. */ logLevel?: pulumi.Input<string>; /** * The metadata key-value pairs assigned to the device. */ metadata?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A unique name for the resource. */ name?: pulumi.Input<string>; /** * The name of the device registry where this device should be created. */ registry: pulumi.Input<string>; }
the_stack
'use strict'; import { DocumentContext } from '@salesforce/salesforcedx-visualforce-markup-language-server'; import { createConnection, Disposable, DocumentRangeFormattingRequest, DocumentSelector, IConnection, InitializeParams, InitializeResult, Position, RequestType, ServerCapabilities, TextDocumentPositionParams, TextDocuments } from 'vscode-languageserver'; import { Diagnostic, DocumentLink, SymbolInformation, TextDocument } from 'vscode-languageserver-types'; import { getLanguageModes, LanguageModes, Settings } from './modes/languageModes'; import { ColorInformation, ColorPresentationRequest, DocumentColorRequest, ServerCapabilities as CPServerCapabilities } from 'vscode-languageserver-protocol'; import { ConfigurationParams, ConfigurationRequest } from 'vscode-languageserver-protocol'; import { format } from './modes/formatting'; import { pushAll } from './utils/arrays'; import * as path from 'path'; import * as url from 'url'; import uri from 'vscode-uri'; import * as nls from 'vscode-nls'; nls.config(process.env['VSCODE_NLS_CONFIG']); // tslint:disable-next-line:no-namespace namespace TagCloseRequest { export const type: RequestType< TextDocumentPositionParams, string, any, any > = new RequestType('html/tag'); } // Create a connection for the server const connection: IConnection = createConnection(); console.log = connection.console.log.bind(connection.console); console.error = connection.console.error.bind(connection.console); // Create a simple text document manager. The text document manager // supports full document sync only const documents: TextDocuments = new TextDocuments(); // Make the text document manager listen on the connection // for open, change and close text document events documents.listen(connection); let workspacePath: string; let languageModes: LanguageModes; let clientSnippetSupport = false; let clientDynamicRegisterSupport = false; let scopedSettingsSupport = false; let globalSettings: Settings = {}; let documentSettings: { [key: string]: Thenable<Settings> } = {}; // remove document settings on close documents.onDidClose(e => { delete documentSettings[e.document.uri]; }); function getDocumentSettings( textDocument: TextDocument, needsDocumentSettings: () => boolean ): Thenable<Settings> { if (scopedSettingsSupport && needsDocumentSettings()) { let promise = documentSettings[textDocument.uri]; if (!promise) { const scopeUri = textDocument.uri; const configRequestParam: ConfigurationParams = { items: [ { scopeUri, section: 'css' }, { scopeUri, section: 'visualforce' }, { scopeUri, section: 'javascript' } ] }; promise = connection .sendRequest(ConfigurationRequest.type, configRequestParam) .then(s => ({ css: s[0], visualforce: s[1], javascript: s[2] })); documentSettings[textDocument.uri] = promise; } return promise; } return Promise.resolve(void 0); } // After the server has started the client sends an initilize request. The server receives // in the passed params the rootPath of the workspace plus the client capabilites connection.onInitialize( (params: InitializeParams): InitializeResult => { const initializationOptions = params.initializationOptions; workspacePath = params.rootPath; languageModes = getLanguageModes( initializationOptions ? initializationOptions.embeddedLanguages : { css: true, javascript: true } ); documents.onDidClose(e => { languageModes.onDocumentRemoved(e.document); }); connection.onShutdown(() => { languageModes.dispose(); }); function hasClientCapability(...keys: string[]) { let c = params.capabilities; for (let i = 0; c && i < keys.length; i++) { c = c[keys[i]]; } return !!c; } clientSnippetSupport = hasClientCapability( 'textDocument', 'completion', 'completionItem', 'snippetSupport' ); clientDynamicRegisterSupport = hasClientCapability( 'workspace', 'symbol', 'dynamicRegistration' ); scopedSettingsSupport = hasClientCapability('workspace', 'configuration'); const capabilities: ServerCapabilities & CPServerCapabilities = { // Tell the client that the server works in FULL text document sync mode textDocumentSync: documents.syncKind, completionProvider: clientSnippetSupport ? { resolveProvider: true, triggerCharacters: ['.', ':', '<', '"', '=', '/', '>'] } : null, hoverProvider: true, documentHighlightProvider: true, documentRangeFormattingProvider: false, documentLinkProvider: { resolveProvider: false }, documentSymbolProvider: true, definitionProvider: true, signatureHelpProvider: { triggerCharacters: ['('] }, referencesProvider: true, colorProvider: true }; return { capabilities }; } ); let formatterRegistration: Thenable<Disposable> = null; // The settings have changed. Is send on server activation as well. connection.onDidChangeConfiguration(change => { globalSettings = change.settings; documentSettings = {}; // reset all document settings languageModes.getAllModes().forEach(m => { if (m.configure) { m.configure(change.settings); } }); documents.all().forEach(triggerValidation); // dynamically enable & disable the formatter if (clientDynamicRegisterSupport) { const enableFormatter = globalSettings && globalSettings.visualforce && globalSettings.visualforce.format && globalSettings.visualforce.format.enable; if (enableFormatter) { if (!formatterRegistration) { const documentSelector: DocumentSelector = [ { language: 'visualforce', scheme: 'file' } ]; formatterRegistration = connection.client.register( DocumentRangeFormattingRequest.type, { documentSelector } ); } } else if (formatterRegistration) { formatterRegistration.then(r => r.dispose()); formatterRegistration = null; } } }); const pendingValidationRequests: { [uri: string]: NodeJS.Timer } = {}; const validationDelayMs = 200; // The content of a text document has changed. This event is emitted // when the text document first opened or when its content has changed. documents.onDidChangeContent(change => { triggerValidation(change.document); }); // a document has closed: clear all diagnostics documents.onDidClose(event => { cleanPendingValidation(event.document); connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] }); }); function cleanPendingValidation(textDocument: TextDocument): void { const request = pendingValidationRequests[textDocument.uri]; if (request) { clearTimeout(request); delete pendingValidationRequests[textDocument.uri]; } } function triggerValidation(textDocument: TextDocument): void { cleanPendingValidation(textDocument); pendingValidationRequests[textDocument.uri] = setTimeout(() => { delete pendingValidationRequests[textDocument.uri]; // tslint:disable-next-line:no-floating-promises validateTextDocument(textDocument); }, validationDelayMs); } function isValidationEnabled( languageId: string, settings: Settings = globalSettings ) { const validationSettings = settings && settings.visualforce && settings.visualforce.validate; if (validationSettings) { return ( (languageId === 'css' && validationSettings.styles !== false) || (languageId === 'javascript' && validationSettings.scripts !== false) ); } return true; } async function validateTextDocument(textDocument: TextDocument) { const diagnostics: Diagnostic[] = []; if (textDocument.languageId === 'html') { const modes = languageModes.getAllModesInDocument(textDocument); const settings = await getDocumentSettings(textDocument, () => modes.some(m => !!m.doValidation) ); modes.forEach(mode => { if (mode.doValidation && isValidationEnabled(mode.getId(), settings)) { pushAll(diagnostics, mode.doValidation(textDocument, settings)); } }); } connection.sendDiagnostics({ uri: textDocument.uri, diagnostics }); } connection.onCompletion(async textDocumentPosition => { const document = documents.get(textDocumentPosition.textDocument.uri); const mode = languageModes.getModeAtPosition( document, textDocumentPosition.position ); if (mode && mode.doComplete) { if (mode.getId() !== 'html') { connection.telemetry.logEvent({ key: 'html.embbedded.complete', value: { languageId: mode.getId() } }); } const settings = await getDocumentSettings( document, () => mode.doComplete.length > 2 ); return mode.doComplete(document, textDocumentPosition.position, settings); } return { isIncomplete: true, items: [] }; }); connection.onCompletionResolve(item => { const data = item.data; if (data && data.languageId && data.uri) { const mode = languageModes.getMode(data.languageId); const document = documents.get(data.uri); if (mode && mode.doResolve && document) { return mode.doResolve(document, item); } } return item; }); connection.onHover(textDocumentPosition => { const document = documents.get(textDocumentPosition.textDocument.uri); const mode = languageModes.getModeAtPosition( document, textDocumentPosition.position ); if (mode && mode.doHover) { return mode.doHover(document, textDocumentPosition.position); } return null; }); connection.onDocumentHighlight(documentHighlightParams => { const document = documents.get(documentHighlightParams.textDocument.uri); const mode = languageModes.getModeAtPosition( document, documentHighlightParams.position ); if (mode && mode.findDocumentHighlight) { return mode.findDocumentHighlight( document, documentHighlightParams.position ); } return []; }); connection.onDefinition(definitionParams => { const document = documents.get(definitionParams.textDocument.uri); const mode = languageModes.getModeAtPosition( document, definitionParams.position ); if (mode && mode.findDefinition) { return mode.findDefinition(document, definitionParams.position); } return []; }); connection.onReferences(referenceParams => { const document = documents.get(referenceParams.textDocument.uri); const mode = languageModes.getModeAtPosition( document, referenceParams.position ); if (mode && mode.findReferences) { return mode.findReferences(document, referenceParams.position); } return []; }); connection.onSignatureHelp(signatureHelpParms => { const document = documents.get(signatureHelpParms.textDocument.uri); const mode = languageModes.getModeAtPosition( document, signatureHelpParms.position ); if (mode && mode.doSignatureHelp) { return mode.doSignatureHelp(document, signatureHelpParms.position); } return null; }); connection.onDocumentRangeFormatting(async formatParams => { const document = documents.get(formatParams.textDocument.uri); let settings = await getDocumentSettings(document, () => true); if (!settings) { settings = globalSettings; } const unformattedTags: string = (settings && settings.visualforce && settings.visualforce.format && settings.visualforce.format.unformatted) || ''; const enabledModes = { css: !unformattedTags.match(/\bstyle\b/), javascript: !unformattedTags.match(/\bscript\b/) }; return format( languageModes, document, formatParams.range, formatParams.options, settings, enabledModes ); }); connection.onDocumentLinks(documentLinkParam => { const document = documents.get(documentLinkParam.textDocument.uri); const documentContext: DocumentContext = { resolveReference: (ref, base) => { if (base) { ref = url.resolve(base, ref); } if (workspacePath && ref[0] === '/') { return uri.file(path.join(workspacePath, ref)).toString(); } return url.resolve(document.uri, ref); } }; const links: DocumentLink[] = []; languageModes.getAllModesInDocument(document).forEach(m => { if (m.findDocumentLinks) { pushAll(links, m.findDocumentLinks(document, documentContext)); } }); return links; }); connection.onDocumentSymbol(documentSymbolParms => { const document = documents.get(documentSymbolParms.textDocument.uri); const symbols: SymbolInformation[] = []; languageModes.getAllModesInDocument(document).forEach(m => { if (m.findDocumentSymbols) { pushAll(symbols, m.findDocumentSymbols(document)); } }); return symbols; }); connection.onRequest(DocumentColorRequest.type, params => { const infos: ColorInformation[] = []; const document = documents.get(params.textDocument.uri); if (document) { languageModes.getAllModesInDocument(document).forEach(m => { if (m.findDocumentColors) { pushAll(infos, m.findDocumentColors(document)); } }); } return infos; }); connection.onRequest(ColorPresentationRequest.type, params => { const document = documents.get(params.textDocument.uri); if (document) { const mode = languageModes.getModeAtPosition(document, params.range.start); if (mode && mode.getColorPresentations) { return mode.getColorPresentations(document, params as ColorInformation); } } return []; }); connection.onRequest(TagCloseRequest.type, params => { const document = documents.get(params.textDocument.uri); if (document) { const pos = params.position; if (pos.character > 0) { const mode = languageModes.getModeAtPosition( document, Position.create(pos.line, pos.character - 1) ); if (mode && mode.doAutoClose) { return mode.doAutoClose(document, pos); } } } return null; }); // Listen on the connection connection.listen();
the_stack
import { nelderMead, bisect, conjugateGradient, zeros, zerosM, norm2, scale } from 'fmin'; import { intersectionArea, circleOverlap, circleCircleIntersection, distance } from './circleintersection'; /** given a list of set objects, and their corresponding overlaps. updates the (x, y, radius) attribute on each set such that their positions roughly correspond to the desired overlaps */ export function venn(areas, parameters?: any) { parameters = parameters || {}; parameters.maxIterations = parameters.maxIterations || 500; const initialLayout = parameters.initialLayout || bestInitialLayout; const loss = parameters.lossFunction || lossFunction; // add in missing pairwise areas as having 0 size areas = addMissingAreas(areas); // initial layout is done greedily const circles = initialLayout(areas, parameters); // transform x/y coordinates to a vector to optimize const initial = [], setids = []; let setid; for (setid in circles) { // eslint-disable-next-line if (circles.hasOwnProperty(setid)) { initial.push(circles[setid].x); initial.push(circles[setid].y); setids.push(setid); } } // optimize initial layout from our loss function const solution = nelderMead( function (values) { const current = {}; for (let i = 0; i < setids.length; ++i) { const setid = setids[i]; current[setid] = { x: values[2 * i], y: values[2 * i + 1], radius: circles[setid].radius, // size : circles[setid].size }; } return loss(current, areas); }, initial, parameters ); // transform solution vector back to x/y points const positions = solution.x; for (let i = 0; i < setids.length; ++i) { setid = setids[i]; circles[setid].x = positions[2 * i]; circles[setid].y = positions[2 * i + 1]; } return circles; } const SMALL = 1e-10; /** Returns the distance necessary for two circles of radius r1 + r2 to have the overlap area 'overlap' */ export function distanceFromIntersectArea(r1, r2, overlap) { // handle complete overlapped circles if (Math.min(r1, r2) * Math.min(r1, r2) * Math.PI <= overlap + SMALL) { return Math.abs(r1 - r2); } return bisect( function (distance) { return circleOverlap(r1, r2, distance) - overlap; }, 0, r1 + r2 ); } /** Missing pair-wise intersection area data can cause problems: treating as an unknown means that sets will be laid out overlapping, which isn't what people expect. To reflect that we want disjoint sets here, set the overlap to 0 for all missing pairwise set intersections */ function addMissingAreas(areas) { areas = areas.slice(); // two circle intersections that aren't defined const ids: number[] = [], pairs: any = {}; let i, j, a, b; for (i = 0; i < areas.length; ++i) { const area = areas[i]; if (area.sets.length == 1) { ids.push(area.sets[0]); } else if (area.sets.length == 2) { a = area.sets[0]; b = area.sets[1]; // @ts-ignore pairs[[a, b]] = true; // @ts-ignore pairs[[b, a]] = true; } } ids.sort((a, b) => { return a > b ? 1 : -1; }); for (i = 0; i < ids.length; ++i) { a = ids[i]; for (j = i + 1; j < ids.length; ++j) { b = ids[j]; // @ts-ignore if (!([a, b] in pairs)) { areas.push({ sets: [a, b], size: 0 }); } } } return areas; } /// Returns two matrices, one of the euclidean distances between the sets /// and the other indicating if there are subset or disjoint set relationships export function getDistanceMatrices(areas, sets, setids) { // initialize an empty distance matrix between all the points const distances = zerosM(sets.length, sets.length), constraints = zerosM(sets.length, sets.length); // compute required distances between all the sets such that // the areas match areas .filter(function (x) { return x.sets.length == 2; }) .map(function (current) { const left = setids[current.sets[0]], right = setids[current.sets[1]], r1 = Math.sqrt(sets[left].size / Math.PI), r2 = Math.sqrt(sets[right].size / Math.PI), distance = distanceFromIntersectArea(r1, r2, current.size); distances[left][right] = distances[right][left] = distance; // also update constraints to indicate if its a subset or disjoint // relationship let c = 0; if (current.size + 1e-10 >= Math.min(sets[left].size, sets[right].size)) { c = 1; } else if (current.size <= 1e-10) { c = -1; } constraints[left][right] = constraints[right][left] = c; }); return { distances: distances, constraints: constraints }; } /// computes the gradient and loss simulatenously for our constrained MDS optimizer function constrainedMDSGradient(x, fxprime, distances, constraints) { let loss = 0, i; for (i = 0; i < fxprime.length; ++i) { fxprime[i] = 0; } for (i = 0; i < distances.length; ++i) { const xi = x[2 * i], yi = x[2 * i + 1]; for (let j = i + 1; j < distances.length; ++j) { const xj = x[2 * j], yj = x[2 * j + 1], dij = distances[i][j], constraint = constraints[i][j]; const squaredDistance = (xj - xi) * (xj - xi) + (yj - yi) * (yj - yi), distance = Math.sqrt(squaredDistance), delta = squaredDistance - dij * dij; if ((constraint > 0 && distance <= dij) || (constraint < 0 && distance >= dij)) { continue; } loss += 2 * delta * delta; fxprime[2 * i] += 4 * delta * (xi - xj); fxprime[2 * i + 1] += 4 * delta * (yi - yj); fxprime[2 * j] += 4 * delta * (xj - xi); fxprime[2 * j + 1] += 4 * delta * (yj - yi); } } return loss; } /// takes the best working variant of either constrained MDS or greedy export function bestInitialLayout(areas, params) { let initial = greedyLayout(areas, params); const loss = params.lossFunction || lossFunction; // greedylayout is sufficient for all 2/3 circle cases. try out // constrained MDS for higher order problems, take its output // if it outperforms. (greedy is aesthetically better on 2/3 circles // since it axis aligns) if (areas.length >= 8) { const constrained = constrainedMDSLayout(areas, params), constrainedLoss = loss(constrained, areas), greedyLoss = loss(initial, areas); if (constrainedLoss + 1e-8 < greedyLoss) { initial = constrained; } } return initial; } /// use the constrained MDS variant to generate an initial layout export function constrainedMDSLayout(areas, params) { params = params || {}; const restarts = params.restarts || 10; // bidirectionally map sets to a rowid (so we can create a matrix) const sets = [], setids = {}; let i; for (i = 0; i < areas.length; ++i) { const area = areas[i]; if (area.sets.length == 1) { setids[area.sets[0]] = sets.length; sets.push(area); } } const matrices = getDistanceMatrices(areas, sets, setids); let distances = matrices.distances; const constraints = matrices.constraints; // keep distances bounded, things get messed up otherwise. // TODO: proper preconditioner? const norm = norm2(distances.map(norm2)) / distances.length; distances = distances.map(function (row) { return row.map(function (value) { return value / norm; }); }); const obj = function (x, fxprime) { return constrainedMDSGradient(x, fxprime, distances, constraints); }; let best, current; for (i = 0; i < restarts; ++i) { const initial = zeros(distances.length * 2).map(Math.random); current = conjugateGradient(obj, initial, params); if (!best || current.fx < best.fx) { best = current; } } const positions = best.x; // translate rows back to (x,y,radius) coordinates const circles = {}; for (i = 0; i < sets.length; ++i) { const set = sets[i]; circles[set.sets[0]] = { x: positions[2 * i] * norm, y: positions[2 * i + 1] * norm, radius: Math.sqrt(set.size / Math.PI), }; } if (params.history) { for (i = 0; i < params.history.length; ++i) { scale(params.history[i].x, norm); } } return circles; } /** Lays out a Venn diagram greedily, going from most overlapped sets to least overlapped, attempting to position each new set such that the overlapping areas to already positioned sets are basically right */ export function greedyLayout(areas, params) { const loss = params && params.lossFunction ? params.lossFunction : lossFunction; // define a circle for each set const circles = {}, setOverlaps = {}; let set; for (let i = 0; i < areas.length; ++i) { const area = areas[i]; if (area.sets.length == 1) { set = area.sets[0]; circles[set] = { x: 1e10, y: 1e10, // rowid: circles.length, // fix to -> rowid: Object.keys(circles).length, size: area.size, radius: Math.sqrt(area.size / Math.PI), }; setOverlaps[set] = []; } } areas = areas.filter(function (a) { return a.sets.length == 2; }); // map each set to a list of all the other sets that overlap it for (let i = 0; i < areas.length; ++i) { const current = areas[i]; // eslint-disable-next-line let weight = current.hasOwnProperty('weight') ? current.weight : 1.0; const left = current.sets[0], right = current.sets[1]; // completely overlapped circles shouldn't be positioned early here if (current.size + SMALL >= Math.min(circles[left].size, circles[right].size)) { weight = 0; } setOverlaps[left].push({ set: right, size: current.size, weight: weight }); setOverlaps[right].push({ set: left, size: current.size, weight: weight }); } // get list of most overlapped sets const mostOverlapped = []; for (set in setOverlaps) { // eslint-disable-next-line if (setOverlaps.hasOwnProperty(set)) { let size = 0; for (let i = 0; i < setOverlaps[set].length; ++i) { size += setOverlaps[set][i].size * setOverlaps[set][i].weight; } mostOverlapped.push({ set: set, size: size }); } } // sort by size desc function sortOrder(a, b) { return b.size - a.size; } mostOverlapped.sort(sortOrder); // keep track of what sets have been laid out const positioned = {}; function isPositioned(element) { return element.set in positioned; } // adds a point to the output function positionSet(point, index) { circles[index].x = point.x; circles[index].y = point.y; positioned[index] = true; } // add most overlapped set at (0,0) positionSet({ x: 0, y: 0 }, mostOverlapped[0].set); // get distances between all points. TODO, necessary? // answer: probably not // var distances = venn.getDistanceMatrices(circles, areas).distances; for (let i = 1; i < mostOverlapped.length; ++i) { const setIndex = mostOverlapped[i].set, overlap = setOverlaps[setIndex].filter(isPositioned); set = circles[setIndex]; overlap.sort(sortOrder); if (overlap.length === 0) { // this shouldn't happen anymore with addMissingAreas throw 'ERROR: missing pairwise overlap information'; } const points = []; for (let j = 0; j < overlap.length; ++j) { // get appropriate distance from most overlapped already added set const p1 = circles[overlap[j].set], d1 = distanceFromIntersectArea(set.radius, p1.radius, overlap[j].size); // sample positions at 90 degrees for maximum aesthetics points.push({ x: p1.x + d1, y: p1.y }); points.push({ x: p1.x - d1, y: p1.y }); points.push({ y: p1.y + d1, x: p1.x }); points.push({ y: p1.y - d1, x: p1.x }); // if we have at least 2 overlaps, then figure out where the // set should be positioned analytically and try those too for (let k = j + 1; k < overlap.length; ++k) { const p2 = circles[overlap[k].set], d2 = distanceFromIntersectArea(set.radius, p2.radius, overlap[k].size); const extraPoints = circleCircleIntersection( { x: p1.x, y: p1.y, radius: d1 }, { x: p2.x, y: p2.y, radius: d2 } ); for (let l = 0; l < extraPoints.length; ++l) { points.push(extraPoints[l]); } } } // we have some candidate positions for the set, examine loss // at each position to figure out where to put it at let bestLoss = 1e50, bestPoint = points[0]; for (let j = 0; j < points.length; ++j) { circles[setIndex].x = points[j].x; circles[setIndex].y = points[j].y; const localLoss = loss(circles, areas); if (localLoss < bestLoss) { bestLoss = localLoss; bestPoint = points[j]; } } positionSet(bestPoint, setIndex); } return circles; } /** Given a bunch of sets, and the desired overlaps between these sets - computes the distance from the actual overlaps to the desired overlaps. Note that this method ignores overlaps of more than 2 circles */ export function lossFunction(sets, overlaps) { let output = 0; function getCircles(indices) { return indices.map(function (i) { return sets[i]; }); } for (let i = 0; i < overlaps.length; ++i) { const area = overlaps[i]; let overlap; if (area.sets.length == 1) { continue; } else if (area.sets.length == 2) { const left = sets[area.sets[0]], right = sets[area.sets[1]]; overlap = circleOverlap(left.radius, right.radius, distance(left, right)); } else { overlap = intersectionArea(getCircles(area.sets)); } // eslint-disable-next-line const weight = area.hasOwnProperty('weight') ? area.weight : 1.0; output += weight * (overlap - area.size) * (overlap - area.size); } return output; } // orientates a bunch of circles to point in orientation function orientateCircles(circles, orientation, orientationOrder) { if (orientationOrder === null) { circles.sort(function (a, b) { return b.radius - a.radius; }); } else { circles.sort(orientationOrder); } let i; // shift circles so largest circle is at (0, 0) if (circles.length > 0) { const largestX = circles[0].x, largestY = circles[0].y; for (i = 0; i < circles.length; ++i) { circles[i].x -= largestX; circles[i].y -= largestY; } } if (circles.length == 2) { // if the second circle is a subset of the first, arrange so that // it is off to one side. hack for https://github.com/benfred/venn.js/issues/120 const dist = distance(circles[0], circles[1]); if (dist < Math.abs(circles[1].radius - circles[0].radius)) { circles[1].x = circles[0].x + circles[0].radius - circles[1].radius - 1e-10; circles[1].y = circles[0].y; } } // rotate circles so that second largest is at an angle of 'orientation' // from largest if (circles.length > 1) { const rotation = Math.atan2(circles[1].x, circles[1].y) - orientation; let x, y; const c = Math.cos(rotation), s = Math.sin(rotation); for (i = 0; i < circles.length; ++i) { x = circles[i].x; y = circles[i].y; circles[i].x = c * x - s * y; circles[i].y = s * x + c * y; } } // mirror solution if third solution is above plane specified by // first two circles if (circles.length > 2) { let angle = Math.atan2(circles[2].x, circles[2].y) - orientation; while (angle < 0) { angle += 2 * Math.PI; } while (angle > 2 * Math.PI) { angle -= 2 * Math.PI; } if (angle > Math.PI) { const slope = circles[1].y / (1e-10 + circles[1].x); for (i = 0; i < circles.length; ++i) { const d = (circles[i].x + slope * circles[i].y) / (1 + slope * slope); circles[i].x = 2 * d - circles[i].x; circles[i].y = 2 * d * slope - circles[i].y; } } } } export function disjointCluster(circles) { // union-find clustering to get disjoint sets circles.map(function (circle) { circle.parent = circle; }); // path compression step in union find function find(circle) { if (circle.parent !== circle) { circle.parent = find(circle.parent); } return circle.parent; } function union(x, y) { const xRoot = find(x), yRoot = find(y); xRoot.parent = yRoot; } // get the union of all overlapping sets for (let i = 0; i < circles.length; ++i) { for (let j = i + 1; j < circles.length; ++j) { const maxDistance = circles[i].radius + circles[j].radius; if (distance(circles[i], circles[j]) + 1e-10 < maxDistance) { union(circles[j], circles[i]); } } } // find all the disjoint clusters and group them together const disjointClusters = {}; let setid; for (let i = 0; i < circles.length; ++i) { setid = find(circles[i]).parent.setid; if (!(setid in disjointClusters)) { disjointClusters[setid] = []; } disjointClusters[setid].push(circles[i]); } // cleanup bookkeeping circles.map(function (circle) { delete circle.parent; }); // return in more usable form const ret = []; for (setid in disjointClusters) { // eslint-disable-next-line if (disjointClusters.hasOwnProperty(setid)) { ret.push(disjointClusters[setid]); } } return ret; } function getBoundingBox(circles) { const minMax = function (d) { const hi = Math.max.apply( null, circles.map(function (c) { return c[d] + c.radius; }) ), lo = Math.min.apply( null, circles.map(function (c) { return c[d] - c.radius; }) ); return { max: hi, min: lo }; }; return { xRange: minMax('x'), yRange: minMax('y') }; } export function normalizeSolution(solution, orientation, orientationOrder) { if (orientation === null) { orientation = Math.PI / 2; } // work with a list instead of a dictionary, and take a copy so we // don't mutate input let circles = [], i, setid; for (setid in solution) { // eslint-disable-next-line if (solution.hasOwnProperty(setid)) { const previous = solution[setid]; circles.push({ x: previous.x, y: previous.y, radius: previous.radius, setid: setid }); } } // get all the disjoint clusters const clusters = disjointCluster(circles); // orientate all disjoint sets, get sizes for (i = 0; i < clusters.length; ++i) { orientateCircles(clusters[i], orientation, orientationOrder); const bounds = getBoundingBox(clusters[i]); clusters[i].size = (bounds.xRange.max - bounds.xRange.min) * (bounds.yRange.max - bounds.yRange.min); clusters[i].bounds = bounds; } clusters.sort(function (a, b) { return b.size - a.size; }); // orientate the largest at 0,0, and get the bounds circles = clusters[0]; // @ts-ignore fixme 从逻辑上看似乎是不对的,后续看看 let returnBounds = circles.bounds; const spacing = (returnBounds.xRange.max - returnBounds.xRange.min) / 50; function addCluster(cluster, right, bottom) { if (!cluster) return; const bounds = cluster.bounds; let xOffset, yOffset, centreing; if (right) { xOffset = returnBounds.xRange.max - bounds.xRange.min + spacing; } else { xOffset = returnBounds.xRange.max - bounds.xRange.max; centreing = (bounds.xRange.max - bounds.xRange.min) / 2 - (returnBounds.xRange.max - returnBounds.xRange.min) / 2; if (centreing < 0) xOffset += centreing; } if (bottom) { yOffset = returnBounds.yRange.max - bounds.yRange.min + spacing; } else { yOffset = returnBounds.yRange.max - bounds.yRange.max; centreing = (bounds.yRange.max - bounds.yRange.min) / 2 - (returnBounds.yRange.max - returnBounds.yRange.min) / 2; if (centreing < 0) yOffset += centreing; } for (let j = 0; j < cluster.length; ++j) { cluster[j].x += xOffset; cluster[j].y += yOffset; circles.push(cluster[j]); } } let index = 1; while (index < clusters.length) { addCluster(clusters[index], true, false); addCluster(clusters[index + 1], false, true); addCluster(clusters[index + 2], true, true); index += 3; // have one cluster (in top left). lay out next three relative // to it in a grid returnBounds = getBoundingBox(circles); } // convert back to solution form const ret = {}; for (i = 0; i < circles.length; ++i) { ret[circles[i].setid] = circles[i]; } return ret; } /** Scales a solution from venn.venn or venn.greedyLayout such that it fits in a rectangle of width/height - with padding around the borders. also centers the diagram in the available space at the same time */ export function scaleSolution(solution, width, height, padding) { const circles = [], setids = []; for (const setid in solution) { // eslint-disable-next-line if (solution.hasOwnProperty(setid)) { setids.push(setid); circles.push(solution[setid]); } } width -= 2 * padding; height -= 2 * padding; const bounds = getBoundingBox(circles), xRange = bounds.xRange, yRange = bounds.yRange; if (xRange.max == xRange.min || yRange.max == yRange.min) { console.log('not scaling solution: zero size detected'); return solution; } const xScaling = width / (xRange.max - xRange.min), yScaling = height / (yRange.max - yRange.min), scaling = Math.min(yScaling, xScaling), // while we're at it, center the diagram too xOffset = (width - (xRange.max - xRange.min) * scaling) / 2, yOffset = (height - (yRange.max - yRange.min) * scaling) / 2; const scaled = {}; for (let i = 0; i < circles.length; ++i) { const circle = circles[i]; scaled[setids[i]] = { radius: scaling * circle.radius, x: padding + xOffset + (circle.x - xRange.min) * scaling, y: padding + yOffset + (circle.y - yRange.min) * scaling, }; } return scaled; }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; /** * Manages a Kinesis Analytics v2 Application. * This resource can be used to manage both Kinesis Data Analytics for SQL applications and Kinesis Data Analytics for Apache Flink applications. * * > **Note:** Kinesis Data Analytics for SQL applications created using this resource cannot currently be viewed in the AWS Console. To manage Kinesis Data Analytics for SQL applications that can also be viewed in the AWS Console, use the `aws.kinesis.AnalyticsApplication`resource. * * ## Example Usage * ### Apache Flink Application * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const exampleBucket = new aws.s3.Bucket("exampleBucket", {}); * const exampleBucketObject = new aws.s3.BucketObject("exampleBucketObject", { * bucket: exampleBucket.bucket, * key: "example-flink-application", * source: new pulumi.asset.FileAsset("flink-app.jar"), * }); * const exampleApplication = new aws.kinesisanalyticsv2.Application("exampleApplication", { * runtimeEnvironment: "FLINK-1_8", * serviceExecutionRole: aws_iam_role.example.arn, * applicationConfiguration: { * applicationCodeConfiguration: { * codeContent: { * s3ContentLocation: { * bucketArn: exampleBucket.arn, * fileKey: exampleBucketObject.key, * }, * }, * codeContentType: "ZIPFILE", * }, * environmentProperties: { * propertyGroups: [ * { * propertyGroupId: "PROPERTY-GROUP-1", * propertyMap: { * Key1: "Value1", * }, * }, * { * propertyGroupId: "PROPERTY-GROUP-2", * propertyMap: { * KeyA: "ValueA", * KeyB: "ValueB", * }, * }, * ], * }, * flinkApplicationConfiguration: { * checkpointConfiguration: { * configurationType: "DEFAULT", * }, * monitoringConfiguration: { * configurationType: "CUSTOM", * logLevel: "DEBUG", * metricsLevel: "TASK", * }, * parallelismConfiguration: { * autoScalingEnabled: true, * configurationType: "CUSTOM", * parallelism: 10, * parallelismPerKpu: 4, * }, * }, * }, * tags: { * Environment: "test", * }, * }); * ``` * ### SQL Application * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const exampleLogGroup = new aws.cloudwatch.LogGroup("exampleLogGroup", {}); * const exampleLogStream = new aws.cloudwatch.LogStream("exampleLogStream", {logGroupName: exampleLogGroup.name}); * const exampleApplication = new aws.kinesisanalyticsv2.Application("exampleApplication", { * runtimeEnvironment: "SQL-1.0", * serviceExecutionRole: aws_iam_role.example.arn, * applicationConfiguration: { * applicationCodeConfiguration: { * codeContent: { * textContent: "SELECT 1;\n", * }, * codeContentType: "PLAINTEXT", * }, * sqlApplicationConfiguration: { * input: { * namePrefix: "PREFIX_1", * inputParallelism: { * count: 3, * }, * inputSchema: { * recordColumns: [ * { * name: "COLUMN_1", * sqlType: "VARCHAR(8)", * mapping: "MAPPING-1", * }, * { * name: "COLUMN_2", * sqlType: "DOUBLE", * }, * ], * recordEncoding: "UTF-8", * recordFormat: { * recordFormatType: "CSV", * mappingParameters: { * csvMappingParameters: { * recordColumnDelimiter: ",", * recordRowDelimiter: "\n", * }, * }, * }, * }, * kinesisStreamsInput: { * resourceArn: aws_kinesis_stream.example.arn, * }, * }, * outputs: [ * { * name: "OUTPUT_1", * destinationSchema: { * recordFormatType: "JSON", * }, * lambdaOutput: { * resourceArn: aws_lambda_function.example.arn, * }, * }, * { * name: "OUTPUT_2", * destinationSchema: { * recordFormatType: "CSV", * }, * kinesisFirehoseOutput: { * resourceArn: aws_kinesis_firehose_delivery_stream.example.arn, * }, * }, * ], * referenceDataSource: { * tableName: "TABLE-1", * referenceSchema: { * recordColumns: [{ * name: "COLUMN_1", * sqlType: "INTEGER", * }], * recordFormat: { * recordFormatType: "JSON", * mappingParameters: { * jsonMappingParameters: { * recordRowPath: "$", * }, * }, * }, * }, * s3ReferenceDataSource: { * bucketArn: aws_s3_bucket.example.arn, * fileKey: "KEY-1", * }, * }, * }, * }, * cloudwatchLoggingOptions: { * logStreamArn: exampleLogStream.arn, * }, * }); * ``` * ### VPC Configuration * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const exampleBucket = new aws.s3.Bucket("exampleBucket", {}); * const exampleBucketObject = new aws.s3.BucketObject("exampleBucketObject", { * bucket: exampleBucket.bucket, * key: "example-flink-application", * source: new pulumi.asset.FileAsset("flink-app.jar"), * }); * const exampleApplication = new aws.kinesisanalyticsv2.Application("exampleApplication", { * runtimeEnvironment: "FLINK-1_8", * serviceExecutionRole: aws_iam_role.example.arn, * applicationConfiguration: { * applicationCodeConfiguration: { * codeContent: { * s3ContentLocation: { * bucketArn: exampleBucket.arn, * fileKey: exampleBucketObject.key, * }, * }, * codeContentType: "ZIPFILE", * }, * vpcConfiguration: { * securityGroupIds: [ * aws_security_group.example[0].id, * aws_security_group.example[1].id, * ], * subnetIds: [aws_subnet.example.id], * }, * }, * }); * ``` * * ## Import * * `aws_kinesisanalyticsv2_application` can be imported by using the application ARN, e.g. * * ```sh * $ pulumi import aws:kinesisanalyticsv2/application:Application example arn:aws:kinesisanalytics:us-west-2:123456789012:application/example-sql-application * ``` */ export class Application extends pulumi.CustomResource { /** * Get an existing Application resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ApplicationState, opts?: pulumi.CustomResourceOptions): Application { return new Application(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:kinesisanalyticsv2/application:Application'; /** * Returns true if the given object is an instance of Application. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Application { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Application.__pulumiType; } /** * The application's configuration */ public readonly applicationConfiguration!: pulumi.Output<outputs.kinesisanalyticsv2.ApplicationApplicationConfiguration>; /** * The ARN of the application. */ public /*out*/ readonly arn!: pulumi.Output<string>; /** * A CloudWatch log stream to monitor application configuration errors. */ public readonly cloudwatchLoggingOptions!: pulumi.Output<outputs.kinesisanalyticsv2.ApplicationCloudwatchLoggingOptions | undefined>; /** * The current timestamp when the application was created. */ public /*out*/ readonly createTimestamp!: pulumi.Output<string>; /** * A summary description of the application. */ public readonly description!: pulumi.Output<string | undefined>; /** * Whether to force stop an unresponsive Flink-based application. */ public readonly forceStop!: pulumi.Output<boolean | undefined>; /** * The current timestamp when the application was last updated. */ public /*out*/ readonly lastUpdateTimestamp!: pulumi.Output<string>; /** * The name of the application. */ public readonly name!: pulumi.Output<string>; /** * The runtime environment for the application. Valid values: `SQL-1_0`, `FLINK-1_6`, `FLINK-1_8`, `FLINK-1_11`. */ public readonly runtimeEnvironment!: pulumi.Output<string>; /** * The ARN of the IAM role used by the application to access Kinesis data streams, Kinesis Data Firehose delivery streams, Amazon S3 objects, and other external resources. */ public readonly serviceExecutionRole!: pulumi.Output<string>; /** * Whether to start or stop the application. */ public readonly startApplication!: pulumi.Output<boolean | undefined>; /** * The status of the application. */ public /*out*/ readonly status!: pulumi.Output<string>; public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * The current application version. Kinesis Data Analytics updates the `versionId` each time the application is updated. */ public /*out*/ readonly versionId!: pulumi.Output<number>; /** * Create a Application resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: ApplicationArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ApplicationArgs | ApplicationState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ApplicationState | undefined; inputs["applicationConfiguration"] = state ? state.applicationConfiguration : undefined; inputs["arn"] = state ? state.arn : undefined; inputs["cloudwatchLoggingOptions"] = state ? state.cloudwatchLoggingOptions : undefined; inputs["createTimestamp"] = state ? state.createTimestamp : undefined; inputs["description"] = state ? state.description : undefined; inputs["forceStop"] = state ? state.forceStop : undefined; inputs["lastUpdateTimestamp"] = state ? state.lastUpdateTimestamp : undefined; inputs["name"] = state ? state.name : undefined; inputs["runtimeEnvironment"] = state ? state.runtimeEnvironment : undefined; inputs["serviceExecutionRole"] = state ? state.serviceExecutionRole : undefined; inputs["startApplication"] = state ? state.startApplication : undefined; inputs["status"] = state ? state.status : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; inputs["versionId"] = state ? state.versionId : undefined; } else { const args = argsOrState as ApplicationArgs | undefined; if ((!args || args.runtimeEnvironment === undefined) && !opts.urn) { throw new Error("Missing required property 'runtimeEnvironment'"); } if ((!args || args.serviceExecutionRole === undefined) && !opts.urn) { throw new Error("Missing required property 'serviceExecutionRole'"); } inputs["applicationConfiguration"] = args ? args.applicationConfiguration : undefined; inputs["cloudwatchLoggingOptions"] = args ? args.cloudwatchLoggingOptions : undefined; inputs["description"] = args ? args.description : undefined; inputs["forceStop"] = args ? args.forceStop : undefined; inputs["name"] = args ? args.name : undefined; inputs["runtimeEnvironment"] = args ? args.runtimeEnvironment : undefined; inputs["serviceExecutionRole"] = args ? args.serviceExecutionRole : undefined; inputs["startApplication"] = args ? args.startApplication : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["arn"] = undefined /*out*/; inputs["createTimestamp"] = undefined /*out*/; inputs["lastUpdateTimestamp"] = undefined /*out*/; inputs["status"] = undefined /*out*/; inputs["tagsAll"] = undefined /*out*/; inputs["versionId"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Application.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Application resources. */ export interface ApplicationState { /** * The application's configuration */ applicationConfiguration?: pulumi.Input<inputs.kinesisanalyticsv2.ApplicationApplicationConfiguration>; /** * The ARN of the application. */ arn?: pulumi.Input<string>; /** * A CloudWatch log stream to monitor application configuration errors. */ cloudwatchLoggingOptions?: pulumi.Input<inputs.kinesisanalyticsv2.ApplicationCloudwatchLoggingOptions>; /** * The current timestamp when the application was created. */ createTimestamp?: pulumi.Input<string>; /** * A summary description of the application. */ description?: pulumi.Input<string>; /** * Whether to force stop an unresponsive Flink-based application. */ forceStop?: pulumi.Input<boolean>; /** * The current timestamp when the application was last updated. */ lastUpdateTimestamp?: pulumi.Input<string>; /** * The name of the application. */ name?: pulumi.Input<string>; /** * The runtime environment for the application. Valid values: `SQL-1_0`, `FLINK-1_6`, `FLINK-1_8`, `FLINK-1_11`. */ runtimeEnvironment?: pulumi.Input<string>; /** * The ARN of the IAM role used by the application to access Kinesis data streams, Kinesis Data Firehose delivery streams, Amazon S3 objects, and other external resources. */ serviceExecutionRole?: pulumi.Input<string>; /** * Whether to start or stop the application. */ startApplication?: pulumi.Input<boolean>; /** * The status of the application. */ status?: pulumi.Input<string>; tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The current application version. Kinesis Data Analytics updates the `versionId` each time the application is updated. */ versionId?: pulumi.Input<number>; } /** * The set of arguments for constructing a Application resource. */ export interface ApplicationArgs { /** * The application's configuration */ applicationConfiguration?: pulumi.Input<inputs.kinesisanalyticsv2.ApplicationApplicationConfiguration>; /** * A CloudWatch log stream to monitor application configuration errors. */ cloudwatchLoggingOptions?: pulumi.Input<inputs.kinesisanalyticsv2.ApplicationCloudwatchLoggingOptions>; /** * A summary description of the application. */ description?: pulumi.Input<string>; /** * Whether to force stop an unresponsive Flink-based application. */ forceStop?: pulumi.Input<boolean>; /** * The name of the application. */ name?: pulumi.Input<string>; /** * The runtime environment for the application. Valid values: `SQL-1_0`, `FLINK-1_6`, `FLINK-1_8`, `FLINK-1_11`. */ runtimeEnvironment: pulumi.Input<string>; /** * The ARN of the IAM role used by the application to access Kinesis data streams, Kinesis Data Firehose delivery streams, Amazon S3 objects, and other external resources. */ serviceExecutionRole: pulumi.Input<string>; /** * Whether to start or stop the application. */ startApplication?: pulumi.Input<boolean>; tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; export class Permissions extends pulumi.CustomResource { /** * Get an existing Permissions resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: PermissionsState, opts?: pulumi.CustomResourceOptions): Permissions { return new Permissions(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:lakeformation/permissions:Permissions'; /** * Returns true if the given object is an instance of Permissions. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Permissions { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Permissions.__pulumiType; } /** * Identifier for the Data Catalog. By default, it is the account ID of the caller. */ public readonly catalogId!: pulumi.Output<string | undefined>; /** * Whether the permissions are to be granted for the Data Catalog. Defaults to `false`. */ public readonly catalogResource!: pulumi.Output<boolean | undefined>; /** * Configuration block for a data location resource. Detailed below. */ public readonly dataLocation!: pulumi.Output<outputs.lakeformation.PermissionsDataLocation>; /** * Configuration block for a database resource. Detailed below. */ public readonly database!: pulumi.Output<outputs.lakeformation.PermissionsDatabase>; /** * List of permissions granted to the principal. Valid values may include `ALL`, `ALTER`, `CREATE_DATABASE`, `CREATE_TABLE`, `DATA_LOCATION_ACCESS`, `DELETE`, `DESCRIBE`, `DROP`, `INSERT`, and `SELECT`. For details on each permission, see [Lake Formation Permissions Reference](https://docs.aws.amazon.com/lake-formation/latest/dg/lf-permissions-reference.html). */ public readonly permissions!: pulumi.Output<string[]>; /** * Subset of `permissions` which the principal can pass. */ public readonly permissionsWithGrantOptions!: pulumi.Output<string[]>; /** * Principal to be granted the permissions on the resource. Supported principals include `IAM_ALLOWED_PRINCIPALS` (see Default Behavior and `IAMAllowedPrincipals` above), IAM roles, users, groups, SAML groups and users, QuickSight groups, OUs, and organizations as well as AWS account IDs for cross-account permissions. For more information, see [Lake Formation Permissions Reference](https://docs.aws.amazon.com/lake-formation/latest/dg/lf-permissions-reference.html). */ public readonly principal!: pulumi.Output<string>; /** * Configuration block for a table resource. Detailed below. */ public readonly table!: pulumi.Output<outputs.lakeformation.PermissionsTable>; /** * Configuration block for a table with columns resource. Detailed below. */ public readonly tableWithColumns!: pulumi.Output<outputs.lakeformation.PermissionsTableWithColumns>; /** * Create a Permissions resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: PermissionsArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: PermissionsArgs | PermissionsState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as PermissionsState | undefined; inputs["catalogId"] = state ? state.catalogId : undefined; inputs["catalogResource"] = state ? state.catalogResource : undefined; inputs["dataLocation"] = state ? state.dataLocation : undefined; inputs["database"] = state ? state.database : undefined; inputs["permissions"] = state ? state.permissions : undefined; inputs["permissionsWithGrantOptions"] = state ? state.permissionsWithGrantOptions : undefined; inputs["principal"] = state ? state.principal : undefined; inputs["table"] = state ? state.table : undefined; inputs["tableWithColumns"] = state ? state.tableWithColumns : undefined; } else { const args = argsOrState as PermissionsArgs | undefined; if ((!args || args.permissions === undefined) && !opts.urn) { throw new Error("Missing required property 'permissions'"); } if ((!args || args.principal === undefined) && !opts.urn) { throw new Error("Missing required property 'principal'"); } inputs["catalogId"] = args ? args.catalogId : undefined; inputs["catalogResource"] = args ? args.catalogResource : undefined; inputs["dataLocation"] = args ? args.dataLocation : undefined; inputs["database"] = args ? args.database : undefined; inputs["permissions"] = args ? args.permissions : undefined; inputs["permissionsWithGrantOptions"] = args ? args.permissionsWithGrantOptions : undefined; inputs["principal"] = args ? args.principal : undefined; inputs["table"] = args ? args.table : undefined; inputs["tableWithColumns"] = args ? args.tableWithColumns : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Permissions.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Permissions resources. */ export interface PermissionsState { /** * Identifier for the Data Catalog. By default, it is the account ID of the caller. */ catalogId?: pulumi.Input<string>; /** * Whether the permissions are to be granted for the Data Catalog. Defaults to `false`. */ catalogResource?: pulumi.Input<boolean>; /** * Configuration block for a data location resource. Detailed below. */ dataLocation?: pulumi.Input<inputs.lakeformation.PermissionsDataLocation>; /** * Configuration block for a database resource. Detailed below. */ database?: pulumi.Input<inputs.lakeformation.PermissionsDatabase>; /** * List of permissions granted to the principal. Valid values may include `ALL`, `ALTER`, `CREATE_DATABASE`, `CREATE_TABLE`, `DATA_LOCATION_ACCESS`, `DELETE`, `DESCRIBE`, `DROP`, `INSERT`, and `SELECT`. For details on each permission, see [Lake Formation Permissions Reference](https://docs.aws.amazon.com/lake-formation/latest/dg/lf-permissions-reference.html). */ permissions?: pulumi.Input<pulumi.Input<string>[]>; /** * Subset of `permissions` which the principal can pass. */ permissionsWithGrantOptions?: pulumi.Input<pulumi.Input<string>[]>; /** * Principal to be granted the permissions on the resource. Supported principals include `IAM_ALLOWED_PRINCIPALS` (see Default Behavior and `IAMAllowedPrincipals` above), IAM roles, users, groups, SAML groups and users, QuickSight groups, OUs, and organizations as well as AWS account IDs for cross-account permissions. For more information, see [Lake Formation Permissions Reference](https://docs.aws.amazon.com/lake-formation/latest/dg/lf-permissions-reference.html). */ principal?: pulumi.Input<string>; /** * Configuration block for a table resource. Detailed below. */ table?: pulumi.Input<inputs.lakeformation.PermissionsTable>; /** * Configuration block for a table with columns resource. Detailed below. */ tableWithColumns?: pulumi.Input<inputs.lakeformation.PermissionsTableWithColumns>; } /** * The set of arguments for constructing a Permissions resource. */ export interface PermissionsArgs { /** * Identifier for the Data Catalog. By default, it is the account ID of the caller. */ catalogId?: pulumi.Input<string>; /** * Whether the permissions are to be granted for the Data Catalog. Defaults to `false`. */ catalogResource?: pulumi.Input<boolean>; /** * Configuration block for a data location resource. Detailed below. */ dataLocation?: pulumi.Input<inputs.lakeformation.PermissionsDataLocation>; /** * Configuration block for a database resource. Detailed below. */ database?: pulumi.Input<inputs.lakeformation.PermissionsDatabase>; /** * List of permissions granted to the principal. Valid values may include `ALL`, `ALTER`, `CREATE_DATABASE`, `CREATE_TABLE`, `DATA_LOCATION_ACCESS`, `DELETE`, `DESCRIBE`, `DROP`, `INSERT`, and `SELECT`. For details on each permission, see [Lake Formation Permissions Reference](https://docs.aws.amazon.com/lake-formation/latest/dg/lf-permissions-reference.html). */ permissions: pulumi.Input<pulumi.Input<string>[]>; /** * Subset of `permissions` which the principal can pass. */ permissionsWithGrantOptions?: pulumi.Input<pulumi.Input<string>[]>; /** * Principal to be granted the permissions on the resource. Supported principals include `IAM_ALLOWED_PRINCIPALS` (see Default Behavior and `IAMAllowedPrincipals` above), IAM roles, users, groups, SAML groups and users, QuickSight groups, OUs, and organizations as well as AWS account IDs for cross-account permissions. For more information, see [Lake Formation Permissions Reference](https://docs.aws.amazon.com/lake-formation/latest/dg/lf-permissions-reference.html). */ principal: pulumi.Input<string>; /** * Configuration block for a table resource. Detailed below. */ table?: pulumi.Input<inputs.lakeformation.PermissionsTable>; /** * Configuration block for a table with columns resource. Detailed below. */ tableWithColumns?: pulumi.Input<inputs.lakeformation.PermissionsTableWithColumns>; }
the_stack
import { Component, Input, OnChanges } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import dayjs from 'dayjs/esm'; import { CourseManagementService } from '../course-management.service'; import { Color, ScaleType } from '@swimlane/ngx-charts'; import { roundScorePercentSpecifiedByCourseSettings } from 'app/shared/util/utils'; import { Course } from 'app/entities/course.model'; import { faArrowLeft, faArrowRight, faSpinner } from '@fortawesome/free-solid-svg-icons'; import * as shape from 'd3-shape'; import { GraphColors } from 'app/entities/statistics.model'; import { ActiveStudentsChart } from 'app/shared/chart/active-students-chart'; import { mean } from 'simple-statistics'; @Component({ selector: 'jhi-course-detail-line-chart', templateUrl: './course-detail-line-chart.component.html', styleUrls: ['./course-detail-line-chart.component.scss'], }) export class CourseDetailLineChartComponent extends ActiveStudentsChart implements OnChanges { @Input() course: Course; @Input() numberOfStudentsInCourse: number; @Input() initialStats: number[] | undefined; loading = true; LEFT = false; RIGHT = true; readonly displayedNumberOfWeeks = 17; showsCurrentWeek = true; // Chart related chartTime: any; amountOfStudents: string; showLifetimeOverview = false; overviewStats: number[]; // Left arrow -> decrease, right arrow -> increase private currentPeriod = 0; // NGX variables chartColor: Color = { name: 'vivid', selectable: true, group: ScaleType.Ordinal, domain: [GraphColors.DARK_BLUE], }; legend = false; xAxis = true; yAxis = true; showYAxisLabel = false; showXAxisLabel = true; xAxisLabel: string; yAxisLabel = ''; timeline = false; data: any[]; // Data changes will be stored in the copy first, to trigger change detection when ready dataCopy = [ { name: '', series: [{}], }, ]; // Used for storing absolute values to display in tooltip absoluteSeries = [{}]; curve: any = shape.curveMonotoneX; average = { name: 'Average', value: 0 }; showAverage = true; startDateDisplayed = false; // Icons faSpinner = faSpinner; faArrowLeft = faArrowLeft; faArrowRight = faArrowRight; constructor(private service: CourseManagementService, private translateService: TranslateService) { super(); this.translateService.onLangChange.subscribe(() => { this.updateXAxisLabel(); }); } ngOnChanges() { this.amountOfStudents = this.translateService.instant('artemisApp.courseStatistics.amountOfStudents'); this.updateXAxisLabel(); this.determineDisplayedPeriod(this.course, this.displayedNumberOfWeeks); /* if the course has a start date and already ended (i.e. the time difference between today and the course end date is at least one week), we show the lifetime overview by default. */ if (this.course.startDate && !!this.currentOffsetToEndDate) { this.showLifetimeOverview = true; this.displayLifetimeOverview(); } else { this.displayDefaultChartScope(); } } /** * Reload the chart with the new data after an arrow is clicked */ private reloadChart() { this.loading = true; this.createLabels(); this.service.getStatisticsData(this.course.id!, this.currentPeriod).subscribe((res: number[]) => { this.processDataAndCreateChart(res); this.data = [...this.dataCopy]; }); } /** * Takes the data, converts it into percentage and sets it accordingly */ private processDataAndCreateChart(array: number[]) { if (this.numberOfStudentsInCourse > 0) { const allValues = []; for (let i = 0; i < array.length; i++) { allValues.push(roundScorePercentSpecifiedByCourseSettings(array[i] / this.numberOfStudentsInCourse, this.course)); this.dataCopy[0].series[i]['value'] = roundScorePercentSpecifiedByCourseSettings(array[i] / this.numberOfStudentsInCourse, this.course); // allValues[i]; this.absoluteSeries[i]['absoluteValue'] = array[i]; } const currentAverage = allValues.length > 0 ? mean(allValues) : 0; this.average.name = currentAverage.toFixed(2) + '%'; this.average.value = currentAverage; } else { for (let i = 0; i < this.displayedNumberOfWeeks; i++) { this.dataCopy[0].series[i]['value'] = 0; this.absoluteSeries[i]['absoluteValue'] = 0; } } this.loading = false; } private createLabels() { this.dataCopy[0].series = [{}]; this.absoluteSeries = [{}]; let startDate: dayjs.Dayjs; let endDate: dayjs.Dayjs; if (this.showLifetimeOverview) { startDate = this.course.startDate!; endDate = dayjs().subtract(this.currentOffsetToEndDate, 'weeks'); this.currentSpanSize = this.determineDifferenceBetweenIsoWeeks(this.course.startDate!, endDate) + 1; } else { /* This variable contains the number of weeks between the last displayed week in the chart and the current date. If the end date is already passed, currentOffsetToEndDate represents the number of weeks between the course end date and the current date. displayedNumberOfWeeks determines the normal scope of the chart (usually 17 weeks). currentPeriod indicates how many times the observer shifted the scope in the past (by pressing the arrow) */ const diffToLastChartWeek = this.currentOffsetToEndDate - this.displayedNumberOfWeeks * this.currentPeriod; endDate = dayjs().subtract(diffToLastChartWeek, 'weeks'); const remainingWeeksTillStartDate = this.course.startDate ? this.determineDifferenceBetweenIsoWeeks(this.course.startDate, endDate) + 1 : this.displayedNumberOfWeeks; this.currentSpanSize = Math.min(remainingWeeksTillStartDate, this.displayedNumberOfWeeks); // for the start date, we subtract the currently possible span size - 1 from the end date in addition startDate = dayjs().subtract(diffToLastChartWeek + this.currentSpanSize - 1, 'weeks'); this.startDateDisplayed = !!this.course.startDate && remainingWeeksTillStartDate <= this.displayedNumberOfWeeks; } this.assignLabelsToDataObjects(); this.chartTime = startDate.isoWeekday(1).format('DD.MM.YYYY') + ' - ' + endDate.isoWeekday(7).format('DD.MM.YYYY'); this.dataCopy[0].name = this.amountOfStudents; } switchTimeSpan(index: boolean): void { if (index) { this.currentPeriod += 1; } else { this.currentPeriod -= 1; } this.showsCurrentWeek = this.currentPeriod === 0; this.reloadChart(); } formatYAxis(value: any) { return value.toLocaleString() + ' %'; } /** * Using the model, we look for the entry with the same title (CW XX) and return the absolute value for this entry */ findAbsoluteValue(model: any) { const result: any = this.absoluteSeries.find((entry: any) => entry.name === model.name); return result ? result.absoluteValue : '/'; } /** * Switches the visibility state for the reference line in the chart */ toggleAverageLine(): void { this.showAverage = !this.showAverage; } /** * Creates the chart for the default scope (<= 17 weeks) */ displayDefaultChartScope(): void { this.showLifetimeOverview = false; this.loading = true; // Only use the pre-loaded stats once if (!this.initialStats) { return; } this.createLabels(); this.processDataAndCreateChart(this.initialStats); this.data = this.dataCopy; } /** * Creates the chart for the lifetime overview */ displayLifetimeOverview(): void { // if the course does not have a start date, we can't create an meaningful lifetime overview if (!this.course.startDate) { return; } this.showLifetimeOverview = true; this.loading = true; this.currentPeriod = 0; this.startDateDisplayed = true; this.showsCurrentWeek = true; this.createLabels(); // we cache the overview stats to prevent many server requests if (!this.overviewStats) { this.fetchLifetimeOverviewData(); } else { this.processDataAndCreateChart(this.overviewStats); this.data = [...this.dataCopy]; } } /** * Auxiliary method reducing the complexity of {@link CourseDetailLineChartComponent#createLabels} * Assigns the correct calendar week numbers to the corresponding data objects as string * Note: the conversion to strings is important as ngx-charts increases the tick steps of on the x axis otherwise * @private */ private assignLabelsToDataObjects(): void { let currentWeek; for (let i = 0; i < this.currentSpanSize; i++) { currentWeek = dayjs() .subtract(this.currentOffsetToEndDate + this.currentSpanSize - 1 - this.displayedNumberOfWeeks * this.currentPeriod - i, 'weeks') .isoWeekday(1) .isoWeek(); this.dataCopy[0].series[i] = {}; this.dataCopy[0].series[i]['name'] = currentWeek.toString(); this.absoluteSeries[i] = {}; this.absoluteSeries[i]['name'] = currentWeek.toString(); } } /** * Fetches and caches the data for the lifetime overview from the server and creates the chart * @private */ private fetchLifetimeOverviewData(): void { this.service.getStatisticsForLifetimeOverview(this.course.id!).subscribe((res: number[]) => { this.overviewStats = res; this.processDataAndCreateChart(this.overviewStats); this.data = [...this.dataCopy]; }); } /** * Auxiliary method handles the translation sensitivity of the x axis label * @private */ private updateXAxisLabel() { this.xAxisLabel = this.translateService.instant('artemisApp.courseStatistics.calendarWeek'); } }
the_stack
import { globalBeforeEach } from '../../__jest__/before-each'; import * as models from '../../models'; import { data as fixtures } from '../__fixtures__/nestedfolders'; import { _repairDatabase, database as db } from '../database'; function loadFixture() { const promises: Promise<models.BaseModel>[] = []; for (const type of Object.keys(fixtures)) { for (const doc of fixtures[type]) { // @ts-expect-error -- TSCONVERSION promises.push(db.insert<models.BaseModel>({ ...doc, type })); } } return Promise.all(promises); } describe('init()', () => { beforeEach(globalBeforeEach); it('handles being initialized twice', async () => { await db.init(models.types(), { inMemoryOnly: true, }); await db.init(models.types(), { inMemoryOnly: true, }); expect((await db.all(models.request.type)).length).toBe(0); }); }); describe('onChange()', () => { beforeEach(globalBeforeEach); it('handles change listeners', async () => { const doc = { type: models.request.type, parentId: 'nothing', name: 'foo', }; const changesSeen: Function[] = []; const callback = change => { changesSeen.push(change); }; db.onChange(callback); const newDoc = await models.request.create(doc); const updatedDoc = await models.request.update(newDoc, { name: 'bar', }); expect(changesSeen.length).toBe(2); expect(changesSeen).toEqual([ [[db.CHANGE_INSERT, newDoc, false]], [[db.CHANGE_UPDATE, updatedDoc, false]], ]); db.offChange(callback); await models.request.create(doc); expect(changesSeen.length).toBe(2); }); }); describe('bufferChanges()', () => { beforeEach(globalBeforeEach); it('properly buffers changes', async () => { const doc = { type: models.request.type, parentId: 'n/a', name: 'foo', }; const changesSeen: Function[] = []; const callback = change => { changesSeen.push(change); }; db.onChange(callback); await db.bufferChanges(); const newDoc = await models.request.create(doc); // @ts-expect-error -- TSCONVERSION appears to be genuine const updatedDoc = await models.request.update(newDoc, true); // Assert no change seen before flush expect(changesSeen.length).toBe(0); // Assert changes seen after flush await db.flushChanges(); expect(changesSeen).toEqual([ [ [db.CHANGE_INSERT, newDoc, false], [db.CHANGE_UPDATE, updatedDoc, false], ], ]); // Assert no more changes seen after flush again await db.flushChanges(); expect(changesSeen).toEqual([ [ [db.CHANGE_INSERT, newDoc, false], [db.CHANGE_UPDATE, updatedDoc, false], ], ]); }); it('should auto flush after a default wait', async () => { const doc = { type: models.request.type, parentId: 'n/a', name: 'foo', }; const changesSeen: Function[] = []; const callback = change => { changesSeen.push(change); }; db.onChange(callback); await db.bufferChanges(); const newDoc = await models.request.create(doc); // @ts-expect-error -- TSCONVERSION appears to be genuine const updatedDoc = await models.request.update(newDoc, true); // Default flush timeout is 1000ms after starting buffering await new Promise(resolve => setTimeout(resolve, 1500)); expect(changesSeen).toEqual([ [ [db.CHANGE_INSERT, newDoc, false], [db.CHANGE_UPDATE, updatedDoc, false], ], ]); }); it('should auto flush after a specified wait', async () => { const doc = { type: models.request.type, parentId: 'n/a', name: 'foo', }; const changesSeen: Function[] = []; const callback = change => { changesSeen.push(change); }; db.onChange(callback); await db.bufferChanges(500); const newDoc = await models.request.create(doc); // @ts-expect-error -- TSCONVERSION appears to be genuine const updatedDoc = await models.request.update(newDoc, true); await new Promise(resolve => setTimeout(resolve, 1000)); expect(changesSeen).toEqual([ [ [db.CHANGE_INSERT, newDoc, false], [db.CHANGE_UPDATE, updatedDoc, false], ], ]); }); }); describe('bufferChangesIndefinitely()', () => { beforeEach(globalBeforeEach); it('should not auto flush', async () => { const doc = { type: models.request.type, parentId: 'n/a', name: 'foo', }; const changesSeen: Function[] = []; const callback = change => { changesSeen.push(change); }; db.onChange(callback); await db.bufferChangesIndefinitely(); const newDoc = await models.request.create(doc); // @ts-expect-error -- TSCONVERSION appears to be genuine const updatedDoc = await models.request.update(newDoc, true); // Default flush timeout is 1000ms after starting buffering await new Promise(resolve => setTimeout(resolve, 1500)); // Assert no change seen before flush expect(changesSeen.length).toBe(0); // Assert changes seen after flush await db.flushChanges(); expect(changesSeen).toEqual([ [ [db.CHANGE_INSERT, newDoc, false], [db.CHANGE_UPDATE, updatedDoc, false], ], ]); }); }); describe('requestCreate()', () => { beforeEach(globalBeforeEach); it('creates a valid request', async () => { const now = Date.now(); const patch = { name: 'My Request', parentId: 'wrk_123', }; const r = await models.request.create(patch); expect(Object.keys(r).length).toBe(21); expect(r._id).toMatch(/^req_[a-zA-Z0-9]{32}$/); expect(r.created).toBeGreaterThanOrEqual(now); expect(r.modified).toBeGreaterThanOrEqual(now); expect(r.type).toBe('Request'); expect(r.name).toBe('My Request'); expect(r.url).toBe(''); expect(r.method).toBe('GET'); expect(r.body).toEqual({}); expect(r.parameters).toEqual([]); expect(r.headers).toEqual([]); expect(r.authentication).toEqual({}); expect(r.metaSortKey).toBeLessThanOrEqual(-1 * now); expect(r.parentId).toBe('wrk_123'); }); it('throws when missing parentID', () => { const fn = () => models.request.create({ name: 'My Request', }); expect(fn).toThrowError('New Requests missing `parentId`'); }); }); describe('requestGroupDuplicate()', () => { beforeEach(async () => { await globalBeforeEach(); await loadFixture(); }); it('duplicates a RequestGroup', async () => { const requestGroup = await models.requestGroup.getById('fld_1'); expect(requestGroup).not.toEqual(null); if (requestGroup === null) { return; } expect(requestGroup.name).toBe('Fld 1'); const newRequestGroup = await models.requestGroup.duplicate(requestGroup); expect(newRequestGroup._id).not.toBe(requestGroup._id); expect(newRequestGroup.name).toBe('Fld 1 (Copy)'); const allRequests = await models.request.all(); const allRequestGroups = await models.requestGroup.all(); const childRequests = await models.request.findByParentId(requestGroup._id); const childRequestGroups = await models.requestGroup.findByParentId(requestGroup._id); const newChildRequests = await models.request.findByParentId(newRequestGroup._id); const newChildRequestGroups = await models.requestGroup.findByParentId(newRequestGroup._id); // This asserting is pretty garbage but it at least checks // to see that the recursion worked (for the most part) expect(allRequests.length).toBe(8); expect(allRequestGroups.length).toBe(5); expect(childRequests.length).toBe(2); expect(childRequestGroups.length).toBe(1); expect(newChildRequests.length).toBe(2); expect(newChildRequestGroups.length).toBe(1); }); }); describe('_repairDatabase()', () => { beforeEach(globalBeforeEach); it('fixes duplicate environments', async () => { // Create Workspace with no children const project = await models.project.create(); const workspace = await models.workspace.create({ _id: 'w1', parentId: project._id, }); const spec = await models.apiSpec.getByParentId(workspace._id); expect((await db.withDescendants(workspace)).length).toBe(2); // Create one set of sub environments await models.environment.create({ _id: 'b1', parentId: 'w1', data: { foo: 'b1', b1: true, }, }); await models.environment.create({ _id: 'b1_sub1', parentId: 'b1', data: { foo: '1', }, }); await models.environment.create({ _id: 'b1_sub2', parentId: 'b1', data: { foo: '2', }, }); // Create second set of sub environments await models.environment.create({ _id: 'b2', parentId: 'w1', data: { foo: 'b2', b2: true, }, }); await models.environment.create({ _id: 'b2_sub1', parentId: 'b2', data: { foo: '3', }, }); await models.environment.create({ _id: 'b2_sub2', parentId: 'b2', data: { foo: '4', }, }); // Make sure we have everything expect((await db.withDescendants(workspace)).length).toBe(8); const descendants = (await db.withDescendants(workspace)).map(d => ({ _id: d._id, parentId: d.parentId, // @ts-expect-error -- TSCONVERSION appears to be genuine data: d.data || null, })); expect(descendants).toEqual([ { _id: 'w1', data: null, parentId: workspace.parentId, }, { _id: 'b1', data: { foo: 'b1', b1: true, }, parentId: 'w1', }, { _id: 'b2', data: { foo: 'b2', b2: true, }, parentId: 'w1', }, expect.objectContaining({ _id: spec?._id, parentId: 'w1', }), { _id: 'b1_sub1', data: { foo: '1', }, parentId: 'b1', }, { _id: 'b1_sub2', data: { foo: '2', }, parentId: 'b1', }, { _id: 'b2_sub1', data: { foo: '3', }, parentId: 'b2', }, { _id: 'b2_sub2', data: { foo: '4', }, parentId: 'b2', }, ]); // Run the fix algorithm await _repairDatabase(); // Make sure things get adjusted const descendants2 = (await db.withDescendants(workspace)).map(d => ({ _id: d._id, parentId: d.parentId, // @ts-expect-error -- TSCONVERSION appears to be genuine data: d.data || null, })); expect(descendants2).toEqual([ { _id: 'w1', data: null, parentId: workspace.parentId, }, { _id: 'b1', data: { foo: 'b1', b1: true, b2: true, }, parentId: 'w1', }, expect.objectContaining({ _id: spec?._id, parentId: 'w1', }), // Extra base environments should have been deleted // {_id: 'b2', data: {foo: 'bar'}, parentId: 'w1'}, // Sub environments should have been moved to new "master" base environment { _id: 'b1_sub1', data: { foo: '1', }, parentId: 'b1', }, { _id: 'b1_sub2', data: { foo: '2', }, parentId: 'b1', }, { _id: 'b2_sub1', data: { foo: '3', }, parentId: 'b1', }, { _id: 'b2_sub2', data: { foo: '4', }, parentId: 'b1', }, ]); }); it('fixes duplicate cookie jars', async () => { // Create Workspace with no children const project = await models.project.create(); const workspace = await models.workspace.create({ _id: 'w1', parentId: project._id, }); const spec = await models.apiSpec.getByParentId(workspace._id); expect((await db.withDescendants(workspace)).length).toBe(2); // Create one set of sub environments await models.cookieJar.create({ _id: 'j1', parentId: 'w1', cookies: [ // @ts-expect-error -- TSCONVERSION { id: '1', key: 'foo', value: '1', }, // @ts-expect-error -- TSCONVERSION { id: 'j1_1', key: 'j1', value: '1', }, ], }); await models.cookieJar.create({ _id: 'j2', parentId: 'w1', cookies: [ // @ts-expect-error -- TSCONVERSION { id: '1', key: 'foo', value: '2', }, // @ts-expect-error -- TSCONVERSION { id: 'j2_1', key: 'j2', value: '2', }, ], }); // Make sure we have everything expect((await db.withDescendants(workspace)).length).toBe(4); const descendants = (await db.withDescendants(workspace)).map(d => ({ _id: d._id, // @ts-expect-error -- TSCONVERSION cookies: d.cookies || null, parentId: d.parentId, })); expect(descendants).toEqual([ { _id: 'w1', cookies: null, parentId: workspace.parentId, }, { _id: 'j1', parentId: 'w1', cookies: [ { id: '1', key: 'foo', value: '1', }, { id: 'j1_1', key: 'j1', value: '1', }, ], }, { _id: 'j2', parentId: 'w1', cookies: [ { id: '1', key: 'foo', value: '2', }, { id: 'j2_1', key: 'j2', value: '2', }, ], }, expect.objectContaining({ _id: spec?._id, parentId: 'w1', }), ]); // Run the fix algorithm await _repairDatabase(); // Make sure things get adjusted const descendants2 = (await db.withDescendants(workspace)).map(d => ({ _id: d._id, // @ts-expect-error -- TSCONVERSION cookies: d.cookies || null, parentId: d.parentId, })); expect(descendants2).toEqual([ { _id: 'w1', cookies: null, parentId: workspace.parentId, }, { _id: 'j1', parentId: 'w1', cookies: [ { id: '1', key: 'foo', value: '1', }, { id: 'j1_1', key: 'j1', value: '1', }, { id: 'j2_1', key: 'j2', value: '2', }, ], }, expect.objectContaining({ _id: spec?._id, parentId: 'w1', }), ]); }); it('fixes the filename on an apiSpec', async () => { // Create Workspace with apiSpec child (migration in workspace will automatically create this as it is not mocked) const w1 = await models.workspace.create({ _id: 'w1', name: 'Workspace 1', }); const w2 = await models.workspace.create({ _id: 'w2', name: 'Workspace 2', }); const w3 = await models.workspace.create({ _id: 'w3', name: 'Workspace 3', }); await models.apiSpec.updateOrCreateForParentId(w1._id, { fileName: '', }); await models.apiSpec.updateOrCreateForParentId(w2._id, { fileName: models.apiSpec.init().fileName, }); await models.apiSpec.updateOrCreateForParentId(w3._id, { fileName: 'Unique name', }); // Make sure we have everything expect((await models.apiSpec.getByParentId(w1._id))?.fileName).toBe(''); expect((await models.apiSpec.getByParentId(w2._id))?.fileName).toBe('New Document'); expect((await models.apiSpec.getByParentId(w3._id))?.fileName).toBe('Unique name'); // Run the fix algorithm await _repairDatabase(); // Make sure things get adjusted expect((await models.apiSpec.getByParentId(w1._id))?.fileName).toBe('Workspace 1'); // Should fix expect((await models.apiSpec.getByParentId(w2._id))?.fileName).toBe('Workspace 2'); // Should fix expect((await models.apiSpec.getByParentId(w3._id))?.fileName).toBe('Unique name'); // should not fix }); it('fixes old git uris', async () => { const oldRepoWithSuffix = await models.gitRepository.create({ uri: 'https://github.com/foo/bar.git', uriNeedsMigration: true, }); const oldRepoWithoutSuffix = await models.gitRepository.create({ uri: 'https://github.com/foo/bar', uriNeedsMigration: true, }); const newRepoWithSuffix = await models.gitRepository.create({ uri: 'https://github.com/foo/bar.git', }); const newRepoWithoutSuffix = await models.gitRepository.create({ uri: 'https://github.com/foo/bar', }); await _repairDatabase(); expect(await db.get(models.gitRepository.type, oldRepoWithSuffix._id)).toEqual( expect.objectContaining({ uri: 'https://github.com/foo/bar.git', uriNeedsMigration: false, }), ); expect(await db.get(models.gitRepository.type, oldRepoWithoutSuffix._id)).toEqual( expect.objectContaining({ uri: 'https://github.com/foo/bar.git', uriNeedsMigration: false, }), ); expect(await db.get(models.gitRepository.type, newRepoWithSuffix._id)).toEqual( expect.objectContaining({ uri: 'https://github.com/foo/bar.git', uriNeedsMigration: false, }), ); expect(await db.get(models.gitRepository.type, newRepoWithoutSuffix._id)).toEqual( expect.objectContaining({ uri: 'https://github.com/foo/bar', uriNeedsMigration: false, }), ); }); }); describe('duplicate()', () => { beforeEach(globalBeforeEach); afterEach(() => jest.restoreAllMocks()); it('should overwrite appropriate fields on the parent when duplicating', async () => { const date = 1478795580200; Date.now = jest.fn().mockReturnValue(date); const workspace = await models.workspace.create({ name: 'Test Workspace', }); const newDescription = 'test'; const duplicated = await db.duplicate(workspace, { description: newDescription, }); expect(duplicated._id).not.toEqual(workspace._id); expect(duplicated._id).toMatch(/^wrk_[a-z0-9]{32}$/); // @ts-expect-error -- TSCONVERSION delete workspace._id; // @ts-expect-error -- TSCONVERSION delete duplicated._id; expect(duplicated).toEqual({ ...workspace, description: newDescription, modified: date, created: date, type: models.workspace.type, }); }); it('should should not call migrate when duplicating', async () => { const workspace = await models.workspace.create({ name: 'Test Workspace', }); const spy = jest.spyOn(models.workspace, 'migrate'); await db.duplicate(workspace); expect(spy).not.toHaveBeenCalled(); }); }); describe('docCreate()', () => { beforeEach(globalBeforeEach); afterEach(() => jest.restoreAllMocks()); it('should call migrate when creating', async () => { const spy = jest.spyOn(models.workspace, 'migrate'); await db.docCreate(models.workspace.type, { name: 'Test Workspace', }); // TODO: This is actually called twice, not once - we should avoid the double model.init() call. expect(spy).toHaveBeenCalled(); }); }); describe('withAncestors()', () => { beforeEach(globalBeforeEach); it('should return itself and all parents but exclude siblings', async () => { const spc = await models.project.create(); const wrk = await models.workspace.create({ parentId: spc._id, }); const wrkReq = await models.request.create({ parentId: wrk._id, }); const wrkGrpcReq = await models.grpcRequest.create({ parentId: wrk._id, }); const grp = await models.requestGroup.create({ parentId: wrk._id, }); const grpReq = await models.request.create({ parentId: grp._id, }); const grpGrpcReq = await models.grpcRequest.create({ parentId: grp._id, }); // Workspace child searching for ancestors await expect(db.withAncestors(wrk)).resolves.toStrictEqual([wrk, spc]); await expect(db.withAncestors(wrkReq)).resolves.toStrictEqual([wrkReq, wrk, spc]); await expect(db.withAncestors(wrkGrpcReq)).resolves.toStrictEqual([wrkGrpcReq, wrk, spc]); // Group searching for ancestors await expect(db.withAncestors(grp)).resolves.toStrictEqual([grp, wrk, spc]); // Group child searching for ancestors await expect(db.withAncestors(grpReq)).resolves.toStrictEqual([grpReq, grp, wrk, spc]); await expect(db.withAncestors(grpGrpcReq)).resolves.toStrictEqual([grpGrpcReq, grp, wrk, spc]); // Group child searching for ancestors with filters await expect(db.withAncestors(grpGrpcReq, [models.requestGroup.type])).resolves.toStrictEqual([ grpGrpcReq, grp, ]); await expect( db.withAncestors(grpGrpcReq, [models.requestGroup.type, models.workspace.type]), ).resolves.toStrictEqual([grpGrpcReq, grp, wrk]); // Group child searching for ancestors but excluding groups will not find the workspace await expect(db.withAncestors(grpGrpcReq, [models.workspace.type])).resolves.toStrictEqual([ grpGrpcReq, ]); }); });
the_stack
import { app } from './app.js'; declare const angular; /** * Spec Canvas Visuals to render bezier curves and other elements */ app.directive('specCanvas', function ($timeout) { // Bezier Curve Drawing // Basic Curves: // Fast Out, Slow In: cubic-bezier(0.4, 0.0, 0.2, 1) // Linear Out, Slow In: cubic-bezier(0.0, 0.0, 0.2, 1) // Fast Out, Linear In: cubic-bezier(0.4, 0.0, 1, 1) // Turns hex to RGB then adds an alpha channel while outputting to CSS format var lighten = function (hex) { hex = hex.replace(/[^0-9A-F]/gi, ''); var bigint = parseInt(hex, 16); var r = (bigint >> 16) & 255; var g = (bigint >> 8) & 255; var b = bigint & 255; return 'rgba(' + r + ',' + g + ',' + b + ',0.15)'; }; // Draws the base bar and begin and end circles var drawBar = function (ctx, w, h) { // ctx.fillRect(0, h-10, 2, 10); // Left Bar (debug) ctx.fillRect(5, h - 6, w - 10, 2); // Bottom Bar // ctx.fillRect(w-2, h-10, 2, 10); // Right Bar (debug) // Circle Params var radius = 5; // Arc radius var startAngle = 0; // Starting point on circle var endAngle = Math.PI * 2; // End point on circle // Left Circle ctx.beginPath(); ctx.arc(5, h - 5, radius, startAngle, endAngle); ctx.fill(); // Right Circle ctx.beginPath(); ctx.arc(w - 5, h - 5, radius, startAngle, endAngle); ctx.fill(); }; var drawDiamond = function (ctx, w, h) { // translate ctx.translate(0, 7); // rotate ctx.rotate((45 * Math.PI) / 180); // draw diamond ctx.fillRect(12.15, 5, 7.5, 7.5); // ctx.fill(); // reset ctx.setTransform(1, 0, 0, 1, 0, 0); }; // Renders the curve on the given canvas var render = function (wrap, canvas, spec, totalDuration) { var baseColor = spec.color; var lightColor = lighten(baseColor); var curve = spec.easing.value; var inValue = 0; var outValue = 0; // Set Canvas Positioning and rudimentary prevention of invalid input // TODO: better error checking if ( +spec.duration + +spec.delay > +totalDuration || +spec.delay < 0 || +spec.duration > +totalDuration ) { console.warn('Duration or Delay are invalid!'); return; } var duration = (spec.duration / totalDuration) * 100; var delay = (spec.delay / totalDuration) * 100; wrap.css({ width: duration + '%', marginLeft: delay + '%', }); var wrapWidth = wrap.width(); canvas.css({ width: wrapWidth + 10, marginLeft: '-5px', marginRight: '-5px', }); // Set Canvas Width / Height var cw = canvas.width(); var ch = canvas.height(); canvas.attr({ width: cw, height: ch, }); // Setup & Reset var ctx = canvas.get(0).getContext('2d'); ctx.clearRect(0, 0, cw, ch); // check duration if (duration === 0) { ctx.fillStyle = baseColor; drawDiamond(ctx, cw, ch); return; } // Curve // Good Explanation: http://blogs.sitepointstatic.com/examples/tech/canvas-curves/bezier-curve.html // http://jsfiddle.net/andershaig/54AsL/ ctx.fillStyle = lightColor; switch (curve) { case 'curve': ctx.beginPath(); ctx.moveTo(5, ch - 5); ctx.bezierCurveTo(5, ch - 5, cw / 2, (ch - 5) * -1, cw - 5, ch - 5); ctx.fill(); break; case 'quantum': inValue = 0.8; outValue = 0.4; ctx.beginPath(); ctx.moveTo(5, ch - 5); ctx.bezierCurveTo( cw * outValue + 5, ch - 5, (1 - inValue) * cw - 5, 0, cw - 5, 0 ); ctx.lineTo(cw - 5, ch - 5); ctx.fill(); break; case 'incoming': inValue = 0.8; outValue = 0; ctx.beginPath(); ctx.moveTo(5, ch - 5); ctx.bezierCurveTo( cw * outValue + 5, ch - 5, (1 - inValue) * cw - 5, 0, cw - 5, 0 ); ctx.lineTo(cw - 5, ch - 5); ctx.fill(); break; case 'outgoing': inValue = 0; outValue = 0.4; ctx.beginPath(); ctx.moveTo(5, ch - 5); ctx.bezierCurveTo( cw * outValue + 5, ch - 5, (1 - inValue) * cw - 5, 0, cw - 5, 0 ); ctx.lineTo(cw - 5, ch - 5); ctx.fill(); break; case 'linear': ctx.beginPath(); ctx.moveTo(5, ch - 5); ctx.lineTo(cw - 5, 0); ctx.lineTo(cw - 5, ch - 5); ctx.fill(); break; case 'custom': inValue = spec.easingCustomIncoming / 100; outValue = spec.easingCustomOutgoing / 100; ctx.beginPath(); ctx.moveTo(5, ch - 5); ctx.bezierCurveTo( cw * outValue + 5, ch - 5, (1 - inValue) * cw - 5, 0, cw - 5, 0 ); ctx.lineTo(cw - 5, ch - 5); ctx.fill(); break; case 'none': ctx.fillRect(5, 0, cw - 10, ch - 5); break; default: break; } // Bar ctx.fillStyle = baseColor; drawBar(ctx, cw, ch); }; return { restrict: 'A', scope: { specCanvas: '=', duration: '=', }, link: function (scope, element, attrs) { var wrap = angular.element(element[0]); var canvas = angular.element(element.find('canvas')[0]); // Watch Changes scope.$watch( 'specCanvas', function (newValue, oldValue) { render(wrap, canvas, scope.specCanvas, scope.duration); }, true ); // Window Width Changes $(window).resize(function () { render(wrap, canvas, scope.specCanvas, scope.duration); }); // Watch for controller to request redraw scope.$on('refreshCanvas', function () { $timeout(function () { render(wrap, canvas, scope.specCanvas, scope.duration); }, 0); }); }, }; }); /** * Grid Background */ app.directive('specGrid', function ($timeout) { var render = function (canvas, spec) { var ms = spec.duration || 300; var minorMs = spec.divisions.minor || 15; var majorMs = spec.divisions.major || 75; // Set Canvas Width / Height var cw = canvas.parent().width(); var ch = canvas.parent().height(); canvas.attr({ width: cw, height: ch, }); spec.canvas.width = cw; // Setup & Reset var ctx = canvas.get(0).getContext('2d'); ctx.clearRect(0, 0, cw, ch); // Generate Grid var minorDivisions = (spec.divisions.minorCount = ms / minorMs); var minorGap = (spec.divisions.minorGap = cw / minorDivisions); ctx.beginPath(); for (var x = 0.5 + minorGap; x <= cw; x += minorGap) { // Adding the gap skips the initial line at 0 var xr = Math.round(x); var nx; if (xr >= x) { nx = xr - 0.5; } else { nx = xr + 0.5; } ctx.moveTo(nx, 0); ctx.lineTo(nx, ch); } ctx.strokeStyle = '#EEEEEE'; ctx.lineWidth = 1; ctx.stroke(); var majorDivisions = (spec.divisions.majorCount = ms / majorMs); var majorGap = (spec.divisions.majorGap = cw / majorDivisions); ctx.beginPath(); for (var x = majorGap; x < cw; x += majorGap) { // Adding the gap skips the initial line at 0 var xr = Math.round(x); ctx.moveTo(xr, 0); ctx.lineTo(xr, ch); } // Always draw start ctx.moveTo(1, 0); ctx.lineTo(1, ch); // Always draw end ctx.moveTo(cw - 1, 0); ctx.lineTo(cw - 1, ch); ctx.strokeStyle = '#DDDDDD'; ctx.lineWidth = 2; ctx.stroke(); }; return { restrict: 'A', scope: { specGrid: '=', }, link: function (scope, element, attrs) { var canvas = angular.element(element[0]); // Watch Changes scope.$watch( 'specGrid', function (newValue, oldValue) { if (scope.specGrid && scope.specGrid !== undefined) { render(canvas, scope.specGrid); } }, true ); // Window Width Changes $(window).resize(function () { if (scope.specGrid && scope.specGrid !== undefined) { render(canvas, scope.specGrid); } }); // Watch for controller to request redraw scope.$on('refreshCanvas', function (type) { $timeout(function () { if (scope.specGrid && scope.specGrid !== undefined) { render(canvas, scope.specGrid); } }, 0); }); }, }; }); /** * Drawable Canvas to add new items * (goes away once drawn and renders using specCanvas' render method) */ app.directive('specDraw', function ($timeout, $document) { var render = function (canvas, spec) { var ms = spec.duration || 300; var minorMs = spec.divisions.minor || 15; var majorMs = spec.divisions.major || 75; // Set Canvas Width / Height var cw = canvas.parent().width(); var ch = canvas.parent().height(); canvas.attr({ width: cw, height: ch, }); // Setup & Reset var ctx = canvas.get(0).getContext('2d'); ctx.clearRect(0, 0, cw, ch); // Add Background ctx.fillStyle = '#F8EFF9'; ctx.fillRect(0, 0, cw, ch); // Generate Grid var minorDivisions = (spec.divisions.minorCount = ms / minorMs); var minorGap = (spec.divisions.minorGap = cw / minorDivisions); ctx.beginPath(); for (var x = 0.5 + minorGap; x <= cw; x += minorGap) { // Adding the gap skips the initial line at 0 var xr = Math.round(x); var nx; if (xr >= x) { nx = xr - 0.5; } else { nx = xr + 0.5; } ctx.moveTo(nx, 0); ctx.lineTo(nx, ch); } ctx.strokeStyle = '#E9E0EB'; ctx.lineWidth = 1; ctx.stroke(); var majorDivisions = (spec.divisions.majorCount = ms / majorMs); var majorGap = (spec.divisions.majorGap = cw / majorDivisions); ctx.beginPath(); for (var x = majorGap; x < cw; x += majorGap) { // Adding the gap skips the initial line at 0 var xr = Math.round(x); ctx.moveTo(xr, 0); ctx.lineTo(xr, ch); } // Always draw start ctx.moveTo(1, 0); ctx.lineTo(1, ch); // Draw end if the duration is a multiple of 75ms if (ms % majorMs === 0) { ctx.moveTo(cw - 1, 0); ctx.lineTo(cw - 1, ch); } ctx.strokeStyle = '#E9E0EB'; ctx.lineWidth = 2; ctx.stroke(); }; var renderCircle = function (canvas, x) { var ctx = canvas.get(0).getContext('2d'); ctx.beginPath(); var y = 30; // y coordinate var radius = 5; // Arc radius var startAngle = 0; // Starting point on circle var endAngle = Math.PI * 2; // End point on circle ctx.arc(x, y, radius, startAngle, endAngle); ctx.fillStyle = '#CE93D8'; ctx.fill(); }; var renderLine = function (canvas, from, to) { var ctx = canvas.get(0).getContext('2d'); ctx.beginPath(); ctx.moveTo(from, 30); ctx.lineTo(to, 30); ctx.strokeStyle = '#CE93D8'; ctx.lineWidth = 2; ctx.stroke(); }; return { restrict: 'A', scope: { specDraw: '=', completeFn: '&', position: '=', }, link: function (scope, element, attrs) { var addSpecRow = function (delay, duration) { var row = { delay: delay || 0, // ms delayFrames: Math.round(delay / (1000 / scope.specDraw.fps)), duration: duration, // ms durationFrames: Math.round(duration / (1000 / scope.specDraw.fps)), color: '#737373', properties: null, easing: { label: '80% Incoming, 40% Outgoing', value: 'quantum', }, easingCustomIncoming: 0, easingCustomOutgoing: 0, tag: { label: 'None', value: 'none', }, customTag: null, comment: null, }; clearCanvas(() => {}); scope.$apply(function () { scope.specDraw.rows.splice(scope.position + 1, 0, row); }); scope.completeFn(); }; var canvas = angular.element(element[0]); var creation: { startX: number | null; endX: number | null; delay: number | null; duration: number | null; } = { startX: null, endX: null, delay: null, duration: null, }; var getLeft = function (el) { var rect = el.getBoundingClientRect(); var docEl = document.documentElement; var left = rect.left + (window.pageXOffset || docEl.scrollLeft || 0); return left; }; var getTop = function (el) { var rect = el.getBoundingClientRect(); var docEl = document.documentElement; var top = rect.top + (window.pageYOffset || docEl.scrollTop || 0); return top; }; element.on('mouseover', function (event) { event.preventDefault(); $document.on('mousemove', mousemove); $document.on('mousedown', mousedown); $document.on('mouseup', mouseup); }); var inBounds = function (event) { var y = event.pageY; var x = event.pageX; var offsetLeft = getLeft(element[0]) - x; var offsetTop = getTop(element[0]) - y; var padding = 20; if ( offsetLeft > padding || offsetLeft < -canvas.width() - padding || offsetTop > padding || offsetTop < -canvas.height() - padding ) { return false; } return true; }; var mousemove = function (event) { if (!inBounds(event)) { clearCanvas(() => {}); return; } var x = event.pageX; var elementX = x - getLeft(element[0]); var mGap = scope.specDraw.divisions.minorGap; var numMinorDivisions = Math.round(elementX / mGap); // numMinorDivisions * minor ms = delay for first click // numMinorDivisions * minor ms - delay = duration for second click var snappedX = numMinorDivisions * mGap; render(canvas, scope.specDraw); if (creation.startX !== null) { // Render initial dot + line renderLine(canvas, creation.startX, snappedX); renderCircle(canvas, creation.startX); renderCircle(canvas, snappedX); } else { // Render hover dot only renderCircle(canvas, snappedX); } }; var addPoint = function (point, ms) { if (creation.startX !== null) { // numMinorDivisions * minor ms - delay = duration for second click if (creation.delay) creation.duration = ms - creation.delay; creation.endX = point; // Finalize Row addSpecRow(creation.delay, creation.duration); } else { // numMinorDivisions * minor ms = delay for first click creation.delay = ms; creation.startX = point; } }; var mousedown = function (event) { var x = event.pageX; var elementX = x - getLeft(element[0]); var ms = scope.specDraw.divisions.minor; var mGap = scope.specDraw.divisions.minorGap; var numMinorDivisions = Math.round(elementX / mGap); var snappedX = numMinorDivisions * mGap; var snappedMs = numMinorDivisions * ms; addPoint(snappedX, snappedMs); }; var mouseup = function (event) { var x = event.pageX; var elementX = x - getLeft(element[0]); var ms = scope.specDraw.divisions.minor; var mGap = scope.specDraw.divisions.minorGap; var numMinorDivisions = Math.round(elementX / mGap); var snappedX = numMinorDivisions * mGap; var snappedMs = numMinorDivisions * ms; // If there is already a start point and this event's point differs if (creation.startX && snappedX !== creation.startX) { addPoint(snappedX, snappedMs); } }; var clearCanvas = function (event) { creation = { startX: null, endX: null, delay: null, duration: null, }; // Clear canvas except for grid render(canvas, scope.specDraw); $document.off('mousemove', mousemove); $document.off('mousedown', mousedown); }; // Watch Changes scope.$watch( 'specDraw', function (newValue, oldValue) { if (scope.specDraw && scope.specDraw !== undefined) { render(canvas, scope.specDraw); } }, true ); // Window Width Changes $(window).resize(function () { if (scope.specDraw && scope.specDraw !== undefined) { render(canvas, scope.specDraw); } }); // Watch for controller to request redraw scope.$on('refreshCanvas', function (type) { $timeout(function () { if (scope.specDraw && scope.specDraw !== undefined) { render(canvas, scope.specDraw); } }, 0); }); }, }; }); /** * Popup & Popup Tip Position */ app.directive('specTip', function () { var render = function (tip, spec, totalDuration) { var duration = spec.duration / totalDuration; var delay = spec.delay / totalDuration; var containerWidth = $('.spec-item-wrap').width(); var offset = delay + duration / 2; if (containerWidth) { var pixelOffset = offset * containerWidth; var centerPoint = pixelOffset - 10; // 10 for tip width tip.css({ left: centerPoint, }); } }; return { restrict: 'A', scope: { specTip: '=', duration: '=', }, link: function (scope, element, attrs) { var tip = angular.element(element[0]); // Watch Changes scope.$watch( 'specTip', function (newValue, oldValue) { render(tip, scope.specTip, scope.duration); }, true ); // Window Width Changes $(window).resize(function () { render(tip, scope.specTip, scope.duration); }); }, }; }); /** * Spec Item Resizing */ app.directive('resizer', function ($document) { return { restrict: 'A', scope: { resizerItem: '=', resizerSpec: '=', }, link: function (scope, element, attrs) { var initial: { x: number | null; delay: number | null; duration: number | null; } = { x: null, delay: null, duration: null, }; element.on('mousedown', function (event) { event.preventDefault(); $document.on('mousemove', mousemove); $document.on('mouseup', mouseup); $document.on('contextmenu', mouseup); // cancel on right clicks }); var mousemove = function (event) { var item = scope.resizerItem; scope.$parent.setResizingRow(item); // Get initial values if (!initial.x) { initial.x = event.pageX; } if (!initial.delay && initial.delay !== 0) { initial.delay = item.delay; } if (!initial.duration) { initial.duration = item.duration; } var duration = scope.resizerSpec.duration; var md = scope.resizerSpec.divisions.minor; var mdCount = scope.resizerSpec.divisions.minorCount; var mdGap = scope.resizerSpec.canvas.width / mdCount; var x = event.pageX; if (initial.x) { var dx = x - initial.x; if (attrs.resizer == 'left') { // Handle left resizer // Snap to minor divisions var changeInDivisions = Math.round(dx / mdGap); // If x increases, reduce delay and add to width // If x decreases, add to delay and reduce width var changeInMs = changeInDivisions * md; if (initial.delay && initial.duration) { var newDelay = initial.delay + changeInMs; var newDuration = initial.duration - changeInMs; // Cannot increase if delay + width = 100% if (newDelay + newDuration > duration) { newDelay = item.delay; newDuration = item.duration; } // Cannot reduce if width is less than 1 minor division if (newDuration < md) { newDelay = item.delay; newDuration = md; } // Cannot increase if delay is 0 (all the way on the left) if (newDelay < 0) { newDelay = 0; newDuration = item.duration; } // Apply new width scope.$apply(function () { item.delay = newDelay; item.delayFrames = Math.round( newDelay / (1000 / scope.resizerSpec.fps) ); item.duration = newDuration; item.durationFrames = Math.round( newDuration / (1000 / scope.resizerSpec.fps) ); }); } } else if (attrs.resizer == 'right') { // Handle right resizer // Snap to minor divisions var changeInDivisions = Math.round(dx / mdGap); // If x increases, add to width // If x decreases, reduce width var changeInMs = changeInDivisions * md; if (initial.duration) { var newDuration = initial.duration + changeInMs; // Cannot increase if delay + width = 100% if (item.delay + newDuration > duration) { newDuration = duration - item.delay; } // Cannot reduce if width is less than 1 minor division if (newDuration < md) { newDuration = md; } // Apply new width scope.$apply(function () { item.duration = newDuration; item.durationFrames = Math.round( newDuration / (1000 / scope.resizerSpec.fps) ); }); } } } }; var mouseup = function () { initial = { x: null, delay: null, duration: null, }; scope.$parent.setResizingRow(null); $document.unbind('mousemove', mousemove); $document.unbind('mouseup', mouseup); $document.unbind('contextmenu', mouseup); }; }, }; });
the_stack
import * as angular from "angular"; import {moduleName} from "../module-name"; import * as _ from "underscore"; import OpsManagerRestUrlService from "../services/OpsManagerRestUrlService"; import {AccessControlService} from "../../services/AccessControlService"; import AccessConstants from '../../constants/AccessConstants'; import {Transition} from "@uirouter/core"; import "./module-require"; import {FEED_DEFINITION_SUMMARY_STATE_NAME} from "../../feed-mgr/model/feed/feed-constants"; /** Manages the Alert Details page. * @constructor * @param $scope the Angular scope * @param $http the HTTP service * @param $mdDialog the dialog server * @param AccessControlService the access control service * @param OpsManagerRestUrlService the REST URL service */ export class AlertDetailsDirectiveController implements ng.IComponentController{ allowAdmin: boolean = false; //Indicates that admin operations are allowed. {boolean} alertData: any; //The alert details. {Object} alertId: any; static readonly $inject=["$scope","$http","$mdDialog","AccessControlService","OpsManagerRestUrlService"]; ngOnInit(){ this.loadAlert(this.alertId); // Fetch alert details this.accessControlService.getUserAllowedActions() // Fetch allowed permissions .then((actionSet: any) =>{ this.allowAdmin = this.accessControlService.hasAction(AccessConstants.OPERATIONS_ADMIN, actionSet.actions); }); } constructor(private $scope: angular.IScope, private $http: angular.IHttpService, private $mdDialog: angular.material.IDialogService , private accessControlService: AccessControlService, private OpsManagerRestUrlService: OpsManagerRestUrlService){ this.ngOnInit(); }// end of constructor /** * Gets the class for the specified state. * @param {string} state the name of the state * @returns {string} class name */ getStateClass =(state: string)=> { switch (state) { case "UNHANDLED": return "error"; case "IN_PROGRESS": return "warn"; case "HANDLED": return "success"; default: return "unknown"; } }; /** * Gets the icon for the specified state. * @param {string} state the name of the state * @returns {string} icon name */ getStateIcon = (state: string)=> { switch (state) { case "CREATED": case "UNHANDLED": return "error_outline"; case "IN_PROGRESS": return "schedule"; case "HANDLED": return "check_circle"; default: return "help_outline"; } }; /** * Gets the display text for the specified state. * @param {string} state the name of the state * @returns {string} display text */ getStateText = (state: string)=> { if (state === "IN_PROGRESS") { return "IN PROGRESS"; } else { return state; } }; //Hides this alert on the list page. hideAlert = ()=> { this.alertData.cleared = true; this.$http.post(this.OpsManagerRestUrlService.ALERT_DETAILS_URL(this.alertData.id), {state: this.alertData.state, clear: true}); }; //Shows the alert removing the 'cleared' flag showAlert = ()=> { this.alertData.cleared = false; this.$http.post(this.OpsManagerRestUrlService.ALERT_DETAILS_URL(this.alertData.id), {state: this.alertData.state, clear: false, unclear:true}); }; /** Loads the data for the specified alert. * @param {string} alertId the id of the alert */ loadAlert = (alertId: string)=> { if(alertId) { this.$http.get(this.OpsManagerRestUrlService.ALERT_DETAILS_URL(alertId)) .then( (response: any)=> { this.alertData = response.data; // Set time since created if (angular.isNumber(this.alertData.createdTime)) { this.alertData.createdTimeSince = Date.now() - this.alertData.createdTime; } // Set state information if (angular.isString(this.alertData.state)) { this.alertData.stateClass = this.getStateClass(this.alertData.state); this.alertData.stateIcon = this.getStateIcon(this.alertData.state); this.alertData.stateText = this.getStateText(this.alertData.state); } var isStream = false; if (angular.isArray(this.alertData.events)) { angular.forEach(this.alertData.events, (event: any)=> { event.stateClass = this.getStateClass(event.state); event.stateIcon = this.getStateIcon(event.state); event.stateText = this.getStateText(event.state); event.contentSummary = null; if(angular.isDefined(event.content)){ try { var alertEventContent = angular.fromJson(event.content); if(alertEventContent && alertEventContent.content){ event.contentSummary = angular.isDefined(alertEventContent.content.failedCount) ? alertEventContent.content.failedCount +" failures" : null; if(!isStream && angular.isDefined(alertEventContent.content.stream)){ isStream = alertEventContent.content.stream; } } }catch(err){ } } }); } this.alertData.links = []; //add in the detail URLs if(this.alertData.type == 'http://kylo.io/alert/job/failure') { if(angular.isDefined(this.alertData.content) && !isStream) { var jobExecutionId = this.alertData.content; this.alertData.links.push({label: "Job Execution", value: "job-details({executionId:'" + jobExecutionId + "'})"}); } this.alertData.links.push({label:"Feed Details", value:FEED_DEFINITION_SUMMARY_STATE_NAME+".feed-activity"+"({feedId:'"+this.alertData.entityId+"'})"}); } else if(this.alertData.type == 'http://kylo.io/alert/alert/sla/violation') { if(angular.isDefined(this.alertData.content)) { this.alertData.links.push({label: "Service Level Assessment", value: "service-level-assessment({assessmentId:'" + this.alertData.content + "'})"}); } this.alertData.links.push({label:"Service Level Agreement", value:"service-level-agreements({slaId:'"+this.alertData.entityId+"'})"}); } else if(this.alertData.type == 'http://kylo.io/alert/service') { this.alertData.links.push({label:"Service Details", value:"service-details({serviceName:'"+this.alertData.subtype+"'})"}); } }); } }; /** * Shows a dialog for adding a new event. * @param $event the event that triggered this dialog */ showEventDialog = ($event: any)=> { this.$mdDialog.show({ controller: 'EventDialogController', locals: { alert: this.alertData }, parent: angular.element(document.body), targetEvent: $event, templateUrl: "./event-dialog.html" }).then((result: any)=> { if (result) { this.loadAlert(this.alertData.id); } }); }; } export interface IMyScope extends ng.IScope { saving?: boolean; state?: string; closeDialog?: any; saveDialog?: any; description?: any; } /** * Manages the Update Alert dialog. * @constructor * @param $scope the Angular scope * @param $http * @param $mdDialog the dialog service * @param OpsManagerRestUrlService the REST URL service * @param alert the alert to update */ export class EventDialogController implements ng.IComponentController{ static readonly $inject=["$scope","$http","$mdDialog","OpsManagerRestUrlService","alert"]; constructor(private $scope: IMyScope, //the Angular scope private $http: angular.IHttpService, //the HTTP service private $mdDialog: angular.material.IDialogService, //the dialog service private OpsManagerRestUrlService: OpsManagerRestUrlService, //the REST URL service private alert: any //the alert to update ){ this.ngOnInit(); } ngOnInit(){ this.$scope.saving = false; //Indicates that this update is currently being saved {boolean} this.$scope.state = (this.alert.state === "HANDLED") ? "HANDLED" : "IN_PROGRESS"; //The new state for the alert{string} /** * Closes this dialog and discards any changes. */ this.$scope.closeDialog = ()=> { this.$mdDialog.hide(false); }; /** * Saves this update and closes this dialog. */ this.$scope.saveDialog = ()=> { this.$scope.saving = true; var event = {state: this.$scope.state, description: this.$scope.description, clear: false}; this.$http.post(this.OpsManagerRestUrlService.ALERT_DETAILS_URL(this.alert.id), event) .then(()=> { this.$mdDialog.hide(true); }, () =>{ this.$scope.saving = false; }); }; } } export class AlertDetailsController implements ng.IComponentController{ alertId: any; $transition$: Transition; constructor(){ this.ngOnInit(); } ngOnInit(){ this.alertId = this.$transition$.params().alertId; } } const module = angular.module(moduleName).component("alertDetailsController", { bindings: { $transition$: '<' }, controller: AlertDetailsController, controllerAs: "vm", templateUrl: "./alert-details.html" }); export default module; angular.module(moduleName).controller("alertDetailsDirectiveController", AlertDetailsDirectiveController, ); angular.module(moduleName).directive("tbaAlertDetails", [ ()=> { return { restrict: "EA", bindToController: { cardTitle: "@", alertId:"=" }, controllerAs: "vm", scope: true, templateUrl: "./alert-details-template.html", controller: AlertDetailsDirectiveController }; } ]); angular.module(moduleName).controller("EventDialogController", EventDialogController );
the_stack
import type { CSpellSettings, CustomDictionaryScope, DictionaryDefinitionCustom, DictionaryDefinitionPreferred, DictionaryId, FsPath, GlobDef, LanguageSetting, OverrideSettings, SimpleGlob, } from '@cspell/cspell-types'; export type { CustomDictionaryScope, DictionaryDefinition, DictionaryDefinitionCustom, DictionaryFileTypes, LanguageSetting, } from '@cspell/cspell-types'; export interface SpellCheckerSettings extends SpellCheckerShouldCheckDocSettings { /** * The limit in K-Characters to be checked in a file. * @scope resource * @default 500 */ checkLimit?: number; /** * @scope resource * @description Issues found by the spell checker are marked with a Diagnostic Severity Level. This affects the color of the squiggle. * @default "Information" * @enumDescriptions [ * "Report Spelling Issues as Errors", * "Report Spelling Issues as Warnings", * "Report Spelling Issues as Information", * "Report Spelling Issues as Hints, will not show up in Problems"] */ diagnosticLevel?: 'Error' | 'Warning' | 'Information' | 'Hint'; /** * Control which file schemas will be checked for spelling (VS Code must be restarted for this setting to take effect). * @markdownDescription * Control which file schemas will be checked for spelling (VS Code must be restarted for this setting to take effect). * * * Some schemas have special meaning like: * - `untitled` - Used for new documents that have not yet been saved * - `vscode-notebook-cell` - Used for validating segments of a Notebook. * @scope window * @default ["file", "gist", "sftp", "untitled", "vscode-notebook-cell"] */ allowedSchemas?: string[]; /** * Set the Debug Level for logging messages. * @scope window * @default "Error" * @enumDescriptions [ * "Do not log", * "Log only errors", * "Log errors and warnings", * "Log errors, warnings, and info", * "Log everything (noisy)"] */ logLevel?: 'None' | 'Error' | 'Warning' | 'Information' | 'Debug'; /** * Have the logs written to a file instead of to VS Code. * @scope window */ logFile?: string; /** * Display the spell checker status on the status bar. * @scope application * @default true */ showStatus?: boolean; /** * The side of the status bar to display the spell checker status. * @scope application * @default "Right" * @enumDescriptions [ * "Left Side of Statusbar", * "Right Side of Statusbar"] */ showStatusAlignment?: 'Left' | 'Right'; /** * @markdownDescription * Show CSpell in-document directives as you type. * * **Note:** VS Code must be restarted for this setting to take effect. * @scope language-overridable * @default false */ showAutocompleteSuggestions?: boolean; /** * Delay in ms after a document has changed before checking it for spelling errors. * @scope application * @default 50 */ spellCheckDelayMs?: number; /** * Use Rename when fixing spelling issues. * @scope language-overridable * @default true */ fixSpellingWithRenameProvider?: boolean; /** * Show Spell Checker actions in Editor Context Menu * @scope application * @default true */ showCommandsInEditorContextMenu?: boolean; /** * @title File Types to Check * @scope resource * @uniqueItems true * @markdownDescription * Enable / Disable checking file types (languageIds). * * These are in additional to the file types specified by `cSpell.enabledLanguageIds`. * To disable a language, prefix with `!` as in `!json`, * * * **Example: individual file types** * ``` * jsonc // enable checking for jsonc * !json // disable checking for json * kotlin // enable checking for kotlin * ``` * * * **Example: enable all file types** * ``` * * // enable checking for all file types * !json // except for json * ``` */ enableFiletypes?: EnableFileTypeId[]; /** * @title Check Only Enabled File Types * @scope resource * @default true * @markdownDescription * By default, the spell checker checks only enabled file types. Use `cSpell.enableFiletypes` * to turn on / off various file types. * * When this setting is `false`, all file types are checked except for the ones disabled by `cSpell.enableFiletypes`. * See `cSpell.enableFiletypes` on how to disable a file type. */ checkOnlyEnabledFileTypes?: boolean; /** * @title Workspace Root Folder Path * @scope resource * @markdownDescription * Define the path to the workspace root folder in a multi-root workspace. * By default it is the first folder. * * This is used to find the `cspell.json` file for the workspace. * * * **Example: use the `client` folder** * ``` * ${workspaceFolder:client} * ``` */ workspaceRootPath?: string; /** * @title Custom User Dictionaries * @scope application * @markdownDescription * Define custom dictionaries to be included by default for the user. * If `addWords` is `true` words will be added to this dictionary. * @deprecated true * @deprecationMessage - Use `customDictionaries` instead. */ customUserDictionaries?: CustomDictionaryEntry[]; /** * @title Custom Workspace Dictionaries * @scope resource * @markdownDescription * Define custom dictionaries to be included by default for the workspace. * If `addWords` is `true` words will be added to this dictionary. * @deprecated true * @deprecationMessage - Use `customDictionaries` instead. */ customWorkspaceDictionaries?: CustomDictionaryEntry[]; /** * @title Custom Folder Dictionaries * @scope resource * @markdownDescription * Define custom dictionaries to be included by default for the folder. * If `addWords` is `true` words will be added to this dictionary. * @deprecated true * @deprecationMessage - Use `customDictionaries` instead. */ customFolderDictionaries?: CustomDictionaryEntry[]; /** * @title Custom Dictionaries * @scope resource * @markdownDescription * Define custom dictionaries to be included by default. * If `addWords` is `true` words will be added to this dictionary. * * * **Example:** * * ```js * "cSpell.customDictionaries": { * "project-words": { * "name": "project-words", * "path": "${workspaceRoot}/project-words.txt", * "description": "Words used in this project", * "addWords": true * }, * "custom": true, // Enable the `custom` dictionary * "internal-terms": false // Disable the `internal-terms` dictionary * } * ``` */ customDictionaries?: CustomDictionaries; /** * @title Spell Check Only Workspace Files * @scope window * @markdownDescription * Only spell check files that are in the currently open workspace. * This same effect can be achieved using the `files` setting. * * * ```js * "cSpell.files": ["**"] * ``` * @default false */ spellCheckOnlyWorkspaceFiles?: boolean; /** * @scope resource * @markdownDescription * The type of menu used to display spelling suggestions. * @default "quickPick" * @enumDescriptions [ * "Suggestions will appear as a drop down at the top of the IDE. (Best choice for Vim Key Bindings)", * "Suggestions will appear inline near the word, inside the text editor."] */ suggestionMenuType?: 'quickPick' | 'quickFix'; /** * Show Regular Expression Explorer * @scope application * @default false */ 'experimental.enableRegexpView'?: boolean; } interface InternalSettings { /** * Map of known and enabled file types. * `true` - enabled * `false` - disabled * @hidden */ mapOfEnabledFileTypes?: Map<string, boolean>; } /** * @title Named dictionary to be enabled / disabled * @markdownDescription * - `true` - turn on the named dictionary * - `false` - turn off the named dictionary */ type EnableCustomDictionary = boolean; /** * @markdownDescription * Enable / Disable checking file types (languageIds). * To disable a language, prefix with `!` as in `!json`, * * * Example: * ``` * jsonc // enable checking for jsonc * !json // disable checking for json * kotlin // enable checking for kotlin * ``` * @pattern (^!*(?!\s)[\s\w_.\-]+$)|(^!*[*]$) * @patternErrorMessage "Allowed characters are `a-zA-Z`, `.`, `-`, `_` and space." */ type EnableFileTypeId = string; interface SpellCheckerShouldCheckDocSettings { /** * @markdownDescription * The maximum line length. * * * Block spell checking if lines are longer than the value given. * This is used to prevent spell checking generated files. * * * **Error Message:** _Lines are too long._ * * * @scope language-overridable * @default 10000 */ blockCheckingWhenLineLengthGreaterThan?: number; /** * @markdownDescription * The maximum length of a chunk of text without word breaks. * * * It is used to prevent spell checking of generated files. * * * A chunk is the characters between absolute word breaks. * Absolute word breaks match: `/[\s,{}[\]]/`, i.e. spaces or braces. * * * **Error Message:** _Maximum Word Length is Too High._ * * * If you are seeing this message, it means that the file contains a very long line * without many word breaks. * * @scope language-overridable * @default 500 */ blockCheckingWhenTextChunkSizeGreaterThan?: number; /** * @markdownDescription * The maximum average length of chunks of text without word breaks. * * * A chunk is the characters between absolute word breaks. * Absolute word breaks match: `/[\s,{}[\]]/` * * * **Error Message:** _Average Word Size is Too High._ * * * If you are seeing this message, it means that the file contains mostly long lines * without many word breaks. * * @scope language-overridable * @default 80 */ blockCheckingWhenAverageChunkSizeGreaterThan?: number; } export type CustomDictionaries = { [Name in DictionaryId]: EnableCustomDictionary | CustomDictionariesDictionary; }; export type CustomDictionaryEntry = CustomDictionary | DictionaryId; type OptionalField<T, K extends keyof T> = { [k in K]?: T[k] } & Omit<T, K>; /** * @title Custom Dictionary Entry * @markdownDescription * Define a custom dictionary to be included. */ export interface CustomDictionariesDictionary extends OptionalField<CustomDictionary, 'name'> {} export interface CustomDictionary { /** * @title Name of Dictionary * @markdownDescription * The reference name of the dictionary. * * * Example: `My Words` or `custom` * * * If they name matches a pre-defined dictionary, it will override the pre-defined dictionary. * If you use: `typescript` it will replace the built-in TypeScript dictionary. */ name: DictionaryId; /** * @title Description of the Dictionary * @markdownDescription * Optional: A human readable description. */ description?: string; /** * @title Optional Path to Dictionary Text File * @markdownDescription * Define the path to the dictionary text file. * * * **Note:** if path is `undefined` the `name`d dictionary is expected to be found * in the `dictionaryDefinitions`. * * * File Format: Each line in the file is considered a dictionary entry. * * * Case is preserved while leading and trailing space is removed. * * * The path should be absolute, or relative to the workspace. * * * **Example:** relative to User's folder * * ``` * ~/dictionaries/custom_dictionary.txt * ``` * * * **Example:** relative to the `client` folder in a multi-root workspace * * ``` * ${workspaceFolder:client}/build/custom_dictionary.txt * ``` * * * **Example:** relative to the current workspace folder in a single-root workspace * * **Note:** this might no as expected in a multi-root workspace since it is based upon the relative * workspace for the currently open file. * * ``` * ${workspaceFolder}/build/custom_dictionary.txt * ``` * * * **Example:** relative to the workspace folder in a single-root workspace or the first folder in * a multi-root workspace * * ``` * ./build/custom_dictionary.txt * ``` */ path?: FsPath; /** * @title Add Words to Dictionary * @markdownDescription * Indicate if this custom dictionary should be used to store added words. * @default false */ addWords?: boolean; /** * @title Scope of dictionary * @markdownDescription * Options are * - `user` - words that apply to all projects and workspaces * - `workspace` - words that apply to the entire workspace * - `folder` - words that apply to only a workspace folder */ scope?: CustomDictionaryScope | CustomDictionaryScope[]; } /** * @hidden */ type HiddenFsPath = FsPath; /** * CSpellSettingsPackageProperties are used to annotate CSpellSettings found in * the `package.json#contributes.configuration` */ interface CSpellSettingsPackageProperties extends CSpellSettings { /** * Enable / Disable the spell checker. * @scope resource * @default true */ enabled?: boolean; /** * @scope resource * @description * Current active spelling language. * Example: "en-GB" for British English * Example: "en,nl" to enable both English and Dutch * @default "en" */ language?: string; /** * @scope resource * @description * Controls the maximum number of spelling errors per document. * @default 100 */ maxNumberOfProblems?: number; /** * @scope resource * @description * Controls the number of suggestions shown. * @default 8 */ numSuggestions?: number; /** * @scope resource * @default 3 */ suggestionNumChanges?: CSpellSettings['suggestionNumChanges']; /** * @scope resource * @default 400 */ suggestionsTimeout?: CSpellSettings['suggestionsTimeout']; /** * @scope resource * @default 4 */ minWordLength?: number; /** * @scope resource * @default 5 */ maxDuplicateProblems?: number; /** * @title Enabled Language Ids * @scope resource * @description * @markdownDescription * Specify a list of file types to spell check. It is better to use `cSpell.enableFiletypes` to Enable / Disable checking files types. * @uniqueItems true * @default [ * "asciidoc", * "c", * "cpp", * "csharp", * "css", * "git-commit", * "go", * "graphql", * "handlebars", * "haskell", * "html", * "jade", * "java", * "javascript", * "javascriptreact", * "json", * "jsonc", * "jupyter", * "latex", * "less", * "markdown", * "php", * "plaintext", * "python", * "pug", * "restructuredtext", * "rust", * "scala", * "scss", * "swift", * "text", * "typescript", * "typescriptreact", * "vue", * "yaml", * "yml" * ] */ enabledLanguageIds?: string[]; /** * @scope resource */ import?: FsPath[] | HiddenFsPath; /** * @scope resource */ words?: string[]; /** * @scope resource */ userWords?: string[]; /** * A list of words to be ignored by the spell checker. * @scope resource */ ignoreWords?: string[]; /** * Glob patterns of files to be ignored. The patterns are relative to the `globRoot` of the configuration file that defines them. * @title Glob patterns of files to be ignored * @scope resource * @default [ * "package-lock.json", * "node_modules", * "vscode-extension", * ".git/objects", * ".vscode", * ".vscode-insiders" * ] */ ignorePaths?: (SimpleGlob | GlobDefX)[]; /** * @description * @markdownDescription * The root to use for glop patterns found in this configuration. * Default: The current workspace folder. * Use `globRoot` to define a different location. `globRoot` can be relative to the location of this configuration file. * Defining globRoot, does not impact imported configurations. * * Special Values: * * - `${workspaceFolder}` - Default - globs will be relative to the current workspace folder\n * - `${workspaceFolder:<name>}` - Where `<name>` is the name of the workspace folder. * * @scope resource */ globRoot?: CSpellSettings['globRoot']; /** * @description * @markdownDescription * Glob patterns of files to be checked. * Glob patterns are relative to the `globRoot` of the configuration file that defines them. * @scope resource */ files?: CSpellSettings['files']; /** * @scope resource */ flagWords?: string[]; /** * @scope resource */ patterns?: CSpellSettings['patterns']; /** * @scope resource */ includeRegExpList?: CSpellSettings['includeRegExpList']; // cspell:ignore mapsto venv /** * @scope resource * @description * @markdownDescription * List of regular expressions or Pattern names (defined in `cSpell.patterns`) to exclude from spell checking. * * - When using the VS Code Preferences UI, it is not necessary to escape the `\`, VS Code takes care of that. * - When editing the VS Code `settings.json` file, * it is necessary to escape `\`. * Each `\` becomes `\\`. * * The default regular expression flags are `gi`. Add `u` (`gui`), to enable Unicode. * * | VS Code UI | JSON | Description | * | :------------------ | :-------------------- | :------------------------------------------- | * | `/\\[a-z]+/gi` | `/\\\\[a-z]+/gi` | Exclude LaTeX command like `\mapsto` | * | `/\b[A-Z]{3,5}\b/g` | `/\\b[A-Z]{3,5}\\b/g` | Exclude full-caps acronyms of 3-5 length. | * | `CStyleComment` | `CStyleComment` | A built in pattern | */ ignoreRegExpList?: CSpellSettings['ignoreRegExpList']; /** * @scope resource * @default false * @description * @markdownDescription * Enable / Disable allowing word compounds. * - `true` means `arraylength` would be ok * - `false` means it would not pass. * * Note: this can also cause many misspelled words to seem correct. */ allowCompoundWords?: CSpellSettings['allowCompoundWords']; /** * @scope resource */ languageSettings?: CSpellSettings['languageSettings']; /** * @scope resource * @description * @markdownDescription * Optional list of dictionaries to use. * Each entry should match the name of the dictionary. * To remove a dictionary from the list add `!` before the name. * i.e. `!typescript` will turn off the dictionary with the name `typescript`. */ dictionaries?: CSpellSettings['dictionaries']; /** * @scope resource */ dictionaryDefinitions?: CSpellSettings['dictionaryDefinitions']; /** * @scope resource */ overrides?: CSpellSettings['overrides']; /** * @scope resource * @description * @markdownDescription * Determines if words must match case and accent rules. * * - `false` - Case is ignored and accents can be missing on the entire word. * Incorrect accents or partially missing accents will be marked as incorrect. * Note: Some languages like Portuguese have case sensitivity turned on by default. * You must use `languageSettings` to turn it off. * - `true` - Case and accents are enforced by default. */ caseSensitive?: CSpellSettings['caseSensitive']; /** * @hidden */ languageId?: CSpellSettings['languageId']; /** * @scope resource */ noConfigSearch?: CSpellSettings['noConfigSearch']; /** * @scope window * @default true */ useGitignore?: CSpellSettings['useGitignore']; /** * Hide this for now. * Need to resolve the roots and support substitution of workspace paths. * @hidden */ gitignoreRoot?: CSpellSettings['gitignoreRoot']; /** * @hidden */ pnpFiles?: CSpellSettings['pnpFiles']; /** * @scope resource */ usePnP?: CSpellSettings['usePnP']; /** * @hidden */ readonly?: CSpellSettings['readonly']; /** * @scope resource */ noSuggestDictionaries?: CSpellSettings['noSuggestDictionaries']; } /** * @hidden */ type GlobDefX = GlobDef; export interface CustomDictionaryWithScope extends CustomDictionary {} export interface CSpellUserSettings extends SpellCheckerSettings, CSpellSettingsPackageProperties, InternalSettings {} export type SpellCheckerSettingsProperties = keyof SpellCheckerSettings; export type SpellCheckerSettingsVSCodePropertyKeys = `cspell.${keyof CSpellUserSettings}`; type DictionaryDef = | Omit<DictionaryDefinitionPreferred, 'type' | 'useCompounds' | 'repMap'> | Omit<DictionaryDefinitionCustom, 'type' | 'useCompounds' | 'repMap'>; interface DictionaryDefinitions { /** * Define additional available dictionaries. * @scope resource */ dictionaryDefinitions?: DictionaryDef[]; } type LanguageSettingsReduced = Omit<LanguageSetting, 'local' | 'dictionaryDefinitions'> & DictionaryDefinitions; interface LanguageSettings { /** * Additional settings for individual programming languages and locales. * @scope resource */ languageSettings?: LanguageSettingsReduced[]; } type OverridesReduced = Omit<OverrideSettings, 'dictionaryDefinitions' | 'languageSettings'> & DictionaryDefinitions & LanguageSettings; interface Overrides { /** * Overrides to apply based upon the file path. * @scope resource */ overrides?: OverridesReduced[]; } type CSpellOmitFieldsFromExtensionContributesInPackageJson = | '$schema' | 'cache' | 'description' | 'enableGlobDot' // Might add this later | 'features' // add this back when they are in use. | 'gitignoreRoot' // Hide until implemented | 'failFast' | 'id' | 'languageId' | 'loadDefaultConfiguration' | 'name' | 'pnpFiles' | 'readonly' | 'reporters' | 'version'; export interface SpellCheckerSettingsVSCodeBase extends Omit< CSpellUserSettings, CSpellOmitFieldsFromExtensionContributesInPackageJson | 'dictionaryDefinitions' | 'languageSettings' | 'overrides' >, DictionaryDefinitions, LanguageSettings, Overrides {} export type AllSpellCheckerSettingsInVSCode = SpellCheckerSettingsVSCodeBase; type Prefix<T, P extends string> = { [K in keyof T as K extends string ? `${P}${K}` : K]: T[K]; }; type PrefixWithCspell<T> = Prefix<T, 'cSpell.'>; /** * @title Code Spell Checker * @order 0 */ type VSConfigRoot = PrefixWithCspell<_VSConfigRoot>; type _VSConfigRoot = Pick<SpellCheckerSettingsVSCodeBase, 'enabled'>; /** * @title Languages and Dictionaries * @order 1 */ type VSConfigLanguageAndDictionaries = PrefixWithCspell<_VSConfigLanguageAndDictionaries>; type _VSConfigLanguageAndDictionaries = Pick< SpellCheckerSettingsVSCodeBase, | 'caseSensitive' | 'customDictionaries' | 'dictionaries' | 'dictionaryDefinitions' | 'flagWords' | 'ignoreWords' | 'language' | 'languageSettings' | 'noSuggestDictionaries' | 'userWords' | 'words' >; /** * @title Reporting and Display * @order 2 */ type VSConfigReporting = PrefixWithCspell<_VSConfigReporting>; type _VSConfigReporting = Pick< SpellCheckerSettingsVSCodeBase, | 'diagnosticLevel' | 'fixSpellingWithRenameProvider' | 'logFile' | 'logLevel' | 'maxDuplicateProblems' | 'maxNumberOfProblems' | 'minWordLength' | 'numSuggestions' | 'showAutocompleteSuggestions' | 'showCommandsInEditorContextMenu' | 'showStatus' | 'showStatusAlignment' | 'suggestionMenuType' | 'suggestionNumChanges' >; /** * @title Performance * @order 4 */ type VSConfigPerf = PrefixWithCspell<_VSConfigPerf>; type _VSConfigPerf = Pick< SpellCheckerSettingsVSCodeBase, | 'blockCheckingWhenAverageChunkSizeGreaterThan' | 'blockCheckingWhenLineLengthGreaterThan' | 'blockCheckingWhenTextChunkSizeGreaterThan' | 'checkLimit' | 'spellCheckDelayMs' | 'suggestionsTimeout' >; /** * @title CSpell * @order 5 */ type VSConfigCSpell = PrefixWithCspell<_VSConfigCSpell>; type _VSConfigCSpell = Omit< SpellCheckerSettingsVSCodeBase, | keyof _VSConfigExperimental | keyof _VSConfigLanguageAndDictionaries | keyof _VSConfigLegacy | keyof _VSConfigPerf | keyof _VSConfigReporting | keyof _VSConfigRoot | keyof _VSConfigFilesAndFolders >; /** * @title Files, Folders, and Workspaces * @order 3 */ type VSConfigFilesAndFolders = PrefixWithCspell<_VSConfigFilesAndFolders>; type _VSConfigFilesAndFolders = Pick< SpellCheckerSettingsVSCodeBase, | 'allowedSchemas' | 'checkOnlyEnabledFileTypes' | 'enableFiletypes' | 'files' | 'globRoot' | 'ignorePaths' | 'import' | 'noConfigSearch' | 'spellCheckOnlyWorkspaceFiles' | 'useGitignore' | 'usePnP' | 'workspaceRootPath' >; /** * @title Legacy * @order 20 */ type VSConfigLegacy = PrefixWithCspell<_VSConfigLegacy>; type _VSConfigLegacy = Pick< SpellCheckerSettingsVSCodeBase, 'enabledLanguageIds' | 'allowCompoundWords' | 'customFolderDictionaries' | 'customUserDictionaries' | 'customWorkspaceDictionaries' >; /** * @title Experimental * @order 19 */ type VSConfigExperimental = PrefixWithCspell<_VSConfigExperimental>; type _VSConfigExperimental = Pick<SpellCheckerSettingsVSCodeBase, 'experimental.enableRegexpView'>; export type SpellCheckerSettingsVSCode = [ VSConfigRoot, VSConfigCSpell, VSConfigExperimental, VSConfigFilesAndFolders, VSConfigLanguageAndDictionaries, VSConfigLegacy, VSConfigPerf, VSConfigReporting ];
the_stack
import { AccessScopeExpression, BindingBehaviorExpression, CallScopeExpression, ExpressionKind, IsBindingBehavior, Scope, LifecycleFlags as LF, SetterObserver } from '@aurelia/runtime'; import { CallBinding, } from '@aurelia/runtime-html'; import { createObserverLocator, createScopeForTest, eachCartesianJoinFactory, assert, createContainer } from '@aurelia/testing'; describe.skip('CallBinding', function () { function createFixture(sourceExpression: IsBindingBehavior, target: any, targetProperty: string) { const container = createContainer(); // Note: used to be RuntimeConfiguration.createContainer, needs deps const observerLocator = createObserverLocator(container); const sut = new CallBinding(sourceExpression as any, target, targetProperty, observerLocator, container); return { sut, container, observerLocator }; } describe('$bind -> $bind', function () { const targetVariations: (() => [{foo?: string}, string])[] = [ () => [({}), `{}`], () => [({ fooz: () => { return; } }), `fooz:()=>{}`] ]; const propVariations: (() => [string, string])[] = [ () => ['fooz', `'fooz' `], () => ['barz', `'barz' `] ]; const exprVariations: (() => [IsBindingBehavior, string])[] = [ () => [new CallScopeExpression('theFunc', []), `theFunc()`], () => [new BindingBehaviorExpression(new CallScopeExpression('theFunc', []), 'debounce', []), `theFunc()`] ]; const scopeVariations: (() => [Scope, string])[] = [ () => [createScopeForTest({theFunc: () => { return; }}), `{theFunc:()=>{}} `] ]; const renewScopeVariations: (() => [boolean, string])[] = [ () => [true, `true`], () => [false, `false`] ]; const inputs: [typeof targetVariations, typeof propVariations, typeof exprVariations, typeof scopeVariations, typeof renewScopeVariations] = [targetVariations, propVariations, exprVariations, scopeVariations, renewScopeVariations]; eachCartesianJoinFactory(inputs, ([target, $1], [prop, $2], [expr, $3], [scope, $4], [renewScope, $5]) => { it(`$bind() target=${$1} prop=${$2} expr=${$3} scope=${$4} renewScope=${$5}`, function () { // - Arrange - const { sut, observerLocator } = createFixture(expr, target, prop); const flags = LF.none; const targetObserver = observerLocator.getObserver(target, prop); // massSpy(scope.bindingContext, 'theFunc'); // massSpy(sut, 'callSource'); // massSpy(targetObserver, 'setValue', 'getValue'); // massSpy(expr, 'evaluate', 'assign', 'connect'); (expr as any).$kind |= ExpressionKind.HasBind | ExpressionKind.HasUnbind; // expr['bind'] = spy(); // expr['unbind'] = spy(); // - Act - sut.$bind(flags, scope); // - Assert - // double check we have the correct target observer assert.strictEqual(sut.targetObserver, targetObserver, `sut.targetObserver`); assert.instanceOf(sut.targetObserver, SetterObserver, `sut.targetObserver`); // expect(expr.bind).to.have.been.calledOnce; // assert.deepStrictEqual( // expr.bind.calls, // [ // [flags, scope, sut], // ], // `expr.bind`, // ); // expect(targetObserver.setValue).to.have.been.calledOnce; // assert.strictEqual(lifecycle.flushCount, 0, `lifecycle.flushCount`); if (renewScope) { scope = { ...scope }; } // - Arrange - // massReset(scope.bindingContext); // massReset(sut); // massReset(targetObserver); // massReset(expr); // - Act - sut.$bind(flags, scope); // - Assert - assert.instanceOf(sut.targetObserver, SetterObserver, `sut.targetObserver`); assert.strictEqual(sut.targetObserver, targetObserver, `sut.targetObserver`); if (renewScope) { // called during $bind, then during $unbind, then during $bind again // expect(targetObserver.setValue).to.have.been.calledThrice; // expect(expr.unbind).to.have.been.calledOnce; // expect(expr.bind).to.have.been.calledOnce; // assert.deepStrictEqual( // expr.bind.calls, // [ // [flags, scope, sut], // ], // `expr.bind`, // ); } // assert.strictEqual(lifecycle.flushCount, 0, `lifecycle.flushCount`); }); } ); }); describe('$bind -> $unbind -> $unbind', function () { const targetVariations: (() => [{foo?: string}, string])[] = [ () => [({}), `{}`], () => [({ fooz: () => { return; } }), `fooz:()=>{}`] ]; const propVariations: (() => [string, string])[] = [ () => ['fooz', `'fooz' `], () => ['barz', `'barz' `] ]; const exprVariations: (() => [IsBindingBehavior, string])[] = [ () => [new CallScopeExpression('theFunc', []), `theFunc()`], () => [new BindingBehaviorExpression(new CallScopeExpression('theFunc', []), 'debounce', []), `theFunc()`] ]; const scopeVariations: (() => [Scope, string])[] = [ () => [createScopeForTest({theFunc: () => { return; }}), `{theFunc:()=>{}} `] ]; const inputs: [typeof targetVariations, typeof propVariations, typeof exprVariations, typeof scopeVariations] = [targetVariations, propVariations, exprVariations, scopeVariations]; eachCartesianJoinFactory(inputs, ([target, $1], [prop, $2], [expr, $3], [scope, $4]) => { it(`$bind() target=${$1} prop=${$2} expr=${$3} scope=${$4}`, function () { // - Arrange - const { sut, observerLocator } = createFixture(expr, target, prop); const flags = LF.none; const targetObserver = observerLocator.getObserver(target, prop); // massSpy(scope.bindingContext, 'theFunc'); // massSpy(sut, 'callSource'); // massSpy(targetObserver, 'setValue', 'getValue'); // massSpy(expr, 'evaluate', 'assign', 'connect'); (expr as any).$kind |= ExpressionKind.HasBind | ExpressionKind.HasUnbind; // expr['bind'] = spy(); // expr['unbind'] = spy(); // - Act - sut.$bind(flags, scope); // - Assert - // double check we have the correct target observer assert.strictEqual(sut.targetObserver, targetObserver, `sut.targetObserver`); assert.instanceOf(sut.targetObserver, SetterObserver, `sut.targetObserver`); // expect(expr.bind).to.have.been.calledOnce; // assert.deepStrictEqual( // expr.bind.calls, // [ // [flags, scope, sut], // ], // `expr.bind`, // ); // expect(targetObserver.setValue).to.have.been.calledOnce; // assert.strictEqual(lifecycle.flushCount, 0, `lifecycle.flushCount`); // - Arrange - // massReset(scope.bindingContext); // massReset(sut); // massReset(targetObserver); // massReset(expr); // - Act - sut.$unbind(flags); // - Assert - assert.instanceOf(sut.targetObserver, SetterObserver, `sut.targetObserver`); assert.strictEqual(sut.targetObserver, targetObserver, `sut.targetObserver`); // expect(expr.unbind).to.have.been.calledOnce; assert.strictEqual(target[prop], null, `target[prop]`); // assert.strictEqual(lifecycle.flushCount, 0, `lifecycle.flushCount`); // - Arrange - // massReset(scope.bindingContext); // massReset(sut); // massReset(targetObserver); // massReset(expr); // - Act - sut.$unbind(flags); // - Assert - assert.instanceOf(sut.targetObserver, SetterObserver, `sut.targetObserver`); assert.strictEqual(sut.targetObserver, targetObserver, `sut.targetObserver`); // assert.strictEqual(lifecycle.flushCount, 0, `lifecycle.flushCount`); // expect(expr.unbind).not.to.have.been.called; }); } ); }); describe('$bind -> call -> $unbind', function () { const targetVariations: (() => [{foo?: string}, string])[] = [ () => [({}), `{}`], () => [({ fooz: () => { return; } }), `fooz:()=>{}`] ]; const propVariations: (() => [string, string])[] = [ () => ['fooz', `'fooz' `], () => ['barz', `'barz' `] ]; const argsVariations: (() => [{}, string])[] = [ () => [{ arg1: 'asdf' }, `{} `], () => [{ arg2: 42 }, `{} `], () => [{ arg3: null }, `{} `], () => [{ arg3: ';lkasdf', arg1: {}, arg2: 42 }, `{} `] ]; const exprVariations: (() => [IsBindingBehavior, string])[] = [ () => [new CallScopeExpression('theFunc', []), `theFunc()`], () => [new CallScopeExpression('theFunc', [new AccessScopeExpression('arg1'), new AccessScopeExpression('arg2'), new AccessScopeExpression('arg3')]), `theFunc(arg1, arg2, arg3)`] ]; const scopeVariations: (() => [Scope, string])[] = [ () => [createScopeForTest({theFunc: () => { return; }}), `{theFunc:()=>{}} `] ]; const inputs: [typeof targetVariations, typeof propVariations, typeof argsVariations, typeof exprVariations, typeof scopeVariations] = [targetVariations, propVariations, argsVariations, exprVariations, scopeVariations]; eachCartesianJoinFactory(inputs, ([target, $1], [prop, $2], [args, $3], [expr, $4], [scope, $5]) => { it(`$bind() target=${$1} prop=${$2} args=${$3} expr=${$4} scope=${$5}`, function () { // - Arrange - const { sut, observerLocator } = createFixture(expr, target, prop); const flags = LF.none; const targetObserver = observerLocator.getObserver(target, prop); // massSpy(scope.bindingContext, 'theFunc'); // massSpy(sut, 'callSource'); // massSpy(targetObserver, 'setValue', 'getValue'); // massSpy(expr, 'evaluate', 'assign', 'connect'); // - Act - sut.$bind(flags, scope); // - Assert - // double check we have the correct target observer assert.strictEqual(sut.targetObserver, targetObserver, `sut.targetObserver`); assert.instanceOf(sut.targetObserver, SetterObserver, `sut.targetObserver`); // expect(targetObserver.setValue).to.have.been.calledOnce; // assert.strictEqual(lifecycle.flushCount, 0, `lifecycle.flushCount`); // - Arrange - // massReset(scope.bindingContext); // massReset(sut); // massReset(targetObserver); // massReset(expr); // massSpy(target, prop); // - Act - target[prop](args); // - Assert - // assert.deepStrictEqual((sut.callSource as SinonSpy).getCalls()[0].args[0], args, `(sut.callSource as SinonSpy).getCalls()[0].args[0]`); // expect(expr.evaluate).to.have.been.calledOnce; // expect(target[prop]).to.have.been.calledOnce; if (expr['args'].length === 3) { // expect(scope.bindingContext['theFunc']).to.have.been.calledWithExactly(args[expr['args'][0].name], args[expr['args'][1].name], args[expr['args'][2].name]); } else { // expect(scope.bindingContext['theFunc']).to.have.been.calledWithExactly(); } // - Arrange - // massRestore(scope.bindingContext); // massRestore(sut); // massRestore(targetObserver); // massRestore(expr); // - Act - sut.$unbind(flags); // - Assert - assert.strictEqual(target[prop], null, `target[prop]`); }); } ); }); });
the_stack
import { PropertyType, TextureChannel, vec3, vec4 } from '../constants'; import { GraphChild, Link } from '../graph/index'; import { GLTF } from '../types/gltf'; import { ColorUtils } from '../utils'; import { ExtensibleProperty } from './extensible-property'; import { COPY_IDENTITY } from './property'; import { TextureLink } from './property-links'; import { Texture } from './texture'; import { TextureInfo } from './texture-info'; const { R, G, B, A } = TextureChannel; /** * # Material * * *Materials describe a surface's appearance and response to light.* * * Each {@link Primitive} within a {@link Mesh} may be assigned a single Material. The number of * GPU draw calls typically increases with both the numbers of Primitives and of Materials in an * asset; Materials should be reused wherever possible. Techniques like texture atlasing and vertex * colors allow objects to have varied appearances while technically sharing a single Material. * * Material properties are modified by both scalars (like `baseColorFactor`) and textures (like * `baseColorTexture`). When both are available, factors are considered linear multipliers against * textures of the same name. In the case of base color, vertex colors (`COLOR_0` attributes) are * also multiplied. * * Textures containing color data (`baseColorTexture`, `emissiveTexture`) are sRGB. All other * textures are linear. Like other resources, textures should be reused when possible. * * Usage: * * ```typescript * const material = doc.createMaterial('myMaterial') * .setBaseColorFactor([1, 0.5, 0.5, 1]) // RGBA * .setOcclusionTexture(aoTexture) * .setOcclusionStrength(0.5); * * mesh.listPrimitives() * .forEach((prim) => prim.setMaterial(material)); * ``` * * @category Properties */ export class Material extends ExtensibleProperty { public readonly propertyType = PropertyType.MATERIAL; /********************************************************************************************** * Constants. */ public static AlphaMode: Record<string, GLTF.MaterialAlphaMode> = { /** * The alpha value is ignored and the rendered output is fully opaque */ OPAQUE: 'OPAQUE', /** * The rendered output is either fully opaque or fully transparent depending on the alpha * value and the specified alpha cutoff value */ MASK: 'MASK', /** * The alpha value is used to composite the source and destination areas. The rendered * output is combined with the background using the normal painting operation (i.e. the * Porter and Duff over operator) */ BLEND: 'BLEND', } /********************************************************************************************** * Instance. */ /** @internal Mode of the material's alpha channels. (`OPAQUE`, `BLEND`, or `MASK`) */ private _alphaMode: GLTF.MaterialAlphaMode = Material.AlphaMode.OPAQUE; /** @internal Visibility threshold. Applied only when `.alphaMode='MASK'`. */ private _alphaCutoff = 0.5; /** @internal When true, both sides of each triangle are rendered. May decrease performance. */ private _doubleSided = false; /** @internal Base color / albedo; linear multiplier. */ private _baseColorFactor: vec4 = [1, 1, 1, 1]; /** @internal Emissive color; linear multiplier. */ private _emissiveFactor: vec3 = [0, 0, 0]; /** @internal Normal (surface detail) factor; linear multiplier. Affects `.normalTexture`. */ private _normalScale = 1; /** @internal (Ambient) Occlusion factor; linear multiplier. Affects `.occlusionMap`. */ private _occlusionStrength = 1; /** * Roughness factor; linear multiplier. Affects roughness channel of * `metallicRoughnessTexture`. * @internal */ private _roughnessFactor = 1; /** * Metallic factor; linear multiplier. Affects metallic channel of * `metallicRoughnessTexture`. * @internal */ private _metallicFactor = 1; /** @internal Base color / albedo texture. */ @GraphChild private baseColorTexture: TextureLink | null = null; @GraphChild private baseColorTextureInfo: Link<this, TextureInfo> = this.graph.link('baseColorTextureInfo', this, new TextureInfo(this.graph)); /** @internal Emissive texture. */ @GraphChild private emissiveTexture: TextureLink | null = null; @GraphChild private emissiveTextureInfo: Link<this, TextureInfo> = this.graph.link('emissiveTextureInfo', this, new TextureInfo(this.graph)); /** * Normal (surface detail) texture. Normal maps often suffer artifacts with JPEG compression, * so PNG files are preferred. * @internal */ @GraphChild private normalTexture: TextureLink | null = null; @GraphChild private normalTextureInfo: Link<this, TextureInfo> = this.graph.link('normalTextureInfo', this, new TextureInfo(this.graph)); /** * (Ambient) Occlusion texture. Occlusion data is stored in the `.r` channel, allowing this * texture to be packed with `metallicRoughnessTexture`, optionally. * @internal */ @GraphChild private occlusionTexture: TextureLink | null = null; @GraphChild private occlusionTextureInfo: Link<this, TextureInfo> = this.graph.link('occlusionTextureInfo', this, new TextureInfo(this.graph)); /** * Metallic/roughness PBR texture. Roughness data is stored in the `.g` channel and metallic * data is stored in the `.b` channel, allowing thist exture to be packed with * `occlusionTexture`, optionally. * @internal */ @GraphChild private metallicRoughnessTexture: TextureLink | null = null; @GraphChild private metallicRoughnessTextureInfo: Link<this, TextureInfo> = this.graph.link('metallicRoughnessTextureInfo', this, new TextureInfo(this.graph)); public copy(other: this, resolve = COPY_IDENTITY): this { super.copy(other, resolve); this._alphaMode = other._alphaMode; this._alphaCutoff = other._alphaCutoff; this._doubleSided = other._doubleSided; this._baseColorFactor = [...other._baseColorFactor] as vec4; this._emissiveFactor = [...other._emissiveFactor] as vec3; this._normalScale = other._normalScale; this._occlusionStrength = other._occlusionStrength; this._roughnessFactor = other._roughnessFactor; this._metallicFactor = other._metallicFactor; this.setBaseColorTexture( other.baseColorTexture ? resolve(other.baseColorTexture.getChild()) : null ); this.baseColorTextureInfo.getChild() .copy(resolve(other.baseColorTextureInfo.getChild()), resolve); this.setEmissiveTexture( other.emissiveTexture ? resolve(other.emissiveTexture.getChild()) : null ); this.emissiveTextureInfo.getChild() .copy(resolve(other.emissiveTextureInfo.getChild()), resolve); this.setNormalTexture( other.normalTexture ? resolve(other.normalTexture.getChild()) : null ); this.normalTextureInfo.getChild() .copy(resolve(other.normalTextureInfo.getChild()), resolve); this.setOcclusionTexture( other.occlusionTexture ? resolve(other.occlusionTexture.getChild()) : null ); this.occlusionTextureInfo.getChild() .copy(resolve(other.occlusionTextureInfo.getChild()), resolve); this.setMetallicRoughnessTexture( other.metallicRoughnessTexture ? resolve(other.metallicRoughnessTexture.getChild()) : null ); this.metallicRoughnessTextureInfo.getChild() .copy(resolve(other.metallicRoughnessTextureInfo.getChild()), resolve); return this; } dispose(): void { // TextureInfo instances were created by this material, and should be disposed with it. this.baseColorTextureInfo.getChild().dispose(); this.emissiveTextureInfo.getChild().dispose(); this.normalTextureInfo.getChild().dispose(); this.occlusionTextureInfo.getChild().dispose(); this.metallicRoughnessTextureInfo.getChild().dispose(); super.dispose(); } /********************************************************************************************** * Double-sided / culling. */ /** Returns true when both sides of triangles should be rendered. May impact performance. */ public getDoubleSided(): boolean { return this._doubleSided; } /** Sets whether to render both sides of triangles. May impact performance. */ public setDoubleSided(doubleSided: boolean): this { this._doubleSided = doubleSided; return this; } /********************************************************************************************** * Alpha. */ /** Returns material alpha, equivalent to baseColorFactor[3]. */ public getAlpha(): number { return this._baseColorFactor[3]; } /** Sets material alpha, equivalent to baseColorFactor[3]. */ public setAlpha(alpha: number): this { this._baseColorFactor[3] = alpha; return this; } /** * Returns the mode of the material's alpha channels, which are provided by `baseColorFactor` * and `baseColorTexture`. * * - `OPAQUE`: Alpha value is ignored and the rendered output is fully opaque. * - `BLEND`: Alpha value is used to determine the transparency each pixel on a surface, and * the fraction of surface vs. background color in the final result. Alpha blending creates * significant edge cases in realtime renderers, and some care when structuring the model is * necessary for good results. In particular, transparent geometry should be kept in separate * meshes or primitives from opaque geometry. The `depthWrite` or `zWrite` settings in engines * should usually be disabled on transparent materials. * - `MASK`: Alpha value is compared against `alphaCutoff` threshold for each pixel on a * surface, and the pixel is either fully visible or fully discarded based on that cutoff. * This technique is useful for things like leafs/foliage, grass, fabric meshes, and other * surfaces where no semitransparency is needed. With a good choice of `alphaCutoff`, surfaces * that don't require semitransparency can avoid the performance penalties and visual issues * involved with `BLEND` transparency. * * Reference: * - [glTF → material.alphaMode](https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materialalphamode) */ public getAlphaMode(): GLTF.MaterialAlphaMode { return this._alphaMode; } /** Sets the mode of the material's alpha channels. See {@link getAlphaMode} for details. */ public setAlphaMode(alphaMode: GLTF.MaterialAlphaMode): this { this._alphaMode = alphaMode; return this; } /** Returns the visibility threshold; applied only when `.alphaMode='MASK'`. */ public getAlphaCutoff(): number { return this._alphaCutoff; } /** Sets the visibility threshold; applied only when `.alphaMode='MASK'`. */ public setAlphaCutoff(alphaCutoff: number): this { this._alphaCutoff = alphaCutoff; return this; } /********************************************************************************************** * Base color. */ /** Base color / albedo factor in linear space. See {@link getBaseColorTexture}. */ public getBaseColorFactor(): vec4 { return this._baseColorFactor; } /** Sets the base color / albedo factor in linear space. See {@link getBaseColorTexture}. */ public setBaseColorFactor(baseColorFactor: vec4): this { this._baseColorFactor = baseColorFactor; return this; } /** * Base color / albedo as hexadecimal in sRGB colorspace. Converted automatically from * baseColorFactor in linear space. See {@link getBaseColorTexture}. */ public getBaseColorHex(): number { return ColorUtils.factorToHex(this._baseColorFactor); } /** * Sets base color / albedo as hexadecimal in sRGB colorspace. Converted automatically to * baseColorFactor in linear space. See {@link getBaseColorTexture}. */ public setBaseColorHex(hex: number): this { ColorUtils.hexToFactor(hex, this._baseColorFactor); return this; } /** * Base color / albedo. The visible color of a non-metallic surface under constant ambient * light would be a linear combination (multiplication) of its vertex colors, base color * factor, and base color texture. Lighting, and reflections in metallic or smooth surfaces, * also effect the final color. The alpha (`.a`) channel of base color factors and textures * will have varying effects, based on the setting of {@link getAlphaMode}. * * Reference: * - [glTF → material.pbrMetallicRoughness.baseColorFactor](https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#pbrmetallicroughnessbasecolorfactor) */ public getBaseColorTexture(): Texture | null { return this.baseColorTexture ? this.baseColorTexture.getChild() : null; } /** * Settings affecting the material's use of its base color texture. If no texture is attached, * {@link TextureInfo} is `null`. */ public getBaseColorTextureInfo(): TextureInfo | null { return this.baseColorTexture ? this.baseColorTextureInfo.getChild() : null; } /** Sets base color / albedo texture. See {@link getBaseColorTexture}. */ public setBaseColorTexture(texture: Texture | null): this { this.baseColorTexture = this.graph.linkTexture('baseColorTexture', R | G | B | A, this, texture); return this; } /********************************************************************************************** * Emissive. */ /** Emissive color; linear multiplier. See {@link getEmissiveTexture}. */ public getEmissiveFactor(): vec3 { return this._emissiveFactor; } /** Sets the emissive color; linear multiplier. See {@link getEmissiveTexture}. */ public setEmissiveFactor(emissiveFactor: vec3): this { this._emissiveFactor = emissiveFactor; return this; } /** * Emissive as hexadecimal in sRGB colorspace. Converted automatically from * emissiveFactor in linear space. See {@link getBaseColorTexture}. */ public getEmissiveHex(): number { return ColorUtils.factorToHex(this._emissiveFactor); } /** * Sets emissive as hexadecimal in sRGB colorspace. Converted automatically to * emissiveFactor in linear space. See {@link getEmissiveTexture}. */ public setEmissiveHex(hex: number): this { ColorUtils.hexToFactor(hex, this._emissiveFactor); return this; } /** * Emissive texture. Emissive color is added to any base color of the material, after any * lighting/shadowing are applied. An emissive color does not inherently "glow", or affect * objects around it at all. To create that effect, most viewers must also enable a * post-processing effect called "bloom". * * Reference: * - [glTF → material.emissiveTexture](https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materialemissivetexture) */ public getEmissiveTexture(): Texture | null { return this.emissiveTexture ? this.emissiveTexture.getChild() : null; } /** * Settings affecting the material's use of its emissive texture. If no texture is attached, * {@link TextureInfo} is `null`. */ public getEmissiveTextureInfo(): TextureInfo | null { return this.emissiveTexture ? this.emissiveTextureInfo.getChild() : null; } /** Sets emissive texture. See {@link getEmissiveTexture}. */ public setEmissiveTexture(texture: Texture | null): this { this.emissiveTexture = this.graph.linkTexture('emissiveTexture', R | G | B, this, texture); return this; } /********************************************************************************************** * Normal. */ /** Normal (surface detail) factor; linear multiplier. Affects `.normalTexture`. */ public getNormalScale(): number { return this. _normalScale; } /** Sets normal (surface detail) factor; linear multiplier. Affects `.normalTexture`. */ public setNormalScale(normalScale: number): this { this._normalScale = normalScale; return this; } /** * Normal (surface detail) texture. * * A tangent space normal map. The texture contains RGB components in linear space. Each texel * represents the XYZ components of a normal vector in tangent space. Red [0 to 255] maps to X * [-1 to 1]. Green [0 to 255] maps to Y [-1 to 1]. Blue [128 to 255] maps to Z [1/255 to 1]. * The normal vectors use OpenGL conventions where +X is right and +Y is up. +Z points toward * the viewer. * * Reference: * - [glTF → material.normalTexture](https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materialnormaltexture) */ public getNormalTexture(): Texture | null { return this.normalTexture ? this.normalTexture.getChild() : null; } /** * Settings affecting the material's use of its normal texture. If no texture is attached, * {@link TextureInfo} is `null`. */ public getNormalTextureInfo(): TextureInfo | null { return this.normalTexture ? this.normalTextureInfo.getChild() : null; } /** Sets normal (surface detail) texture. See {@link getNormalTexture}. */ public setNormalTexture(texture: Texture | null): this { this.normalTexture = this.graph.linkTexture('normalTexture', R | G | B, this, texture); return this; } /********************************************************************************************** * Occlusion. */ /** (Ambient) Occlusion factor; linear multiplier. Affects `.occlusionTexture`. */ public getOcclusionStrength(): number { return this._occlusionStrength; } /** Sets (ambient) occlusion factor; linear multiplier. Affects `.occlusionTexture`. */ public setOcclusionStrength(occlusionStrength: number): this { this._occlusionStrength = occlusionStrength; return this; } /** * (Ambient) Occlusion texture, generally used for subtle 'baked' shadowing effects that are * independent of an object's position, such as shading in inset areas and corners. Direct * lighting is not affected by occlusion, so at least one indirect light source must be present * in the scene for occlusion effects to be visible. * * The occlusion values are sampled from the R channel. Higher values indicate areas that * should receive full indirect lighting and lower values indicate no indirect lighting. * * Reference: * - [glTF → material.occlusionTexture](https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materialocclusiontexture) */ public getOcclusionTexture(): Texture | null { return this.occlusionTexture ? this.occlusionTexture.getChild() : null; } /** * Settings affecting the material's use of its occlusion texture. If no texture is attached, * {@link TextureInfo} is `null`. */ public getOcclusionTextureInfo(): TextureInfo | null { return this.occlusionTexture ? this.occlusionTextureInfo.getChild() : null; } /** Sets (ambient) occlusion texture. See {@link getOcclusionTexture}. */ public setOcclusionTexture(texture: Texture | null): this { this.occlusionTexture = this.graph.linkTexture('occlusionTexture', R, this, texture); return this; } /********************************************************************************************** * Metallic / roughness. */ /** * Roughness factor; linear multiplier. Affects roughness channel of * `metallicRoughnessTexture`. See {@link getMetallicRoughnessTexture}. */ public getRoughnessFactor(): number { return this._roughnessFactor; } /** * Sets roughness factor; linear multiplier. Affects roughness channel of * `metallicRoughnessTexture`. See {@link getMetallicRoughnessTexture}. */ public setRoughnessFactor(roughnessFactor: number): this { this._roughnessFactor = roughnessFactor; return this; } /** * Metallic factor; linear multiplier. Affects roughness channel of * `metallicRoughnessTexture`. See {@link getMetallicRoughnessTexture}. */ public getMetallicFactor(): number { return this._metallicFactor; } /** * Sets metallic factor; linear multiplier. Affects roughness channel of * `metallicRoughnessTexture`. See {@link getMetallicRoughnessTexture}. */ public setMetallicFactor(metallicFactor: number): this { this._metallicFactor = metallicFactor; return this; } /** * Metallic roughness texture. The metalness values are sampled from the B channel. The * roughness values are sampled from the G channel. When a material is fully metallic, * or nearly so, it may require image-based lighting (i.e. an environment map) or global * illumination to appear well-lit. * * Reference: * - [glTF → material.pbrMetallicRoughness.metallicRoughnessTexture](https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#pbrmetallicroughnessmetallicroughnesstexture) */ public getMetallicRoughnessTexture(): Texture | null { return this.metallicRoughnessTexture ? this.metallicRoughnessTexture.getChild() : null; } /** * Settings affecting the material's use of its metallic/roughness texture. If no texture is * attached, {@link TextureInfo} is `null`. */ public getMetallicRoughnessTextureInfo(): TextureInfo | null { return this.metallicRoughnessTexture ? this.metallicRoughnessTextureInfo.getChild() : null; } /** Sets metallic/roughness texture. See {@link getMetallicRoughnessTexture}. */ public setMetallicRoughnessTexture(texture: Texture | null): this { this.metallicRoughnessTexture = this.graph.linkTexture('metallicRoughnessTexture', G | B, this, texture); return this; } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; /** * Provides a AWS Transfer Access resource. * * ## Example Usage * ### Basic S3 * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.transfer.Access("example", { * externalId: "S-1-1-12-1234567890-123456789-1234567890-1234", * serverId: aws_transfer_server.example.id, * role: aws_iam_role.example.arn, * homeDirectory: `/${aws_s3_bucket.example.id}/`, * }); * ``` * ### Basic EFS * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const test = new aws.transfer.Access("test", { * externalId: "S-1-1-12-1234567890-123456789-1234567890-1234", * serverId: aws_transfer_server.test.id, * role: aws_iam_role.test.arn, * homeDirectory: `/${aws_efs_file_system.test.id}/`, * posixProfile: { * gid: 1000, * uid: 1000, * }, * }); * ``` * * ## Import * * Transfer Accesses can be imported using the `server_id` and `external_id`, e.g. * * ```sh * $ pulumi import aws:transfer/access:Access example s-12345678/S-1-1-12-1234567890-123456789-1234567890-1234 * ``` */ export class Access extends pulumi.CustomResource { /** * Get an existing Access resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: AccessState, opts?: pulumi.CustomResourceOptions): Access { return new Access(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:transfer/access:Access'; /** * Returns true if the given object is an instance of Access. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Access { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Access.__pulumiType; } /** * The SID of a group in the directory connected to the Transfer Server (e.g. `S-1-1-12-1234567890-123456789-1234567890-1234`) */ public readonly externalId!: pulumi.Output<string>; /** * The landing directory (folder) for a user when they log in to the server using their SFTP client. It should begin with a `/`. The first item in the path is the name of the home bucket (accessible as `${Transfer:HomeBucket}` in the policy) and the rest is the home directory (accessible as `${Transfer:HomeDirectory}` in the policy). For example, `/example-bucket-1234/username` would set the home bucket to `example-bucket-1234` and the home directory to `username`. */ public readonly homeDirectory!: pulumi.Output<string | undefined>; /** * Logical directory mappings that specify what S3 paths and keys should be visible to your user and how you want to make them visible. See Home Directory Mappings below. */ public readonly homeDirectoryMappings!: pulumi.Output<outputs.transfer.AccessHomeDirectoryMapping[] | undefined>; /** * The type of landing directory (folder) you mapped for your users' home directory. Valid values are `PATH` and `LOGICAL`. */ public readonly homeDirectoryType!: pulumi.Output<string | undefined>; public readonly policy!: pulumi.Output<string | undefined>; /** * Specifies the full POSIX identity, including user ID (Uid), group ID (Gid), and any secondary groups IDs (SecondaryGids), that controls your users' access to your Amazon EFS file systems. See Posix Profile below. */ public readonly posixProfile!: pulumi.Output<outputs.transfer.AccessPosixProfile | undefined>; /** * Amazon Resource Name (ARN) of an IAM role that allows the service to controls your user’s access to your Amazon S3 bucket. */ public readonly role!: pulumi.Output<string | undefined>; /** * The Server ID of the Transfer Server (e.g. `s-12345678`) */ public readonly serverId!: pulumi.Output<string>; /** * Create a Access resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: AccessArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: AccessArgs | AccessState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as AccessState | undefined; inputs["externalId"] = state ? state.externalId : undefined; inputs["homeDirectory"] = state ? state.homeDirectory : undefined; inputs["homeDirectoryMappings"] = state ? state.homeDirectoryMappings : undefined; inputs["homeDirectoryType"] = state ? state.homeDirectoryType : undefined; inputs["policy"] = state ? state.policy : undefined; inputs["posixProfile"] = state ? state.posixProfile : undefined; inputs["role"] = state ? state.role : undefined; inputs["serverId"] = state ? state.serverId : undefined; } else { const args = argsOrState as AccessArgs | undefined; if ((!args || args.externalId === undefined) && !opts.urn) { throw new Error("Missing required property 'externalId'"); } if ((!args || args.serverId === undefined) && !opts.urn) { throw new Error("Missing required property 'serverId'"); } inputs["externalId"] = args ? args.externalId : undefined; inputs["homeDirectory"] = args ? args.homeDirectory : undefined; inputs["homeDirectoryMappings"] = args ? args.homeDirectoryMappings : undefined; inputs["homeDirectoryType"] = args ? args.homeDirectoryType : undefined; inputs["policy"] = args ? args.policy : undefined; inputs["posixProfile"] = args ? args.posixProfile : undefined; inputs["role"] = args ? args.role : undefined; inputs["serverId"] = args ? args.serverId : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Access.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Access resources. */ export interface AccessState { /** * The SID of a group in the directory connected to the Transfer Server (e.g. `S-1-1-12-1234567890-123456789-1234567890-1234`) */ externalId?: pulumi.Input<string>; /** * The landing directory (folder) for a user when they log in to the server using their SFTP client. It should begin with a `/`. The first item in the path is the name of the home bucket (accessible as `${Transfer:HomeBucket}` in the policy) and the rest is the home directory (accessible as `${Transfer:HomeDirectory}` in the policy). For example, `/example-bucket-1234/username` would set the home bucket to `example-bucket-1234` and the home directory to `username`. */ homeDirectory?: pulumi.Input<string>; /** * Logical directory mappings that specify what S3 paths and keys should be visible to your user and how you want to make them visible. See Home Directory Mappings below. */ homeDirectoryMappings?: pulumi.Input<pulumi.Input<inputs.transfer.AccessHomeDirectoryMapping>[]>; /** * The type of landing directory (folder) you mapped for your users' home directory. Valid values are `PATH` and `LOGICAL`. */ homeDirectoryType?: pulumi.Input<string>; policy?: pulumi.Input<string>; /** * Specifies the full POSIX identity, including user ID (Uid), group ID (Gid), and any secondary groups IDs (SecondaryGids), that controls your users' access to your Amazon EFS file systems. See Posix Profile below. */ posixProfile?: pulumi.Input<inputs.transfer.AccessPosixProfile>; /** * Amazon Resource Name (ARN) of an IAM role that allows the service to controls your user’s access to your Amazon S3 bucket. */ role?: pulumi.Input<string>; /** * The Server ID of the Transfer Server (e.g. `s-12345678`) */ serverId?: pulumi.Input<string>; } /** * The set of arguments for constructing a Access resource. */ export interface AccessArgs { /** * The SID of a group in the directory connected to the Transfer Server (e.g. `S-1-1-12-1234567890-123456789-1234567890-1234`) */ externalId: pulumi.Input<string>; /** * The landing directory (folder) for a user when they log in to the server using their SFTP client. It should begin with a `/`. The first item in the path is the name of the home bucket (accessible as `${Transfer:HomeBucket}` in the policy) and the rest is the home directory (accessible as `${Transfer:HomeDirectory}` in the policy). For example, `/example-bucket-1234/username` would set the home bucket to `example-bucket-1234` and the home directory to `username`. */ homeDirectory?: pulumi.Input<string>; /** * Logical directory mappings that specify what S3 paths and keys should be visible to your user and how you want to make them visible. See Home Directory Mappings below. */ homeDirectoryMappings?: pulumi.Input<pulumi.Input<inputs.transfer.AccessHomeDirectoryMapping>[]>; /** * The type of landing directory (folder) you mapped for your users' home directory. Valid values are `PATH` and `LOGICAL`. */ homeDirectoryType?: pulumi.Input<string>; policy?: pulumi.Input<string>; /** * Specifies the full POSIX identity, including user ID (Uid), group ID (Gid), and any secondary groups IDs (SecondaryGids), that controls your users' access to your Amazon EFS file systems. See Posix Profile below. */ posixProfile?: pulumi.Input<inputs.transfer.AccessPosixProfile>; /** * Amazon Resource Name (ARN) of an IAM role that allows the service to controls your user’s access to your Amazon S3 bucket. */ role?: pulumi.Input<string>; /** * The Server ID of the Transfer Server (e.g. `s-12345678`) */ serverId: pulumi.Input<string>; }
the_stack
import { BackendBreakpoint, Stack, Variable, VariableObject, MIError } from "./backend" import * as ChildProcess from "child_process" import { EventEmitter } from "events" import { parseMI, MINode } from './mi_parse'; import * as net from "net" import * as fs from "fs" import { posix } from "path" import * as nativePath from "path" let path = posix; export function escape(str: string) { return str.replace(/\\/g, "\\\\").replace(/"/g, "\\\""); } const nonOutput = /^(?:\d*|undefined)[\*\+\=]|[\~\@\&\^]/; const gdbMatch = /(?:\d*|undefined)\(gdb\)/; const numRegex = /\d+/; function couldBeOutput(line: string) { if (nonOutput.exec(line)) return false; return true; } const trace = false; enum ProcessState { Stopped, Running }; export class MI2 extends EventEmitter { constructor(public application: string, debug : boolean, public preargs: string[], public extraargs: string[], procEnv: any) { super(); this.debug = debug; if (procEnv) { var env = {}; // Duplicate process.env so we don't override it for (var key in process.env) if (process.env.hasOwnProperty(key)) env[key] = process.env[key]; // Overwrite with user specified variables for (var key in procEnv) { if (procEnv.hasOwnProperty(key)) { if (procEnv === null) delete env[key]; else env[key] = procEnv[key]; } } this.procEnv = env; } } load(cwd: string, target: string, procArgs: string): Thenable<any> { if (!nativePath.isAbsolute(target)) target = nativePath.join(cwd, target); return new Promise((resolve, reject) => { let startDebugArgs = this.debug ? ["--debug-mi"] : []; let args = startDebugArgs.concat(this.preargs).concat(this.extraargs || []).concat([target]); if (procArgs) args = args.concat(["--"]).concat(procArgs); this.log("log", "Current directory: " + cwd); const msg = this.debug ? "Running debugger: " : "Running: "; this.log("log", msg + this.application + " " + args.join(" ")); this.process = ChildProcess.spawn(this.application, args, { cwd: cwd, env: this.procEnv, shell: true }); this.process.stdout.setEncoding('utf-8'); this.process.stderr.setEncoding('utf-8'); this.process.stdout.on("data", this.stdout.bind(this)); this.process.stderr.on("data", this.stderr.bind(this)); this.process.on("exit", (() => { this.emit("quit"); this.process = null; }).bind(this)); this.process.on("error", ((err) => { this.emit("launcherror", err); }).bind(this)); this.emit("debug-ready"); resolve(this); }); } stdout(data) { if (trace) this.log("stderr", "stdout: " + data); this.buffer += data; let end = this.buffer.lastIndexOf('\n'); if (end != -1) { this.onOutput(this.buffer.substr(0, end)); this.buffer = this.buffer.substr(end + 1); } if (this.buffer.length) { if (this.onOutputPartial(this.buffer)) { this.buffer = ""; } } } stderr(data) { this.errbuf += data; let end = this.errbuf.lastIndexOf('\n'); if (end != -1) { this.onOutputStderr(this.errbuf.substr(0, end)); this.errbuf = this.errbuf.substr(end + 1); } if (this.errbuf.length) { this.logNoNewLine("stderr", this.errbuf); this.errbuf = ""; } } onOutputStderr(lines) { lines = <string[]>lines.split('\n'); lines.forEach(line => { this.log("stderr", line); }); } onOutputPartial(line) { if (couldBeOutput(line)) { this.logNoNewLine("stdout", line); return true; } return false; } onOutput(lines) { lines = <string[]>lines.split('\n'); lines.forEach(line => { if (!this.debug) { this.log("stdout", line); } else if (couldBeOutput(line)) { if (!gdbMatch.exec(line)) this.log("stdout", line); } else { if (this.debugOutput) this.log("log", "GDB -> App [raw]: " + line); let parsed = parseMI(line); if (this.debugOutput) this.log("log", "GDB -> App: " + JSON.stringify(parsed)); let handled = false; if (parsed.token !== undefined) { if (this.handlers[parsed.token]) { this.handlers[parsed.token](parsed); delete this.handlers[parsed.token]; handled = true; } } if (!handled && parsed.resultRecords && parsed.resultRecords.resultClass == "error") { this.log("stderr", parsed.result("msg") || line); } if (parsed.outOfBandRecord) { parsed.outOfBandRecord.forEach(record => { if (record.isStream) { if (this.debugOutput || record.type != "log") this.log(record.type, record.content); // detect program existed normally - flowcpp does not supply reason code if (record.type == "target" && record.content.trim() == "The program has exited") this.exitedNormallyReceived = true; // detect program interrupt - again, flowcpp does not supply reason code if (record.type == "console" && record.content.startsWith("Interrupt in")) this.interruptDetected = true; } else { if (record.type == "exec") { this.emit("exec-async-output", parsed); if (record.asyncClass == "running") { this.state = ProcessState.Running; this.emit("running", parsed); } else if (record.asyncClass == "stopped") { this.state = ProcessState.Stopped; let reason = parsed.record("reason"); // flowcpp does not return reason - assuming breakpoint-hit unless // there was 'exited normally' or 'interrupt' message before (see above) if (reason == undefined) { if (this.exitedNormallyReceived) reason = "exited-normally"; else if (this.interruptDetected) reason = "interrupt-stop"; else reason = "breakpoint-hit"; } this.exitedNormallyReceived = false; this.interruptDetected = false; if (trace) this.log("stderr", "stop: " + reason); if (reason == "breakpoint-hit") this.emit("breakpoint", parsed); else if (reason == "end-stepping-range") this.emit("step-end", parsed); else if (reason == "function-finished") this.emit("step-out-end", parsed); else if (reason == "signal-received") this.emit("signal-stop", parsed); else if (reason == "exited-normally") this.emit("exited-normally", parsed); else if (reason == "exited") { // exit with error code != 0 this.log("stderr", "Program exited with code " + parsed.record("exit-code")); this.emit("exited-normally", parsed); } else if (reason == "interrupt-stop") { // do nothing - this is done to stop, change breakpoints, restart the program }else { this.log("console", "Not implemented stop reason (assuming exception): " + reason); this.emit("stopped", parsed); } } else this.log("log", JSON.stringify(parsed)); } } }); handled = true; } if (parsed.token == undefined && parsed.resultRecords == undefined && parsed.outOfBandRecord.length == 0) handled = true; if (!handled) this.log("log", "Unhandled: " + JSON.stringify(parsed)); } }); } start(): Promise<boolean> { return new Promise((resolve, reject) => { this.once("ui-break-done", async () => { if (this.debug) { this.log("console", "Running executable"); let info = await this.sendCommand("exec-run"); resolve(info.resultRecords.resultClass == "running"); } else { resolve(true); } }); }); } stop() { if (this.process) { let proc = this.process; let to = setTimeout(() => { process.kill(-proc.pid); }, 1000); this.process.on("exit", function (code) { clearTimeout(to); }); if (this.debug) this.sendRaw("-gdb-exit"); } } async interrupt(): Promise<boolean> { if (trace) this.log("stderr", "interrupt"); let info = await this.sendCommand("exec-interrupt"); return info.resultRecords.resultClass == "done"; } async continue(): Promise<boolean> { if (trace) this.log("stderr", "continue"); let info = await this.sendCommand("exec-continue"); return info.resultRecords.resultClass == "running"; } async next(): Promise<boolean> { if (trace) this.log("stderr", "next"); let info = await this.sendCommand("exec-next"); return info.resultRecords.resultClass == "running"; } async step(): Promise<boolean> { if (trace) this.log("stderr", "step"); let info = await this.sendCommand("exec-step"); return info.resultRecords.resultClass == "running"; } async stepOut(): Promise<boolean> { if (trace) this.log("stderr", "stepOut"); let info = await this.sendCommand("exec-finish"); return info.resultRecords.resultClass == "running"; } changeVariable(name: string, rawValue: string): Thenable<any> { if (trace) this.log("stderr", "changeVariable"); return this.sendCommand("var-assign " + name + " " + rawValue); } loadBreakPoints(breakpoints: BackendBreakpoint[]): Thenable<[boolean, BackendBreakpoint][]> { if (trace) this.log("stderr", "loadBreakPoints"); let promisses = breakpoints.map(breakpoint => this.addBreakPoint(breakpoint)); return Promise.all(promisses); } setBreakPointCondition(bkptNum, condition): Thenable<any> { if (trace) this.log("stderr", "setBreakPointCondition"); return this.sendCommand("break-condition " + bkptNum + " " + condition); } async addBreakPoint(breakpoint: BackendBreakpoint): Promise<[boolean, BackendBreakpoint]> { if (trace) this.log("stderr", "addBreakPoint"); if (this.breakpoints.has(breakpoint)) return [false, undefined]; let location = ""; if (breakpoint.countCondition) { if (breakpoint.countCondition[0] == ">") location += "-i " + numRegex.exec(breakpoint.countCondition.substr(1))[0] + " "; else { let match = numRegex.exec(breakpoint.countCondition)[0]; if (match.length != breakpoint.countCondition.length) { this.log("stderr", "Unsupported break count expression: '" + breakpoint.countCondition + "'. Only supports 'X' for breaking once after X times or '>X' for ignoring the first X breaks"); location += "-t "; } else if (parseInt(match) != 0) location += "-t -i " + parseInt(match) + " "; } } if (breakpoint.raw) location += '"' + escape(breakpoint.raw) + '"'; else location += '"' + escape(breakpoint.file) + ":" + breakpoint.line + '"'; try { let result = await this.sendCommand("break-insert " + location); if (result.resultRecords.resultClass == "done") { let bkptNum = parseInt(result.result("bkpt.number")); let newBrk = { file: result.result("bkpt.file"), line: parseInt(result.result("bkpt.line")), condition: breakpoint.condition }; if (breakpoint.condition) { let result = await this.setBreakPointCondition(bkptNum, breakpoint.condition); if (result.resultRecords.resultClass == "done") { this.breakpoints.set(newBrk, bkptNum); return [true, newBrk]; } else { return [false, null]; } } else { this.breakpoints.set(newBrk, bkptNum); return [true, newBrk]; } } else return [false, undefined]; } catch (e) { this.log("stderr", "Error setting breakpoint: " + e); return [false, undefined]; } } async removeBreakPoint(breakpoint: BackendBreakpoint): Promise<boolean> { if (trace) this.log("stderr", "removeBreakPoint"); if (!this.breakpoints.has(breakpoint)) return false; let result = await this.sendCommand("break-delete " + this.breakpoints.get(breakpoint)); if (result.resultRecords.resultClass == "done") { this.breakpoints.delete(breakpoint); return true; } else return false; } async clearBreakPoints(): Promise<boolean> { if (trace) this.log("stderr", "clearBreakPoints"); if (this.isRunning()) // stop if we are running if (!await this.interrupt()) return false; let breakpointIndices = Array.from(this.breakpoints.values()); let result = await this.sendCommand("break-delete " + breakpointIndices.join(" ")); if (result.resultRecords.resultClass == "done") { this.breakpoints.clear(); return true; } else return false; } async getStack(maxLevels: number): Promise<Stack[]> { if (trace) this.log("stderr", "getStack"); let command = "stack-list-frames"; if (maxLevels) { command += " 0 " + maxLevels; } let result = await this.sendCommand(command); let stack = result.result("stack"); let ret: Stack[] = stack.map(element => { let level = MINode.valueOf(element, "@frame.level"); let addr = MINode.valueOf(element, "@frame.addr"); let func = MINode.valueOf(element, "@frame.func"); let filename = MINode.valueOf(element, "@frame.file"); let isEnd = filename == '--end--'; // marks end of stack, no source provided let file = MINode.valueOf(element, "@frame.fullname"); let line = 0; let lnstr = MINode.valueOf(element, "@frame.line"); if (lnstr) line = parseInt(lnstr); let from = parseInt(MINode.valueOf(element, "@frame.from")); let args = MINode.valueOf(element, "@frame.args"); return { address: addr, fileName: isEnd ? null : filename, file: isEnd ? null : file, function: func || from, level: level, line: line, args: args }; }); return ret; } async evalExpression(name: string): Promise<any> { if (trace) this.log("stderr", "evalExpression"); return this.sendCommand("data-evaluate-expression " + name); } async getVarAttrs(name: string): Promise<any> { if (trace) this.log("stderr", "getVarAttrs"); return this.sendCommand("var-show-attributes " + name); } async getStackVariables(thread: number, frame: number, argsOnly : boolean): Promise<Variable[]> { if (trace) this.log("stderr", "getStackVariables"); const selectRes = await this.sendCommand(`stack-select-frame ${frame}`); if (argsOnly) { const stackInfo = await this.sendCommand("stack-info-frame"); // args - they are returned with values, wrapping into Variable const argsRaw: any[] = MINode.valueOf(stackInfo.result("frame"), "args") || []; const args = argsRaw.map(a => ({name : MINode.valueOf(a, "name"), valueStr : MINode.valueOf(a, "value")})); return args; } else { const localsResult = await this.sendCommand("stack-list-locals"); const locals: any[] = localsResult.result("locals"); // locals - we only get names - but we do not actually need values const varNamesRaw: any = MINode.valueOf(locals, "name") || []; const varNames: string[] = typeof(varNamesRaw) == "string" ? [varNamesRaw] : varNamesRaw; return varNames.map(a => ({ name : a})); } } async varCreate(expression: string, frameNum : number, name: string = "-"): Promise<VariableObject> { if (trace) this.log("stderr", "varCreate"); const res = await this.sendCommand(`var-create ${name} ${frameNum} "${expression}"`); return new VariableObject(res.result("")); } async varListChildren(name: string): Promise<VariableObject[]> { if (trace) this.log("stderr", "varListChildren"); //TODO: add `from` and `to` arguments const res = await this.sendCommand(`var-list-children ${name}`); const children = res.result("children") || []; let omg: VariableObject[] = children.map(child => new VariableObject(child[1])); return omg; } async varUpdate(name: string = "*"): Promise<MINode> { if (trace) this.log("stderr", "varUpdate"); return this.sendCommand(`var-update --all-values ${name}`) } async varAssign(name: string, rawValue: string): Promise<MINode> { if (trace) this.log("stderr", "varAssign"); return this.sendCommand(`var-assign ${name} ${rawValue}`); } async varDelete(name: string): Promise<MINode> { if (trace) this.log("stderr", "varAssign"); return this.sendCommand(`var-delete ${name}`); } logNoNewLine(type: string, msg: string) { this.emit("msg", type, msg); } log(type: string, msg: string) { this.emit("msg", type, msg[msg.length - 1] == '\n' ? msg : (msg + "\n")); } sendUserInput(command: string): Thenable<any> { if (command.startsWith("-")) { return this.sendCommand(command.substr(1)); } else { this.sendRaw(command); return Promise.resolve(undefined); } } sendRaw(raw: string) { if (this.printCalls) this.log("log", raw); this.process.stdin.write(raw + "\n"); } sendCommand(command: string, suppressFailure: boolean = false): Thenable<MINode> { let sel = this.currentToken++; return new Promise((resolve, reject) => { this.handlers[sel] = (node: MINode) => { if (node && node.resultRecords && node.resultRecords.resultClass === "error") { if (suppressFailure) { this.log("stderr", `WARNING: Error executing command '${command}'`); resolve(node); } else reject(new MIError(node.result("msg") || "Internal error", command)); } else resolve(node); }; this.sendRaw(sel + "-" + command); }); } isReady(): boolean { return !!this.process; } isRunning(): boolean { return this.state == ProcessState.Running; } printCalls: boolean; debugOutput: boolean; public procEnv: any; protected currentToken: number = 1; protected handlers: { [index: number]: (info: MINode) => any } = {}; protected breakpoints: Map<BackendBreakpoint, Number> = new Map(); protected buffer: string = ""; protected errbuf: string = ""; protected process: ChildProcess.ChildProcess; protected stream; private exitedNormallyReceived: boolean = false; private interruptDetected: boolean = false; protected state: ProcessState = ProcessState.Stopped; protected debug: boolean; }
the_stack
* @module Serialization */ import { flatbuffers } from "flatbuffers"; import { BGFBAccessors } from "./BGFBAccessors"; import { CurvePrimitive } from "../curve/CurvePrimitive"; import { LineSegment3d } from "../curve/LineSegment3d"; import { Arc3d } from "../curve/Arc3d"; import { LineString3d } from "../curve/LineString3d"; import { GrowableXYZArray } from "../geometry3d/GrowableXYZArray"; import { IndexedPolyface } from "../polyface/Polyface"; import { CurveCollection } from "../curve/CurveCollection"; import { ParityRegion } from "../curve/ParityRegion"; import { Loop } from "../curve/Loop"; import { UnionRegion } from "../curve/UnionRegion"; import { Path } from "../curve/Path"; import { BSplineCurve3d } from "../bspline/BSplineCurve"; import { BSplineCurve3dH } from "../bspline/BSplineCurve3dH"; import { SolidPrimitive } from "../solid/SolidPrimitive"; import { Box } from "../solid/Box"; import { Sphere } from "../solid/Sphere"; import { LinearSweep } from "../solid/LinearSweep"; import { RotationalSweep } from "../solid/RotationalSweep"; import { RuledSweep } from "../solid/RuledSweep"; import { TorusPipe } from "../solid/TorusPipe"; import { Cone } from "../solid/Cone"; import { GeometryQuery } from "../curve/GeometryQuery"; import { BSplineSurface3d, BSplineSurface3dH, UVSelect } from "../bspline/BSplineSurface"; import { PointString3d } from "../curve/PointString3d"; import { Point3d, XYZ } from "../geometry3d/Point3dVector3d"; import { AuxChannel, AuxChannelData, PolyfaceAuxData } from "../polyface/AuxData"; import { TransitionSpiral3d } from "../curve/spiral/TransitionSpiral3d"; import { IntegratedSpiral3d } from "../curve/spiral/IntegratedSpiral3d"; import { DgnSpiralTypeQueries } from "./BGFBReader"; import { DirectSpiral3d } from "../curve/spiral/DirectSpiral3d"; import { TaggedNumericData } from "../polyface/TaggedNumericData"; import { InterpolationCurve3d } from "../bspline/InterpolationCurve3d"; import { AkimaCurve3d } from "../bspline/AkimaCurve3d"; /** * Context to write to a flatbuffer blob. * * This class is internal. * * Public access is through BentleyGeometryFlatBuffer.geometryToBytes() * @internal */ export class BGFBWriter { public builder: flatbuffers.Builder; public constructor(defaultSize: number = 1024) { this.builder = new flatbuffers.Builder(defaultSize); } /** * * @param data data source, as Float64Array or number[]. * @param count optional count, used only if less than .length numbers are to be written. */ public writeDoubleArray(data: Float64Array | number[] | undefined, count?: number): number { if (data === undefined) return 0; let numFloats = data.length; if (numFloats === 0) return 0; if (count !== undefined && count < numFloats) numFloats = count; this.builder.startVector(8, numFloats, 8); for (let i = numFloats - 1; i >= 0; i--) { this.builder.addFloat64(data[i]); } return this.builder.endVector(); } /** * * @param data data source, as Float64Array or number[]. * @param count optional count, used only if less than .length numbers are to be written. */ public writeIntArray(data: Int32Array | number[] | undefined): number { if (data === undefined) return 0; const numInt = data.length; if (numInt === 0) return 0; this.builder.startVector(4, numInt, 4); for (let i = numInt - 1; i >= 0; i--) { this.builder.addInt32(data[i]); } return this.builder.endVector(); } /** * * @param data data source, as array derived from XYZ. * The data is output as a flat array of 3*data.length numbers. */ public writePackedYZArray(data: XYZ[] | undefined): number { if (data === undefined) return 0; const numFloats = data.length * 3; if (numFloats === 0) return 0; this.builder.startVector(8, numFloats, 8); // write in reverse index order, and zyx within each XYZ for (let i = data.length - 1; i >= 0; i--) { this.builder.addFloat64(data[i].z); this.builder.addFloat64(data[i].y); this.builder.addFloat64(data[i].x); } return this.builder.endVector(); } public writeCurveCollectionAsFBCurveVector(cv: CurveCollection): number | undefined { const childrenOffsets: flatbuffers.Offset[] = []; for (const child of cv.children!) { if (child instanceof CurvePrimitive) { const childOffset = this.writeCurvePrimitiveAsFBVariantGeometry(child); if (childOffset) childrenOffsets.push(childOffset); } else if (child instanceof CurveCollection) { const childOffset = this.writeCurveCollectionAsFBVariantGeometry(child); if (childOffset) childrenOffsets.push(childOffset); } } const childrenVectorOffset = BGFBAccessors.CurveVector.createCurvesVector(this.builder, childrenOffsets); let cvType = 0; if (cv instanceof Path) cvType = 1; else if (cv instanceof Loop) { cvType = cv.isInner ? 3 : 2; } else if (cv instanceof ParityRegion) cvType = 4; else if (cv instanceof UnionRegion) cvType = 5; const curveVectorOffset = BGFBAccessors.CurveVector.createCurveVector(this.builder, cvType, childrenVectorOffset); return curveVectorOffset; } public writeCurveCollectionAsFBVariantGeometry(cv: CurveCollection): number | undefined { const curveVectorOffset = this.writeCurveCollectionAsFBCurveVector(cv); if (curveVectorOffset === undefined) return undefined; return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagCurveVector, curveVectorOffset, 0); } public writeInterpolationCurve3dAsFBVariantGeometry(curve: InterpolationCurve3d): number | undefined { const props = curve.cloneProps(); const fitPointsOffset = this.writeDoubleArray(curve.copyFitPointsFloat64Array()); const knotOffset = props.knots ? this.writeDoubleArray(props.knots) : 0; // REMARK: some native or flatbuffer quirk made startTangent a point and endTangent a vector. BGFBAccessors.InterpolationCurve.startInterpolationCurve(this.builder); BGFBAccessors.InterpolationCurve.addFitPoints(this.builder, fitPointsOffset); if (props.order) BGFBAccessors.InterpolationCurve.addOrder(this.builder, props.order); if (props.closed) BGFBAccessors.InterpolationCurve.addClosed(this.builder, props.closed); if (props.isChordLenKnots) BGFBAccessors.InterpolationCurve.addIsChordLenKnots(this.builder, props.isChordLenKnots); if (props.isColinearTangents) BGFBAccessors.InterpolationCurve.addIsColinearTangents(this.builder, props.isColinearTangents); if (props.isChordLenKnots) BGFBAccessors.InterpolationCurve.addIsChordLenKnots(this.builder, props.isChordLenKnots); if (props.isNaturalTangents) BGFBAccessors.InterpolationCurve.addIsNaturalTangents(this.builder, props.isNaturalTangents); if (props.startTangent !== undefined) { const startTangentOffset = BGFBAccessors.DPoint3d.createDPoint3d(this.builder, XYZ.x(props.startTangent), XYZ.y(props.startTangent), XYZ.z(props.startTangent)); BGFBAccessors.InterpolationCurve.addStartTangent(this.builder, startTangentOffset); } if (props.endTangent !== undefined) { const endTangentOffset = BGFBAccessors.DPoint3d.createDPoint3d(this.builder, XYZ.x(props.endTangent), XYZ.y(props.endTangent), XYZ.z(props.endTangent)); BGFBAccessors.InterpolationCurve.addEndTangent(this.builder, endTangentOffset); } if (knotOffset !== 0) BGFBAccessors.InterpolationCurve.addKnots(this.builder, knotOffset); const headerOffset = BGFBAccessors.InterpolationCurve.endInterpolationCurve(this.builder); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagInterpolationCurve, headerOffset, 0); } public writeAkimaCurve3dAsFBVariantGeometry(curve: AkimaCurve3d): number | undefined { const fitPointsOffset = this.writeDoubleArray(curve.copyFitPointsFloat64Array()); BGFBAccessors.AkimaCurve.startAkimaCurve(this.builder); BGFBAccessors.AkimaCurve.addPoints(this.builder, fitPointsOffset); const headerOffset = BGFBAccessors.AkimaCurve.endAkimaCurve(this.builder); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagAkimaCurve, headerOffset, 0); } public writeBsplineCurve3dAsFBVariantGeometry(bcurve: BSplineCurve3d): number | undefined { const order = bcurve.order; const closed = false; // typescript bcurves are not closed. There is API to impose wrapping . . . const weightsOffset = 0; const polesOffset = this.writeDoubleArray(bcurve.copyPointsFloat64Array()); if (polesOffset === undefined) return undefined; const knotsOffset = this.writeDoubleArray(bcurve.copyKnots(true)); const headerOffset = BGFBAccessors.BsplineCurve.createBsplineCurve(this.builder, order, closed, polesOffset, weightsOffset, knotsOffset); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagBsplineCurve, headerOffset, 0); } public writeBSplineSurfaceAsFBVariantGeometry(bsurf: BSplineSurface3d | BSplineSurface3dH): number | undefined { const orderU = bsurf.orderUV(UVSelect.uDirection); const orderV = bsurf.orderUV(UVSelect.VDirection); const numPolesU = bsurf.numPolesUV(UVSelect.uDirection); const numPolesV = bsurf.numPolesUV(UVSelect.VDirection); const closedU = false; const closedV = false; const holeOrigin = 0; const boundariesOffset = 0; let polesOffset = 0; let weightsOffset = 0; if (bsurf instanceof BSplineSurface3d) { polesOffset = this.writeDoubleArray(bsurf.copyPointsFloat64Array()); } else if (bsurf instanceof BSplineSurface3dH) { polesOffset = this.writeDoubleArray(bsurf.copyXYZToFloat64Array(false)); weightsOffset = this.writeDoubleArray(bsurf.copyWeightsToFloat64Array()); } const uKnotsOffset = this.writeDoubleArray(bsurf.knots[0].copyKnots(true)); const vKnotsOffset = this.writeDoubleArray(bsurf.knots[1].copyKnots(true)); const headerOffset = BGFBAccessors.BsplineSurface.createBsplineSurface(this.builder, polesOffset, weightsOffset, uKnotsOffset, vKnotsOffset, numPolesU, numPolesV, orderU, orderV, 0, 0, holeOrigin, boundariesOffset, closedU, closedV); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagBsplineSurface, headerOffset, 0); } public writeBsplineCurve3dAHsFBVariantGeometry(bcurve: BSplineCurve3dH): number | undefined { const order = bcurve.order; const closed = false; // typescript bcurves are not closed. There is API to impose wrapping . . . const polesOffset = this.writeDoubleArray(bcurve.copyXYZFloat64Array(false)); const weightsOffset = this.writeDoubleArray(bcurve.copyWeightsFloat64Array()); const knotsOffset = this.writeDoubleArray(bcurve.copyKnots(true)); const headerOffset = BGFBAccessors.BsplineCurve.createBsplineCurve(this.builder, order, closed, polesOffset, weightsOffset, knotsOffset); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagBsplineCurve, headerOffset, 0); } public writeCurvePrimitiveAsFBVariantGeometry(curvePrimitive: CurvePrimitive): number | undefined { if (curvePrimitive instanceof LineSegment3d) { const segmentDataOffset = BGFBAccessors.DSegment3d.createDSegment3d(this.builder, curvePrimitive.point0Ref.x, curvePrimitive.point0Ref.y, curvePrimitive.point0Ref.z, curvePrimitive.point1Ref.x, curvePrimitive.point1Ref.y, curvePrimitive.point1Ref.z); const lineSegmentOffset = BGFBAccessors.LineSegment.createLineSegment(this.builder, segmentDataOffset); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagLineSegment, lineSegmentOffset, 0); } else if (curvePrimitive instanceof Arc3d) { const data = curvePrimitive.toVectors(); const arcDataOffset = BGFBAccessors.DEllipse3d.createDEllipse3d(this.builder, data.center.x, data.center.y, data.center.z, data.vector0.x, data.vector0.y, data.vector0.z, data.vector90.x, data.vector90.y, data.vector90.z, data.sweep.startRadians, data.sweep.sweepRadians); const arcOffset = BGFBAccessors.EllipticArc.createEllipticArc(this.builder, arcDataOffset); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagEllipticArc, arcOffset, 0); } else if (curvePrimitive instanceof LineString3d) { const coordinates = extractNumberArray(curvePrimitive.packedPoints); const lineStringOffset = BGFBAccessors.LineString.createLineString(this.builder, BGFBAccessors.LineString.createPointsVector(this.builder, coordinates)); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagLineString, lineStringOffset, 0); } else if (curvePrimitive instanceof BSplineCurve3d) { return this.writeBsplineCurve3dAsFBVariantGeometry(curvePrimitive); } else if (curvePrimitive instanceof BSplineCurve3dH) { return this.writeBsplineCurve3dAHsFBVariantGeometry(curvePrimitive); } else if (curvePrimitive instanceof InterpolationCurve3d) { return this.writeInterpolationCurve3dAsFBVariantGeometry(curvePrimitive); } else if (curvePrimitive instanceof AkimaCurve3d) { return this.writeAkimaCurve3dAsFBVariantGeometry(curvePrimitive); } else if (curvePrimitive instanceof IntegratedSpiral3d) { const placement = curvePrimitive.localToWorld; const typeCode = DgnSpiralTypeQueries.stringToTypeCode(curvePrimitive.spiralType, true)!; const spiralDetailOffset = BGFBAccessors.TransitionSpiralDetail.createTransitionSpiralDetail(this.builder, placement.matrix.coffs[0], placement.matrix.coffs[1], placement.matrix.coffs[2], placement.origin.x, placement.matrix.coffs[3], placement.matrix.coffs[4], placement.matrix.coffs[5], placement.origin.y, placement.matrix.coffs[6], placement.matrix.coffs[5], placement.matrix.coffs[8], placement.origin.z, curvePrimitive.activeFractionInterval.x0, curvePrimitive.activeFractionInterval.x1, curvePrimitive.bearing01.startRadians, curvePrimitive.bearing01.endRadians, TransitionSpiral3d.radiusToCurvature(curvePrimitive.radius01.x0), TransitionSpiral3d.radiusToCurvature(curvePrimitive.radius01.x1), typeCode, 0); const transitionTableOffset = BGFBAccessors.TransitionSpiral.createTransitionSpiral(this.builder, spiralDetailOffset, 0, 0); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagTransitionSpiral, transitionTableOffset, 0); } else if (curvePrimitive instanceof DirectSpiral3d) { const placement = curvePrimitive.localToWorld; // direct spirals always inflect at the origin of the local frame .. // spiral const curvature0 = 0.0; const curvature1 = curvePrimitive.nominalCurvature1; const radius0 = 0.0; const radius1 = curvePrimitive.nominalR1; // which is 1/curvature1 const nominalLength = curvePrimitive.nominalL1; const bearing0Radians = 0.0; const bearing1Radians = TransitionSpiral3d.radiusRadiusLengthToSweepRadians(radius0, radius1, nominalLength); const typeCode = DgnSpiralTypeQueries.stringToTypeCode(curvePrimitive.spiralType, true)!; const spiralDetailOffset = BGFBAccessors.TransitionSpiralDetail.createTransitionSpiralDetail(this.builder, placement.matrix.coffs[0], placement.matrix.coffs[1], placement.matrix.coffs[2], placement.origin.x, placement.matrix.coffs[3], placement.matrix.coffs[4], placement.matrix.coffs[5], placement.origin.y, placement.matrix.coffs[6], placement.matrix.coffs[5], placement.matrix.coffs[8], placement.origin.z, curvePrimitive.activeFractionInterval.x0, curvePrimitive.activeFractionInterval.x1, bearing0Radians, bearing1Radians, curvature0, curvature1, typeCode, 0); const transitionTableOffset = BGFBAccessors.TransitionSpiral.createTransitionSpiral(this.builder, spiralDetailOffset, 0, 0); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagTransitionSpiral, transitionTableOffset, 0); } return undefined; } public writePointString3dAsFBVariantGeometry(pointString: PointString3d): number | undefined { if (pointString instanceof PointString3d) { const coordinates = extractNumberArray(pointString.points); const headerOffset = BGFBAccessors.PointString.createPointString(this.builder, BGFBAccessors.PointString.createPointsVector(this.builder, coordinates)); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagPointString, headerOffset, 0); } return undefined; } public writeSolidPrimitiveAsFBVariantGeometry(solid: SolidPrimitive): number | undefined { // NOTE: Box, Sphere, Cone, and TorusPipe have "detail" within a "table" // BUT: linear, rotational, and ruled sweeps have their contour and numerics directly within their table. if (solid instanceof Box) { const originA = solid.getBaseOrigin(); const originB = solid.getTopOrigin(); const vectorX = solid.getVectorX(); const vectorY = solid.getVectorY(); const baseX = solid.getBaseX(); const baseY = solid.getBaseY(); const topX = solid.getTopX(); const topY = solid.getTopY(); const detailOffset = BGFBAccessors.DgnBoxDetail.createDgnBoxDetail(this.builder, originA.x, originA.y, originA.z, originB.x, originB.y, originB.z, vectorX.x, vectorX.y, vectorX.z, vectorY.x, vectorY.y, vectorY.z, baseX, baseY, topX, topY, solid.capped); const carrierOffset = BGFBAccessors.DgnBox.createDgnBox(this.builder, detailOffset); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagDgnBox, carrierOffset, 0); } else if (solid instanceof Sphere) { const localToWorld = solid.cloneLocalToWorld(); const sweep = solid.cloneLatitudeSweep(); const detailOffset = BGFBAccessors.DgnSphereDetail.createDgnSphereDetail(this.builder, localToWorld.matrix.coffs[0], localToWorld.matrix.coffs[1], localToWorld.matrix.coffs[2], localToWorld.origin.x, localToWorld.matrix.coffs[3], localToWorld.matrix.coffs[4], localToWorld.matrix.coffs[5], localToWorld.origin.y, localToWorld.matrix.coffs[6], localToWorld.matrix.coffs[7], localToWorld.matrix.coffs[8], localToWorld.origin.z, sweep.startRadians, sweep.sweepRadians, solid.capped); const carrierOffset = BGFBAccessors.DgnSphere.createDgnSphere(this.builder, detailOffset); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagDgnSphere, carrierOffset, 0); } else if (solid instanceof Cone) { const centerA = solid.getCenterA(); const centerB = solid.getCenterB(); const vectorX = solid.getVectorX(); const vectorY = solid.getVectorY(); const radiusA = solid.getRadiusA(); const radiusB = solid.getRadiusB(); const detailOffset = BGFBAccessors.DgnConeDetail.createDgnConeDetail(this.builder, centerA.x, centerA.y, centerA.z, centerB.x, centerB.y, centerB.z, vectorX.x, vectorX.y, vectorX.z, vectorY.x, vectorY.y, vectorY.z, radiusA, radiusB, solid.capped); const carrierOffset = BGFBAccessors.DgnCone.createDgnCone(this.builder, detailOffset); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagDgnCone, carrierOffset, 0); } else if (solid instanceof TorusPipe) { const center = solid.cloneCenter(); const vectorX = solid.cloneVectorX(); const vectorY = solid.cloneVectorY(); const minorRadius = solid.getMinorRadius(); const majorRadius = solid.getMajorRadius(); const sweepRadians = solid.getSweepAngle().radians; const detailOffset = BGFBAccessors.DgnTorusPipeDetail.createDgnTorusPipeDetail(this.builder, center.x, center.y, center.z, vectorX.x, vectorX.y, vectorX.z, vectorY.x, vectorY.y, vectorY.z, majorRadius, minorRadius, sweepRadians, solid.capped); const carrierOffset = BGFBAccessors.DgnTorusPipe.createDgnTorusPipe(this.builder, detailOffset); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagDgnTorusPipe, carrierOffset, 0); } else if (solid instanceof LinearSweep) { const baseCurveOffset = this.writeCurveCollectionAsFBCurveVector(solid.getSweepContourRef().getCurves())!; const sweepVector = solid.cloneSweepVector(); // const sweepVectorOffset = BGFBAccessors.DVector3d.createDVector3d(this.builder, sweepVector.x, sweepVector.y, sweepVector.z); // const carrierOffset = BGFBAccessors.DgnExtrusion.createDgnExtrusion(this.builder, contourOffset, sweepVectorOffset, solid.capped); // WOW -- the machine generated createDgnExtrusion expects an offset for the sweepVector, but then // chokes trying to add it. BGFBAccessors.DgnExtrusion.startDgnExtrusion(this.builder); BGFBAccessors.DgnExtrusion.addBaseCurve(this.builder, baseCurveOffset); const extrusionVectorOffset = BGFBAccessors.DVector3d.createDVector3d(this.builder, sweepVector.x, sweepVector.y, sweepVector.z); BGFBAccessors.DgnExtrusion.addExtrusionVector(this.builder, extrusionVectorOffset); BGFBAccessors.DgnExtrusion.addCapped(this.builder, solid.capped); const dgnExtrusionOffset = BGFBAccessors.DgnExtrusion.endDgnExtrusion(this.builder); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagDgnExtrusion, dgnExtrusionOffset, 0); } else if (solid instanceof RotationalSweep) { const baseCurveOffset = this.writeCurveCollectionAsFBCurveVector(solid.getSweepContourRef().getCurves())!; const axis = solid.cloneAxisRay(); const sweepAngle = solid.getSweep(); // const sweepVectorOffset = BGFBAccessors.DVector3d.createDVector3d(this.builder, sweepVector.x, sweepVector.y, sweepVector.z); // const carrierOffset = BGFBAccessors.DgnExtrusion.createDgnExtrusion(this.builder, contourOffset, sweepVectorOffset, solid.capped); // WOW -- the machine generated createDgnExtrusion expects an offset for the sweepVector, but then // chokes trying to add it. BGFBAccessors.DgnRotationalSweep.startDgnRotationalSweep(this.builder); BGFBAccessors.DgnRotationalSweep.addBaseCurve(this.builder, baseCurveOffset); const axisRayOffset = BGFBAccessors.DRay3d.createDRay3d(this.builder, axis.origin.x, axis.origin.y, axis.origin.z, axis.direction.x, axis.direction.y, axis.direction.z); BGFBAccessors.DgnRotationalSweep.addAxis(this.builder, axisRayOffset); BGFBAccessors.DgnRotationalSweep.addSweepRadians(this.builder, sweepAngle.radians); BGFBAccessors.DgnRotationalSweep.addCapped(this.builder, solid.capped); const dgnRotationalSweepOffset = BGFBAccessors.DgnRotationalSweep.endDgnRotationalSweep(this.builder); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagDgnRotationalSweep, dgnRotationalSweepOffset, 0); } else if (solid instanceof RuledSweep) { const contours = solid.sweepContoursRef(); const contourOffsets: flatbuffers.Offset[] = []; for (const contour of contours) { const contourOffset = this.writeCurveCollectionAsFBCurveVector(contour.getCurves()); if (contourOffset !== undefined) contourOffsets.push(contourOffset); } const contoursVectorOffset = BGFBAccessors.DgnRuledSweep.createCurvesVector(this.builder, contourOffsets); const ruledSweepTable = BGFBAccessors.DgnRuledSweep.createDgnRuledSweep(this.builder, contoursVectorOffset, solid.capped); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagDgnRuledSweep, ruledSweepTable, 0); } return undefined; } public writePolyfaceAuxChannelDataAsFBVariantGeometry(channelData: AuxChannelData): number | undefined { if (channelData instanceof AuxChannelData) { const valuesOffset = BGFBAccessors.PolyfaceAuxChannelData.createValuesVector(this.builder, channelData.values); return BGFBAccessors.PolyfaceAuxChannelData.createPolyfaceAuxChannelData(this.builder, channelData.input, valuesOffset ); } return undefined; } public writePolyfaceAuxChannelAsFBVariantGeometry(channel: AuxChannel): number | undefined { if (channel instanceof AuxChannel) { const channelDataOffsets: number[] = []; for (const channelData of channel.data) { channelDataOffsets.push(this.writePolyfaceAuxChannelDataAsFBVariantGeometry(channelData)!); } const valuesOffset = BGFBAccessors.PolyfaceAuxChannel.createDataVector(this.builder, channelDataOffsets); const nameOffset = channel.name ? this.builder.createString(channel.name) : 0; const inputNameOffset = channel.inputName ? this.builder.createString(channel.inputName) : 0; return BGFBAccessors.PolyfaceAuxChannel.createPolyfaceAuxChannel(this.builder, channel.dataType, nameOffset, inputNameOffset, valuesOffset ); } return undefined; } public writePolyfaceAuxDataAsFBVariantGeometry(data: PolyfaceAuxData): number | undefined { if (data instanceof PolyfaceAuxData) { const channelOffsets: number[] = []; for (const channel of data.channels) { channelOffsets.push(this.writePolyfaceAuxChannelAsFBVariantGeometry(channel)!); } const channelOffsetsOffset = BGFBAccessors.PolyfaceAuxChannel.createDataVector(this.builder, channelOffsets); const indicesOffset = BGFBAccessors.PolyfaceAuxData.createIndicesVector(this.builder, data.indices); return BGFBAccessors.PolyfaceAuxData.createPolyfaceAuxData(this.builder, indicesOffset, channelOffsetsOffset ); } return undefined; } public writeTaggedNumericDataArray(data: TaggedNumericData | undefined): number { if (data){ const intDataOffset = this.writeIntArray(data.intData); const doubleDataOffset = this.writeDoubleArray(data.doubleData); return BGFBAccessors.TaggedNumericData.createTaggedNumericData(this.builder, data.tagA, data.tagB, intDataOffset, doubleDataOffset); } return 0; } public writePolyfaceAsFBVariantGeometry(mesh: IndexedPolyface): number | undefined { if (mesh instanceof IndexedPolyface) { // WE KNOW . . . . the polyface has blocks of zero-based indices. const indexArray: number[] = []; // and this will really be integers. const numberArray: number[] = []; // and this will really be doubles. copyToPackedNumberArray(numberArray, mesh.data.point.float64Data(), mesh.data.point.float64Length); const pointOffset = BGFBAccessors.Polyface.createPointVector(this.builder, numberArray); let paramIndexOffset = 0; let normalIndexOffset = 0; let colorIndexOffset = 0; let intColorOffset = 0; let normalOffset = 0; let paramOffset = 0; let auxDataOffset = 0; let taggedNumericDataOffset = 0; const meshStyle = 1; // That is . . . MESH_ELM_STYLE_INDEXED_FACE_LOOPS (and specifically, variable size with with 0 terminators) const numPerFace = 0; this.fillOneBasedIndexArray(mesh, mesh.data.pointIndex, mesh.data.edgeVisible, 0, indexArray); const twoSided = mesh.twoSided; const pointIndexOffset = BGFBAccessors.Polyface.createPointIndexVector(this.builder, indexArray); if (mesh.data.paramIndex !== undefined && mesh.data.paramIndex.length > 0) { this.fillOneBasedIndexArray(mesh, mesh.data.paramIndex, undefined, 0, indexArray); paramIndexOffset = BGFBAccessors.Polyface.createParamIndexVector(this.builder, indexArray); } if (mesh.data.normalIndex !== undefined && mesh.data.normalIndex.length > 0) { this.fillOneBasedIndexArray(mesh, mesh.data.normalIndex, undefined, 0, indexArray); normalIndexOffset = BGFBAccessors.Polyface.createNormalIndexVector(this.builder, indexArray); } if (mesh.data.colorIndex !== undefined && mesh.data.colorIndex.length > 0) { this.fillOneBasedIndexArray(mesh, mesh.data.colorIndex, undefined, 0, indexArray); colorIndexOffset = BGFBAccessors.Polyface.createColorIndexVector(this.builder, indexArray); } if (mesh.data.color !== undefined && mesh.data.color.length > 0) { intColorOffset = BGFBAccessors.Polyface.createIntColorVector(this.builder, mesh.data.color); } /* if (mesh.data.face !== undefined && mesh.data.face.length > 0) { this.writeOneBasedIndexArray(mesh, mesh.data.face, undefined, 0, indexArray); BGFBAccessors.Polyface.createFaceDataVector(this.builder, indexArray); } */ if (mesh.data.normal) { copyToPackedNumberArray(numberArray, mesh.data.normal.float64Data(), mesh.data.normal.float64Length); normalOffset = BGFBAccessors.Polyface.createNormalVector(this.builder, numberArray); } if (mesh.data.param) { copyToPackedNumberArray(numberArray, mesh.data.param.float64Data(), mesh.data.param.float64Length); paramOffset = BGFBAccessors.Polyface.createPointVector(this.builder, numberArray); } if (mesh.data.auxData) { auxDataOffset = this.writePolyfaceAuxDataAsFBVariantGeometry(mesh.data.auxData)!; } if (mesh.data.taggedNumericData) taggedNumericDataOffset = this.writeTaggedNumericDataArray(mesh.data.taggedNumericData); const expectedClosure = mesh.expectedClosure; const polyfaceOffset = BGFBAccessors.Polyface.createPolyface(this.builder, pointOffset, paramOffset, normalOffset, 0, intColorOffset, pointIndexOffset, paramIndexOffset, normalIndexOffset, colorIndexOffset, 0, 0, 0, meshStyle, twoSided, numPerFace, 0, auxDataOffset, expectedClosure, taggedNumericDataOffset); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagPolyface, polyfaceOffset, 0); } return undefined; } public fillOneBasedIndexArray(mesh: IndexedPolyface, sourceIndex: number[], visible: boolean[] | undefined, facetTerminator: number | undefined, destIndex: number[]) { destIndex.length = 0; const numFacet = mesh.facetCount; for (let facetIndex = 0; facetIndex < numFacet; facetIndex++) { const k0 = mesh.facetIndex0(facetIndex); const k1 = mesh.facetIndex1(facetIndex); for (let k = k0; k < k1; k++) { let q = sourceIndex[k] + 1; if (visible !== undefined && !visible[k]) q = -q; destIndex.push(q); } if (facetTerminator !== undefined) destIndex.push(facetTerminator); } } public writeGeometryQueryAsFBVariantGeometry(g: GeometryQuery): number | undefined { let offset: number | undefined; if (g instanceof CurvePrimitive && (offset = this.writeCurvePrimitiveAsFBVariantGeometry(g)) !== undefined) return offset; if (g instanceof CurveCollection && (offset = this.writeCurveCollectionAsFBVariantGeometry(g)) !== undefined) return offset; if (g instanceof IndexedPolyface && (offset = this.writePolyfaceAsFBVariantGeometry(g)) !== undefined) return offset; if (g instanceof SolidPrimitive && (offset = this.writeSolidPrimitiveAsFBVariantGeometry(g)) !== undefined) return offset; if (g instanceof BSplineSurface3d && (offset = this.writeBSplineSurfaceAsFBVariantGeometry(g)) !== undefined) return offset; if (g instanceof BSplineSurface3dH && (offset = this.writeBSplineSurfaceAsFBVariantGeometry(g)) !== undefined) return offset; if (g instanceof PointString3d && (offset = this.writePointString3dAsFBVariantGeometry(g)) !== undefined) return offset; return undefined; } public writeGeometryQueryArrayAsFBVariantGeometry(allGeometry: GeometryQuery | GeometryQuery[] | undefined): number | undefined{ if (Array.isArray(allGeometry)) { const allOffsets: number[] = []; for (const g of allGeometry) { const offset = this.writeGeometryQueryAsFBVariantGeometry(g); if (offset !== undefined) allOffsets.push(offset); } if (allOffsets.length > 0) { const membersOffset = BGFBAccessors.VectorOfVariantGeometry.createMembersVector(this.builder, allOffsets); const vectorOffset = BGFBAccessors.VectorOfVariantGeometry.createVectorOfVariantGeometry(this.builder, membersOffset); return BGFBAccessors.VariantGeometry.createVariantGeometry(this.builder, BGFBAccessors.VariantGeometryUnion.tagVectorOfVariantGeometry, vectorOffset, 0); } } else if (allGeometry instanceof GeometryQuery) return this.writeGeometryQueryAsFBVariantGeometry(allGeometry); return undefined; } /** * Serialize bytes to a flatbuffer. */ public static geometryToBytes(data: GeometryQuery | GeometryQuery[], signatureBytes?: Uint8Array): Uint8Array | undefined { const writer = new BGFBWriter(); const rootOffset = writer.writeGeometryQueryArrayAsFBVariantGeometry(data); if (rootOffset !== undefined) { const builder = writer.builder; builder.finish(rootOffset); const buffer = builder.dataBuffer(); if (!signatureBytes) { return buffer.bytes().slice(buffer.position()); } else if (buffer.position() >= signatureBytes.length) { // The buffer has space for the signature ahead of its position . . . const i0 = buffer.position() - signatureBytes.length; let i = i0; for (const k of signatureBytes) buffer.bytes()[i++] = k; return buffer.bytes().slice(i0); } else { // There is no space ahead of the position () . . . // coverage remark: I have never seen this happen for real. // It has been exercised by adding 1024 to the signatureBytes.length test to force this branch. const num1 = buffer.bytes().length - buffer.position(); const num0 = signatureBytes.length; const newBytes = new Uint8Array(num0 + num1); newBytes.set(signatureBytes, 0); newBytes.set(buffer.bytes().slice(buffer.position()), num0); return newBytes; } } return undefined; } } function extractNumberArray(data: GrowableXYZArray | Point3d[]): number[] { const result = []; if (data instanceof GrowableXYZArray) { // ugh -- accessors only deal with number[] .. const numCoordinate = 3 * data.length; const source = data.float64Data(); for (let i = 0; i < numCoordinate; i++) result.push(source[i]); return result; } else if (Array.isArray(data)) { for (const xyz of data) result.push(xyz.x, xyz.y, xyz.z); } return result; } /** Copy the active data to a simple number array. */ function copyToPackedNumberArray(dest: number[], source: Float64Array, count: number) { dest.length = 0; for (let i = 0; i < count; i++) dest.push(source[i]); }
the_stack
import {bindAll, extend, warnOnce, clamp, wrap, ease as defaultEasing, pick} from '../util/util'; import {number as interpolate} from '../style-spec/util/interpolate'; import browser from '../util/browser'; import LngLat from '../geo/lng_lat'; import LngLatBounds from '../geo/lng_lat_bounds'; import Point, {PointLike} from '../util/point'; import {Event, Evented} from '../util/evented'; import assert from 'assert'; import {Debug} from '../util/debug'; import type Transform from '../geo/transform'; import type {LngLatLike} from '../geo/lng_lat'; import type {LngLatBoundsLike} from '../geo/lng_lat_bounds'; import type {TaskID} from '../util/task_queue'; import type {PaddingOptions} from '../geo/edge_insets'; /** * Options common to {@link Map#jumpTo}, {@link Map#easeTo}, and {@link Map#flyTo}, controlling the desired location, * zoom, bearing, and pitch of the camera. All properties are optional, and when a property is omitted, the current * camera value for that property will remain unchanged. * * @typedef {Object} CameraOptions * @property {LngLatLike} center The desired center. * @property {number} zoom The desired zoom level. * @property {number} bearing The desired bearing in degrees. The bearing is the compass direction that * is "up". For example, `bearing: 90` orients the map so that east is up. * @property {number} pitch The desired pitch in degrees. The pitch is the angle towards the horizon * measured in degrees with a range between 0 and 60 degrees. For example, pitch: 0 provides the appearance * of looking straight down at the map, while pitch: 60 tilts the user's perspective towards the horizon. * Increasing the pitch value is often used to display 3D objects. * @property {LngLatLike} around If `zoom` is specified, `around` determines the point around which the zoom is centered. * @property {PaddingOptions} padding Dimensions in pixels applied on each side of the viewport for shifting the vanishing point. * @example * // set the map's initial perspective with CameraOptions * var map = new maplibregl.Map({ * container: 'map', * style: 'mapbox://styles/mapbox/streets-v11', * center: [-73.5804, 45.53483], * pitch: 60, * bearing: -60, * zoom: 10 * }); * @see [Set pitch and bearing](https://maplibre.org/maplibre-gl-js-docs/example/set-perspective/) * @see [Jump to a series of locations](https://maplibre.org/maplibre-gl-js-docs/example/jump-to/) * @see [Fly to a location](https://maplibre.org/maplibre-gl-js-docs/example/flyto/) * @see [Display buildings in 3D](https://maplibre.org/maplibre-gl-js-docs/example/3d-buildings/) */ export type CameraOptions = { center?: LngLatLike; zoom?: number; bearing?: number; pitch?: number; around?: LngLatLike; padding?: PaddingOptions; maxZoom?: number; offset?: PointLike; }; /** * Options common to map movement methods that involve animation, such as {@link Map#panBy} and * {@link Map#easeTo}, controlling the duration and easing function of the animation. All properties * are optional. * * @typedef {Object} AnimationOptions * @property {number} duration The animation's duration, measured in milliseconds. * @property {Function} easing A function taking a time in the range 0..1 and returning a number where 0 is * the initial state and 1 is the final state. * @property {PointLike} offset of the target center relative to real map container center at the end of animation. * @property {boolean} animate If `false`, no animation will occur. * @property {boolean} essential If `true`, then the animation is considered essential and will not be affected by * [`prefers-reduced-motion`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion). */ export type AnimationOptions = { duration?: number; easing?: (_: number) => number; offset?: PointLike; animate?: boolean; essential?: boolean; }; /** * Options for setting padding on calls to methods such as {@link Map#fitBounds}, {@link Map#fitScreenCoordinates}, and {@link Map#setPadding}. Adjust these options to set the amount of padding in pixels added to the edges of the canvas. Set a uniform padding on all edges or individual values for each edge. All properties of this object must be * non-negative integers. * * @typedef {Object} PaddingOptions * @property {number} top Padding in pixels from the top of the map canvas. * @property {number} bottom Padding in pixels from the bottom of the map canvas. * @property {number} left Padding in pixels from the left of the map canvas. * @property {number} right Padding in pixels from the right of the map canvas. * * @example * var bbox = [[-79, 43], [-73, 45]]; * map.fitBounds(bbox, { * padding: {top: 10, bottom:25, left: 15, right: 5} * }); * * @example * var bbox = [[-79, 43], [-73, 45]]; * map.fitBounds(bbox, { * padding: 20 * }); * @see [Fit to the bounds of a LineString](https://maplibre.org/maplibre-gl-js-docs/example/zoomto-linestring/) * @see [Fit a map to a bounding box](https://maplibre.org/maplibre-gl-js-docs/example/fitbounds/) */ abstract class Camera extends Evented { transform: Transform; _moving: boolean; _zooming: boolean; _rotating: boolean; _pitching: boolean; _padding: boolean; _bearingSnap: number; _easeStart: number; _easeOptions: { duration: number; easing: (_: number) => number; }; _easeId: string | void; _onEaseFrame: (_: number) => void; _onEaseEnd: (easeId?: string) => void; _easeFrameId: TaskID; abstract _requestRenderFrame(a: () => void): TaskID; abstract _cancelRenderFrame(_: TaskID): void; constructor(transform: Transform, options: { bearingSnap: number; }) { super(); this._moving = false; this._zooming = false; this.transform = transform; this._bearingSnap = options.bearingSnap; bindAll(['_renderFrameCallback'], this); //addAssertions(this); } /** * Returns the map's geographical centerpoint. * * @memberof Map# * @returns The map's geographical centerpoint. * @example * // return a LngLat object such as {lng: 0, lat: 0} * var center = map.getCenter(); * // access longitude and latitude values directly * var {lng, lat} = map.getCenter(); * @see Tutorial: [Use Mapbox GL JS in a React app](https://docs.mapbox.com/help/tutorials/use-mapbox-gl-js-with-react/#store-the-new-coordinates) */ getCenter(): LngLat { return new LngLat(this.transform.center.lng, this.transform.center.lat); } /** * Sets the map's geographical centerpoint. Equivalent to `jumpTo({center: center})`. * * @memberof Map# * @param center The centerpoint to set. * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires moveend * @returns {Map} `this` * @example * map.setCenter([-74, 38]); */ setCenter(center: LngLatLike, eventData?: any) { return this.jumpTo({center}, eventData); } /** * Pans the map by the specified offset. * * @memberof Map# * @param offset `x` and `y` coordinates by which to pan the map. * @param options Options object * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires moveend * @returns {Map} `this` * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js-docs/example/game-controls/) */ panBy(offset: PointLike, options?: AnimationOptions, eventData?: any) { offset = Point.convert(offset).mult(-1); return this.panTo(this.transform.center, extend({offset}, options), eventData); } /** * Pans the map to the specified location with an animated transition. * * @memberof Map# * @param lnglat The location to pan the map to. * @param options Options describing the destination and animation of the transition. * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires moveend * @returns {Map} `this` * @example * map.panTo([-74, 38]); * @example * // Specify that the panTo animation should last 5000 milliseconds. * map.panTo([-74, 38], {duration: 5000}); * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js-docs/example/live-update-feature/) */ panTo(lnglat: LngLatLike, options?: AnimationOptions, eventData?: any) { return this.easeTo(extend({ center: lnglat }, options), eventData); } /** * Returns the map's current zoom level. * * @memberof Map# * @returns The map's current zoom level. * @example * map.getZoom(); */ getZoom(): number { return this.transform.zoom; } /** * Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`. * * @memberof Map# * @param zoom The zoom level to set (0-20). * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires zoomstart * @fires move * @fires zoom * @fires moveend * @fires zoomend * @returns {Map} `this` * @example * // Zoom to the zoom level 5 without an animated transition * map.setZoom(5); */ setZoom(zoom: number, eventData?: any) { this.jumpTo({zoom}, eventData); return this; } /** * Zooms the map to the specified zoom level, with an animated transition. * * @memberof Map# * @param zoom The zoom level to transition to. * @param options Options object * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires zoomstart * @fires move * @fires zoom * @fires moveend * @fires zoomend * @returns {Map} `this` * @example * // Zoom to the zoom level 5 without an animated transition * map.zoomTo(5); * // Zoom to the zoom level 8 with an animated transition * map.zoomTo(8, { * duration: 2000, * offset: [100, 50] * }); */ zoomTo(zoom: number, options?: AnimationOptions | null, eventData?: any) { return this.easeTo(extend({ zoom }, options), eventData); } /** * Increases the map's zoom level by 1. * * @memberof Map# * @param options Options object * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires zoomstart * @fires move * @fires zoom * @fires moveend * @fires zoomend * @returns {Map} `this` * @example * // zoom the map in one level with a custom animation duration * map.zoomIn({duration: 1000}); */ zoomIn(options?: AnimationOptions, eventData?: any) { this.zoomTo(this.getZoom() + 1, options, eventData); return this; } /** * Decreases the map's zoom level by 1. * * @memberof Map# * @param options Options object * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires zoomstart * @fires move * @fires zoom * @fires moveend * @fires zoomend * @returns {Map} `this` * @example * // zoom the map out one level with a custom animation offset * map.zoomOut({offset: [80, 60]}); */ zoomOut(options?: AnimationOptions, eventData?: any) { this.zoomTo(this.getZoom() - 1, options, eventData); return this; } /** * Returns the map's current bearing. The bearing is the compass direction that is "up"; for example, a bearing * of 90° orients the map so that east is up. * * @memberof Map# * @returns The map's current bearing. * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js-docs/example/game-controls/) */ getBearing(): number { return this.transform.bearing; } /** * Sets the map's bearing (rotation). The bearing is the compass direction that is "up"; for example, a bearing * of 90° orients the map so that east is up. * * Equivalent to `jumpTo({bearing: bearing})`. * * @memberof Map# * @param bearing The desired bearing. * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires moveend * @returns {Map} `this` * @example * // rotate the map to 90 degrees * map.setBearing(90); */ setBearing(bearing: number, eventData?: any) { this.jumpTo({bearing}, eventData); return this; } /** * Returns the current padding applied around the map viewport. * * @memberof Map# * @returns The current padding around the map viewport. */ getPadding(): PaddingOptions { return this.transform.padding; } /** * Sets the padding in pixels around the viewport. * * Equivalent to `jumpTo({padding: padding})`. * * @memberof Map# * @param padding The desired padding. Format: { left: number, right: number, top: number, bottom: number } * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires moveend * @returns {Map} `this` * @example * // Sets a left padding of 300px, and a top padding of 50px * map.setPadding({ left: 300, top: 50 }); */ setPadding(padding: PaddingOptions, eventData?: any) { this.jumpTo({padding}, eventData); return this; } /** * Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction * that is \"up\"; for example, a bearing of 90° orients the map so that east is up. * * @memberof Map# * @param bearing The desired bearing. * @param options Options object * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires moveend * @returns {Map} `this` */ rotateTo(bearing: number, options?: AnimationOptions, eventData?: any) { return this.easeTo(extend({ bearing }, options), eventData); } /** * Rotates the map so that north is up (0° bearing), with an animated transition. * * @memberof Map# * @param options Options object * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires moveend * @returns {Map} `this` */ resetNorth(options?: AnimationOptions, eventData?: any) { this.rotateTo(0, extend({duration: 1000}, options), eventData); return this; } /** * Rotates and pitches the map so that north is up (0° bearing) and pitch is 0°, with an animated transition. * * @memberof Map# * @param options Options object * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires moveend * @returns {Map} `this` */ resetNorthPitch(options?: AnimationOptions, eventData?: any) { this.easeTo(extend({ bearing: 0, pitch: 0, duration: 1000 }, options), eventData); return this; } /** * Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the * `bearingSnap` threshold). * * @memberof Map# * @param options Options object * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires moveend * @returns {Map} `this` */ snapToNorth(options?: AnimationOptions, eventData?: any) { if (Math.abs(this.getBearing()) < this._bearingSnap) { return this.resetNorth(options, eventData); } return this; } /** * Returns the map's current pitch (tilt). * * @memberof Map# * @returns The map's current pitch, measured in degrees away from the plane of the screen. */ getPitch(): number { return this.transform.pitch; } /** * Sets the map's pitch (tilt). Equivalent to `jumpTo({pitch: pitch})`. * * @memberof Map# * @param pitch The pitch to set, measured in degrees away from the plane of the screen (0-60). * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires pitchstart * @fires movestart * @fires moveend * @returns {Map} `this` */ setPitch(pitch: number, eventData?: any) { this.jumpTo({pitch}, eventData); return this; } /** * @memberof Map# * @param {LngLatBoundsLike} bounds Calculate the center for these bounds in the viewport and use * the highest zoom level up to and including `Map#getMaxZoom()` that fits * in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0. * @param options Options object * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds. * @param {number} [options.bearing=0] Desired map bearing at end of animation, in degrees. * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels. * @param {number} [options.maxZoom] The maximum zoom level to allow when the camera would transition to the specified bounds. * @returns {CameraOptions | void} If map is able to fit to provided bounds, returns `CameraOptions` with * `center`, `zoom`, and `bearing`. If map is unable to fit, method will warn and return undefined. * @example * var bbox = [[-79, 43], [-73, 45]]; * var newCameraTransform = map.cameraForBounds(bbox, { * padding: {top: 10, bottom:25, left: 15, right: 5} * }); */ cameraForBounds(bounds: LngLatBoundsLike, options?: CameraOptions): void | CameraOptions & AnimationOptions { bounds = LngLatBounds.convert(bounds); const bearing = options && options.bearing || 0; return this._cameraForBoxAndBearing(bounds.getNorthWest(), bounds.getSouthEast(), bearing, options); } /** * Calculate the center of these two points in the viewport and use * the highest zoom level up to and including `Map#getMaxZoom()` that fits * the points in the viewport at the specified bearing. * @memberof Map# * @param {LngLatLike} p0 First point * @param {LngLatLike} p1 Second point * @param bearing Desired map bearing at end of animation, in degrees * @param options * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds. * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels. * @param {number} [options.maxZoom] The maximum zoom level to allow when the camera would transition to the specified bounds. * @returns {CameraOptions | void} If map is able to fit to provided bounds, returns `CameraOptions` with * `center`, `zoom`, and `bearing`. If map is unable to fit, method will warn and return undefined. * @private * @example * var p0 = [-79, 43]; * var p1 = [-73, 45]; * var bearing = 90; * var newCameraTransform = map._cameraForBoxAndBearing(p0, p1, bearing, { * padding: {top: 10, bottom:25, left: 15, right: 5} * }); */ _cameraForBoxAndBearing(p0: LngLatLike, p1: LngLatLike, bearing: number, options?: CameraOptions): void | CameraOptions & AnimationOptions { const defaultPadding = { top: 0, bottom: 0, right: 0, left: 0 }; options = extend({ padding: defaultPadding, offset: [0, 0], maxZoom: this.transform.maxZoom }, options); if (typeof options.padding === 'number') { const p = options.padding; options.padding = { top: p, bottom: p, right: p, left: p }; } options.padding = extend(defaultPadding, options.padding); const tr = this.transform; const edgePadding = tr.padding; // We want to calculate the upper right and lower left of the box defined by p0 and p1 // in a coordinate system rotate to match the destination bearing. const p0world = tr.project(LngLat.convert(p0)); const p1world = tr.project(LngLat.convert(p1)); const p0rotated = p0world.rotate(-bearing * Math.PI / 180); const p1rotated = p1world.rotate(-bearing * Math.PI / 180); const upperRight = new Point(Math.max(p0rotated.x, p1rotated.x), Math.max(p0rotated.y, p1rotated.y)); const lowerLeft = new Point(Math.min(p0rotated.x, p1rotated.x), Math.min(p0rotated.y, p1rotated.y)); // Calculate zoom: consider the original bbox and padding. const size = upperRight.sub(lowerLeft); const scaleX = (tr.width - (edgePadding.left + edgePadding.right + options.padding.left + options.padding.right)) / size.x; const scaleY = (tr.height - (edgePadding.top + edgePadding.bottom + options.padding.top + options.padding.bottom)) / size.y; if (scaleY < 0 || scaleX < 0) { warnOnce( 'Map cannot fit within canvas with the given bounds, padding, and/or offset.' ); return; } const zoom = Math.min(tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY)), options.maxZoom); // Calculate center: apply the zoom, the configured offset, as well as offset that exists as a result of padding. const offset = Point.convert(options.offset); const paddingOffsetX = (options.padding.left - options.padding.right) / 2; const paddingOffsetY = (options.padding.top - options.padding.bottom) / 2; const paddingOffset = new Point(paddingOffsetX, paddingOffsetY); const rotatedPaddingOffset = paddingOffset.rotate(bearing * Math.PI / 180); const offsetAtInitialZoom = offset.add(rotatedPaddingOffset); const offsetAtFinalZoom = offsetAtInitialZoom.mult(tr.scale / tr.zoomScale(zoom)); const center = tr.unproject(p0world.add(p1world).div(2).sub(offsetAtFinalZoom)); return { center, zoom, bearing }; } /** * Pans and zooms the map to contain its visible area within the specified geographical bounds. * This function will also reset the map's bearing to 0 if bearing is nonzero. * * @memberof Map# * @param bounds Center these bounds in the viewport and use the highest * zoom level up to and including `Map#getMaxZoom()` that fits them in the viewport. * @param {Object} [options] Options supports all properties from {@link AnimationOptions} and {@link CameraOptions} in addition to the fields below. * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds. * @param {boolean} [options.linear=false] If `true`, the map transitions using * {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}. See * those functions and {@link AnimationOptions} for information about options available. * @param {Function} [options.easing] An easing function for the animated transition. See {@link AnimationOptions}. * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels. * @param {number} [options.maxZoom] The maximum zoom level to allow when the map view transitions to the specified bounds. * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires moveend * @returns {Map} `this` * @example * var bbox = [[-79, 43], [-73, 45]]; * map.fitBounds(bbox, { * padding: {top: 10, bottom:25, left: 15, right: 5} * }); * @see [Fit a map to a bounding box](https://maplibre.org/maplibre-gl-js-docs/example/fitbounds/) */ fitBounds(bounds: LngLatBoundsLike, options?: AnimationOptions & CameraOptions & { linear: boolean }, eventData?: any) { return this._fitInternal( this.cameraForBounds(bounds, options) as AnimationOptions & CameraOptions, options, eventData); } /** * Pans, rotates and zooms the map to to fit the box made by points p0 and p1 * once the map is rotated to the specified bearing. To zoom without rotating, * pass in the current map bearing. * * @memberof Map# * @param p0 First point on screen, in pixel coordinates * @param p1 Second point on screen, in pixel coordinates * @param bearing Desired map bearing at end of animation, in degrees * @param options Options object * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds. * @param {boolean} [options.linear=false] If `true`, the map transitions using * {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}. See * those functions and {@link AnimationOptions} for information about options available. * @param {Function} [options.easing] An easing function for the animated transition. See {@link AnimationOptions}. * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels. * @param {number} [options.maxZoom] The maximum zoom level to allow when the map view transitions to the specified bounds. * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires moveend * @returns {Map} `this` * @example * var p0 = [220, 400]; * var p1 = [500, 900]; * map.fitScreenCoordinates(p0, p1, map.getBearing(), { * padding: {top: 10, bottom:25, left: 15, right: 5} * }); * @see Used by {@link BoxZoomHandler} */ fitScreenCoordinates(p0: PointLike, p1: PointLike, bearing: number, options?: AnimationOptions & CameraOptions & { linear: boolean }, eventData?: any) { return this._fitInternal( this._cameraForBoxAndBearing( this.transform.pointLocation(Point.convert(p0)), this.transform.pointLocation(Point.convert(p1)), bearing, options) as CameraOptions & AnimationOptions, options, eventData); } _fitInternal(calculatedOptions?: CameraOptions & AnimationOptions, options?: AnimationOptions & CameraOptions & { linear: boolean }, eventData?: any) { // cameraForBounds warns + returns undefined if unable to fit: if (!calculatedOptions) return this; options = extend(calculatedOptions, options); // Explictly remove the padding field because, calculatedOptions already accounts for padding by setting zoom and center accordingly. delete options.padding; return options.linear ? this.easeTo(options, eventData) : this.flyTo(options, eventData); } /** * Changes any combination of center, zoom, bearing, and pitch, without * an animated transition. The map will retain its current values for any * details not specified in `options`. * * @memberof Map# * @param options Options object * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires zoomstart * @fires pitchstart * @fires rotate * @fires move * @fires zoom * @fires pitch * @fires moveend * @fires zoomend * @fires pitchend * @returns {Map} `this` * @example * // jump to coordinates at current zoom * map.jumpTo({center: [0, 0]}); * // jump with zoom, pitch, and bearing options * map.jumpTo({ * center: [0, 0], * zoom: 8, * pitch: 45, * bearing: 90 * }); * @see [Jump to a series of locations](https://maplibre.org/maplibre-gl-js-docs/example/jump-to/) * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js-docs/example/live-update-feature/) */ jumpTo(options: CameraOptions, eventData?: any) { this.stop(); const tr = this.transform; let zoomChanged = false, bearingChanged = false, pitchChanged = false; if ('zoom' in options && tr.zoom !== +options.zoom) { zoomChanged = true; tr.zoom = +options.zoom; } if (options.center !== undefined) { tr.center = LngLat.convert(options.center); } if ('bearing' in options && tr.bearing !== +options.bearing) { bearingChanged = true; tr.bearing = +options.bearing; } if ('pitch' in options && tr.pitch !== +options.pitch) { pitchChanged = true; tr.pitch = +options.pitch; } if (options.padding != null && !tr.isPaddingEqual(options.padding)) { tr.padding = options.padding; } this.fire(new Event('movestart', eventData)) .fire(new Event('move', eventData)); if (zoomChanged) { this.fire(new Event('zoomstart', eventData)) .fire(new Event('zoom', eventData)) .fire(new Event('zoomend', eventData)); } if (bearingChanged) { this.fire(new Event('rotatestart', eventData)) .fire(new Event('rotate', eventData)) .fire(new Event('rotateend', eventData)); } if (pitchChanged) { this.fire(new Event('pitchstart', eventData)) .fire(new Event('pitch', eventData)) .fire(new Event('pitchend', eventData)); } return this.fire(new Event('moveend', eventData)); } /** * Changes any combination of `center`, `zoom`, `bearing`, `pitch`, and `padding` with an animated transition * between old and new values. The map will retain its current values for any * details not specified in `options`. * * Note: The transition will happen instantly if the user has enabled * the `reduced motion` accesibility feature enabled in their operating system, * unless `options` includes `essential: true`. * * @memberof Map# * @param options Options describing the destination and animation of the transition. * Accepts {@link CameraOptions} and {@link AnimationOptions}. * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires zoomstart * @fires pitchstart * @fires rotate * @fires move * @fires zoom * @fires pitch * @fires moveend * @fires zoomend * @fires pitchend * @returns {Map} `this` * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js-docs/example/game-controls/) */ easeTo(options: CameraOptions & AnimationOptions & { easeId?: string; noMoveStart?: boolean; }, eventData?: any) { this._stop(false, options.easeId); options = extend({ offset: [0, 0], duration: 500, easing: defaultEasing }, options); if (options.animate === false || (!options.essential && browser.prefersReducedMotion)) options.duration = 0; const tr = this.transform, startZoom = this.getZoom(), startBearing = this.getBearing(), startPitch = this.getPitch(), startPadding = this.getPadding(), zoom = 'zoom' in options ? +options.zoom : startZoom, bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing, pitch = 'pitch' in options ? +options.pitch : startPitch, padding = 'padding' in options ? options.padding : tr.padding; const offsetAsPoint = Point.convert(options.offset); let pointAtOffset = tr.centerPoint.add(offsetAsPoint); const locationAtOffset = tr.pointLocation(pointAtOffset); const center = LngLat.convert(options.center || locationAtOffset); this._normalizeCenter(center); const from = tr.project(locationAtOffset); const delta = tr.project(center).sub(from); const finalScale = tr.zoomScale(zoom - startZoom); let around, aroundPoint; if (options.around) { around = LngLat.convert(options.around); aroundPoint = tr.locationPoint(around); } const currently = { moving: this._moving, zooming: this._zooming, rotating: this._rotating, pitching: this._pitching }; this._zooming = this._zooming || (zoom !== startZoom); this._rotating = this._rotating || (startBearing !== bearing); this._pitching = this._pitching || (pitch !== startPitch); this._padding = !tr.isPaddingEqual(padding); this._easeId = options.easeId; this._prepareEase(eventData, options.noMoveStart, currently); this._ease((k) => { if (this._zooming) { tr.zoom = interpolate(startZoom, zoom, k); } if (this._rotating) { tr.bearing = interpolate(startBearing, bearing, k); } if (this._pitching) { tr.pitch = interpolate(startPitch, pitch, k); } if (this._padding) { tr.interpolatePadding(startPadding, padding, k); // When padding is being applied, Transform#centerPoint is changing continously, // thus we need to recalculate offsetPoint every fra,e pointAtOffset = tr.centerPoint.add(offsetAsPoint); } if (around) { tr.setLocationAtPoint(around, aroundPoint); } else { const scale = tr.zoomScale(tr.zoom - startZoom); const base = zoom > startZoom ? Math.min(2, finalScale) : Math.max(0.5, finalScale); const speedup = Math.pow(base, 1 - k); const newCenter = tr.unproject(from.add(delta.mult(k * speedup)).mult(scale)); tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset); } this._fireMoveEvents(eventData); }, (interruptingEaseId?: string) => { this._afterEase(eventData, interruptingEaseId); }, options as any); return this; } _prepareEase(eventData: any, noMoveStart: boolean, currently: any = {}) { this._moving = true; if (!noMoveStart && !currently.moving) { this.fire(new Event('movestart', eventData)); } if (this._zooming && !currently.zooming) { this.fire(new Event('zoomstart', eventData)); } if (this._rotating && !currently.rotating) { this.fire(new Event('rotatestart', eventData)); } if (this._pitching && !currently.pitching) { this.fire(new Event('pitchstart', eventData)); } } _fireMoveEvents(eventData?: any) { this.fire(new Event('move', eventData)); if (this._zooming) { this.fire(new Event('zoom', eventData)); } if (this._rotating) { this.fire(new Event('rotate', eventData)); } if (this._pitching) { this.fire(new Event('pitch', eventData)); } } _afterEase(eventData?: any, easeId?: string) { // if this easing is being stopped to start another easing with // the same id then don't fire any events to avoid extra start/stop events if (this._easeId && easeId && this._easeId === easeId) { return; } delete this._easeId; const wasZooming = this._zooming; const wasRotating = this._rotating; const wasPitching = this._pitching; this._moving = false; this._zooming = false; this._rotating = false; this._pitching = false; this._padding = false; if (wasZooming) { this.fire(new Event('zoomend', eventData)); } if (wasRotating) { this.fire(new Event('rotateend', eventData)); } if (wasPitching) { this.fire(new Event('pitchend', eventData)); } this.fire(new Event('moveend', eventData)); } /** * Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that * evokes flight. The animation seamlessly incorporates zooming and panning to help * the user maintain her bearings even after traversing a great distance. * * Note: The animation will be skipped, and this will behave equivalently to `jumpTo` * if the user has the `reduced motion` accesibility feature enabled in their operating system, * unless 'options' includes `essential: true`. * * @memberof Map# * @param {Object} options Options describing the destination and animation of the transition. * Accepts {@link CameraOptions}, {@link AnimationOptions}, * and the following additional options. * @param {number} [options.curve=1.42] The zooming "curve" that will occur along the * flight path. A high value maximizes zooming for an exaggerated animation, while a low * value minimizes zooming for an effect closer to {@link Map#easeTo}. 1.42 is the average * value selected by participants in the user study discussed in * [van Wijk (2003)](https://www.win.tue.nl/~vanwijk/zoompan.pdf). A value of * `Math.pow(6, 0.25)` would be equivalent to the root mean squared average velocity. A * value of 1 would produce a circular motion. * @param {number} [options.minZoom] The zero-based zoom level at the peak of the flight path. If * `options.curve` is specified, this option is ignored. * @param {number} [options.speed=1.2] The average speed of the animation defined in relation to * `options.curve`. A speed of 1.2 means that the map appears to move along the flight path * by 1.2 times `options.curve` screenfuls every second. A _screenful_ is the map's visible span. * It does not correspond to a fixed physical distance, but varies by zoom level. * @param {number} [options.screenSpeed] The average speed of the animation measured in screenfuls * per second, assuming a linear timing curve. If `options.speed` is specified, this option is ignored. * @param {number} [options.maxDuration] The animation's maximum duration, measured in milliseconds. * If duration exceeds maximum duration, it resets to 0. * @param eventData Additional properties to be added to event objects of events triggered by this method. * @fires movestart * @fires zoomstart * @fires pitchstart * @fires move * @fires zoom * @fires rotate * @fires pitch * @fires moveend * @fires zoomend * @fires pitchend * @returns {Map} `this` * @example * // fly with default options to null island * map.flyTo({center: [0, 0], zoom: 9}); * // using flyTo options * map.flyTo({ * center: [0, 0], * zoom: 9, * speed: 0.2, * curve: 1, * easing(t) { * return t; * } * }); * @see [Fly to a location](https://maplibre.org/maplibre-gl-js-docs/example/flyto/) * @see [Slowly fly to a location](https://maplibre.org/maplibre-gl-js-docs/example/flyto-options/) * @see [Fly to a location based on scroll position](https://maplibre.org/maplibre-gl-js-docs/example/scroll-fly-to/) */ flyTo(options: any, eventData?: any) { // Fall through to jumpTo if user has set prefers-reduced-motion if (!options.essential && browser.prefersReducedMotion) { const coercedOptions = (pick(options, ['center', 'zoom', 'bearing', 'pitch', 'around']) as CameraOptions); return this.jumpTo(coercedOptions, eventData); } // This method implements an “optimal path” animation, as detailed in: // // Van Wijk, Jarke J.; Nuij, Wim A. A. “Smooth and efficient zooming and panning.” INFOVIS // ’03. pp. 15–22. <https://www.win.tue.nl/~vanwijk/zoompan.pdf#page=5>. // // Where applicable, local variable documentation begins with the associated variable or // function in van Wijk (2003). this.stop(); options = extend({ offset: [0, 0], speed: 1.2, curve: 1.42, easing: defaultEasing }, options); const tr = this.transform, startZoom = this.getZoom(), startBearing = this.getBearing(), startPitch = this.getPitch(), startPadding = this.getPadding(); const zoom = 'zoom' in options ? clamp(+options.zoom, tr.minZoom, tr.maxZoom) : startZoom; const bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing; const pitch = 'pitch' in options ? +options.pitch : startPitch; const padding = 'padding' in options ? options.padding : tr.padding; const scale = tr.zoomScale(zoom - startZoom); const offsetAsPoint = Point.convert(options.offset); let pointAtOffset = tr.centerPoint.add(offsetAsPoint); const locationAtOffset = tr.pointLocation(pointAtOffset); const center = LngLat.convert(options.center || locationAtOffset); this._normalizeCenter(center); const from = tr.project(locationAtOffset); const delta = tr.project(center).sub(from); let rho = options.curve; // w₀: Initial visible span, measured in pixels at the initial scale. const w0 = Math.max(tr.width, tr.height), // w₁: Final visible span, measured in pixels with respect to the initial scale. w1 = w0 / scale, // Length of the flight path as projected onto the ground plane, measured in pixels from // the world image origin at the initial scale. u1 = delta.mag(); if ('minZoom' in options) { const minZoom = clamp(Math.min(options.minZoom, startZoom, zoom), tr.minZoom, tr.maxZoom); // w<sub>m</sub>: Maximum visible span, measured in pixels with respect to the initial // scale. const wMax = w0 / tr.zoomScale(minZoom - startZoom); rho = Math.sqrt(wMax / u1 * 2); } // ρ² const rho2 = rho * rho; /** * rᵢ: Returns the zoom-out factor at one end of the animation. * * @param i 0 for the ascent or 1 for the descent. * @private */ function r(i) { const b = (w1 * w1 - w0 * w0 + (i ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (i ? w1 : w0) * rho2 * u1); return Math.log(Math.sqrt(b * b + 1) - b); } function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; } function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; } function tanh(n) { return sinh(n) / cosh(n); } // r₀: Zoom-out factor during ascent. const r0 = r(0); // w(s): Returns the visible span on the ground, measured in pixels with respect to the // initial scale. Assumes an angular field of view of 2 arctan ½ ≈ 53°. let w: (_: number) => number = function (s) { return (cosh(r0) / cosh(r0 + rho * s)); }; // u(s): Returns the distance along the flight path as projected onto the ground plane, // measured in pixels from the world image origin at the initial scale. let u: (_: number) => number = function (s) { return w0 * ((cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2) / u1; }; // S: Total length of the flight path, measured in ρ-screenfuls. let S = (r(1) - r0) / rho; // When u₀ = u₁, the optimal path doesn’t require both ascent and descent. if (Math.abs(u1) < 0.000001 || !isFinite(S)) { // Perform a more or less instantaneous transition if the path is too short. if (Math.abs(w0 - w1) < 0.000001) return this.easeTo(options, eventData); const k = w1 < w0 ? -1 : 1; S = Math.abs(Math.log(w1 / w0)) / rho; u = function() { return 0; }; w = function(s) { return Math.exp(k * rho * s); }; } if ('duration' in options) { options.duration = +options.duration; } else { const V = 'screenSpeed' in options ? +options.screenSpeed / rho : +options.speed; options.duration = 1000 * S / V; } if (options.maxDuration && options.duration > options.maxDuration) { options.duration = 0; } this._zooming = true; this._rotating = (startBearing !== bearing); this._pitching = (pitch !== startPitch); this._padding = !tr.isPaddingEqual(padding); this._prepareEase(eventData, false); this._ease((k) => { // s: The distance traveled along the flight path, measured in ρ-screenfuls. const s = k * S; const scale = 1 / w(s); tr.zoom = k === 1 ? zoom : startZoom + tr.scaleZoom(scale); if (this._rotating) { tr.bearing = interpolate(startBearing, bearing, k); } if (this._pitching) { tr.pitch = interpolate(startPitch, pitch, k); } if (this._padding) { tr.interpolatePadding(startPadding, padding, k); // When padding is being applied, Transform#centerPoint is changing continously, // thus we need to recalculate offsetPoint every frame pointAtOffset = tr.centerPoint.add(offsetAsPoint); } const newCenter = k === 1 ? center : tr.unproject(from.add(delta.mult(u(s))).mult(scale)); tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset); this._fireMoveEvents(eventData); }, () => this._afterEase(eventData), options); return this; } isEasing() { return !!this._easeFrameId; } /** * Stops any animated transition underway. * * @memberof Map# * @returns {Map} `this` */ stop(): this { return this._stop(); } _stop(allowGestures?: boolean, easeId?: string): this { if (this._easeFrameId) { this._cancelRenderFrame(this._easeFrameId); delete this._easeFrameId; delete this._onEaseFrame; } if (this._onEaseEnd) { // The _onEaseEnd function might emit events which trigger new // animation, which sets a new _onEaseEnd. Ensure we don't delete // it unintentionally. const onEaseEnd = this._onEaseEnd; delete this._onEaseEnd; onEaseEnd.call(this, easeId); } if (!allowGestures) { const handlers = (this as any).handlers; if (handlers) handlers.stop(false); } return this; } _ease(frame: (_: number) => void, finish: () => void, options: { animate: boolean; duration: number; easing: (_: number) => number; }) { if (options.animate === false || options.duration === 0) { frame(1); finish(); } else { this._easeStart = browser.now(); this._easeOptions = options; this._onEaseFrame = frame; this._onEaseEnd = finish; this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback); } } // Callback for map._requestRenderFrame _renderFrameCallback() { const t = Math.min((browser.now() - this._easeStart) / this._easeOptions.duration, 1); this._onEaseFrame(this._easeOptions.easing(t)); if (t < 1) { this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback); } else { this.stop(); } } // convert bearing so that it's numerically close to the current one so that it interpolates properly _normalizeBearing(bearing: number, currentBearing: number) { bearing = wrap(bearing, -180, 180); const diff = Math.abs(bearing - currentBearing); if (Math.abs(bearing - 360 - currentBearing) < diff) bearing -= 360; if (Math.abs(bearing + 360 - currentBearing) < diff) bearing += 360; return bearing; } // If a path crossing the antimeridian would be shorter, extend the final coordinate so that // interpolating between the two endpoints will cross it. _normalizeCenter(center: LngLat) { const tr = this.transform; if (!tr.renderWorldCopies || tr.lngRange) return; const delta = center.lng - tr.center.lng; center.lng += delta > 180 ? -360 : delta < -180 ? 360 : 0; } } // In debug builds, check that camera change events are fired in the correct order. // - ___start events needs to be fired before ___ and ___end events // - another ___start event can't be fired before a ___end event has been fired for the previous one function addAssertions(camera: Camera) { //eslint-disable-line Debug.run(() => { const inProgress = {} as any; ['drag', 'zoom', 'rotate', 'pitch', 'move'].forEach(name => { inProgress[name] = false; camera.on(`${name}start`, () => { assert(!inProgress[name], `"${name}start" fired twice without a "${name}end"`); inProgress[name] = true; assert(inProgress.move); }); camera.on(name, () => { assert(inProgress[name]); assert(inProgress.move); }); camera.on(`${name}end`, () => { assert(inProgress.move); assert(inProgress[name]); inProgress[name] = false; }); }); // Canary used to test whether this function is stripped in prod build canary = 'canary debug run'; // eslint-disable-line }); } let canary; // eslint-disable-line export default Camera;
the_stack
import {loadUserManager} from 'app/client/lib/imports'; import {ImportSourceElement} from 'app/client/lib/ImportSourceElement'; import {reportError} from 'app/client/models/AppModel'; import {docUrl, urlState} from 'app/client/models/gristUrlState'; import {HomeModel} from 'app/client/models/HomeModel'; import {getWorkspaceInfo, workspaceName} from 'app/client/models/WorkspaceInfo'; import {addNewButton, cssAddNewButton} from 'app/client/ui/AddNewButton'; import {docImport, importFromPlugin} from 'app/client/ui/HomeImports'; import {cssLinkText, cssPageEntry, cssPageIcon, cssPageLink} from 'app/client/ui/LeftPanelCommon'; import {transientInput} from 'app/client/ui/transientInput'; import {colors, testId} from 'app/client/ui2018/cssVars'; import {icon} from 'app/client/ui2018/icons'; import {menu, menuIcon, menuItem, upgradableMenuItem, upgradeText} from 'app/client/ui2018/menus'; import {confirmModal} from 'app/client/ui2018/modals'; import * as roles from 'app/common/roles'; import {Workspace} from 'app/common/UserAPI'; import {computed, dom, domComputed, DomElementArg, observable, Observable, styled} from 'grainjs'; import {createHelpTools, cssLeftPanel, cssScrollPane, cssSectionHeader, cssTools} from 'app/client/ui/LeftPanelCommon'; export function createHomeLeftPane(leftPanelOpen: Observable<boolean>, home: HomeModel) { const creating = observable<boolean>(false); const renaming = observable<Workspace|null>(null); return cssContent( dom.autoDispose(creating), dom.autoDispose(renaming), addNewButton(leftPanelOpen, menu(() => addMenu(home, creating), { placement: 'bottom-start', // "Add New" menu should have the same width as the "Add New" button that opens it. stretchToSelector: `.${cssAddNewButton.className}` }), testId('dm-add-new') ), cssScrollPane( cssPageEntry( cssPageEntry.cls('-selected', (use) => use(home.currentPage) === "all"), cssPageLink(cssPageIcon('Home'), cssLinkText('All Documents'), urlState().setLinkUrl({ws: undefined, homePage: undefined}), testId('dm-all-docs'), ), ), dom.maybe(use => !use(home.singleWorkspace), () => cssSectionHeader('Workspaces', // Give it a testId, because it's a good element to simulate "click-away" in tests. testId('dm-ws-label') ), ), dom.forEach(home.workspaces, (ws) => { if (ws.isSupportWorkspace) { return null; } const isTrivial = computed((use) => Boolean(getWorkspaceInfo(home.app, ws).isDefault && use(home.singleWorkspace))); // TODO: Introduce a "SwitchSelector" pattern to avoid the need for N computeds (and N // recalculations) to select one of N items. const isRenaming = computed((use) => use(renaming) === ws); return cssPageEntry( dom.autoDispose(isRenaming), dom.autoDispose(isTrivial), dom.hide(isTrivial), cssPageEntry.cls('-selected', (use) => use(home.currentWSId) === ws.id), cssPageLink(cssPageIcon('Folder'), cssLinkText(workspaceName(home.app, ws)), dom.hide(isRenaming), urlState().setLinkUrl({ws: ws.id}), cssMenuTrigger(icon('Dots'), menu(() => workspaceMenu(home, ws, renaming), {placement: 'bottom-start', parentSelectorToMark: '.' + cssPageEntry.className}), // Clicks on the menu trigger shouldn't follow the link that it's contained in. dom.on('click', (ev) => { ev.stopPropagation(); ev.preventDefault(); }), testId('dm-workspace-options'), ), testId('dm-workspace'), ), cssPageEntry.cls('-renaming', isRenaming), dom.maybe(isRenaming, () => cssPageLink(cssPageIcon('Folder'), cssEditorInput({ initialValue: ws.name || '', save: async (val) => (val !== ws.name) ? home.renameWorkspace(ws.id, val) : undefined, close: () => renaming.set(null), }, testId('dm-ws-name-editor')) ) ), ); }), dom.maybe(creating, () => cssPageEntry( cssPageLink(cssPageIcon('Folder'), cssEditorInput({ initialValue: '', save: async (val) => (val !== '') ? home.createWorkspace(val) : undefined, close: () => creating.set(false), }, testId('dm-ws-name-editor')) ) )), cssTools( cssPageEntry( cssPageEntry.cls('-selected', (use) => use(home.currentPage) === "templates"), cssPageLink(cssPageIcon('FieldTable'), cssLinkText("Examples & Templates"), urlState().setLinkUrl({homePage: "templates"}), testId('dm-templates-page'), ), ), cssPageEntry( cssPageEntry.cls('-selected', (use) => use(home.currentPage) === "trash"), cssPageLink(cssPageIcon('Remove'), cssLinkText("Trash"), urlState().setLinkUrl({homePage: "trash"}), testId('dm-trash'), ), ), createHelpTools(home.app), ) ) ); } export async function createDocAndOpen(home: HomeModel) { const destWS = home.newDocWorkspace.get(); if (!destWS) { return; } try { const docId = await home.createDoc("Untitled document", destWS === "unsaved" ? "unsaved" : destWS.id); // Fetch doc information including urlId. // TODO: consider changing API to return same response as a GET when creating an // object, which is a semi-standard. const doc = await home.app.api.getDoc(docId); await urlState().pushUrl(docUrl(doc)); } catch (err) { reportError(err); } } export async function importDocAndOpen(home: HomeModel) { const destWS = home.newDocWorkspace.get(); if (!destWS) { return; } const docId = await docImport(home.app, destWS === "unsaved" ? "unsaved" : destWS.id); if (docId) { const doc = await home.app.api.getDoc(docId); await urlState().pushUrl(docUrl(doc)); } } export async function importFromPluginAndOpen(home: HomeModel, source: ImportSourceElement) { try { const destWS = home.newDocWorkspace.get(); if (!destWS) { return; } const docId = await importFromPlugin( home.app, destWS === "unsaved" ? "unsaved" : destWS.id, source); if (docId) { const doc = await home.app.api.getDoc(docId); await urlState().pushUrl(docUrl(doc)); } } catch (err) { reportError(err); } } function addMenu(home: HomeModel, creating: Observable<boolean>): DomElementArg[] { const org = home.app.currentOrg; const orgAccess: roles.Role|null = org ? org.access : null; const needUpgrade = home.app.currentFeatures.maxWorkspacesPerOrg === 1; return [ menuItem(() => createDocAndOpen(home), menuIcon('Page'), "Create Empty Document", dom.cls('disabled', !home.newDocWorkspace.get()), testId("dm-new-doc") ), menuItem(() => importDocAndOpen(home), menuIcon('Import'), "Import Document", dom.cls('disabled', !home.newDocWorkspace.get()), testId("dm-import") ), domComputed(home.importSources, importSources => ([ ...importSources.map((source, i) => menuItem(() => importFromPluginAndOpen(home, source), menuIcon('Import'), source.importSource.label, dom.cls('disabled', !home.newDocWorkspace.get()), testId(`dm-import-plugin`) )) ])), // For workspaces: if ACL says we can create them, but product says we can't, // then offer an upgrade link. upgradableMenuItem(needUpgrade, () => creating.set(true), menuIcon('Folder'), "Create Workspace", dom.cls('disabled', (use) => !roles.canEdit(orgAccess) || !use(home.available)), testId("dm-new-workspace") ), upgradeText(needUpgrade), ]; } function workspaceMenu(home: HomeModel, ws: Workspace, renaming: Observable<Workspace|null>) { function deleteWorkspace() { confirmModal(`Delete ${ws.name} and all included documents?`, 'Delete', () => home.deleteWorkspace(ws.id, false), 'Workspace will be moved to Trash.'); } async function manageWorkspaceUsers() { const api = home.app.api; const user = home.app.currentUser; (await loadUserManager()).showUserManagerModal(api, { permissionData: api.getWorkspaceAccess(ws.id), activeEmail: user ? user.email : null, resourceType: 'workspace', resourceId: ws.id }); } const needUpgrade = home.app.currentFeatures.maxWorkspacesPerOrg === 1; return [ upgradableMenuItem(needUpgrade, () => renaming.set(ws), "Rename", dom.cls('disabled', !roles.canEdit(ws.access)), testId('dm-rename-workspace')), upgradableMenuItem(needUpgrade, deleteWorkspace, "Delete", dom.cls('disabled', user => !roles.canEdit(ws.access)), testId('dm-delete-workspace')), upgradableMenuItem(needUpgrade, manageWorkspaceUsers, "Manage Users", dom.cls('disabled', !roles.canEditAccess(ws.access)), testId('dm-workspace-access')), upgradeText(needUpgrade), ]; } // Below are all the styled elements. const cssContent = styled(cssLeftPanel, ` --page-icon-margin: 12px; `); export const cssEditorInput = styled(transientInput, ` height: 24px; flex: 1 1 0px; min-width: 0px; color: initial; margin-right: 16px; font-size: inherit; `); const cssMenuTrigger = styled('div', ` margin: 0 4px 0 auto; height: 24px; width: 24px; padding: 4px; line-height: 0px; border-radius: 3px; cursor: default; display: none; .${cssPageLink.className}:hover > &, &.weasel-popup-open { display: block; } &:hover, &.weasel-popup-open { background-color: ${colors.darkGrey}; } .${cssPageEntry.className}-selected &:hover, .${cssPageEntry.className}-selected &.weasel-popup-open { background-color: ${colors.slate}; } `);
the_stack
import * as Context from "../context" declare global { interface NexusGenCustomOutputProperties<TypeName extends string> { model: NexusPrisma<TypeName, 'model'> crud: any } } declare global { interface NexusGen extends NexusGenTypes {} } export interface NexusGenInputs { AddressInput: { // input type city?: string | null; // String isPrimary?: boolean | null; // Boolean number?: string | null; // String postNumber?: string | null; // String state?: string | null; // String street?: string | null; // String } AddressWhereUniqueInput: { // input type id?: string | null; // String } CreateCustomerInput: { // input type addresses?: NexusGenInputs['AddressInput'][] | null; // [AddressInput!] allowedBankPayments?: boolean | null; // Boolean email?: string | null; // String identificationNumber?: string | null; // String name?: string | null; // String note?: string | null; // String personName?: string | null; // String phone?: string | null; // String taxIdentificationNumber?: string | null; // String } CreateUserInput: { // input type email: string; // String! name?: string | null; // String password: string; // String! role?: NexusGenEnums['UserRole'] | null; // UserRole } OrderInput: { // input type customerId?: string | null; // ID items: NexusGenInputs['OrderItemInput'][]; // [OrderItemInput!]! note?: string | null; // String status?: NexusGenEnums['OrderStatus'] | null; // OrderStatus totalPrice: number; // Float! totalTax: number; // Float! urgency?: number | null; // Int } OrderItemInput: { // input type height?: number | null; // Float materialId?: string | null; // ID name?: string | null; // String pieces?: number | null; // Int totalPrice: number; // Float! totalTax: number; // Float! width?: number | null; // Float } OrderItemWhereUniqueInput: { // input type id?: string | null; // String } OrderItemsOrderByInput: { // input type createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder } UpdateAddressInput: { // input type city?: string | null; // String id?: string | null; // ID isPrimary?: boolean | null; // Boolean number?: string | null; // String postNumber?: string | null; // String state?: string | null; // String street?: string | null; // String } UpdateCustomerInput: { // input type addresses?: NexusGenInputs['UpdateAddressInput'][] | null; // [UpdateAddressInput!] allowedBankPayments?: boolean | null; // Boolean email?: string | null; // String id?: string | null; // ID identificationNumber?: string | null; // String name?: string | null; // String note?: string | null; // String personName?: string | null; // String phone?: string | null; // String taxIdentificationNumber?: string | null; // String } UpdateOrderInput: { // input type customerId?: string | null; // ID items?: NexusGenInputs['UpdateOrderItemInput'][] | null; // [UpdateOrderItemInput!] note?: string | null; // String status?: NexusGenEnums['OrderStatus'] | null; // OrderStatus totalPrice?: number | null; // Float totalTax?: number | null; // Float urgency?: number | null; // Int } UpdateOrderItemInput: { // input type height?: number | null; // Float id?: string | null; // ID materialId: string; // ID! name?: string | null; // String pieces?: number | null; // Int totalPrice: number; // Float! totalTax: number; // Float! width?: number | null; // Float } UpdateUserInput: { // input type email: string; // String! name?: string | null; // String password?: string | null; // String role?: NexusGenEnums['UserRole'] | null; // UserRole } } export interface NexusGenEnums { OrderByArg: "asc" | "desc" OrderStatus: "DONE" | "NEW" | "READY_TO_PRINT" | "TO_BE_SHIPPED" | "WAITING_FOR_CALCULATION" | "WAITING_FOR_PRODUCTION" ProductionLogType: "PRINT" | "PRODUCTION" SortOrder: "asc" | "desc" UserRole: "ADMINISTRATION" | "EXECUTIVE" | "FACTORY" } export interface NexusGenRootTypes { Address: { // root type city?: string | null; // String id: string; // String! isPrimary: boolean; // Boolean! number?: string | null; // String postNumber?: string | null; // String street?: string | null; // String } AuthPayload: { // root type token: string; // String! user: NexusGenRootTypes['User']; // User! } Customer: { // root type allowedBankPayments: boolean; // Boolean! createdAt: any; // DateTime! email?: string | null; // String id: string; // String! identificationNumber?: string | null; // String name?: string | null; // String note?: string | null; // String personName?: string | null; // String phone?: string | null; // String taxIdentificationNumber?: string | null; // String updatedAt: any; // DateTime! } CustomerHelperInfo: { // root type city?: string | null; // String identificationNumber?: string | null; // String name?: string | null; // String postNumber?: string | null; // String street?: string | null; // String taxIdentificationNumber?: string | null; // String } CustomerPaginated: { // root type items: NexusGenRootTypes['Customer'][]; // [Customer!]! totalCount: number; // Int! } Material: { // root type createdAt: any; // DateTime! id: string; // String! name: string; // String! price: number; // Float! updatedAt: any; // DateTime! } Mutation: {}; Order: { // root type createdAt: any; // DateTime! id: string; // String! note?: string | null; // String number: number; // Int! shippedAt?: any | null; // DateTime status: string; // String! totalPrice: number; // Float! totalTax: number; // Float! updatedAt: any; // DateTime! urgency: number; // Int! } OrderItem: { // root type createdAt: any; // DateTime! height?: number | null; // Float id: string; // String! name?: string | null; // String pieces?: number | null; // Int totalPrice: number; // Float! totalTax: number; // Float! updatedAt: any; // DateTime! width?: number | null; // Float } OrderPaginated: { // root type items: NexusGenRootTypes['Order'][]; // [Order!]! totalCount: number; // Int! } ProductionLog: { // root type action: string; // String! createdAt: any; // DateTime! id: string; // String! pieces: number; // Int! } Query: {}; User: { // root type email: string; // String! id: string; // String! name?: string | null; // String role: string; // String! } String: string; Int: number; Float: number; Boolean: boolean; ID: string; DateTime: any; } export interface NexusGenAllTypes extends NexusGenRootTypes { AddressInput: NexusGenInputs['AddressInput']; AddressWhereUniqueInput: NexusGenInputs['AddressWhereUniqueInput']; CreateCustomerInput: NexusGenInputs['CreateCustomerInput']; CreateUserInput: NexusGenInputs['CreateUserInput']; OrderInput: NexusGenInputs['OrderInput']; OrderItemInput: NexusGenInputs['OrderItemInput']; OrderItemWhereUniqueInput: NexusGenInputs['OrderItemWhereUniqueInput']; OrderItemsOrderByInput: NexusGenInputs['OrderItemsOrderByInput']; UpdateAddressInput: NexusGenInputs['UpdateAddressInput']; UpdateCustomerInput: NexusGenInputs['UpdateCustomerInput']; UpdateOrderInput: NexusGenInputs['UpdateOrderInput']; UpdateOrderItemInput: NexusGenInputs['UpdateOrderItemInput']; UpdateUserInput: NexusGenInputs['UpdateUserInput']; OrderByArg: NexusGenEnums['OrderByArg']; OrderStatus: NexusGenEnums['OrderStatus']; ProductionLogType: NexusGenEnums['ProductionLogType']; SortOrder: NexusGenEnums['SortOrder']; UserRole: NexusGenEnums['UserRole']; } export interface NexusGenFieldTypes { Address: { // field return type city: string | null; // String id: string; // String! isPrimary: boolean; // Boolean! number: string | null; // String postNumber: string | null; // String street: string | null; // String } AuthPayload: { // field return type token: string; // String! user: NexusGenRootTypes['User']; // User! } Customer: { // field return type addresses: NexusGenRootTypes['Address'][]; // [Address!]! allowedBankPayments: boolean; // Boolean! createdAt: any; // DateTime! createdBy: NexusGenRootTypes['User']; // User! email: string | null; // String id: string; // String! identificationNumber: string | null; // String name: string | null; // String note: string | null; // String personName: string | null; // String phone: string | null; // String taxIdentificationNumber: string | null; // String updatedAt: any; // DateTime! } CustomerHelperInfo: { // field return type city: string | null; // String identificationNumber: string | null; // String name: string | null; // String postNumber: string | null; // String street: string | null; // String taxIdentificationNumber: string | null; // String } CustomerPaginated: { // field return type items: NexusGenRootTypes['Customer'][]; // [Customer!]! totalCount: number; // Int! } Material: { // field return type createdAt: any; // DateTime! createdBy: NexusGenRootTypes['User']; // User! id: string; // String! name: string; // String! price: number; // Float! updatedAt: any; // DateTime! } Mutation: { // field return type addProductionLog: NexusGenRootTypes['OrderItem']; // OrderItem! addUser: NexusGenRootTypes['User']; // User! changePassword: NexusGenRootTypes['User']; // User! createCustomer: NexusGenRootTypes['Customer']; // Customer! createMaterial: NexusGenRootTypes['Material']; // Material! createOrder: NexusGenRootTypes['Order']; // Order! deleteCustomer: NexusGenRootTypes['Customer']; // Customer! deleteMaterial: NexusGenRootTypes['Material']; // Material! deleteOrder: NexusGenRootTypes['Order']; // Order! deleteUser: NexusGenRootTypes['User']; // User! login: NexusGenRootTypes['AuthPayload']; // AuthPayload! updateCustomer: NexusGenRootTypes['Customer']; // Customer! updateMaterial: NexusGenRootTypes['Material']; // Material! updateOrder: NexusGenRootTypes['Order']; // Order! updateOrderNote: NexusGenRootTypes['Order']; // Order! updateOrderStatus: NexusGenRootTypes['Order']; // Order! updateUser: NexusGenRootTypes['User']; // User! } Order: { // field return type createdAt: any; // DateTime! createdBy: NexusGenRootTypes['User']; // User! customer: NexusGenRootTypes['Customer'] | null; // Customer id: string; // String! items: NexusGenRootTypes['OrderItem'][]; // [OrderItem!]! note: string | null; // String number: number; // Int! shippedAt: any | null; // DateTime status: string; // String! totalPrice: number; // Float! totalSize: number; // Float! totalTax: number; // Float! updatedAt: any; // DateTime! urgency: number; // Int! } OrderItem: { // field return type createdAt: any; // DateTime! createdBy: NexusGenRootTypes['User']; // User! height: number | null; // Float id: string; // String! material: NexusGenRootTypes['Material'] | null; // Material name: string | null; // String pieces: number | null; // Int printedPieces: number; // Int! producedPieces: number; // Int! productionLog: NexusGenRootTypes['ProductionLog'][]; // [ProductionLog!]! totalPrice: number; // Float! totalTax: number; // Float! updatedAt: any; // DateTime! width: number | null; // Float } OrderPaginated: { // field return type items: NexusGenRootTypes['Order'][]; // [Order!]! totalCount: number; // Int! } ProductionLog: { // field return type action: string; // String! createdAt: any; // DateTime! createdBy: NexusGenRootTypes['User']; // User! id: string; // String! orderItem: NexusGenRootTypes['OrderItem']; // OrderItem! pieces: number; // Int! } Query: { // field return type getAllCustomers: NexusGenRootTypes['CustomerPaginated']; // CustomerPaginated! getAllMaterials: NexusGenRootTypes['Material'][]; // [Material!]! getAllOrders: NexusGenRootTypes['OrderPaginated']; // OrderPaginated! getAllUsers: NexusGenRootTypes['User'][]; // [User!]! getCustomer: NexusGenRootTypes['Customer'] | null; // Customer getCustomerHelperInfo: NexusGenRootTypes['CustomerHelperInfo']; // CustomerHelperInfo! getHighestOrderNumber: number | null; // Int getOrder: NexusGenRootTypes['Order'] | null; // Order getOrderByNumber: NexusGenRootTypes['Order'] | null; // Order me: NexusGenRootTypes['User']; // User! } User: { // field return type email: string; // String! id: string; // String! name: string | null; // String role: string; // String! } } export interface NexusGenArgTypes { Customer: { addresses: { // args after?: NexusGenInputs['AddressWhereUniqueInput'] | null; // AddressWhereUniqueInput before?: NexusGenInputs['AddressWhereUniqueInput'] | null; // AddressWhereUniqueInput first?: number | null; // Int last?: number | null; // Int } } Mutation: { addProductionLog: { // args action: NexusGenEnums['ProductionLogType']; // ProductionLogType! orderItemId: string; // ID! pieces: number; // Int! } addUser: { // args input: NexusGenInputs['CreateUserInput']; // CreateUserInput! } changePassword: { // args newPassword: string; // String! oldPassword: string; // String! } createCustomer: { // args input: NexusGenInputs['CreateCustomerInput']; // CreateCustomerInput! } createMaterial: { // args name: string; // String! price: number; // Float! } createOrder: { // args input: NexusGenInputs['OrderInput']; // OrderInput! number: number; // Int! } deleteCustomer: { // args id: string; // ID! } deleteMaterial: { // args id: string; // ID! } deleteOrder: { // args id: string; // ID! } deleteUser: { // args id: string; // ID! } login: { // args email: string; // String! password: string; // String! } updateCustomer: { // args input: NexusGenInputs['UpdateCustomerInput']; // UpdateCustomerInput! } updateMaterial: { // args id: string; // ID! name?: string | null; // String price?: number | null; // Float } updateOrder: { // args id: string; // ID! input: NexusGenInputs['UpdateOrderInput']; // UpdateOrderInput! } updateOrderNote: { // args id: string; // ID! note?: string | null; // String } updateOrderStatus: { // args id: string; // ID! status: NexusGenEnums['OrderStatus']; // OrderStatus! } updateUser: { // args id: string; // ID! input: NexusGenInputs['UpdateUserInput']; // UpdateUserInput! } } Order: { items: { // args after?: NexusGenInputs['OrderItemWhereUniqueInput'] | null; // OrderItemWhereUniqueInput before?: NexusGenInputs['OrderItemWhereUniqueInput'] | null; // OrderItemWhereUniqueInput first?: number | null; // Int last?: number | null; // Int orderBy?: NexusGenInputs['OrderItemsOrderByInput'][] | null; // [OrderItemsOrderByInput!] } } Query: { getAllCustomers: { // args first?: number | null; // Int search?: string | null; // String skip?: number | null; // Int } getAllMaterials: { // args deleted?: boolean | null; // Boolean } getAllOrders: { // args customerId?: string | null; // ID first?: number | null; // Int orderByUrgency?: NexusGenEnums['OrderByArg'] | null; // OrderByArg skip?: number | null; // Int status?: NexusGenEnums['OrderStatus'] | null; // OrderStatus } getCustomer: { // args id: string; // ID! } getCustomerHelperInfo: { // args partialIdentificationNumber: string; // String! } getOrder: { // args id: string; // ID! } getOrderByNumber: { // args number: number; // Int! } } } export interface NexusGenAbstractResolveReturnTypes { } export interface NexusGenInheritedFields {} export type NexusGenObjectNames = "Address" | "AuthPayload" | "Customer" | "CustomerHelperInfo" | "CustomerPaginated" | "Material" | "Mutation" | "Order" | "OrderItem" | "OrderPaginated" | "ProductionLog" | "Query" | "User"; export type NexusGenInputNames = "AddressInput" | "AddressWhereUniqueInput" | "CreateCustomerInput" | "CreateUserInput" | "OrderInput" | "OrderItemInput" | "OrderItemWhereUniqueInput" | "OrderItemsOrderByInput" | "UpdateAddressInput" | "UpdateCustomerInput" | "UpdateOrderInput" | "UpdateOrderItemInput" | "UpdateUserInput"; export type NexusGenEnumNames = "OrderByArg" | "OrderStatus" | "ProductionLogType" | "SortOrder" | "UserRole"; export type NexusGenInterfaceNames = never; export type NexusGenScalarNames = "Boolean" | "DateTime" | "Float" | "ID" | "Int" | "String"; export type NexusGenUnionNames = never; export interface NexusGenTypes { context: Context.Context; inputTypes: NexusGenInputs; rootTypes: NexusGenRootTypes; argTypes: NexusGenArgTypes; fieldTypes: NexusGenFieldTypes; allTypes: NexusGenAllTypes; inheritedFields: NexusGenInheritedFields; objectNames: NexusGenObjectNames; inputNames: NexusGenInputNames; enumNames: NexusGenEnumNames; interfaceNames: NexusGenInterfaceNames; scalarNames: NexusGenScalarNames; unionNames: NexusGenUnionNames; allInputTypes: NexusGenTypes['inputNames'] | NexusGenTypes['enumNames'] | NexusGenTypes['scalarNames']; allOutputTypes: NexusGenTypes['objectNames'] | NexusGenTypes['enumNames'] | NexusGenTypes['unionNames'] | NexusGenTypes['interfaceNames'] | NexusGenTypes['scalarNames']; allNamedTypes: NexusGenTypes['allInputTypes'] | NexusGenTypes['allOutputTypes'] abstractTypes: NexusGenTypes['interfaceNames'] | NexusGenTypes['unionNames']; abstractResolveReturn: NexusGenAbstractResolveReturnTypes; } declare global { interface NexusGenPluginTypeConfig<TypeName extends string> { } interface NexusGenPluginFieldConfig<TypeName extends string, FieldName extends string> { } interface NexusGenPluginSchemaConfig { } }
the_stack
import Page = require('../../../../base/Page'); import Response = require('../../../../http/response'); import V1 = require('../../V1'); import serialize = require('../../../../base/serialize'); import { FieldList } from './task/field'; import { FieldListInstance } from './task/field'; import { SampleList } from './task/sample'; import { SampleListInstance } from './task/sample'; import { SerializableClass } from '../../../../interfaces'; import { TaskActionsList } from './task/taskActions'; import { TaskActionsListInstance } from './task/taskActions'; import { TaskStatisticsList } from './task/taskStatistics'; import { TaskStatisticsListInstance } from './task/taskStatistics'; /** * Initialize the TaskList * * PLEASE NOTE that this class contains preview products that are subject to * change. Use them with caution. If you currently do not have developer preview * access, please contact help@twilio.com. * * @param version - Version of the resource * @param assistantSid - The SID of the Assistant that is the parent of the resource */ declare function TaskList(version: V1, assistantSid: string): TaskListInstance; /** * Options to pass to update * * @property actions - The JSON string that specifies the actions that instruct the Assistant on how to perform the task * @property actionsUrl - The URL from which the Assistant can fetch actions * @property friendlyName - A string to describe the resource * @property uniqueName - An application-defined string that uniquely identifies the resource */ interface TaskInstanceUpdateOptions { actions?: object; actionsUrl?: string; friendlyName?: string; uniqueName?: string; } interface TaskListInstance { /** * @param sid - sid of instance */ (sid: string): TaskContext; /** * create a TaskInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ create(opts: TaskListInstanceCreateOptions, callback?: (error: Error | null, item: TaskInstance) => any): Promise<TaskInstance>; /** * Streams TaskInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Function to process each record */ each(opts?: TaskListInstanceEachOptions, callback?: (item: TaskInstance, done: (err?: Error) => void) => void): void; /** * Constructs a task * * @param sid - The unique string that identifies the resource to fetch */ get(sid: string): TaskContext; /** * Retrieve a single target page of TaskInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param targetUrl - API-generated URL for the requested results page * @param callback - Callback to handle list of records */ getPage(targetUrl?: string, callback?: (error: Error | null, items: TaskPage) => any): Promise<TaskPage>; /** * Lists TaskInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ list(opts?: TaskListInstanceOptions, callback?: (error: Error | null, items: TaskInstance[]) => any): Promise<TaskInstance[]>; /** * Retrieve a single page of TaskInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ page(opts?: TaskListInstancePageOptions, callback?: (error: Error | null, items: TaskPage) => any): Promise<TaskPage>; /** * Provide a user-friendly representation */ toJSON(): any; } /** * Options to pass to create * * @property actions - The JSON string that specifies the actions that instruct the Assistant on how to perform the task * @property actionsUrl - The URL from which the Assistant can fetch actions * @property friendlyName - descriptive string that you create to describe the new resource * @property uniqueName - An application-defined string that uniquely identifies the resource */ interface TaskListInstanceCreateOptions { actions?: object; actionsUrl?: string; friendlyName?: string; uniqueName: string; } /** * Options to pass to each * * @property callback - * Function to process each record. If this and a positional * callback are passed, this one will be used * @property done - Function to be called upon completion of streaming * @property limit - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) */ interface TaskListInstanceEachOptions { callback?: (item: TaskInstance, done: (err?: Error) => void) => void; done?: Function; limit?: number; pageSize?: number; } /** * Options to pass to list * * @property limit - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) */ interface TaskListInstanceOptions { limit?: number; pageSize?: number; } /** * Options to pass to page * * @property pageNumber - Page Number, this value is simply for client state * @property pageSize - Number of records to return, defaults to 50 * @property pageToken - PageToken provided by the API */ interface TaskListInstancePageOptions { pageNumber?: number; pageSize?: number; pageToken?: string; } interface TaskPayload extends TaskResource, Page.TwilioResponsePayload { } interface TaskResource { account_sid: string; actions_url: string; assistant_sid: string; date_created: Date; date_updated: Date; friendly_name: string; links: string; sid: string; unique_name: string; url: string; } interface TaskSolution { assistantSid?: string; } declare class TaskContext { /** * Initialize the TaskContext * * PLEASE NOTE that this class contains preview products that are subject to * change. Use them with caution. If you currently do not have developer preview * access, please contact help@twilio.com. * * @param version - Version of the resource * @param assistantSid - The SID of the Assistant that is the parent of the resource to fetch * @param sid - The unique string that identifies the resource to fetch */ constructor(version: V1, assistantSid: string, sid: string); /** * fetch a TaskInstance * * @param callback - Callback to handle processed record */ fetch(callback?: (error: Error | null, items: TaskInstance) => any): Promise<TaskInstance>; fields: FieldListInstance; /** * remove a TaskInstance * * @param callback - Callback to handle processed record */ remove(callback?: (error: Error | null, items: TaskInstance) => any): void; samples: SampleListInstance; statistics: TaskStatisticsListInstance; taskActions: TaskActionsListInstance; /** * Provide a user-friendly representation */ toJSON(): any; /** * update a TaskInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ update(opts?: TaskInstanceUpdateOptions, callback?: (error: Error | null, items: TaskInstance) => any): Promise<TaskInstance>; } declare class TaskInstance extends SerializableClass { /** * Initialize the TaskContext * * PLEASE NOTE that this class contains preview products that are subject to * change. Use them with caution. If you currently do not have developer preview * access, please contact help@twilio.com. * * @param version - Version of the resource * @param payload - The instance payload * @param assistantSid - The SID of the Assistant that is the parent of the resource * @param sid - The unique string that identifies the resource to fetch */ constructor(version: V1, payload: TaskPayload, assistantSid: string, sid: string); private _proxy: TaskContext; accountSid: string; actionsUrl: string; assistantSid: string; dateCreated: Date; dateUpdated: Date; /** * fetch a TaskInstance * * @param callback - Callback to handle processed record */ fetch(callback?: (error: Error | null, items: TaskInstance) => any): void; /** * Access the fields */ fields(): FieldListInstance; friendlyName: string; links: string; /** * remove a TaskInstance * * @param callback - Callback to handle processed record */ remove(callback?: (error: Error | null, items: TaskInstance) => any): void; /** * Access the samples */ samples(): SampleListInstance; sid: string; /** * Access the statistics */ statistics(): TaskStatisticsListInstance; /** * Access the taskActions */ taskActions(): TaskActionsListInstance; /** * Provide a user-friendly representation */ toJSON(): any; uniqueName: string; /** * update a TaskInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ update(opts?: TaskInstanceUpdateOptions, callback?: (error: Error | null, items: TaskInstance) => any): void; url: string; } declare class TaskPage extends Page<V1, TaskPayload, TaskResource, TaskInstance> { /** * Initialize the TaskPage * * PLEASE NOTE that this class contains preview products that are subject to * change. Use them with caution. If you currently do not have developer preview * access, please contact help@twilio.com. * * @param version - Version of the resource * @param response - Response from the API * @param solution - Path solution */ constructor(version: V1, response: Response<string>, solution: TaskSolution); /** * Build an instance of TaskInstance * * @param payload - Payload response from the API */ getInstance(payload: TaskPayload): TaskInstance; /** * Provide a user-friendly representation */ toJSON(): any; } export { TaskContext, TaskInstance, TaskList, TaskListInstance, TaskListInstanceCreateOptions, TaskListInstanceEachOptions, TaskListInstanceOptions, TaskListInstancePageOptions, TaskPage, TaskPayload, TaskResource, TaskSolution }
the_stack
import Conditions from '../../../../../resources/conditions'; import NetRegexes from '../../../../../resources/netregexes'; import { Responses } from '../../../../../resources/responses'; import ZoneId from '../../../../../resources/zone_id'; import { RaidbossData } from '../../../../../types/data'; import { TriggerSet } from '../../../../../types/trigger'; export interface Data extends RaidbossData { lunarFlares?: number; } const triggerSet: TriggerSet<Data> = { zoneId: ZoneId.Paglthan, timelineFile: 'paglthan.txt', timelineTriggers: [ { // This is a rear cone attack that always follows Wide Blaster. // It has a cast time of under a GCD, so we pre-warn during Wide Blaster. // Only the sides are safe to call at this moment. id: 'Paglthan Spike Flail', regex: /Spike Flail/, beforeSeconds: 4, response: Responses.goSides(), }, ], triggers: [ { id: 'Paglthan Critical Rip', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '5C4E', source: 'Amhuluk' }), netRegexDe: NetRegexes.startsUsing({ id: '5C4E', source: 'Amhuluk' }), netRegexFr: NetRegexes.startsUsing({ id: '5C4E', source: 'Amhuluk' }), netRegexJa: NetRegexes.startsUsing({ id: '5C4E', source: 'アムルック' }), netRegexCn: NetRegexes.startsUsing({ id: '5C4E', source: '阿姆鲁克' }), netRegexKo: NetRegexes.startsUsing({ id: '5C4E', source: '아물룩' }), response: Responses.tankBuster(), }, { id: 'Paglthan Electric Burst', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '5C4D', source: 'Amhuluk', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '5C4D', source: 'Amhuluk', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '5C4D', source: 'Amhuluk', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '5C4D', source: 'アムルック', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '5C4D', source: '阿姆鲁克', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '5C4D', source: '아물룩', capture: false }), response: Responses.aoe(), }, { id: 'Paglthan Lightning Rod Gain', type: 'GainsEffect', netRegex: NetRegexes.gainsEffect({ effectId: 'A0E' }), condition: Conditions.targetIsYou(), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Go to a lightning rod', de: 'Geh zu einem Blitzableiter', fr: 'Allez sur un paratonnerre', ja: '避雷針に円範囲を転嫁', cn: '蹭一下无AoE的塔', ko: '장판 기둥에 넘기기', }, }, }, { id: 'Paglthan Lightning Rod Lose', type: 'LosesEffect', netRegex: NetRegexes.losesEffect({ effectId: 'A0E' }), condition: Conditions.targetIsYou(), response: Responses.goMiddle(), }, { id: 'Paglthan Ballistic', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '5C97', source: 'Magitek Fortress', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '5C97', source: 'Magitek-Festung', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '5C97', source: 'Forteresse Magitek', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '5C97', source: '魔導フォートレス', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '5C97', source: '魔导要塞', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '5C97', source: '마도 요새', capture: false }), response: Responses.knockback(), }, { id: 'Paglthan Defensive Reaction', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '5C9E', source: 'Magitek Core', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '5C9E', source: 'Magitek-Reaktor', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '5C9E', source: 'Réacteur Magitek', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '5C9E', source: '魔導コア', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '5C9E', source: '魔导核心', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '5C9E', source: '마도핵', capture: false }), response: Responses.aoe(), }, { id: 'Paglthan Twisted Scream', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '5B47', source: 'Lunar Bahamut', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '5B47', source: 'Luna-Bahamut', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '5B47', source: 'Luna-Bahamut', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '5B47', source: 'ルナバハムート', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '5B47', source: '真月巴哈姆特', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '5B47', source: '루나 바하무트', capture: false }), response: Responses.aoe(), }, { id: 'Paglthan Akh Morn', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '005D' }), response: Responses.stackMarkerOn(), }, { id: 'Paglthan Mega Flare Spread', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '0017' }), condition: Conditions.targetIsYou(), response: Responses.spread(), }, { id: 'Paglthan Mega Flare Move', type: 'Ability', netRegex: NetRegexes.ability({ id: '5B4D', source: 'Lunar Bahamut' }), netRegexDe: NetRegexes.ability({ id: '5B4D', source: 'Luna-Bahamut' }), netRegexFr: NetRegexes.ability({ id: '5B4D', source: 'Luna-Bahamut' }), netRegexJa: NetRegexes.ability({ id: '5B4D', source: 'ルナバハムート' }), netRegexCn: NetRegexes.ability({ id: '5B4D', source: '真月巴哈姆特' }), netRegexKo: NetRegexes.ability({ id: '5B4D', source: '루나 바하무트' }), condition: Conditions.targetIsYou(), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Away from circles', de: 'Weg von den Kreisen', fr: 'Éloignez-vous des cercles', ja: '円を避ける', cn: '远离圈圈', ko: '장판 피하기', }, }, }, { id: 'Paglthan Kan Rhai Marker', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '0104' }), condition: Conditions.targetIsYou(), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Kan Rhai on YOU', de: 'Kan Rhai auf DIR', fr: 'Kan Rhai sur VOUS', ja: '自分にカン・ラーイ', cn: '十字AoE点名', ko: '십자 장판 대상자', }, }, }, { id: 'Paglthan Kan Rhai Move', type: 'Ability', netRegex: NetRegexes.ability({ id: '5B4F', source: 'Lunar Bahamut', capture: false }), netRegexDe: NetRegexes.ability({ id: '5B4F', source: 'Luna-Bahamut', capture: false }), netRegexFr: NetRegexes.ability({ id: '5B4F', source: 'Luna-Bahamut', capture: false }), netRegexJa: NetRegexes.ability({ id: '5B4F', source: 'ルナバハムート', capture: false }), netRegexCn: NetRegexes.ability({ id: '5B4F', source: '真月巴哈姆特', capture: false }), netRegexKo: NetRegexes.ability({ id: '5B4F', source: '루나 바하무트', capture: false }), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Away from crosses', de: 'Weg von dem Kreuz', fr: 'Éloignez-vous des croix', ja: '十字から離れる', cn: '远离十字', ko: '십자 피하기', }, }, }, { id: 'Paglthan Lunar Flare Reset', type: 'Ability', netRegex: NetRegexes.ability({ id: '5B49', source: 'Lunar Bahamut', capture: false }), netRegexDe: NetRegexes.ability({ id: '5B49', source: 'Luna-Bahamut', capture: false }), netRegexFr: NetRegexes.ability({ id: '5B49', source: 'Luna-Bahamut', capture: false }), netRegexJa: NetRegexes.ability({ id: '5B49', source: 'ルナバハムート', capture: false }), netRegexCn: NetRegexes.ability({ id: '5B49', source: '真月巴哈姆特', capture: false }), netRegexKo: NetRegexes.ability({ id: '5B49', source: '루나 바하무트', capture: false }), run: (data) => data.lunarFlares = 0, }, { id: 'Paglthan Lunar Flare Collect', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '5B4[AB]', source: 'Lunar Bahamut', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '5B4[AB]', source: 'Luna-Bahamut', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '5B4[AB]', source: 'Luna-Bahamut', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '5B4[AB]', source: 'ルナバハムート', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '5B4[AB]', source: '真月巴哈姆特', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '5B4[AB]', source: '루나 바하무트', capture: false }), run: (data) => data.lunarFlares = (data.lunarFlares ?? 0) + 1, }, { // Get middle is 4x5B4A and 4x5B4B, get outside is 5x5B4A id: 'Paglthan Lunar Flare', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '5B4[AB]', source: 'Lunar Bahamut', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '5B4[AB]', source: 'Luna-Bahamut', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '5B4[AB]', source: 'Luna-Bahamut', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '5B4[AB]', source: 'ルナバハムート', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '5B4[AB]', source: '真月巴哈姆特', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '5B4[AB]', source: '루나 바하무트', capture: false }), delaySeconds: 0.5, suppressSeconds: 1, alertText: (data, _matches, output) => { if (data.lunarFlares === 5) return output.getOutsideBetweenCircles!(); if (data.lunarFlares === 8) return output.getMiddle!(); }, outputStrings: { getMiddle: { en: 'Get Middle', de: 'In die Mitte gehen', fr: 'Allez au milieu', ja: '中心へ', cn: '中间', ko: '중앙으로', }, getOutsideBetweenCircles: { en: 'Get Outside Between Circles', de: 'Geh zum Rand zwichen den Kreisen', fr: 'Allez à l\'extérieur entre les cercles', ja: '外周の円の隙間へ', cn: '去外圈交接处', ko: '바깥 장판 사이로', }, }, }, { id: 'Paglthan Flatten', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '5B58', source: 'Lunar Bahamut' }), netRegexDe: NetRegexes.startsUsing({ id: '5B58', source: 'Luna-Bahamut' }), netRegexFr: NetRegexes.startsUsing({ id: '5B58', source: 'Luna-Bahamut' }), netRegexJa: NetRegexes.startsUsing({ id: '5B58', source: 'ルナバハムート' }), netRegexCn: NetRegexes.startsUsing({ id: '5B58', source: '真月巴哈姆特' }), netRegexKo: NetRegexes.startsUsing({ id: '5B58', source: '루나 바하무트' }), response: Responses.tankBuster(), }, { id: 'Paglthan Giga Flare', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '5B57', source: 'Lunar Bahamut', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '5B57', source: 'Luna-Bahamut', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '5B57', source: 'Luna-Bahamut', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '5B57', source: 'ルナバハムート', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '5B57', source: '真月巴哈姆特', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '5B57', source: '루나 바하무트', capture: false }), response: Responses.aoe(), }, ], timelineReplace: [ { 'locale': 'de', 'replaceSync': { 'Amhuluk': 'Amhuluk', 'Lunar Bahamut': 'Luna-Bahamut', 'Magitek Fortress': 'Magitek-Festung', 'Magitek Core': 'Magitek-Reaktor', 'Sunseat': 'Dämmergarten', 'The Gathering Ring': 'Festplatz von Zolm\'ak', }, 'replaceText': { '\\(circles\\)': '(Kreise)', '\\(explosions\\)': '(Explosionen)', '--Levin orbs--': '--Elektrosphären--', 'Akh Morn': 'Akh Morn', 'Big Burst': 'Detonation', 'Critical Rip': 'Kritischer Riss', 'Electric Burst': 'Stromstoß', 'Flatten': 'Einebnen', 'Gigaflare': 'Gigaflare', 'Kan Rhai': 'Kan Rhai', 'Lightning Bolt': 'Blitzschlag', 'Lunar Flare': 'Lunaflare', 'Megaflare(?! Dive)': 'Megaflare', 'Megaflare Dive': 'Megaflare-Sturz', 'Perigean Breath': 'Perigäum-Atem', 'Spike Flail': 'Dornendresche', 'Thundercall': 'Donnerruf', 'Twisted Scream': 'Verzerrtes Brüllen', 'Upburst': 'Quantengravitation', 'Wide Blaster': 'Weitwinkel-Blaster', }, }, { 'locale': 'fr', 'replaceSync': { 'Amhuluk': 'Amhuluk', 'Lunar Bahamut': 'Luna-Bahamut', 'Magitek Fortress': 'forteresse magitek', 'Magitek Core': 'réacteur magitek', 'Sunseat': 'Clos du Crépuscule', 'The Gathering Ring': 'Autel de Zolm\'ak', }, 'replaceText': { '\\(circles\\)': '(cercles)', '\\(explosions\\)': '(explosions)', '--Levin orbs--': '--Orbes de foudre--', 'Akh Morn': 'Akh Morn', 'Big Burst': 'Grosse explosion', 'Critical Rip': 'Griffure critique', 'Electric Burst': 'Salve électrique', 'Flatten': 'Compression', 'Gigaflare': 'GigaBrasier', 'Kan Rhai': 'Kan Rhai', 'Lightning Bolt': 'Éclair de foudre', 'Lunar Flare': 'LunaBrasier', 'Megaflare(?! Dive)': 'MégaBrasier', 'Megaflare Dive': 'Plongeon MégaBrasier', 'Perigean Breath': 'Souffle de périgée', 'Spike Flail': 'Fléau à pointes', 'Thundercall': 'Drain fulminant', 'Twisted Scream': 'Hurlement de l\'Anomalie', 'Upburst': 'Saillie', 'Wide Blaster': 'Fulguration large', }, }, { 'locale': 'ja', 'missingTranslations': true, 'replaceSync': { 'Amhuluk': 'アムルック', 'Lunar Bahamut': 'ルナバハムート', 'Magitek Fortress': '魔導フォートレス', 'Magitek Core': '魔導コア', 'Sunseat': '黄昏の庭', 'The Gathering Ring': 'ゾレマク祭場', }, 'replaceText': { 'Akh Morn': 'アク・モーン', 'Big Burst': '大爆発', 'Critical Rip': 'クリティカルリップ', 'Electric Burst': 'エレクトリックバースト', 'Flatten': 'フラッテン', 'Gigaflare': 'ギガフレア', 'Kan Rhai': 'カン・ラーイ', 'Lightning Bolt': '落雷', 'Lunar Flare': 'ルナフレア', 'Megaflare(?! Dive)': 'メガフレア', 'Megaflare Dive': 'メガフレアダイブ', 'Perigean Breath': 'ペリジアンブレス', 'Spike Flail': 'スパイクフレイル', 'Thundercall': '招雷', 'Twisted Scream': '異形の咆哮', 'Upburst': '突出', 'Wide Blaster': 'ワイドブラスター', }, }, { 'locale': 'cn', 'replaceSync': { 'Amhuluk': '阿姆鲁克', 'Lunar Bahamut': '真月巴哈姆特', 'Magitek Fortress': '魔导要塞', 'Magitek Core': '魔导核心', 'Sunseat': '黄昏庭园', 'The Gathering Ring': '佐尔玛刻祭场', }, 'replaceText': { '\\(circles\\)': '圈', '\\(explosions\\)': '(爆炸)', '--Levin orbs--': '--电球--', 'Akh Morn': '死亡轮回', 'Big Burst': '大爆炸', 'Critical Rip': '暴击撕裂', 'Electric Burst': '电光爆发', 'Flatten': '夷为平地', 'Gigaflare': '十亿核爆', 'Kan Rhai': '天光交错', 'Lightning Bolt': '落雷', 'Lunar Flare': '真月核爆', 'Megaflare(?! Dive)': '百万核爆', 'Megaflare Dive': '百万核爆冲', 'Perigean Breath': '近地吐息', 'Spike Flail': '刃尾横扫', 'Thundercall': '招雷', 'Twisted Scream': '异形咆哮', 'Upburst': '顶起', 'Wide Blaster': '广域冲击波', }, }, { 'locale': 'ko', 'replaceSync': { 'Amhuluk': '아물룩', 'Lunar Bahamut': '루나 바하무트', 'Magitek Fortress': '마도 요새', 'Magitek Core': '마도핵', 'Sunseat': '황혼의 뜰', 'The Gathering Ring': '졸마크 제단', }, 'replaceText': { '\\(circles\\)': '원', '\\(explosions\\)': '(폭발)', '--Levin orbs--': '--번개 구슬--', 'Akh Morn': '아크 몬', 'Big Burst': '대폭발', 'Critical Rip': '찢어가르기', 'Electric Burst': '전하 폭발', 'Flatten': '압사', 'Gigaflare': '기가플레어', 'Kan Rhai': '칸 라이', 'Lightning Bolt': '번개 발생', 'Lunar Flare': '루나 플레어', 'Megaflare(?! Dive)': '메가플레어', 'Megaflare Dive': '메가플레어 다이브', 'Perigean Breath': '근지점 입김', 'Spike Flail': '가시 매타작', 'Thundercall': '초뢰', 'Twisted Scream': '기괴한 포효', 'Upburst': '돌출', 'Wide Blaster': '광범위 블래스터', }, }, ], }; export default triggerSet;
the_stack
export enum MOUSE { LEFT = 0, MIDDLE = 1, RIGHT = 2, ROTATE = 0, DOLLY = 1, PAN = 2, } export enum TOUCH { ROTATE = 0, PAN = 1, DOLLY_PAN = 2, DOLLY_ROTATE = 3, } // GL STATE CONSTANTS export enum CullFace { CullFaceNone = 0, CullFaceBack = 1, CullFaceFront = 2, CullFaceFrontBack = 3, } export const CullFaceNone: CullFace = 0 export const CullFaceBack: CullFace = 1 export const CullFaceFront: CullFace = 2 export const CullFaceFrontBack: CullFace = 3 // Shadowing Type export enum ShadowMapType { BasicShadowMap = 0, PCFShadowMap = 1, PCFSoftShadowMap = 2, VSMShadowMap = 3, } export const BasicShadowMap: ShadowMapType = 0 export const PCFShadowMap: ShadowMapType = 1 export const PCFSoftShadowMap: ShadowMapType = 2 export const VSMShadowMap: ShadowMapType = 3 // MATERIAL CONSTANTS // side export enum Side { FrontSide, BackSide, DoubleSide, } // shadow side export enum ShadowSide { FrontSide, BackSide, DoubleSide, AutoSide, } // shading export enum Shading { FlatShading = 1, SmoothShading = 2, } export const FlatShading: Shading = 1 export const SmoothShading: Shading = 2 export enum Precision { Highp, Mediump, Lowp, Default, } export enum PowerPreference { HighPerformance, LowPower, Default, } // colors export enum Colors { NoColors = 0, FaceColors = 1, VertexColors = 2, } export const NoColors: Colors = 0 export const FaceColors: Colors = 1 export const VertexColors: Colors = 2 // blending modes export enum Blending { NoBlending = 0, NormalBlending = 1, AdditiveBlending = 2, SubtractiveBlending = 3, MultiplyBlending = 4, CustomBlending = 5, } export const NoBlending: Blending = 0 export const NormalBlending: Blending = 1 export const AdditiveBlending: Blending = 2 export const SubtractiveBlending: Blending = 3 export const MultiplyBlending: Blending = 4 export const CustomBlending: Blending = 5 // custom blending equations // (numbers start from 100 not to clash with other // mappings to OpenGL constants defined in Texture.js) export enum BlendingEquation { AddEquation = 100, SubtractEquation = 101, ReverseSubtractEquation = 102, MinEquation = 103, MaxEquation = 104, } export const AddEquation: BlendingEquation = 100 export const SubtractEquation: BlendingEquation = 101 export const ReverseSubtractEquation: BlendingEquation = 102 export const MinEquation: BlendingEquation = 103 export const MaxEquation: BlendingEquation = 104 // custom blending destination factors export enum BlendingDstFactor { ZeroFactor = 200, OneFactor = 201, SrcColorFactor = 202, OneMinusSrcColorFactor = 203, SrcAlphaFactor = 204, OneMinusSrcAlphaFactor = 205, DstAlphaFactor = 206, OneMinusDstAlphaFactor = 207, DstColorFactor = 208, OneMinusDstColorFactor = 209, } // custom blending source factors (contains the same values as BlendingDstFactor, // plus one additional value that is only valid as a source value) export enum BlendingSrcFactor { ZeroFactor = 200, OneFactor = 201, SrcColorFactor = 202, OneMinusSrcColorFactor = 203, SrcAlphaFactor = 204, OneMinusSrcAlphaFactor = 205, DstAlphaFactor = 206, OneMinusDstAlphaFactor = 207, DstColorFactor = 208, OneMinusDstColorFactor = 209, SrcAlphaSaturateFactor = 210, } // depth modes export enum DepthModes { NeverDepth = 0, AlwaysDepth = 1, LessDepth = 2, LessEqualDepth = 3, EqualDepth = 4, GreaterEqualDepth = 5, GreaterDepth = 6, NotEqualDepth = 7, } export const NeverDepth: DepthModes = 0 export const AlwaysDepth: DepthModes = 1 export const LessDepth: DepthModes = 2 export const LessEqualDepth: DepthModes = 3 export const EqualDepth: DepthModes = 4 export const GreaterEqualDepth: DepthModes = 5 export const GreaterDepth: DepthModes = 6 export const NotEqualDepth: DepthModes = 7 // TEXTURE CONSTANTS // Operations export enum Combine { MultiplyOperation = 0, MixOperation = 1, AddOperation = 2, } export const MultiplyOperation: Combine = 0 export const MixOperation: Combine = 1 export const AddOperation: Combine = 2 // Tone Mapping modes export enum ToneMapping { NoToneMapping = 0, LinearToneMapping = 1, ReinhardToneMapping = 2, Uncharted2ToneMapping = 3, CineonToneMapping = 4, ACESFilmicToneMapping = 5, } export const NoToneMapping: ToneMapping = ToneMapping.NoToneMapping export const LinearToneMapping: ToneMapping = ToneMapping.LinearToneMapping export const ReinhardToneMapping: ToneMapping = ToneMapping.ReinhardToneMapping export const Uncharted2ToneMapping: ToneMapping = ToneMapping.Uncharted2ToneMapping export const CineonToneMapping: ToneMapping = ToneMapping.CineonToneMapping export const ACESFilmicToneMapping: ToneMapping = ToneMapping.ACESFilmicToneMapping // Mapping modes export enum Mapping { UVMapping = 300, CubeReflectionMapping = 301, CubeRefractionMapping = 302, EquirectangularReflectionMapping = 303, EquirectangularRefractionMapping = 304, SphericalReflectionMapping = 305, CubeUVReflectionMapping = 306, CubeUVRefractionMapping = 307, } export const UVMapping: Mapping = 300 export const CubeReflectionMapping: Mapping = 301 export const CubeRefractionMapping: Mapping = 302 export const EquirectangularReflectionMapping: Mapping = 303 export const EquirectangularRefractionMapping: Mapping = 304 export const SphericalReflectionMapping: Mapping = 305 export const CubeUVReflectionMapping: Mapping = 306 export const CubeUVRefractionMapping: Mapping = 307 // Wrapping modes export enum Wrapping { RepeatWrapping = 1000, ClampToEdgeWrapping = 1001, MirroredRepeatWrapping = 1002, } export const RepeatWrapping: Wrapping = 1000 export const ClampToEdgeWrapping: Wrapping = 1001 export const MirroredRepeatWrapping: Wrapping = 1002 // Filters export enum TextureFilter { NearestFilter = 1003, NearestMipMapNearestFilter = 1004, NearestMipMapLinearFilter = 1005, LinearFilter = 1006, LinearMipMapNearestFilter = 1007, LinearMipMapLinearFilter = 1008, } export const NearestFilter: TextureFilter = 1003 export const NearestMipMapNearestFilter: TextureFilter = 1004 export const NearestMipMapLinearFilter: TextureFilter = 1005 export const LinearFilter: TextureFilter = 1006 export const LinearMipMapNearestFilter: TextureFilter = 1007 export const LinearMipMapLinearFilter: TextureFilter = 1008 // Data types export enum TextureDataType { UnsignedByteType = 1009, ByteType = 1010, ShortType = 1011, UnsignedShortType = 1012, IntType = 1013, UnsignedIntType = 1014, FloatType = 1015, HalfFloatType = 1016, } export const UnsignedByteType: TextureDataType = 1009 export const ByteType: TextureDataType = 1010 export const ShortType: TextureDataType = 1011 export const UnsignedShortType: TextureDataType = 1012 export const IntType: TextureDataType = 1013 export const UnsignedIntType: TextureDataType = 1014 export const FloatType: TextureDataType = 1015 export const HalfFloatType: TextureDataType = 1016 // Pixel types export enum PixelType { UnsignedShort4444Type = 1017, UnsignedShort5551Type = 1018, UnsignedShort565Type = 1019, UnsignedInt248Type = 1020, } export const UnsignedShort4444Type: PixelType = 1017 export const UnsignedShort5551Type: PixelType = 1018 export const UnsignedShort565Type: PixelType = 1019 export const UnsignedInt248Type: PixelType = 1020 // Pixel formats export enum PixelFormat { AlphaFormat = 1021, RGBFormat = 1022, RGBAFormat = 1023, LuminanceFormat = 1024, LuminanceAlphaFormat = 1025, RGBEFormat = RGBAFormat, DepthFormat = 1026, DepthStencilFormat = 1027, RedFormat = 1028, } export const AlphaFormat: PixelFormat = 1021 export const RGBFormat: PixelFormat = 1022 export const RGBAFormat: PixelFormat = 1023 export const LuminanceFormat: PixelFormat = 1024 export const LuminanceAlphaFormat: PixelFormat = 1025 export const RGBEFormat: PixelFormat = RGBAFormat export const DepthFormat: PixelFormat = 1026 export const DepthStencilFormat: PixelFormat = 1027 export const RedFormat: PixelFormat = 1028 // Compressed texture formats export enum CompressedPixelFormat { // DDS / ST3C Compressed texture formats RGB_S3TC_DXT1_Format = 33776, RGBA_S3TC_DXT1_Format = 33777, RGBA_S3TC_DXT3_Format = 33778, RGBA_S3TC_DXT5_Format = 33779, // PVRTC compressed './texture formats RGB_PVRTC_4BPPV1_Format = 35840, RGB_PVRTC_2BPPV1_Format = 35841, RGBA_PVRTC_4BPPV1_Format = 35842, RGBA_PVRTC_2BPPV1_Format = 35843, // ETC compressed texture formats RGB_ETC1_Format = 36196, // ASTC compressed texture formats RGBA_ASTC_4x4_Format = 37808, RGBA_ASTC_5x4_Format = 37809, RGBA_ASTC_5x5_Format = 37810, RGBA_ASTC_6x5_Format = 37811, RGBA_ASTC_6x6_Format = 37812, RGBA_ASTC_8x5_Format = 37813, RGBA_ASTC_8x6_Format = 37814, RGBA_ASTC_8x8_Format = 37815, RGBA_ASTC_10x5_Format = 37816, RGBA_ASTC_10x6_Format = 37817, RGBA_ASTC_10x8_Format = 37818, RGBA_ASTC_10x10_Format = 37819, RGBA_ASTC_12x10_Format = 37820, RGBA_ASTC_12x12_Format = 37821, } // DDS / ST3C Compressed texture formats export const RGB_S3TC_DXT1_Format: CompressedPixelFormat = 33776 export const RGBA_S3TC_DXT1_Format: CompressedPixelFormat = 33777 export const RGBA_S3TC_DXT3_Format: CompressedPixelFormat = 33778 export const RGBA_S3TC_DXT5_Format: CompressedPixelFormat = 33779 // PVRTC compressed './texture formats export const RGB_PVRTC_4BPPV1_Format: CompressedPixelFormat = 35840 export const RGB_PVRTC_2BPPV1_Format: CompressedPixelFormat = 35841 export const RGBA_PVRTC_4BPPV1_Format: CompressedPixelFormat = 35842 export const RGBA_PVRTC_2BPPV1_Format: CompressedPixelFormat = 35843 // ETC compressed texture formats export const RGB_ETC1_Format: CompressedPixelFormat = 36196 // ASTC compressed texture formats export const RGBA_ASTC_4x4_Format: CompressedPixelFormat = 37808 export const RGBA_ASTC_5x4_Format: CompressedPixelFormat = 37809 export const RGBA_ASTC_5x5_Format: CompressedPixelFormat = 37810 export const RGBA_ASTC_6x5_Format: CompressedPixelFormat = 37811 export const RGBA_ASTC_6x6_Format: CompressedPixelFormat = 37812 export const RGBA_ASTC_8x5_Format: CompressedPixelFormat = 37813 export const RGBA_ASTC_8x6_Format: CompressedPixelFormat = 37814 export const RGBA_ASTC_8x8_Format: CompressedPixelFormat = 37815 export const RGBA_ASTC_10x5_Format: CompressedPixelFormat = 37816 export const RGBA_ASTC_10x6_Format: CompressedPixelFormat = 37817 export const RGBA_ASTC_10x8_Format: CompressedPixelFormat = 37818 export const RGBA_ASTC_10x10_Format: CompressedPixelFormat = 37819 export const RGBA_ASTC_12x10_Format: CompressedPixelFormat = 37820 export const RGBA_ASTC_12x12_Format: CompressedPixelFormat = 37821 // Loop styles for AnimationAction export enum AnimationActionLoopStyles { LoopOnce = 2200, LoopRepeat = 2201, LoopPingPong = 2202, } export const LoopOnce: AnimationActionLoopStyles = 2200 export const LoopRepeat: AnimationActionLoopStyles = 2201 export const LoopPingPong: AnimationActionLoopStyles = 2202 // Interpolation export enum InterpolationModes { InterpolateDiscrete = 2300, InterpolateLinear = 2301, InterpolateSmooth = 2302, } export const InterpolateDiscrete: InterpolationModes = 2300 export const InterpolateLinear: InterpolationModes = 2301 export const InterpolateSmooth: InterpolationModes = 2302 // Interpolant ending modes export enum InterpolationEndingModes { ZeroCurvatureEnding = 2400, ZeroSlopeEnding = 2401, WrapAroundEnding = 2402, } export const ZeroCurvatureEnding: InterpolationEndingModes = 2400 export const ZeroSlopeEnding: InterpolationEndingModes = 2401 export const WrapAroundEnding: InterpolationEndingModes = 2402 // Triangle Draw modes export enum TrianglesDrawModes { TrianglesDrawMode = 0, TriangleStripDrawMode = 1, TriangleFanDrawMode = 2, } export const TrianglesDrawMode: TrianglesDrawModes = 0 export const TriangleStripDrawMode: TrianglesDrawModes = 1 export const TriangleFanDrawMode: TrianglesDrawModes = 2 // Texture Encodings export enum TextureEncoding { LinearEncoding = 3000, sRGBEncoding = 3001, GammaEncoding = 3007, RGBEEncoding = 3002, LogLuvEncoding = 3003, RGBM7Encoding = 3004, RGBM16Encoding = 3005, RGBDEncoding = 3006, } export const LinearEncoding: TextureEncoding = 3000 export const sRGBEncoding: TextureEncoding = 3001 export const GammaEncoding: TextureEncoding = 3007 export const RGBEEncoding: TextureEncoding = 3002 export const LogLuvEncoding: TextureEncoding = 3003 export const RGBM7Encoding: TextureEncoding = 3004 export const RGBM16Encoding: TextureEncoding = 3005 export const RGBDEncoding: TextureEncoding = 3006 // Depth packing strategies export enum DepthPackingStrategies { BasicDepthPacking = 3200, RGBADepthPacking = 3201, } export const BasicDepthPacking: DepthPackingStrategies = 3200 export const RGBADepthPacking: DepthPackingStrategies = 3201 // Normal Map types export enum NormalMapTypes { TangentSpaceNormalMap = 0, ObjectSpaceNormalMap = 0, } export const TangentSpaceNormalMap: NormalMapTypes = 0 export const ObjectSpaceNormalMap: NormalMapTypes = 0
the_stack
import { Loki } from "../../src/loki"; import { Collection } from "../../src/collection"; import Transform = Collection.Transform; describe("transforms", () => { interface User { name: string; owner?: string; maker?: string; } let db: Loki; let items: Collection<User>; beforeEach(() => { db = new Loki("transformTest"); items = db.addCollection<User>("items"); items.insert({name: "mjolnir", owner: "thor", maker: "dwarves"}); items.insert({name: "gungnir", owner: "odin", maker: "elves"}); items.insert({name: "tyrfing", owner: "Svafrlami", maker: "dwarves"}); items.insert({name: "draupnir", owner: "odin", maker: "elves"}); }); describe("basic find transform", () => { it("works", () => { const tx: Transform<User>[] = [ { type: "find", value: { owner: "odin" } } ]; const results = items.chain(tx).data(); expect(results.length).toBe(2); }); }); describe("basic multi-step transform", () => { it("works", () => { const tx: Transform<User>[] = [ { type: "find", value: { owner: "odin" } }, { type: "where", value: function (obj: User) { return (obj.name.indexOf("drau") !== -1); } } ]; const results = items.chain(tx).data(); expect(results.length).toBe(1); }); }); describe("parameterized find", () => { it("works", () => { const tx: Transform<User>[] = [ { type: "find", value: { owner: "[%lktxp]OwnerName" } } ]; const params = { OwnerName: "odin" }; const results = items.chain(tx, params).data(); expect(results.length).toBe(2); }); }); describe("parameterized transform with non-serializable non-params", function () { it("works", function () { interface Person { name: string; age: number; } const db = new Loki("tx.db"); const items = db.addCollection<Person>("items"); items.insert({name: "mjolnir", age: 5}); items.insert({name: "tyrfing", age: 9}); let mapper = function (item: Person) { return item.age; }; let averageReduceFunction = function (values: number[]) { let sum = 0; values.forEach(function (i) { sum += i; }); return sum / values.length; }; // so ideally, transform params are useful for // - extracting values that will change across multiple executions, and also // - extracting values which are not serializable so that the transform can be // named and serialized along with the database. // // The transform used here is not serializable so this test is just to verify // that our parameter substitution method does not have problem with // non-serializable transforms. let tx1: Transform<Person>[] = [ { type: "mapReduce", mapFunction: mapper, reduceFunction: averageReduceFunction } ]; let tx2: Transform[] = [ { type: "find", value: { age: { "$gt": "[%lktxp]minimumAge" }, } }, { type: "mapReduce", mapFunction: mapper, reduceFunction: averageReduceFunction } ] as any; // no data() call needed to mapReduce expect(items.chain(tx1) as any as number).toBe(7); expect(items.chain(tx1, {foo: 5}) as any as number).toBe(7); // params will cause a recursive shallow clone of objects before substitution expect(items.chain(tx2, {minimumAge: 4}) as any as number).toBe(7); // make sure original transform is unchanged expect(tx2[0].type).toEqual("find"); expect(tx2[0]["value"].age.$gt).toEqual("[%lktxp]minimumAge"); expect(tx2[1].type).toEqual("mapReduce"); expect(typeof tx2[1]["mapFunction"]).toEqual("function"); expect(typeof tx2[1]["reduceFunction"]).toEqual("function"); }); }); describe("parameterized where", () => { it("works", () => { const tx: Transform<User>[] = [ { type: "where", value: "[%lktxp]NameFilter" } ]; const params = { NameFilter: function (obj: User) { return (obj.name.indexOf("nir") !== -1); } }; const results = items.chain(tx, params).data(); expect(results.length).toBe(3); }); }); describe("named find transform", () => { it("works", () => { const tx: Transform<User>[] = [ { type: "find", value: { owner: "[%lktxp]OwnerName" } } ]; items.addTransform("OwnerLookup", tx); const params = { OwnerName: "odin" }; const results = items.chain("OwnerLookup", params).data(); expect(results.length).toBe(2); }); }); describe("dynamic view named transform", () => { it("works", () => { interface AB { a: string; b: number; } const testColl = db.addCollection<AB>("test"); testColl.insert({ a: "first", b: 1 }); testColl.insert({ a: "second", b: 2 }); testColl.insert({ a: "third", b: 3 }); testColl.insert({ a: "fourth", b: 4 }); testColl.insert({ a: "fifth", b: 5 }); testColl.insert({ a: "sixth", b: 6 }); testColl.insert({ a: "seventh", b: 7 }); testColl.insert({ a: "eighth", b: 8 }); // our view should allow only first 4 test records const dv = testColl.addDynamicView("lower"); dv.applyFind({b: {"$lte": 4}}); // our transform will desc sort string column as 'third', 'second', 'fourth', 'first', // and then limit to first two const tx: Transform<AB>[] = [ { type: "simplesort", property: "a", options: true }, { type: "limit", value: 2 } ]; expect(dv.branchResultSet(tx).data().length).toBe(2); // now store as named (collection) transform and run off dynamic view testColl.addTransform("desc4limit2", tx); const results = dv.branchResultSet("desc4limit2").data(); expect(results.length).toBe(2); expect(results[0].a).toBe("third"); expect(results[1].a).toBe("second"); }); }); describe("eqJoin step with dataOptions works", function () { it("works", () => { const db1 = new Loki("testJoins"); interface Director { name: string; directorId: number; } interface Film { title: string; filmId: number; directorId: number; } const directors = db1.addCollection<Director>("directors"); const films = db1.addCollection<Film>("films"); directors.insert([ {name: "Martin Scorsese", directorId: 1}, {name: "Francis Ford Coppola", directorId: 2}, {name: "Steven Spielberg", directorId: 3}, {name: "Quentin Tarantino", directorId: 4} ]); films.insert([ {title: "Taxi", filmId: 1, directorId: 1}, {title: "Raging Bull", filmId: 2, directorId: 1}, {title: "The Godfather", filmId: 3, directorId: 2}, {title: "Jaws", filmId: 4, directorId: 3}, {title: "ET", filmId: 5, directorId: 3}, {title: "Raiders of the Lost Ark", filmId: 6, directorId: 3} ]); // Since our collection options do not specify cloning, this is only safe // because we have cloned internal objects with dataOptions before modifying them. function fdmap(left: object, right: object) { // PhantomJS does not support es6 Object.assign //left = Object.assign(left, right); Object.keys(right).forEach((key) => { left[key] = right[key]; }); return left; } // The 'joinData' in this instance is a Collection which we will call // data() on with the specified (optional) dataOptions on. // It could also be a ResultSet or data array. // Our left side ResultSet which this transform is executed on will also // call data() with specified (optional) dataOptions. films.addTransform("filmdirect", [ { type: "eqJoin", joinData: directors, leftJoinKey: "directorId", rightJoinKey: "directorId", mapFun: fdmap, dataOptions: {removeMeta: true} } ]); // Although we removed all meta, the eqjoin inserts the resulting objects // into a new volatile collection which would adds its own meta and loki. // We don't care about these useless volatile data so grab results without it. const results = films.chain("filmdirect").data({removeMeta: true}) as any as (Director & Film)[]; expect(results.length).toEqual(6); expect(results[0].title).toEqual("Taxi"); expect(results[0].name).toEqual("Martin Scorsese"); expect(results[5].title).toEqual("Raiders of the Lost Ark"); expect(results[5].name).toEqual("Steven Spielberg"); results.forEach((obj) => { expect(Object.keys(obj).length).toEqual(4); }); }); }); describe("map step with dataOptions works", function () { it("works", () => { const db1 = new Loki("testJoins"); interface C1 { a: number; b: number; c?: number; } const c1 = db1.addCollection<C1>("c1"); c1.insert([ {a: 1, b: 9}, {a: 2, b: 8}, {a: 3, b: 7}, {a: 4, b: 6} ]); // only safe because our 'removeMeta' option will clone objects passed in function graftMap(obj: C1) { obj.c = obj.b - obj.a; return obj; } const tx: Transform<C1>[] = [{ type: "map", value: graftMap, dataOptions: {removeMeta: true} }]; const results = c1.chain(tx).data({removeMeta: true}); expect(results.length).toEqual(4); expect(results[0].a).toEqual(1); expect(results[0].b).toEqual(9); expect(results[0].c).toEqual(8); expect(results[3].a).toEqual(4); expect(results[3].b).toEqual(6); expect(results[3].c).toEqual(2); results.forEach((obj) => { expect(Object.keys(obj).length).toEqual(3); }); }); }); });
the_stack
import EventEmitter from 'eventemitter3'; import Events from '../Events/index'; import Errors from '../Errors/index'; import Transmuxer from '../Controller/Transmuxer'; import MSEController from '../Controller/MSEController'; import { InitSegment, MediaSegment } from '../Interfaces/Segment'; import MediaConfig from '../Interfaces/MediaConfig'; import { IllegalStateException } from '../Utils/Exception'; import Browser from '../Utils/Browser'; import Logger from '../Utils/Logger'; import MediaInfoObject from '../Interfaces/MediaInfoObject'; import StatisticsInfoObject from '../Interfaces/StatisticsInfo'; import Metadata from '../Interfaces/Metadata'; import ErrorData from '../Interfaces/ErrorData'; import HJPlayerConfig from '../Interfaces/HJPlayerConfig'; import TSManifest from '../Interfaces/TSManifest'; /* eslint-enabale */ class MSEPlayer { /** * 文件标签 */ Tag: string /** * 播放器类型 */ private _type: string /** * 事件中心 */ private _emitter: EventEmitter | null /** * 媒体设置 */ mediaConfig: MediaConfig | null /** * 用户设置 */ userConfig: HJPlayerConfig | null /** * 存放回调函数的对象 */ private e: any /** * 获得当前时间的函数 */ private _now: Function /** * 等待跳转的时间点, 在没有媒体元素时先记录该时间点 */ private _pendingSeekTime: number | null private _requestSetTime: boolean /** * seek点记录 */ private _seekpointRecord: SeekpointRecord | null /** * 进度检查定时器 */ private _progressCheckTimer: number | undefined /** * 媒体元素 */ private _mediaElement: HTMLMediaElement | null /** * MediaSource 控制器 */ private _msectl: MSEController | null /** * 转码器 */ private _transmuxer: Transmuxer | null /** * MediaSource 是否处于已 opened 状态 */ private _mseSourceOpened: boolean /** * 是否正在等待load, 如果是的话, 会在 souceOpen 事件之后 执行 load 操作 */ private _hasPendingLoad: boolean /** * 接收到的媒体数据流是否可以支持播放 */ private _receivedCanPlay: boolean /** * 媒体的信息 */ private _mediaInfo: MediaInfoObject | null /** * 媒体播放时的统计信息 */ private _statisticsInfo: StatisticsInfoObject | null /** * M3U8文档是否已经解析 */ private _manifestParsed: boolean /** * 开始播放时设定的 currentTime */ private _startPosition: number /** * 当前播放的M3U8 playlist文档 解析后的内筒 */ private _currentDetail: any | null /** * 是否一直 seek 到 关键帧 */ private _alwaysSeekKeyframe: boolean constructor(mediaConfig: MediaConfig, config: HJPlayerConfig) { this.Tag = 'MSEPlayer'; this._type = 'MSEPlayer'; this._emitter = new EventEmitter(); this.userConfig = config; this.mediaConfig = mediaConfig; this.e = { onvLoadedMetadata: this._onvLoadedMetadata.bind(this), onvSeeking: this._onvSeeking.bind(this), onvCanPlay: this._onvCanPlay.bind(this), onvStalled: this._onvStalled.bind(this), onvProgress: this._onvProgress.bind(this), }; if(window.performance && window.performance.now) { this._now = window.performance.now.bind(window.performance); } else { this._now = Date.now; } this._pendingSeekTime = null; // in seconds this._requestSetTime = false; this._seekpointRecord = null; this._progressCheckTimer = undefined; this._mediaElement = null; this._msectl = null; this._transmuxer = null; this._mseSourceOpened = false; this._hasPendingLoad = false; this._receivedCanPlay = false; this._mediaInfo = null; this._statisticsInfo = null; const chromeNeedIDRFix = Browser.chrome && (Browser.version.major < 50 || (Browser.version.major === 50 && Browser.version.build < 2661)); this._alwaysSeekKeyframe = !!(chromeNeedIDRFix || Browser.msedge || Browser.msie); if(this._alwaysSeekKeyframe) { this.userConfig.accurateSeek = false; } this._manifestParsed = false; // 是否已经解析了M3U8文件 this._startPosition = 0; // 起播点 this._currentDetail = null; // playList-loader 解析出来的文档 } /** * MSEPlayer销毁 */ destroy() { if(this._progressCheckTimer !== undefined) { window.clearInterval(this._progressCheckTimer); this._progressCheckTimer = undefined; } if(this._transmuxer) { this.unload(); } if(this._mediaElement) { this.detachMediaElement(); } this.e = null; this._emitter && this._emitter.removeAllListeners(); this._manifestParsed = false; this._startPosition = 0; this._currentDetail = null; this._statisticsInfo = null; this._mediaInfo = null; this._seekpointRecord = null; delete this._emitter; delete this.mediaConfig; delete this.userConfig; this._emitter = null; this.mediaConfig = null; this.userConfig = null; } /** * MSEPlayer绑定事件 * @param event 事件名 * @param listener 回调函数 */ on(event: string, listener: EventEmitter.ListenerFn) { if(!this._emitter) return; if(event === Events.MEDIA_INFO) { if(this._mediaInfo !== null) { Promise.resolve().then(() => { this._emitter && this._emitter.emit(Events.MEDIA_INFO, this.mediaInfo); }); } } else if(event === Events.STATISTICS_INFO) { if(this._statisticsInfo !== null) { Promise.resolve().then(() => { this._emitter && this._emitter.emit(Events.STATISTICS_INFO, this.statisticsInfo); }); } } this._emitter.addListener(event, listener); } /** * MSEPlayer取消绑定事件 * @param event 事件名 * @param listener 回调函数 */ off(event: string, listener: EventEmitter.ListenerFn) { this._emitter && this._emitter.removeListener(event, listener); } /** * 媒体元素和 MediaSource 链接起来 * @param mediaElement 要绑定的媒体元素 */ attachMediaElement(mediaElement: HTMLMediaElement) { this._mediaElement = mediaElement; mediaElement.addEventListener('loadedmetadata', this.e.onvLoadedMetadata); mediaElement.addEventListener('seeking', this.e.onvSeeking); mediaElement.addEventListener('canplay', this.e.onvCanPlay); mediaElement.addEventListener('stalled', this.e.onvStalled); mediaElement.addEventListener('progress', this.e.onvProgress); this.userConfig && (this._msectl = new MSEController(this.userConfig)); this._msectl!.on(Events.UPDATE_END, this._onmseUpdateEnd.bind(this)); this._msectl!.on(Events.BUFFER_FULL, this._onmseBufferFull.bind(this)); this._msectl!.on(Events.SOURCE_OPEN, () => { this._mseSourceOpened = true; if(this._hasPendingLoad) { this._hasPendingLoad = false; this.load(); } }); this._msectl!.on(Events.ERROR, (info: ErrorData) => { this._emitter && this._emitter.emit(Events.ERROR, Errors.MEDIA_ERROR, Errors.MEDIA_MSE_ERROR, info); }); this._msectl!.attachMediaElement(mediaElement); if(this._pendingSeekTime != null) { try { mediaElement.currentTime = this._pendingSeekTime; this._pendingSeekTime = null; } catch (e) { // IE11 may throw InvalidStateError if readyState === 0 // We can defer set currentTime operation after loadedmetadata } } } /** * MediaSource 与 媒体元素 分离链接 */ detachMediaElement() { if(this._mediaElement && this.e) { this._msectl && this._msectl.detachMediaElement(); this._mediaElement.removeEventListener('loadedmetadata', this.e.onvLoadedMetadata); this._mediaElement.removeEventListener('seeking', this.e.onvSeeking); this._mediaElement.removeEventListener('canplay', this.e.onvCanPlay); this._mediaElement.removeEventListener('stalled', this.e.onvStalled); this._mediaElement.removeEventListener('progress', this.e.onvProgress); this._mediaElement = null; } if(this._msectl) { this._msectl.destroy(); this._msectl = null; } this._startPosition = 0; } /** * 加载媒体文件, 并绑定回调事件 */ load() { if(!this._mediaElement) { throw new IllegalStateException('HTMLMediaElement must be attached before load()!'); } if(this._transmuxer) { throw new IllegalStateException( 'FlvPlayer.load() has been called, please call unload() first!' ); } if(this._hasPendingLoad) { return; } if(this.userConfig!.deferLoadAfterSourceOpen && this._mseSourceOpened === false) { this._hasPendingLoad = true; return; } if(this._mediaElement.readyState > 0) { // IE11 may throw InvalidStateError if readyState === 0 this._setMediaCurrentTime(0); } this.mediaConfig && this.userConfig && (this._transmuxer = new Transmuxer(this.mediaConfig, this.userConfig)); this._transmuxer!.on(Events.INIT_SEGMENT, (type: string, is: InitSegment) => { this._msectl && this._msectl.appendInitSegment(is); }); this._transmuxer!.on(Events.MEDIA_SEGMENT, (type: string, ms: MediaSegment) => { this._msectl && this._msectl.appendMediaSegment(ms); // lazyLoad check TODO 需要TS解码器中的Segment中添加Sample的相关信息, 添加后同样适用 HLS 点播流 // && this.mediaConfig!.type === 'flv' if( this.userConfig!.lazyLoad && !this.userConfig!.isLive && this._mediaElement ) { const { currentTime } = this._mediaElement; if( ms.info && ms.info.endDts >= (currentTime + this.userConfig!.lazyLoadMaxDuration) * 1000 ) { if(this._progressCheckTimer === undefined) { Logger.info( this.Tag, 'Maximum buffering duration exceeded, suspend transmuxing task' ); Logger.info(this.Tag, `start load at ${ms.info.endDts}`); this._suspendTransmuxer(); } } } }); this._transmuxer!.on(Events.LOAD_COMPLETE, () => { this._msectl && this._msectl.endOfStream(); this._emitter!.emit(Events.LOAD_COMPLETE); }); this._transmuxer!.on(Events.RECOVERED_EARLY_EOF, () => { this._emitter!.emit(Events.RECOVERED_EARLY_EOF); }); this._transmuxer!.on(Events.IO_ERROR, (detail: string, info: ErrorData) => { this._emitter!.emit(Events.ERROR, Errors.NETWORK_ERROR, detail, info); }); this._transmuxer!.on(Events.DEMUX_ERROR, (detail: string, info: string) => { this._emitter!.emit(Events.ERROR, Errors.MEDIA_ERROR, detail, { code: -1, reason: info }); }); this._transmuxer!.on(Events.MEDIA_INFO, (mediaInfo: MediaInfoObject) => { this._mediaInfo = mediaInfo; this._emitter!.emit(Events.MEDIA_INFO, { ...mediaInfo }); }); this._transmuxer!.on(Events.METADATA_ARRIVED, (metadata: Metadata) => { this._emitter!.emit(Events.METADATA_ARRIVED, metadata); }); this._transmuxer!.on(Events.SCRIPTDATA_ARRIVED, (data: any) => { this._emitter!.emit(Events.SCRIPTDATA_ARRIVED, data); }); this._transmuxer!.on(Events.STATISTICS_INFO, (statInfo: StatisticsInfoObject) => { this._statisticsInfo = this._fillStatisticsInfo(statInfo); this._emitter!.emit(Events.STATISTICS_INFO, { ...this._statisticsInfo }); }); this._transmuxer!.on(Events.RECOMMEND_SEEKPOINT, (milliseconds: number) => { if(this._mediaElement && !this.userConfig!.accurateSeek) { this._setMediaCurrentTime(milliseconds / 1000); } }); this._transmuxer!.on(Events.GET_SEI_INFO, (data: Uint8Array) => { this._emitter!.emit(Events.GET_SEI_INFO, data); }); this._transmuxer!.on(Events.MANIFEST_PARSED, (data: TSManifest) => { // 只对HLS生效 // this._dealVideoCurrentTime(data); if(!this._manifestParsed) { this._manifestParsed = true; if(data.details.live === true) { this.setMediaSourceDuration(Infinity); } else { this.setMediaSourceDuration(data.details.totalduration); } } this._emitter!.emit(Events.MANIFEST_PARSED, data); this._currentDetail = data.details; }); this._transmuxer && this._transmuxer.open(); } /** * 停止加载 */ unload() { if(this._mediaElement) { this._mediaElement.pause(); } if(this._msectl) { this._msectl.seek(); } if(this._transmuxer) { this._transmuxer.close(); this._transmuxer.destroy(); this._transmuxer = null; } this._manifestParsed = false; this._startPosition = 0; this._currentDetail = null; } /** * 开始播放 */ play() { if(this._mediaElement) { return this._mediaElement.play(); } } /** * 暂停 */ pause() { this._mediaElement && this._mediaElement.pause(); } /** * 返回当前播放器类型 */ get type() { return this._type; } /** * 返回媒体元素已缓存的时间段 */ get buffered() { return this._mediaElement ? this._mediaElement.buffered : null; } /** * 返回媒体元素加载的时长或者整个媒体文件的时长 */ get duration() { return this._mediaElement ? this._mediaElement.duration : 0; } /** * 获取媒体元素的声音大小 */ get volume() { return this._mediaElement ? this._mediaElement.volume : 0; } /** * 设置媒体元素的声音 */ set volume(value) { this._mediaElement && (this._mediaElement.volume = value); } /** * 获取媒体元素是否静音 */ get muted() { return this._mediaElement ? this._mediaElement.muted : false; } /** * 设置媒体静音 */ set muted(muted) { this._mediaElement && (this._mediaElement.muted = muted); } /** * 获取媒体元素当前播放的时间点 */ get currentTime() { if(this._mediaElement) { return this._mediaElement.currentTime; } return 0; } /** * 设置媒体元素的 currentTime */ set currentTime(seconds) { if(this._mediaElement) { this._internalSeek(seconds); } else { this._pendingSeekTime = seconds; } } /** * 获取媒体文件信息 */ get mediaInfo() { return { ...this._mediaInfo }; } /** * 获取播放器的统计信息 */ get statisticsInfo() { if(this._statisticsInfo == null) { this._statisticsInfo = {}; } this._statisticsInfo = this._fillStatisticsInfo(this._statisticsInfo); return { ...this._statisticsInfo }; } /** * 填充 MSEPlayer 这一层的少量统计信息, 并返回全部统计信息 * @param statInfo 待填充 MSEPlayer 这一层信息的残缺的统计信息 */ private _fillStatisticsInfo(statInfo: StatisticsInfoObject): StatisticsInfoObject { statInfo.playerType = this._type; if(!(this._mediaElement instanceof HTMLVideoElement)) { return statInfo; } let hasQualityInfo = true; let decoded = 0; let dropped = 0; if(this._mediaElement.getVideoPlaybackQuality) { const quality = this._mediaElement.getVideoPlaybackQuality(); decoded = quality.totalVideoFrames; dropped = quality.droppedVideoFrames; } else if((this._mediaElement as any).webkitDecodedFrameCount !== undefined) { decoded = (this._mediaElement as any).webkitDecodedFrameCount; dropped = (this._mediaElement as any).webkitDroppedFrameCount; } else { hasQualityInfo = false; } if(hasQualityInfo) { statInfo.decodedFrames = decoded; statInfo.droppedFrames = dropped; } return statInfo; } /** * 当 MediaSource 更新结束后的处理事件, 通过判断已缓存的进度来判断是否暂停加载 */ private _onmseUpdateEnd() { if(!this.userConfig!.lazyLoad || this.userConfig!.isLive || !this._mediaElement) { return; } const { buffered } = this._mediaElement; const { currentTime } = this._mediaElement; let currentRangeEnd = 0; for(let i = 0; i < buffered.length; i++) { const start = buffered.start(i); const end = buffered.end(i); if(start <= currentTime && currentTime < end) { currentRangeEnd = end; break; } } if( currentRangeEnd >= currentTime + this.userConfig!.lazyLoadMaxDuration && this._progressCheckTimer === undefined ) { Logger.info(this.Tag, 'Maximum buffering duration exceeded, suspend transmuxing task'); Logger.info(this.Tag, `start load at ${currentRangeEnd}`); this._suspendTransmuxer(); } } /** * 当 MediaSource Buffer 已满的处理事件, 暂停加载 */ private _onmseBufferFull() { Logger.info(this.Tag, 'MSE SourceBuffer is full, suspend transmuxing task'); if(this._progressCheckTimer === undefined) { this._suspendTransmuxer(); } } /** * 暂停加载, 并启动进度检查定时器 */ private _suspendTransmuxer() { if(this._transmuxer) { this._transmuxer.pause(); if(this._progressCheckTimer === undefined) { this._progressCheckTimer = window.setInterval( this._checkProgressAndResume.bind(this), 1000 ); } } } /** * 检查播放进度, 当 currentTime 和 缓存的进度 之间的差值 小于 this.userConfig.lazyLoadRecoverDuration 时, 恢复加载 */ private _checkProgressAndResume() { if(!this._mediaElement) return; /** * 媒体元素当前播放时间点 */ const { currentTime } = this._mediaElement; /** * 媒体元素缓冲的时间点 */ const { buffered } = this._mediaElement; /** * 是否需要回复加载 */ let needResume = false; for(let i = 0; i < buffered.length; i++) { const start = buffered.start(i); const end = buffered.end(i); if(currentTime >= start && currentTime < end) { if(currentTime >= end - this.userConfig!.lazyLoadRecoverDuration) { needResume = true; } break; } } if(needResume) { window.clearInterval(this._progressCheckTimer); this._progressCheckTimer = undefined; if(needResume) { Logger.info(this.Tag, 'Continue loading from paused position'); this._transmuxer && this._transmuxer.resume(); } } } /** * 查询要跳转的时间点是否已处于缓存区域 * @param seconds 查询的时间点 */ private _isTimepointBuffered(seconds: number) { if(!this._mediaElement) return false; const { buffered } = this._mediaElement; for(let i = 0; i < buffered.length; i++) { const from = buffered.start(i); const to = buffered.end(i); if(seconds >= from && seconds < to) { return true; } } return false; } /** * 非用户操作的内部跳转 * @param seconds seek的描述 */ private _internalSeek(seconds: number) { if(!this._mediaElement) return false; /** * 是否能直接跳转 */ const directSeek = this._isTimepointBuffered(seconds); /** * 是否直接跳转到视频开始处 */ let directSeekBegin = false; /** * 直接跳转到开始处的相应时间 */ let directSeekBeginTime = 0; if(seconds < 1.0 && this._mediaElement.buffered.length > 0) { const videoBeginTime = this._mediaElement.buffered.start(0); if((videoBeginTime < 1.0 && seconds < videoBeginTime) || Browser.safari) { directSeekBegin = true; // also workaround for Safari: Seek to 0 may cause video stuck, use 0.1 to avoid directSeekBeginTime = Browser.safari ? 0.1 : videoBeginTime; } } if(directSeekBegin) { // seek to video begin, set currentTime directly if beginPTS buffered this._setMediaCurrentTime(directSeekBeginTime); return; } if(directSeek) { // buffered position if(!this._alwaysSeekKeyframe) { this._setMediaCurrentTime(seconds); } else { const idr = this._msectl ? this._msectl.getNearestKeyframe(Math.floor(seconds * 1000)) : null; const setTime: number = idr !== null ? idr.dts / 1000 : seconds; this._setMediaCurrentTime(setTime); } if(this._progressCheckTimer !== undefined) { this._checkProgressAndResume(); } return; } if(this._progressCheckTimer !== undefined) { window.clearInterval(this._progressCheckTimer); this._progressCheckTimer = undefined; } this._msectl && this._msectl.seek(); this._transmuxer && this._transmuxer.seek(Math.floor(seconds * 1000)); // in milliseconds // no need to set mediaElement.currentTime if non-accurateSeek, // just wait for the recommend_seekpoint callback if(this.userConfig!.accurateSeek) { this._setMediaCurrentTime(seconds); } } /** * 过100毫秒之后检查, 如果要跳转的点还没有缓存就停止progressCheck, _msectl 和 _transmuxer 跳转到相应时间点 */ private _checkAndApplyUnbufferedSeekpoint() { if(this._seekpointRecord && this._mediaElement) { if(this._seekpointRecord.recordTime <= this._now() - 100) { const target = this._mediaElement.currentTime; this._seekpointRecord = null; if(!this._isTimepointBuffered(target)) { if(this._progressCheckTimer !== undefined) { window.clearTimeout(this._progressCheckTimer); this._progressCheckTimer = undefined; } // .currentTime is consists with .buffered timestamp // Chrome/Edge use DTS, while FireFox/Safari use PTS this._msectl && this._msectl.seek(); this._transmuxer && this._transmuxer.seek(Math.floor(target * 1000)); // set currentTime if accurateSeek, or wait for recommend_seekpoint callback if(this.userConfig!.accurateSeek && this._mediaElement) { // this._requestSetTime = true // this._mediaElement.currentTime = target this._setMediaCurrentTime(target); } } } else { window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this), 50); } } } /** * 当 MediaElement 触发 `stalled`事件 或者 触发 `progress` 时的操作, 进行检查和恢复处理 * @param stalled 是否卡住了 */ private _checkAndResumeStuckPlayback(stalled?: boolean) { if(!this._mediaElement) return false; const media = this._mediaElement; if(stalled || !this._receivedCanPlay || media.readyState < 2) { // HAVE_CURRENT_DATA const { buffered } = media; if(buffered.length > 0 && media.currentTime < buffered.start(0)) { Logger.warn( this.Tag, `Playback seems stuck at ${media.currentTime}, seek to ${buffered.start(0)}` ); this._setMediaCurrentTime(buffered.start(0)); this._mediaElement.removeEventListener('progress', this.e.onvProgress); } } else { // Playback didn't stuck, remove progress event listener this._mediaElement.removeEventListener('progress', this.e.onvProgress); } } /** * 当接收到视频Metadata数据时的处理函数, 当已收到Metadata后把等待跳转的时间点设置为元素的currentTime * 当IE11在 attachMedia时设置 currentTime 报错, 那么在 LoadedMetadata 后设置 currentTime */ private _onvLoadedMetadata() { if(this._pendingSeekTime != null && this._mediaElement) { this._mediaElement.currentTime = this._pendingSeekTime; this._pendingSeekTime = null; } } /** * 当视频 seek 的时候处理函数 */ private _onvSeeking() { // handle seeking request from browser's progress bar if(!this._mediaElement) return false; const target = this._mediaElement.currentTime; const { buffered } = this._mediaElement; if(this._requestSetTime) { this._requestSetTime = false; return; } if(target < 1.0 && buffered.length > 0) { // seek to video begin, set currentTime directly if beginPTS buffered const videoBeginTime = buffered.start(0); if((videoBeginTime < 1.0 && target < videoBeginTime) || Browser.safari) { // also workaround for Safari: Seek to 0 may cause video stuck, use 0.1 to avoid // this._mediaElement.currentTime = Browser.safari ? 0.1 : videoBeginTime this._setMediaCurrentTime(Browser.safari ? 0.1 : videoBeginTime); return; } } if(this._isTimepointBuffered(target)) { if(this._alwaysSeekKeyframe && this._msectl) { const idr = this._msectl.getNearestKeyframe(Math.floor(target * 1000)); if(idr != null) { this._setMediaCurrentTime(idr.dts / 1000); } } if(this._progressCheckTimer !== undefined) { this._checkProgressAndResume(); } return; } this._seekpointRecord = { seekPoint: target, recordTime: this._now() }; window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this), 50); } private _onvCanPlay() { this._receivedCanPlay = true; this._mediaElement && this._mediaElement.removeEventListener('canplay', this.e.onvCanPlay); } private _onvStalled() { this._checkAndResumeStuckPlayback(true); } private _onvProgress() { this._checkAndResumeStuckPlayback(); } /** * 给 media 设置 currentTime * @param seconds 设置的时间 */ private _setMediaCurrentTime(seconds: number) { this._requestSetTime = true; this._mediaElement && (this._mediaElement.currentTime = seconds); } setMediaSourceDuration(duration: number) { this._msectl!.setMediaSourceDuration(duration); } } export default MSEPlayer;
the_stack
import * as cp from "child_process"; import * as wdio from "webdriverio"; import * as mkdirp from "mkdirp"; import * as kill from "tree-kill"; import { SmokeTestsConstants } from "./smokeTestsConstants"; import { sleep, waitUntil } from "./utilities"; import * as clipboardy from "clipboardy"; import { SmokeTestLogger } from "./smokeTestLogger"; let appiumProcess: null | cp.ChildProcess; export type AppiumClient = wdio.Browser<"async">; export enum Platform { Android = "Android", AndroidExpo = "AndroidExpo", iOS = "iOS", iOSExpo = "iOSExpo", } const XDL = require("xdl"); type XPathSelector = { [TKey in Platform]: string }; type XPathSelectors = { [key: string]: XPathSelector }; export class AppiumHelper { private static waitUntilEnableRemoteDebugOptions: wdio.WaitUntilOptions = { timeout: SmokeTestsConstants.enableRemoteJSTimeout, timeoutMsg: `Remote debugging UI element not found after ${SmokeTestsConstants.enableRemoteJSTimeout}ms`, interval: 1000, }; // Paths for searching UI elements public static XPATH: XPathSelectors = { RN_RELOAD_BUTTON: { [Platform.Android]: "//*[@text='Reload']", [Platform.AndroidExpo]: "//*[@text='Reload']", [Platform.iOS]: "//XCUIElementTypeButton[@name='Reload']", [Platform.iOSExpo]: "//XCUIElementTypeOther[@name='Reload JS Bundle']", }, RN_ENABLE_REMOTE_DEBUGGING_BUTTON: { [Platform.Android]: "//*[@text='Debug JS Remotely' or @text='Debug']", [Platform.AndroidExpo]: "//*[@text='Debug Remote JS']", [Platform.iOS]: "//XCUIElementTypeButton[@name='Debug JS Remotely' or @name='Debug']", [Platform.iOSExpo]: "//XCUIElementTypeOther[@name='󰢹 Debug Remote JS']", }, RN_STOP_REMOTE_DEBUGGING_BUTTON: { [Platform.Android]: "//*[@text='Stop Remote JS Debugging' or @text='Stop Debugging']", [Platform.AndroidExpo]: "//*[@text='Stop Remote Debugging']", [Platform.iOS]: "//XCUIElementTypeButton[@name='Stop Remote JS Debugging' or @name='Stop Debugging']", [Platform.iOSExpo]: "//XCUIElementTypeOther[@name=' Stop Remote Debugging']", }, RN_DEV_MENU_CANCEL: { [Platform.Android]: "//*[@text='Cancel']", [Platform.AndroidExpo]: "//*[@text='Cancel']", [Platform.iOS]: "//XCUIElementTypeButton[@name='Cancel']", [Platform.iOSExpo]: "(//XCUIElementTypeOther[@name='Cancel'])[1]", }, EXPO_ELEMENT_LOAD_TRIGGER: { [Platform.Android]: "", [Platform.AndroidExpo]: "//*[@text='Home']", [Platform.iOS]: "", // todo [Platform.iOSExpo]: "", // todo }, GOT_IT_BUTTON: { [Platform.Android]: "", [Platform.AndroidExpo]: "//*[@text='Got it']", [Platform.iOS]: "", [Platform.iOSExpo]: "//XCUIElementTypeOther[@name='Got it']", }, }; public static runAppium(appiumLogPath: string): void { SmokeTestLogger.info(`*** Executing Appium with logging to ${appiumLogPath}`); let appiumCommand = process.platform === "win32" ? "appium.cmd" : "appium"; // We need to inherit stdio streams because, otherwise, on Windows appium is stuck at the middle of the Expo test. // We ignore stdout because --log already does the trick, but keeps stdin and stderr. appiumProcess = cp.spawn(appiumCommand, ["--log", appiumLogPath], { stdio: ["inherit", "ignore", "inherit"], }); appiumProcess.on("exit", () => { SmokeTestLogger.info("*** Appium terminated"); }); appiumProcess.on("error", error => { SmokeTestLogger.error(`Error occurred in Appium process: ${error.toString()}`); }); } public static async terminateAppium(): Promise<boolean> { const errorCallback = (err: any) => { if (err) { SmokeTestLogger.error("Error occured while terminating Appium"); throw err; } }; if (appiumProcess) { let retrieveProcessesData; if (process.platform == "win32") { retrieveProcessesData = () => cp.execSync("tasklist").toString(); } else { retrieveProcessesData = () => { try { return appiumProcess ? cp.execSync(`ps -p ${appiumProcess.pid}`).toString() : ""; } catch (err) { if (err.stdout.toString() && !err.stderr.toString()) { return err.stdout.toString(); } else { throw err; } } }; } const condition = () => { if (appiumProcess && retrieveProcessesData().includes(String(appiumProcess.pid))) { SmokeTestLogger.info( `*** Sending SIGINT to Appium process with PID ${appiumProcess.pid}`, ); kill(appiumProcess.pid, "SIGINT", errorCallback); return false; } else { return true; } }; const result = await waitUntil(condition, 5 * 60 * 1000, 10 * 1000); if (result) { SmokeTestLogger.success(`*** Appium process was killed`); } else { SmokeTestLogger.error(`*** Could not kill Appium process`); } return result; } else { return true; } } public static prepareAttachOptsForAndroidActivity( applicationPackage: string, applicationActivity: string, deviceName: string = SmokeTestsConstants.defaultTargetAndroidDeviceName, ): wdio.RemoteOptions { SmokeTestLogger.info( `*** process.env.WEBDRIVER_IO_LOGS_DIR: ${process.env.WEBDRIVER_IO_LOGS_DIR}`, ); return { capabilities: { platformName: "Android", platformVersion: process.env.ANDROID_VERSION || SmokeTestsConstants.defaultTargetAndroidPlatformVersion, deviceName: deviceName, appActivity: applicationActivity, appPackage: applicationPackage, automationName: "UiAutomator2", newCommandTimeout: 300, }, path: "/wd/hub", port: 4723, logLevel: "trace", outputDir: process.env.WEBDRIVER_IO_LOGS_DIR, }; } public static prepareAttachOptsForIosApp( deviceName: string, appPath: string, ): wdio.RemoteOptions { SmokeTestLogger.info( `*** process.env.WEBDRIVER_IO_LOGS_DIR: ${process.env.WEBDRIVER_IO_LOGS_DIR}`, ); return { capabilities: { platformName: "iOS", platformVersion: process.env.IOS_VERSION || SmokeTestsConstants.defaultTargetIosPlatformVersion, deviceName: deviceName, app: appPath, automationName: "XCUITest", newCommandTimeout: 500, }, path: "/wd/hub", port: 4723, logLevel: "trace", outputDir: process.env.WEBDRIVER_IO_LOGS_DIR, }; } public static webdriverAttach(attachArgs: wdio.RemoteOptions): Promise<AppiumClient> { // Connect to the emulator with predefined opts return wdio.remote(attachArgs); } public static createWebdriverIOLogDir(webdriverIOLogDir: string): void { mkdirp.sync(webdriverIOLogDir); } public static async openExpoApplication( platform: Platform, client: AppiumClient, expoURL: string, projectFolder: string, firstLaunch?: boolean, ): Promise<void> { // There are two ways to run app in Expo app: // - via clipboard // - via expo XDL function if (platform === Platform.Android) { if (process.platform === "darwin") { // Longer way to open Expo app, but // it certainly works on Mac return this.openExpoAppViaExpoXDLAndroidFunction(client, projectFolder); } else { // The quickest way to open Expo app, // it doesn't work on Mac though return this.openExpoAppViaClipboardAndroid(client, expoURL); } } else if (platform === Platform.iOS) { // Launch Expo using XDL.Simulator function return this.openExpoAppViaExpoXDLSimulatorFunction(client, projectFolder, firstLaunch); } else { throw new Error(`Unknown platform ${platform}`); } } /** * Enables RN Dev Menu on native app * @see https://facebook.github.io/react-native/docs/debugging#accessing-the-in-app-developer-menu * @param client - Initialized Appium client * @param platform - Android or iOS */ public static async callRNDevMenu(client: AppiumClient, platform: Platform): Promise<void> { switch (platform) { case Platform.Android: case Platform.AndroidExpo: SmokeTestLogger.info( "*** Opening DevMenu by calling 'adb shell input keyevent 82'...", ); const devMenuCallCommand = "adb shell input keyevent 82"; cp.exec(devMenuCallCommand); await sleep(10 * 1000); break; case Platform.iOS: case Platform.iOSExpo: // Sending Cmd+D doesn't work sometimes but shake gesture works flawlessly SmokeTestLogger.info("*** Opening DevMenu by sending shake gesture..."); await client.shake(); await sleep(2 * 1000); break; default: throw new Error("Unknown platform"); } } public static async reloadRNApp(client: AppiumClient, platform: Platform): Promise<void> { SmokeTestLogger.info("*** Reloading React Native application with DevMenu..."); const reloadButton = await client.$(this.XPATH.RN_RELOAD_BUTTON[platform]); await client.waitUntil(async () => { await this.callRNDevMenu(client, platform); if (await reloadButton.isExisting()) { SmokeTestLogger.info("*** Reload button found..."); await reloadButton.click(); SmokeTestLogger.info("*** Reload button clicked..."); return true; } return false; }, this.waitUntilEnableRemoteDebugOptions); } public static async enableRemoteDebugJS( client: AppiumClient, platform: Platform, ): Promise<void> { SmokeTestLogger.info("*** Enabling Remote JS Debugging for application with DevMenu..."); const enableRemoteDebugButton = await client.$( this.XPATH.RN_ENABLE_REMOTE_DEBUGGING_BUTTON[platform], ); const enableRemoteDebugStopButton = await client.$( this.XPATH.RN_STOP_REMOTE_DEBUGGING_BUTTON[platform], ); const enableRemoteDebugCancelButton = await client.$( this.XPATH.RN_DEV_MENU_CANCEL[platform], ); await client.waitUntil(async () => { if (await enableRemoteDebugButton.isExisting()) { SmokeTestLogger.info("*** Debug JS Remotely button found..."); await enableRemoteDebugButton.click(); SmokeTestLogger.info("*** Debug JS Remotely button clicked..."); await sleep(1000); if (await enableRemoteDebugButton.isExisting()) { await enableRemoteDebugButton.click(); SmokeTestLogger.info("*** Debug JS Remotely button clicked second time..."); } return true; } else if (await enableRemoteDebugStopButton.isExisting()) { SmokeTestLogger.info( "*** Stop Remote JS Debugging button found, closing Dev Menu...", ); if (await enableRemoteDebugCancelButton.isExisting()) { SmokeTestLogger.info("*** Cancel button found..."); await enableRemoteDebugCancelButton.click(); SmokeTestLogger.info("*** Cancel button clicked..."); return true; } else { await this.callRNDevMenu(client, platform); return false; } } await this.callRNDevMenu(client, platform); return false; }, this.waitUntilEnableRemoteDebugOptions); } // Expo 32 has an error on iOS application start up // it is not breaking the app, but may broke the tests, so need to click Dismiss button in the RN Red Box to proceed further public static async disableExpoErrorRedBox(client: AppiumClient): Promise<void> { const dismissButton = await client.$("//XCUIElementTypeButton[@name='redbox-dismiss']"); if (await dismissButton.isExisting()) { SmokeTestLogger.info("*** React Native Red Box found, disabling..."); await dismissButton.click(); } } // New Expo versions shows DevMenu at first launch with informational message, // it is better to disable this message and then call DevMenu ourselves public static async disableDevMenuInformationalMsg( client: AppiumClient, platform: Platform, ): Promise<void> { const gotItButton = await client.$(this.XPATH.GOT_IT_BUTTON[platform]); if (await gotItButton.isExisting()) { SmokeTestLogger.info("*** Expo DevMenu informational message found, disabling..."); await gotItButton.click(); } } public static async clickTestButton( client: AppiumClient, testButtonName: string, platform: Platform, ): Promise<void> { SmokeTestLogger.info(`*** Pressing button with text "${testButtonName}"...`); let testButton: any; switch (platform) { case Platform.Android: testButton = await client.$(`//*[@text='${testButtonName.toUpperCase()}']`); break; case Platform.iOS: testButton = await client.$(`//XCUIElementTypeButton[@name="${testButtonName}"]`); break; } await testButton.waitForExist({ timeout: SmokeTestsConstants.waitForElementTimeout, }); await testButton.click(); } public static async isHermesWorking( client: AppiumClient, platform: Platform, ): Promise<boolean> { let hermesMark: any; switch (platform) { case Platform.Android: hermesMark = await client.$("//*[@text='Engine: Hermes']"); break; case Platform.iOS: hermesMark = await client.$('//XCUIElementTypeStaticText[@name="Engine: Hermes"]'); break; } return hermesMark.waitForExist({ timeout: SmokeTestsConstants.waitForElementTimeout, }); } private static async openExpoAppViaClipboardAndroid(client: AppiumClient, expoURL: string) { // Expo application automatically detects Expo URLs in the clipboard // So we are copying expoURL to system clipboard and click on the special "Open from Clipboard" UI element const exploreElement = await client.$("//android.widget.TextView[@text='Projects']"); await exploreElement.waitForExist({ timeout: SmokeTestsConstants.waitForElementTimeout }); await exploreElement.click(); SmokeTestLogger.info(`*** Pressing "Projects" icon...`); SmokeTestLogger.info(`*** Opening Expo app via clipboard`); SmokeTestLogger.info(`*** Copying ${expoURL} to system clipboard...`); clipboardy.writeSync(expoURL); const expoOpenFromClipboard = await client.$("//*[@text='Open from Clipboard']"); SmokeTestLogger.info( `*** Searching for ${expoOpenFromClipboard.selector} element for click...`, ); // Run Expo app by expoURL await expoOpenFromClipboard.waitForExist({ timeout: SmokeTestsConstants.waitForElementTimeout, }); await expoOpenFromClipboard.click(); SmokeTestLogger.info(`*** ${expoOpenFromClipboard.selector} clicked...`); } private static async openExpoAppViaExpoXDLAndroidFunction( client: AppiumClient, projectFolder: string, ) { SmokeTestLogger.info(`*** Opening Expo app via XDL.Android function`); SmokeTestLogger.info(`*** Searching for the "Explore" button...`); const exploreElement = await client.$("//android.widget.TextView[@text='Projects']"); await exploreElement.waitForExist({ timeout: SmokeTestsConstants.waitForElementTimeout }); await XDL.Android.openProjectAsync({ projectRoot: projectFolder }); } private static async openExpoAppViaExpoXDLSimulatorFunction( client: AppiumClient, projectFolder: string, firstLaunch?: boolean, ) { SmokeTestLogger.info(`*** Opening Expo app via XDL.Simulator function`); SmokeTestLogger.info(`*** Searching for the "Explore" button...`); const projectsElement = await client.$( `//XCUIElementTypeButton[@name="Projects, tab, 1 of 3"]`, ); await projectsElement.waitForExist({ timeout: SmokeTestsConstants.waitForElementTimeout }); await XDL.Simulator.openProjectAsync({ projectRoot: projectFolder }); if (firstLaunch) { // it's required to allow launch of an Expo application when it's launched for the first time SmokeTestLogger.info(`*** First launch of Expo app`); SmokeTestLogger.info(`*** Pressing "Open" button...`); const openButton = await client.$(`//XCUIElementTypeButton[@name="Open"]`); await openButton.waitForExist({ timeout: 10 * 1000 }); await openButton.click(); } } }
the_stack
import * as AngularAnimations from '@angular/animations'; import * as AngularCore from '@angular/core'; import * as AngularCommon from '@angular/common'; import * as AngularForms from '@angular/forms'; import * as AngularFlexLayout from '@angular/flex-layout'; import * as AngularFlexLayoutFlex from '@angular/flex-layout/flex'; import * as AngularFlexLayoutGrid from '@angular/flex-layout/grid'; import * as AngularFlexLayoutExtended from '@angular/flex-layout/extended'; import * as AngularPlatformBrowser from '@angular/platform-browser'; import * as AngularPlatformBrowserAnimations from '@angular/platform-browser/animations'; import * as AngularRouter from '@angular/router'; import * as AngularCdkCoercion from '@angular/cdk/coercion'; import * as AngularCdkCollections from '@angular/cdk/collections'; import * as AngularCdkKeycodes from '@angular/cdk/keycodes'; import * as AngularCdkLayout from '@angular/cdk/layout'; import * as AngularCdkOverlay from '@angular/cdk/overlay'; import * as AngularCdkPortal from '@angular/cdk/portal'; import * as AngularCdkBidi from '@angular/cdk/bidi'; import * as AngularCdkPlatform from '@angular/cdk/platform'; import * as AngularMaterialAutocomplete from '@angular/material/autocomplete'; import * as AngularMaterialBadge from '@angular/material/badge'; import * as AngularMaterialBottomSheet from '@angular/material/bottom-sheet'; import * as AngularMaterialButton from '@angular/material/button'; import * as AngularMaterialButtonToggle from '@angular/material/button-toggle'; import * as AngularMaterialCard from '@angular/material/card'; import * as AngularMaterialCheckbox from '@angular/material/checkbox'; import * as AngularMaterialChips from '@angular/material/chips'; import * as AngularMaterialCore from '@angular/material/core'; import * as AngularMaterialDatepicker from '@angular/material/datepicker'; import * as AngularMaterialDialog from '@angular/material/dialog'; import * as AngularMaterialDivider from '@angular/material/divider'; import * as AngularMaterialExpansion from '@angular/material/expansion'; import * as AngularMaterialFormField from '@angular/material/form-field'; import * as AngularMaterialGridList from '@angular/material/grid-list'; import * as AngularMaterialIcon from '@angular/material/icon'; import * as AngularMaterialInput from '@angular/material/input'; import * as AngularMaterialList from '@angular/material/list'; import * as AngularMaterialMenu from '@angular/material/menu'; import * as AngularMaterialPaginator from '@angular/material/paginator'; import * as AngularMaterialProgressBar from '@angular/material/progress-bar'; import * as AngularMaterialProgressSpinner from '@angular/material/progress-spinner'; import * as AngularMaterialRadio from '@angular/material/radio'; import * as AngularMaterialSelect from '@angular/material/select'; import * as AngularMaterialSidenav from '@angular/material/sidenav'; import * as AngularMaterialSlideToggle from '@angular/material/slide-toggle'; import * as AngularMaterialSlider from '@angular/material/slider'; import * as AngularMaterialSnackBar from '@angular/material/snack-bar'; import * as AngularMaterialSort from '@angular/material/sort'; import * as AngularMaterialStepper from '@angular/material/stepper'; import * as AngularMaterialTable from '@angular/material/table'; import * as AngularMaterialTabs from '@angular/material/tabs'; import * as AngularMaterialToolbar from '@angular/material/toolbar'; import * as AngularMaterialTooltip from '@angular/material/tooltip'; import * as AngularMaterialTree from '@angular/material/tree'; import * as DragDropModule from '@angular/cdk/drag-drop'; import * as HttpClientModule from '@angular/common/http'; import * as NgrxStore from '@ngrx/store'; import * as RxJs from 'rxjs'; import * as RxJsOperators from 'rxjs/operators'; import * as TranslateCore from '@ngx-translate/core'; import * as MatDateTimePicker from '@mat-datetimepicker/core'; import * as _moment from 'moment'; import * as tslib from 'tslib'; import * as TbCore from '@core/public-api'; import * as TbShared from '@shared/public-api'; import * as TbHomeComponents from '@home/components/public-api'; import * as MillisecondsToTimeStringPipe from '@shared/pipe/milliseconds-to-time-string.pipe'; import * as EnumToArrayPipe from '@shared/pipe/enum-to-array.pipe'; import * as HighlightPipe from '@shared/pipe/highlight.pipe'; import * as TruncatePipe from '@shared/pipe/truncate.pipe'; import * as TbJsonPipe from '@shared/pipe/tbJson.pipe'; import * as FileSizePipe from '@shared/pipe/file-size.pipe'; import * as NospacePipe from '@shared/pipe/nospace.pipe'; import * as SelectableColumnsPipe from '@shared/pipe/selectable-columns.pipe'; import * as KeyboardShortcutPipe from '@shared/pipe/keyboard-shortcut.pipe'; import * as FooterComponent from '@shared/components/footer.component'; import * as LogoComponent from '@shared/components/logo.component'; import * as FooterFabButtonsComponent from '@shared/components/footer-fab-buttons.component'; import * as FullscreenDirective from '@shared/components/fullscreen.directive'; import * as CircularProgressDirective from '@shared/components/circular-progress.directive'; import * as MatChipDraggableDirective from '@shared/components/mat-chip-draggable.directive'; import * as TbHotkeysDirective from '@shared/components/hotkeys.directive'; import * as TbAnchorComponent from '@shared/components/tb-anchor.component'; import * as TbPopoverComponent from '@shared/components/popover.component'; import * as TbStringTemplateOutletDirective from '@shared/components/directives/sring-template-outlet.directive'; import * as TbComponentOutletDirective from '@shared/components/directives/component-outlet.directive'; import * as TbMarkdownComponent from '@shared/components/markdown.component'; import * as HelpComponent from '@shared/components/help.component'; import * as HelpMarkdownComponent from '@shared/components/help-markdown.component'; import * as HelpPopupComponent from '@shared/components/help-popup.component'; import * as TbCheckboxComponent from '@shared/components/tb-checkbox.component'; import * as TbToast from '@shared/components/toast.directive'; import * as TbErrorComponent from '@shared/components/tb-error.component'; import * as TbCheatSheetComponent from '@shared/components/cheatsheet.component'; import * as BreadcrumbComponent from '@shared/components/breadcrumb.component'; import * as UserMenuComponent from '@shared/components/user-menu.component'; import * as TimewindowComponent from '@shared/components/time/timewindow.component'; import * as TimewindowPanelComponent from '@shared/components/time/timewindow-panel.component'; import * as TimeintervalComponent from '@shared/components/time/timeinterval.component'; import * as QuickTimeIntervalComponent from '@shared/components/time/quick-time-interval.component'; import * as DashboardSelectComponent from '@shared/components/dashboard-select.component'; import * as DashboardSelectPanelComponent from '@shared/components/dashboard-select-panel.component'; import * as DatetimePeriodComponent from '@shared/components/time/datetime-period.component'; import * as DatetimeComponent from '@shared/components/time/datetime.component'; import * as TimezoneSelectComponent from '@shared/components/time/timezone-select.component'; import * as ValueInputComponent from '@shared/components/value-input.component'; import * as DashboardAutocompleteComponent from '@shared/components/dashboard-autocomplete.component'; import * as EntitySubTypeAutocompleteComponent from '@shared/components/entity/entity-subtype-autocomplete.component'; import * as EntitySubTypeSelectComponent from '@shared/components/entity/entity-subtype-select.component'; import * as EntitySubTypeListComponent from '@shared/components/entity/entity-subtype-list.component'; import * as EntityAutocompleteComponent from '@shared/components/entity/entity-autocomplete.component'; import * as EntityListComponent from '@shared/components/entity/entity-list.component'; import * as EntityTypeSelectComponent from '@shared/components/entity/entity-type-select.component'; import * as EntitySelectComponent from '@shared/components/entity/entity-select.component'; import * as EntityKeysListComponent from '@shared/components/entity/entity-keys-list.component'; import * as EntityListSelectComponent from '@shared/components/entity/entity-list-select.component'; import * as EntityTypeListComponent from '@shared/components/entity/entity-type-list.component'; import * as QueueTypeListComponent from '@shared/components/queue/queue-type-list.component'; import * as RelationTypeAutocompleteComponent from '@shared/components/relation/relation-type-autocomplete.component'; import * as SocialSharePanelComponent from '@shared/components/socialshare-panel.component'; import * as JsonObjectEditComponent from '@shared/components/json-object-edit.component'; import * as JsonContentComponent from '@shared/components/json-content.component'; import * as JsFuncComponent from '@shared/components/js-func.component'; import * as FabToolbarComponent from '@shared/components/fab-toolbar.component'; import * as WidgetsBundleSelectComponent from '@shared/components/widgets-bundle-select.component'; import * as ConfirmDialogComponent from '@shared/components/dialog/confirm-dialog.component'; import * as AlertDialogComponent from '@shared/components/dialog/alert-dialog.component'; import * as TodoDialogComponent from '@shared/components/dialog/todo-dialog.component'; import * as ColorPickerDialogComponent from '@shared/components/dialog/color-picker-dialog.component'; import * as MaterialIconsDialogComponent from '@shared/components/dialog/material-icons-dialog.component'; import * as ColorInputComponent from '@shared/components/color-input.component'; import * as MaterialIconSelectComponent from '@shared/components/material-icon-select.component'; import * as NodeScriptTestDialogComponent from '@shared/components/dialog/node-script-test-dialog.component'; import * as JsonFormComponent from '@shared/components/json-form/json-form.component'; import * as ImageInputComponent from '@shared/components/image-input.component'; import * as FileInputComponent from '@shared/components/file-input.component'; import * as MessageTypeAutocompleteComponent from '@shared/components/message-type-autocomplete.component'; import * as KeyValMapComponent from '@shared/components/kv-map.component'; import * as NavTreeComponent from '@shared/components/nav-tree.component'; import * as LedLightComponent from '@shared/components/led-light.component'; import * as TbJsonToStringDirective from '@shared/components/directives/tb-json-to-string.directive'; import * as JsonObjectEditDialogComponent from '@shared/components/dialog/json-object-edit-dialog.component'; import * as HistorySelectorComponent from '@shared/components/time/history-selector/history-selector.component'; import * as EntityGatewaySelectComponent from '@shared/components/entity/entity-gateway-select.component'; import * as ContactComponent from '@shared/components/contact.component'; import * as OtaPackageAutocompleteComponent from '@shared/components/ota-package/ota-package-autocomplete.component'; import * as WidgetsBundleSearchComponent from '@shared/components/widgets-bundle-search.component'; import * as CopyButtonComponent from '@shared/components/button/copy-button.component'; import * as TogglePasswordComponent from '@shared/components/button/toggle-password.component'; import * as ProtobufContentComponent from '@shared/components/protobuf-content.component'; import * as AddEntityDialogComponent from '@home/components/entity/add-entity-dialog.component'; import * as EntitiesTableComponent from '@home/components/entity/entities-table.component'; import * as DetailsPanelComponent from '@home/components/details-panel.component'; import * as EntityDetailsPanelComponent from '@home/components/entity/entity-details-panel.component'; import * as AuditLogDetailsDialogComponent from '@home/components/audit-log/audit-log-details-dialog.component'; import * as AuditLogTableComponent from '@home/components/audit-log/audit-log-table.component'; import * as EventTableHeaderComponent from '@home/components/event/event-table-header.component'; import * as EventTableComponent from '@home/components/event/event-table.component'; import * as EventFilterPanelComponent from '@home/components/event/event-filter-panel.component'; import * as RelationTableComponent from '@home/components/relation/relation-table.component'; import * as RelationDialogComponent from '@home/components/relation/relation-dialog.component'; import * as AlarmTableHeaderComponent from '@home/components/alarm/alarm-table-header.component'; import * as AlarmTableComponent from '@home/components/alarm/alarm-table.component'; import * as AttributeTableComponent from '@home/components/attribute/attribute-table.component'; import * as AddAttributeDialogComponent from '@home/components/attribute/add-attribute-dialog.component'; import * as EditAttributeValuePanelComponent from '@home/components/attribute/edit-attribute-value-panel.component'; import * as DashboardComponent from '@home/components/dashboard/dashboard.component'; import * as WidgetComponent from '@home/components/widget/widget.component'; import * as LegendComponent from '@home/components/widget/legend.component'; import * as AliasesEntitySelectPanelComponent from '@home/components/alias/aliases-entity-select-panel.component'; import * as AliasesEntitySelectComponent from '@home/components/alias/aliases-entity-select.component'; import * as WidgetConfigComponent from '@home/components/widget/widget-config.component'; import * as EntityAliasesDialogComponent from '@home/components/alias/entity-aliases-dialog.component'; import * as EntityFilterViewComponent from '@home/components/entity/entity-filter-view.component'; import * as EntityAliasDialogComponent from '@home/components/alias/entity-alias-dialog.component'; import * as EntityFilterComponent from '@home/components/entity/entity-filter.component'; import * as RelationFiltersComponent from '@home/components/relation/relation-filters.component'; import * as EntityAliasSelectComponent from '@home/components/alias/entity-alias-select.component'; import * as DataKeysComponent from '@home/components/widget/data-keys.component'; import * as DataKeyConfigDialogComponent from '@home/components/widget/data-key-config-dialog.component'; import * as DataKeyConfigComponent from '@home/components/widget/data-key-config.component'; import * as LegendConfigComponent from '@home/components/widget/legend-config.component'; import * as ManageWidgetActionsComponent from '@home/components/widget/action/manage-widget-actions.component'; import * as WidgetActionDialogComponent from '@home/components/widget/action/widget-action-dialog.component'; import * as CustomActionPrettyResourcesTabsComponent from '@home/components/widget/action/custom-action-pretty-resources-tabs.component'; import * as CustomActionPrettyEditorComponent from '@home/components/widget/action/custom-action-pretty-editor.component'; import * as MobileActionEditorComponent from '@home/components/widget/action/mobile-action-editor.component'; import * as CustomDialogService from '@home/components/widget/dialog/custom-dialog.service'; import * as CustomDialogContainerComponent from '@home/components/widget/dialog/custom-dialog-container.component'; import * as ImportDialogComponent from '@home/components/import-export/import-dialog.component'; import * as AddWidgetToDashboardDialogComponent from '@home/components/attribute/add-widget-to-dashboard-dialog.component'; import * as ImportDialogCsvComponent from '@home/components/import-export/import-dialog-csv.component'; import * as TableColumnsAssignmentComponent from '@home/components/import-export/table-columns-assignment.component'; import * as EventContentDialogComponent from '@home/components/event/event-content-dialog.component'; import * as SharedHomeComponentsModule from '@home/components/shared-home-components.module'; import * as SelectTargetLayoutDialogComponent from '@home/components/dashboard/select-target-layout-dialog.component'; import * as SelectTargetStateDialogComponent from '@home/components/dashboard/select-target-state-dialog.component'; import * as AliasesEntityAutocompleteComponent from '@home/components/alias/aliases-entity-autocomplete.component'; import * as BooleanFilterPredicateComponent from '@home/components/filter/boolean-filter-predicate.component'; import * as StringFilterPredicateComponent from '@home/components/filter/string-filter-predicate.component'; import * as NumericFilterPredicateComponent from '@home/components/filter/numeric-filter-predicate.component'; import * as ComplexFilterPredicateComponent from '@home/components/filter/complex-filter-predicate.component'; import * as FilterPredicateComponent from '@home/components/filter/filter-predicate.component'; import * as FilterPredicateListComponent from '@home/components/filter/filter-predicate-list.component'; import * as KeyFilterListComponent from '@home/components/filter/key-filter-list.component'; import * as ComplexFilterPredicateDialogComponent from '@home/components/filter/complex-filter-predicate-dialog.component'; import * as KeyFilterDialogComponent from '@home/components/filter/key-filter-dialog.component'; import * as FiltersDialogComponent from '@home/components/filter/filters-dialog.component'; import * as FilterDialogComponent from '@home/components/filter/filter-dialog.component'; import * as FilterSelectComponent from '@home/components/filter/filter-select.component'; import * as FiltersEditComponent from '@home/components/filter/filters-edit.component'; import * as FiltersEditPanelComponent from '@home/components/filter/filters-edit-panel.component'; import * as UserFilterDialogComponent from '@home/components/filter/user-filter-dialog.component'; import * as FilterUserInfoComponent from '@home/components/filter/filter-user-info.component'; import * as FilterUserInfoDialogComponent from '@home/components/filter/filter-user-info-dialog.component'; import * as FilterPredicateValueComponent from '@home/components/filter/filter-predicate-value.component'; import * as TenantProfileComponent from '@home/components/profile/tenant-profile.component'; import * as TenantProfileDialogComponent from '@home/components/profile/tenant-profile-dialog.component'; import * as TenantProfileDataComponent from '@home/components/profile/tenant-profile-data.component'; // tslint:disable-next-line:max-line-length import * as DefaultDeviceProfileConfigurationComponent from '@home/components/profile/device/default-device-profile-configuration.component'; import * as DeviceProfileConfigurationComponent from '@home/components/profile/device/device-profile-configuration.component'; import * as DeviceProfileComponent from '@home/components/profile/device-profile.component'; import * as DefaultDeviceProfileTransportConfigurationComponent from '@home/components/profile/device/default-device-profile-transport-configuration.component'; import * as DeviceProfileTransportConfigurationComponent from '@home/components/profile/device/device-profile-transport-configuration.component'; import * as DeviceProfileDialogComponent from '@home/components/profile/device-profile-dialog.component'; import * as DeviceProfileAutocompleteComponent from '@home/components/profile/device-profile-autocomplete.component'; import * as MqttDeviceProfileTransportConfigurationComponent from '@home/components/profile/device/mqtt-device-profile-transport-configuration.component'; import * as CoapDeviceProfileTransportConfigurationComponent from '@home/components/profile/device/coap-device-profile-transport-configuration.component'; import * as DeviceProfileAlarmsComponent from '@home/components/profile/alarm/device-profile-alarms.component'; import * as DeviceProfileAlarmComponent from '@home/components/profile/alarm/device-profile-alarm.component'; import * as CreateAlarmRulesComponent from '@home/components/profile/alarm/create-alarm-rules.component'; import * as AlarmRuleComponent from '@home/components/profile/alarm/alarm-rule.component'; import * as AlarmRuleConditionComponent from '@home/components/profile/alarm/alarm-rule-condition.component'; import * as FilterTextComponent from '@home/components/filter/filter-text.component'; import * as AddDeviceProfileDialogComponent from '@home/components/profile/add-device-profile-dialog.component'; import * as RuleChainAutocompleteComponent from '@home/components/rule-chain/rule-chain-autocomplete.component'; import * as DeviceProfileProvisionConfigurationComponent from '@home/components/profile/device-profile-provision-configuration.component'; import * as AlarmScheduleComponent from '@home/components/profile/alarm/alarm-schedule.component'; import * as DeviceWizardDialogComponent from '@home/components/wizard/device-wizard-dialog.component'; import * as AlarmScheduleInfoComponent from '@home/components/profile/alarm/alarm-schedule-info.component'; import * as AlarmScheduleDialogComponent from '@home/components/profile/alarm/alarm-schedule-dialog.component'; import * as EditAlarmDetailsDialogComponent from '@home/components/profile/alarm/edit-alarm-details-dialog.component'; import * as AlarmRuleConditionDialogComponent from '@home/components/profile/alarm/alarm-rule-condition-dialog.component'; // tslint:disable-next-line:max-line-length import * as DefaultTenantProfileConfigurationComponent from '@home/components/profile/tenant/default-tenant-profile-configuration.component'; import * as TenantProfileConfigurationComponent from '@home/components/profile/tenant/tenant-profile-configuration.component'; import * as SmsProviderConfigurationComponent from '@home/components/sms/sms-provider-configuration.component'; import * as AwsSnsProviderConfigurationComponent from '@home/components/sms/aws-sns-provider-configuration.component'; import * as TwilioSmsProviderConfigurationComponent from '@home/components/sms/twilio-sms-provider-configuration.component'; import * as DashboardPageComponent from '@home/components/dashboard-page/dashboard-page.component'; import * as DashboardToolbarComponent from '@home/components/dashboard-page/dashboard-toolbar.component'; import * as DashboardLayoutComponent from '@home/components/dashboard-page/layout/dashboard-layout.component'; import * as EditWidgetComponent from '@home/components/dashboard-page/edit-widget.component'; import * as DashboardWidgetSelectComponent from '@home/components/dashboard-page/dashboard-widget-select.component'; import * as AddWidgetDialogComponent from '@home/components/dashboard-page/add-widget-dialog.component'; import * as ManageDashboardLayoutsDialogComponent from '@home/components/dashboard-page/layout/manage-dashboard-layouts-dialog.component'; import * as DashboardSettingsDialogComponent from '@home/components/dashboard-page/dashboard-settings-dialog.component'; import * as ManageDashboardStatesDialogComponent from '@home/components/dashboard-page/states/manage-dashboard-states-dialog.component'; import * as DashboardStateDialogComponent from '@home/components/dashboard-page/states/dashboard-state-dialog.component'; import * as EmbedDashboardDialogComponent from '@home/components/widget/dialog/embed-dashboard-dialog.component'; import * as EdgeDownlinkTableComponent from '@home/components/edge/edge-downlink-table.component'; import * as EdgeDownlinkTableHeaderComponent from '@home/components/edge/edge-downlink-table-header.component'; import * as DisplayWidgetTypesPanelComponent from '@home/components/dashboard-page/widget-types-panel.component'; import * as AlarmDurationPredicateValueComponent from '@home/components/profile/alarm/alarm-duration-predicate-value.component'; import * as DashboardImageDialogComponent from '@home/components/dashboard-page/dashboard-image-dialog.component'; import * as WidgetContainerComponent from '@home/components/widget/widget-container.component'; import { IModulesMap } from '@modules/common/modules-map.models'; declare const System; class ModulesMap implements IModulesMap { private initialized = false; private modulesMap: {[key: string]: any} = { '@angular/animations': AngularAnimations, '@angular/core': AngularCore, '@angular/common': AngularCommon, '@angular/common/http': HttpClientModule, '@angular/forms': AngularForms, '@angular/flex-layout': AngularFlexLayout, '@angular/flex-layout/flex': AngularFlexLayoutFlex, '@angular/flex-layout/grid': AngularFlexLayoutGrid, '@angular/flex-layout/extended': AngularFlexLayoutExtended, '@angular/platform-browser': AngularPlatformBrowser, '@angular/platform-browser/animations': AngularPlatformBrowserAnimations, '@angular/router': AngularRouter, '@angular/cdk/coercion': AngularCdkCoercion, '@angular/cdk/collections': AngularCdkCollections, '@angular/cdk/keycodes': AngularCdkKeycodes, '@angular/cdk/layout': AngularCdkLayout, '@angular/cdk/overlay': AngularCdkOverlay, '@angular/cdk/portal': AngularCdkPortal, '@angular/cdk/bidi': AngularCdkBidi, '@angular/cdk/platform': AngularCdkPlatform, '@angular/cdk/drag-drop': DragDropModule, '@angular/material/autocomplete': AngularMaterialAutocomplete, '@angular/material/badge': AngularMaterialBadge, '@angular/material/bottom-sheet': AngularMaterialBottomSheet, '@angular/material/button': AngularMaterialButton, '@angular/material/button-toggle': AngularMaterialButtonToggle, '@angular/material/card': AngularMaterialCard, '@angular/material/checkbox': AngularMaterialCheckbox, '@angular/material/chips': AngularMaterialChips, '@angular/material/core': AngularMaterialCore, '@angular/material/datepicker': AngularMaterialDatepicker, '@angular/material/dialog': AngularMaterialDialog, '@angular/material/divider': AngularMaterialDivider, '@angular/material/expansion': AngularMaterialExpansion, '@angular/material/form-field': AngularMaterialFormField, '@angular/material/grid-list': AngularMaterialGridList, '@angular/material/icon': AngularMaterialIcon, '@angular/material/input': AngularMaterialInput, '@angular/material/list': AngularMaterialList, '@angular/material/menu': AngularMaterialMenu, '@angular/material/paginator': AngularMaterialPaginator, '@angular/material/progress-bar': AngularMaterialProgressBar, '@angular/material/progress-spinner': AngularMaterialProgressSpinner, '@angular/material/radio': AngularMaterialRadio, '@angular/material/select': AngularMaterialSelect, '@angular/material/sidenav': AngularMaterialSidenav, '@angular/material/slide-toggle': AngularMaterialSlideToggle, '@angular/material/slider': AngularMaterialSlider, '@angular/material/snack-bar': AngularMaterialSnackBar, '@angular/material/sort': AngularMaterialSort, '@angular/material/stepper': AngularMaterialStepper, '@angular/material/table': AngularMaterialTable, '@angular/material/tabs': AngularMaterialTabs, '@angular/material/toolbar': AngularMaterialToolbar, '@angular/material/tooltip': AngularMaterialTooltip, '@angular/material/tree': AngularMaterialTree, '@ngrx/store': NgrxStore, rxjs: RxJs, 'rxjs/operators': RxJsOperators, '@ngx-translate/core': TranslateCore, '@mat-datetimepicker/core': MatDateTimePicker, moment: _moment, tslib, '@core/public-api': TbCore, '@shared/public-api': TbShared, '@home/components/public-api': TbHomeComponents, '@shared/pipe/milliseconds-to-time-string.pipe': MillisecondsToTimeStringPipe, '@shared/pipe/enum-to-array.pipe': EnumToArrayPipe, '@shared/pipe/highlight.pipe': HighlightPipe, '@shared/pipe/truncate.pipe': TruncatePipe, '@shared/pipe/tbJson.pipe': TbJsonPipe, '@shared/pipe/file-size.pipe': FileSizePipe, '@shared/pipe/nospace.pipe': NospacePipe, '@shared/pipe/selectable-columns.pipe': SelectableColumnsPipe, '@shared/pipe/keyboard-shortcut.pipe': KeyboardShortcutPipe, '@shared/components/footer.component': FooterComponent, '@shared/components/logo.component': LogoComponent, '@shared/components/footer-fab-buttons.component': FooterFabButtonsComponent, '@shared/components/fullscreen.directive': FullscreenDirective, '@shared/components/circular-progress.directive': CircularProgressDirective, '@shared/components/mat-chip-draggable.directive': MatChipDraggableDirective, '@shared/components/hotkeys.directive': TbHotkeysDirective, '@shared/components/tb-anchor.component': TbAnchorComponent, '@shared/components/popover.component': TbPopoverComponent, '@shared/components/directives/sring-template-outlet.directive': TbStringTemplateOutletDirective, '@shared/components/directives/component-outlet.directive': TbComponentOutletDirective, '@shared/components/markdown.component': TbMarkdownComponent, '@shared/components/help.component': HelpComponent, '@shared/components/help-markdown.component': HelpMarkdownComponent, '@shared/components/help-popup.component': HelpPopupComponent, '@shared/components/tb-checkbox.component': TbCheckboxComponent, '@shared/components/toast.directive': TbToast, '@shared/components/tb-error.component': TbErrorComponent, '@shared/components/cheatsheet.component': TbCheatSheetComponent, '@shared/components/breadcrumb.component': BreadcrumbComponent, '@shared/components/user-menu.component': UserMenuComponent, '@shared/components/time/timewindow.component': TimewindowComponent, '@shared/components/time/timewindow-panel.component': TimewindowPanelComponent, '@shared/components/time/timeinterval.component': TimeintervalComponent, '@shared/components/time/quick-time-interval.component': QuickTimeIntervalComponent, '@shared/components/dashboard-select.component': DashboardSelectComponent, '@shared/components/dashboard-select-panel.component': DashboardSelectPanelComponent, '@shared/components/time/datetime-period.component': DatetimePeriodComponent, '@shared/components/time/datetime.component': DatetimeComponent, '@shared/components/time/timezone-select.component': TimezoneSelectComponent, '@shared/components/value-input.component': ValueInputComponent, '@shared/components/dashboard-autocomplete.component': DashboardAutocompleteComponent, '@shared/components/entity/entity-subtype-autocomplete.component': EntitySubTypeAutocompleteComponent, '@shared/components/entity/entity-subtype-select.component': EntitySubTypeSelectComponent, '@shared/components/entity/entity-subtype-list.component': EntitySubTypeListComponent, '@shared/components/entity/entity-autocomplete.component': EntityAutocompleteComponent, '@shared/components/entity/entity-list.component': EntityListComponent, '@shared/components/entity/entity-type-select.component': EntityTypeSelectComponent, '@shared/components/entity/entity-select.component': EntitySelectComponent, '@shared/components/entity/entity-keys-list.component': EntityKeysListComponent, '@shared/components/entity/entity-list-select.component': EntityListSelectComponent, '@shared/components/entity/entity-type-list.component': EntityTypeListComponent, '@shared/components/queue/queue-type-list.component': QueueTypeListComponent, '@shared/components/relation/relation-type-autocomplete.component': RelationTypeAutocompleteComponent, '@shared/components/socialshare-panel.component': SocialSharePanelComponent, '@shared/components/json-object-edit.component': JsonObjectEditComponent, '@shared/components/json-content.component': JsonContentComponent, '@shared/components/js-func.component': JsFuncComponent, '@shared/components/fab-toolbar.component': FabToolbarComponent, '@shared/components/widgets-bundle-select.component': WidgetsBundleSelectComponent, '@shared/components/dialog/confirm-dialog.component': ConfirmDialogComponent, '@shared/components/dialog/alert-dialog.component': AlertDialogComponent, '@shared/components/dialog/todo-dialog.component': TodoDialogComponent, '@shared/components/dialog/color-picker-dialog.component': ColorPickerDialogComponent, '@shared/components/dialog/material-icons-dialog.component': MaterialIconsDialogComponent, '@shared/components/color-input.component': ColorInputComponent, '@shared/components/material-icon-select.component': MaterialIconSelectComponent, '@shared/components/dialog/node-script-test-dialog.component': NodeScriptTestDialogComponent, '@shared/components/json-form/json-form.component': JsonFormComponent, '@shared/components/image-input.component': ImageInputComponent, '@shared/components/file-input.component': FileInputComponent, '@shared/components/message-type-autocomplete.component': MessageTypeAutocompleteComponent, '@shared/components/kv-map.component': KeyValMapComponent, '@shared/components/nav-tree.component': NavTreeComponent, '@shared/components/led-light.component': LedLightComponent, '@shared/components/directives/tb-json-to-string.directive': TbJsonToStringDirective, '@shared/components/dialog/json-object-edit-dialog.component': JsonObjectEditDialogComponent, '@shared/components/time/history-selector/history-selector.component': HistorySelectorComponent, '@shared/components/entity/entity-gateway-select.component': EntityGatewaySelectComponent, '@shared/components/contact.component': ContactComponent, '@shared/components/ota-package/ota-package-autocomplete.component': OtaPackageAutocompleteComponent, '@shared/components/widgets-bundle-search.component': WidgetsBundleSearchComponent, '@shared/components/button/copy-button.component': CopyButtonComponent, '@shared/components/button/toggle-password.component': TogglePasswordComponent, '@shared/components/protobuf-content.component': ProtobufContentComponent, '@home/components/entity/add-entity-dialog.component': AddEntityDialogComponent, '@home/components/entity/entities-table.component': EntitiesTableComponent, '@home/components/details-panel.component': DetailsPanelComponent, '@home/components/entity/entity-details-panel.component': EntityDetailsPanelComponent, '@home/components/audit-log/audit-log-details-dialog.component': AuditLogDetailsDialogComponent, '@home/components/audit-log/audit-log-table.component': AuditLogTableComponent, '@home/components/event/event-table-header.component': EventTableHeaderComponent, '@home/components/event/event-table.component': EventTableComponent, '@home/components/event/event-filter-panel.component': EventFilterPanelComponent, '@home/components/relation/relation-table.component': RelationTableComponent, '@home/components/relation/relation-dialog.component': RelationDialogComponent, '@home/components/alarm/alarm-table-header.component': AlarmTableHeaderComponent, '@home/components/alarm/alarm-table.component': AlarmTableComponent, '@home/components/attribute/attribute-table.component': AttributeTableComponent, '@home/components/attribute/add-attribute-dialog.component': AddAttributeDialogComponent, '@home/components/attribute/edit-attribute-value-panel.component': EditAttributeValuePanelComponent, '@home/components/dashboard/dashboard.component': DashboardComponent, '@home/components/widget/widget.component': WidgetComponent, '@home/components/widget/legend.component': LegendComponent, '@home/components/alias/aliases-entity-select-panel.component': AliasesEntitySelectPanelComponent, '@home/components/alias/aliases-entity-select.component': AliasesEntitySelectComponent, '@home/components/widget/widget-config.component': WidgetConfigComponent, '@home/components/alias/entity-aliases-dialog.component': EntityAliasesDialogComponent, '@home/components/entity/entity-filter-view.component': EntityFilterViewComponent, '@home/components/alias/entity-alias-dialog.component': EntityAliasDialogComponent, '@home/components/entity/entity-filter.component': EntityFilterComponent, '@home/components/relation/relation-filters.component': RelationFiltersComponent, '@home/components/alias/entity-alias-select.component': EntityAliasSelectComponent, '@home/components/widget/data-keys.component': DataKeysComponent, '@home/components/widget/data-key-config-dialog.component': DataKeyConfigDialogComponent, '@home/components/widget/data-key-config.component': DataKeyConfigComponent, '@home/components/widget/legend-config.component': LegendConfigComponent, '@home/components/widget/action/manage-widget-actions.component': ManageWidgetActionsComponent, '@home/components/widget/action/widget-action-dialog.component': WidgetActionDialogComponent, '@home/components/widget/action/custom-action-pretty-resources-tabs.component': CustomActionPrettyResourcesTabsComponent, '@home/components/widget/action/custom-action-pretty-editor.component': CustomActionPrettyEditorComponent, '@home/components/widget/action/mobile-action-editor.component': MobileActionEditorComponent, '@home/components/widget/dialog/custom-dialog.service': CustomDialogService, '@home/components/widget/dialog/custom-dialog-container.component': CustomDialogContainerComponent, '@home/components/import-export/import-dialog.component': ImportDialogComponent, '@home/components/attribute/add-widget-to-dashboard-dialog.component': AddWidgetToDashboardDialogComponent, '@home/components/import-export/import-dialog-csv.component': ImportDialogCsvComponent, '@home/components/import-export/table-columns-assignment.component': TableColumnsAssignmentComponent, '@home/components/event/event-content-dialog.component': EventContentDialogComponent, '@home/components/shared-home-components.module': SharedHomeComponentsModule, '@home/components/dashboard/select-target-layout-dialog.component': SelectTargetLayoutDialogComponent, '@home/components/dashboard/select-target-state-dialog.component': SelectTargetStateDialogComponent, '@home/components/alias/aliases-entity-autocomplete.component': AliasesEntityAutocompleteComponent, '@home/components/filter/boolean-filter-predicate.component': BooleanFilterPredicateComponent, '@home/components/filter/string-filter-predicate.component': StringFilterPredicateComponent, '@home/components/filter/numeric-filter-predicate.component': NumericFilterPredicateComponent, '@home/components/filter/complex-filter-predicate.component': ComplexFilterPredicateComponent, '@home/components/filter/filter-predicate.component': FilterPredicateComponent, '@home/components/filter/filter-predicate-list.component': FilterPredicateListComponent, '@home/components/filter/key-filter-list.component': KeyFilterListComponent, '@home/components/filter/complex-filter-predicate-dialog.component': ComplexFilterPredicateDialogComponent, '@home/components/filter/key-filter-dialog.component': KeyFilterDialogComponent, '@home/components/filter/filters-dialog.component': FiltersDialogComponent, '@home/components/filter/filter-dialog.component': FilterDialogComponent, '@home/components/filter/filter-select.component': FilterSelectComponent, '@home/components/filter/filters-edit.component': FiltersEditComponent, '@home/components/filter/filters-edit-panel.component': FiltersEditPanelComponent, '@home/components/filter/user-filter-dialog.component': UserFilterDialogComponent, '@home/components/filter/filter-user-info.component': FilterUserInfoComponent, '@home/components/filter/filter-user-info-dialog.component': FilterUserInfoDialogComponent, '@home/components/filter/filter-predicate-value.component': FilterPredicateValueComponent, '@home/components/profile/tenant-profile.component': TenantProfileComponent, '@home/components/profile/tenant-profile-dialog.component': TenantProfileDialogComponent, '@home/components/profile/tenant-profile-data.component': TenantProfileDataComponent, '@home/components/profile/device/default-device-profile-configuration.component': DefaultDeviceProfileConfigurationComponent, '@home/components/profile/device/device-profile-configuration.component': DeviceProfileConfigurationComponent, '@home/components/profile/device-profile.component': DeviceProfileComponent, '@home/components/profile/device/default-device-profile-transport-configuration.component': DefaultDeviceProfileTransportConfigurationComponent, '@home/components/profile/device/device-profile-transport-configuration.component': DeviceProfileTransportConfigurationComponent, '@home/components/profile/device-profile-dialog.component': DeviceProfileDialogComponent, '@home/components/profile/device-profile-autocomplete.component': DeviceProfileAutocompleteComponent, '@home/components/profile/device/mqtt-device-profile-transport-configuration.component': MqttDeviceProfileTransportConfigurationComponent, '@home/components/profile/device/coap-device-profile-transport-configuration.component': CoapDeviceProfileTransportConfigurationComponent, '@home/components/profile/alarm/device-profile-alarms.component': DeviceProfileAlarmsComponent, '@home/components/profile/alarm/device-profile-alarm.component': DeviceProfileAlarmComponent, '@home/components/profile/alarm/create-alarm-rules.component': CreateAlarmRulesComponent, '@home/components/profile/alarm/alarm-rule.component': AlarmRuleComponent, '@home/components/profile/alarm/alarm-rule-condition.component': AlarmRuleConditionComponent, '@home/components/filter/filter-text.component': FilterTextComponent, '@home/components/profile/add-device-profile-dialog.component': AddDeviceProfileDialogComponent, '@home/components/rule-chain/rule-chain-autocomplete.component': RuleChainAutocompleteComponent, '@home/components/profile/device-profile-provision-configuration.component': DeviceProfileProvisionConfigurationComponent, '@home/components/profile/alarm/alarm-schedule.component': AlarmScheduleComponent, '@home/components/wizard/device-wizard-dialog.component': DeviceWizardDialogComponent, '@home/components/profile/alarm/alarm-schedule-info.component': AlarmScheduleInfoComponent, '@home/components/profile/alarm/alarm-schedule-dialog.component': AlarmScheduleDialogComponent, '@home/components/profile/alarm/edit-alarm-details-dialog.component': EditAlarmDetailsDialogComponent, '@home/components/profile/alarm/alarm-rule-condition-dialog.component': AlarmRuleConditionDialogComponent, '@home/components/profile/tenant/default-tenant-profile-configuration.component': DefaultTenantProfileConfigurationComponent, '@home/components/profile/tenant/tenant-profile-configuration.component': TenantProfileConfigurationComponent, '@home/components/sms/sms-provider-configuration.component': SmsProviderConfigurationComponent, '@home/components/sms/aws-sns-provider-configuration.component': AwsSnsProviderConfigurationComponent, '@home/components/sms/twilio-sms-provider-configuration.component': TwilioSmsProviderConfigurationComponent, '@home/components/dashboard-page/dashboard-page.component': DashboardPageComponent, '@home/components/dashboard-page/dashboard-toolbar.component': DashboardToolbarComponent, '@home/components/dashboard-page/layout/dashboard-layout.component': DashboardLayoutComponent, '@home/components/dashboard-page/edit-widget.component': EditWidgetComponent, '@home/components/dashboard-page/dashboard-widget-select.component': DashboardWidgetSelectComponent, '@home/components/dashboard-page/add-widget-dialog.component': AddWidgetDialogComponent, '@home/components/dashboard-page/layout/manage-dashboard-layouts-dialog.component': ManageDashboardLayoutsDialogComponent, '@home/components/dashboard-page/dashboard-settings-dialog.component': DashboardSettingsDialogComponent, '@home/components/dashboard-page/states/manage-dashboard-states-dialog.component': ManageDashboardStatesDialogComponent, '@home/components/dashboard-page/states/dashboard-state-dialog.component': DashboardStateDialogComponent, '@home/components/widget/dialog/embed-dashboard-dialog.component': EmbedDashboardDialogComponent, '@home/components/edge/edge-downlink-table.component': EdgeDownlinkTableComponent, '@home/components/edge/edge-downlink-table-header.component': EdgeDownlinkTableHeaderComponent, '@home/components/dashboard-page/widget-types-panel.component': DisplayWidgetTypesPanelComponent, '@home/components/profile/alarm/alarm-duration-predicate-value.component': AlarmDurationPredicateValueComponent, '@home/components/dashboard-page/dashboard-image-dialog.component': DashboardImageDialogComponent, '@home/components/widget/widget-container.component': WidgetContainerComponent, }; init() { if (!this.initialized) { System.constructor.prototype.resolve = (id) => { try { if (this.modulesMap[id]) { return 'app:' + id; } else { return id; } } catch (err) { return id; } }; for (const moduleId of Object.keys(this.modulesMap)) { System.set('app:' + moduleId, this.modulesMap[moduleId]); } this.initialized = true; } } } export const modulesMap = new ModulesMap();
the_stack
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subject, forkJoin } from 'rxjs'; import { TranslateService } from '@ngx-translate/core'; import { TranslateReplaceService, WebAppSettingDataService, MessageQueueService, MESSAGE_TO, AnalyticsService, TRACKED_EVENT_LIST } from 'app/shared/services'; import { PinpointUserDataService, IPinpointUserResponse } from './pinpoint-user-data.service'; import { isThatType, isEmpty } from 'app/core/utils/util'; @Component({ selector: 'pp-pinpoint-user-container', templateUrl: './pinpoint-user-container.component.html', styleUrls: ['./pinpoint-user-container.component.css'] }) export class PinpointUserContainerComponent implements OnInit, OnDestroy { private unsubscribe = new Subject<void>(); private searchQuery = ''; i18nLabel = { USER_ID_LABEL: '', NAME_LABEL: '', DEPARTMENT_LABEL: '', PHONE_LABEL: '', EMAIL_LABEL: '', }; i18nGuide: { [key: string]: IFormFieldErrorType }; i18nText = { EMPTY: '', SEARCH_INPUT_GUIDE: '' }; minLength = { userId: 3, name: 3, search: 2 }; allowedUserEdit = false; searchUseEnter = true; pinpointUserList: IUserProfile[] = []; groupMemberList: string[] = []; userInfo: IUserProfile; isUserGroupSelected = false; useDisable = true; showLoading = true; showCreate = false; errorMessage: string; isEmpty: boolean; constructor( private webAppSettingDataService: WebAppSettingDataService, private pinpointUserDataService: PinpointUserDataService, private translateService: TranslateService, private translateReplaceService: TranslateReplaceService, private messageQueueService: MessageQueueService, private analyticsService: AnalyticsService, ) {} ngOnInit() { this.webAppSettingDataService.useUserEdit().subscribe((allowedUserEdit: boolean) => { this.allowedUserEdit = allowedUserEdit; }); this.messageQueueService.receiveMessage(this.unsubscribe, MESSAGE_TO.USER_GROUP_SELECTED_USER_GROUP).subscribe((userGroupId: string) => { this.isUserGroupSelected = userGroupId === '' ? false : true; }); this.messageQueueService.receiveMessage(this.unsubscribe, MESSAGE_TO.GROUP_MEMBER_SET_CURRENT_GROUP_MEMBERS).subscribe((param: string[]) => { this.groupMemberList = param; this.hideProcessing(); }); this.getI18NText(); this.getPinpointUserList(); } ngOnDestroy() { this.unsubscribe.next(); this.unsubscribe.complete(); } private getI18NText(): void { forkJoin( this.translateService.get('COMMON.EMPTY_ON_SEARCH'), this.translateService.get('COMMON.MIN_LENGTH'), this.translateService.get('COMMON.REQUIRED'), this.translateService.get('CONFIGURATION.COMMON.USER_ID'), this.translateService.get('CONFIGURATION.COMMON.NAME'), this.translateService.get('CONFIGURATION.COMMON.DEPARTMENT'), this.translateService.get('CONFIGURATION.COMMON.PHONE'), this.translateService.get('CONFIGURATION.COMMON.EMAIL'), this.translateService.get('CONFIGURATION.PINPOINT_USER.USER_ID_VALIDATION'), this.translateService.get('CONFIGURATION.PINPOINT_USER.NAME_VALIDATION'), this.translateService.get('CONFIGURATION.PINPOINT_USER.DEPARTMENT_VALIDATION'), this.translateService.get('CONFIGURATION.PINPOINT_USER.PHONE_VALIDATION'), this.translateService.get('CONFIGURATION.PINPOINT_USER.EMAIL_VALIDATION'), ).subscribe(([ emptyText, minLengthMessage, requiredMessage, idLabel, nameLabel, departmentLabel, phoneLabel, emailLabel, userIdValidation, nameValidation, departmentValidation, phoneValidation, emailValidation ]: string[]) => { this.i18nGuide = { userId: { required: this.translateReplaceService.replace(requiredMessage, idLabel), valueRule: userIdValidation }, name: { required: this.translateReplaceService.replace(requiredMessage, nameLabel), valueRule: nameValidation }, department: { valueRule: departmentValidation }, phoneNumber: { valueRule: phoneValidation }, email: { minlength: emailValidation, maxlength: emailValidation, valueRule: emailValidation } }; this.i18nText.EMPTY = emptyText; this.i18nText.SEARCH_INPUT_GUIDE = this.translateReplaceService.replace(minLengthMessage, this.minLength.search); this.i18nLabel.USER_ID_LABEL = idLabel; this.i18nLabel.NAME_LABEL = nameLabel; this.i18nLabel.DEPARTMENT_LABEL = departmentLabel; this.i18nLabel.PHONE_LABEL = phoneLabel; this.i18nLabel.EMAIL_LABEL = emailLabel; }); } private getPinpointUserList(query?: string): void { this.showProcessing(); this.pinpointUserDataService.retrieve(query).subscribe((result: IUserProfile[] | IServerErrorShortFormat) => { isThatType<IServerErrorShortFormat>(result, 'errorCode', 'errorMessage') ? this.errorMessage = result.errorMessage : (this.pinpointUserList = result, this.isEmpty = isEmpty(this.pinpointUserList)); this.hideProcessing(); }, (error: IServerErrorFormat) => { this.errorMessage = error.exception.message; this.hideProcessing(); }); } isChecked(userId: string): boolean { return this.groupMemberList.indexOf(userId) !== -1; } onAddUser(pinpointUserId: string): void { this.messageQueueService.sendMessage({ to: MESSAGE_TO.PINPOINT_USER_ADD_USER, param: pinpointUserId }); this.analyticsService.trackEvent(TRACKED_EVENT_LIST.ADD_USER_TO_GROUP); } onCloseErrorMessage(): void { this.errorMessage = ''; } onCheckUser(userId: string): void { this.userInfo = this.getUserInfo(userId); this.showCreate = true; } onSearch(query: string): void { this.searchQuery = query; this.getPinpointUserList(this.searchQuery); this.analyticsService.trackEvent(TRACKED_EVENT_LIST.SEARCH_USER); } onReload(): void { this.getPinpointUserList(this.searchQuery); this.analyticsService.trackEvent(TRACKED_EVENT_LIST.RELOAD_USER_LIST); } onCloseCreateUserPopup(): void { this.showCreate = false; } onShowAddUser(): void { this.userInfo = null; this.showCreate = true; this.analyticsService.trackEvent(TRACKED_EVENT_LIST.SHOW_USER_CREATION_POPUP); } // TODO: Refactor - Avoid nested subscribe syntax. onCreatePinpointUser(userInfo: IUserProfile): void { this.pinpointUserDataService.create(userInfo).subscribe((response: IPinpointUserResponse | IServerErrorShortFormat) => { isThatType<IServerErrorShortFormat>(response, 'errorCode', 'errorMessage') ? this.errorMessage = response.errorMessage : ( this.getPinpointUserList(this.searchQuery), this.analyticsService.trackEvent(TRACKED_EVENT_LIST.CREATE_USER) ); this.hideProcessing(); }, (error: IServerErrorFormat) => { this.hideProcessing(); this.errorMessage = error.exception.message; }); } // TODO: Refactor - Avoid nested subscribe syntax. onUpdatePinpointUser(userInfo: IUserProfile): void { this.showProcessing(); this.pinpointUserDataService.update(userInfo).subscribe((response: IPinpointUserResponse | IServerErrorShortFormat) => { if (isThatType<IServerErrorShortFormat>(response, 'errorCode', 'errorMessage')) { this.errorMessage = response.errorMessage; } else { this.getPinpointUserList(this.searchQuery); if (this.isUserGroupSelected) { this.messageQueueService.sendMessage({ to: MESSAGE_TO.PINPOINT_USER_UPDATE_USER, param: { userId: userInfo.userId, department: userInfo.department, name: userInfo.name } }); } this.analyticsService.trackEvent(TRACKED_EVENT_LIST.UPDATE_USER); } this.hideProcessing(); }, (error: IServerErrorFormat) => { this.hideProcessing(); this.errorMessage = error.exception.message; }); } // TODO: Refactor - Avoid nested subscribe syntax. onRemovePinpointUser(userId: string): void { this.showProcessing(); this.pinpointUserDataService.remove(userId).subscribe((response: IPinpointUserResponse | IServerErrorShortFormat) => { if (isThatType<IServerErrorShortFormat>(response, 'errorCode', 'errorMessage')) { this.errorMessage = response.errorMessage; } else { this.getPinpointUserList(this.searchQuery); if (this.isUserGroupSelected) { this.messageQueueService.sendMessage({ to: MESSAGE_TO.PINPOINT_USER_REMOVE_USER, param: userId }); } this.analyticsService.trackEvent(TRACKED_EVENT_LIST.REMOVE_USER); } this.hideProcessing(); }, (error: IServerErrorFormat) => { this.hideProcessing(); this.errorMessage = error.exception.message; }); } onShowUpdateUser(userId: string): void { this.userInfo = this.getUserInfo(userId); this.showCreate = true; this.analyticsService.trackEvent(TRACKED_EVENT_LIST.SHOW_USER_UPDATE_POPUP); } private getUserInfo(userId: string): IUserProfile { return this.pinpointUserList.find(({userId: id}: IUserProfile) => id === userId); } private showProcessing(): void { this.useDisable = true; this.showLoading = true; } private hideProcessing(): void { this.useDisable = false; this.showLoading = false; } }
the_stack
import cls from 'classnames'; import React from 'react'; import AutoSizer from 'react-virtualized-auto-sizer'; import { FixedSizeList, VariableSizeList, Align, ListOnScrollProps } from 'react-window'; import { ScrollbarsVirtualList } from '../scrollbars'; export interface IRecycleListProps { /** * 容器高度 * height 计算出可视区域渲染数量 * @type {number} * @memberof RecycleTreeProps */ height?: number; /** * 容器宽度 * height 计算出可视区域渲染数量 * @type {number} * @memberof RecycleTreeProps */ width?: number; /** * 最大容器高度 * 当容器内容高度大于该值时列表将不再增长,而是出现滚动条 * maxHeight 匹配优先级高于 height 属性 * @type {number} * @memberof RecycleTreeProps */ maxHeight?: number; /** * 最小容器高度 * 当容器内容高度小于该值时将不再收缩,而是固定高度,一般需要配合 maxHeight一起使用 * maxHeight 匹配优先级高于 height 属性 * @type {number} * @memberof RecycleTreeProps */ minHeight?: number; /** * 节点高度 * @type {number} * @memberof RecycleTreeProps */ itemHeight?: number; /** * List外部样式 * @type {React.CSSProperties} * @memberof RecycleListProps */ style?: React.CSSProperties; /** * List外部样式名 * @type {string} * @memberof RecycleListProps */ className?: string; /** * List数据源 * @type {any[]} * @memberof IRecycleListProps */ data: any[]; /** * 基础数据源渲染模板 * 默认传入参数为:(data, index) => {} * data 为 this.props.data中的子项 * index 为当前下标 * @type {React.ComponentType<any>} * @memberof IRecycleListProps */ template: React.ComponentType<any>; /** * 头部组件渲染模板 * 默认传入参数为:() => {} * @type {React.ComponentType<any>} * @memberof IRecycleListProps */ header?: React.ComponentType<any>; /** * 底部组件渲染模板 * 默认传入参数为:() => {} * @type {React.ComponentType<any>} * @memberof IRecycleListProps */ footer?: React.ComponentType<any>; /** * List 底部边距大小,默认值为 0 * @type {React.ComponentType<any>} * @memberof IRecycleListProps */ paddingBottomSize?: number; /** * 处理 RecycleList API回调 * @memberof IRecycleListProps */ onReady?: (api: IRecycleListHandler) => void; /** * Called when the list scroll positions changes, as a result of user scrolling or scroll-to method calls. */ onScroll?: ((props: ListOnScrollProps) => any) | undefined; /** * 如果为不定高 Item 时可以指定动态获取 item Size * https://react-window.vercel.app/#/examples/list/variable-size */ getSize?: (index: number) => number; } export interface IRecycleListHandler { scrollTo: (offset: number) => void; scrollToIndex: (index: number, position?: Align) => void; } export const RECYCLE_LIST_STABILIZATION_TIME = 500; export const RECYCLE_LIST_OVER_SCAN_COUNT = 50; export const RecycleList: React.FC<IRecycleListProps> = ({ width, height, maxHeight, minHeight, className, style, data, onReady, onScroll, itemHeight, header: Header, footer: Footer, template: Template, paddingBottomSize, getSize: customGetSize, }) => { const listRef = React.useRef<FixedSizeList | VariableSizeList>(); const sizeMap = React.useRef<{ [key: string]: number }>({}); const scrollToIndexTimer = React.useRef<any>(); React.useEffect(() => { if (typeof onReady === 'function') { const api = { scrollTo: (offset: number) => { listRef.current?.scrollTo(offset); }, // custom alignment: center, start, or end scrollToIndex: (index: number, position: Align = 'start') => { let locationIndex = index; if (Header) { locationIndex++; } if (typeof itemHeight === 'number') { listRef.current?.scrollToItem(locationIndex, position); } else { if (scrollToIndexTimer.current) { clearTimeout(scrollToIndexTimer.current); } const keys = sizeMap.current ? Object.keys(sizeMap.current) : []; const offset = keys.slice(0, locationIndex).reduce((p, i) => p + getSize(i), 0); listRef.current?.scrollToItem(index, position); // 在动态列表情况下,由于渲染抖动问题,可能需要再渲染后尝试再进行一次滚动位置定位 scrollToIndexTimer.current = setTimeout(() => { const keys = sizeMap.current ? Object.keys(sizeMap.current) : []; const nextOffset = keys.slice(0, locationIndex).reduce((p, i) => p + getSize(i), 0); if (nextOffset !== offset) { listRef.current?.scrollToItem(index, position); } scrollToIndexTimer.current = null; }, RECYCLE_LIST_STABILIZATION_TIME); } }, }; onReady(api); } }, []); const setSize = (index: number, size: number) => { if (sizeMap.current[index] !== size) { sizeMap.current = { ...sizeMap.current, [index]: size }; if (listRef.current) { // 清理缓存数据并重新渲染 (listRef.current as VariableSizeList<any>)?.resetAfterIndex(0); } } }; const getSize = React.useCallback( (index: string | number) => { if (customGetSize) { return customGetSize(Number(index)); } return (sizeMap?.current || [])[index] || itemHeight || 100; }, [itemHeight, customGetSize], ); const getMaxListHeight = React.useCallback(() => { if (maxHeight) { let height = 0; for (let i = 0; i < data.length; i++) { height += getSize(i); } if (height > maxHeight) { return maxHeight; } else { return height; } } }, [maxHeight, data]); const getMinListHeight = React.useCallback(() => { if (minHeight) { return minHeight; } }, [minHeight, data]); const adjustedRowCount = React.useMemo(() => { let count = data.length; if (Header) { count++; } if (Footer) { count++; } return count; }, [data]); const renderItem = ({ index, style }): JSX.Element => { let node; if (index === 0) { if (Header) { return ( <div style={style}> <Header /> </div> ); } } if (index + 1 === adjustedRowCount) { if (Footer) { return ( <div style={style}> <Footer /> </div> ); } } if (Header) { node = data[index - 1]; } else { node = data[index]; } if (!node) { return <div style={style}></div>; } // ref: https://developers.google.com/web/fundamentals/accessibility/semantics-aria/aria-labels-and-relationships const ariaInfo = { 'aria-setsize': adjustedRowCount, 'aria-posinset': index, }; return ( <div tabIndex={0} style={style} role='listitem' {...ariaInfo}> <Template data={node} index={index} /> </div> ); }; const renderDynamicItem = ({ index, style }): JSX.Element => { const rowRoot = React.useRef<null | HTMLDivElement>(null); const observer = React.useRef<any>(); const setItemSize = () => { if (rowRoot.current) { let height = 0; // eslint-disable-next-line @typescript-eslint/prefer-for-of for (let i = 0; i < rowRoot.current.children.length; i++) { height += rowRoot.current.children[i].getBoundingClientRect().height; } setSize(index, height); } }; React.useEffect(() => { if (rowRoot.current && listRef.current) { observer.current = new MutationObserver((mutations, observer) => { setItemSize(); }); const observerOption = { childList: true, // 子节点的变动(新增、删除或者更改) attributes: true, // 属性的变动 characterData: true, // 节点内容或节点文本的变动 attributeFilter: ['class', 'style'], // 观察特定属性 attributeOldValue: true, // 观察 attributes 变动时,是否需要记录变动前的属性值 characterDataOldValue: true, // 观察 characterData 变动,是否需要记录变动前的值 }; // 监听子节点属性变化 observer.current.observe(rowRoot.current, observerOption); setItemSize(); } return () => { observer.current.disconnect(); }; }, [rowRoot.current]); let node; if (index === 0) { if (Header) { return ( <div style={style}> <Header /> </div> ); } } if (index + 1 === adjustedRowCount) { if (Footer) { return ( <div style={style}> <Footer /> </div> ); } } if (Header) { node = data[index - 1]; } else { node = data[index]; } if (!node) { return <div style={style}></div>; } return ( <div style={style} ref={rowRoot}> <Template data={node} index={index} /> </div> ); }; // 通过计算平均行高来提高准确性 // 修复滚动条行为,见: https://github.com/bvaughn/react-window/issues/408 const calcEstimatedSize = React.useMemo(() => { const estimatedHeight = data.reduce((p, i) => p + getSize(i), 0); return estimatedHeight / data.length; }, [data]); // 为 List 添加下边距 const InnerElementType = React.forwardRef((props, ref) => { const { style, ...rest } = props as any; return ( <div ref={ref!} style={{ ...style, height: `${parseFloat(style.height) + (paddingBottomSize ? paddingBottomSize : 0)}px`, }} {...rest} /> ); }); const render = () => { const isDynamicList = typeof itemHeight !== 'number'; const isAutoSizeList = !width || !height; const renderList = () => { const renderContent = ({ width, height }) => { const maxH = getMaxListHeight(); const minH = getMinListHeight(); let currentHeight = height; if (minH) { currentHeight = Math.min(height, minH); } else if (maxH) { currentHeight = maxH; } if (isDynamicList) { return ( <VariableSizeList onScroll={onScroll} width={width} height={currentHeight} // 这里的数据不是必要的,主要用于在每次更新列表 itemData={[]} itemSize={getSize} itemCount={adjustedRowCount} overscanCount={RECYCLE_LIST_OVER_SCAN_COUNT} ref={listRef as any} style={{ transform: 'translate3d(0px, 0px, 0px)', ...style, }} className={cls(className, 'kt-recycle-list')} innerElementType={InnerElementType} outerElementType={ScrollbarsVirtualList} estimatedItemSize={calcEstimatedSize} > {renderDynamicItem} </VariableSizeList> ); } else { return ( <FixedSizeList onScroll={onScroll} width={width} height={currentHeight} // 这里的数据不是必要的,主要用于在每次更新列表 itemData={[]} itemSize={itemHeight} itemCount={adjustedRowCount} overscanCount={RECYCLE_LIST_OVER_SCAN_COUNT} ref={listRef as any} style={{ transform: 'translate3d(0px, 0px, 0px)', ...style, }} className={cls(className, 'kt-recycle-list')} innerElementType={InnerElementType} outerElementType={ScrollbarsVirtualList} > {renderItem} </FixedSizeList> ); } }; if (!isAutoSizeList) { return renderContent({ width, height }); } else { return <AutoSizer>{renderContent}</AutoSizer>; } }; return renderList(); }; return render(); };
the_stack
'use strict' namespace altai { const vertexFormatMap = [ [ 1, WebGLRenderingContext.FLOAT, false ], [ 2, WebGLRenderingContext.FLOAT, false ], [ 3, WebGLRenderingContext.FLOAT, false ], [ 4, WebGLRenderingContext.FLOAT, false ], [ 4, WebGLRenderingContext.BYTE, false ], [ 4, WebGLRenderingContext.BYTE, true ], [ 4, WebGLRenderingContext.UNSIGNED_BYTE, false ], [ 4, WebGLRenderingContext.UNSIGNED_BYTE, true ], [ 2, WebGLRenderingContext.SHORT, false ], [ 2, WebGLRenderingContext.SHORT, true ], [ 4, WebGLRenderingContext.SHORT, false ], [ 4, WebGLRenderingContext.SHORT, true ] ]; const cubeFaceMap = [ WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X, WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X, WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_Y, WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_Y, WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_Z, WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_Z, ]; /** * Altai's main interface for resource creation and rendering. */ export class Gfx { private gl: WebGL2RenderingContext | WebGLRenderingContext; private webgl2: boolean = false; private cache: PipelineState; private curProgram: WebGLProgram; private curIndexFormat: GLenum; private curIndexSize: number = 0; private curPrimType: PrimitiveType; /** * Create the Altai interface object. * * @param {GfxOptions} options - WebGL context and HTML canvas intialization options */ constructor(options: GfxOptions) { const glContextAttrs = { alpha: some(options.Alpha, true), depth: some(options.Depth, true), stencil: some(options.Stencil, false), antialias: some(options.AntiAlias, true), premultipliedAlpha: some(options.PreMultipliedAlpha, true), preserveDrawingBuffer: some(options.PreserveDrawingBuffer, false), preferLowPowerToHighPerformance: some(options.PreferLowPowerToHighPerformance, false), failIfMajorPerformanceCaveat: some(options.FailIfMajorPerformanceCaveat, false) }; const canvas = document.getElementById(some(options.Canvas, "canvas")) as HTMLCanvasElement; if (options.Width != null) { canvas.width = options.Width; } if (options.Height != null) { canvas.height = options.Height; } if (some(options.UseWebGL2, false)) { this.gl = (canvas.getContext("webgl2", glContextAttrs) || canvas.getContext("webgl2-experimental", glContextAttrs)) as WebGL2RenderingContext; if (this.gl != null) { this.webgl2 = true; console.log("altai: using webgl2"); } } if (this.gl == null) { this.gl = (canvas.getContext("webgl", glContextAttrs) || canvas.getContext("experimental-webgl", glContextAttrs)) as WebGLRenderingContext; console.log("altai: using webgl1"); } this.gl.viewport(0, 0, canvas.width, canvas.height); this.gl.enable(this.gl.DEPTH_TEST); // FIXME: HighDPI handling // apply default state this.cache = new PipelineState({ VertexLayouts: [], Shader: null }); this.applyState(this.cache, true); } /** * Create a new Pass object. * * @param {PassOptions} options - Pass creation options */ public makePass(options: PassOptions): Pass { // special handling for default pass if (null == options.ColorAttachments[0].Texture) { return new Pass(options, null, null); } // an offscreen pass, need to create a framebuffer with color- and depth attachments const gl = this.gl; const gl2 = this.gl as WebGL2RenderingContext; const isMSAA = options.ColorAttachments[0].Texture.sampleCount > 1; const glFb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, glFb); if (isMSAA) { // MSAA offscreen rendering, attach the MSAA renderbuffers from texture objects for (let i = 0; i < options.ColorAttachments.length; i++) { const glMsaaFb = options.ColorAttachments[i].Texture.glMSAARenderBuffer; gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, glMsaaFb); } } else { // non-MSAA rendering, attach texture objects for (let i = 0; i < options.ColorAttachments.length; i++) { const att = options.ColorAttachments[i]; const tex = att.Texture; switch (tex.type) { case TextureType.Texture2D: gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, tex.glTexture, att.MipLevel); break; case TextureType.TextureCube: gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, cubeFaceMap[att.Slice], tex.glTexture, att.MipLevel); break; default: // 3D and 2D-array textures gl2.framebufferTextureLayer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, tex.glTexture, att.MipLevel, att.Slice); break; } } } // attach optional depth-stencil buffer to framebuffer if (options.DepthAttachment.Texture) { const glDSRenderBuffer = options.DepthAttachment.Texture.glDepthRenderBuffer; gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, glDSRenderBuffer); if (options.DepthAttachment.Texture.depthFormat === DepthStencilFormat.DEPTHSTENCIL) { gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, glDSRenderBuffer); } } if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) { console.warn('altai.makePass(): framebuffer completeness check failed!'); } // for MSAA, create resolve-framebuffers const glMsaaFbs = []; if (isMSAA) { for (let i = 0; i < options.ColorAttachments.length; i++) { glMsaaFbs[i] = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, glMsaaFbs[i]); const att = options.ColorAttachments[i]; const glTex = att.Texture.glTexture; switch (att.Texture.type) { case TextureType.Texture2D: gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glTex, att.MipLevel); break; case TextureType.TextureCube: gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, cubeFaceMap[att.Slice], glTex, att.MipLevel); break; default: gl2.framebufferTextureLayer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTex, att.MipLevel, att.Slice); break; } if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) { console.warn('altai.makePass(): framebuffer completeness check failed (for MSAA resolve buffers)'); } } } return new Pass(options, glFb, glMsaaFbs); } /** * Create a new Buffer object. * * @param {BufferOptions} options - Buffer creation options */ public makeBuffer(options: BufferOptions): Buffer { const gl: WebGLRenderingContext = this.gl; const buf = new Buffer(options, gl.createBuffer()); gl.bindBuffer(buf.type, buf.glBuffer); if (options.Data) { gl.bufferData(buf.type, options.Data as ArrayBuffer, buf.usage); } else if (options.LengthInBytes) { gl.bufferData(buf.type, options.LengthInBytes, buf.usage); } return buf; } private asGLTexImgFormat(p: PixelFormat): number { const gl = this.gl; switch (p) { case PixelFormat.RGBA8: case PixelFormat.RGBA4: case PixelFormat.RGB5_A1: case PixelFormat.RGB10_A2: case PixelFormat.RGBA32F: case PixelFormat.RGBA16F: return gl.RGBA; case PixelFormat.RGB8: case PixelFormat.RGB565: return gl.RGB; case PixelFormat.R32F: case PixelFormat.R16F: return gl.LUMINANCE; default: return 0; } } private asGLDepthTexImgFormat(d: DepthStencilFormat): number { switch (d) { case DepthStencilFormat.DEPTH: return this.gl.DEPTH_COMPONENT16; case DepthStencilFormat.DEPTHSTENCIL: return this.gl.DEPTH_STENCIL; default: return 0; } } private asGLTexImgType(p: PixelFormat): number { const gl = this.gl; switch (p) { case PixelFormat.RGBA32F: case PixelFormat.R32F: return gl.FLOAT; case PixelFormat.RGBA16F: case PixelFormat.R16F: return WebGL2RenderingContext.HALF_FLOAT; case PixelFormat.RGBA8: case PixelFormat.RGB8: return gl.UNSIGNED_BYTE; case PixelFormat.RGB5_A1: return gl.UNSIGNED_SHORT_5_5_5_1; case PixelFormat.RGB565: return gl.UNSIGNED_SHORT_5_6_5; case PixelFormat.RGBA4: return gl.UNSIGNED_SHORT_4_4_4_4; } } /** * Create a new Texture object * * @param {TextureOptions} options - Texture creation options */ public makeTexture(options: TextureOptions): Texture { const gl = this.gl; const tex = new Texture(options, gl); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(tex.type, tex.glTexture); gl.texParameteri(tex.type, gl.TEXTURE_MIN_FILTER, tex.minFilter); gl.texParameteri(tex.type, gl.TEXTURE_MAG_FILTER, tex.magFilter); gl.texParameteri(tex.type, gl.TEXTURE_WRAP_S, tex.wrapU); gl.texParameteri(tex.type, gl.TEXTURE_WRAP_T, tex.wrapV); if (tex.type === WebGL2RenderingContext.TEXTURE_3D) { gl.texParameteri(tex.type, WebGL2RenderingContext.TEXTURE_WRAP_R, tex.wrapW); } const numFaces = tex.type === TextureType.TextureCube ? 6 : 1; const imgFmt = this.asGLTexImgFormat(tex.colorFormat); const imgType = this.asGLTexImgType(tex.colorFormat); for (let faceIndex = 0; faceIndex < numFaces; faceIndex++) { const imgTgt = tex.type === TextureType.TextureCube ? cubeFaceMap[faceIndex] : tex.type; for (let mipIndex = 0; mipIndex < tex.numMipMaps; mipIndex++) { // FIXME: data! let mipWidth = tex.width >> mipIndex; if (mipWidth === 0) { mipWidth = 1; } let mipHeight = tex.height >> mipIndex; if (mipHeight === 0) { mipHeight = 1; } if ((TextureType.Texture2D === tex.type) || (TextureType.TextureCube === tex.type)) { // FIXME: compressed formats + data gl.texImage2D(imgTgt, mipIndex, imgFmt, mipWidth, mipHeight, 0, imgFmt, imgType, null); } } } // MSAA render buffer? const isMSAA = tex.sampleCount > 1; if (isMSAA) { const gl2 = gl as WebGL2RenderingContext; gl2.bindRenderbuffer(gl.RENDERBUFFER, tex.glMSAARenderBuffer); gl2.renderbufferStorageMultisample(gl.RENDERBUFFER, tex.sampleCount, imgFmt, tex.width, tex.height); } // depth render buffer? if (tex.depthFormat != DepthStencilFormat.NONE) { const depthFmt = this.asGLDepthTexImgFormat(tex.depthFormat); gl.bindRenderbuffer(gl.RENDERBUFFER, tex.glDepthRenderBuffer); if (isMSAA) { const gl2 = gl as WebGL2RenderingContext; gl2.renderbufferStorageMultisample(gl.RENDERBUFFER, tex.sampleCount, depthFmt, tex.width, tex.height); } else { gl.renderbufferStorage(gl.RENDERBUFFER, depthFmt, tex.width, tex.height); } } return tex; } /** * Create a new Shader object. * * @param {ShaderOptions} options - Shader creation options */ public makeShader(options: ShaderOptions): Shader { const gl = this.gl; const vs = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vs, options.VertexShader); gl.compileShader(vs); if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) { console.error("Failed to compile vertex shader:\n" + gl.getShaderInfoLog(vs)); } const fs = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fs, options.FragmentShader); gl.compileShader(fs); if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) { console.error("Failed to compile fragment shader:\n" + gl.getShaderInfoLog(fs)); } const prog = gl.createProgram(); gl.attachShader(prog, vs); gl.attachShader(prog, fs); gl.linkProgram(prog); if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) { console.error("Failed to link shader program!"); } const shd = new Shader(prog); gl.deleteShader(vs); gl.deleteShader(fs); return shd; } /** * Create a new Pipeline object. * * @param {PipelineOptions} options - Pipeline creation options */ public makePipeline(options: PipelineOptions): Pipeline { const gl = this.gl; const pip = new Pipeline(options); // resolve vertex attributes for (let layoutIndex = 0; layoutIndex < pip.vertexLayouts.length; layoutIndex++) { const layout = pip.vertexLayouts[layoutIndex]; const layoutByteSize = layout.byteSize(); for (let compIndex = 0; compIndex < layout.components.length; compIndex++) { const comp = layout.components[compIndex]; const attrName = comp[0]; const attrFormat = comp[1]; const attrIndex = gl.getAttribLocation(pip.shader.glProgram, attrName); if (attrIndex != -1) { const attrib = pip.glAttribs[attrIndex]; attrib.enabled = true; attrib.vbIndex = layoutIndex; attrib.divisor = layout.stepFunc == StepFunc.PerVertex ? 0 : layout.stepRate; attrib.stride = layoutByteSize; attrib.offset = layout.componentByteOffset(compIndex); attrib.size = vertexFormatMap[attrFormat][0] as number; attrib.type = vertexFormatMap[attrFormat][1] as number; attrib.normalized = vertexFormatMap[attrFormat][2] as boolean; } else { console.warn("Attribute '", attrName, "' not found in shader!"); } } } return pip; } /** * Create a new DrawState object. * * @param {DrawStateOptions} options - DrawState creation options */ public makeDrawState(options: DrawStateOptions): DrawState { return new DrawState(options); } /** * Begin a render-pass. * * @param {Pass} pass - a Pass object which describes what happens at the start and end of the render pass */ public beginPass(pass: Pass) { const gl = this.gl; const gl2 = this.gl as WebGL2RenderingContext; const isDefaultPass: boolean = !pass.ColorAttachments[0].texture; const width = isDefaultPass ? gl.canvas.width : pass.ColorAttachments[0].texture.width; const height = isDefaultPass ? gl.canvas.height : pass.ColorAttachments[0].texture.height; if (isDefaultPass) { gl.bindFramebuffer(gl.FRAMEBUFFER, null); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, pass.glFramebuffer); if (this.webgl2) { const drawBuffers: number[] = []; for (let i = 0; i < pass.ColorAttachments.length; i++) { if (pass.ColorAttachments[i].texture) { drawBuffers[i] = gl.COLOR_ATTACHMENT0 + i; } } gl2.drawBuffers(drawBuffers); } } // prepare clear operations gl.viewport(0, 0, width, height); gl.disable(WebGLRenderingContext.SCISSOR_TEST); gl.colorMask(true, true, true, true); gl.depthMask(true); gl.stencilMask(0xFF); // update cache this.cache.scissorTestEnabled = false; this.cache.colorWriteMask[0] = true; this.cache.colorWriteMask[1] = true; this.cache.colorWriteMask[2] = true; this.cache.colorWriteMask[3] = true; this.cache.depthWriteEnabled = true; this.cache.frontStencilWriteMask = 0xFF; this.cache.backStencilWriteMask = 0xFF; if (isDefaultPass || !this.webgl2) { let clearMask = 0; const col = pass.ColorAttachments[0]; const dep = pass.DepthAttachment; if (col.loadAction === LoadAction.Clear) { clearMask |= WebGLRenderingContext.COLOR_BUFFER_BIT; gl.clearColor(col.clearColor[0], col.clearColor[1], col.clearColor[2], col.clearColor[3]); } if (dep.loadAction === LoadAction.Clear) { clearMask |= WebGLRenderingContext.DEPTH_BUFFER_BIT | WebGLRenderingContext.STENCIL_BUFFER_BIT; gl.clearDepth(dep.clearDepth); gl.clearStencil(dep.clearStencil); } if (0 !== clearMask) { gl.clear(clearMask); } } else { // offscreen WebGL2 (could be MRT) for (let i = 0; i < pass.ColorAttachments.length; i++) { const col = pass.ColorAttachments[i]; if (col.texture && (LoadAction.Clear == col.loadAction)) { gl2.clearBufferfv(gl2.COLOR, i, col.clearColor); } } const dep = pass.DepthAttachment; if (LoadAction.Clear === dep.loadAction) { gl2.clearBufferfi(gl2.DEPTH_STENCIL, 0, dep.clearDepth, dep.clearStencil); } } } /** * Finish current render-pass. */ public endPass() { // FIXME: perform MSAA resolve } /** * Apply a new viewport area. * * @param {number} x - horizontal pixel position of viewport area * @param {number} y - vertical pixel position of viewport area * @param {number} width - width in pixels of viewport area * @param {number} height - height in pixels of viewport area */ public applyViewPort(x: number, y: number, width: number, height: number) { this.gl.viewport(x, y, width, height); } /** * Apply new scissor rectangle. * * @param {number} x - horizontal pixel position of scissor rect * @param {number} y - vertical pixel position of scissor rect * @param {number} width - width in pixels of viewport area * @param {number} height - height in pixels of viewport area */ public applyScissorRect(x: number, y: number, width: number, height: number) { this.gl.scissor(x, y, width, height); } /** * Apply new resource bindings. * * @param {DrawState} drawState - a DrawState object with the new resource bindings */ public applyDrawState(drawState: DrawState) { const gl = this.gl; // some validity checks if ((drawState.IndexBuffer != null) && (drawState.Pipeline.indexFormat === IndexFormat.None)) { console.warn("altai.applyDrawState(): index buffer bound but pipeline.indexFormat is none!"); } if ((drawState.IndexBuffer == null) && (drawState.Pipeline.indexFormat !== IndexFormat.None)) { console.warn("altai.applyDrawState(): pipeline.indexFormat is not none, but no index buffer bound!"); } this.curPrimType = drawState.Pipeline.primitiveType; // update render state this.applyState(drawState.Pipeline.state, false); // apply shader program if (this.curProgram !== drawState.Pipeline.shader.glProgram) { this.curProgram = drawState.Pipeline.shader.glProgram; gl.useProgram(this.curProgram); } // apply index and vertex data this.curIndexFormat = drawState.Pipeline.indexFormat; this.curIndexSize = drawState.Pipeline.indexSize; if (drawState.IndexBuffer != null) { gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, drawState.IndexBuffer.glBuffer); } else { gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); } let curVB: WebGLBuffer = null; for (let attrIndex = 0; attrIndex < MaxNumVertexAttribs; attrIndex++) { const attrib = drawState.Pipeline.glAttribs[attrIndex]; // FIXME: implement a state cache for vertex attrib bindings if (attrib.enabled) { if (drawState.VertexBuffers[attrib.vbIndex].glBuffer !== curVB) { curVB = drawState.VertexBuffers[attrib.vbIndex].glBuffer; gl.bindBuffer(gl.ARRAY_BUFFER, curVB); } gl.vertexAttribPointer(attrIndex, attrib.size, attrib.type, attrib.normalized, attrib.stride, attrib.offset); gl.enableVertexAttribArray(attrIndex); // FIMXE: WebGL2 vertex attrib divisor! } else { gl.disableVertexAttribArray(attrIndex); } } // apply texture uniforms let texSlot = 0; for (const key in drawState.Textures) { const tex = drawState.Textures[key]; const loc = gl.getUniformLocation(this.curProgram, key); gl.activeTexture(gl.TEXTURE0+texSlot); gl.bindTexture(tex.type, tex.glTexture); gl.uniform1i(loc, texSlot); texSlot++; } } /** * Apply shader uniforms by name and value. Only the following * types are allowed: float, vec2, vec3, vec4, mat4. Textures * are applied via applyDrawState. * * @param uniforms - uniform name/value pairs */ applyUniforms(uniforms: {[key: string]: number[] | number}) { let gl: WebGLRenderingContext = this.gl; for (let key in uniforms) { const val = uniforms[key]; const loc = gl.getUniformLocation(this.curProgram, key); if (loc !== null) { if (typeof val === "number") { gl.uniform1f(loc, val); } else { switch (val.length) { case 1: gl.uniform1fv(loc, val); break; case 2: gl.uniform2fv(loc, val); break; case 3: gl.uniform3fv(loc, val); break; case 4: gl.uniform4fv(loc, val); break; case 16: gl.uniformMatrix4fv(loc, false, val); break; default: console.warn('altai.applyUniforms: invalid parameter type!'); } } } } } /** * Draw primitive range with current draw settings. * * @param {number} baseElement - index of first vertex or index * @param {number} numElements - number of vertices or indices * @param {number} numInstances - number of instances (default: 1) */ draw(baseElement: number, numElements: number, numInstances: number = 1) { if (IndexFormat.None == this.curIndexFormat) { // non-indexed rendering if (1 == numInstances) { this.gl.drawArrays(this.curPrimType, baseElement, numElements); } else { // FIXME: instanced rendering! } } else { // indexed rendering let indexOffset = baseElement * this.curIndexSize; if (1 == numInstances) { this.gl.drawElements(this.curPrimType, numElements, this.curIndexFormat, indexOffset); } else { // FIXME: instanced rendering! } } } /** * Finish current frame, pass function pointer of next frame's draw function. * * @param {() => void} drawFunc - the next frame's draw function */ commitFrame(drawFunc: () => void) { requestAnimationFrame(drawFunc); } private applyState(state: PipelineState, force: boolean) { let gl = this.gl; // apply depth-stencil state changes if (force || (this.cache.depthCmpFunc != state.depthCmpFunc)) { this.cache.depthCmpFunc = state.depthCmpFunc; gl.depthFunc(state.depthCmpFunc); } if (force || (this.cache.depthWriteEnabled != state.depthWriteEnabled)) { this.cache.depthWriteEnabled = state.depthWriteEnabled; gl.depthMask(state.depthWriteEnabled); } if (force || (this.cache.stencilEnabled != state.stencilEnabled)) { this.cache.stencilEnabled = state.stencilEnabled; if (state.stencilEnabled) gl.enable(gl.STENCIL_TEST); else gl.disable(gl.STENCIL_TEST); } let sCmpFunc = state.frontStencilCmpFunc; let sReadMask = state.frontStencilReadMask; let sRef = state.frontStencilRef; if (force || (this.cache.frontStencilCmpFunc != sCmpFunc) || (this.cache.frontStencilReadMask != sReadMask) || (this.cache.frontStencilRef != sRef)) { this.cache.frontStencilCmpFunc = sCmpFunc; this.cache.frontStencilReadMask = sReadMask; this.cache.frontStencilRef = sRef; gl.stencilFuncSeparate(gl.FRONT, sCmpFunc, sRef, sReadMask); } sCmpFunc = state.backStencilCmpFunc; sReadMask = state.backStencilReadMask; sRef = state.backStencilRef; if (force || (this.cache.backStencilCmpFunc != sCmpFunc) || (this.cache.backStencilReadMask != sReadMask) || (this.cache.backStencilRef != sRef)) { this.cache.backStencilCmpFunc = sCmpFunc; this.cache.backStencilReadMask = sReadMask; this.cache.backStencilRef = sRef; gl.stencilFuncSeparate(gl.BACK, sCmpFunc, sRef, sReadMask); } let sFailOp = state.frontStencilFailOp; let sDepthFailOp = state.frontStencilDepthFailOp; let sPassOp = state.frontStencilPassOp; if (force || (this.cache.frontStencilFailOp != sFailOp) || (this.cache.frontStencilDepthFailOp != sDepthFailOp) || (this.cache.frontStencilPassOp != sPassOp)) { this.cache.frontStencilFailOp = sFailOp; this.cache.frontStencilDepthFailOp = sDepthFailOp; this.cache.frontStencilPassOp = sPassOp; gl.stencilOpSeparate(gl.FRONT, sFailOp, sDepthFailOp, sPassOp); } sFailOp = state.backStencilFailOp; sDepthFailOp = state.backStencilDepthFailOp; sPassOp = state.backStencilPassOp; if (force || (this.cache.backStencilFailOp != sFailOp) || (this.cache.backStencilDepthFailOp != sDepthFailOp) || (this.cache.backStencilPassOp != sPassOp)) { this.cache.backStencilFailOp = sFailOp; this.cache.backStencilDepthFailOp = sDepthFailOp; this.cache.backStencilPassOp = sPassOp; gl.stencilOpSeparate(gl.BACK, sFailOp, sDepthFailOp, sPassOp); } if (force || (this.cache.frontStencilWriteMask != state.frontStencilWriteMask)) { this.cache.frontStencilWriteMask = state.frontStencilWriteMask; gl.stencilMaskSeparate(gl.FRONT, state.frontStencilWriteMask) } if (force || (this.cache.backStencilWriteMask != state.backStencilWriteMask)) { this.cache.backStencilWriteMask = state.backStencilWriteMask; gl.stencilMaskSeparate(gl.BACK, state.backStencilWriteMask); } // apply blend state changes if (force || (this.cache.blendEnabled != state.blendEnabled)) { this.cache.blendEnabled = state.blendEnabled; gl.enable(gl.BLEND); } if (force || (this.cache.blendSrcFactorRGB != state.blendSrcFactorRGB) || (this.cache.blendDstFactorRGB != state.blendDstFactorRGB) || (this.cache.blendSrcFactorAlpha != state.blendSrcFactorAlpha) || (this.cache.blendDstFactorAlpha != state.blendDstFactorAlpha)) { this.cache.blendSrcFactorRGB = state.blendSrcFactorRGB; this.cache.blendDstFactorRGB = state.blendDstFactorRGB; this.cache.blendSrcFactorAlpha = state.blendSrcFactorAlpha; this.cache.blendDstFactorAlpha = state.blendDstFactorAlpha; gl.blendFuncSeparate(state.blendSrcFactorRGB, state.blendDstFactorRGB, state.blendSrcFactorAlpha, state.blendDstFactorAlpha); } if (force || (this.cache.blendOpRGB != state.blendOpRGB) || (this.cache.blendOpAlpha != state.blendOpAlpha)) { this.cache.blendOpRGB = state.blendOpRGB; this.cache.blendOpAlpha = state.blendOpAlpha; gl.blendEquationSeparate(state.blendOpRGB, state.blendOpAlpha); } if (force || (this.cache.colorWriteMask[0] != state.colorWriteMask[0]) || (this.cache.colorWriteMask[1] != state.colorWriteMask[1]) || (this.cache.colorWriteMask[2] != state.colorWriteMask[2]) || (this.cache.colorWriteMask[3] != state.colorWriteMask[3])) { this.cache.colorWriteMask[0] = state.colorWriteMask[0]; this.cache.colorWriteMask[1] = state.colorWriteMask[1]; this.cache.colorWriteMask[2] = state.colorWriteMask[2]; this.cache.colorWriteMask[3] = state.colorWriteMask[3]; gl.colorMask(state.colorWriteMask[0], state.colorWriteMask[1], state.colorWriteMask[2], state.colorWriteMask[3]); } if (force || (this.cache.blendColor[0] != state.blendColor[0]) || (this.cache.blendColor[1] != state.blendColor[1]) || (this.cache.blendColor[2] != state.blendColor[2]) || (this.cache.blendColor[3] != state.blendColor[3])) { this.cache.blendColor[0] = state.blendColor[0]; this.cache.blendColor[1] = state.blendColor[1]; this.cache.blendColor[2] = state.blendColor[2]; this.cache.blendColor[3] = state.blendColor[3]; gl.blendColor(state.blendColor[0], state.blendColor[1], state.blendColor[2], state.blendColor[3]); } // apply rasterizer state if (force || (this.cache.cullFaceEnabled != state.cullFaceEnabled)) { this.cache.cullFaceEnabled = state.cullFaceEnabled; if (state.cullFaceEnabled) gl.enable(gl.CULL_FACE); else gl.disable(gl.CULL_FACE); } if (force || (this.cache.cullFace != state.cullFace)) { this.cache.cullFace = state.cullFace; gl.cullFace(state.cullFace); } if (force || (this.cache.scissorTestEnabled != state.scissorTestEnabled)) { this.cache.scissorTestEnabled = state.scissorTestEnabled; if (state.scissorTestEnabled) gl.enable(gl.SCISSOR_TEST); else gl.disable(gl.SCISSOR_TEST); } } } }
the_stack
import { TestBed, fakeAsync, tick, waitForAsync } from '@angular/core/testing'; import { SortingDirection } from '../../data-operations/sorting-expression.interface'; import { IgxTreeGridComponent } from './tree-grid.component'; import { IgxTreeGridModule } from './public_api'; import { IgxTreeGridSortingComponent } from '../../test-utils/tree-grid-components.spec'; import { TreeGridFunctions } from '../../test-utils/tree-grid-functions.spec'; import { configureTestSuite } from '../../test-utils/configure-suite'; import { DefaultSortingStrategy } from '../../data-operations/sorting-strategy'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { GridFunctions } from '../../test-utils/grid-functions.spec'; describe('IgxTreeGrid - Sorting #tGrid', () => { configureTestSuite(); let fix; let treeGrid: IgxTreeGridComponent; beforeAll(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ IgxTreeGridSortingComponent ], imports: [IgxTreeGridModule, NoopAnimationsModule] }) .compileComponents(); })); beforeEach(fakeAsync(/** height/width setter rAF */() => { fix = TestBed.createComponent(IgxTreeGridSortingComponent); fix.detectChanges(); tick(16); treeGrid = fix.componentInstance.treeGrid; })); describe('API sorting', () => { it('should sort descending all treeGrid levels by column name through API', () => { treeGrid.sort({ fieldName: 'Name', dir: SortingDirection.Desc, ignoreCase: false, strategy: DefaultSortingStrategy.instance() }); fix.detectChanges(); // Verify first level records are desc sorted expect(treeGrid.getCellByColumn(0, 'Name').value).toEqual('Yang Wang'); expect(treeGrid.getCellByColumn(1, 'Name').value).toEqual('John Winchester'); expect(treeGrid.getCellByColumn(8, 'Name').value).toEqual('Ana Sanders'); // Verify second level records are desc sorted expect(treeGrid.getCellByColumn(2, 'Name').value).toEqual('Thomas Hardy'); expect(treeGrid.getCellByColumn(3, 'Name').value).toEqual('Monica Reyes'); expect(treeGrid.getCellByColumn(7, 'Name').value).toEqual('Michael Langdon'); // Verify third level records are desc sorted expect(treeGrid.getCellByColumn(4, 'Name').value).toEqual('Sven Ottlieb'); expect(treeGrid.getCellByColumn(5, 'Name').value).toEqual('Roland Mendel'); expect(treeGrid.getCellByColumn(6, 'Name').value).toEqual('Peter Lewis'); }); it('should sort ascending all treeGrid levels by column name through API', () => { treeGrid.sort({ fieldName: 'Age', dir: SortingDirection.Asc, ignoreCase: false }); fix.detectChanges(); // Verify first level records are asc sorted expect(treeGrid.getCellByColumn(0, 'Age').value).toEqual(42); expect(treeGrid.getCellByColumn(2, 'Age').value).toEqual(55); expect(treeGrid.getCellByColumn(9, 'Age').value).toEqual(61); // Verify second level records are asc sorted expect(treeGrid.getCellByColumn(3, 'Age').value).toEqual(29); expect(treeGrid.getCellByColumn(4, 'Age').value).toEqual(30); expect(treeGrid.getCellByColumn(5, 'Age').value).toEqual(31); // Verify third level records are asc sorted expect(treeGrid.getCellByColumn(6, 'Age').value).toEqual(25); expect(treeGrid.getCellByColumn(7, 'Age').value).toEqual(35); expect(treeGrid.getCellByColumn(8, 'Age').value).toEqual(44); }); it('should not sort treeGrid when trying to sort by invalid column through API', () => { treeGrid.sort({ fieldName: 'TEST', dir: SortingDirection.Desc, ignoreCase: false, strategy: DefaultSortingStrategy.instance() }); fix.detectChanges(); // Verify first level records with default order expect(treeGrid.getCellByColumn(0, 'Name').value).toEqual('John Winchester'); expect(treeGrid.getCellByColumn(7, 'Name').value).toEqual('Yang Wang'); expect(treeGrid.getCellByColumn(8, 'Name').value).toEqual('Ana Sanders'); // Verify second level records with default order expect(treeGrid.getCellByColumn(1, 'Name').value).toEqual('Michael Langdon'); expect(treeGrid.getCellByColumn(2, 'Name').value).toEqual('Thomas Hardy'); expect(treeGrid.getCellByColumn(3, 'Name').value).toEqual('Monica Reyes'); // Verify third level records with default order expect(treeGrid.getCellByColumn(4, 'Name').value).toEqual('Roland Mendel'); expect(treeGrid.getCellByColumn(5, 'Name').value).toEqual('Sven Ottlieb'); expect(treeGrid.getCellByColumn(6, 'Name').value).toEqual('Peter Lewis'); }); it('should clear sorting of treeGrid through API', () => { // Verify first record of all 3 levels (default layout) expect(treeGrid.getCellByColumn(0, 'Age').value).toEqual(55); expect(treeGrid.getCellByColumn(1, 'Age').value).toEqual(30); expect(treeGrid.getCellByColumn(4, 'Age').value).toEqual(35); treeGrid.sort({ fieldName: 'Age', dir: SortingDirection.Asc, ignoreCase: false }); fix.detectChanges(); // Verify first record of all 3 levels (sorted layout) expect(treeGrid.getCellByColumn(0, 'Age').value).toEqual(42); expect(treeGrid.getCellByColumn(3, 'Age').value).toEqual(29); expect(treeGrid.getCellByColumn(6, 'Age').value).toEqual(25); treeGrid.clearSort(); fix.detectChanges(); // Verify first record of all 3 levels (default layout) expect(treeGrid.getCellByColumn(0, 'Age').value).toEqual(55); expect(treeGrid.getCellByColumn(1, 'Age').value).toEqual(30); expect(treeGrid.getCellByColumn(4, 'Age').value).toEqual(35); }); it('should sort treeGrid by multiple expressions through API', () => { pending('figure out how was this passing before'); // Test prerequisites (need to have multiple records with the same name on every level) treeGrid.data[0].Name = 'Ana Sanders'; treeGrid.data[0].Employees[1].Name = 'Michael Langdon'; treeGrid.data[0].Employees[2].Employees[0].Name = 'Peter Lewis'; fix.detectChanges(); const exprs = [ { fieldName: 'Name', dir: SortingDirection.Asc, ignoreCase: true }, { fieldName: 'Age', dir: SortingDirection.Desc, ignoreCase: true } ]; treeGrid.sort(exprs); fix.detectChanges(); expect(treeGrid.sortingExpressions.length).toBe(2); // Verify first level multiple expressions sorting expect(treeGrid.getCellByColumn(0, 'Name').value).toEqual('Ana Sanders'); expect(treeGrid.getCellByColumn(0, 'Age').value).toEqual(55); expect(treeGrid.getCellByColumn(7, 'Name').value).toEqual('Ana Sanders'); expect(treeGrid.getCellByColumn(7, 'Age').value).toEqual(42); expect(treeGrid.getCellByColumn(9, 'Name').value).toEqual('Yang Wang'); expect(treeGrid.getCellByColumn(9, 'Age').value).toEqual(61); // Verify second level multiple expressions sorting expect(treeGrid.getCellByColumn(1, 'Name').value).toEqual('Michael Langdon'); expect(treeGrid.getCellByColumn(1, 'Age').value).toEqual(30); expect(treeGrid.getCellByColumn(2, 'Name').value).toEqual('Michael Langdon'); expect(treeGrid.getCellByColumn(2, 'Age').value).toEqual(29); expect(treeGrid.getCellByColumn(3, 'Name').value).toEqual('Monica Reyes'); expect(treeGrid.getCellByColumn(3, 'Age').value).toEqual(31); // Verify third level multiple expressions sorting expect(treeGrid.getCellByColumn(4, 'Name').value).toEqual('Peter Lewis'); expect(treeGrid.getCellByColumn(4, 'Age').value).toEqual(35); expect(treeGrid.getCellByColumn(5, 'Name').value).toEqual('Peter Lewis'); expect(treeGrid.getCellByColumn(5, 'Age').value).toEqual(25); expect(treeGrid.getCellByColumn(6, 'Name').value).toEqual('Sven Ottlieb'); expect(treeGrid.getCellByColumn(6, 'Age').value).toEqual(44); }); it('should clear sorting of treeGrid for one column only through API', () => { // Test prerequisites (need to have multiple records with the same name on every level) treeGrid.getCellByColumn(0, 'Name').value = 'Ana Sanders'; treeGrid.getCellByColumn(2, 'Name').value = 'Michael Langdon'; treeGrid.getCellByColumn(4, 'Name').value = 'Peter Lewis'; fix.detectChanges(); const exprs = [ { fieldName: 'Name', dir: SortingDirection.Asc, ignoreCase: true }, { fieldName: 'Age', dir: SortingDirection.Desc, ignoreCase: true } ]; treeGrid.sort(exprs); fix.detectChanges(); treeGrid.clearSort('Name'); fix.detectChanges(); expect(treeGrid.sortingExpressions.length).toBe(1); // Verify first level single expression sorting expect(treeGrid.getCellByColumn(0, 'Age').value).toEqual(61); expect(treeGrid.getCellByColumn(1, 'Age').value).toEqual(55); expect(treeGrid.getCellByColumn(8, 'Age').value).toEqual(42); // Verify second level single expression sorting expect(treeGrid.getCellByColumn(2, 'Age').value).toEqual(31); expect(treeGrid.getCellByColumn(6, 'Age').value).toEqual(30); expect(treeGrid.getCellByColumn(7, 'Age').value).toEqual(29); // Verify third level single expression sorting expect(treeGrid.getCellByColumn(3, 'Age').value).toEqual(44); expect(treeGrid.getCellByColumn(4, 'Age').value).toEqual(35); expect(treeGrid.getCellByColumn(5, 'Age').value).toEqual(25); }); }); describe('UI sorting', () => { it('should sort descending all treeGrid levels by column name through UI', () => { const header = TreeGridFunctions.getHeaderCell(fix, 'Name'); GridFunctions.clickHeaderSortIcon(header); GridFunctions.clickHeaderSortIcon(header); fix.detectChanges(); // Verify first level records are desc sorted expect(treeGrid.getCellByColumn(0, 'Name').value).toEqual('Yang Wang'); expect(treeGrid.getCellByColumn(1, 'Name').value).toEqual('John Winchester'); expect(treeGrid.getCellByColumn(8, 'Name').value).toEqual('Ana Sanders'); // Verify second level records are desc sorted expect(treeGrid.getCellByColumn(2, 'Name').value).toEqual('Thomas Hardy'); expect(treeGrid.getCellByColumn(3, 'Name').value).toEqual('Monica Reyes'); expect(treeGrid.getCellByColumn(7, 'Name').value).toEqual('Michael Langdon'); // Verify third level records are desc sorted expect(treeGrid.getCellByColumn(4, 'Name').value).toEqual('Sven Ottlieb'); expect(treeGrid.getCellByColumn(5, 'Name').value).toEqual('Roland Mendel'); expect(treeGrid.getCellByColumn(6, 'Name').value).toEqual('Peter Lewis'); }); it('should sort ascending all treeGrid levels by column name through UI', () => { const header = TreeGridFunctions.getHeaderCell(fix, 'Age'); GridFunctions.clickHeaderSortIcon(header); fix.detectChanges(); // Verify first level records are asc sorted expect(treeGrid.getCellByColumn(0, 'Age').value).toEqual(42); expect(treeGrid.getCellByColumn(2, 'Age').value).toEqual(55); expect(treeGrid.getCellByColumn(9, 'Age').value).toEqual(61); // Verify second level records are asc sorted expect(treeGrid.getCellByColumn(3, 'Age').value).toEqual(29); expect(treeGrid.getCellByColumn(4, 'Age').value).toEqual(30); expect(treeGrid.getCellByColumn(5, 'Age').value).toEqual(31); // Verify third level records are asc sorted expect(treeGrid.getCellByColumn(6, 'Age').value).toEqual(25); expect(treeGrid.getCellByColumn(7, 'Age').value).toEqual(35); expect(treeGrid.getCellByColumn(8, 'Age').value).toEqual(44); }); it('should clear sorting of treeGrid when header cell is clicked 3 times through UI', () => { // Verify first record of all 3 levels (default layout) expect(treeGrid.getCellByColumn(0, 'Age').value).toEqual(55); expect(treeGrid.getCellByColumn(1, 'Age').value).toEqual(30); expect(treeGrid.getCellByColumn(4, 'Age').value).toEqual(35); // Click header once const header = TreeGridFunctions.getHeaderCell(fix, 'Age'); GridFunctions.clickHeaderSortIcon(header); fix.detectChanges(); // Verify first record of all 3 levels (sorted layout) expect(treeGrid.getCellByColumn(0, 'Age').value).toEqual(42); expect(treeGrid.getCellByColumn(3, 'Age').value).toEqual(29); expect(treeGrid.getCellByColumn(6, 'Age').value).toEqual(25); // Click header two more times GridFunctions.clickHeaderSortIcon(header); fix.detectChanges(); GridFunctions.clickHeaderSortIcon(header); fix.detectChanges(); // Verify first record of all 3 levels (default layout) expect(treeGrid.getCellByColumn(0, 'Age').value).toEqual(55); expect(treeGrid.getCellByColumn(1, 'Age').value).toEqual(30); expect(treeGrid.getCellByColumn(4, 'Age').value).toEqual(35); }); it('should sort treeGrid by multiple expressions through UI', () => { // Test prerequisites (need to have multiple records with the same name on every level) treeGrid.data[0].Name = 'Ana Sanders'; treeGrid.data[0].Employees[1].Name = 'Michael Langdon'; treeGrid.data[0].Employees[2].Employees[0].Name = 'Peter Lewis'; fix.detectChanges(); // Sort by 'Name' in asc order and by 'Age' in desc order const headerName = TreeGridFunctions.getHeaderCell(fix, 'Name'); const headerAge = TreeGridFunctions.getHeaderCell(fix, 'Age'); GridFunctions.clickHeaderSortIcon(headerName); fix.detectChanges(); GridFunctions.clickHeaderSortIcon(headerAge); fix.detectChanges(); GridFunctions.clickHeaderSortIcon(headerAge); fix.detectChanges(); expect(treeGrid.sortingExpressions.length).toBe(2); // Verify first level multiple expressions sorting expect(treeGrid.getCellByColumn(0, 'Name').value).toEqual('Ana Sanders'); expect(treeGrid.getCellByColumn(0, 'Age').value).toEqual(55); expect(treeGrid.getCellByColumn(7, 'Name').value).toEqual('Ana Sanders'); expect(treeGrid.getCellByColumn(7, 'Age').value).toEqual(42); expect(treeGrid.getCellByColumn(9, 'Name').value).toEqual('Yang Wang'); expect(treeGrid.getCellByColumn(9, 'Age').value).toEqual(61); // Verify second level multiple expressions sorting expect(treeGrid.getCellByColumn(1, 'Name').value).toEqual('Michael Langdon'); expect(treeGrid.getCellByColumn(1, 'Age').value).toEqual(30); expect(treeGrid.getCellByColumn(2, 'Name').value).toEqual('Michael Langdon'); expect(treeGrid.getCellByColumn(2, 'Age').value).toEqual(29); expect(treeGrid.getCellByColumn(3, 'Name').value).toEqual('Monica Reyes'); expect(treeGrid.getCellByColumn(3, 'Age').value).toEqual(31); // Verify third level multiple expressions sorting expect(treeGrid.getCellByColumn(4, 'Name').value).toEqual('Peter Lewis'); expect(treeGrid.getCellByColumn(4, 'Age').value).toEqual(35); expect(treeGrid.getCellByColumn(5, 'Name').value).toEqual('Peter Lewis'); expect(treeGrid.getCellByColumn(5, 'Age').value).toEqual(25); expect(treeGrid.getCellByColumn(6, 'Name').value).toEqual('Sven Ottlieb'); expect(treeGrid.getCellByColumn(6, 'Age').value).toEqual(44); }); it('should clear sorting of treeGrid for one column only through UI', () => { // Test prerequisites (need to have multiple records with the same name on every level) treeGrid.getCellByColumn(0, 'Name').value = 'Ana Sanders'; treeGrid.getCellByColumn(2, 'Name').value = 'Michael Langdon'; treeGrid.getCellByColumn(4, 'Name').value = 'Peter Lewis'; fix.detectChanges(); // Sort by 'Name' in asc order and by 'Age' in desc order const headerName = TreeGridFunctions.getHeaderCell(fix, 'Name'); const headerAge = TreeGridFunctions.getHeaderCell(fix, 'Age'); GridFunctions.clickHeaderSortIcon(headerName); fix.detectChanges(); GridFunctions.clickHeaderSortIcon(headerAge); fix.detectChanges(); GridFunctions.clickHeaderSortIcon(headerAge); fix.detectChanges(); // Clear sorting for 'Name' column GridFunctions.clickHeaderSortIcon(headerName); fix.detectChanges(); GridFunctions.clickHeaderSortIcon(headerName); fix.detectChanges(); expect(treeGrid.sortingExpressions.length).toBe(1); // Verify first level single expression sorting expect(treeGrid.getCellByColumn(0, 'Age').value).toEqual(61); expect(treeGrid.getCellByColumn(1, 'Age').value).toEqual(55); expect(treeGrid.getCellByColumn(8, 'Age').value).toEqual(42); // Verify second level single expression sorting expect(treeGrid.getCellByColumn(2, 'Age').value).toEqual(31); expect(treeGrid.getCellByColumn(6, 'Age').value).toEqual(30); expect(treeGrid.getCellByColumn(7, 'Age').value).toEqual(29); // Verify third level single expression sorting expect(treeGrid.getCellByColumn(3, 'Age').value).toEqual(44); expect(treeGrid.getCellByColumn(4, 'Age').value).toEqual(35); expect(treeGrid.getCellByColumn(5, 'Age').value).toEqual(25); }); }); });
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 Braket extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: Braket.Types.ClientConfiguration) config: Config & Braket.Types.ClientConfiguration; /** * Cancels the specified task. */ cancelQuantumTask(params: Braket.Types.CancelQuantumTaskRequest, callback?: (err: AWSError, data: Braket.Types.CancelQuantumTaskResponse) => void): Request<Braket.Types.CancelQuantumTaskResponse, AWSError>; /** * Cancels the specified task. */ cancelQuantumTask(callback?: (err: AWSError, data: Braket.Types.CancelQuantumTaskResponse) => void): Request<Braket.Types.CancelQuantumTaskResponse, AWSError>; /** * Creates a quantum task. */ createQuantumTask(params: Braket.Types.CreateQuantumTaskRequest, callback?: (err: AWSError, data: Braket.Types.CreateQuantumTaskResponse) => void): Request<Braket.Types.CreateQuantumTaskResponse, AWSError>; /** * Creates a quantum task. */ createQuantumTask(callback?: (err: AWSError, data: Braket.Types.CreateQuantumTaskResponse) => void): Request<Braket.Types.CreateQuantumTaskResponse, AWSError>; /** * Retrieves the devices available in Amazon Braket. */ getDevice(params: Braket.Types.GetDeviceRequest, callback?: (err: AWSError, data: Braket.Types.GetDeviceResponse) => void): Request<Braket.Types.GetDeviceResponse, AWSError>; /** * Retrieves the devices available in Amazon Braket. */ getDevice(callback?: (err: AWSError, data: Braket.Types.GetDeviceResponse) => void): Request<Braket.Types.GetDeviceResponse, AWSError>; /** * Retrieves the specified quantum task. */ getQuantumTask(params: Braket.Types.GetQuantumTaskRequest, callback?: (err: AWSError, data: Braket.Types.GetQuantumTaskResponse) => void): Request<Braket.Types.GetQuantumTaskResponse, AWSError>; /** * Retrieves the specified quantum task. */ getQuantumTask(callback?: (err: AWSError, data: Braket.Types.GetQuantumTaskResponse) => void): Request<Braket.Types.GetQuantumTaskResponse, AWSError>; /** * Shows the tags associated with this resource. */ listTagsForResource(params: Braket.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: Braket.Types.ListTagsForResourceResponse) => void): Request<Braket.Types.ListTagsForResourceResponse, AWSError>; /** * Shows the tags associated with this resource. */ listTagsForResource(callback?: (err: AWSError, data: Braket.Types.ListTagsForResourceResponse) => void): Request<Braket.Types.ListTagsForResourceResponse, AWSError>; /** * Searches for devices using the specified filters. */ searchDevices(params: Braket.Types.SearchDevicesRequest, callback?: (err: AWSError, data: Braket.Types.SearchDevicesResponse) => void): Request<Braket.Types.SearchDevicesResponse, AWSError>; /** * Searches for devices using the specified filters. */ searchDevices(callback?: (err: AWSError, data: Braket.Types.SearchDevicesResponse) => void): Request<Braket.Types.SearchDevicesResponse, AWSError>; /** * Searches for tasks that match the specified filter values. */ searchQuantumTasks(params: Braket.Types.SearchQuantumTasksRequest, callback?: (err: AWSError, data: Braket.Types.SearchQuantumTasksResponse) => void): Request<Braket.Types.SearchQuantumTasksResponse, AWSError>; /** * Searches for tasks that match the specified filter values. */ searchQuantumTasks(callback?: (err: AWSError, data: Braket.Types.SearchQuantumTasksResponse) => void): Request<Braket.Types.SearchQuantumTasksResponse, AWSError>; /** * Add a tag to the specified resource. */ tagResource(params: Braket.Types.TagResourceRequest, callback?: (err: AWSError, data: Braket.Types.TagResourceResponse) => void): Request<Braket.Types.TagResourceResponse, AWSError>; /** * Add a tag to the specified resource. */ tagResource(callback?: (err: AWSError, data: Braket.Types.TagResourceResponse) => void): Request<Braket.Types.TagResourceResponse, AWSError>; /** * Remove tags from a resource. */ untagResource(params: Braket.Types.UntagResourceRequest, callback?: (err: AWSError, data: Braket.Types.UntagResourceResponse) => void): Request<Braket.Types.UntagResourceResponse, AWSError>; /** * Remove tags from a resource. */ untagResource(callback?: (err: AWSError, data: Braket.Types.UntagResourceResponse) => void): Request<Braket.Types.UntagResourceResponse, AWSError>; } declare namespace Braket { export interface CancelQuantumTaskRequest { /** * The client token associated with the request. */ clientToken: String64; /** * The ARN of the task to cancel. */ quantumTaskArn: QuantumTaskArn; } export interface CancelQuantumTaskResponse { /** * The status of the cancellation request. */ cancellationStatus: CancellationStatus; /** * The ARN of the task. */ quantumTaskArn: QuantumTaskArn; } export type CancellationStatus = "CANCELLING"|"CANCELLED"|string; export interface CreateQuantumTaskRequest { /** * The action associated with the task. */ action: JsonValue; /** * The client token associated with the request. */ clientToken: String64; /** * The ARN of the device to run the task on. */ deviceArn: DeviceArn; /** * The parameters for the device to run the task on. */ deviceParameters?: CreateQuantumTaskRequestDeviceParametersString; /** * The S3 bucket to store task result files in. */ outputS3Bucket: CreateQuantumTaskRequestOutputS3BucketString; /** * The key prefix for the location in the S3 bucket to store task results in. */ outputS3KeyPrefix: CreateQuantumTaskRequestOutputS3KeyPrefixString; /** * The number of shots to use for the task. */ shots: CreateQuantumTaskRequestShotsLong; /** * Tags to be added to the quantum task you're creating. */ tags?: TagsMap; } export type CreateQuantumTaskRequestDeviceParametersString = string; export type CreateQuantumTaskRequestOutputS3BucketString = string; export type CreateQuantumTaskRequestOutputS3KeyPrefixString = string; export type CreateQuantumTaskRequestShotsLong = number; export interface CreateQuantumTaskResponse { /** * The ARN of the task created by the request. */ quantumTaskArn: QuantumTaskArn; } export type DeviceArn = string; export type DeviceStatus = "ONLINE"|"OFFLINE"|"RETIRED"|string; export interface DeviceSummary { /** * The ARN of the device. */ deviceArn: DeviceArn; /** * The name of the device. */ deviceName: String; /** * The status of the device. */ deviceStatus: DeviceStatus; /** * The type of the device. */ deviceType: DeviceType; /** * The provider of the device. */ providerName: String; } export type DeviceSummaryList = DeviceSummary[]; export type DeviceType = "QPU"|"SIMULATOR"|string; export interface GetDeviceRequest { /** * The ARN of the device to retrieve. */ deviceArn: DeviceArn; } export interface GetDeviceResponse { /** * The ARN of the device. */ deviceArn: DeviceArn; /** * Details about the capabilities of the device. */ deviceCapabilities: JsonValue; /** * The name of the device. */ deviceName: String; /** * The status of the device. */ deviceStatus: DeviceStatus; /** * The type of the device. */ deviceType: DeviceType; /** * The name of the partner company for the device. */ providerName: String; } export interface GetQuantumTaskRequest { /** * the ARN of the task to retrieve. */ quantumTaskArn: QuantumTaskArn; } export interface GetQuantumTaskResponse { /** * The time at which the task was created. */ createdAt: SyntheticTimestamp_date_time; /** * The ARN of the device the task was run on. */ deviceArn: DeviceArn; /** * The parameters for the device on which the task ran. */ deviceParameters: JsonValue; /** * The time at which the task ended. */ endedAt?: SyntheticTimestamp_date_time; /** * The reason that a task failed. */ failureReason?: String; /** * The S3 bucket where task results are stored. */ outputS3Bucket: String; /** * The folder in the S3 bucket where task results are stored. */ outputS3Directory: String; /** * The ARN of the task. */ quantumTaskArn: QuantumTaskArn; /** * The number of shots used in the task. */ shots: Long; /** * The status of the task. */ status: QuantumTaskStatus; /** * The tags that belong to this task. */ tags?: TagsMap; } export type JsonValue = string; export interface ListTagsForResourceRequest { /** * Specify the resourceArn for the resource whose tags to display. */ resourceArn: String; } export interface ListTagsForResourceResponse { /** * Displays the key, value pairs of tags associated with this resource. */ tags?: TagsMap; } export type Long = number; export type QuantumTaskArn = string; export type QuantumTaskStatus = "CREATED"|"QUEUED"|"RUNNING"|"COMPLETED"|"FAILED"|"CANCELLING"|"CANCELLED"|string; export interface QuantumTaskSummary { /** * The time at which the task was created. */ createdAt: SyntheticTimestamp_date_time; /** * The ARN of the device the task ran on. */ deviceArn: DeviceArn; /** * The time at which the task finished. */ endedAt?: SyntheticTimestamp_date_time; /** * The S3 bucket where the task result file is stored.. */ outputS3Bucket: String; /** * The folder in the S3 bucket where the task result file is stored. */ outputS3Directory: String; /** * The ARN of the task. */ quantumTaskArn: QuantumTaskArn; /** * The shots used for the task. */ shots: Long; /** * The status of the task. */ status: QuantumTaskStatus; /** * Displays the key, value pairs of tags associated with this quantum task. */ tags?: TagsMap; } export type QuantumTaskSummaryList = QuantumTaskSummary[]; export interface SearchDevicesFilter { /** * The name to use to filter results. */ name: SearchDevicesFilterNameString; /** * The values to use to filter results. */ values: SearchDevicesFilterValuesList; } export type SearchDevicesFilterNameString = string; export type SearchDevicesFilterValuesList = String256[]; export interface SearchDevicesRequest { /** * The filter values to use to search for a device. */ filters: SearchDevicesRequestFiltersList; /** * The maximum number of results to return in the response. */ maxResults?: SearchDevicesRequestMaxResultsInteger; /** * A token used for pagination of results returned in the response. Use the token returned from the previous request continue results where the previous request ended. */ nextToken?: String; } export type SearchDevicesRequestFiltersList = SearchDevicesFilter[]; export type SearchDevicesRequestMaxResultsInteger = number; export interface SearchDevicesResponse { /** * An array of DeviceSummary objects for devices that match the specified filter values. */ devices: DeviceSummaryList; /** * A token used for pagination of results, or null if there are no additional results. Use the token value in a subsequent request to continue results where the previous request ended. */ nextToken?: String; } export interface SearchQuantumTasksFilter { /** * The name of the device used for the task. */ name: String64; /** * An operator to use in the filter. */ operator: SearchQuantumTasksFilterOperator; /** * The values to use for the filter. */ values: SearchQuantumTasksFilterValuesList; } export type SearchQuantumTasksFilterOperator = "LT"|"LTE"|"EQUAL"|"GT"|"GTE"|"BETWEEN"|string; export type SearchQuantumTasksFilterValuesList = String256[]; export interface SearchQuantumTasksRequest { /** * Array of SearchQuantumTasksFilter objects. */ filters: SearchQuantumTasksRequestFiltersList; /** * Maximum number of results to return in the response. */ maxResults?: SearchQuantumTasksRequestMaxResultsInteger; /** * A token used for pagination of results returned in the response. Use the token returned from the previous request continue results where the previous request ended. */ nextToken?: String; } export type SearchQuantumTasksRequestFiltersList = SearchQuantumTasksFilter[]; export type SearchQuantumTasksRequestMaxResultsInteger = number; export interface SearchQuantumTasksResponse { /** * A token used for pagination of results, or null if there are no additional results. Use the token value in a subsequent request to continue results where the previous request ended. */ nextToken?: String; /** * An array of QuantumTaskSummary objects for tasks that match the specified filters. */ quantumTasks: QuantumTaskSummaryList; } export type String = string; export type String256 = string; export type String64 = string; export type SyntheticTimestamp_date_time = Date; export type TagKeys = String[]; export interface TagResourceRequest { /** * Specify the resourceArn of the resource to which a tag will be added. */ resourceArn: String; /** * Specify the tags to add to the resource. */ tags: TagsMap; } export interface TagResourceResponse { } export type TagsMap = {[key: string]: String}; export interface UntagResourceRequest { /** * Specify the resourceArn for the resource from which to remove the tags. */ resourceArn: String; /** * Specify the keys for the tags to remove from the resource. */ tagKeys: TagKeys; } export interface UntagResourceResponse { } /** * 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-09-01"|"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 Braket client. */ export import Types = Braket; } export = Braket;
the_stack
* Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { ActivityHandler, AppBasedLinkQuery, ChannelInfo, Channels, FileConsentCardResponse, InvokeResponse, MeetingStartEventDetails, MeetingEndEventDetails, MessagingExtensionAction, MessagingExtensionActionResponse, MessagingExtensionQuery, MessagingExtensionResponse, O365ConnectorCardActionQuery, SigninStateVerificationQuery, TabRequest, TabResponse, TabSubmit, TaskModuleRequest, TaskModuleResponse, TeamsChannelData, TeamsChannelAccount, TeamInfo, TurnContext, tokenExchangeOperationName, verifyStateOperationName, } from 'botbuilder-core'; import { TeamsInfo } from './teamsInfo'; import * as z from 'zod'; const TeamsMeetingStartT = z .object({ Id: z.string(), JoinUrl: z.string(), MeetingType: z.string(), Title: z.string(), StartTime: z.string(), }) .nonstrict(); const TeamsMeetingEndT = z .object({ Id: z.string(), JoinUrl: z.string(), MeetingType: z.string(), Title: z.string(), EndTime: z.string(), }) .nonstrict(); /** * Adds support for Microsoft Teams specific events and interactions. * * @remarks * Developers may handle Conversation Update activities sent from Microsoft Teams via two methods: * 1. Overriding methods starting with `on..` and *not* ending in `..Event()` (e.g. `onTeamsMembersAdded()`), or instead * 2. Passing callbacks to methods starting with `on..` *and* ending in `...Event()` (e.g. `onTeamsMembersAddedEvent()`), * to stay in line with older {@see ActivityHandler} implementation. * * Developers should use either #1 or #2, above for all Conversation Update activities and not *both* #2 and #3 for the same activity. Meaning, * developers should override `onTeamsMembersAdded()` and not use both `onTeamsMembersAdded()` and `onTeamsMembersAddedEvent()`. * * Developers wanting to handle Invoke activities *must* override methods starting with `handle...()` (e.g. `handleTeamsTaskModuleFetch()`). */ export class TeamsActivityHandler extends ActivityHandler { /** * Invoked when an invoke activity is received from the connector. * Invoke activities can be used to communicate many different things. * * @param context A context object for this turn. * @returns An Invoke Response for the activity. */ protected async onInvokeActivity(context: TurnContext): Promise<InvokeResponse> { let runEvents = true; try { if (!context.activity.name && context.activity.channelId === 'msteams') { return await this.handleTeamsCardActionInvoke(context); } else { switch (context.activity.name) { case 'fileConsent/invoke': return ActivityHandler.createInvokeResponse( await this.handleTeamsFileConsent(context, context.activity.value) ); case 'actionableMessage/executeAction': await this.handleTeamsO365ConnectorCardAction(context, context.activity.value); return ActivityHandler.createInvokeResponse(); case 'composeExtension/queryLink': return ActivityHandler.createInvokeResponse( await this.handleTeamsAppBasedLinkQuery(context, context.activity.value) ); case 'composeExtension/query': return ActivityHandler.createInvokeResponse( await this.handleTeamsMessagingExtensionQuery(context, context.activity.value) ); case 'composeExtension/selectItem': return ActivityHandler.createInvokeResponse( await this.handleTeamsMessagingExtensionSelectItem(context, context.activity.value) ); case 'composeExtension/submitAction': return ActivityHandler.createInvokeResponse( await this.handleTeamsMessagingExtensionSubmitActionDispatch( context, context.activity.value ) ); case 'composeExtension/fetchTask': return ActivityHandler.createInvokeResponse( await this.handleTeamsMessagingExtensionFetchTask(context, context.activity.value) ); case 'composeExtension/querySettingUrl': return ActivityHandler.createInvokeResponse( await this.handleTeamsMessagingExtensionConfigurationQuerySettingUrl( context, context.activity.value ) ); case 'composeExtension/setting': await this.handleTeamsMessagingExtensionConfigurationSetting(context, context.activity.value); return ActivityHandler.createInvokeResponse(); case 'composeExtension/onCardButtonClicked': await this.handleTeamsMessagingExtensionCardButtonClicked(context, context.activity.value); return ActivityHandler.createInvokeResponse(); case 'task/fetch': return ActivityHandler.createInvokeResponse( await this.handleTeamsTaskModuleFetch(context, context.activity.value) ); case 'task/submit': return ActivityHandler.createInvokeResponse( await this.handleTeamsTaskModuleSubmit(context, context.activity.value) ); case 'tab/fetch': return ActivityHandler.createInvokeResponse( await this.handleTeamsTabFetch(context, context.activity.value) ); case 'tab/submit': return ActivityHandler.createInvokeResponse( await this.handleTeamsTabSubmit(context, context.activity.value) ); default: runEvents = false; return super.onInvokeActivity(context); } } } catch (err) { if (err.message === 'NotImplemented') { return { status: 501 }; } else if (err.message === 'BadRequest') { return { status: 400 }; } throw err; } finally { if (runEvents) { this.defaultNextEvent(context)(); } } } /** * Handles a Teams Card Action Invoke activity. * * @param _context A context object for this turn. * @returns An Invoke Response for the activity. */ protected async handleTeamsCardActionInvoke(_context: TurnContext): Promise<InvokeResponse> { throw new Error('NotImplemented'); } /** * Receives invoke activities with Activity name of 'fileConsent/invoke'. Handlers registered here run before * `handleTeamsFileConsentAccept` and `handleTeamsFileConsentDecline`. * Developers are not passed a pointer to the next `handleTeamsFileConsent` handler because the _wrapper_ around * the handler will call `onDialogs` handlers after delegating to `handleTeamsFileConsentAccept` or `handleTeamsFileConsentDecline`. * * @param context A context object for this turn. * @param fileConsentCardResponse Represents the value of the invoke activity sent when the user acts on a file consent card. * @returns A promise that represents the work queued. */ protected async handleTeamsFileConsent( context: TurnContext, fileConsentCardResponse: FileConsentCardResponse ): Promise<void> { switch (fileConsentCardResponse.action) { case 'accept': return await this.handleTeamsFileConsentAccept(context, fileConsentCardResponse); case 'decline': return await this.handleTeamsFileConsentDecline(context, fileConsentCardResponse); default: throw new Error('BadRequest'); } } /** * Receives invoke activities with Activity name of 'fileConsent/invoke' with confirmation from user * * @remarks * This type of invoke activity occur during the File Consent flow. * @param _context A context object for this turn. * @param _fileConsentCardResponse Represents the value of the invoke activity sent when the user acts on a file consent card. * @returns A promise that represents the work queued. */ protected async handleTeamsFileConsentAccept( _context: TurnContext, _fileConsentCardResponse: FileConsentCardResponse ): Promise<void> { throw new Error('NotImplemented'); } /** * Receives invoke activities with Activity name of 'fileConsent/invoke' with decline from user * * @remarks * This type of invoke activity occur during the File Consent flow. * @param _context A context object for this turn. * @param _fileConsentCardResponse Represents the value of the invoke activity sent when the user acts on a file consent card. * @returns A promise that represents the work queued. */ protected async handleTeamsFileConsentDecline( _context: TurnContext, _fileConsentCardResponse: FileConsentCardResponse ): Promise<void> { throw new Error('NotImplemented'); } /** * Receives invoke activities with Activity name of 'actionableMessage/executeAction'. * * @param _context A context object for this turn. * @param _query The O365 connector card HttpPOST invoke query. * @returns A promise that represents the work queued. */ protected async handleTeamsO365ConnectorCardAction( _context: TurnContext, _query: O365ConnectorCardActionQuery ): Promise<void> { throw new Error('NotImplemented'); } /** * Invoked when a signIn invoke activity is received from the connector. * * @param context A context object for this turn. * @returns A promise that represents the work queued. */ protected async onSignInInvoke(context: TurnContext): Promise<void> { switch (context.activity.name) { case verifyStateOperationName: return await this.handleTeamsSigninVerifyState(context, context.activity.value); case tokenExchangeOperationName: return await this.handleTeamsSigninTokenExchange(context, context.activity.value); } } /** * Receives invoke activities with Activity name of 'signin/verifyState'. * * @param _context A context object for this turn. * @param _query Signin state (part of signin action auth flow) verification invoke query. * @returns A promise that represents the work queued. */ protected async handleTeamsSigninVerifyState( _context: TurnContext, _query: SigninStateVerificationQuery ): Promise<void> { throw new Error('NotImplemented'); } /** * Receives invoke activities with Activity name of 'signin/tokenExchange' * * @param _context A context object for this turn. * @param _query Signin state (part of signin action auth flow) verification invoke query * @returns A promise that represents the work queued. */ protected async handleTeamsSigninTokenExchange( _context: TurnContext, _query: SigninStateVerificationQuery ): Promise<void> { throw new Error('NotImplemented'); } /** * Receives invoke activities with Activity name of 'composeExtension/onCardButtonClicked' * * @param _context A context object for this turn. * @param _cardData Object representing the card data. * @returns A promise that represents the work queued. */ protected async handleTeamsMessagingExtensionCardButtonClicked( _context: TurnContext, _cardData: any ): Promise<void> { throw new Error('NotImplemented'); } /** * Receives invoke activities with Activity name of 'task/fetch' * * @param _context A context object for this turn. * @param _taskModuleRequest The task module invoke request value payload. * @returns A Task Module Response for the request. */ protected async handleTeamsTaskModuleFetch( _context: TurnContext, _taskModuleRequest: TaskModuleRequest ): Promise<TaskModuleResponse> { throw new Error('NotImplemented'); } /** * Receives invoke activities with Activity name of 'task/submit' * * @param _context A context object for this turn. * @param _taskModuleRequest The task module invoke request value payload. * @returns A Task Module Response for the request. */ protected async handleTeamsTaskModuleSubmit( _context: TurnContext, _taskModuleRequest: TaskModuleRequest ): Promise<TaskModuleResponse> { throw new Error('NotImplemented'); } /** * Receives invoke activities with Activity name of 'tab/fetch' * * @param _context A context object for this turn. * @param _tabRequest The tab invoke request value payload. * @returns A Tab Response for the request. */ protected async handleTeamsTabFetch(_context: TurnContext, _tabRequest: TabRequest): Promise<TabResponse> { throw new Error('NotImplemented'); } /** * Receives invoke activities with Activity name of 'tab/submit' * * @param _context A context object for this turn. * @param _tabSubmit The tab submit invoke request value payload. * @returns A Tab Response for the request. */ protected async handleTeamsTabSubmit(_context: TurnContext, _tabSubmit: TabSubmit): Promise<TabResponse> { throw new Error('NotImplemented'); } /** * Receives invoke activities with Activity name of 'composeExtension/queryLink' * * @remarks * Used in creating a Search-based Message Extension. * @param _context A context object for this turn. * @param _query he invoke request body type for app-based link query. * @returns The Messaging Extension Response for the query. */ protected async handleTeamsAppBasedLinkQuery( _context: TurnContext, _query: AppBasedLinkQuery ): Promise<MessagingExtensionResponse> { throw new Error('NotImplemented'); } /** * Receives invoke activities with the name 'composeExtension/query'. * * @remarks * Used in creating a Search-based Message Extension. * @param _context A context object for this turn. * @param _query The query for the search command. * @returns The Messaging Extension Response for the query. */ protected async handleTeamsMessagingExtensionQuery( _context: TurnContext, _query: MessagingExtensionQuery ): Promise<MessagingExtensionResponse> { throw new Error('NotImplemented'); } /** * Receives invoke activities with the name 'composeExtension/selectItem'. * * @remarks * Used in creating a Search-based Message Extension. * @param _context A context object for this turn. * @param _query he object representing the query. * @returns The Messaging Extension Response for the query. */ protected async handleTeamsMessagingExtensionSelectItem( _context: TurnContext, _query: any ): Promise<MessagingExtensionResponse> { throw new Error('NotImplemented'); } /** * Receives invoke activities with the name 'composeExtension/submitAction' and dispatches to botMessagePreview-flows as applicable. * * @remarks * A handler registered through this method does not dispatch to the next handler (either `handleTeamsMessagingExtensionSubmitAction`, `handleTeamsMessagingExtensionBotMessagePreviewEdit`, or `handleTeamsMessagingExtensionBotMessagePreviewSend`). * This method exists for developers to optionally add more logic before the TeamsActivityHandler routes the activity to one of the * previously mentioned handlers. * @param context A context object for this turn. * @param action The messaging extension action. * @returns The Messaging Extension Action Response for the action. */ protected async handleTeamsMessagingExtensionSubmitActionDispatch( context: TurnContext, action: MessagingExtensionAction ): Promise<MessagingExtensionActionResponse> { if (action.botMessagePreviewAction) { switch (action.botMessagePreviewAction) { case 'edit': return await this.handleTeamsMessagingExtensionBotMessagePreviewEdit(context, action); case 'send': return await this.handleTeamsMessagingExtensionBotMessagePreviewSend(context, action); default: throw new Error('BadRequest'); } } else { return await this.handleTeamsMessagingExtensionSubmitAction(context, action); } } /** * Receives invoke activities with the name 'composeExtension/submitAction'. * * @param _context A context object for this turn. * @param _action The messaging extension action. * @returns The Messaging Extension Action Response for the action. */ protected async handleTeamsMessagingExtensionSubmitAction( _context: TurnContext, _action: MessagingExtensionAction ): Promise<MessagingExtensionActionResponse> { throw new Error('NotImplemented'); } /** * Receives invoke activities with the name 'composeExtension/submitAction' with the 'botMessagePreview' property present on activity.value. * The value for 'botMessagePreview' is 'edit'. * * @param _context A context object for this turn. * @param _action The messaging extension action. * @returns The Messaging Extension Action Response for the action. */ protected async handleTeamsMessagingExtensionBotMessagePreviewEdit( _context: TurnContext, _action: MessagingExtensionAction ): Promise<MessagingExtensionActionResponse> { throw new Error('NotImplemented'); } /** * Receives invoke activities with the name 'composeExtension/submitAction' with the 'botMessagePreview' property present on activity.value. * The value for 'botMessagePreview' is 'send'. * * @param _context A context object for this turn. * @param _action The messaging extension action. * @returns The Messaging Extension Action Response for the action. */ protected async handleTeamsMessagingExtensionBotMessagePreviewSend( _context: TurnContext, _action: MessagingExtensionAction ): Promise<MessagingExtensionActionResponse> { throw new Error('NotImplemented'); } /** * Receives invoke activities with the name 'composeExtension/fetchTask' * * @param _context A context object for this turn. * @param _action The messaging extension action. * @returns The Messaging Extension Action Response for the action. */ protected async handleTeamsMessagingExtensionFetchTask( _context: TurnContext, _action: MessagingExtensionAction ): Promise<MessagingExtensionActionResponse> { throw new Error('NotImplemented'); } /** * Receives invoke activities with the name 'composeExtension/querySettingUrl' * * @param _context A context object for this turn. * @param _query The Messaging extension query. * @returns The Messaging Extension Action Response for the query. */ protected async handleTeamsMessagingExtensionConfigurationQuerySettingUrl( _context: TurnContext, _query: MessagingExtensionQuery ): Promise<MessagingExtensionResponse> { throw new Error('NotImplemented'); } /** * Receives invoke activities with the name 'composeExtension/setting' * * @param _context A context object for this turn. * @param _settings Object representing the configuration settings. */ protected handleTeamsMessagingExtensionConfigurationSetting(_context: TurnContext, _settings: any): Promise<void> { throw new Error('NotImplemented'); } /** * Override this method to change the dispatching of ConversationUpdate activities. * * @param context A context object for this turn. * @returns A promise that represents the work queued. */ protected async dispatchConversationUpdateActivity(context: TurnContext): Promise<void> { if (context.activity.channelId == 'msteams') { const channelData = context.activity.channelData as TeamsChannelData; if (context.activity.membersAdded && context.activity.membersAdded.length > 0) { return await this.onTeamsMembersAdded(context); } if (context.activity.membersRemoved && context.activity.membersRemoved.length > 0) { return await this.onTeamsMembersRemoved(context); } if (!channelData || !channelData.eventType) { return await super.dispatchConversationUpdateActivity(context); } switch (channelData.eventType) { case 'channelCreated': return await this.onTeamsChannelCreated(context); case 'channelDeleted': return await this.onTeamsChannelDeleted(context); case 'channelRenamed': return await this.onTeamsChannelRenamed(context); case 'teamArchived': return await this.onTeamsTeamArchived(context); case 'teamDeleted': return await this.onTeamsTeamDeleted(context); case 'teamHardDeleted': return await this.onTeamsTeamHardDeleted(context); case 'channelRestored': return await this.onTeamsChannelRestored(context); case 'teamRenamed': return await this.onTeamsTeamRenamed(context); case 'teamRestored': return await this.onTeamsTeamRestored(context); case 'teamUnarchived': return await this.onTeamsTeamUnarchived(context); default: return await super.dispatchConversationUpdateActivity(context); } } else { return await super.dispatchConversationUpdateActivity(context); } } /** * Called in `dispatchConversationUpdateActivity()` to trigger the `'TeamsMembersAdded'` handlers. * Override this in a derived class to provide logic for when members other than the bot * join the channel, such as your bot's welcome logic. * * @remarks * If no handlers are registered for the `'TeamsMembersAdded'` event, the `'MembersAdded'` handlers will run instead. * @param context A context object for this turn. * @returns A promise that represents the work queued. */ protected async onTeamsMembersAdded(context: TurnContext): Promise<void> { if ('TeamsMembersAdded' in this.handlers && this.handlers['TeamsMembersAdded'].length > 0) { for (let i = 0; i < context.activity.membersAdded.length; i++) { const channelAccount = context.activity.membersAdded[i]; // check whether we have a TeamChannelAccount, or the member is the bot if ( 'givenName' in channelAccount || 'surname' in channelAccount || 'email' in channelAccount || 'userPrincipalName' in channelAccount || context.activity.recipient.id === channelAccount.id ) { // we must have a TeamsChannelAccount, or a bot so skip to the next one continue; } try { context.activity.membersAdded[i] = await TeamsInfo.getMember(context, channelAccount.id); } catch (err) { const errCode: string = err.body && err.body.error && err.body.error.code; if (errCode === 'ConversationNotFound') { // unable to find the member added in ConversationUpdate Activity in the response from the getMember call const teamsChannelAccount: TeamsChannelAccount = { id: channelAccount.id, name: channelAccount.name, aadObjectId: channelAccount.aadObjectId, role: channelAccount.role, }; context.activity.membersAdded[i] = teamsChannelAccount; } else { throw err; } } } await this.handle(context, 'TeamsMembersAdded', this.defaultNextEvent(context)); } else { await this.handle(context, 'MembersAdded', this.defaultNextEvent(context)); } } /** * Called in `dispatchConversationUpdateActivity()` to trigger the `'TeamsMembersRemoved'` handlers. * Override this in a derived class to provide logic for when members other than the bot * leave the channel, such as your bot's good-bye logic. * * @remarks * If no handlers are registered for the `'TeamsMembersRemoved'` event, the `'MembersRemoved'` handlers will run instead. * @param context A context object for this turn. * @returns A promise that represents the work queued. */ protected async onTeamsMembersRemoved(context: TurnContext): Promise<void> { if ('TeamsMembersRemoved' in this.handlers && this.handlers['TeamsMembersRemoved'].length > 0) { await this.handle(context, 'TeamsMembersRemoved', this.defaultNextEvent(context)); } else { await this.handle(context, 'MembersRemoved', this.defaultNextEvent(context)); } } /** * Invoked when a Channel Created event activity is received from the connector. * Channel Created corresponds to the user creating a new channel. * Override this in a derived class to provide logic for when a channel is created. * * @param context A context object for this turn. * @returns A promise that represents the work queued. */ protected async onTeamsChannelCreated(context): Promise<void> { await this.handle(context, 'TeamsChannelCreated', this.defaultNextEvent(context)); } /** * Invoked when a Channel Deleted event activity is received from the connector. * Channel Deleted corresponds to the user deleting a channel. * Override this in a derived class to provide logic for when a channel is deleted. * * @param context A context object for this turn. * @returns A promise that represents the work queued. */ protected async onTeamsChannelDeleted(context): Promise<void> { await this.handle(context, 'TeamsChannelDeleted', this.defaultNextEvent(context)); } /** * Invoked when a Channel Renamed event activity is received from the connector. * Channel Renamed corresponds to the user renaming a new channel. * Override this in a derived class to provide logic for when a channel is renamed. * * @param context A context object for this turn. * @returns A promise that represents the work queued. */ protected async onTeamsChannelRenamed(context): Promise<void> { await this.handle(context, 'TeamsChannelRenamed', this.defaultNextEvent(context)); } /** * Invoked when a Team Archived event activity is received from the connector. * Team Archived corresponds to the user archiving a team. * Override this in a derived class to provide logic for when a team is archived. * * @param context The context for this turn. * @returns A promise that represents the work queued. */ protected async onTeamsTeamArchived(context): Promise<void> { await this.handle(context, 'TeamsTeamArchived', this.defaultNextEvent(context)); } /** * Invoked when a Team Deleted event activity is received from the connector. * Team Deleted corresponds to the user deleting a team. * Override this in a derived class to provide logic for when a team is deleted. * * @param context The context for this turn. * @returns A promise that represents the work queued. */ protected async onTeamsTeamDeleted(context): Promise<void> { await this.handle(context, 'TeamsTeamDeleted', this.defaultNextEvent(context)); } /** * Invoked when a Team Hard Deleted event activity is received from the connector. * Team Hard Deleted corresponds to the user hard-deleting a team. * Override this in a derived class to provide logic for when a team is hard-deleted. * * @param context The context for this turn. * @returns A promise that represents the work queued. */ protected async onTeamsTeamHardDeleted(context): Promise<void> { await this.handle(context, 'TeamsTeamHardDeleted', this.defaultNextEvent(context)); } /** * * Invoked when a Channel Restored event activity is received from the connector. * Channel Restored corresponds to the user restoring a previously deleted channel. * Override this in a derived class to provide logic for when a channel is restored. * * @param context The context for this turn. * @returns A promise that represents the work queued. */ protected async onTeamsChannelRestored(context): Promise<void> { await this.handle(context, 'TeamsChannelRestored', this.defaultNextEvent(context)); } /** * Invoked when a Team Renamed event activity is received from the connector. * Team Renamed corresponds to the user renaming a team. * Override this in a derived class to provide logic for when a team is renamed. * * @param context The context for this turn. * @returns A promise that represents the work queued. */ protected async onTeamsTeamRenamed(context): Promise<void> { await this.handle(context, 'TeamsTeamRenamed', this.defaultNextEvent(context)); } /** * Invoked when a Team Restored event activity is received from the connector. * Team Restored corresponds to the user restoring a team. * Override this in a derived class to provide logic for when a team is restored. * * @param context The context for this turn. * @returns A promise that represents the work queued. */ protected async onTeamsTeamRestored(context): Promise<void> { await this.handle(context, 'TeamsTeamRestored', this.defaultNextEvent(context)); } /** * Invoked when a Team Unarchived event activity is received from the connector. * Team Unarchived corresponds to the user unarchiving a team. * Override this in a derived class to provide logic for when a team is unarchived. * * @param context The context for this turn. * @returns A promise that represents the work queued. */ protected async onTeamsTeamUnarchived(context): Promise<void> { await this.handle(context, 'TeamsTeamUnarchived', this.defaultNextEvent(context)); } /** * Registers a handler for TeamsMembersAdded events, such as for when members other than the bot * join the channel, such as your bot's welcome logic. * * @param handler A callback to handle the teams members added event. * @returns A promise that represents the work queued. */ onTeamsMembersAddedEvent( handler: ( membersAdded: TeamsChannelAccount[], teamInfo: TeamInfo, context: TurnContext, next: () => Promise<void> ) => Promise<void> ): this { return this.on('TeamsMembersAdded', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; await handler(context.activity.membersAdded, teamsChannelData.team, context, next); }); } /** * Registers a handler for TeamsMembersRemoved events, such as for when members other than the bot * leave the channel, such as your bot's good-bye logic. * * @param handler A callback to handle the teams members removed event. * @returns A promise that represents the work queued. */ onTeamsMembersRemovedEvent( handler: ( membersRemoved: TeamsChannelAccount[], teamInfo: TeamInfo, context: TurnContext, next: () => Promise<void> ) => Promise<void> ): this { return this.on('TeamsMembersRemoved', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; await handler(context.activity.membersRemoved, teamsChannelData.team, context, next); }); } /** * Registers a handler for TeamsChannelCreated events, such as for when a channel is created. * * @param handler A callback to handle the teams channel created event. * @returns A promise that represents the work queued. */ onTeamsChannelCreatedEvent( handler: ( channelInfo: ChannelInfo, teamInfo: TeamInfo, context: TurnContext, next: () => Promise<void> ) => Promise<void> ): this { return this.on('TeamsChannelCreated', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; await handler(teamsChannelData.channel, teamsChannelData.team, context, next); }); } /** * Registers a handler for TeamsChannelDeleted events, such as for when a channel is deleted. * * @param handler A callback to handle the teams channel deleted event. * @returns A promise that represents the work queued. */ onTeamsChannelDeletedEvent( handler: ( channelInfo: ChannelInfo, teamInfo: TeamInfo, context: TurnContext, next: () => Promise<void> ) => Promise<void> ): this { return this.on('TeamsChannelDeleted', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; await handler(teamsChannelData.channel, teamsChannelData.team, context, next); }); } /** * Registers a handler for TeamsChannelRenamed events, such as for when a channel is renamed. * * @param handler A callback to handle the teams channel renamed event. * @returns A promise that represents the work queued. */ onTeamsChannelRenamedEvent( handler: ( channelInfo: ChannelInfo, teamInfo: TeamInfo, context: TurnContext, next: () => Promise<void> ) => Promise<void> ): this { return this.on('TeamsChannelRenamed', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; await handler(teamsChannelData.channel, teamsChannelData.team, context, next); }); } /** * Registers a handler for TeamsTeamArchived events, such as for when a team is archived. * * @param handler A callback to handle the teams team archived event. * @returns A promise that represents the work queued. */ onTeamsTeamArchivedEvent( handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise<void>) => Promise<void> ): this { return this.on('TeamsTeamArchived', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; await handler(teamsChannelData.team, context, next); }); } /** * Registers a handler for TeamsTeamDeleted events, such as for when a team is deleted. * * @param handler A callback to handle the teams team deleted event. * @returns A promise that represents the work queued. */ onTeamsTeamDeletedEvent( handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise<void>) => Promise<void> ): this { return this.on('TeamsTeamDeleted', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; await handler(teamsChannelData.team, context, next); }); } /** * Registers a handler for TeamsTeamHardDeleted events, such as for when a team is hard-deleted. * * @param handler A callback to handle the teams team hard deleted event. * @returns A promise that represents the work queued. */ onTeamsTeamHardDeletedEvent( handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise<void>) => Promise<void> ): this { return this.on('TeamsTeamHardDeleted', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; await handler(teamsChannelData.team, context, next); }); } /** * Registers a handler for TeamsChannelRestored events, such as for when a channel is restored. * * @param handler A callback to handle the teams channel restored event. * @returns A promise that represents the work queued. */ onTeamsChannelRestoredEvent( handler: ( channelInfo: ChannelInfo, teamInfo: TeamInfo, context: TurnContext, next: () => Promise<void> ) => Promise<void> ): this { return this.on('TeamsChannelRestored', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; await handler(teamsChannelData.channel, teamsChannelData.team, context, next); }); } /** * Registers a handler for TeamsTeamRenamed events, such as for when a team is renamed. * * @param handler A callback to handle the teams team renamed event. * @returns A promise that represents the work queued. */ onTeamsTeamRenamedEvent( handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise<void>) => Promise<void> ): this { return this.on('TeamsTeamRenamed', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; await handler(teamsChannelData.team, context, next); }); } /** * Registers a handler for TeamsTeamRestored events, such as for when a team is restored. * * @param handler A callback to handle the teams team restored event. * @returns A promise that represents the work queued. */ onTeamsTeamRestoredEvent( handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise<void>) => Promise<void> ): this { return this.on('TeamsTeamRestored', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; await handler(teamsChannelData.team, context, next); }); } /** * Registers a handler for TeamsTeamUnarchived events, such as for when a team is unarchived. * * @param handler A callback to handle the teams team unarchived event. * @returns A promise that represents the work queued. */ onTeamsTeamUnarchivedEvent( handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise<void>) => Promise<void> ): this { return this.on('TeamsTeamUnarchived', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; await handler(teamsChannelData.team, context, next); }); } /** * Runs the _event_ sub-type handlers, as appropriate, and then continues the event emission process. * * @param context The context object for the current turn. * @returns A promise that represents the work queued. * * @remarks * Override this method to support channel-specific behavior across multiple channels or to add * custom event sub-type events. */ protected async dispatchEventActivity(context: TurnContext): Promise<void> { if (context.activity.channelId === Channels.Msteams) { switch (context.activity.name) { case 'application/vnd.microsoft.meetingStart': return this.onTeamsMeetingStart(context); case 'application/vnd.microsoft.meetingEnd': return this.onTeamsMeetingEnd(context); } } return super.dispatchEventActivity(context); } /** * Invoked when a Meeting Started event activity is received from the connector. * Override this in a derived class to provide logic for when a meeting is started. * * @param context The context for this turn. * @returns A promise that represents the work queued. */ protected async onTeamsMeetingStart(context: TurnContext): Promise<void> { await this.handle(context, 'TeamsMeetingStart', this.defaultNextEvent(context)); } /** * Invoked when a Meeting End event activity is received from the connector. * Override this in a derived class to provide logic for when a meeting is ended. * * @param context The context for this turn. * @returns A promise that represents the work queued. */ protected async onTeamsMeetingEnd(context: TurnContext): Promise<void> { await this.handle(context, 'TeamsMeetingEnd', this.defaultNextEvent(context)); } /** * Registers a handler for when a Teams meeting starts. * * @param handler A callback that handles Meeting Start events. * @returns A promise that represents the work queued. */ onTeamsMeetingStartEvent( handler: (meeting: MeetingStartEventDetails, context: TurnContext, next: () => Promise<void>) => Promise<void> ): this { return this.on('TeamsMeetingStart', async (context, next) => { const meeting = TeamsMeetingStartT.parse(context.activity.value); await handler( { id: meeting.Id, joinUrl: meeting.JoinUrl, meetingType: meeting.MeetingType, startTime: new Date(meeting.StartTime), title: meeting.Title, }, context, next ); }); } /** * Registers a handler for when a Teams meeting ends. * * @param handler A callback that handles Meeting End events. * @returns A promise that represents the work queued. */ onTeamsMeetingEndEvent( handler: (meeting: MeetingEndEventDetails, context: TurnContext, next: () => Promise<void>) => Promise<void> ): this { return this.on('TeamsMeetingEnd', async (context, next) => { const meeting = TeamsMeetingEndT.parse(context.activity.value); await handler( { id: meeting.Id, joinUrl: meeting.JoinUrl, meetingType: meeting.MeetingType, endTime: new Date(meeting.EndTime), title: meeting.Title, }, context, next ); }); } }
the_stack
import { Dexie as IDexie } from "../../public/types/dexie"; import { DexieOptions, DexieConstructor } from "../../public/types/dexie-constructor"; import { DbEvents } from "../../public/types/db-events"; //import { PromiseExtended, PromiseExtendedConstructor } from '../../public/types/promise-extended'; import { Table as ITable } from '../../public/types/table'; import { TableSchema } from "../../public/types/table-schema"; import { DbSchema } from '../../public/types/db-schema'; // Internal imports import { Table, TableConstructor, createTableConstructor } from "../table"; import { Collection, CollectionConstructor, createCollectionConstructor } from '../collection'; import { WhereClause } from '../where-clause/where-clause'; import { WhereClauseConstructor, createWhereClauseConstructor } from '../where-clause/where-clause-constructor'; import { Transaction } from '../transaction'; import { TransactionConstructor, createTransactionConstructor } from '../transaction/transaction-constructor'; import { Version } from "../version/version"; import { VersionConstructor, createVersionConstructor } from '../version/version-constructor'; // Other imports... import { DexieEventSet } from '../../public/types/dexie-event-set'; import { DexieExceptionClasses } from '../../public/types/errors'; import { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies'; import { nop, promisableChain } from '../../functions/chaining-functions'; import Promise, { PSD } from '../../helpers/promise'; import { extend, override, keys, hasOwn } from '../../functions/utils'; import Events from '../../helpers/Events'; import { maxString, connections, READONLY, READWRITE } from '../../globals/constants'; import { getMaxKey } from '../../functions/quirks'; import { exceptions } from '../../errors'; import { lowerVersionFirst } from '../version/schema-helpers'; import { dexieOpen } from './dexie-open'; import { wrap } from '../../helpers/promise'; import { _onDatabaseDeleted } from '../../helpers/database-enumerator'; import { eventRejectHandler } from '../../functions/event-wrappers'; import { extractTransactionArgs, enterTransactionScope } from './transaction-helpers'; import { TransactionMode } from '../../public/types/transaction-mode'; import { rejection } from '../../helpers/promise'; import { usePSD } from '../../helpers/promise'; import { DBCore } from '../../public/types/dbcore'; import { Middleware, DexieStacks } from '../../public/types/middleware'; import { virtualIndexMiddleware } from '../../dbcore/virtual-index-middleware'; import { hooksMiddleware } from '../../hooks/hooks-middleware'; import { IndexableType } from '../../public'; import { observabilityMiddleware } from '../../live-query/observability-middleware'; import { cacheExistingValuesMiddleware } from '../../dbcore/cache-existing-values-middleware'; export interface DbReadyState { dbOpenError: any; isBeingOpened: boolean; onReadyBeingFired: undefined | Function[]; openComplete: boolean; dbReadyResolve: () => void; dbReadyPromise: Promise<any>; cancelOpen: (reason?: Error) => void; openCanceller: Promise<any> & { _stackHolder?: Error }; autoSchema: boolean; vcFired?: boolean; PR1398_maxLoop?: number; } export class Dexie implements IDexie { _options: DexieOptions; _state: DbReadyState; _versions: Version[]; _storeNames: string[]; _deps: DexieDOMDependencies; _allTables: { [name: string]: Table; }; _createTransaction: (this: Dexie, mode: IDBTransactionMode, storeNames: ArrayLike<string>, dbschema: { [tableName: string]: TableSchema; }, parentTransaction?: Transaction) => Transaction; _dbSchema: { [tableName: string]: TableSchema; }; _hasGetAll?: boolean; _maxKey: IndexableType; _fireOnBlocked: (ev: Event) => void; _middlewares: {[StackName in keyof DexieStacks]?: Middleware<DexieStacks[StackName]>[]} = {}; _vip?: boolean; _novip: Dexie;// db._novip is to escape to orig db from db.vip. core: DBCore; name: string; verno: number = 0; idbdb: IDBDatabase | null; vip: Dexie; on: DbEvents; Table: TableConstructor; WhereClause: WhereClauseConstructor; Collection: CollectionConstructor; Version: VersionConstructor; Transaction: TransactionConstructor; constructor(name: string, options?: DexieOptions) { const deps = (Dexie as any as DexieConstructor).dependencies; this._options = options = { // Default Options addons: (Dexie as any as DexieConstructor).addons, // Pick statically registered addons by default autoOpen: true, // Don't require db.open() explicitely. // Default DOM dependency implementations from static prop. indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to browser env. IDBKeyRange: deps.IDBKeyRange, // Backend IDBKeyRange api. Default to browser env. ...options }; this._deps = { indexedDB: options.indexedDB as IDBFactory, IDBKeyRange: options.IDBKeyRange as typeof IDBKeyRange }; const { addons, } = options; this._dbSchema = {}; this._versions = []; this._storeNames = []; this._allTables = {}; this.idbdb = null; this._novip = this; const state: DbReadyState = { dbOpenError: null, isBeingOpened: false, onReadyBeingFired: null, openComplete: false, dbReadyResolve: nop, dbReadyPromise: null as Promise, cancelOpen: nop, openCanceller: null as Promise, autoSchema: true, PR1398_maxLoop: 3 }; state.dbReadyPromise = new Promise(resolve => { state.dbReadyResolve = resolve; }); state.openCanceller = new Promise((_, reject) => { state.cancelOpen = reject; }); this._state = state; this.name = name; this.on = Events(this, "populate", "blocked", "versionchange", "close", { ready: [promisableChain, nop] }) as DbEvents; this.on.ready.subscribe = override(this.on.ready.subscribe, subscribe => { return (subscriber, bSticky) => { (Dexie as any as DexieConstructor).vip(() => { const state = this._state; if (state.openComplete) { // Database already open. Call subscriber asap. if (!state.dbOpenError) Promise.resolve().then(subscriber); // bSticky: Also subscribe to future open sucesses (after close / reopen) if (bSticky) subscribe(subscriber); } else if (state.onReadyBeingFired) { // db.on('ready') subscribers are currently being executed and have not yet resolved or rejected state.onReadyBeingFired.push(subscriber); if (bSticky) subscribe(subscriber); } else { // Database not yet open. Subscribe to it. subscribe(subscriber); // If bSticky is falsy, make sure to unsubscribe subscriber when fired once. const db = this; if (!bSticky) subscribe(function unsubscribe() { db.on.ready.unsubscribe(subscriber); db.on.ready.unsubscribe(unsubscribe); }); } }); } }); // Create derived classes bound to this instance of Dexie: this.Collection = createCollectionConstructor(this); this.Table = createTableConstructor(this); this.Transaction = createTransactionConstructor(this); this.Version = createVersionConstructor(this); this.WhereClause = createWhereClauseConstructor(this); // Default subscribers to "versionchange" and "blocked". // Can be overridden by custom handlers. If custom handlers return false, these default // behaviours will be prevented. this.on("versionchange", ev => { // Default behavior for versionchange event is to close database connection. // Caller can override this behavior by doing db.on("versionchange", function(){ return false; }); // Let's not block the other window from making it's delete() or open() call. // NOTE! This event is never fired in IE,Edge or Safari. if (ev.newVersion > 0) console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`); else console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`); this.close(); // In many web applications, it would be recommended to force window.reload() // when this event occurs. To do that, subscribe to the versionchange event // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion) // The reason for this is that your current web app obviously has old schema code that needs // to be updated. Another window got a newer version of the app and needs to upgrade DB but // your window is blocking it unless we close it here. }); this.on("blocked", ev => { if (!ev.newVersion || ev.newVersion < ev.oldVersion) console.warn(`Dexie.delete('${this.name}') was blocked`); else console.warn(`Upgrade '${this.name}' blocked by other connection holding version ${ev.oldVersion / 10}`); }); this._maxKey = getMaxKey(options.IDBKeyRange as typeof IDBKeyRange); this._createTransaction = ( mode: IDBTransactionMode, storeNames: string[], dbschema: DbSchema, parentTransaction?: Transaction) => new this.Transaction(mode, storeNames, dbschema, this._options.chromeTransactionDurability, parentTransaction); this._fireOnBlocked = ev => { this.on("blocked").fire(ev); // Workaround (not fully*) for missing "versionchange" event in IE,Edge and Safari: connections .filter(c => c.name === this.name && c !== this && !c._state.vcFired) .map(c => c.on("versionchange").fire(ev)); } // Default middlewares: this.use(virtualIndexMiddleware); this.use(hooksMiddleware); this.use(observabilityMiddleware); this.use(cacheExistingValuesMiddleware); this.vip = Object.create(this, {_vip: {value: true}}) as Dexie; // Call each addon: addons.forEach(addon => addon(this)); } version(versionNumber: number): Version { if (isNaN(versionNumber) || versionNumber < 0.1) throw new exceptions.Type(`Given version is not a positive number`); versionNumber = Math.round(versionNumber * 10) / 10; if (this.idbdb || this._state.isBeingOpened) throw new exceptions.Schema("Cannot add version when database is open"); this.verno = Math.max(this.verno, versionNumber); const versions = this._versions; var versionInstance = versions.filter( v => v._cfg.version === versionNumber)[0]; if (versionInstance) return versionInstance; versionInstance = new this.Version(versionNumber); versions.push(versionInstance); versions.sort(lowerVersionFirst); versionInstance.stores({}); // Derive earlier schemas by default. // Disable autoschema mode, as at least one version is specified. this._state.autoSchema = false; return versionInstance; } _whenReady<T>(fn: () => Promise<T>): Promise<T> { return (this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new Promise<T>((resolve, reject) => { if (this._state.openComplete) { // idbdb is falsy but openComplete is true. Must have been an exception durin open. // Don't wait for openComplete as it would lead to infinite loop. return reject(new exceptions.DatabaseClosed(this._state.dbOpenError)); } if (!this._state.isBeingOpened) { if (!this._options.autoOpen) { reject(new exceptions.DatabaseClosed()); return; } this.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. } this._state.dbReadyPromise.then(resolve, reject); }).then(fn); } use({stack, create, level, name}: Middleware<DBCore>): this { if (name) this.unuse({stack, name}); // Be able to replace existing middleware. const middlewares = this._middlewares[stack] || (this._middlewares[stack] = []); middlewares.push({stack, create, level: level == null ? 10 : level, name}); middlewares.sort((a, b) => a.level - b.level); // Todo update db.core and db.tables...core ? Or should be expect this to have effect // only after next open()? return this; } unuse({stack, create}: Middleware<{stack: keyof DexieStacks}>): this; unuse({stack, name}: {stack: keyof DexieStacks, name: string}): this; unuse({stack, name, create}: {stack: keyof DexieStacks, name?: string, create?: Function}) { if (stack && this._middlewares[stack]) { this._middlewares[stack] = this._middlewares[stack].filter(mw => create ? mw.create !== create : // Given middleware has a create method. Match that exactly. name ? mw.name !== name : // Given middleware spec false); } return this; } open() { return dexieOpen(this); } _close(): void { const state = this._state; const idx = connections.indexOf(this); if (idx >= 0) connections.splice(idx, 1); if (this.idbdb) { try { this.idbdb.close(); } catch (e) { } this._novip.idbdb = null; // db._novip is because db can be an Object.create(origDb). } // Reset dbReadyPromise promise: state.dbReadyPromise = new Promise(resolve => { state.dbReadyResolve = resolve; }); state.openCanceller = new Promise((_, reject) => { state.cancelOpen = reject; }); } close(): void { this._close(); const state = this._state; this._options.autoOpen = false; state.dbOpenError = new exceptions.DatabaseClosed(); if (state.isBeingOpened) state.cancelOpen(state.dbOpenError); } delete(): Promise<void> { const hasArguments = arguments.length > 0; const state = this._state; return new Promise((resolve, reject) => { const doDelete = () => { this.close(); var req = this._deps.indexedDB.deleteDatabase(this.name); req.onsuccess = wrap(() => { _onDatabaseDeleted(this._deps, this.name); resolve(); }); req.onerror = eventRejectHandler(reject); req.onblocked = this._fireOnBlocked; } if (hasArguments) throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()"); if (state.isBeingOpened) { state.dbReadyPromise.then(doDelete); } else { doDelete(); } }); } backendDB() { return this.idbdb; } isOpen() { return this.idbdb !== null; } hasBeenClosed() { const dbOpenError = this._state.dbOpenError; return dbOpenError && (dbOpenError.name === 'DatabaseClosed'); } hasFailed() { return this._state.dbOpenError !== null; } dynamicallyOpened() { return this._state.autoSchema; } get tables () { return keys(this._allTables).map(name => this._allTables[name]); } transaction(): Promise { const args = extractTransactionArgs.apply(this, arguments); return this._transaction.apply(this, args); } _transaction(mode: TransactionMode, tables: Array<ITable | string>, scopeFunc: Function) { let parentTransaction = PSD.trans as Transaction | undefined; // Check if parent transactions is bound to this db instance, and if caller wants to reuse it if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) parentTransaction = null; const onlyIfCompatible = mode.indexOf('?') !== -1; mode = mode.replace('!', '').replace('?', '') as TransactionMode; // Ok. Will change arguments[0] as well but we wont touch arguments henceforth. let idbMode: IDBTransactionMode, storeNames; try { // // Get storeNames from arguments. Either through given table instances, or through given table names. // storeNames = tables.map(table => { var storeName = table instanceof this.Table ? table.name : table; if (typeof storeName !== 'string') throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed"); return storeName; }); // // Resolve mode. Allow shortcuts "r" and "rw". // if (mode == "r" || mode === READONLY) idbMode = READONLY; else if (mode == "rw" || mode == READWRITE) idbMode = READWRITE; else throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); if (parentTransaction) { // Basic checks if (parentTransaction.mode === READONLY && idbMode === READWRITE) { if (onlyIfCompatible) { // Spawn new transaction instead. parentTransaction = null; } else throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); } if (parentTransaction) { storeNames.forEach(storeName => { if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) { if (onlyIfCompatible) { // Spawn new transaction instead. parentTransaction = null; } else throw new exceptions.SubTransaction("Table " + storeName + " not included in parent transaction."); } }); } if (onlyIfCompatible && parentTransaction && !parentTransaction.active) { // '?' mode should not keep using an inactive transaction. parentTransaction = null; } } } catch (e) { return parentTransaction ? parentTransaction._promise(null, (_, reject) => {reject(e);}) : rejection (e); } // If this is a sub-transaction, lock the parent and then launch the sub-transaction. const enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc); return (parentTransaction ? parentTransaction._promise(idbMode, enterTransaction, "lock") : PSD.trans ? // no parent transaction despite PSD.trans exists. Make sure also // that the zone we create is not a sub-zone of current, because // Promise.follow() should not wait for it if so. usePSD(PSD.transless, ()=>this._whenReady(enterTransaction)) : this._whenReady (enterTransaction)); } table(tableName: string): Table; table<T, TKey extends IndexableType=IndexableType>(tableName: string): ITable<T, TKey>; table(tableName: string): Table { if (!hasOwn(this._allTables, tableName)) { throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); } return this._allTables[tableName]; } }
the_stack
declare module com { export module facebook { export class AccessToken { public static class: java.lang.Class<com.facebook.AccessToken>; public static ACCESS_TOKEN_KEY: string; public static EXPIRES_IN_KEY: string; public static USER_ID_KEY: string; public static DATA_ACCESS_EXPIRATION_TIME: string; public static GRAPH_DOMAIN: string; public static DEFAULT_GRAPH_DOMAIN: string; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.AccessToken>; public static Companion: com.facebook.AccessToken.Companion; public equals(param0: any): boolean; public getPermissions(): java.util.Set<string>; public isDataAccessExpired(): boolean; public isInstagramToken(): boolean; public static isLoggedInWithInstagram(): boolean; public static getPermissionsFromBundle$facebook_core_release(param0: globalAndroid.os.Bundle, param1: string): java.util.List<string>; public constructor(param0: string, param1: string, param2: string, param3: java.util.Collection<string>, param4: java.util.Collection<string>, param5: java.util.Collection<string>, param6: com.facebook.AccessTokenSource, param7: java.util.Date, param8: java.util.Date, param9: java.util.Date, param10: string); public static refreshCurrentAccessTokenAsync(): void; public static createFromRefresh$facebook_core_release(param0: com.facebook.AccessToken, param1: globalAndroid.os.Bundle): com.facebook.AccessToken; public getExpires(): java.util.Date; public getUserId(): string; public isExpired(): boolean; public static isCurrentAccessTokenActive(): boolean; public static createFromNativeLinkingIntent(param0: globalAndroid.content.Intent, param1: string, param2: com.facebook.AccessToken.AccessTokenCreationCallback): void; public static createFromJSONObject$facebook_core_release(param0: org.json.JSONObject): com.facebook.AccessToken; public getDeclinedPermissions(): java.util.Set<string>; public getGraphDomain(): string; public constructor(param0: string, param1: string, param2: string, param3: java.util.Collection<string>, param4: java.util.Collection<string>, param5: java.util.Collection<string>, param6: com.facebook.AccessTokenSource, param7: java.util.Date, param8: java.util.Date, param9: java.util.Date); public getToken(): string; public getExpiredPermissions(): java.util.Set<string>; public getApplicationId(): string; public static isDataAccessActive(): boolean; public static refreshCurrentAccessTokenAsync(param0: com.facebook.AccessToken.AccessTokenRefreshCallback): void; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: globalAndroid.os.Parcel); public static createFromLegacyCache$facebook_core_release(param0: globalAndroid.os.Bundle): com.facebook.AccessToken; public toJSONObject$facebook_core_release(): org.json.JSONObject; public toString(): string; public getSource(): com.facebook.AccessTokenSource; public getLastRefresh(): java.util.Date; public describeContents(): number; public static getCurrentAccessToken(): com.facebook.AccessToken; public static expireCurrentAccessToken(): void; public getDataAccessExpirationTime(): java.util.Date; public hashCode(): number; public static setCurrentAccessToken(param0: com.facebook.AccessToken): void; } export module AccessToken { export class AccessTokenCreationCallback { public static class: java.lang.Class<com.facebook.AccessToken.AccessTokenCreationCallback>; /** * Constructs a new instance of the com.facebook.AccessToken$AccessTokenCreationCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onSuccess(param0: com.facebook.AccessToken): void; onError(param0: com.facebook.FacebookException): void; }); public constructor(); public onSuccess(param0: com.facebook.AccessToken): void; public onError(param0: com.facebook.FacebookException): void; } export class AccessTokenRefreshCallback { public static class: java.lang.Class<com.facebook.AccessToken.AccessTokenRefreshCallback>; /** * Constructs a new instance of the com.facebook.AccessToken$AccessTokenRefreshCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { OnTokenRefreshed(param0: com.facebook.AccessToken): void; OnTokenRefreshFailed(param0: com.facebook.FacebookException): void; }); public constructor(); public OnTokenRefreshFailed(param0: com.facebook.FacebookException): void; public OnTokenRefreshed(param0: com.facebook.AccessToken): void; } export class Companion { public static class: java.lang.Class<com.facebook.AccessToken.Companion>; public refreshCurrentAccessTokenAsync(): void; public isDataAccessActive(): boolean; public getPermissionsFromBundle$facebook_core_release(param0: globalAndroid.os.Bundle, param1: string): java.util.List<string>; public setCurrentAccessToken(param0: com.facebook.AccessToken): void; public isLoggedInWithInstagram(): boolean; public createFromJSONObject$facebook_core_release(param0: org.json.JSONObject): com.facebook.AccessToken; public expireCurrentAccessToken(): void; public createFromNativeLinkingIntent(param0: globalAndroid.content.Intent, param1: string, param2: com.facebook.AccessToken.AccessTokenCreationCallback): void; public createExpired$facebook_core_release(param0: com.facebook.AccessToken): com.facebook.AccessToken; public createFromRefresh$facebook_core_release(param0: com.facebook.AccessToken, param1: globalAndroid.os.Bundle): com.facebook.AccessToken; public getCurrentAccessToken(): com.facebook.AccessToken; public isCurrentAccessTokenActive(): boolean; public refreshCurrentAccessTokenAsync(param0: com.facebook.AccessToken.AccessTokenRefreshCallback): void; public createFromLegacyCache$facebook_core_release(param0: globalAndroid.os.Bundle): com.facebook.AccessToken; } export class WhenMappings { public static class: java.lang.Class<com.facebook.AccessToken.WhenMappings>; } } } } declare module com { export module facebook { export class AccessTokenCache { public static class: java.lang.Class<com.facebook.AccessTokenCache>; public static CACHED_ACCESS_TOKEN_KEY: string; public static Companion: com.facebook.AccessTokenCache.Companion; public clear(): void; public constructor(); public load(): com.facebook.AccessToken; public save(param0: com.facebook.AccessToken): void; public constructor(param0: globalAndroid.content.SharedPreferences, param1: com.facebook.AccessTokenCache.SharedPreferencesTokenCachingStrategyFactory); } export module AccessTokenCache { export class Companion { public static class: java.lang.Class<com.facebook.AccessTokenCache.Companion>; } export class SharedPreferencesTokenCachingStrategyFactory { public static class: java.lang.Class<com.facebook.AccessTokenCache.SharedPreferencesTokenCachingStrategyFactory>; public create(): com.facebook.LegacyTokenHelper; public constructor(); } } } } declare module com { export module facebook { export class AccessTokenManager { public static class: java.lang.Class<com.facebook.AccessTokenManager>; public static TAG: string; public static ACTION_CURRENT_ACCESS_TOKEN_CHANGED: string; public static EXTRA_OLD_ACCESS_TOKEN: string; public static EXTRA_NEW_ACCESS_TOKEN: string; public static SHARED_PREFERENCES_NAME: string; public static Companion: com.facebook.AccessTokenManager.Companion; public loadCurrentAccessToken(): boolean; public currentAccessTokenChanged(): void; public constructor(param0: androidx.localbroadcastmanager.content.LocalBroadcastManager, param1: com.facebook.AccessTokenCache); public getCurrentAccessToken(): com.facebook.AccessToken; public setCurrentAccessToken(param0: com.facebook.AccessToken): void; public static getInstance(): com.facebook.AccessTokenManager; public extendAccessTokenIfNeeded(): void; public refreshCurrentAccessToken(param0: com.facebook.AccessToken.AccessTokenRefreshCallback): void; } export module AccessTokenManager { export class Companion { public static class: java.lang.Class<com.facebook.AccessTokenManager.Companion>; public getInstance(): com.facebook.AccessTokenManager; } export class FacebookRefreshTokenInfo extends com.facebook.AccessTokenManager.RefreshTokenInfo { public static class: java.lang.Class<com.facebook.AccessTokenManager.FacebookRefreshTokenInfo>; public getGrantType(): string; public getGraphPath(): string; public constructor(); } export class InstagramRefreshTokenInfo extends com.facebook.AccessTokenManager.RefreshTokenInfo { public static class: java.lang.Class<com.facebook.AccessTokenManager.InstagramRefreshTokenInfo>; public getGrantType(): string; public getGraphPath(): string; public constructor(); } export class RefreshResult { public static class: java.lang.Class<com.facebook.AccessTokenManager.RefreshResult>; public getExpiresAt(): number; public getExpiresIn(): number; public setAccessToken(param0: string): void; public getGraphDomain(): string; public setExpiresAt(param0: number): void; public getAccessToken(): string; public setDataAccessExpirationTime(param0: java.lang.Long): void; public setExpiresIn(param0: number): void; public getDataAccessExpirationTime(): java.lang.Long; public setGraphDomain(param0: string): void; public constructor(); } export class RefreshTokenInfo { public static class: java.lang.Class<com.facebook.AccessTokenManager.RefreshTokenInfo>; /** * Constructs a new instance of the com.facebook.AccessTokenManager$RefreshTokenInfo interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getGraphPath(): string; getGrantType(): string; }); public constructor(); public getGrantType(): string; public getGraphPath(): string; } } } } declare module com { export module facebook { export class AccessTokenSource { public static class: java.lang.Class<com.facebook.AccessTokenSource>; public static NONE: com.facebook.AccessTokenSource; public static FACEBOOK_APPLICATION_WEB: com.facebook.AccessTokenSource; public static FACEBOOK_APPLICATION_NATIVE: com.facebook.AccessTokenSource; public static FACEBOOK_APPLICATION_SERVICE: com.facebook.AccessTokenSource; public static WEB_VIEW: com.facebook.AccessTokenSource; public static CHROME_CUSTOM_TAB: com.facebook.AccessTokenSource; public static TEST_USER: com.facebook.AccessTokenSource; public static CLIENT_TOKEN: com.facebook.AccessTokenSource; public static DEVICE_AUTH: com.facebook.AccessTokenSource; public static INSTAGRAM_APPLICATION_WEB: com.facebook.AccessTokenSource; public static INSTAGRAM_CUSTOM_CHROME_TAB: com.facebook.AccessTokenSource; public static INSTAGRAM_WEB_VIEW: com.facebook.AccessTokenSource; public static values(): androidNative.Array<com.facebook.AccessTokenSource>; public static valueOf(param0: string): com.facebook.AccessTokenSource; public fromInstagram(): boolean; public canExtendToken(): boolean; } export module AccessTokenSource { export class WhenMappings { public static class: java.lang.Class<com.facebook.AccessTokenSource.WhenMappings>; } } } } declare module com { export module facebook { export abstract class AccessTokenTracker { public static class: java.lang.Class<com.facebook.AccessTokenTracker>; public onCurrentAccessTokenChanged(param0: com.facebook.AccessToken, param1: com.facebook.AccessToken): void; public startTracking(): void; public stopTracking(): void; public constructor(); public isTracking(): boolean; } export module AccessTokenTracker { export class CurrentAccessTokenBroadcastReceiver { public static class: java.lang.Class<com.facebook.AccessTokenTracker.CurrentAccessTokenBroadcastReceiver>; public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void; } } } } declare module com { export module facebook { export class AuthenticationToken { public static class: java.lang.Class<com.facebook.AuthenticationToken>; public static AUTHENTICATION_TOKEN_KEY: string; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.AuthenticationToken>; public static Companion: com.facebook.AuthenticationToken.Companion; public constructor(param0: string, param1: string); public equals(param0: any): boolean; public getHeader(): com.facebook.AuthenticationTokenHeader; public getToken(): string; public describeContents(): number; public getSignature(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: globalAndroid.os.Parcel); public getExpectedNonce(): string; public getClaims(): com.facebook.AuthenticationTokenClaims; public hashCode(): number; } export module AuthenticationToken { export class Companion { public static class: java.lang.Class<com.facebook.AuthenticationToken.Companion>; } } } } declare module com { export module facebook { export class AuthenticationTokenCache { public static class: java.lang.Class<com.facebook.AuthenticationTokenCache>; public static CACHED_AUTHENTICATION_TOKEN_KEY: string; public static CACHED_AUTHENTICATION_TOKEN_NONCE_KEY: string; public static Companion: com.facebook.AuthenticationTokenCache.Companion; public save(param0: com.facebook.AuthenticationToken): void; public clear(): void; public load(): com.facebook.AuthenticationToken; public constructor(param0: globalAndroid.content.SharedPreferences); public constructor(); } export module AuthenticationTokenCache { export class Companion { public static class: java.lang.Class<com.facebook.AuthenticationTokenCache.Companion>; } } } } declare module com { export module facebook { export class AuthenticationTokenClaims { public static class: java.lang.Class<com.facebook.AuthenticationTokenClaims>; public static MAX_TIME_SINCE_TOKEN_ISSUED: number; public static JSON_KEY_JIT: string; public static JSON_KEY_ISS: string; public static JSON_KEY_AUD: string; public static JSON_KEY_NONCE: string; public static JSON_KEY_EXP: string; public static JSON_KEY_IAT: string; public static JSON_KEY_SUB: string; public static JSON_KEY_NAME: string; public static JSON_KEY_GIVEN_NAME: string; public static JSON_KEY_MIDDLE_NAME: string; public static JSON_KEY_FAMILY_NAME: string; public static JSON_KEY_EMAIL: string; public static JSON_KEY_PICTURE: string; public static JSON_KEY_USER_FRIENDS: string; public static JSON_KEY_USER_BIRTHDAY: string; public static JSON_KEY_USER_AGE_RANGE: string; public static JSON_KEY_USER_HOMETOWN: string; public static JSON_KEY_USER_GENDER: string; public static JSON_KEY_USER_LINK: string; public static JSON_KEY_USER_LOCATION: string; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.AuthenticationTokenClaims>; public static Companion: com.facebook.AuthenticationTokenClaims.Companion; public getNonce(): string; public equals(param0: any): boolean; public getFamilyName(): string; public getJti(): string; public getPicture(): string; public constructor(param0: string, param1: string, param2: string, param3: string, param4: number, param5: number, param6: string); public getUserHometown(): java.util.Map<string,string>; public constructor(param0: string, param1: string); public constructor(param0: string, param1: string, param2: string, param3: string, param4: number, param5: number, param6: string, param7: string, param8: string, param9: string, param10: string, param11: string, param12: string); public getExp(): number; public constructor(param0: string, param1: string, param2: string, param3: string, param4: number, param5: number, param6: string, param7: string, param8: string, param9: string, param10: string, param11: string, param12: string, param13: java.util.Collection<string>, param14: string); public getUserAgeRange(): java.util.Map<string,java.lang.Integer>; public constructor(param0: string, param1: string, param2: string, param3: string, param4: number, param5: number, param6: string, param7: string, param8: string, param9: string, param10: string, param11: string); public getAud(): string; public constructor(param0: string, param1: string, param2: string, param3: string, param4: number, param5: number, param6: string, param7: string, param8: string, param9: string, param10: string, param11: string, param12: string, param13: java.util.Collection<string>); public constructor(param0: string, param1: string, param2: string, param3: string, param4: number, param5: number, param6: string, param7: string, param8: string, param9: string, param10: string, param11: string, param12: string, param13: java.util.Collection<string>, param14: string, param15: java.util.Map<string,java.lang.Integer>, param16: java.util.Map<string,string>, param17: java.util.Map<string,string>, param18: string); public constructor(param0: string, param1: string, param2: string, param3: string, param4: number, param5: number, param6: string, param7: string, param8: string, param9: string, param10: string, param11: string, param12: string, param13: java.util.Collection<string>, param14: string, param15: java.util.Map<string,java.lang.Integer>); public constructor(param0: string, param1: string, param2: string, param3: string, param4: number, param5: number, param6: string, param7: string); public getUserLocation(): java.util.Map<string,string>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: globalAndroid.os.Parcel); public getUserBirthday(): string; public getUserLink(): string; public constructor(param0: string, param1: string, param2: string, param3: string, param4: number, param5: number, param6: string, param7: string, param8: string); public toJSONObject$facebook_core_release(): org.json.JSONObject; public toString(): string; public getName(): string; public getMiddleName(): string; public constructor(param0: string, param1: string, param2: string, param3: string, param4: number, param5: number, param6: string, param7: string, param8: string, param9: string, param10: string, param11: string, param12: string, param13: java.util.Collection<string>, param14: string, param15: java.util.Map<string,java.lang.Integer>, param16: java.util.Map<string,string>, param17: java.util.Map<string,string>); public constructor(param0: string, param1: string, param2: string, param3: string, param4: number, param5: number, param6: string, param7: string, param8: string, param9: string); public constructor(param0: string, param1: string, param2: string, param3: string, param4: number, param5: number, param6: string, param7: string, param8: string, param9: string, param10: string, param11: string, param12: string, param13: java.util.Collection<string>, param14: string, param15: java.util.Map<string,java.lang.Integer>, param16: java.util.Map<string,string>); public getIat(): number; public getSub(): string; public describeContents(): number; public getGivenName(): string; public getIss(): string; public toEnCodedString(): string; public constructor(param0: string, param1: string, param2: string, param3: string, param4: number, param5: number, param6: string, param7: string, param8: string, param9: string, param10: string, param11: string, param12: string, param13: java.util.Collection<string>, param14: string, param15: java.util.Map<string,java.lang.Integer>, param16: java.util.Map<string,string>, param17: java.util.Map<string,string>, param18: string, param19: string); public getUserGender(): string; public getUserFriends(): java.util.Set<string>; public getEmail(): string; public hashCode(): number; public constructor(param0: string, param1: string, param2: string, param3: string, param4: number, param5: number, param6: string, param7: string, param8: string, param9: string, param10: string); } export module AuthenticationTokenClaims { export class Companion { public static class: java.lang.Class<com.facebook.AuthenticationTokenClaims.Companion>; public getNullableString$facebook_core_release(param0: org.json.JSONObject, param1: string): string; public createFromJSONObject$facebook_core_release(param0: org.json.JSONObject): com.facebook.AuthenticationTokenClaims; } } } } declare module com { export module facebook { export class AuthenticationTokenHeader { public static class: java.lang.Class<com.facebook.AuthenticationTokenHeader>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.AuthenticationTokenHeader>; public static Companion: com.facebook.AuthenticationTokenHeader.Companion; public equals(param0: any): boolean; public getKid(): string; public constructor(param0: string, param1: string, param2: string); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: globalAndroid.os.Parcel); public getAlg(): string; public toJSONObject$facebook_core_release(): org.json.JSONObject; public toString(): string; public describeContents(): number; public toEnCodedString(): string; public getTyp(): string; public constructor(param0: string); public hashCode(): number; } export module AuthenticationTokenHeader { export class Companion { public static class: java.lang.Class<com.facebook.AuthenticationTokenHeader.Companion>; } } } } declare module com { export module facebook { export class AuthenticationTokenManager { public static class: java.lang.Class<com.facebook.AuthenticationTokenManager>; public static TAG: string; public static ACTION_CURRENT_AUTHENTICATION_TOKEN_CHANGED: string; public static EXTRA_OLD_AUTHENTICATION_TOKEN: string; public static EXTRA_NEW_AUTHENTICATION_TOKEN: string; public static SHARED_PREFERENCES_NAME: string; public static Companion: com.facebook.AuthenticationTokenManager.Companion; public static getInstance(): com.facebook.AuthenticationTokenManager; public getCurrentAuthenticationToken(): com.facebook.AuthenticationToken; public setCurrentAuthenticationToken(param0: com.facebook.AuthenticationToken): void; public loadCurrentAuthenticationToken(): boolean; public constructor(param0: androidx.localbroadcastmanager.content.LocalBroadcastManager, param1: com.facebook.AuthenticationTokenCache); public currentAuthenticationTokenChanged(): void; } export module AuthenticationTokenManager { export class Companion { public static class: java.lang.Class<com.facebook.AuthenticationTokenManager.Companion>; public getInstance(): com.facebook.AuthenticationTokenManager; } export class CurrentAuthenticationTokenChangedBroadcastReceiver { public static class: java.lang.Class<com.facebook.AuthenticationTokenManager.CurrentAuthenticationTokenChangedBroadcastReceiver>; public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void; public constructor(); } } } } declare module com { export module facebook { export class CallbackManager { public static class: java.lang.Class<com.facebook.CallbackManager>; /** * Constructs a new instance of the com.facebook.CallbackManager interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): boolean; }); public constructor(); public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): boolean; } export module CallbackManager { export class Factory { public static class: java.lang.Class<com.facebook.CallbackManager.Factory>; public static INSTANCE: com.facebook.CallbackManager.Factory; public static create(): com.facebook.CallbackManager; } } } } declare module com { export module facebook { export class CurrentAccessTokenExpirationBroadcastReceiver { public static class: java.lang.Class<com.facebook.CurrentAccessTokenExpirationBroadcastReceiver>; public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void; public constructor(); } } } declare module com { export module facebook { export class CustomTabActivity { public static class: java.lang.Class<com.facebook.CustomTabActivity>; public static CUSTOM_TAB_REDIRECT_ACTION: string; public static DESTROY_ACTION: string; public onCreate(param0: globalAndroid.os.Bundle): void; public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): void; public constructor(); public onDestroy(): void; } } } declare module com { export module facebook { export class CustomTabMainActivity { public static class: java.lang.Class<com.facebook.CustomTabMainActivity>; public static EXTRA_ACTION: string; public static EXTRA_PARAMS: string; public static EXTRA_CHROME_PACKAGE: string; public static EXTRA_URL: string; public static EXTRA_TARGET_APP: string; public static REFRESH_ACTION: string; public static NO_ACTIVITY_EXCEPTION: string; public onResume(): void; public onCreate(param0: globalAndroid.os.Bundle): void; public constructor(); public onNewIntent(param0: globalAndroid.content.Intent): void; } } } declare module com { export module facebook { export class FacebookActivity { public static class: java.lang.Class<com.facebook.FacebookActivity>; public static PASS_THROUGH_CANCEL_ACTION: string; public getFragment(): androidx.fragment.app.Fragment; public onCreate(param0: globalAndroid.os.Bundle): void; public onConfigurationChanged(param0: globalAndroid.content.res.Configuration): void; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: androidNative.Array<string>): void; public constructor(); public getCurrentFragment(): androidx.fragment.app.Fragment; } } } declare module com { export module facebook { export class FacebookAuthorizationException extends com.facebook.FacebookException { public static class: java.lang.Class<com.facebook.FacebookAuthorizationException>; public constructor(param0: java.lang.Throwable); public constructor(param0: string, param1: java.lang.Throwable); public constructor(); public constructor(param0: string); public constructor(param0: string, param1: androidNative.Array<any>); } } } declare module com { export module facebook { export class FacebookBroadcastReceiver { public static class: java.lang.Class<com.facebook.FacebookBroadcastReceiver>; public onFailedAppCall(param0: string, param1: string, param2: globalAndroid.os.Bundle): void; public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void; public constructor(); public onSuccessfulAppCall(param0: string, param1: string, param2: globalAndroid.os.Bundle): void; } } } declare module com { export module facebook { export abstract class FacebookButtonBase { public static class: java.lang.Class<com.facebook.FacebookButtonBase>; public getAndroidxActivityResultRegistryOwner(): androidx.activity.result.ActivityResultRegistryOwner; public getFragment(): androidx.fragment.app.Fragment; public getCompoundPaddingLeft(): number; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet, param2: number, param3: number, param4: string, param5: string); public getRequestCode(): number; public onDraw(param0: globalAndroid.graphics.Canvas): void; public getCompoundPaddingRight(): number; public configureButton(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet, param2: number, param3: number): void; public measureTextWidth(param0: string): number; public setFragment(param0: androidx.fragment.app.Fragment): void; public getDefaultRequestCode(): number; public getActivity(): globalAndroid.app.Activity; public setInternalOnClickListener(param0: globalAndroid.view.View.OnClickListener): void; public getNativeFragment(): globalAndroid.app.Fragment; public setOnClickListener(param0: globalAndroid.view.View.OnClickListener): void; public setFragment(param0: globalAndroid.app.Fragment): void; public callExternalOnClickListener(param0: globalAndroid.view.View): void; public onAttachedToWindow(): void; public getDefaultStyleResource(): number; } } } declare module com { export module facebook { export class FacebookCallback<RESULT> extends java.lang.Object { public static class: java.lang.Class<com.facebook.FacebookCallback<any>>; /** * Constructs a new instance of the com.facebook.FacebookCallback<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onSuccess(param0: RESULT): void; onCancel(): void; onError(param0: com.facebook.FacebookException): void; }); public constructor(); public onCancel(): void; public onSuccess(param0: RESULT): void; public onError(param0: com.facebook.FacebookException): void; } } } declare module com { export module facebook { export class FacebookContentProvider { public static class: java.lang.Class<com.facebook.FacebookContentProvider>; public static Companion: com.facebook.FacebookContentProvider.Companion; public onCreate(): boolean; public update(param0: globalAndroid.net.Uri, param1: globalAndroid.content.ContentValues, param2: string, param3: androidNative.Array<string>): number; public openFile(param0: globalAndroid.net.Uri, param1: string): globalAndroid.os.ParcelFileDescriptor; public delete(param0: globalAndroid.net.Uri, param1: string, param2: androidNative.Array<string>): number; public constructor(); public insert(param0: globalAndroid.net.Uri, param1: globalAndroid.content.ContentValues): globalAndroid.net.Uri; public static getAttachmentUrl(param0: string, param1: java.util.UUID, param2: string): string; public query(param0: globalAndroid.net.Uri, param1: androidNative.Array<string>, param2: string, param3: androidNative.Array<string>, param4: string): globalAndroid.database.Cursor; public getType(param0: globalAndroid.net.Uri): string; } export module FacebookContentProvider { export class Companion { public static class: java.lang.Class<com.facebook.FacebookContentProvider.Companion>; public getAttachmentUrl(param0: string, param1: java.util.UUID, param2: string): string; } } } } declare module com { export module facebook { export class FacebookDialog<CONTENT, RESULT> extends java.lang.Object { public static class: java.lang.Class<com.facebook.FacebookDialog<any,any>>; /** * Constructs a new instance of the com.facebook.FacebookDialog<any,any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { canShow(param0: CONTENT): boolean; show(param0: CONTENT): void; registerCallback(param0: com.facebook.CallbackManager, param1: com.facebook.FacebookCallback<RESULT>): void; registerCallback(param0: com.facebook.CallbackManager, param1: com.facebook.FacebookCallback<RESULT>, param2: number): void; }); public constructor(); public registerCallback(param0: com.facebook.CallbackManager, param1: com.facebook.FacebookCallback<RESULT>, param2: number): void; public canShow(param0: CONTENT): boolean; public show(param0: CONTENT): void; public registerCallback(param0: com.facebook.CallbackManager, param1: com.facebook.FacebookCallback<RESULT>): void; } } } declare module com { export module facebook { export class FacebookDialogException extends com.facebook.FacebookException { public static class: java.lang.Class<com.facebook.FacebookDialogException>; public constructor(param0: string, param1: number, param2: string); public getErrorCode(): number; public toString(): string; public constructor(param0: java.lang.Throwable); public constructor(param0: string, param1: java.lang.Throwable); public getFailingUrl(): string; public constructor(); public constructor(param0: string); public constructor(param0: string, param1: androidNative.Array<any>); } } } declare module com { export module facebook { export class FacebookException { public static class: java.lang.Class<com.facebook.FacebookException>; public static serialVersionUID: number; public static Companion: com.facebook.FacebookException.Companion; public toString(): string; public constructor(param0: java.lang.Throwable); public constructor(param0: string, param1: java.lang.Throwable); public constructor(); public constructor(param0: string); public constructor(param0: string, param1: androidNative.Array<any>); } export module FacebookException { export class Companion { public static class: java.lang.Class<com.facebook.FacebookException.Companion>; } } } } declare module com { export module facebook { export class FacebookGraphResponseException extends com.facebook.FacebookException { public static class: java.lang.Class<com.facebook.FacebookGraphResponseException>; public toString(): string; public constructor(param0: com.facebook.GraphResponse, param1: string); public constructor(param0: java.lang.Throwable); public constructor(param0: string, param1: java.lang.Throwable); public constructor(); public constructor(param0: string); public getGraphResponse(): com.facebook.GraphResponse; public constructor(param0: string, param1: androidNative.Array<any>); } } } declare module com { export module facebook { export class FacebookOperationCanceledException extends com.facebook.FacebookException { public static class: java.lang.Class<com.facebook.FacebookOperationCanceledException>; public static serialVersionUID: number; public static Companion: com.facebook.FacebookOperationCanceledException.Companion; public constructor(param0: java.lang.Throwable); public constructor(param0: string, param1: java.lang.Throwable); public constructor(); public constructor(param0: string); public constructor(param0: string, param1: androidNative.Array<any>); } export module FacebookOperationCanceledException { export class Companion { public static class: java.lang.Class<com.facebook.FacebookOperationCanceledException.Companion>; } } } } declare module com { export module facebook { export class FacebookRequestError { public static class: java.lang.Class<com.facebook.FacebookRequestError>; public static INVALID_ERROR_CODE: number; public static INVALID_HTTP_STATUS_CODE: number; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.FacebookRequestError>; public static Companion: com.facebook.FacebookRequestError.Companion; public constructor(param0: number, param1: string, param2: string); public getErrorCode(): number; public getCategory(): com.facebook.FacebookRequestError.Category; public getConnection(): java.net.HttpURLConnection; public getErrorUserMessage(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public static checkResponseAndCreateError(param0: org.json.JSONObject, param1: any, param2: java.net.HttpURLConnection): com.facebook.FacebookRequestError; public getBatchRequestResult(): any; public getRequestResult(): org.json.JSONObject; public constructor(param0: java.net.HttpURLConnection, param1: java.lang.Exception); public getSubErrorCode(): number; public static getErrorClassification(): com.facebook.internal.FacebookRequestErrorClassification; public getErrorMessage(): string; public toString(): string; public describeContents(): number; public getErrorRecoveryMessage(): string; public getErrorType(): string; public getErrorUserTitle(): string; public getRequestStatusCode(): number; public getRequestResultBody(): org.json.JSONObject; public getException(): com.facebook.FacebookException; } export module FacebookRequestError { export class Category { public static class: java.lang.Class<com.facebook.FacebookRequestError.Category>; public static LOGIN_RECOVERABLE: com.facebook.FacebookRequestError.Category; public static OTHER: com.facebook.FacebookRequestError.Category; public static TRANSIENT: com.facebook.FacebookRequestError.Category; public static values(): androidNative.Array<com.facebook.FacebookRequestError.Category>; public static valueOf(param0: string): com.facebook.FacebookRequestError.Category; } export class Companion { public static class: java.lang.Class<com.facebook.FacebookRequestError.Companion>; public getErrorClassification(): com.facebook.internal.FacebookRequestErrorClassification; public checkResponseAndCreateError(param0: org.json.JSONObject, param1: any, param2: java.net.HttpURLConnection): com.facebook.FacebookRequestError; public getHTTP_RANGE_SUCCESS$facebook_core_release(): com.facebook.FacebookRequestError.Range; } export class Range { public static class: java.lang.Class<com.facebook.FacebookRequestError.Range>; public constructor(param0: number, param1: number); public contains(param0: number): boolean; } } } } declare module com { export module facebook { export class FacebookSdk { public static class: java.lang.Class<com.facebook.FacebookSdk>; public static CALLBACK_OFFSET_CHANGED_AFTER_INIT: string; public static CALLBACK_OFFSET_NEGATIVE: string; public static APP_EVENT_PREFERENCES: string; public static DATA_PROCESSING_OPTIONS_PREFERENCES: string; public static APPLICATION_ID_PROPERTY: string; public static APPLICATION_NAME_PROPERTY: string; public static CLIENT_TOKEN_PROPERTY: string; public static WEB_DIALOG_THEME: string; public static AUTO_INIT_ENABLED_PROPERTY: string; public static AUTO_LOG_APP_EVENTS_ENABLED_PROPERTY: string; public static CODELESS_DEBUG_LOG_ENABLED_PROPERTY: string; public static ADVERTISER_ID_COLLECTION_ENABLED_PROPERTY: string; public static CALLBACK_OFFSET_PROPERTY: string; public static MONITOR_ENABLED_PROPERTY: string; public static DATA_PROCESSION_OPTIONS: string; public static DATA_PROCESSION_OPTIONS_COUNTRY: string; public static DATA_PROCESSION_OPTIONS_STATE: string; public static hasCustomTabsPrefetching: boolean; public static ignoreAppSwitchToLoggedOut: boolean; public static bypassAppSwitch: boolean; public static INSTAGRAM: string; public static GAMING: string; public static FACEBOOK_COM: string; public static FB_GG: string; public static INSTAGRAM_COM: string; public static INSTANCE: com.facebook.FacebookSdk; /** @deprecated */ public static sdkInitialize(param0: globalAndroid.content.Context, param1: number): void; public static publishInstallAsync(param0: globalAndroid.content.Context, param1: string): void; public static setFacebookDomain(param0: string): void; public static getCodelessDebugLogEnabled(): boolean; public static clearLoggingBehaviors(): void; public static getApplicationSignature(param0: globalAndroid.content.Context): string; public static getInstagramDomain(): string; public static setExecutor(param0: java.util.concurrent.Executor): void; public static setApplicationName(param0: string): void; public static getCodelessSetupEnabled(): boolean; public static setAutoLogAppEventsEnabled(param0: boolean): void; public static setOnProgressThreshold(param0: number): void; public static isInitialized(): boolean; public static setLegacyTokenUpgradeSupported(param0: boolean): void; public static setDataProcessingOptions(param0: androidNative.Array<string>): void; public static getApplicationId(): string; public static setDataProcessingOptions(param0: androidNative.Array<string>, param1: number, param2: number): void; public static setAutoInitEnabled(param0: boolean): void; public static setAdvertiserIDCollectionEnabled(param0: boolean): void; public static addLoggingBehavior(param0: com.facebook.LoggingBehavior): void; public static getAutoInitEnabled(): boolean; public static setCodelessDebugLogEnabled(param0: boolean): void; public static setMonitorEnabled(param0: boolean): void; public static loadDefaultsFromMetadata$facebook_core_release(param0: globalAndroid.content.Context): void; public static getAutoLogAppEventsEnabled(): boolean; public static fullyInitialize(): void; public static setCacheDir(param0: java.io.File): void; /** @deprecated */ public static sdkInitialize(param0: globalAndroid.content.Context): void; /** @deprecated */ public static sdkInitialize(param0: globalAndroid.content.Context, param1: com.facebook.FacebookSdk.InitializeCallback): void; public static setLimitEventAndDataUsage(param0: globalAndroid.content.Context, param1: boolean): void; public static getExecutor(): java.util.concurrent.Executor; public static isDebugEnabled(): boolean; public static setIsDebugEnabled(param0: boolean): void; public static getGraphApiVersion(): string; public static getAdvertiserIDCollectionEnabled(): boolean; /** @deprecated */ public static sdkInitialize(param0: globalAndroid.content.Context, param1: number, param2: com.facebook.FacebookSdk.InitializeCallback): void; public static isFullyInitialized(): boolean; public static getCallbackRequestCodeOffset(): number; public static isFacebookRequestCode(param0: number): boolean; public static getOnProgressThreshold(): number; public static setGraphApiVersion(param0: string): void; public static getGraphDomain(): string; public static getLimitEventAndDataUsage(param0: globalAndroid.content.Context): boolean; public static getApplicationContext(): globalAndroid.content.Context; public static getLoggingBehaviors(): java.util.Set<com.facebook.LoggingBehavior>; public static getApplicationName(): string; public static getMonitorEnabled(): boolean; public static setGraphRequestCreator$facebook_core_release(param0: com.facebook.FacebookSdk.GraphRequestCreator): void; public static getFacebookDomain(): string; public static setApplicationId(param0: string): void; public static getClientToken(): string; public static setClientToken(param0: string): void; public static getCacheDir(): java.io.File; public static isLoggingBehaviorEnabled(param0: com.facebook.LoggingBehavior): boolean; public static getSdkVersion(): string; public static isLegacyTokenUpgradeSupported(): boolean; public static removeLoggingBehavior(param0: com.facebook.LoggingBehavior): void; } export module FacebookSdk { export class GraphRequestCreator { public static class: java.lang.Class<com.facebook.FacebookSdk.GraphRequestCreator>; /** * Constructs a new instance of the com.facebook.FacebookSdk$GraphRequestCreator interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { createPostRequest(param0: com.facebook.AccessToken, param1: string, param2: org.json.JSONObject, param3: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; }); public constructor(); public createPostRequest(param0: com.facebook.AccessToken, param1: string, param2: org.json.JSONObject, param3: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; } export class InitializeCallback { public static class: java.lang.Class<com.facebook.FacebookSdk.InitializeCallback>; /** * Constructs a new instance of the com.facebook.FacebookSdk$InitializeCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onInitialized(): void; }); public constructor(); public onInitialized(): void; } } } } declare module com { export module facebook { export class FacebookSdkNotInitializedException extends com.facebook.FacebookException { public static class: java.lang.Class<com.facebook.FacebookSdkNotInitializedException>; public static serialVersionUID: number; public static Companion: com.facebook.FacebookSdkNotInitializedException.Companion; public constructor(param0: java.lang.Throwable); public constructor(param0: string, param1: java.lang.Throwable); public constructor(); public constructor(param0: string); public constructor(param0: string, param1: androidNative.Array<any>); } export module FacebookSdkNotInitializedException { export class Companion { public static class: java.lang.Class<com.facebook.FacebookSdkNotInitializedException.Companion>; } } } } declare module com { export module facebook { export class FacebookSdkVersion { public static class: java.lang.Class<com.facebook.FacebookSdkVersion>; public static BUILD: string; public static INSTANCE: com.facebook.FacebookSdkVersion; } } } declare module com { export module facebook { export class FacebookServiceException extends com.facebook.FacebookException { public static class: java.lang.Class<com.facebook.FacebookServiceException>; public static Companion: com.facebook.FacebookServiceException.Companion; public toString(): string; public constructor(param0: com.facebook.FacebookRequestError, param1: string); public constructor(param0: java.lang.Throwable); public constructor(param0: string, param1: java.lang.Throwable); public constructor(); public constructor(param0: string); public getRequestError(): com.facebook.FacebookRequestError; public constructor(param0: string, param1: androidNative.Array<any>); } export module FacebookServiceException { export class Companion { public static class: java.lang.Class<com.facebook.FacebookServiceException.Companion>; } } } } declare module com { export module facebook { export class GraphRequest { public static class: java.lang.Class<com.facebook.GraphRequest>; public static MAXIMUM_BATCH_SIZE: number; public static TAG: string; public static ACCESS_TOKEN_PARAM: string; public static FIELDS_PARAM: string; public static Companion: com.facebook.GraphRequest.Companion; public constructor(param0: com.facebook.AccessToken, param1: java.net.URL); public static toHttpConnection(param0: androidNative.Array<com.facebook.GraphRequest>): java.net.HttpURLConnection; public constructor(param0: com.facebook.AccessToken); public setVersion(param0: string): void; public constructor(param0: com.facebook.AccessToken, param1: string, param2: globalAndroid.os.Bundle, param3: com.facebook.HttpMethod, param4: com.facebook.GraphRequest.Callback, param5: string); public static executeConnectionAsync(param0: globalAndroid.os.Handler, param1: java.net.HttpURLConnection, param2: com.facebook.GraphRequestBatch): com.facebook.GraphRequestAsyncTask; public static serializeToUrlConnection$facebook_core_release(param0: com.facebook.GraphRequestBatch, param1: java.net.HttpURLConnection): void; public getCallback(): com.facebook.GraphRequest.Callback; public static executeBatchAndWait(param0: androidNative.Array<com.facebook.GraphRequest>): java.util.List<com.facebook.GraphResponse>; public static newMyFriendsRequest(param0: com.facebook.AccessToken, param1: com.facebook.GraphRequest.GraphJSONArrayCallback): com.facebook.GraphRequest; public static runCallbacks$facebook_core_release(param0: com.facebook.GraphRequestBatch, param1: java.util.List<com.facebook.GraphResponse>): void; public static shouldWarnOnMissingFieldsParam$facebook_core_release(param0: com.facebook.GraphRequest): boolean; public getTag(): any; public setCallback(param0: com.facebook.GraphRequest.Callback): void; public static newUploadPhotoRequest(param0: com.facebook.AccessToken, param1: string, param2: globalAndroid.graphics.Bitmap, param3: string, param4: globalAndroid.os.Bundle, param5: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public static toHttpConnection(param0: java.util.Collection<com.facebook.GraphRequest>): java.net.HttpURLConnection; public static executeBatchAsync(param0: androidNative.Array<com.facebook.GraphRequest>): com.facebook.GraphRequestAsyncTask; public static executeConnectionAndWait(param0: java.net.HttpURLConnection, param1: java.util.Collection<com.facebook.GraphRequest>): java.util.List<com.facebook.GraphResponse>; public constructor(param0: com.facebook.AccessToken, param1: string, param2: globalAndroid.os.Bundle); public getParameters(): globalAndroid.os.Bundle; public getBatchEntryDependsOn(): string; public constructor(param0: com.facebook.AccessToken, param1: string); public constructor(); public static executeBatchAsync(param0: com.facebook.GraphRequestBatch): com.facebook.GraphRequestAsyncTask; public getGraphObject(): org.json.JSONObject; public setForceApplicationRequest(param0: boolean): void; public static setDefaultBatchApplicationId(param0: string): void; public static executeAndWait(param0: com.facebook.GraphRequest): com.facebook.GraphResponse; public static executeConnectionAsync(param0: java.net.HttpURLConnection, param1: com.facebook.GraphRequestBatch): com.facebook.GraphRequestAsyncTask; public static getDefaultBatchApplicationId(): string; /** @deprecated */ public setSkipClientToken(param0: boolean): void; public static newGraphPathRequest(param0: com.facebook.AccessToken, param1: string, param2: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public static executeBatchAndWait(param0: java.util.Collection<com.facebook.GraphRequest>): java.util.List<com.facebook.GraphResponse>; public static newPostRequest(param0: com.facebook.AccessToken, param1: string, param2: org.json.JSONObject, param3: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public executeAndWait(): com.facebook.GraphResponse; public getUrlForSingleRequest(): string; public static newUploadPhotoRequest(param0: com.facebook.AccessToken, param1: string, param2: globalAndroid.net.Uri, param3: string, param4: globalAndroid.os.Bundle, param5: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public static newMeRequest(param0: com.facebook.AccessToken, param1: com.facebook.GraphRequest.GraphJSONObjectCallback): com.facebook.GraphRequest; public static newDeleteObjectRequest(param0: com.facebook.AccessToken, param1: string, param2: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public setBatchEntryName(param0: string): void; public setGraphPath(param0: string): void; public setParameters(param0: globalAndroid.os.Bundle): void; public static executeConnectionAndWait(param0: java.net.HttpURLConnection, param1: com.facebook.GraphRequestBatch): java.util.List<com.facebook.GraphResponse>; public getBatchEntryOmitResultOnSuccess(): boolean; public static toHttpConnection(param0: com.facebook.GraphRequestBatch): java.net.HttpURLConnection; public getRelativeUrlForBatchedRequest(): string; public setTag(param0: any): void; public setBatchEntryOmitResultOnSuccess(param0: boolean): void; public static executeBatchAndWait(param0: com.facebook.GraphRequestBatch): java.util.List<com.facebook.GraphResponse>; public constructor(param0: com.facebook.AccessToken, param1: string, param2: globalAndroid.os.Bundle, param3: com.facebook.HttpMethod); public static newCustomAudienceThirdPartyIdRequest(param0: com.facebook.AccessToken, param1: globalAndroid.content.Context, param2: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public executeAsync(): com.facebook.GraphRequestAsyncTask; public static validateFieldsParamForGetRequests$facebook_core_release(param0: com.facebook.GraphRequestBatch): void; public static executeBatchAsync(param0: java.util.Collection<com.facebook.GraphRequest>): com.facebook.GraphRequestAsyncTask; public setAccessToken(param0: com.facebook.AccessToken): void; public setHttpMethod(param0: com.facebook.HttpMethod): void; public static newCustomAudienceThirdPartyIdRequest(param0: com.facebook.AccessToken, param1: globalAndroid.content.Context, param2: string, param3: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public toString(): string; public constructor(param0: com.facebook.AccessToken, param1: string, param2: globalAndroid.os.Bundle, param3: com.facebook.HttpMethod, param4: com.facebook.GraphRequest.Callback); public getAccessToken(): com.facebook.AccessToken; public setGraphObject(param0: org.json.JSONObject): void; public getHttpMethod(): com.facebook.HttpMethod; public static newUploadPhotoRequest(param0: com.facebook.AccessToken, param1: string, param2: java.io.File, param3: string, param4: globalAndroid.os.Bundle, param5: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public getBatchEntryName(): string; public getVersion(): string; public getGraphPath(): string; public setBatchEntryDependsOn(param0: string): void; public static newPlacesSearchRequest(param0: com.facebook.AccessToken, param1: globalAndroid.location.Location, param2: number, param3: number, param4: string, param5: com.facebook.GraphRequest.GraphJSONArrayCallback): com.facebook.GraphRequest; } export module GraphRequest { export class Attachment { public static class: java.lang.Class<com.facebook.GraphRequest.Attachment>; public constructor(param0: com.facebook.GraphRequest, param1: any); public getRequest(): com.facebook.GraphRequest; public getValue(): any; } export class Callback { public static class: java.lang.Class<com.facebook.GraphRequest.Callback>; /** * Constructs a new instance of the com.facebook.GraphRequest$Callback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onCompleted(param0: com.facebook.GraphResponse): void; }); public constructor(); public onCompleted(param0: com.facebook.GraphResponse): void; } export class Companion { public static class: java.lang.Class<com.facebook.GraphRequest.Companion>; public newMeRequest(param0: com.facebook.AccessToken, param1: com.facebook.GraphRequest.GraphJSONObjectCallback): com.facebook.GraphRequest; public validateFieldsParamForGetRequests$facebook_core_release(param0: com.facebook.GraphRequestBatch): void; public newPlacesSearchRequest(param0: com.facebook.AccessToken, param1: globalAndroid.location.Location, param2: number, param3: number, param4: string, param5: com.facebook.GraphRequest.GraphJSONArrayCallback): com.facebook.GraphRequest; public runCallbacks$facebook_core_release(param0: com.facebook.GraphRequestBatch, param1: java.util.List<com.facebook.GraphResponse>): void; public executeBatchAndWait(param0: java.util.Collection<com.facebook.GraphRequest>): java.util.List<com.facebook.GraphResponse>; public executeConnectionAndWait(param0: java.net.HttpURLConnection, param1: com.facebook.GraphRequestBatch): java.util.List<com.facebook.GraphResponse>; public newDeleteObjectRequest(param0: com.facebook.AccessToken, param1: string, param2: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public newCustomAudienceThirdPartyIdRequest(param0: com.facebook.AccessToken, param1: globalAndroid.content.Context, param2: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public getDefaultBatchApplicationId(): string; public newUploadPhotoRequest(param0: com.facebook.AccessToken, param1: string, param2: globalAndroid.net.Uri, param3: string, param4: globalAndroid.os.Bundle, param5: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public newCustomAudienceThirdPartyIdRequest(param0: com.facebook.AccessToken, param1: globalAndroid.content.Context, param2: string, param3: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public toHttpConnection(param0: androidNative.Array<com.facebook.GraphRequest>): java.net.HttpURLConnection; public toHttpConnection(param0: java.util.Collection<com.facebook.GraphRequest>): java.net.HttpURLConnection; public executeBatchAsync(param0: java.util.Collection<com.facebook.GraphRequest>): com.facebook.GraphRequestAsyncTask; public executeBatchAndWait(param0: androidNative.Array<com.facebook.GraphRequest>): java.util.List<com.facebook.GraphResponse>; public executeBatchAsync(param0: androidNative.Array<com.facebook.GraphRequest>): com.facebook.GraphRequestAsyncTask; public executeConnectionAsync(param0: globalAndroid.os.Handler, param1: java.net.HttpURLConnection, param2: com.facebook.GraphRequestBatch): com.facebook.GraphRequestAsyncTask; public newUploadPhotoRequest(param0: com.facebook.AccessToken, param1: string, param2: java.io.File, param3: string, param4: globalAndroid.os.Bundle, param5: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public toHttpConnection(param0: com.facebook.GraphRequestBatch): java.net.HttpURLConnection; public newUploadPhotoRequest(param0: com.facebook.AccessToken, param1: string, param2: globalAndroid.graphics.Bitmap, param3: string, param4: globalAndroid.os.Bundle, param5: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public executeBatchAsync(param0: com.facebook.GraphRequestBatch): com.facebook.GraphRequestAsyncTask; public serializeToUrlConnection$facebook_core_release(param0: com.facebook.GraphRequestBatch, param1: java.net.HttpURLConnection): void; public newGraphPathRequest(param0: com.facebook.AccessToken, param1: string, param2: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public executeBatchAndWait(param0: com.facebook.GraphRequestBatch): java.util.List<com.facebook.GraphResponse>; public executeConnectionAsync(param0: java.net.HttpURLConnection, param1: com.facebook.GraphRequestBatch): com.facebook.GraphRequestAsyncTask; public setDefaultBatchApplicationId(param0: string): void; public newMyFriendsRequest(param0: com.facebook.AccessToken, param1: com.facebook.GraphRequest.GraphJSONArrayCallback): com.facebook.GraphRequest; public shouldWarnOnMissingFieldsParam$facebook_core_release(param0: com.facebook.GraphRequest): boolean; public newPostRequest(param0: com.facebook.AccessToken, param1: string, param2: org.json.JSONObject, param3: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public executeConnectionAndWait(param0: java.net.HttpURLConnection, param1: java.util.Collection<com.facebook.GraphRequest>): java.util.List<com.facebook.GraphResponse>; public executeAndWait(param0: com.facebook.GraphRequest): com.facebook.GraphResponse; } export class GraphJSONArrayCallback { public static class: java.lang.Class<com.facebook.GraphRequest.GraphJSONArrayCallback>; /** * Constructs a new instance of the com.facebook.GraphRequest$GraphJSONArrayCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onCompleted(param0: org.json.JSONArray, param1: com.facebook.GraphResponse): void; }); public constructor(); public onCompleted(param0: org.json.JSONArray, param1: com.facebook.GraphResponse): void; } export class GraphJSONObjectCallback { public static class: java.lang.Class<com.facebook.GraphRequest.GraphJSONObjectCallback>; /** * Constructs a new instance of the com.facebook.GraphRequest$GraphJSONObjectCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onCompleted(param0: org.json.JSONObject, param1: com.facebook.GraphResponse): void; }); public constructor(); public onCompleted(param0: org.json.JSONObject, param1: com.facebook.GraphResponse): void; } export class KeyValueSerializer { public static class: java.lang.Class<com.facebook.GraphRequest.KeyValueSerializer>; /** * Constructs a new instance of the com.facebook.GraphRequest$KeyValueSerializer interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { writeString(param0: string, param1: string): void; }); public constructor(); public writeString(param0: string, param1: string): void; } export class OnProgressCallback extends com.facebook.GraphRequest.Callback { public static class: java.lang.Class<com.facebook.GraphRequest.OnProgressCallback>; /** * Constructs a new instance of the com.facebook.GraphRequest$OnProgressCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onProgress(param0: number, param1: number): void; onCompleted(param0: com.facebook.GraphResponse): void; }); public constructor(); public onCompleted(param0: com.facebook.GraphResponse): void; public onProgress(param0: number, param1: number): void; } export class ParcelableResourceWithMimeType<RESOURCE> extends globalAndroid.os.Parcelable { public static class: java.lang.Class<com.facebook.GraphRequest.ParcelableResourceWithMimeType<any>>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.GraphRequest.ParcelableResourceWithMimeType<any>>; public static Companion: com.facebook.GraphRequest.ParcelableResourceWithMimeType.Companion; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: any, param1: string); public getResource(): any; public getMimeType(): string; public describeContents(): number; } export module ParcelableResourceWithMimeType { export class Companion { public static class: java.lang.Class<com.facebook.GraphRequest.ParcelableResourceWithMimeType.Companion>; } } export class Serializer extends com.facebook.GraphRequest.KeyValueSerializer { public static class: java.lang.Class<com.facebook.GraphRequest.Serializer>; public writeString(param0: string, param1: string): void; public writeFile(param0: string, param1: globalAndroid.os.ParcelFileDescriptor, param2: string): void; public writeBitmap(param0: string, param1: globalAndroid.graphics.Bitmap): void; public writeContentDisposition(param0: string, param1: string, param2: string): void; public writeRecordBoundary(): void; public write(param0: string, param1: androidNative.Array<any>): void; public constructor(param0: java.io.OutputStream, param1: com.facebook.internal.Logger, param2: boolean); public writeRequestsAsJson(param0: string, param1: org.json.JSONArray, param2: java.util.Collection<com.facebook.GraphRequest>): void; public writeContentUri(param0: string, param1: globalAndroid.net.Uri, param2: string): void; public writeLine(param0: string, param1: androidNative.Array<any>): void; public writeObject(param0: string, param1: any, param2: com.facebook.GraphRequest): void; public writeBytes(param0: string, param1: androidNative.Array<number>): void; } } } } declare module com { export module facebook { export class GraphRequestAsyncTask extends globalAndroid.os.AsyncTask<java.lang.Void,java.lang.Void,java.util.List<any>> { public static class: java.lang.Class<com.facebook.GraphRequestAsyncTask>; public static Companion: com.facebook.GraphRequestAsyncTask.Companion; public constructor(param0: androidNative.Array<com.facebook.GraphRequest>); public constructor(param0: java.net.HttpURLConnection, param1: java.util.Collection<com.facebook.GraphRequest>); public toString(): string; public onPostExecute(param0: java.util.List<com.facebook.GraphResponse>): void; public getException(): java.lang.Exception; public doInBackground(param0: androidNative.Array<java.lang.Void>): java.util.List<com.facebook.GraphResponse>; public constructor(param0: java.net.HttpURLConnection, param1: com.facebook.GraphRequestBatch); public constructor(param0: java.net.HttpURLConnection, param1: androidNative.Array<com.facebook.GraphRequest>); public onPreExecute(): void; public getRequests(): com.facebook.GraphRequestBatch; public constructor(param0: java.util.Collection<com.facebook.GraphRequest>); public constructor(param0: com.facebook.GraphRequestBatch); } export module GraphRequestAsyncTask { export class Companion { public static class: java.lang.Class<com.facebook.GraphRequestAsyncTask.Companion>; } } } } declare module com { export module facebook { export class GraphRequestBatch extends java.util.AbstractList<com.facebook.GraphRequest> { public static class: java.lang.Class<com.facebook.GraphRequestBatch>; public static Companion: com.facebook.GraphRequestBatch.Companion; public constructor(param0: androidNative.Array<com.facebook.GraphRequest>); public add(param0: com.facebook.GraphRequest): boolean; public getCallbackHandler(): globalAndroid.os.Handler; public getSize(): number; public contains(param0: any): boolean; public addCallback(param0: com.facebook.GraphRequestBatch.Callback): void; public removeAt(param0: number): com.facebook.GraphRequest; public set(param0: number, param1: com.facebook.GraphRequest): com.facebook.GraphRequest; public remove(param0: com.facebook.GraphRequest): boolean; public getTimeout(): number; public indexOf(param0: com.facebook.GraphRequest): number; public getCallbacks(): java.util.List<com.facebook.GraphRequestBatch.Callback>; public getBatchApplicationId(): string; public clear(): void; public setTimeout(param0: number): void; public lastIndexOf(param0: com.facebook.GraphRequest): number; public get(param0: number): com.facebook.GraphRequest; public size(): number; public add(param0: number, param1: com.facebook.GraphRequest): void; public removeCallback(param0: com.facebook.GraphRequestBatch.Callback): void; public constructor(); public executeAsync(): com.facebook.GraphRequestAsyncTask; public constructor(param0: java.util.Collection<com.facebook.GraphRequest>); public remove(param0: any): boolean; public contains(param0: com.facebook.GraphRequest): boolean; public getId(): string; public lastIndexOf(param0: any): number; public setBatchApplicationId(param0: string): void; public remove(param0: number): com.facebook.GraphRequest; public indexOf(param0: any): number; public getRequests(): java.util.List<com.facebook.GraphRequest>; public executeAndWait(): java.util.List<com.facebook.GraphResponse>; public constructor(param0: com.facebook.GraphRequestBatch); public setCallbackHandler(param0: globalAndroid.os.Handler): void; } export module GraphRequestBatch { export class Callback { public static class: java.lang.Class<com.facebook.GraphRequestBatch.Callback>; /** * Constructs a new instance of the com.facebook.GraphRequestBatch$Callback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onBatchCompleted(param0: com.facebook.GraphRequestBatch): void; }); public constructor(); public onBatchCompleted(param0: com.facebook.GraphRequestBatch): void; } export class Companion { public static class: java.lang.Class<com.facebook.GraphRequestBatch.Companion>; } export class OnProgressCallback extends com.facebook.GraphRequestBatch.Callback { public static class: java.lang.Class<com.facebook.GraphRequestBatch.OnProgressCallback>; /** * Constructs a new instance of the com.facebook.GraphRequestBatch$OnProgressCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onBatchProgress(param0: com.facebook.GraphRequestBatch, param1: number, param2: number): void; onBatchCompleted(param0: com.facebook.GraphRequestBatch): void; }); public constructor(); public onBatchProgress(param0: com.facebook.GraphRequestBatch, param1: number, param2: number): void; public onBatchCompleted(param0: com.facebook.GraphRequestBatch): void; } } } } declare module com { export module facebook { export class GraphResponse { public static class: java.lang.Class<com.facebook.GraphResponse>; public static NON_JSON_RESPONSE_PROPERTY: string; public static SUCCESS_KEY: string; public static Companion: com.facebook.GraphResponse.Companion; public getRequestForPagedResults(param0: com.facebook.GraphResponse.PagingDirection): com.facebook.GraphRequest; public getJSONArray(): org.json.JSONArray; public getRequest(): com.facebook.GraphRequest; public static constructErrorResponses(param0: java.util.List<com.facebook.GraphRequest>, param1: java.net.HttpURLConnection, param2: com.facebook.FacebookException): java.util.List<com.facebook.GraphResponse>; public getConnection(): java.net.HttpURLConnection; public getRawResponse(): string; public static createResponsesFromString$facebook_core_release(param0: string, param1: java.net.HttpURLConnection, param2: com.facebook.GraphRequestBatch): java.util.List<com.facebook.GraphResponse>; public getJsonArray(): org.json.JSONArray; public getJSONObject(): org.json.JSONObject; public constructor(param0: com.facebook.GraphRequest, param1: java.net.HttpURLConnection, param2: string, param3: org.json.JSONObject, param4: org.json.JSONArray, param5: com.facebook.FacebookRequestError); public constructor(param0: com.facebook.GraphRequest, param1: java.net.HttpURLConnection, param2: string, param3: org.json.JSONArray); public getJsonObject(): org.json.JSONObject; public toString(): string; public constructor(param0: com.facebook.GraphRequest, param1: java.net.HttpURLConnection, param2: com.facebook.FacebookRequestError); public constructor(param0: com.facebook.GraphRequest, param1: java.net.HttpURLConnection, param2: string, param3: org.json.JSONObject); public static createResponsesFromStream$facebook_core_release(param0: java.io.InputStream, param1: java.net.HttpURLConnection, param2: com.facebook.GraphRequestBatch): java.util.List<com.facebook.GraphResponse>; public getError(): com.facebook.FacebookRequestError; public static fromHttpConnection$facebook_core_release(param0: java.net.HttpURLConnection, param1: com.facebook.GraphRequestBatch): java.util.List<com.facebook.GraphResponse>; } export module GraphResponse { export class Companion { public static class: java.lang.Class<com.facebook.GraphResponse.Companion>; public fromHttpConnection$facebook_core_release(param0: java.net.HttpURLConnection, param1: com.facebook.GraphRequestBatch): java.util.List<com.facebook.GraphResponse>; public createResponsesFromString$facebook_core_release(param0: string, param1: java.net.HttpURLConnection, param2: com.facebook.GraphRequestBatch): java.util.List<com.facebook.GraphResponse>; public createResponsesFromStream$facebook_core_release(param0: java.io.InputStream, param1: java.net.HttpURLConnection, param2: com.facebook.GraphRequestBatch): java.util.List<com.facebook.GraphResponse>; public constructErrorResponses(param0: java.util.List<com.facebook.GraphRequest>, param1: java.net.HttpURLConnection, param2: com.facebook.FacebookException): java.util.List<com.facebook.GraphResponse>; } export class PagingDirection { public static class: java.lang.Class<com.facebook.GraphResponse.PagingDirection>; public static NEXT: com.facebook.GraphResponse.PagingDirection; public static PREVIOUS: com.facebook.GraphResponse.PagingDirection; public static values(): androidNative.Array<com.facebook.GraphResponse.PagingDirection>; public static valueOf(param0: string): com.facebook.GraphResponse.PagingDirection; } } } } declare module com { export module facebook { export class HttpMethod { public static class: java.lang.Class<com.facebook.HttpMethod>; public static GET: com.facebook.HttpMethod; public static POST: com.facebook.HttpMethod; public static DELETE: com.facebook.HttpMethod; public static values(): androidNative.Array<com.facebook.HttpMethod>; public static valueOf(param0: string): com.facebook.HttpMethod; } } } declare module com { export module facebook { export class LegacyTokenHelper { public static class: java.lang.Class<com.facebook.LegacyTokenHelper>; public static TOKEN_KEY: string; public static EXPIRATION_DATE_KEY: string; public static LAST_REFRESH_DATE_KEY: string; public static TOKEN_SOURCE_KEY: string; public static PERMISSIONS_KEY: string; public static DECLINED_PERMISSIONS_KEY: string; public static EXPIRED_PERMISSIONS_KEY: string; public static APPLICATION_ID_KEY: string; public static DEFAULT_CACHE_KEY: string; public static Companion: com.facebook.LegacyTokenHelper.Companion; public clear(): void; public static putLastRefreshDate(param0: globalAndroid.os.Bundle, param1: java.util.Date): void; public static putSource(param0: globalAndroid.os.Bundle, param1: com.facebook.AccessTokenSource): void; public static putApplicationId(param0: globalAndroid.os.Bundle, param1: string): void; public constructor(param0: globalAndroid.content.Context, param1: string); public static putPermissions(param0: globalAndroid.os.Bundle, param1: java.util.Collection<string>): void; public static getLastRefreshDate(param0: globalAndroid.os.Bundle): java.util.Date; public load(): globalAndroid.os.Bundle; public static getToken(param0: globalAndroid.os.Bundle): string; public static putExpirationDate(param0: globalAndroid.os.Bundle, param1: java.util.Date): void; public static getExpirationDate(param0: globalAndroid.os.Bundle): java.util.Date; public static putExpirationMilliseconds(param0: globalAndroid.os.Bundle, param1: number): void; public save(param0: globalAndroid.os.Bundle): void; public static getApplicationId(param0: globalAndroid.os.Bundle): string; public static hasTokenInformation(param0: globalAndroid.os.Bundle): boolean; public static getSource(param0: globalAndroid.os.Bundle): com.facebook.AccessTokenSource; public static putExpiredPermissions(param0: globalAndroid.os.Bundle, param1: java.util.Collection<string>): void; public static putToken(param0: globalAndroid.os.Bundle, param1: string): void; public static getPermissions(param0: globalAndroid.os.Bundle): java.util.Set<string>; public static getExpirationMilliseconds(param0: globalAndroid.os.Bundle): number; public static putLastRefreshMilliseconds(param0: globalAndroid.os.Bundle, param1: number): void; public constructor(param0: globalAndroid.content.Context); public static getLastRefreshMilliseconds(param0: globalAndroid.os.Bundle): number; public static putDeclinedPermissions(param0: globalAndroid.os.Bundle, param1: java.util.Collection<string>): void; } export module LegacyTokenHelper { export class Companion { public static class: java.lang.Class<com.facebook.LegacyTokenHelper.Companion>; public hasTokenInformation(param0: globalAndroid.os.Bundle): boolean; public getPermissions(param0: globalAndroid.os.Bundle): java.util.Set<string>; public getLastRefreshDate(param0: globalAndroid.os.Bundle): java.util.Date; public putToken(param0: globalAndroid.os.Bundle, param1: string): void; public putApplicationId(param0: globalAndroid.os.Bundle, param1: string): void; public putSource(param0: globalAndroid.os.Bundle, param1: com.facebook.AccessTokenSource): void; public putLastRefreshMilliseconds(param0: globalAndroid.os.Bundle, param1: number): void; public getSource(param0: globalAndroid.os.Bundle): com.facebook.AccessTokenSource; public putPermissions(param0: globalAndroid.os.Bundle, param1: java.util.Collection<string>): void; public putLastRefreshDate(param0: globalAndroid.os.Bundle, param1: java.util.Date): void; public getLastRefreshMilliseconds(param0: globalAndroid.os.Bundle): number; public getExpirationMilliseconds(param0: globalAndroid.os.Bundle): number; public getToken(param0: globalAndroid.os.Bundle): string; public getExpirationDate(param0: globalAndroid.os.Bundle): java.util.Date; public putExpirationMilliseconds(param0: globalAndroid.os.Bundle, param1: number): void; public putExpiredPermissions(param0: globalAndroid.os.Bundle, param1: java.util.Collection<string>): void; public getApplicationId(param0: globalAndroid.os.Bundle): string; public putDeclinedPermissions(param0: globalAndroid.os.Bundle, param1: java.util.Collection<string>): void; public putExpirationDate(param0: globalAndroid.os.Bundle, param1: java.util.Date): void; } } } } declare module com { export module facebook { export class LoggingBehavior { public static class: java.lang.Class<com.facebook.LoggingBehavior>; public static REQUESTS: com.facebook.LoggingBehavior; public static INCLUDE_ACCESS_TOKENS: com.facebook.LoggingBehavior; public static INCLUDE_RAW_RESPONSES: com.facebook.LoggingBehavior; public static CACHE: com.facebook.LoggingBehavior; public static APP_EVENTS: com.facebook.LoggingBehavior; public static DEVELOPER_ERRORS: com.facebook.LoggingBehavior; public static GRAPH_API_DEBUG_WARNING: com.facebook.LoggingBehavior; public static GRAPH_API_DEBUG_INFO: com.facebook.LoggingBehavior; public static values(): androidNative.Array<com.facebook.LoggingBehavior>; public static valueOf(param0: string): com.facebook.LoggingBehavior; } } } declare module com { export module facebook { export class LoginStatusCallback { public static class: java.lang.Class<com.facebook.LoginStatusCallback>; /** * Constructs a new instance of the com.facebook.LoginStatusCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onCompleted(param0: com.facebook.AccessToken): void; onFailure(): void; onError(param0: java.lang.Exception): void; }); public constructor(); public onCompleted(param0: com.facebook.AccessToken): void; public onFailure(): void; public onError(param0: java.lang.Exception): void; } } } declare module com { export module facebook { export class Profile { public static class: java.lang.Class<com.facebook.Profile>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.Profile>; public static Companion: com.facebook.Profile.Companion; public static fetchProfileForCurrentAccessToken(): void; public equals(param0: any): boolean; public constructor(param0: string, param1: string, param2: string, param3: string, param4: string, param5: globalAndroid.net.Uri); public getProfilePictureUri(param0: number, param1: number): globalAndroid.net.Uri; public constructor(param0: string, param1: string, param2: string, param3: string, param4: string, param5: globalAndroid.net.Uri, param6: globalAndroid.net.Uri); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public toJSONObject(): org.json.JSONObject; public getId(): string; public getMiddleName(): string; public getName(): string; public getFirstName(): string; public describeContents(): number; public constructor(param0: org.json.JSONObject); public getLastName(): string; public static getCurrentProfile(): com.facebook.Profile; public getLinkUri(): globalAndroid.net.Uri; public static setCurrentProfile(param0: com.facebook.Profile): void; public getPictureUri(): globalAndroid.net.Uri; public hashCode(): number; } export module Profile { export class Companion { public static class: java.lang.Class<com.facebook.Profile.Companion>; public fetchProfileForCurrentAccessToken(): void; public getCurrentProfile(): com.facebook.Profile; public setCurrentProfile(param0: com.facebook.Profile): void; } } } } declare module com { export module facebook { export class ProfileCache { public static class: java.lang.Class<com.facebook.ProfileCache>; public static CACHED_PROFILE_KEY: string; public static SHARED_PREFERENCES_NAME: string; public static Companion: com.facebook.ProfileCache.Companion; public clear(): void; public save(param0: com.facebook.Profile): void; public load(): com.facebook.Profile; public constructor(); } export module ProfileCache { export class Companion { public static class: java.lang.Class<com.facebook.ProfileCache.Companion>; } } } } declare module com { export module facebook { export class ProfileManager { public static class: java.lang.Class<com.facebook.ProfileManager>; public static ACTION_CURRENT_PROFILE_CHANGED: string; public static EXTRA_OLD_PROFILE: string; public static EXTRA_NEW_PROFILE: string; public static Companion: com.facebook.ProfileManager.Companion; public constructor(param0: androidx.localbroadcastmanager.content.LocalBroadcastManager, param1: com.facebook.ProfileCache); public setCurrentProfile(param0: com.facebook.Profile): void; public static getInstance(): com.facebook.ProfileManager; public loadCurrentProfile(): boolean; public getCurrentProfile(): com.facebook.Profile; } export module ProfileManager { export class Companion { public static class: java.lang.Class<com.facebook.ProfileManager.Companion>; public getInstance(): com.facebook.ProfileManager; } } } } declare module com { export module facebook { export abstract class ProfileTracker { public static class: java.lang.Class<com.facebook.ProfileTracker>; public startTracking(): void; public stopTracking(): void; public constructor(); public isTracking(): boolean; public onCurrentProfileChanged(param0: com.facebook.Profile, param1: com.facebook.Profile): void; } export module ProfileTracker { export class ProfileBroadcastReceiver { public static class: java.lang.Class<com.facebook.ProfileTracker.ProfileBroadcastReceiver>; public constructor(param0: com.facebook.ProfileTracker); public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void; } } } } declare module com { export module facebook { export class ProgressNoopOutputStream implements com.facebook.RequestOutputStream { public static class: java.lang.Class<com.facebook.ProgressNoopOutputStream>; public setCurrentRequest(param0: com.facebook.GraphRequest): void; public getProgressMap(): java.util.Map<com.facebook.GraphRequest,com.facebook.RequestProgress>; public write(param0: number): void; public constructor(param0: globalAndroid.os.Handler); public getMaxProgress(): number; public write(param0: androidNative.Array<number>): void; public write(param0: androidNative.Array<number>, param1: number, param2: number): void; public addProgress(param0: number): void; } } } declare module com { export module facebook { export class ProgressOutputStream implements com.facebook.RequestOutputStream { public static class: java.lang.Class<com.facebook.ProgressOutputStream>; public setCurrentRequest(param0: com.facebook.GraphRequest): void; public write(param0: number): void; public getMaxProgress(): number; public getBatchProgress(): number; public constructor(param0: java.io.OutputStream, param1: com.facebook.GraphRequestBatch, param2: java.util.Map<com.facebook.GraphRequest,com.facebook.RequestProgress>, param3: number); public close(): void; public write(param0: androidNative.Array<number>): void; public write(param0: androidNative.Array<number>, param1: number, param2: number): void; } } } declare module com { export module facebook { export class RequestOutputStream { public static class: java.lang.Class<com.facebook.RequestOutputStream>; /** * Constructs a new instance of the com.facebook.RequestOutputStream interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { setCurrentRequest(param0: com.facebook.GraphRequest): void; }); public constructor(); public setCurrentRequest(param0: com.facebook.GraphRequest): void; } } } declare module com { export module facebook { export class RequestProgress { public static class: java.lang.Class<com.facebook.RequestProgress>; public getProgress(): number; public reportProgress(): void; public getMaxProgress(): number; public constructor(param0: globalAndroid.os.Handler, param1: com.facebook.GraphRequest); public addToMax(param0: number): void; public addProgress(param0: number): void; } } } declare module com { export module facebook { export class ShareGraphRequest { public static class: java.lang.Class<com.facebook.ShareGraphRequest>; public static createOpenGraphObject(param0: com.facebook.share.model.ShareOpenGraphObject): com.facebook.GraphRequest; public constructor(); } } } declare module com { export module facebook { export class UserSettingsManager { public static class: java.lang.Class<com.facebook.UserSettingsManager>; public static INSTANCE: com.facebook.UserSettingsManager; public static getAutoLogAppEventsEnabled(): boolean; public static getCodelessSetupEnabled(): boolean; public static setAutoLogAppEventsEnabled(param0: boolean): void; public static getMonitorEnabled(): boolean; public static logIfAutoAppLinkEnabled(): void; public static setAutoInitEnabled(param0: boolean): void; public static setAdvertiserIDCollectionEnabled(param0: boolean): void; public static getAutoInitEnabled(): boolean; public static setMonitorEnabled(param0: boolean): void; public static getAdvertiserIDCollectionEnabled(): boolean; } export module UserSettingsManager { export class UserSetting { public static class: java.lang.Class<com.facebook.UserSettingsManager.UserSetting>; public setDefaultVal(param0: boolean): void; public setValue(param0: java.lang.Boolean): void; public setLastTS(param0: number): void; public getDefaultVal(): boolean; public constructor(param0: boolean, param1: string); public getValue(): java.lang.Boolean; public setKey(param0: string): void; public getLastTS(): number; public getValue(): boolean; public getKey(): string; } } } } declare module com { export module facebook { export class WebDialog { public static class: java.lang.Class<com.facebook.WebDialog>; public static setWebDialogTheme(param0: number): void; public static getWebDialogTheme(): number; } } } declare module com { export module facebook { export module appevents { export class AccessTokenAppIdPair { public static class: java.lang.Class<com.facebook.appevents.AccessTokenAppIdPair>; public static Companion: com.facebook.appevents.AccessTokenAppIdPair.Companion; public constructor(param0: com.facebook.AccessToken); public getAccessTokenString(): string; public hashCode(): number; public equals(param0: any): boolean; public getApplicationId(): string; public constructor(param0: string, param1: string); } export module AccessTokenAppIdPair { export class Companion { public static class: java.lang.Class<com.facebook.appevents.AccessTokenAppIdPair.Companion>; } export class SerializationProxyV1 { public static class: java.lang.Class<com.facebook.appevents.AccessTokenAppIdPair.SerializationProxyV1>; public static Companion: com.facebook.appevents.AccessTokenAppIdPair.SerializationProxyV1.Companion; public constructor(param0: string, param1: string); } export module SerializationProxyV1 { export class Companion { public static class: java.lang.Class<com.facebook.appevents.AccessTokenAppIdPair.SerializationProxyV1.Companion>; } } } } } } declare module com { export module facebook { export module appevents { export class AnalyticsUserIDStore { public static class: java.lang.Class<com.facebook.appevents.AnalyticsUserIDStore>; public static INSTANCE: com.facebook.appevents.AnalyticsUserIDStore; public static setUserID(param0: string): void; public static initStore(): void; public static getUserID(): string; } } } } declare module com { export module facebook { export module appevents { export class AppEvent { public static class: java.lang.Class<com.facebook.appevents.AppEvent>; public static Companion: com.facebook.appevents.AppEvent.Companion; public getJSONObject(): org.json.JSONObject; public constructor(param0: string, param1: string, param2: java.lang.Double, param3: globalAndroid.os.Bundle, param4: boolean, param5: boolean, param6: java.util.UUID); public isImplicit(): boolean; public getJsonObject(): org.json.JSONObject; public getIsImplicit(): boolean; public getName(): string; public isChecksumValid(): boolean; public toString(): string; } export module AppEvent { export class Companion { public static class: java.lang.Class<com.facebook.appevents.AppEvent.Companion>; } export class SerializationProxyV2 { public static class: java.lang.Class<com.facebook.appevents.AppEvent.SerializationProxyV2>; public static Companion: com.facebook.appevents.AppEvent.SerializationProxyV2.Companion; public constructor(param0: string, param1: boolean, param2: boolean, param3: string); } export module SerializationProxyV2 { export class Companion { public static class: java.lang.Class<com.facebook.appevents.AppEvent.SerializationProxyV2.Companion>; } } } } } } declare module com { export module facebook { export module appevents { export class AppEventCollection { public static class: java.lang.Class<com.facebook.appevents.AppEventCollection>; public addEvent(param0: com.facebook.appevents.AccessTokenAppIdPair, param1: com.facebook.appevents.AppEvent): void; public addPersistedEvents(param0: com.facebook.appevents.PersistedEvents): void; public get(param0: com.facebook.appevents.AccessTokenAppIdPair): com.facebook.appevents.SessionEventsState; public keySet(): java.util.Set<com.facebook.appevents.AccessTokenAppIdPair>; public getEventCount(): number; public constructor(); } } } } declare module com { export module facebook { export module appevents { export class AppEventQueue { public static class: java.lang.Class<com.facebook.appevents.AppEventQueue>; public static INSTANCE: com.facebook.appevents.AppEventQueue; public static flush(param0: com.facebook.appevents.FlushReason): void; public static add(param0: com.facebook.appevents.AccessTokenAppIdPair, param1: com.facebook.appevents.AppEvent): void; public static buildRequests(param0: com.facebook.appevents.AppEventCollection, param1: com.facebook.appevents.FlushStatistics): java.util.List<com.facebook.GraphRequest>; public static buildRequestForSession(param0: com.facebook.appevents.AccessTokenAppIdPair, param1: com.facebook.appevents.SessionEventsState, param2: boolean, param3: com.facebook.appevents.FlushStatistics): com.facebook.GraphRequest; public static sendEventsToServer(param0: com.facebook.appevents.FlushReason, param1: com.facebook.appevents.AppEventCollection): com.facebook.appevents.FlushStatistics; public static persistToDisk(): void; public static getKeySet(): java.util.Set<com.facebook.appevents.AccessTokenAppIdPair>; public static handleResponse(param0: com.facebook.appevents.AccessTokenAppIdPair, param1: com.facebook.GraphRequest, param2: com.facebook.GraphResponse, param3: com.facebook.appevents.SessionEventsState, param4: com.facebook.appevents.FlushStatistics): void; public static flushAndWait(param0: com.facebook.appevents.FlushReason): void; } } } } declare module com { export module facebook { export module appevents { export class AppEventStore { public static class: java.lang.Class<com.facebook.appevents.AppEventStore>; public static INSTANCE: com.facebook.appevents.AppEventStore; public static persistEvents(param0: com.facebook.appevents.AppEventCollection): void; public static readAndClearStore(): com.facebook.appevents.PersistedEvents; public static saveEventsToDisk$facebook_core_release(param0: com.facebook.appevents.PersistedEvents): void; public static persistEvents(param0: com.facebook.appevents.AccessTokenAppIdPair, param1: com.facebook.appevents.SessionEventsState): void; } export module AppEventStore { export class MovedClassObjectInputStream { public static class: java.lang.Class<com.facebook.appevents.AppEventStore.MovedClassObjectInputStream>; public static Companion: com.facebook.appevents.AppEventStore.MovedClassObjectInputStream.Companion; public constructor(param0: java.io.InputStream); public readClassDescriptor(): java.io.ObjectStreamClass; } export module MovedClassObjectInputStream { export class Companion { public static class: java.lang.Class<com.facebook.appevents.AppEventStore.MovedClassObjectInputStream.Companion>; } } } } } } declare module com { export module facebook { export module appevents { export class AppEventsConstants { public static class: java.lang.Class<com.facebook.appevents.AppEventsConstants>; public static EVENT_NAME_ACTIVATED_APP: string; public static EVENT_NAME_DEACTIVATED_APP: string; public static EVENT_NAME_SESSION_INTERRUPTIONS: string; public static EVENT_NAME_TIME_BETWEEN_SESSIONS: string; public static EVENT_NAME_COMPLETED_REGISTRATION: string; public static EVENT_NAME_VIEWED_CONTENT: string; public static EVENT_NAME_SEARCHED: string; public static EVENT_NAME_RATED: string; public static EVENT_NAME_COMPLETED_TUTORIAL: string; public static EVENT_NAME_PUSH_TOKEN_OBTAINED: string; public static EVENT_NAME_ADDED_TO_CART: string; public static EVENT_NAME_ADDED_TO_WISHLIST: string; public static EVENT_NAME_INITIATED_CHECKOUT: string; public static EVENT_NAME_ADDED_PAYMENT_INFO: string; public static EVENT_NAME_PURCHASED: string; public static EVENT_NAME_ACHIEVED_LEVEL: string; public static EVENT_NAME_UNLOCKED_ACHIEVEMENT: string; public static EVENT_NAME_SPENT_CREDITS: string; public static EVENT_NAME_CONTACT: string; public static EVENT_NAME_CUSTOMIZE_PRODUCT: string; public static EVENT_NAME_DONATE: string; public static EVENT_NAME_FIND_LOCATION: string; public static EVENT_NAME_SCHEDULE: string; public static EVENT_NAME_START_TRIAL: string; public static EVENT_NAME_SUBMIT_APPLICATION: string; public static EVENT_NAME_SUBSCRIBE: string; public static EVENT_NAME_AD_IMPRESSION: string; public static EVENT_NAME_AD_CLICK: string; public static EVENT_NAME_LIVE_STREAMING_START: string; public static EVENT_NAME_LIVE_STREAMING_STOP: string; public static EVENT_NAME_LIVE_STREAMING_PAUSE: string; public static EVENT_NAME_LIVE_STREAMING_RESUME: string; public static EVENT_NAME_LIVE_STREAMING_ERROR: string; public static EVENT_NAME_LIVE_STREAMING_UPDATE_STATUS: string; public static EVENT_NAME_PRODUCT_CATALOG_UPDATE: string; public static EVENT_PARAM_LIVE_STREAMING_PREV_STATUS: string; public static EVENT_PARAM_LIVE_STREAMING_STATUS: string; public static EVENT_PARAM_LIVE_STREAMING_ERROR: string; public static EVENT_PARAM_CURRENCY: string; public static EVENT_PARAM_REGISTRATION_METHOD: string; public static EVENT_PARAM_CONTENT_TYPE: string; public static EVENT_PARAM_CONTENT: string; public static EVENT_PARAM_CONTENT_ID: string; public static EVENT_PARAM_SEARCH_STRING: string; public static EVENT_PARAM_SUCCESS: string; public static EVENT_PARAM_MAX_RATING_VALUE: string; public static EVENT_PARAM_PAYMENT_INFO_AVAILABLE: string; public static EVENT_PARAM_NUM_ITEMS: string; public static EVENT_PARAM_LEVEL: string; public static EVENT_PARAM_DESCRIPTION: string; public static EVENT_PARAM_SOURCE_APPLICATION: string; public static EVENT_PARAM_PACKAGE_FP: string; public static EVENT_PARAM_APP_CERT_HASH: string; public static EVENT_PARAM_VALUE_YES: string; public static EVENT_PARAM_VALUE_NO: string; public static EVENT_PARAM_AD_TYPE: string; public static EVENT_PARAM_ORDER_ID: string; public static EVENT_PARAM_VALUE_TO_SUM: string; public static EVENT_PARAM_PRODUCT_CUSTOM_LABEL_0: string; public static EVENT_PARAM_PRODUCT_CUSTOM_LABEL_1: string; public static EVENT_PARAM_PRODUCT_CUSTOM_LABEL_2: string; public static EVENT_PARAM_PRODUCT_CUSTOM_LABEL_3: string; public static EVENT_PARAM_PRODUCT_CUSTOM_LABEL_4: string; public static EVENT_PARAM_PRODUCT_CATEGORY: string; public static EVENT_PARAM_PRODUCT_APPLINK_IOS_URL: string; public static EVENT_PARAM_PRODUCT_APPLINK_IOS_APP_STORE_ID: string; public static EVENT_PARAM_PRODUCT_APPLINK_IOS_APP_NAME: string; public static EVENT_PARAM_PRODUCT_APPLINK_IPHONE_URL: string; public static EVENT_PARAM_PRODUCT_APPLINK_IPHONE_APP_STORE_ID: string; public static EVENT_PARAM_PRODUCT_APPLINK_IPHONE_APP_NAME: string; public static EVENT_PARAM_PRODUCT_APPLINK_IPAD_URL: string; public static EVENT_PARAM_PRODUCT_APPLINK_IPAD_APP_STORE_ID: string; public static EVENT_PARAM_PRODUCT_APPLINK_IPAD_APP_NAME: string; public static EVENT_PARAM_PRODUCT_APPLINK_ANDROID_URL: string; public static EVENT_PARAM_PRODUCT_APPLINK_ANDROID_PACKAGE: string; public static EVENT_PARAM_PRODUCT_APPLINK_ANDROID_APP_NAME: string; public static EVENT_PARAM_PRODUCT_APPLINK_WINDOWS_PHONE_URL: string; public static EVENT_PARAM_PRODUCT_APPLINK_WINDOWS_PHONE_APP_ID: string; public static EVENT_PARAM_PRODUCT_APPLINK_WINDOWS_PHONE_APP_NAME: string; public static INSTANCE: com.facebook.appevents.AppEventsConstants; } } } } declare module com { export module facebook { export module appevents { export class AppEventsLogger { public static class: java.lang.Class<com.facebook.appevents.AppEventsLogger>; public static ACTION_APP_EVENTS_FLUSHED: string; public static APP_EVENTS_EXTRA_NUM_EVENTS_FLUSHED: string; public static APP_EVENTS_EXTRA_FLUSH_RESULT: string; public static Companion: com.facebook.appevents.AppEventsLogger.Companion; public logPurchase(param0: java.math.BigDecimal, param1: java.util.Currency): void; public isValidForAccessToken(param0: com.facebook.AccessToken): boolean; public static initializeLib(param0: globalAndroid.content.Context, param1: string): void; public logEvent(param0: string, param1: number): void; public static newLogger(param0: globalAndroid.content.Context): com.facebook.appevents.AppEventsLogger; public flush(): void; public static setFlushBehavior(param0: com.facebook.appevents.AppEventsLogger.FlushBehavior): void; public static setUserID(param0: string): void; public static getFlushBehavior(): com.facebook.appevents.AppEventsLogger.FlushBehavior; public logProductItem(param0: string, param1: com.facebook.appevents.AppEventsLogger.ProductAvailability, param2: com.facebook.appevents.AppEventsLogger.ProductCondition, param3: string, param4: string, param5: string, param6: string, param7: java.math.BigDecimal, param8: java.util.Currency, param9: string, param10: string, param11: string, param12: globalAndroid.os.Bundle): void; public logPurchase(param0: java.math.BigDecimal, param1: java.util.Currency, param2: globalAndroid.os.Bundle): void; public getApplicationId(): string; public static activateApp(param0: globalAndroid.app.Application): void; public static newLogger(param0: globalAndroid.content.Context, param1: com.facebook.AccessToken): com.facebook.appevents.AppEventsLogger; public static getUserID(): string; public static clearUserData(): void; public logEvent(param0: string): void; public static setPushNotificationsRegistrationId(param0: string): void; public static setInstallReferrer(param0: string): void; public logPushNotificationOpen(param0: globalAndroid.os.Bundle): void; public static augmentWebView(param0: globalAndroid.webkit.WebView, param1: globalAndroid.content.Context): void; public logPushNotificationOpen(param0: globalAndroid.os.Bundle, param1: string): void; public static getAnonymousAppDeviceGUID(param0: globalAndroid.content.Context): string; public logEvent(param0: string, param1: number, param2: globalAndroid.os.Bundle): void; public static setUserData(param0: string, param1: string, param2: string, param3: string, param4: string, param5: string, param6: string, param7: string, param8: string, param9: string): void; public static newLogger(param0: globalAndroid.content.Context, param1: string, param2: com.facebook.AccessToken): com.facebook.appevents.AppEventsLogger; public static activateApp(param0: globalAndroid.app.Application, param1: string): void; public static getUserData(): string; public static clearUserID(): void; public static onContextStop(): void; public logEvent(param0: string, param1: globalAndroid.os.Bundle): void; public static newLogger(param0: globalAndroid.content.Context, param1: string): com.facebook.appevents.AppEventsLogger; } export module AppEventsLogger { export class Companion { public static class: java.lang.Class<com.facebook.appevents.AppEventsLogger.Companion>; public getUserID(): string; public getUserData(): string; public activateApp(param0: globalAndroid.app.Application, param1: string): void; public setUserData(param0: string, param1: string, param2: string, param3: string, param4: string, param5: string, param6: string, param7: string, param8: string, param9: string): void; public initializeLib(param0: globalAndroid.content.Context, param1: string): void; public setUserID(param0: string): void; public getAnonymousAppDeviceGUID(param0: globalAndroid.content.Context): string; public clearUserData(): void; public onContextStop(): void; public clearUserID(): void; public newLogger(param0: globalAndroid.content.Context): com.facebook.appevents.AppEventsLogger; public newLogger(param0: globalAndroid.content.Context, param1: string): com.facebook.appevents.AppEventsLogger; public setInstallReferrer(param0: string): void; public setFlushBehavior(param0: com.facebook.appevents.AppEventsLogger.FlushBehavior): void; public setPushNotificationsRegistrationId(param0: string): void; public getFlushBehavior(): com.facebook.appevents.AppEventsLogger.FlushBehavior; public activateApp(param0: globalAndroid.app.Application): void; public newLogger(param0: globalAndroid.content.Context, param1: string, param2: com.facebook.AccessToken): com.facebook.appevents.AppEventsLogger; public augmentWebView(param0: globalAndroid.webkit.WebView, param1: globalAndroid.content.Context): void; public newLogger(param0: globalAndroid.content.Context, param1: com.facebook.AccessToken): com.facebook.appevents.AppEventsLogger; } export class FlushBehavior { public static class: java.lang.Class<com.facebook.appevents.AppEventsLogger.FlushBehavior>; public static AUTO: com.facebook.appevents.AppEventsLogger.FlushBehavior; public static EXPLICIT_ONLY: com.facebook.appevents.AppEventsLogger.FlushBehavior; public static valueOf(param0: string): com.facebook.appevents.AppEventsLogger.FlushBehavior; public static values(): androidNative.Array<com.facebook.appevents.AppEventsLogger.FlushBehavior>; } export class ProductAvailability { public static class: java.lang.Class<com.facebook.appevents.AppEventsLogger.ProductAvailability>; public static IN_STOCK: com.facebook.appevents.AppEventsLogger.ProductAvailability; public static OUT_OF_STOCK: com.facebook.appevents.AppEventsLogger.ProductAvailability; public static PREORDER: com.facebook.appevents.AppEventsLogger.ProductAvailability; public static AVALIABLE_FOR_ORDER: com.facebook.appevents.AppEventsLogger.ProductAvailability; public static DISCONTINUED: com.facebook.appevents.AppEventsLogger.ProductAvailability; public static valueOf(param0: string): com.facebook.appevents.AppEventsLogger.ProductAvailability; public static values(): androidNative.Array<com.facebook.appevents.AppEventsLogger.ProductAvailability>; } export class ProductCondition { public static class: java.lang.Class<com.facebook.appevents.AppEventsLogger.ProductCondition>; public static NEW: com.facebook.appevents.AppEventsLogger.ProductCondition; public static REFURBISHED: com.facebook.appevents.AppEventsLogger.ProductCondition; public static USED: com.facebook.appevents.AppEventsLogger.ProductCondition; public static valueOf(param0: string): com.facebook.appevents.AppEventsLogger.ProductCondition; public static values(): androidNative.Array<com.facebook.appevents.AppEventsLogger.ProductCondition>; } } } } } declare module com { export module facebook { export module appevents { export class AppEventsLoggerImpl { public static class: java.lang.Class<com.facebook.appevents.AppEventsLoggerImpl>; public static Companion: com.facebook.appevents.AppEventsLoggerImpl.Companion; public logPurchase(param0: java.math.BigDecimal, param1: java.util.Currency): void; public logPurchaseImplicitly(param0: java.math.BigDecimal, param1: java.util.Currency, param2: globalAndroid.os.Bundle): void; public logPurchase(param0: java.math.BigDecimal, param1: java.util.Currency, param2: globalAndroid.os.Bundle, param3: boolean): void; public logEvent(param0: string, param1: java.lang.Double, param2: globalAndroid.os.Bundle, param3: boolean, param4: java.util.UUID): void; public static getInstallReferrer(): string; public isValidForAccessToken(param0: com.facebook.AccessToken): boolean; public static initializeLib(param0: globalAndroid.content.Context, param1: string): void; public logEvent(param0: string, param1: number): void; public flush(): void; public logEventImplicitly(param0: string, param1: java.lang.Double, param2: globalAndroid.os.Bundle): void; public static setFlushBehavior(param0: com.facebook.appevents.AppEventsLogger.FlushBehavior): void; public logSdkEvent(param0: string, param1: java.lang.Double, param2: globalAndroid.os.Bundle): void; public static getFlushBehavior(): com.facebook.appevents.AppEventsLogger.FlushBehavior; public constructor(param0: globalAndroid.content.Context, param1: string, param2: com.facebook.AccessToken); public logProductItem(param0: string, param1: com.facebook.appevents.AppEventsLogger.ProductAvailability, param2: com.facebook.appevents.AppEventsLogger.ProductCondition, param3: string, param4: string, param5: string, param6: string, param7: java.math.BigDecimal, param8: java.util.Currency, param9: string, param10: string, param11: string, param12: globalAndroid.os.Bundle): void; public logPurchase(param0: java.math.BigDecimal, param1: java.util.Currency, param2: globalAndroid.os.Bundle): void; public getApplicationId(): string; public logEvent(param0: string): void; public static setPushNotificationsRegistrationId(param0: string): void; public logEventImplicitly(param0: string, param1: java.math.BigDecimal, param2: java.util.Currency, param3: globalAndroid.os.Bundle): void; public static getPushNotificationsRegistrationId(): string; public static setInstallReferrer(param0: string): void; public constructor(param0: string, param1: string, param2: com.facebook.AccessToken); public static augmentWebView(param0: globalAndroid.webkit.WebView, param1: globalAndroid.content.Context): void; public logPushNotificationOpen(param0: globalAndroid.os.Bundle, param1: string): void; public static getAnonymousAppDeviceGUID(param0: globalAndroid.content.Context): string; public logEvent(param0: string, param1: number, param2: globalAndroid.os.Bundle): void; public static getAnalyticsExecutor(): java.util.concurrent.Executor; public logEventFromSE(param0: string, param1: string): void; public static activateApp(param0: globalAndroid.app.Application, param1: string): void; public static onContextStop(): void; public logEvent(param0: string, param1: globalAndroid.os.Bundle): void; public static functionDEPRECATED(param0: string): void; } export module AppEventsLoggerImpl { export class Companion { public static class: java.lang.Class<com.facebook.appevents.AppEventsLoggerImpl.Companion>; public getPushNotificationsRegistrationId(): string; public activateApp(param0: globalAndroid.app.Application, param1: string): void; public initializeLib(param0: globalAndroid.content.Context, param1: string): void; public eagerFlush(): void; public getAnonymousAppDeviceGUID(param0: globalAndroid.content.Context): string; public onContextStop(): void; public functionDEPRECATED(param0: string): void; public getAnalyticsExecutor(): java.util.concurrent.Executor; public getInstallReferrer(): string; public setInstallReferrer(param0: string): void; public setFlushBehavior(param0: com.facebook.appevents.AppEventsLogger.FlushBehavior): void; public setPushNotificationsRegistrationId(param0: string): void; public getFlushBehavior(): com.facebook.appevents.AppEventsLogger.FlushBehavior; public augmentWebView(param0: globalAndroid.webkit.WebView, param1: globalAndroid.content.Context): void; } } } } } declare module com { export module facebook { export module appevents { export class AppEventsManager { public static class: java.lang.Class<com.facebook.appevents.AppEventsManager>; public static INSTANCE: com.facebook.appevents.AppEventsManager; public static start(): void; } } } } declare module com { export module facebook { export module appevents { export class FacebookSDKJSInterface { public static class: java.lang.Class<com.facebook.appevents.FacebookSDKJSInterface>; public static Companion: com.facebook.appevents.FacebookSDKJSInterface.Companion; public sendEvent(param0: string, param1: string, param2: string): void; public constructor(param0: globalAndroid.content.Context); public getProtocol(): string; } export module FacebookSDKJSInterface { export class Companion { public static class: java.lang.Class<com.facebook.appevents.FacebookSDKJSInterface.Companion>; public getTAG(): string; } } } } } declare module com { export module facebook { export module appevents { export class FlushReason { public static class: java.lang.Class<com.facebook.appevents.FlushReason>; public static EXPLICIT: com.facebook.appevents.FlushReason; public static TIMER: com.facebook.appevents.FlushReason; public static SESSION_CHANGE: com.facebook.appevents.FlushReason; public static PERSISTED_EVENTS: com.facebook.appevents.FlushReason; public static EVENT_THRESHOLD: com.facebook.appevents.FlushReason; public static EAGER_FLUSHING_EVENT: com.facebook.appevents.FlushReason; public static values(): androidNative.Array<com.facebook.appevents.FlushReason>; public static valueOf(param0: string): com.facebook.appevents.FlushReason; } } } } declare module com { export module facebook { export module appevents { export class FlushResult { public static class: java.lang.Class<com.facebook.appevents.FlushResult>; public static SUCCESS: com.facebook.appevents.FlushResult; public static SERVER_ERROR: com.facebook.appevents.FlushResult; public static NO_CONNECTIVITY: com.facebook.appevents.FlushResult; public static UNKNOWN_ERROR: com.facebook.appevents.FlushResult; public static values(): androidNative.Array<com.facebook.appevents.FlushResult>; public static valueOf(param0: string): com.facebook.appevents.FlushResult; } } } } declare module com { export module facebook { export module appevents { export class FlushStatistics { public static class: java.lang.Class<com.facebook.appevents.FlushStatistics>; public setResult(param0: com.facebook.appevents.FlushResult): void; public getResult(): com.facebook.appevents.FlushResult; public setNumEvents(param0: number): void; public getNumEvents(): number; public constructor(); } } } } declare module com { export module facebook { export module appevents { export class InternalAppEventsLogger { public static class: java.lang.Class<com.facebook.appevents.InternalAppEventsLogger>; public static Companion: com.facebook.appevents.InternalAppEventsLogger.Companion; public logPurchaseImplicitly(param0: java.math.BigDecimal, param1: java.util.Currency, param2: globalAndroid.os.Bundle): void; public logEventImplicitly(param0: string, param1: java.math.BigDecimal, param2: java.util.Currency, param3: globalAndroid.os.Bundle): void; public static getPushNotificationsRegistrationId(): string; public constructor(param0: globalAndroid.content.Context, param1: string); public constructor(param0: string, param1: string, param2: com.facebook.AccessToken); public constructor(param0: com.facebook.appevents.AppEventsLoggerImpl); public static setUserData(param0: globalAndroid.os.Bundle): void; public logChangedSettingsEvent(param0: globalAndroid.os.Bundle): void; public logEvent(param0: string, param1: number, param2: globalAndroid.os.Bundle): void; public logEventImplicitly(param0: string): void; public logEventImplicitly(param0: string, param1: java.lang.Double, param2: globalAndroid.os.Bundle): void; public flush(): void; public logEventImplicitly(param0: string, param1: globalAndroid.os.Bundle): void; public static getAnalyticsExecutor(): java.util.concurrent.Executor; public static getFlushBehavior(): com.facebook.appevents.AppEventsLogger.FlushBehavior; public logEventFromSE(param0: string, param1: string): void; public constructor(param0: globalAndroid.content.Context); public static setInternalUserData(param0: java.util.Map<string,string>): void; public logEvent(param0: string, param1: globalAndroid.os.Bundle): void; } export module InternalAppEventsLogger { export class Companion { public static class: java.lang.Class<com.facebook.appevents.InternalAppEventsLogger.Companion>; public getPushNotificationsRegistrationId(): string; public getAnalyticsExecutor(): java.util.concurrent.Executor; public setUserData(param0: globalAndroid.os.Bundle): void; public getFlushBehavior(): com.facebook.appevents.AppEventsLogger.FlushBehavior; public setInternalUserData(param0: java.util.Map<string,string>): void; } } } } } declare module com { export module facebook { export module appevents { export class PerformanceGuardian { public static class: java.lang.Class<com.facebook.appevents.PerformanceGuardian>; public static INSTANCE: com.facebook.appevents.PerformanceGuardian; public static isBannedActivity(param0: string, param1: com.facebook.appevents.PerformanceGuardian.UseCase): boolean; public static limitProcessTime(param0: string, param1: com.facebook.appevents.PerformanceGuardian.UseCase, param2: number, param3: number): void; } export module PerformanceGuardian { export class UseCase { public static class: java.lang.Class<com.facebook.appevents.PerformanceGuardian.UseCase>; public static CODELESS: com.facebook.appevents.PerformanceGuardian.UseCase; public static SUGGESTED_EVENT: com.facebook.appevents.PerformanceGuardian.UseCase; public static values(): androidNative.Array<com.facebook.appevents.PerformanceGuardian.UseCase>; public static valueOf(param0: string): com.facebook.appevents.PerformanceGuardian.UseCase; } export class WhenMappings { public static class: java.lang.Class<com.facebook.appevents.PerformanceGuardian.WhenMappings>; } } } } } declare module com { export module facebook { export module appevents { export class PersistedEvents { public static class: java.lang.Class<com.facebook.appevents.PersistedEvents>; public static Companion: com.facebook.appevents.PersistedEvents.Companion; public keySet(): java.util.Set<com.facebook.appevents.AccessTokenAppIdPair>; public containsKey(param0: com.facebook.appevents.AccessTokenAppIdPair): boolean; public get(param0: com.facebook.appevents.AccessTokenAppIdPair): java.util.List<com.facebook.appevents.AppEvent>; public constructor(param0: java.util.HashMap<com.facebook.appevents.AccessTokenAppIdPair,java.util.List<com.facebook.appevents.AppEvent>>); public addEvents(param0: com.facebook.appevents.AccessTokenAppIdPair, param1: java.util.List<com.facebook.appevents.AppEvent>): void; public constructor(); } export module PersistedEvents { export class Companion { public static class: java.lang.Class<com.facebook.appevents.PersistedEvents.Companion>; } export class SerializationProxyV1 { public static class: java.lang.Class<com.facebook.appevents.PersistedEvents.SerializationProxyV1>; public static Companion: com.facebook.appevents.PersistedEvents.SerializationProxyV1.Companion; public constructor(param0: java.util.HashMap<com.facebook.appevents.AccessTokenAppIdPair,java.util.List<com.facebook.appevents.AppEvent>>); } export module SerializationProxyV1 { export class Companion { public static class: java.lang.Class<com.facebook.appevents.PersistedEvents.SerializationProxyV1.Companion>; } } } } } } declare module com { export module facebook { export module appevents { export class SessionEventsState { public static class: java.lang.Class<com.facebook.appevents.SessionEventsState>; public static Companion: com.facebook.appevents.SessionEventsState.Companion; public constructor(param0: com.facebook.internal.AttributionIdentifiers, param1: string); public clearInFlightAndStats(param0: boolean): void; public addEvent(param0: com.facebook.appevents.AppEvent): void; public populateRequest(param0: com.facebook.GraphRequest, param1: globalAndroid.content.Context, param2: boolean, param3: boolean): number; public accumulatePersistedEvents(param0: java.util.List<com.facebook.appevents.AppEvent>): void; public getAccumulatedEventCount(): number; public getEventsToPersist(): java.util.List<com.facebook.appevents.AppEvent>; } export module SessionEventsState { export class Companion { public static class: java.lang.Class<com.facebook.appevents.SessionEventsState.Companion>; } } } } } declare module com { export module facebook { export module appevents { export class UserDataStore { public static class: java.lang.Class<com.facebook.appevents.UserDataStore>; public static EMAIL: string; public static FIRST_NAME: string; public static LAST_NAME: string; public static PHONE: string; public static DATE_OF_BIRTH: string; public static GENDER: string; public static CITY: string; public static STATE: string; public static ZIP: string; public static COUNTRY: string; public static INSTANCE: com.facebook.appevents.UserDataStore; public static getHashedUserData$facebook_core_release(): string; public static setUserDataAndHash(param0: string, param1: string, param2: string, param3: string, param4: string, param5: string, param6: string, param7: string, param8: string, param9: string): void; public static clear(): void; public static initStore(): void; public static setInternalUd(param0: java.util.Map<string,string>): void; public static setUserDataAndHash(param0: globalAndroid.os.Bundle): void; public static getAllHashedUserData(): string; } } } } declare module com { export module facebook { export module appevents { export module aam { export class MetadataIndexer { public static class: java.lang.Class<com.facebook.appevents.aam.MetadataIndexer>; public static INSTANCE: com.facebook.appevents.aam.MetadataIndexer; public static enable(): void; public static onActivityResumed(param0: globalAndroid.app.Activity): void; } } } } } declare module com { export module facebook { export module appevents { export module aam { export class MetadataMatcher { public static class: java.lang.Class<com.facebook.appevents.aam.MetadataMatcher>; public static INSTANCE: com.facebook.appevents.aam.MetadataMatcher; public static matchIndicator(param0: java.util.List<string>, param1: java.util.List<string>): boolean; public static getCurrentViewIndicators(param0: globalAndroid.view.View): java.util.List<string>; public static getAroundViewIndicators(param0: globalAndroid.view.View): java.util.List<string>; public static matchValue(param0: string, param1: string): boolean; } } } } } declare module com { export module facebook { export module appevents { export module aam { export class MetadataRule { public static class: java.lang.Class<com.facebook.appevents.aam.MetadataRule>; public static Companion: com.facebook.appevents.aam.MetadataRule.Companion; public static getEnabledRuleNames(): java.util.Set<string>; public getName(): string; public static updateRules(param0: string): void; public getValRule(): string; public getKeyRules(): java.util.List<string>; public static getRules(): java.util.Set<com.facebook.appevents.aam.MetadataRule>; } export module MetadataRule { export class Companion { public static class: java.lang.Class<com.facebook.appevents.aam.MetadataRule.Companion>; public getEnabledRuleNames(): java.util.Set<string>; public getRules(): java.util.Set<com.facebook.appevents.aam.MetadataRule>; public updateRules(param0: string): void; } } } } } } declare module com { export module facebook { export module appevents { export module aam { export class MetadataViewObserver { public static class: java.lang.Class<com.facebook.appevents.aam.MetadataViewObserver>; public static Companion: com.facebook.appevents.aam.MetadataViewObserver.Companion; public static startTrackingActivity(param0: globalAndroid.app.Activity): void; public static stopTrackingActivity(param0: globalAndroid.app.Activity): void; public onGlobalFocusChanged(param0: globalAndroid.view.View, param1: globalAndroid.view.View): void; } export module MetadataViewObserver { export class Companion { public static class: java.lang.Class<com.facebook.appevents.aam.MetadataViewObserver.Companion>; public startTrackingActivity(param0: globalAndroid.app.Activity): void; public stopTrackingActivity(param0: globalAndroid.app.Activity): void; } } } } } } declare module com { export module facebook { export module appevents { export module codeless { export class CodelessLoggingEventListener { public static class: java.lang.Class<com.facebook.appevents.codeless.CodelessLoggingEventListener>; public static INSTANCE: com.facebook.appevents.codeless.CodelessLoggingEventListener; public updateParameters$facebook_core_release(param0: globalAndroid.os.Bundle): void; public static logEvent$facebook_core_release(param0: com.facebook.appevents.codeless.internal.EventBinding, param1: globalAndroid.view.View, param2: globalAndroid.view.View): void; public static getOnClickListener(param0: com.facebook.appevents.codeless.internal.EventBinding, param1: globalAndroid.view.View, param2: globalAndroid.view.View): com.facebook.appevents.codeless.CodelessLoggingEventListener.AutoLoggingOnClickListener; public static getOnItemClickListener(param0: com.facebook.appevents.codeless.internal.EventBinding, param1: globalAndroid.view.View, param2: globalAndroid.widget.AdapterView<any>): com.facebook.appevents.codeless.CodelessLoggingEventListener.AutoLoggingOnItemClickListener; } export module CodelessLoggingEventListener { export class AutoLoggingOnClickListener { public static class: java.lang.Class<com.facebook.appevents.codeless.CodelessLoggingEventListener.AutoLoggingOnClickListener>; public getSupportCodelessLogging(): boolean; public setSupportCodelessLogging(param0: boolean): void; public constructor(param0: com.facebook.appevents.codeless.internal.EventBinding, param1: globalAndroid.view.View, param2: globalAndroid.view.View); public onClick(param0: globalAndroid.view.View): void; } export class AutoLoggingOnItemClickListener { public static class: java.lang.Class<com.facebook.appevents.codeless.CodelessLoggingEventListener.AutoLoggingOnItemClickListener>; public getSupportCodelessLogging(): boolean; public setSupportCodelessLogging(param0: boolean): void; public onItemClick(param0: globalAndroid.widget.AdapterView<any>, param1: globalAndroid.view.View, param2: number, param3: number): void; public constructor(param0: com.facebook.appevents.codeless.internal.EventBinding, param1: globalAndroid.view.View, param2: globalAndroid.widget.AdapterView<any>); } } } } } } declare module com { export module facebook { export module appevents { export module codeless { export class CodelessManager { public static class: java.lang.Class<com.facebook.appevents.codeless.CodelessManager>; public static INSTANCE: com.facebook.appevents.codeless.CodelessManager; public static disable(): void; public static updateAppIndexing$facebook_core_release(param0: boolean): void; public static isDebugOnEmulator$facebook_core_release(): boolean; public static getCurrentDeviceSessionID$facebook_core_release(): string; public static getIsAppIndexingEnabled$facebook_core_release(): boolean; public static enable(): void; public static onActivityDestroyed(param0: globalAndroid.app.Activity): void; public static checkCodelessSession$facebook_core_release(param0: string): void; public static onActivityResumed(param0: globalAndroid.app.Activity): void; public static onActivityPaused(param0: globalAndroid.app.Activity): void; } } } } } declare module com { export module facebook { export module appevents { export module codeless { export class CodelessMatcher { public static class: java.lang.Class<com.facebook.appevents.codeless.CodelessMatcher>; public static Companion: com.facebook.appevents.codeless.CodelessMatcher.Companion; public add(param0: globalAndroid.app.Activity): void; public remove(param0: globalAndroid.app.Activity): void; public static getParameters(param0: com.facebook.appevents.codeless.internal.EventBinding, param1: globalAndroid.view.View, param2: globalAndroid.view.View): globalAndroid.os.Bundle; public static getInstance(): com.facebook.appevents.codeless.CodelessMatcher; public destroy(param0: globalAndroid.app.Activity): void; } export module CodelessMatcher { export class Companion { public static class: java.lang.Class<com.facebook.appevents.codeless.CodelessMatcher.Companion>; public getParameters(param0: com.facebook.appevents.codeless.internal.EventBinding, param1: globalAndroid.view.View, param2: globalAndroid.view.View): globalAndroid.os.Bundle; public getInstance(): com.facebook.appevents.codeless.CodelessMatcher; } export class MatchedView { public static class: java.lang.Class<com.facebook.appevents.codeless.CodelessMatcher.MatchedView>; public constructor(param0: globalAndroid.view.View, param1: string); public getView(): globalAndroid.view.View; public getViewMapKey(): string; } export class ViewMatcher { public static class: java.lang.Class<com.facebook.appevents.codeless.CodelessMatcher.ViewMatcher>; public static Companion: com.facebook.appevents.codeless.CodelessMatcher.ViewMatcher.Companion; public run(): void; public onScrollChanged(): void; public onGlobalLayout(): void; public static findViewByPath(param0: com.facebook.appevents.codeless.internal.EventBinding, param1: globalAndroid.view.View, param2: java.util.List<com.facebook.appevents.codeless.internal.PathComponent>, param3: number, param4: number, param5: string): java.util.List<com.facebook.appevents.codeless.CodelessMatcher.MatchedView>; public constructor(param0: globalAndroid.view.View, param1: globalAndroid.os.Handler, param2: java.util.HashSet<string>, param3: string); } export module ViewMatcher { export class Companion { public static class: java.lang.Class<com.facebook.appevents.codeless.CodelessMatcher.ViewMatcher.Companion>; public findViewByPath(param0: com.facebook.appevents.codeless.internal.EventBinding, param1: globalAndroid.view.View, param2: java.util.List<com.facebook.appevents.codeless.internal.PathComponent>, param3: number, param4: number, param5: string): java.util.List<com.facebook.appevents.codeless.CodelessMatcher.MatchedView>; } } } } } } } declare module com { export module facebook { export module appevents { export module codeless { export class RCTCodelessLoggingEventListener { public static class: java.lang.Class<com.facebook.appevents.codeless.RCTCodelessLoggingEventListener>; public static INSTANCE: com.facebook.appevents.codeless.RCTCodelessLoggingEventListener; public static getOnTouchListener(param0: com.facebook.appevents.codeless.internal.EventBinding, param1: globalAndroid.view.View, param2: globalAndroid.view.View): com.facebook.appevents.codeless.RCTCodelessLoggingEventListener.AutoLoggingOnTouchListener; } export module RCTCodelessLoggingEventListener { export class AutoLoggingOnTouchListener { public static class: java.lang.Class<com.facebook.appevents.codeless.RCTCodelessLoggingEventListener.AutoLoggingOnTouchListener>; public getSupportCodelessLogging(): boolean; public setSupportCodelessLogging(param0: boolean): void; public constructor(param0: com.facebook.appevents.codeless.internal.EventBinding, param1: globalAndroid.view.View, param2: globalAndroid.view.View); public onTouch(param0: globalAndroid.view.View, param1: globalAndroid.view.MotionEvent): boolean; } } } } } } declare module com { export module facebook { export module appevents { export module codeless { export class ViewIndexer { public static class: java.lang.Class<com.facebook.appevents.codeless.ViewIndexer>; public static Companion: com.facebook.appevents.codeless.ViewIndexer.Companion; public unschedule(): void; public static buildAppIndexingRequest(param0: string, param1: com.facebook.AccessToken, param2: string, param3: string): com.facebook.GraphRequest; public processRequest(param0: com.facebook.GraphRequest, param1: string): void; public static sendToServerUnityInstance(param0: string): void; public schedule(): void; public constructor(param0: globalAndroid.app.Activity); } export module ViewIndexer { export class Companion { public static class: java.lang.Class<com.facebook.appevents.codeless.ViewIndexer.Companion>; public buildAppIndexingRequest(param0: string, param1: com.facebook.AccessToken, param2: string, param3: string): com.facebook.GraphRequest; public sendToServerUnityInstance(param0: string): void; } export class ScreenshotTaker extends java.util.concurrent.Callable<string> { public static class: java.lang.Class<com.facebook.appevents.codeless.ViewIndexer.ScreenshotTaker>; public call(): string; public constructor(param0: globalAndroid.view.View); } } } } } } declare module com { export module facebook { export module appevents { export module codeless { export class ViewIndexingTrigger { public static class: java.lang.Class<com.facebook.appevents.codeless.ViewIndexingTrigger>; public static Companion: com.facebook.appevents.codeless.ViewIndexingTrigger.Companion; public setOnShakeListener(param0: com.facebook.appevents.codeless.ViewIndexingTrigger.OnShakeListener): void; public onSensorChanged(param0: globalAndroid.hardware.SensorEvent): void; public onAccuracyChanged(param0: globalAndroid.hardware.Sensor, param1: number): void; public constructor(); } export module ViewIndexingTrigger { export class Companion { public static class: java.lang.Class<com.facebook.appevents.codeless.ViewIndexingTrigger.Companion>; } export class OnShakeListener { public static class: java.lang.Class<com.facebook.appevents.codeless.ViewIndexingTrigger.OnShakeListener>; /** * Constructs a new instance of the com.facebook.appevents.codeless.ViewIndexingTrigger$OnShakeListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onShake(): void; }); public constructor(); public onShake(): void; } } } } } } declare module com { export module facebook { export module appevents { export module codeless { export module internal { export class Constants { public static class: java.lang.Class<com.facebook.appevents.codeless.internal.Constants>; public static MAX_TREE_DEPTH: number; public static IS_CODELESS_EVENT_KEY: string; public static EVENT_MAPPING_PATH_TYPE_KEY: string; public static PATH_TYPE_RELATIVE: string; public static PATH_TYPE_ABSOLUTE: string; public static PLATFORM: string; public static APP_INDEXING_SCHEDULE_INTERVAL_MS: number; public static APP_INDEXING_ENABLED: string; public static DEVICE_SESSION_ID: string; public static EXTINFO: string; public static APP_INDEXING: string; public static BUTTON_SAMPLING: string; public static INSTANCE: com.facebook.appevents.codeless.internal.Constants; } } } } } } declare module com { export module facebook { export module appevents { export module codeless { export module internal { export class EventBinding { public static class: java.lang.Class<com.facebook.appevents.codeless.internal.EventBinding>; public static Companion: com.facebook.appevents.codeless.internal.EventBinding.Companion; public getViewParameters(): java.util.List<com.facebook.appevents.codeless.internal.ParameterComponent>; public getAppVersion(): string; public getActivityName(): string; public static getInstanceFromJson(param0: org.json.JSONObject): com.facebook.appevents.codeless.internal.EventBinding; public getEventName(): string; public getMethod(): com.facebook.appevents.codeless.internal.EventBinding.MappingMethod; public static parseArray(param0: org.json.JSONArray): java.util.List<com.facebook.appevents.codeless.internal.EventBinding>; public getViewPath(): java.util.List<com.facebook.appevents.codeless.internal.PathComponent>; public getComponentId(): string; public getPathType(): string; public constructor(param0: string, param1: com.facebook.appevents.codeless.internal.EventBinding.MappingMethod, param2: com.facebook.appevents.codeless.internal.EventBinding.ActionType, param3: string, param4: java.util.List<com.facebook.appevents.codeless.internal.PathComponent>, param5: java.util.List<com.facebook.appevents.codeless.internal.ParameterComponent>, param6: string, param7: string, param8: string); public getType(): com.facebook.appevents.codeless.internal.EventBinding.ActionType; } export module EventBinding { export class ActionType { public static class: java.lang.Class<com.facebook.appevents.codeless.internal.EventBinding.ActionType>; public static CLICK: com.facebook.appevents.codeless.internal.EventBinding.ActionType; public static SELECTED: com.facebook.appevents.codeless.internal.EventBinding.ActionType; public static TEXT_CHANGED: com.facebook.appevents.codeless.internal.EventBinding.ActionType; public static valueOf(param0: string): com.facebook.appevents.codeless.internal.EventBinding.ActionType; public static values(): androidNative.Array<com.facebook.appevents.codeless.internal.EventBinding.ActionType>; } export class Companion { public static class: java.lang.Class<com.facebook.appevents.codeless.internal.EventBinding.Companion>; public parseArray(param0: org.json.JSONArray): java.util.List<com.facebook.appevents.codeless.internal.EventBinding>; public getInstanceFromJson(param0: org.json.JSONObject): com.facebook.appevents.codeless.internal.EventBinding; } export class MappingMethod { public static class: java.lang.Class<com.facebook.appevents.codeless.internal.EventBinding.MappingMethod>; public static MANUAL: com.facebook.appevents.codeless.internal.EventBinding.MappingMethod; public static INFERENCE: com.facebook.appevents.codeless.internal.EventBinding.MappingMethod; public static valueOf(param0: string): com.facebook.appevents.codeless.internal.EventBinding.MappingMethod; public static values(): androidNative.Array<com.facebook.appevents.codeless.internal.EventBinding.MappingMethod>; } } } } } } } declare module com { export module facebook { export module appevents { export module codeless { export module internal { export class ParameterComponent { public static class: java.lang.Class<com.facebook.appevents.codeless.internal.ParameterComponent>; public static Companion: com.facebook.appevents.codeless.internal.ParameterComponent.Companion; public getValue(): string; public constructor(param0: org.json.JSONObject); public getPath(): java.util.List<com.facebook.appevents.codeless.internal.PathComponent>; public getName(): string; public getPathType(): string; } export module ParameterComponent { export class Companion { public static class: java.lang.Class<com.facebook.appevents.codeless.internal.ParameterComponent.Companion>; } } } } } } } declare module com { export module facebook { export module appevents { export module codeless { export module internal { export class PathComponent { public static class: java.lang.Class<com.facebook.appevents.codeless.internal.PathComponent>; public static Companion: com.facebook.appevents.codeless.internal.PathComponent.Companion; public getHint(): string; public getMatchBitmask(): number; public getTag(): string; public constructor(param0: org.json.JSONObject); public getClassName(): string; public getIndex(): number; public getDescription(): string; public getText(): string; public getId(): number; } export module PathComponent { export class Companion { public static class: java.lang.Class<com.facebook.appevents.codeless.internal.PathComponent.Companion>; } export class MatchBitmaskType { public static class: java.lang.Class<com.facebook.appevents.codeless.internal.PathComponent.MatchBitmaskType>; public static ID: com.facebook.appevents.codeless.internal.PathComponent.MatchBitmaskType; public static TEXT: com.facebook.appevents.codeless.internal.PathComponent.MatchBitmaskType; public static TAG: com.facebook.appevents.codeless.internal.PathComponent.MatchBitmaskType; public static DESCRIPTION: com.facebook.appevents.codeless.internal.PathComponent.MatchBitmaskType; public static HINT: com.facebook.appevents.codeless.internal.PathComponent.MatchBitmaskType; public static values(): androidNative.Array<com.facebook.appevents.codeless.internal.PathComponent.MatchBitmaskType>; public static valueOf(param0: string): com.facebook.appevents.codeless.internal.PathComponent.MatchBitmaskType; public getValue(): number; } } } } } } } declare module com { export module facebook { export module appevents { export module codeless { export module internal { export class SensitiveUserDataUtils { public static class: java.lang.Class<com.facebook.appevents.codeless.internal.SensitiveUserDataUtils>; public static INSTANCE: com.facebook.appevents.codeless.internal.SensitiveUserDataUtils; public static isSensitiveUserData(param0: globalAndroid.view.View): boolean; } } } } } } declare module com { export module facebook { export module appevents { export module codeless { export module internal { export class UnityReflection { public static class: java.lang.Class<com.facebook.appevents.codeless.internal.UnityReflection>; public static INSTANCE: com.facebook.appevents.codeless.internal.UnityReflection; public static captureViewHierarchy(): void; public static sendMessage(param0: string, param1: string, param2: string): void; public static sendEventMapping(param0: string): void; } } } } } } declare module com { export module facebook { export module appevents { export module codeless { export module internal { export class ViewHierarchy { public static class: java.lang.Class<com.facebook.appevents.codeless.internal.ViewHierarchy>; public static INSTANCE: com.facebook.appevents.codeless.internal.ViewHierarchy; public static getDictionaryOfView(param0: globalAndroid.view.View): org.json.JSONObject; public static getClassTypeBitmask(param0: globalAndroid.view.View): number; public static getTextOfView(param0: globalAndroid.view.View): string; public static getExistingOnClickListener(param0: globalAndroid.view.View): globalAndroid.view.View.OnClickListener; public static getExistingOnTouchListener(param0: globalAndroid.view.View): globalAndroid.view.View.OnTouchListener; public static setOnClickListener(param0: globalAndroid.view.View, param1: globalAndroid.view.View.OnClickListener): void; public static updateBasicInfoOfView(param0: globalAndroid.view.View, param1: org.json.JSONObject): void; public static getChildrenOfView(param0: globalAndroid.view.View): java.util.List<globalAndroid.view.View>; public isRCTButton(param0: globalAndroid.view.View, param1: globalAndroid.view.View): boolean; public static getParentOfView(param0: globalAndroid.view.View): globalAndroid.view.ViewGroup; public static getHintOfView(param0: globalAndroid.view.View): string; public static findRCTRootView(param0: globalAndroid.view.View): globalAndroid.view.View; public static updateAppearanceOfView(param0: globalAndroid.view.View, param1: org.json.JSONObject, param2: number): void; } } } } } } declare module com { export module facebook { export module appevents { export module eventdeactivation { export class EventDeactivationManager { public static class: java.lang.Class<com.facebook.appevents.eventdeactivation.EventDeactivationManager>; public static INSTANCE: com.facebook.appevents.eventdeactivation.EventDeactivationManager; public static processEvents(param0: java.util.List<com.facebook.appevents.AppEvent>): void; public static processDeprecatedParameters(param0: java.util.Map<string,string>, param1: string): void; public static enable(): void; } export module EventDeactivationManager { export class DeprecatedParamFilter { public static class: java.lang.Class<com.facebook.appevents.eventdeactivation.EventDeactivationManager.DeprecatedParamFilter>; public setDeprecateParams(param0: java.util.List<string>): void; public getEventName(): string; public setEventName(param0: string): void; public constructor(param0: string, param1: java.util.List<string>); public getDeprecateParams(): java.util.List<string>; } } } } } } declare module com { export module facebook { export module appevents { export module iap { export class InAppPurchaseActivityLifecycleTracker { public static class: java.lang.Class<com.facebook.appevents.iap.InAppPurchaseActivityLifecycleTracker>; public static INSTANCE: com.facebook.appevents.iap.InAppPurchaseActivityLifecycleTracker; public static startIapLogging(): void; } } } } } declare module com { export module facebook { export module appevents { export module iap { export class InAppPurchaseAutoLogger { public static class: java.lang.Class<com.facebook.appevents.iap.InAppPurchaseAutoLogger>; public static INSTANCE: com.facebook.appevents.iap.InAppPurchaseAutoLogger; public static startIapLogging(param0: globalAndroid.content.Context): void; } } } } } declare module com { export module facebook { export module appevents { export module iap { export class InAppPurchaseBillingClientWrapper { public static class: java.lang.Class<com.facebook.appevents.iap.InAppPurchaseBillingClientWrapper>; public static Companion: com.facebook.appevents.iap.InAppPurchaseBillingClientWrapper.Companion; public queryPurchase(param0: string, param1: java.lang.Runnable): void; public static getOrCreateInstance(param0: globalAndroid.content.Context): com.facebook.appevents.iap.InAppPurchaseBillingClientWrapper; public queryPurchaseHistory(param0: string, param1: java.lang.Runnable): void; } export module InAppPurchaseBillingClientWrapper { export class BillingClientStateListenerWrapper { public static class: java.lang.Class<com.facebook.appevents.iap.InAppPurchaseBillingClientWrapper.BillingClientStateListenerWrapper>; public invoke(param0: any, param1: java.lang.reflect.Method, param2: androidNative.Array<any>): any; public constructor(); } export class Companion { public static class: java.lang.Class<com.facebook.appevents.iap.InAppPurchaseBillingClientWrapper.Companion>; public getSkuDetailsMap(): java.util.Map<string,org.json.JSONObject>; public isServiceConnected(): java.util.concurrent.atomic.AtomicBoolean; public getPurchaseDetailsMap(): java.util.Map<string,org.json.JSONObject>; public getOrCreateInstance(param0: globalAndroid.content.Context): com.facebook.appevents.iap.InAppPurchaseBillingClientWrapper; } export class PurchaseHistoryResponseListenerWrapper { public static class: java.lang.Class<com.facebook.appevents.iap.InAppPurchaseBillingClientWrapper.PurchaseHistoryResponseListenerWrapper>; public invoke(param0: any, param1: java.lang.reflect.Method, param2: androidNative.Array<any>): any; public getRunnable(): java.lang.Runnable; public constructor(param0: java.lang.Runnable); public setRunnable(param0: java.lang.Runnable): void; } export class PurchasesUpdatedListenerWrapper { public static class: java.lang.Class<com.facebook.appevents.iap.InAppPurchaseBillingClientWrapper.PurchasesUpdatedListenerWrapper>; public invoke(param0: any, param1: java.lang.reflect.Method, param2: androidNative.Array<any>): any; public constructor(); } export class SkuDetailsResponseListenerWrapper { public static class: java.lang.Class<com.facebook.appevents.iap.InAppPurchaseBillingClientWrapper.SkuDetailsResponseListenerWrapper>; public invoke(param0: any, param1: java.lang.reflect.Method, param2: androidNative.Array<any>): any; public getRunnable(): java.lang.Runnable; public parseSkuDetails(param0: java.util.List<any>): void; public constructor(param0: java.lang.Runnable); public setRunnable(param0: java.lang.Runnable): void; } } } } } } declare module com { export module facebook { export module appevents { export module iap { export class InAppPurchaseEventManager { public static class: java.lang.Class<com.facebook.appevents.iap.InAppPurchaseEventManager>; public static INSTANCE: com.facebook.appevents.iap.InAppPurchaseEventManager; public static asInterface(param0: globalAndroid.content.Context, param1: globalAndroid.os.IBinder): any; public static getPurchasesInapp(param0: globalAndroid.content.Context, param1: any): java.util.ArrayList<string>; public static getSkuDetails(param0: globalAndroid.content.Context, param1: java.util.ArrayList<string>, param2: any, param3: boolean): java.util.Map<string,string>; public hasFreeTrialPeirod(param0: string): boolean; public static getPurchasesSubs(param0: globalAndroid.content.Context, param1: any): java.util.ArrayList<string>; public static clearSkuDetailsCache(): void; public static getPurchaseHistoryInapp(param0: globalAndroid.content.Context, param1: any): java.util.ArrayList<string>; } } } } } declare module com { export module facebook { export module appevents { export module iap { export class InAppPurchaseLoggerManager { public static class: java.lang.Class<com.facebook.appevents.iap.InAppPurchaseLoggerManager>; public static INSTANCE: com.facebook.appevents.iap.InAppPurchaseLoggerManager; public static filterPurchaseLogging(param0: java.util.Map<string,org.json.JSONObject>, param1: java.util.Map<string,any>): void; public cacheDeDupPurchase$facebook_core_release(param0: java.util.Map<string,org.json.JSONObject>): java.util.Map<string,org.json.JSONObject>; public static eligibleQueryPurchaseHistory(): boolean; public constructLoggingReadyMap$facebook_core_release(param0: java.util.Map<string,any>, param1: java.util.Map<string,any>): java.util.Map<string,string>; public clearOutdatedProductInfoInCache$facebook_core_release(): void; } } } } } declare module com { export module facebook { export module appevents { export module iap { export class InAppPurchaseManager { public static class: java.lang.Class<com.facebook.appevents.iap.InAppPurchaseManager>; public static INSTANCE: com.facebook.appevents.iap.InAppPurchaseManager; public static startTracking(): void; public static enableAutoLogging(): void; } } } } } declare module com { export module facebook { export module appevents { export module iap { export class InAppPurchaseSkuDetailsWrapper { public static class: java.lang.Class<com.facebook.appevents.iap.InAppPurchaseSkuDetailsWrapper>; public static Companion: com.facebook.appevents.iap.InAppPurchaseSkuDetailsWrapper.Companion; public constructor(param0: java.lang.Class<any>, param1: java.lang.Class<any>, param2: java.lang.reflect.Method, param3: java.lang.reflect.Method, param4: java.lang.reflect.Method, param5: java.lang.reflect.Method); public static getOrCreateInstance(): com.facebook.appevents.iap.InAppPurchaseSkuDetailsWrapper; public getSkuDetailsParams(param0: string, param1: java.util.List<string>): any; public getSkuDetailsParamsClazz(): java.lang.Class<any>; } export module InAppPurchaseSkuDetailsWrapper { export class Companion { public static class: java.lang.Class<com.facebook.appevents.iap.InAppPurchaseSkuDetailsWrapper.Companion>; public getOrCreateInstance(): com.facebook.appevents.iap.InAppPurchaseSkuDetailsWrapper; } } } } } } declare module com { export module facebook { export module appevents { export module iap { export class InAppPurchaseUtils { public static class: java.lang.Class<com.facebook.appevents.iap.InAppPurchaseUtils>; public static INSTANCE: com.facebook.appevents.iap.InAppPurchaseUtils; public static getClass(param0: string): java.lang.Class<any>; public static getMethod(param0: java.lang.Class<any>, param1: string, param2: androidNative.Array<java.lang.Class<any>>): java.lang.reflect.Method; public static invokeMethod(param0: java.lang.Class<any>, param1: java.lang.reflect.Method, param2: any, param3: androidNative.Array<any>): any; } } } } } declare module com { export module facebook { export module appevents { export module integrity { export class IntegrityManager { public static class: java.lang.Class<com.facebook.appevents.integrity.IntegrityManager>; public static INTEGRITY_TYPE_NONE: string; public static INTEGRITY_TYPE_ADDRESS: string; public static INTEGRITY_TYPE_HEALTH: string; public static INSTANCE: com.facebook.appevents.integrity.IntegrityManager; public static processParameters(param0: java.util.Map<string,string>): void; public static enable(): void; } } } } } declare module com { export module facebook { export module appevents { export module internal { export class ActivityLifecycleTracker { public static class: java.lang.Class<com.facebook.appevents.internal.ActivityLifecycleTracker>; public static INSTANCE: com.facebook.appevents.internal.ActivityLifecycleTracker; public static isInBackground(): boolean; public static getCurrentSessionGuid(): java.util.UUID; public static isTracking(): boolean; public static startTracking(param0: globalAndroid.app.Application, param1: string): void; public static getCurrentActivity(): globalAndroid.app.Activity; public static onActivityCreated(param0: globalAndroid.app.Activity): void; public static onActivityResumed(param0: globalAndroid.app.Activity): void; } } } } } declare module com { export module facebook { export module appevents { export module internal { export class AppEventUtility { public static class: java.lang.Class<com.facebook.appevents.internal.AppEventUtility>; public static INSTANCE: com.facebook.appevents.internal.AppEventUtility; public static assertIsNotMainThread(): void; public static getRootView(param0: globalAndroid.app.Activity): globalAndroid.view.View; public static bytesToHex(param0: androidNative.Array<number>): string; public static getAppVersion(): string; public static assertIsMainThread(): void; public static normalizePrice(param0: string): number; public static isEmulator(): boolean; } } } } } declare module com { export module facebook { export module appevents { export module internal { export class AppEventsLoggerUtility { public static class: java.lang.Class<com.facebook.appevents.internal.AppEventsLoggerUtility>; public static INSTANCE: com.facebook.appevents.internal.AppEventsLoggerUtility; public static getJSONObjectForGraphAPICall(param0: com.facebook.appevents.internal.AppEventsLoggerUtility.GraphAPIActivityType, param1: com.facebook.internal.AttributionIdentifiers, param2: string, param3: boolean, param4: globalAndroid.content.Context): org.json.JSONObject; } export module AppEventsLoggerUtility { export class GraphAPIActivityType { public static class: java.lang.Class<com.facebook.appevents.internal.AppEventsLoggerUtility.GraphAPIActivityType>; public static MOBILE_INSTALL_EVENT: com.facebook.appevents.internal.AppEventsLoggerUtility.GraphAPIActivityType; public static CUSTOM_APP_EVENTS: com.facebook.appevents.internal.AppEventsLoggerUtility.GraphAPIActivityType; public static values(): androidNative.Array<com.facebook.appevents.internal.AppEventsLoggerUtility.GraphAPIActivityType>; public static valueOf(param0: string): com.facebook.appevents.internal.AppEventsLoggerUtility.GraphAPIActivityType; } } } } } } declare module com { export module facebook { export module appevents { export module internal { export class AutomaticAnalyticsLogger { public static class: java.lang.Class<com.facebook.appevents.internal.AutomaticAnalyticsLogger>; public static INSTANCE: com.facebook.appevents.internal.AutomaticAnalyticsLogger; public static logPurchase(param0: string, param1: string, param2: boolean): void; public static isImplicitPurchaseLoggingEnabled(): boolean; public static logActivateAppEvent(): void; public static logActivityTimeSpentEvent(param0: string, param1: number): void; } export module AutomaticAnalyticsLogger { export class PurchaseLoggingParameters { public static class: java.lang.Class<com.facebook.appevents.internal.AutomaticAnalyticsLogger.PurchaseLoggingParameters>; public getPurchaseAmount(): java.math.BigDecimal; public getCurrency(): java.util.Currency; public getParam(): globalAndroid.os.Bundle; public setPurchaseAmount(param0: java.math.BigDecimal): void; public setParam(param0: globalAndroid.os.Bundle): void; public constructor(param0: java.math.BigDecimal, param1: java.util.Currency, param2: globalAndroid.os.Bundle); public setCurrency(param0: java.util.Currency): void; } } } } } } declare module com { export module facebook { export module appevents { export module internal { export class Constants { public static class: java.lang.Class<com.facebook.appevents.internal.Constants>; public static LOG_TIME_APP_EVENT_KEY: string; public static EVENT_NAME_EVENT_KEY: string; public static EVENT_NAME_MD5_EVENT_KEY: string; public static AA_TIME_SPENT_EVENT_NAME: string; public static AA_TIME_SPENT_SCREEN_PARAMETER_NAME: string; public static IAP_PRODUCT_ID: string; public static IAP_PURCHASE_TIME: string; public static IAP_PURCHASE_TOKEN: string; public static IAP_PRODUCT_TYPE: string; public static IAP_PRODUCT_TITLE: string; public static IAP_PRODUCT_DESCRIPTION: string; public static IAP_PACKAGE_NAME: string; public static IAP_SUBSCRIPTION_AUTORENEWING: string; public static IAP_SUBSCRIPTION_PERIOD: string; public static IAP_FREE_TRIAL_PERIOD: string; public static IAP_INTRO_PRICE_AMOUNT_MICROS: string; public static IAP_INTRO_PRICE_CYCLES: string; public static EVENT_PARAM_PRODUCT_ITEM_ID: string; public static EVENT_PARAM_PRODUCT_AVAILABILITY: string; public static EVENT_PARAM_PRODUCT_CONDITION: string; public static EVENT_PARAM_PRODUCT_DESCRIPTION: string; public static EVENT_PARAM_PRODUCT_IMAGE_LINK: string; public static EVENT_PARAM_PRODUCT_LINK: string; public static EVENT_PARAM_PRODUCT_TITLE: string; public static EVENT_PARAM_PRODUCT_GTIN: string; public static EVENT_PARAM_PRODUCT_MPN: string; public static EVENT_PARAM_PRODUCT_BRAND: string; public static EVENT_PARAM_PRODUCT_PRICE_AMOUNT: string; public static EVENT_PARAM_PRODUCT_PRICE_CURRENCY: string; public static INSTANCE: com.facebook.appevents.internal.Constants; public static getDefaultAppEventsSessionTimeoutInSeconds(): number; } } } } } declare module com { export module facebook { export module appevents { export module internal { export class FileDownloadTask extends globalAndroid.os.AsyncTask<string,java.lang.Void,java.lang.Boolean> { public static class: java.lang.Class<com.facebook.appevents.internal.FileDownloadTask>; public onPostExecute(param0: boolean): void; public constructor(param0: string, param1: java.io.File, param2: com.facebook.appevents.internal.FileDownloadTask.Callback); public doInBackground(param0: androidNative.Array<string>): java.lang.Boolean; } export module FileDownloadTask { export class Callback { public static class: java.lang.Class<com.facebook.appevents.internal.FileDownloadTask.Callback>; /** * Constructs a new instance of the com.facebook.appevents.internal.FileDownloadTask$Callback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onComplete(param0: java.io.File): void; }); public constructor(); public onComplete(param0: java.io.File): void; } } } } } } declare module com { export module facebook { export module appevents { export module internal { export class HashUtils { public static class: java.lang.Class<com.facebook.appevents.internal.HashUtils>; public static INSTANCE: com.facebook.appevents.internal.HashUtils; public static computeChecksumWithPackageManager(param0: globalAndroid.content.Context, param1: java.lang.Long): string; public static computeChecksum(param0: string): string; } } } } } declare module com { export module facebook { export module appevents { export module internal { export class SessionInfo { public static class: java.lang.Class<com.facebook.appevents.internal.SessionInfo>; public static Companion: com.facebook.appevents.internal.SessionInfo.Companion; public getDiskRestoreTime(): java.lang.Long; public getSourceApplicationInfo(): com.facebook.appevents.internal.SourceApplicationInfo; public static getStoredSessionInfo(): com.facebook.appevents.internal.SessionInfo; public getInterruptionCount(): number; public getSessionId(): java.util.UUID; public static clearSavedSessionFromDisk(): void; public incrementInterruptionCount(): void; public setDiskRestoreTime(param0: java.lang.Long): void; public setSourceApplicationInfo(param0: com.facebook.appevents.internal.SourceApplicationInfo): void; public writeSessionToDisk(): void; public getSessionLastEventTime(): java.lang.Long; public setSessionLastEventTime(param0: java.lang.Long): void; public getSessionLength(): number; public getSessionStartTime(): java.lang.Long; public setSessionId(param0: java.util.UUID): void; public constructor(param0: java.lang.Long, param1: java.lang.Long, param2: java.util.UUID); public constructor(param0: java.lang.Long, param1: java.lang.Long); } export module SessionInfo { export class Companion { public static class: java.lang.Class<com.facebook.appevents.internal.SessionInfo.Companion>; public getStoredSessionInfo(): com.facebook.appevents.internal.SessionInfo; public clearSavedSessionFromDisk(): void; } } } } } } declare module com { export module facebook { export module appevents { export module internal { export class SessionLogger { public static class: java.lang.Class<com.facebook.appevents.internal.SessionLogger>; public static INSTANCE: com.facebook.appevents.internal.SessionLogger; public static logDeactivateApp(param0: string, param1: com.facebook.appevents.internal.SessionInfo, param2: string): void; public computePackageChecksum(param0: globalAndroid.content.Context): string; public static logActivateApp(param0: string, param1: com.facebook.appevents.internal.SourceApplicationInfo, param2: string, param3: globalAndroid.content.Context): void; public static getQuantaIndex(param0: number): number; } } } } } declare module com { export module facebook { export module appevents { export module internal { export class SourceApplicationInfo { public static class: java.lang.Class<com.facebook.appevents.internal.SourceApplicationInfo>; public static Companion: com.facebook.appevents.internal.SourceApplicationInfo.Companion; public writeSourceApplicationInfoToDisk(): void; public toString(): string; public static clearSavedSourceApplicationInfoFromDisk(): void; public getCallingApplicationPackage(): string; public static getStoredSourceApplicatioInfo(): com.facebook.appevents.internal.SourceApplicationInfo; public isOpenedByAppLink(): boolean; } export module SourceApplicationInfo { export class Companion { public static class: java.lang.Class<com.facebook.appevents.internal.SourceApplicationInfo.Companion>; public clearSavedSourceApplicationInfoFromDisk(): void; public getStoredSourceApplicatioInfo(): com.facebook.appevents.internal.SourceApplicationInfo; } export class Factory { public static class: java.lang.Class<com.facebook.appevents.internal.SourceApplicationInfo.Factory>; public static INSTANCE: com.facebook.appevents.internal.SourceApplicationInfo.Factory; public static create(param0: globalAndroid.app.Activity): com.facebook.appevents.internal.SourceApplicationInfo; } } } } } } declare module com { export module facebook { export module appevents { export module internal { export class ViewHierarchyConstants { public static class: java.lang.Class<com.facebook.appevents.internal.ViewHierarchyConstants>; public static ID_KEY: string; public static CLASS_NAME_KEY: string; public static CLASS_TYPE_BITMASK_KEY: string; public static TEXT_KEY: string; public static DESC_KEY: string; public static DIMENSION_KEY: string; public static IS_USER_INPUT_KEY: string; public static TAG_KEY: string; public static CHILDREN_VIEW_KEY: string; public static HINT_KEY: string; public static DIMENSION_TOP_KEY: string; public static DIMENSION_LEFT_KEY: string; public static DIMENSION_WIDTH_KEY: string; public static DIMENSION_HEIGHT_KEY: string; public static DIMENSION_SCROLL_X_KEY: string; public static DIMENSION_SCROLL_Y_KEY: string; public static DIMENSION_VISIBILITY_KEY: string; public static TEXT_SIZE: string; public static TEXT_IS_BOLD: string; public static TEXT_IS_ITALIC: string; public static TEXT_STYLE: string; public static ICON_BITMAP: string; public static INPUT_TYPE_KEY: string; public static IS_INTERACTED_KEY: string; public static SCREEN_NAME_KEY: string; public static VIEW_KEY: string; public static ENGLISH: string; public static GERMAN: string; public static SPANISH: string; public static JAPANESE: string; public static VIEW_CONTENT: string; public static SEARCH: string; public static ADD_TO_CART: string; public static ADD_TO_WISHLIST: string; public static INITIATE_CHECKOUT: string; public static ADD_PAYMENT_INFO: string; public static PURCHASE: string; public static LEAD: string; public static COMPLETE_REGISTRATION: string; public static BUTTON_TEXT: string; public static PAGE_TITLE: string; public static RESOLVED_DOCUMENT_LINK: string; public static BUTTON_ID: string; public static TEXTVIEW_BITMASK: number; public static IMAGEVIEW_BITMASK: number; public static BUTTON_BITMASK: number; public static CLICKABLE_VIEW_BITMASK: number; public static REACT_NATIVE_BUTTON_BITMASK: number; public static ADAPTER_VIEW_ITEM_BITMASK: number; public static LABEL_BITMASK: number; public static INPUT_BITMASK: number; public static PICKER_BITMASK: number; public static SWITCH_BITMASK: number; public static RADIO_GROUP_BITMASK: number; public static CHECKBOX_BITMASK: number; public static RATINGBAR_BITMASK: number; public static INSTANCE: com.facebook.appevents.internal.ViewHierarchyConstants; } } } } } declare module com { export module facebook { export module appevents { export module ml { export class MTensor { public static class: java.lang.Class<com.facebook.appevents.ml.MTensor>; public static Companion: com.facebook.appevents.ml.MTensor.Companion; public getShapeSize(): number; public reshape(param0: androidNative.Array<number>): void; public getData(): androidNative.Array<number>; public getShape(param0: number): number; public constructor(param0: androidNative.Array<number>); } export module MTensor { export class Companion { public static class: java.lang.Class<com.facebook.appevents.ml.MTensor.Companion>; } } } } } } declare module com { export module facebook { export module appevents { export module ml { export class Model { public static class: java.lang.Class<com.facebook.appevents.ml.Model>; public static Companion: com.facebook.appevents.ml.Model.Companion; public predictOnMTML(param0: com.facebook.appevents.ml.MTensor, param1: androidNative.Array<string>, param2: string): com.facebook.appevents.ml.MTensor; } export module Model { export class Companion { public static class: java.lang.Class<com.facebook.appevents.ml.Model.Companion>; public build(param0: java.io.File): com.facebook.appevents.ml.Model; } } } } } } declare module com { export module facebook { export module appevents { export module ml { export class ModelManager { public static class: java.lang.Class<com.facebook.appevents.ml.ModelManager>; public static INSTANCE: com.facebook.appevents.ml.ModelManager; public static getRuleFile(param0: com.facebook.appevents.ml.ModelManager.Task): java.io.File; public static predict(param0: com.facebook.appevents.ml.ModelManager.Task, param1: androidNative.Array<androidNative.Array<number>>, param2: androidNative.Array<string>): androidNative.Array<string>; public static enable(): void; } export module ModelManager { export class Task { public static class: java.lang.Class<com.facebook.appevents.ml.ModelManager.Task>; public static MTML_INTEGRITY_DETECT: com.facebook.appevents.ml.ModelManager.Task; public static MTML_APP_EVENT_PREDICTION: com.facebook.appevents.ml.ModelManager.Task; public toKey(): string; public static values(): androidNative.Array<com.facebook.appevents.ml.ModelManager.Task>; public toUseCase(): string; public static valueOf(param0: string): com.facebook.appevents.ml.ModelManager.Task; } export module Task { export class WhenMappings { public static class: java.lang.Class<com.facebook.appevents.ml.ModelManager.Task.WhenMappings>; } } export class TaskHandler { public static class: java.lang.Class<com.facebook.appevents.ml.ModelManager.TaskHandler>; public static Companion: com.facebook.appevents.ml.ModelManager.TaskHandler.Companion; public setVersionId(param0: number): void; public getRuleFile(): java.io.File; public getRuleUri(): string; public getThresholds(): androidNative.Array<number>; public getModel(): com.facebook.appevents.ml.Model; public setUseCase(param0: string): void; public setModel(param0: com.facebook.appevents.ml.Model): void; public setOnPostExecute(param0: java.lang.Runnable): com.facebook.appevents.ml.ModelManager.TaskHandler; public setRuleFile(param0: java.io.File): void; public getUseCase(): string; public getVersionId(): number; public constructor(param0: string, param1: string, param2: string, param3: number, param4: androidNative.Array<number>); public getAssetUri(): string; public setRuleUri(param0: string): void; public setThresholds(param0: androidNative.Array<number>): void; public setAssetUri(param0: string): void; } export module TaskHandler { export class Companion { public static class: java.lang.Class<com.facebook.appevents.ml.ModelManager.TaskHandler.Companion>; public execute(param0: com.facebook.appevents.ml.ModelManager.TaskHandler): void; public execute(param0: com.facebook.appevents.ml.ModelManager.TaskHandler, param1: java.util.List<com.facebook.appevents.ml.ModelManager.TaskHandler>): void; public build(param0: org.json.JSONObject): com.facebook.appevents.ml.ModelManager.TaskHandler; } } export class WhenMappings { public static class: java.lang.Class<com.facebook.appevents.ml.ModelManager.WhenMappings>; } } } } } } declare module com { export module facebook { export module appevents { export module ml { export class Operator { public static class: java.lang.Class<com.facebook.appevents.ml.Operator>; public static INSTANCE: com.facebook.appevents.ml.Operator; public static addmv(param0: com.facebook.appevents.ml.MTensor, param1: com.facebook.appevents.ml.MTensor): void; public static flatten(param0: com.facebook.appevents.ml.MTensor, param1: number): void; public static transpose3D(param0: com.facebook.appevents.ml.MTensor): com.facebook.appevents.ml.MTensor; public static mul(param0: com.facebook.appevents.ml.MTensor, param1: com.facebook.appevents.ml.MTensor): com.facebook.appevents.ml.MTensor; public static concatenate(param0: androidNative.Array<com.facebook.appevents.ml.MTensor>): com.facebook.appevents.ml.MTensor; public static softmax(param0: com.facebook.appevents.ml.MTensor): void; public static maxPool1D(param0: com.facebook.appevents.ml.MTensor, param1: number): com.facebook.appevents.ml.MTensor; public static transpose2D(param0: com.facebook.appevents.ml.MTensor): com.facebook.appevents.ml.MTensor; public static conv1D(param0: com.facebook.appevents.ml.MTensor, param1: com.facebook.appevents.ml.MTensor): com.facebook.appevents.ml.MTensor; public static dense(param0: com.facebook.appevents.ml.MTensor, param1: com.facebook.appevents.ml.MTensor, param2: com.facebook.appevents.ml.MTensor): com.facebook.appevents.ml.MTensor; public static relu(param0: com.facebook.appevents.ml.MTensor): void; public static embedding(param0: androidNative.Array<string>, param1: number, param2: com.facebook.appevents.ml.MTensor): com.facebook.appevents.ml.MTensor; } } } } } declare module com { export module facebook { export module appevents { export module ml { export class Utils { public static class: java.lang.Class<com.facebook.appevents.ml.Utils>; public static INSTANCE: com.facebook.appevents.ml.Utils; public vectorize(param0: string, param1: number): androidNative.Array<number>; public static parseModelWeights(param0: java.io.File): java.util.Map<string,com.facebook.appevents.ml.MTensor>; public normalizeString(param0: string): string; public static getMlDir(): java.io.File; } } } } } declare module com { export module facebook { export module appevents { export module ondeviceprocessing { export class OnDeviceProcessingManager { public static class: java.lang.Class<com.facebook.appevents.ondeviceprocessing.OnDeviceProcessingManager>; public static INSTANCE: com.facebook.appevents.ondeviceprocessing.OnDeviceProcessingManager; public static sendCustomEventAsync(param0: string, param1: com.facebook.appevents.AppEvent): void; public static sendInstallEventAsync(param0: string, param1: string): void; public static isOnDeviceProcessingEnabled(): boolean; } } } } } declare module com { export module facebook { export module appevents { export module ondeviceprocessing { export class RemoteServiceParametersHelper { public static class: java.lang.Class<com.facebook.appevents.ondeviceprocessing.RemoteServiceParametersHelper>; public static INSTANCE: com.facebook.appevents.ondeviceprocessing.RemoteServiceParametersHelper; public static buildEventsBundle(param0: com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.EventType, param1: string, param2: java.util.List<com.facebook.appevents.AppEvent>): globalAndroid.os.Bundle; } } } } } declare module com { export module facebook { export module appevents { export module ondeviceprocessing { export class RemoteServiceWrapper { public static class: java.lang.Class<com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper>; public static RECEIVER_SERVICE_ACTION: string; public static RECEIVER_SERVICE_PACKAGE: string; public static RECEIVER_SERVICE_PACKAGE_WAKIZASHI: string; public static INSTANCE: com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper; public static isServiceAvailable(): boolean; public static sendCustomEvents(param0: string, param1: java.util.List<com.facebook.appevents.AppEvent>): com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.ServiceResult; public static sendInstallEvent(param0: string): com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.ServiceResult; } export module RemoteServiceWrapper { export class EventType { public static class: java.lang.Class<com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.EventType>; public static MOBILE_APP_INSTALL: com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.EventType; public static CUSTOM_APP_EVENTS: com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.EventType; public static values(): androidNative.Array<com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.EventType>; public static valueOf(param0: string): com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.EventType; public toString(): string; } export class RemoteServiceConnection { public static class: java.lang.Class<com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.RemoteServiceConnection>; public onNullBinding(param0: globalAndroid.content.ComponentName): void; public constructor(); public onServiceConnected(param0: globalAndroid.content.ComponentName, param1: globalAndroid.os.IBinder): void; public getBinder(): globalAndroid.os.IBinder; public onServiceDisconnected(param0: globalAndroid.content.ComponentName): void; } export class ServiceResult { public static class: java.lang.Class<com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.ServiceResult>; public static OPERATION_SUCCESS: com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.ServiceResult; public static SERVICE_NOT_AVAILABLE: com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.ServiceResult; public static SERVICE_ERROR: com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.ServiceResult; public static values(): androidNative.Array<com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.ServiceResult>; public static valueOf(param0: string): com.facebook.appevents.ondeviceprocessing.RemoteServiceWrapper.ServiceResult; } } } } } } declare module com { export module facebook { export module appevents { export module restrictivedatafilter { export class RestrictiveDataManager { public static class: java.lang.Class<com.facebook.appevents.restrictivedatafilter.RestrictiveDataManager>; public static INSTANCE: com.facebook.appevents.restrictivedatafilter.RestrictiveDataManager; public static processParameters(param0: java.util.Map<string,string>, param1: string): void; public static enable(): void; public static processEvent(param0: string): string; } export module RestrictiveDataManager { export class RestrictiveParamFilter { public static class: java.lang.Class<com.facebook.appevents.restrictivedatafilter.RestrictiveDataManager.RestrictiveParamFilter>; public getRestrictiveParams(): java.util.Map<string,string>; public getEventName(): string; public setRestrictiveParams(param0: java.util.Map<string,string>): void; public setEventName(param0: string): void; public constructor(param0: string, param1: java.util.Map<string,string>); } } } } } } declare module com { export module facebook { export module appevents { export module suggestedevents { export class FeatureExtractor { public static class: java.lang.Class<com.facebook.appevents.suggestedevents.FeatureExtractor>; public static INSTANCE: com.facebook.appevents.suggestedevents.FeatureExtractor; public static initialize(param0: java.io.File): void; public static getTextFeature(param0: string, param1: string, param2: string): string; public static isInitialized(): boolean; public static getDenseFeatures(param0: org.json.JSONObject, param1: string): androidNative.Array<number>; } } } } } declare module com { export module facebook { export module appevents { export module suggestedevents { export class PredictionHistoryManager { public static class: java.lang.Class<com.facebook.appevents.suggestedevents.PredictionHistoryManager>; public static INSTANCE: com.facebook.appevents.suggestedevents.PredictionHistoryManager; public static addPrediction(param0: string, param1: string): void; public static getPathID(param0: globalAndroid.view.View, param1: string): string; public static queryEvent(param0: string): string; } } } } } declare module com { export module facebook { export module appevents { export module suggestedevents { export class SuggestedEventViewHierarchy { public static class: java.lang.Class<com.facebook.appevents.suggestedevents.SuggestedEventViewHierarchy>; public static INSTANCE: com.facebook.appevents.suggestedevents.SuggestedEventViewHierarchy; public static updateBasicInfo(param0: globalAndroid.view.View, param1: org.json.JSONObject): void; public static getDictionaryOfView(param0: globalAndroid.view.View, param1: globalAndroid.view.View): org.json.JSONObject; public static getAllClickableViews(param0: globalAndroid.view.View): java.util.List<globalAndroid.view.View>; public static getTextOfViewRecursively(param0: globalAndroid.view.View): string; } } } } } declare module com { export module facebook { export module appevents { export module suggestedevents { export class SuggestedEventsManager { public static class: java.lang.Class<com.facebook.appevents.suggestedevents.SuggestedEventsManager>; public static INSTANCE: com.facebook.appevents.suggestedevents.SuggestedEventsManager; public static isEnabled(): boolean; public populateEventsFromRawJsonString$facebook_core_release(param0: string): void; public static isProductionEvents$facebook_core_release(param0: string): boolean; public static trackActivity(param0: globalAndroid.app.Activity): void; public static enable(): void; public static isEligibleEvents$facebook_core_release(param0: string): boolean; } } } } } declare module com { export module facebook { export module appevents { export module suggestedevents { export class ViewObserver { public static class: java.lang.Class<com.facebook.appevents.suggestedevents.ViewObserver>; public static Companion: com.facebook.appevents.suggestedevents.ViewObserver.Companion; public static startTrackingActivity(param0: globalAndroid.app.Activity): void; public static stopTrackingActivity(param0: globalAndroid.app.Activity): void; public onGlobalLayout(): void; } export module ViewObserver { export class Companion { public static class: java.lang.Class<com.facebook.appevents.suggestedevents.ViewObserver.Companion>; public startTrackingActivity(param0: globalAndroid.app.Activity): void; public stopTrackingActivity(param0: globalAndroid.app.Activity): void; } } } } } } declare module com { export module facebook { export module appevents { export module suggestedevents { export class ViewOnClickListener { public static class: java.lang.Class<com.facebook.appevents.suggestedevents.ViewOnClickListener>; public static OTHER_EVENT: string; public static Companion: com.facebook.appevents.suggestedevents.ViewOnClickListener.Companion; public onClick(param0: globalAndroid.view.View): void; public static attachListener$facebook_core_release(param0: globalAndroid.view.View, param1: globalAndroid.view.View, param2: string): void; } export module ViewOnClickListener { export class Companion { public static class: java.lang.Class<com.facebook.appevents.suggestedevents.ViewOnClickListener.Companion>; public attachListener$facebook_core_release(param0: globalAndroid.view.View, param1: globalAndroid.view.View, param2: string): void; } } } } } } declare module com { export module facebook { export module bolts { export class AggregateException { public static class: java.lang.Class<com.facebook.bolts.AggregateException>; public static Companion: com.facebook.bolts.AggregateException.Companion; public printStackTrace(param0: java.io.PrintWriter): void; public constructor(param0: string, param1: java.util.List<any>); public printStackTrace(param0: java.io.PrintStream): void; } export module AggregateException { export class Companion { public static class: java.lang.Class<com.facebook.bolts.AggregateException.Companion>; } } } } } declare module com { export module facebook { export module bolts { export class AndroidExecutors { public static class: java.lang.Class<com.facebook.bolts.AndroidExecutors>; public static Companion: com.facebook.bolts.AndroidExecutors.Companion; public static newCachedThreadPool(): java.util.concurrent.ExecutorService; public static uiThread(): java.util.concurrent.Executor; } export module AndroidExecutors { export class Companion { public static class: java.lang.Class<com.facebook.bolts.AndroidExecutors.Companion>; public uiThread(): java.util.concurrent.Executor; public newCachedThreadPool(): java.util.concurrent.ExecutorService; } export class UIThreadExecutor { public static class: java.lang.Class<com.facebook.bolts.AndroidExecutors.UIThreadExecutor>; public execute(param0: java.lang.Runnable): void; public constructor(); } } } } } declare module com { export module facebook { export module bolts { export class AppLink { public static class: java.lang.Class<com.facebook.bolts.AppLink>; public getTargets(): java.util.List<com.facebook.bolts.AppLink.Target>; public getWebUrl(): globalAndroid.net.Uri; public getSourceUrl(): globalAndroid.net.Uri; public constructor(param0: globalAndroid.net.Uri, param1: java.util.List<com.facebook.bolts.AppLink.Target>, param2: globalAndroid.net.Uri); } export module AppLink { export class Target { public static class: java.lang.Class<com.facebook.bolts.AppLink.Target>; public getClassName(): string; public constructor(param0: string, param1: string, param2: globalAndroid.net.Uri, param3: string); public getPackageName(): string; public getAppName(): string; public getUrl(): globalAndroid.net.Uri; } } } } } declare module com { export module facebook { export module bolts { export class AppLinkResolver { public static class: java.lang.Class<com.facebook.bolts.AppLinkResolver>; /** * Constructs a new instance of the com.facebook.bolts.AppLinkResolver interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getAppLinkFromUrlInBackground(param0: globalAndroid.net.Uri): com.facebook.bolts.Task<com.facebook.bolts.AppLink>; }); public constructor(); public getAppLinkFromUrlInBackground(param0: globalAndroid.net.Uri): com.facebook.bolts.Task<com.facebook.bolts.AppLink>; } } } } declare module com { export module facebook { export module bolts { export class AppLinks { public static class: java.lang.Class<com.facebook.bolts.AppLinks>; public static KEY_NAME_APPLINK_DATA: string; public static KEY_NAME_EXTRAS: string; public static INSTANCE: com.facebook.bolts.AppLinks; public static getAppLinkData(param0: globalAndroid.content.Intent): globalAndroid.os.Bundle; public static getAppLinkExtras(param0: globalAndroid.content.Intent): globalAndroid.os.Bundle; } } } } declare module com { export module facebook { export module bolts { export class BoltsExecutors { public static class: java.lang.Class<com.facebook.bolts.BoltsExecutors>; public static Companion: com.facebook.bolts.BoltsExecutors.Companion; public static immediate$facebook_core_release(): java.util.concurrent.Executor; public static background(): java.util.concurrent.ExecutorService; public static scheduled$facebook_core_release(): java.util.concurrent.ScheduledExecutorService; } export module BoltsExecutors { export class Companion { public static class: java.lang.Class<com.facebook.bolts.BoltsExecutors.Companion>; public scheduled$facebook_core_release(): java.util.concurrent.ScheduledExecutorService; public background(): java.util.concurrent.ExecutorService; public immediate$facebook_core_release(): java.util.concurrent.Executor; } export class ImmediateExecutor { public static class: java.lang.Class<com.facebook.bolts.BoltsExecutors.ImmediateExecutor>; public static Companion: com.facebook.bolts.BoltsExecutors.ImmediateExecutor.Companion; public execute(param0: java.lang.Runnable): void; public constructor(); } export module ImmediateExecutor { export class Companion { public static class: java.lang.Class<com.facebook.bolts.BoltsExecutors.ImmediateExecutor.Companion>; } } } } } } declare module com { export module facebook { export module bolts { export class CancellationToken { public static class: java.lang.Class<com.facebook.bolts.CancellationToken>; public register(param0: java.lang.Runnable): com.facebook.bolts.CancellationTokenRegistration; public throwIfCancellationRequested(): void; public toString(): string; public constructor(param0: com.facebook.bolts.CancellationTokenSource); public isCancellationRequested(): boolean; } } } } declare module com { export module facebook { export module bolts { export class CancellationTokenRegistration { public static class: java.lang.Class<com.facebook.bolts.CancellationTokenRegistration>; public close(): void; public constructor(param0: com.facebook.bolts.CancellationTokenSource, param1: java.lang.Runnable); public runAction$facebook_core_release(): void; } } } } declare module com { export module facebook { export module bolts { export class CancellationTokenSource { public static class: java.lang.Class<com.facebook.bolts.CancellationTokenSource>; public getToken(): com.facebook.bolts.CancellationToken; public close(): void; public cancelAfter(param0: number): void; public register$facebook_core_release(param0: java.lang.Runnable): com.facebook.bolts.CancellationTokenRegistration; public cancel(): void; public throwIfCancellationRequested$facebook_core_release(): void; public toString(): string; public isCancellationRequested(): boolean; public unregister$facebook_core_release(param0: com.facebook.bolts.CancellationTokenRegistration): void; public constructor(); } } } } declare module com { export module facebook { export module bolts { export class Continuation<TTaskResult, TContinuationResult> extends java.lang.Object { public static class: java.lang.Class<com.facebook.bolts.Continuation<any,any>>; /** * Constructs a new instance of the com.facebook.bolts.Continuation<any,any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { then(param0: com.facebook.bolts.Task<TTaskResult>): TContinuationResult; }); public constructor(); public then(param0: com.facebook.bolts.Task<TTaskResult>): TContinuationResult; } } } } declare module com { export module facebook { export module bolts { export class ExecutorException { public static class: java.lang.Class<com.facebook.bolts.ExecutorException>; public constructor(param0: java.lang.Exception); } } } } declare module com { export module facebook { export module bolts { export class Task<TResult> extends java.lang.Object { public static class: java.lang.Class<com.facebook.bolts.Task<any>>; public static BACKGROUND_EXECUTOR: java.util.concurrent.ExecutorService; public static UI_THREAD_EXECUTOR: java.util.concurrent.Executor; public static Companion: com.facebook.bolts.Task.Companion; public getResult(): TResult; public continueWhile(param0: java.util.concurrent.Callable<java.lang.Boolean>, param1: com.facebook.bolts.Continuation<java.lang.Void,com.facebook.bolts.Task<java.lang.Void>>, param2: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<java.lang.Void>; public static delay(param0: number): com.facebook.bolts.Task<java.lang.Void>; public static call(param0: java.util.concurrent.Callable, param1: java.util.concurrent.Executor, param2: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<any>; public static call(param0: java.util.concurrent.Callable, param1: java.util.concurrent.Executor): com.facebook.bolts.Task<any>; public continueWith(param0: com.facebook.bolts.Continuation<any,any>, param1: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<any>; public constructor(); public continueWithTask(param0: com.facebook.bolts.Continuation<any,any>, param1: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<any>; public isCompleted(): boolean; public cast(): com.facebook.bolts.Task<any>; public static delay(param0: number, param1: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<java.lang.Void>; public static forError(param0: java.lang.Exception): com.facebook.bolts.Task<any>; public onSuccess(param0: com.facebook.bolts.Continuation<any,any>, param1: java.util.concurrent.Executor, param2: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<any>; public trySetResult(param0: TResult): boolean; public static callInBackground(param0: java.util.concurrent.Callable, param1: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<any>; public waitForCompletion(param0: number, param1: java.util.concurrent.TimeUnit): boolean; public onSuccess(param0: com.facebook.bolts.Continuation<any,any>, param1: java.util.concurrent.Executor): com.facebook.bolts.Task<any>; public static getUnobservedExceptionHandler(): com.facebook.bolts.Task.UnobservedExceptionHandler; public continueWithTask(param0: com.facebook.bolts.Continuation<any,any>, param1: java.util.concurrent.Executor): com.facebook.bolts.Task<any>; public static call(param0: java.util.concurrent.Callable): com.facebook.bolts.Task<any>; public continueWithTask(param0: com.facebook.bolts.Continuation<any,any>, param1: java.util.concurrent.Executor, param2: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<any>; public static call(param0: java.util.concurrent.Callable, param1: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<any>; public static whenAllResult(param0: java.util.Collection): com.facebook.bolts.Task<any>; public static setUnobservedExceptionHandler(param0: com.facebook.bolts.Task.UnobservedExceptionHandler): void; public continueWhile(param0: java.util.concurrent.Callable<java.lang.Boolean>, param1: com.facebook.bolts.Continuation<java.lang.Void,com.facebook.bolts.Task<java.lang.Void>>, param2: java.util.concurrent.Executor, param3: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<java.lang.Void>; public static whenAll(param0: java.util.Collection<any>): com.facebook.bolts.Task<java.lang.Void>; public trySetError(param0: java.lang.Exception): boolean; public onSuccessTask(param0: com.facebook.bolts.Continuation<any,any>, param1: java.util.concurrent.Executor, param2: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<any>; public continueWhile(param0: java.util.concurrent.Callable<java.lang.Boolean>, param1: com.facebook.bolts.Continuation<java.lang.Void,com.facebook.bolts.Task<java.lang.Void>>): com.facebook.bolts.Task<java.lang.Void>; public onSuccess(param0: com.facebook.bolts.Continuation<any,any>): com.facebook.bolts.Task<any>; public static forResult(param0: any): com.facebook.bolts.Task<any>; public getError(): java.lang.Exception; public static callInBackground(param0: java.util.concurrent.Callable): com.facebook.bolts.Task<any>; public isFaulted(): boolean; public static delay$facebook_core_release(param0: number, param1: java.util.concurrent.ScheduledExecutorService, param2: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<java.lang.Void>; public onSuccessTask(param0: com.facebook.bolts.Continuation<any,any>): com.facebook.bolts.Task<any>; public onSuccessTask(param0: com.facebook.bolts.Continuation<any,any>, param1: java.util.concurrent.Executor): com.facebook.bolts.Task<any>; public onSuccessTask(param0: com.facebook.bolts.Continuation<any,any>, param1: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<any>; public continueWith(param0: com.facebook.bolts.Continuation<any,any>): com.facebook.bolts.Task<any>; public continueWith(param0: com.facebook.bolts.Continuation<any,any>, param1: java.util.concurrent.Executor): com.facebook.bolts.Task<any>; public static cancelled(): com.facebook.bolts.Task<any>; public continueWith(param0: com.facebook.bolts.Continuation<any,any>, param1: java.util.concurrent.Executor, param2: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<any>; public makeVoid(): com.facebook.bolts.Task<java.lang.Void>; public static whenAny(param0: java.util.Collection<any>): com.facebook.bolts.Task<com.facebook.bolts.Task<any>>; public trySetCancelled(): boolean; public static whenAnyResult(param0: java.util.Collection): com.facebook.bolts.Task<any>; public waitForCompletion(): void; public continueWithTask(param0: com.facebook.bolts.Continuation<any,any>): com.facebook.bolts.Task<any>; public isCancelled(): boolean; public onSuccess(param0: com.facebook.bolts.Continuation<any,any>, param1: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<any>; } export module Task { export class Companion { public static class: java.lang.Class<com.facebook.bolts.Task.Companion>; public call(param0: java.util.concurrent.Callable): com.facebook.bolts.Task<any>; public call(param0: java.util.concurrent.Callable, param1: java.util.concurrent.Executor, param2: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<any>; public delay$facebook_core_release(param0: number, param1: java.util.concurrent.ScheduledExecutorService, param2: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<java.lang.Void>; public whenAll(param0: java.util.Collection<any>): com.facebook.bolts.Task<java.lang.Void>; public delay(param0: number): com.facebook.bolts.Task<java.lang.Void>; public callInBackground(param0: java.util.concurrent.Callable, param1: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<any>; public forError(param0: java.lang.Exception): com.facebook.bolts.Task<any>; public delay(param0: number, param1: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<java.lang.Void>; public whenAny(param0: java.util.Collection<any>): com.facebook.bolts.Task<com.facebook.bolts.Task<any>>; public whenAnyResult(param0: java.util.Collection): com.facebook.bolts.Task<any>; public call(param0: java.util.concurrent.Callable, param1: com.facebook.bolts.CancellationToken): com.facebook.bolts.Task<any>; public callInBackground(param0: java.util.concurrent.Callable): com.facebook.bolts.Task<any>; public whenAllResult(param0: java.util.Collection): com.facebook.bolts.Task<any>; public getUnobservedExceptionHandler(): com.facebook.bolts.Task.UnobservedExceptionHandler; public call(param0: java.util.concurrent.Callable, param1: java.util.concurrent.Executor): com.facebook.bolts.Task<any>; public setUnobservedExceptionHandler(param0: com.facebook.bolts.Task.UnobservedExceptionHandler): void; public forResult(param0: any): com.facebook.bolts.Task<any>; public cancelled(): com.facebook.bolts.Task<any>; } export class TaskCompletionSource extends com.facebook.bolts.TaskCompletionSource<any> { public static class: java.lang.Class<com.facebook.bolts.Task.TaskCompletionSource>; public constructor(); public constructor(param0: com.facebook.bolts.Task<any>); } export class UnobservedExceptionHandler { public static class: java.lang.Class<com.facebook.bolts.Task.UnobservedExceptionHandler>; /** * Constructs a new instance of the com.facebook.bolts.Task$UnobservedExceptionHandler interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { unobservedException(param0: com.facebook.bolts.Task<any>, param1: com.facebook.bolts.UnobservedTaskException): void; }); public constructor(); public unobservedException(param0: com.facebook.bolts.Task<any>, param1: com.facebook.bolts.UnobservedTaskException): void; } } } } } declare module com { export module facebook { export module bolts { export class TaskCompletionSource<TResult> extends java.lang.Object { public static class: java.lang.Class<com.facebook.bolts.TaskCompletionSource<any>>; public getTask(): com.facebook.bolts.Task<TResult>; public trySetResult(param0: TResult): boolean; public setResult(param0: TResult): void; public trySetError(param0: java.lang.Exception): boolean; public setError(param0: java.lang.Exception): void; public trySetCancelled(): boolean; public setCancelled(): void; public constructor(); } } } } declare module com { export module facebook { export module bolts { export class UnobservedErrorNotifier { public static class: java.lang.Class<com.facebook.bolts.UnobservedErrorNotifier>; public setObserved(): void; public finalize(): void; public constructor(param0: com.facebook.bolts.Task<any>); } } } } declare module com { export module facebook { export module bolts { export class UnobservedTaskException { public static class: java.lang.Class<com.facebook.bolts.UnobservedTaskException>; public constructor(param0: java.lang.Throwable); } } } } declare module com { export module facebook { export module common { export class BuildConfig { public static class: java.lang.Class<com.facebook.common.BuildConfig>; public static DEBUG: boolean; public static LIBRARY_PACKAGE_NAME: string; public static APPLICATION_ID: string; public static BUILD_TYPE: string; public static FLAVOR: string; public static VERSION_CODE: number; public static VERSION_NAME: string; public constructor(); } } } } declare module com { export module facebook { export module common { export class Common { public static class: java.lang.Class<com.facebook.common.Common>; public constructor(); } } } } declare module com { export module facebook { export module core { export class BuildConfig { public static class: java.lang.Class<com.facebook.core.BuildConfig>; public static DEBUG: boolean; public static LIBRARY_PACKAGE_NAME: string; public static APPLICATION_ID: string; public static BUILD_TYPE: string; public static FLAVOR: string; public static VERSION_CODE: number; public static VERSION_NAME: string; public constructor(); } } } } declare module com { export module facebook { export module core { export class Core { public static class: java.lang.Class<com.facebook.core.Core>; public constructor(); } } } } declare module com { export module facebook { export module devicerequests { export module internal { export class DeviceRequestsHelper { public static class: java.lang.Class<com.facebook.devicerequests.internal.DeviceRequestsHelper>; public static DEVICE_INFO_PARAM: string; public static DEVICE_TARGET_USER_ID: string; public constructor(); public static getDeviceInfo(param0: java.util.Map<string,string>): string; public static getDeviceInfo(): string; public static generateQRCode(param0: string): globalAndroid.graphics.Bitmap; public static cleanUpAdvertisementService(param0: string): void; public static isAvailable(): boolean; public static startAdvertisementService(param0: string): boolean; } } } } } declare module com { export module facebook { export module internal { export class AnalyticsEvents { public static class: java.lang.Class<com.facebook.internal.AnalyticsEvents>; public static EVENT_NATIVE_LOGIN_DIALOG_COMPLETE: string; public static EVENT_NATIVE_LOGIN_DIALOG_START: string; public static EVENT_WEB_LOGIN_COMPLETE: string; public static EVENT_FRIEND_PICKER_USAGE: string; public static EVENT_PLACE_PICKER_USAGE: string; public static EVENT_LOGIN_VIEW_USAGE: string; public static EVENT_USER_SETTINGS_USAGE: string; public static EVENT_NATIVE_DIALOG_START: string; public static EVENT_NATIVE_DIALOG_COMPLETE: string; public static PARAMETER_WEB_LOGIN_E2E: string; public static PARAMETER_WEB_LOGIN_SWITCHBACK_TIME: string; public static PARAMETER_APP_ID: string; public static PARAMETER_CALL_ID: string; public static PARAMETER_ACTION_ID: string; public static PARAMETER_NATIVE_LOGIN_DIALOG_START_TIME: string; public static PARAMETER_NATIVE_LOGIN_DIALOG_COMPLETE_TIME: string; public static PARAMETER_DIALOG_OUTCOME: string; public static PARAMETER_DIALOG_OUTCOME_VALUE_COMPLETED: string; public static PARAMETER_DIALOG_OUTCOME_VALUE_UNKNOWN: string; public static PARAMETER_DIALOG_OUTCOME_VALUE_CANCELLED: string; public static PARAMETER_DIALOG_OUTCOME_VALUE_FAILED: string; public static EVENT_NATIVE_DIALOG_TYPE_SHARE: string; public static EVENT_NATIVE_DIALOG_TYPE_MESSAGE: string; public static EVENT_NATIVE_DIALOG_TYPE_OG_SHARE: string; public static EVENT_NATIVE_DIALOG_TYPE_OG_MESSAGE: string; public static EVENT_NATIVE_DIALOG_TYPE_PHOTO_SHARE: string; public static EVENT_NATIVE_DIALOG_TYPE_PHOTO_MESSAGE: string; public static EVENT_NATIVE_DIALOG_TYPE_VIDEO_SHARE: string; public static EVENT_NATIVE_DIALOG_TYPE_LIKE: string; public static EVENT_LIKE_VIEW_CANNOT_PRESENT_DIALOG: string; public static EVENT_LIKE_VIEW_DID_LIKE: string; public static EVENT_LIKE_VIEW_DID_PRESENT_DIALOG: string; public static EVENT_LIKE_VIEW_DID_PRESENT_FALLBACK: string; public static EVENT_LIKE_VIEW_DID_UNLIKE: string; public static EVENT_LIKE_VIEW_DID_UNDO_QUICKLY: string; public static EVENT_LIKE_VIEW_DIALOG_DID_SUCCEED: string; public static EVENT_LIKE_VIEW_ERROR: string; public static PARAMETER_LIKE_VIEW_STYLE: string; public static PARAMETER_LIKE_VIEW_AUXILIARY_POSITION: string; public static PARAMETER_LIKE_VIEW_HORIZONTAL_ALIGNMENT: string; public static PARAMETER_LIKE_VIEW_OBJECT_ID: string; public static PARAMETER_LIKE_VIEW_OBJECT_TYPE: string; public static PARAMETER_LIKE_VIEW_CURRENT_ACTION: string; public static PARAMETER_LIKE_VIEW_ERROR_JSON: string; public static PARAMETER_SHARE_OUTCOME: string; public static PARAMETER_SHARE_OUTCOME_SUCCEEDED: string; public static PARAMETER_SHARE_OUTCOME_CANCELLED: string; public static PARAMETER_SHARE_OUTCOME_ERROR: string; public static PARAMETER_SHARE_OUTCOME_UNKNOWN: string; public static PARAMETER_SHARE_ERROR_MESSAGE: string; public static PARAMETER_SHARE_DIALOG_SHOW: string; public static PARAMETER_SHARE_DIALOG_SHOW_WEB: string; public static PARAMETER_SHARE_DIALOG_SHOW_NATIVE: string; public static PARAMETER_SHARE_DIALOG_SHOW_AUTOMATIC: string; public static PARAMETER_SHARE_DIALOG_SHOW_UNKNOWN: string; public static PARAMETER_SHARE_DIALOG_CONTENT_TYPE: string; public static PARAMETER_SHARE_DIALOG_CONTENT_UUID: string; public static PARAMETER_SHARE_DIALOG_CONTENT_PAGE_ID: string; public static PARAMETER_SHARE_DIALOG_CONTENT_VIDEO: string; public static PARAMETER_SHARE_DIALOG_CONTENT_PHOTO: string; public static PARAMETER_SHARE_DIALOG_CONTENT_STATUS: string; public static PARAMETER_SHARE_DIALOG_CONTENT_OPENGRAPH: string; public static PARAMETER_SHARE_DIALOG_CONTENT_UNKNOWN: string; public static EVENT_SHARE_RESULT: string; public static EVENT_SHARE_DIALOG_SHOW: string; public static EVENT_SHARE_MESSENGER_DIALOG_SHOW: string; public static EVENT_LIKE_BUTTON_CREATE: string; public static EVENT_LOGIN_BUTTON_CREATE: string; public static EVENT_SHARE_BUTTON_CREATE: string; public static EVENT_SEND_BUTTON_CREATE: string; public static EVENT_SHARE_BUTTON_DID_TAP: string; public static EVENT_SEND_BUTTON_DID_TAP: string; public static EVENT_LIKE_BUTTON_DID_TAP: string; public static EVENT_LOGIN_BUTTON_DID_TAP: string; public static EVENT_DEVICE_SHARE_BUTTON_CREATE: string; public static EVENT_DEVICE_SHARE_BUTTON_DID_TAP: string; public static EVENT_SMART_LOGIN_SERVICE: string; public static EVENT_SDK_INITIALIZE: string; public static PARAMETER_SHARE_MESSENGER_GENERIC_TEMPLATE: string; public static PARAMETER_SHARE_MESSENGER_MEDIA_TEMPLATE: string; public static PARAMETER_SHARE_MESSENGER_OPEN_GRAPH_MUSIC_TEMPLATE: string; public static EVENT_FOA_LOGIN_BUTTON_CREATE: string; public static EVENT_FOA_LOGIN_BUTTON_DID_TAP: string; public static EVENT_FOA_DISAMBIGUATION_DIALOG_FB_DID_TAP: string; public static EVENT_FOA_DISAMBIGUATION_DIALOG_IG_DID_TAP: string; public static EVENT_FOA_DISAMBIGUATION_DIALOG_CANCELLED: string; public static EVENT_FOA_FB_LOGIN_BUTTON_CREATE: string; public static EVENT_FOA_FB_LOGIN_BUTTON_DID_TAP: string; public static EVENT_FOA_IG_LOGIN_BUTTON_CREATE: string; public static EVENT_FOA_IG_LOGIN_BUTTON_DID_TAP: string; public static INSTANCE: com.facebook.internal.AnalyticsEvents; } } } } declare module com { export module facebook { export module internal { export class AppCall { public static class: java.lang.Class<com.facebook.internal.AppCall>; public static getCurrentPendingCall(): com.facebook.internal.AppCall; public static finishPendingCall(param0: java.util.UUID, param1: number): com.facebook.internal.AppCall; public getCallId(): java.util.UUID; public setRequestCode(param0: number): void; public setRequestIntent(param0: globalAndroid.content.Intent): void; public constructor(param0: number); public constructor(param0: number, param1: java.util.UUID); public getRequestCode(): number; public setPending(): boolean; public getRequestIntent(): globalAndroid.content.Intent; } } } } declare module com { export module facebook { export module internal { export class AttributionIdentifiers { public static class: java.lang.Class<com.facebook.internal.AttributionIdentifiers>; public static cachedIdentifiers: com.facebook.internal.AttributionIdentifiers; public static Companion: com.facebook.internal.AttributionIdentifiers.Companion; public static isTrackingLimited(param0: globalAndroid.content.Context): boolean; public getAndroidInstallerPackage(): string; public getAndroidAdvertiserId(): string; public isTrackingLimited(): boolean; public getAttributionId(): string; public static getAttributionIdentifiers(param0: globalAndroid.content.Context): com.facebook.internal.AttributionIdentifiers; public constructor(); } export module AttributionIdentifiers { export class Companion { public static class: java.lang.Class<com.facebook.internal.AttributionIdentifiers.Companion>; public isTrackingLimited(param0: globalAndroid.content.Context): boolean; public getAttributionIdentifiers(param0: globalAndroid.content.Context): com.facebook.internal.AttributionIdentifiers; } export class GoogleAdInfo { public static class: java.lang.Class<com.facebook.internal.AttributionIdentifiers.GoogleAdInfo>; public static Companion: com.facebook.internal.AttributionIdentifiers.GoogleAdInfo.Companion; public getAdvertiserId(): string; public isTrackingLimited(): boolean; public constructor(param0: globalAndroid.os.IBinder); public asBinder(): globalAndroid.os.IBinder; } export module GoogleAdInfo { export class Companion { public static class: java.lang.Class<com.facebook.internal.AttributionIdentifiers.GoogleAdInfo.Companion>; } } export class GoogleAdServiceConnection { public static class: java.lang.Class<com.facebook.internal.AttributionIdentifiers.GoogleAdServiceConnection>; public onServiceConnected(param0: globalAndroid.content.ComponentName, param1: globalAndroid.os.IBinder): void; public getBinder(): globalAndroid.os.IBinder; public constructor(); public onServiceDisconnected(param0: globalAndroid.content.ComponentName): void; } } } } } declare module com { export module facebook { export module internal { export class BoltsMeasurementEventListener { public static class: java.lang.Class<com.facebook.internal.BoltsMeasurementEventListener>; public static Companion: com.facebook.internal.BoltsMeasurementEventListener.Companion; public static getInstance(param0: globalAndroid.content.Context): com.facebook.internal.BoltsMeasurementEventListener; public finalize(): void; public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void; } export module BoltsMeasurementEventListener { export class Companion { public static class: java.lang.Class<com.facebook.internal.BoltsMeasurementEventListener.Companion>; public getMEASUREMENT_EVENT_NOTIFICATION_NAME$facebook_core_release(): string; public getInstance(param0: globalAndroid.content.Context): com.facebook.internal.BoltsMeasurementEventListener; } } } } } declare module com { export module facebook { export module internal { export class BundleJSONConverter { public static class: java.lang.Class<com.facebook.internal.BundleJSONConverter>; public static INSTANCE: com.facebook.internal.BundleJSONConverter; public static convertToBundle(param0: org.json.JSONObject): globalAndroid.os.Bundle; public static convertToJSON(param0: globalAndroid.os.Bundle): org.json.JSONObject; } export module BundleJSONConverter { export class Setter { public static class: java.lang.Class<com.facebook.internal.BundleJSONConverter.Setter>; /** * Constructs a new instance of the com.facebook.internal.BundleJSONConverter$Setter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { setOnBundle(param0: globalAndroid.os.Bundle, param1: string, param2: any): void; setOnJSON(param0: org.json.JSONObject, param1: string, param2: any): void; }); public constructor(); public setOnJSON(param0: org.json.JSONObject, param1: string, param2: any): void; public setOnBundle(param0: globalAndroid.os.Bundle, param1: string, param2: any): void; } } } } } declare module com { export module facebook { export module internal { export class CallbackManagerImpl extends com.facebook.CallbackManager { public static class: java.lang.Class<com.facebook.internal.CallbackManagerImpl>; public static Companion: com.facebook.internal.CallbackManagerImpl.Companion; public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): boolean; public registerCallback(param0: number, param1: com.facebook.internal.CallbackManagerImpl.Callback): void; public unregisterCallback(param0: number): void; public constructor(); public static registerStaticCallback(param0: number, param1: com.facebook.internal.CallbackManagerImpl.Callback): void; } export module CallbackManagerImpl { export class Callback { public static class: java.lang.Class<com.facebook.internal.CallbackManagerImpl.Callback>; /** * Constructs a new instance of the com.facebook.internal.CallbackManagerImpl$Callback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onActivityResult(param0: number, param1: globalAndroid.content.Intent): boolean; }); public constructor(); public onActivityResult(param0: number, param1: globalAndroid.content.Intent): boolean; } export class Companion { public static class: java.lang.Class<com.facebook.internal.CallbackManagerImpl.Companion>; public registerStaticCallback(param0: number, param1: com.facebook.internal.CallbackManagerImpl.Callback): void; } export class RequestCodeOffset { public static class: java.lang.Class<com.facebook.internal.CallbackManagerImpl.RequestCodeOffset>; public static Login: com.facebook.internal.CallbackManagerImpl.RequestCodeOffset; public static Share: com.facebook.internal.CallbackManagerImpl.RequestCodeOffset; public static Message: com.facebook.internal.CallbackManagerImpl.RequestCodeOffset; public static Like: com.facebook.internal.CallbackManagerImpl.RequestCodeOffset; public static GameRequest: com.facebook.internal.CallbackManagerImpl.RequestCodeOffset; public static AppGroupCreate: com.facebook.internal.CallbackManagerImpl.RequestCodeOffset; public static AppGroupJoin: com.facebook.internal.CallbackManagerImpl.RequestCodeOffset; public static AppInvite: com.facebook.internal.CallbackManagerImpl.RequestCodeOffset; public static DeviceShare: com.facebook.internal.CallbackManagerImpl.RequestCodeOffset; public static GamingFriendFinder: com.facebook.internal.CallbackManagerImpl.RequestCodeOffset; public static GamingGroupIntegration: com.facebook.internal.CallbackManagerImpl.RequestCodeOffset; public static Referral: com.facebook.internal.CallbackManagerImpl.RequestCodeOffset; public static values(): androidNative.Array<com.facebook.internal.CallbackManagerImpl.RequestCodeOffset>; public toRequestCode(): number; public static valueOf(param0: string): com.facebook.internal.CallbackManagerImpl.RequestCodeOffset; } } } } } declare module com { export module facebook { export module internal { export class CustomTab { public static class: java.lang.Class<com.facebook.internal.CustomTab>; public uri: globalAndroid.net.Uri; public constructor(param0: string, param1: globalAndroid.os.Bundle); public static getURIForAction(param0: string, param1: globalAndroid.os.Bundle): globalAndroid.net.Uri; public openCustomTab(param0: globalAndroid.app.Activity, param1: string): boolean; } } } } declare module com { export module facebook { export module internal { export class CustomTabUtils { public static class: java.lang.Class<com.facebook.internal.CustomTabUtils>; public static getChromePackage(): string; public static getValidRedirectURI(param0: string): string; public static getDefaultRedirectURI(): string; public constructor(); } } } } declare module com { export module facebook { export module internal { export class DialogFeature { public static class: java.lang.Class<com.facebook.internal.DialogFeature>; /** * Constructs a new instance of the com.facebook.internal.DialogFeature interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getAction(): string; getMinVersion(): number; name(): string; }); public constructor(); public getMinVersion(): number; public name(): string; public getAction(): string; } } } } declare module com { export module facebook { export module internal { export class DialogPresenter { public static class: java.lang.Class<com.facebook.internal.DialogPresenter>; public static setupAppCallForNativeDialog(param0: com.facebook.internal.AppCall, param1: com.facebook.internal.DialogPresenter.ParameterProvider, param2: com.facebook.internal.DialogFeature): void; public static setupAppCallForWebFallbackDialog(param0: com.facebook.internal.AppCall, param1: globalAndroid.os.Bundle, param2: com.facebook.internal.DialogFeature): void; public static setupAppCallForErrorResult(param0: com.facebook.internal.AppCall, param1: com.facebook.FacebookException): void; public static canPresentNativeDialogWithFeature(param0: com.facebook.internal.DialogFeature): boolean; public static canPresentWebFallbackDialogWithFeature(param0: com.facebook.internal.DialogFeature): boolean; public static present(param0: com.facebook.internal.AppCall, param1: androidx.activity.result.ActivityResultRegistry, param2: com.facebook.CallbackManager): void; public static logDialogActivity(param0: globalAndroid.content.Context, param1: string, param2: string): void; public constructor(); public static present(param0: com.facebook.internal.AppCall, param1: com.facebook.internal.FragmentWrapper): void; public static startActivityForResultWithAndroidX(param0: androidx.activity.result.ActivityResultRegistry, param1: com.facebook.CallbackManager, param2: globalAndroid.content.Intent, param3: number): void; public static getProtocolVersionForNativeDialog(param0: com.facebook.internal.DialogFeature): com.facebook.internal.NativeProtocol.ProtocolVersionQueryResult; public static setupAppCallForCustomTabDialog(param0: com.facebook.internal.AppCall, param1: string, param2: globalAndroid.os.Bundle): void; public static setupAppCallForWebDialog(param0: com.facebook.internal.AppCall, param1: string, param2: globalAndroid.os.Bundle): void; public static setupAppCallForValidationError(param0: com.facebook.internal.AppCall, param1: com.facebook.FacebookException): void; public static setupAppCallForCannotShowError(param0: com.facebook.internal.AppCall): void; public static present(param0: com.facebook.internal.AppCall, param1: globalAndroid.app.Activity): void; } export module DialogPresenter { export class ParameterProvider { public static class: java.lang.Class<com.facebook.internal.DialogPresenter.ParameterProvider>; /** * Constructs a new instance of the com.facebook.internal.DialogPresenter$ParameterProvider interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getParameters(): globalAndroid.os.Bundle; getLegacyParameters(): globalAndroid.os.Bundle; }); public constructor(); public getParameters(): globalAndroid.os.Bundle; public getLegacyParameters(): globalAndroid.os.Bundle; } } } } } declare module com { export module facebook { export module internal { export abstract class FacebookDialogBase<CONTENT, RESULT> extends com.facebook.FacebookDialog<any,any> { public static class: java.lang.Class<com.facebook.internal.FacebookDialogBase<any,any>>; public static BASE_AUTOMATIC_MODE: any; public constructor(param0: com.facebook.internal.FragmentWrapper, param1: number); public setCallbackManager(param0: com.facebook.CallbackManager): void; public showImpl(param0: any, param1: any): void; public registerCallback(param0: com.facebook.CallbackManager, param1: com.facebook.FacebookCallback<any>, param2: number): void; public canShowImpl(param0: any, param1: any): boolean; public canShow(param0: any): boolean; public constructor(param0: globalAndroid.app.Activity, param1: number); public registerCallback(param0: com.facebook.CallbackManager, param1: com.facebook.FacebookCallback<any>): void; public getOrderedModeHandlers(): java.util.List<com.facebook.internal.FacebookDialogBase.ModeHandler>; public registerCallbackImpl(param0: com.facebook.internal.CallbackManagerImpl, param1: com.facebook.FacebookCallback<any>): void; public setRequestCode(param0: number): void; public show(param0: any): void; public startActivityForResult(param0: globalAndroid.content.Intent, param1: number): void; public getActivityContext(): globalAndroid.app.Activity; public createBaseAppCall(): com.facebook.internal.AppCall; public getRequestCode(): number; } export module FacebookDialogBase { export abstract class ModeHandler { public static class: java.lang.Class<com.facebook.internal.FacebookDialogBase.ModeHandler>; public getMode(): any; public canShow(param0: any, param1: boolean): boolean; public createAppCall(param0: any): com.facebook.internal.AppCall; public constructor(param0: com.facebook.internal.FacebookDialogBase<any,any>); } } } } } declare module com { export module facebook { export module internal { export class FacebookDialogFragment { public static class: java.lang.Class<com.facebook.internal.FacebookDialogFragment>; public static TAG: string; public setDialog(param0: globalAndroid.app.Dialog): void; public onCreate(param0: globalAndroid.os.Bundle): void; public onResume(): void; public onConfigurationChanged(param0: globalAndroid.content.res.Configuration): void; public onDestroyView(): void; public onCreateDialog(param0: globalAndroid.os.Bundle): globalAndroid.app.Dialog; public constructor(); } } } } declare module com { export module facebook { export module internal { export class FacebookInitProvider { public static class: java.lang.Class<com.facebook.internal.FacebookInitProvider>; public static Companion: com.facebook.internal.FacebookInitProvider.Companion; public getType(param0: globalAndroid.net.Uri): string; public insert(param0: globalAndroid.net.Uri, param1: globalAndroid.content.ContentValues): globalAndroid.net.Uri; public update(param0: globalAndroid.net.Uri, param1: globalAndroid.content.ContentValues, param2: string, param3: androidNative.Array<string>): number; public delete(param0: globalAndroid.net.Uri, param1: string, param2: androidNative.Array<string>): number; public query(param0: globalAndroid.net.Uri, param1: androidNative.Array<string>, param2: string, param3: androidNative.Array<string>, param4: string): globalAndroid.database.Cursor; public onCreate(): boolean; public constructor(); } export module FacebookInitProvider { export class Companion { public static class: java.lang.Class<com.facebook.internal.FacebookInitProvider.Companion>; } } } } } declare module com { export module facebook { export module internal { export class FacebookRequestErrorClassification { public static class: java.lang.Class<com.facebook.internal.FacebookRequestErrorClassification>; public static EC_SERVICE_UNAVAILABLE: number; public static EC_APP_TOO_MANY_CALLS: number; public static EC_RATE: number; public static EC_USER_TOO_MANY_CALLS: number; public static EC_INVALID_SESSION: number; public static EC_INVALID_TOKEN: number; public static EC_APP_NOT_INSTALLED: number; public static EC_TOO_MANY_USER_ACTION_CALLS: number; public static ESC_APP_NOT_INSTALLED: number; public static ESC_APP_INACTIVE: number; public static KEY_RECOVERY_MESSAGE: string; public static KEY_NAME: string; public static KEY_OTHER: string; public static KEY_TRANSIENT: string; public static KEY_LOGIN_RECOVERABLE: string; public static Companion: com.facebook.internal.FacebookRequestErrorClassification.Companion; public getLoginRecoverableErrors(): java.util.Map<java.lang.Integer,java.util.Set<java.lang.Integer>>; public static getDefaultErrorClassification(): com.facebook.internal.FacebookRequestErrorClassification; public getTransientErrors(): java.util.Map<java.lang.Integer,java.util.Set<java.lang.Integer>>; public getOtherErrors(): java.util.Map<java.lang.Integer,java.util.Set<java.lang.Integer>>; public classify(param0: number, param1: number, param2: boolean): com.facebook.FacebookRequestError.Category; public getRecoveryMessage(param0: com.facebook.FacebookRequestError.Category): string; public constructor(param0: java.util.Map<java.lang.Integer,any>, param1: java.util.Map<java.lang.Integer,any>, param2: java.util.Map<java.lang.Integer,any>, param3: string, param4: string, param5: string); public static createFromJSON(param0: org.json.JSONArray): com.facebook.internal.FacebookRequestErrorClassification; } export module FacebookRequestErrorClassification { export class Companion { public static class: java.lang.Class<com.facebook.internal.FacebookRequestErrorClassification.Companion>; public createFromJSON(param0: org.json.JSONArray): com.facebook.internal.FacebookRequestErrorClassification; public getDefaultErrorClassification(): com.facebook.internal.FacebookRequestErrorClassification; } export class WhenMappings { public static class: java.lang.Class<com.facebook.internal.FacebookRequestErrorClassification.WhenMappings>; } } } } } declare module com { export module facebook { export module internal { export class FacebookSignatureValidator { public static class: java.lang.Class<com.facebook.internal.FacebookSignatureValidator>; public static INSTANCE: com.facebook.internal.FacebookSignatureValidator; public static validateSignature(param0: globalAndroid.content.Context, param1: string): boolean; } } } } declare module com { export module facebook { export module internal { export class FacebookWebFallbackDialog extends com.facebook.internal.WebDialog { public static class: java.lang.Class<com.facebook.internal.FacebookWebFallbackDialog>; public static newInstance(param0: globalAndroid.content.Context, param1: string, param2: globalAndroid.os.Bundle, param3: number, param4: com.facebook.login.LoginTargetApp, param5: com.facebook.internal.WebDialog.OnCompleteListener): com.facebook.internal.WebDialog; public cancel(): void; public static newInstance(param0: globalAndroid.content.Context, param1: string, param2: globalAndroid.os.Bundle, param3: number, param4: com.facebook.internal.WebDialog.OnCompleteListener): com.facebook.internal.WebDialog; public parseResponseUri(param0: string): globalAndroid.os.Bundle; public static newInstance(param0: globalAndroid.content.Context, param1: string, param2: string): com.facebook.internal.FacebookWebFallbackDialog; } } } } declare module com { export module facebook { export module internal { export class FeatureManager { public static class: java.lang.Class<com.facebook.internal.FeatureManager>; public static INSTANCE: com.facebook.internal.FeatureManager; public static isEnabled(param0: com.facebook.internal.FeatureManager.Feature): boolean; public static disableFeature(param0: com.facebook.internal.FeatureManager.Feature): void; public static checkFeature(param0: com.facebook.internal.FeatureManager.Feature, param1: com.facebook.internal.FeatureManager.Callback): void; public static getFeature(param0: string): com.facebook.internal.FeatureManager.Feature; } export module FeatureManager { export class Callback { public static class: java.lang.Class<com.facebook.internal.FeatureManager.Callback>; /** * Constructs a new instance of the com.facebook.internal.FeatureManager$Callback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onCompleted(param0: boolean): void; }); public constructor(); public onCompleted(param0: boolean): void; } export class Feature { public static class: java.lang.Class<com.facebook.internal.FeatureManager.Feature>; public static Unknown: com.facebook.internal.FeatureManager.Feature; public static Core: com.facebook.internal.FeatureManager.Feature; public static AppEvents: com.facebook.internal.FeatureManager.Feature; public static CodelessEvents: com.facebook.internal.FeatureManager.Feature; public static RestrictiveDataFiltering: com.facebook.internal.FeatureManager.Feature; public static AAM: com.facebook.internal.FeatureManager.Feature; public static PrivacyProtection: com.facebook.internal.FeatureManager.Feature; public static SuggestedEvents: com.facebook.internal.FeatureManager.Feature; public static IntelligentIntegrity: com.facebook.internal.FeatureManager.Feature; public static ModelRequest: com.facebook.internal.FeatureManager.Feature; public static EventDeactivation: com.facebook.internal.FeatureManager.Feature; public static OnDeviceEventProcessing: com.facebook.internal.FeatureManager.Feature; public static OnDevicePostInstallEventProcessing: com.facebook.internal.FeatureManager.Feature; public static IapLogging: com.facebook.internal.FeatureManager.Feature; public static IapLoggingLib2: com.facebook.internal.FeatureManager.Feature; public static Instrument: com.facebook.internal.FeatureManager.Feature; public static CrashReport: com.facebook.internal.FeatureManager.Feature; public static CrashShield: com.facebook.internal.FeatureManager.Feature; public static ThreadCheck: com.facebook.internal.FeatureManager.Feature; public static ErrorReport: com.facebook.internal.FeatureManager.Feature; public static AnrReport: com.facebook.internal.FeatureManager.Feature; public static Monitoring: com.facebook.internal.FeatureManager.Feature; public static Login: com.facebook.internal.FeatureManager.Feature; public static ChromeCustomTabsPrefetching: com.facebook.internal.FeatureManager.Feature; public static IgnoreAppSwitchToLoggedOut: com.facebook.internal.FeatureManager.Feature; public static BypassAppSwitch: com.facebook.internal.FeatureManager.Feature; public static Share: com.facebook.internal.FeatureManager.Feature; public static Places: com.facebook.internal.FeatureManager.Feature; public static Companion: com.facebook.internal.FeatureManager.Feature.Companion; public toString(): string; public getParent(): com.facebook.internal.FeatureManager.Feature; public static values(): androidNative.Array<com.facebook.internal.FeatureManager.Feature>; public static valueOf(param0: string): com.facebook.internal.FeatureManager.Feature; public toKey(): string; } export module Feature { export class Companion { public static class: java.lang.Class<com.facebook.internal.FeatureManager.Feature.Companion>; public fromInt(param0: number): com.facebook.internal.FeatureManager.Feature; } export class WhenMappings { public static class: java.lang.Class<com.facebook.internal.FeatureManager.Feature.WhenMappings>; } } export class WhenMappings { public static class: java.lang.Class<com.facebook.internal.FeatureManager.WhenMappings>; } } } } } declare module com { export module facebook { export module internal { export class FetchedAppGateKeepersManager { public static class: java.lang.Class<com.facebook.internal.FetchedAppGateKeepersManager>; public static INSTANCE: com.facebook.internal.FetchedAppGateKeepersManager; public static getGateKeeperForKey(param0: string, param1: string, param2: boolean): boolean; public loadAppGateKeepersAsync(): void; public static resetRuntimeGateKeeperCache(): void; public static setRuntimeGateKeeper(param0: string, param1: com.facebook.internal.gatekeeper.GateKeeper): void; public static queryAppGateKeepers(param0: string, param1: boolean): org.json.JSONObject; public getGateKeepersForApplication(param0: string): java.util.Map<string,java.lang.Boolean>; public static parseAppGateKeepersFromJSON$facebook_core_release(param0: string, param1: org.json.JSONObject): org.json.JSONObject; public static loadAppGateKeepersAsync(param0: com.facebook.internal.FetchedAppGateKeepersManager.Callback): void; } export module FetchedAppGateKeepersManager { export class Callback { public static class: java.lang.Class<com.facebook.internal.FetchedAppGateKeepersManager.Callback>; /** * Constructs a new instance of the com.facebook.internal.FetchedAppGateKeepersManager$Callback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onCompleted(): void; }); public constructor(); public onCompleted(): void; } } } } } declare module com { export module facebook { export module internal { export class FetchedAppSettings { public static class: java.lang.Class<com.facebook.internal.FetchedAppSettings>; public static Companion: com.facebook.internal.FetchedAppSettings.Companion; public getErrorClassification(): com.facebook.internal.FacebookRequestErrorClassification; public getSmartLoginMenuIconURL(): string; public getEventBindings(): org.json.JSONArray; public getSdkUpdateMessage(): string; public getRestrictiveDataSetting(): string; public getIAPAutomaticLoggingEnabled(): boolean; public getCodelessEventsEnabled(): boolean; public static getDialogFeatureConfig(param0: string, param1: string, param2: string): com.facebook.internal.FetchedAppSettings.DialogFeatureConfig; public getNuxContent(): string; public getSmartLoginOptions(): java.util.EnumSet<com.facebook.internal.SmartLoginOption>; public getTrackUninstallEnabled(): boolean; public getSessionTimeoutInSeconds(): number; public getDialogConfigurations(): java.util.Map<string,java.util.Map<string,com.facebook.internal.FetchedAppSettings.DialogFeatureConfig>>; public getMonitorViaDialogEnabled(): boolean; public getAutomaticLoggingEnabled(): boolean; public getSmartLoginBookmarkIconURL(): string; public getSuggestedEventsSetting(): string; public getRawAamRules(): string; public supportsImplicitLogging(): boolean; public getNuxEnabled(): boolean; public constructor(param0: boolean, param1: string, param2: boolean, param3: number, param4: java.util.EnumSet<com.facebook.internal.SmartLoginOption>, param5: java.util.Map<string,any>, param6: boolean, param7: com.facebook.internal.FacebookRequestErrorClassification, param8: string, param9: string, param10: boolean, param11: boolean, param12: org.json.JSONArray, param13: string, param14: boolean, param15: boolean, param16: string, param17: string, param18: string); } export module FetchedAppSettings { export class Companion { public static class: java.lang.Class<com.facebook.internal.FetchedAppSettings.Companion>; public getDialogFeatureConfig(param0: string, param1: string, param2: string): com.facebook.internal.FetchedAppSettings.DialogFeatureConfig; } export class DialogFeatureConfig { public static class: java.lang.Class<com.facebook.internal.FetchedAppSettings.DialogFeatureConfig>; public static Companion: com.facebook.internal.FetchedAppSettings.DialogFeatureConfig.Companion; public getFeatureName(): string; public getFallbackUrl(): globalAndroid.net.Uri; public getVersionSpec(): androidNative.Array<number>; public getDialogName(): string; } export module DialogFeatureConfig { export class Companion { public static class: java.lang.Class<com.facebook.internal.FetchedAppSettings.DialogFeatureConfig.Companion>; public parseDialogConfig(param0: org.json.JSONObject): com.facebook.internal.FetchedAppSettings.DialogFeatureConfig; } } } } } } declare module com { export module facebook { export module internal { export class FetchedAppSettingsManager { public static class: java.lang.Class<com.facebook.internal.FetchedAppSettingsManager>; public static INSTANCE: com.facebook.internal.FetchedAppSettingsManager; public static getAppSettingsAsync(param0: com.facebook.internal.FetchedAppSettingsManager.FetchedAppSettingsCallback): void; public static getAppSettingsWithoutQuery(param0: string): com.facebook.internal.FetchedAppSettings; public static setIsUnityInit(param0: boolean): void; public parseAppSettingsFromJSON$facebook_core_release(param0: string, param1: org.json.JSONObject): com.facebook.internal.FetchedAppSettings; public static loadAppSettingsAsync(): void; public static queryAppSettings(param0: string, param1: boolean): com.facebook.internal.FetchedAppSettings; } export module FetchedAppSettingsManager { export class FetchAppSettingState { public static class: java.lang.Class<com.facebook.internal.FetchedAppSettingsManager.FetchAppSettingState>; public static NOT_LOADED: com.facebook.internal.FetchedAppSettingsManager.FetchAppSettingState; public static LOADING: com.facebook.internal.FetchedAppSettingsManager.FetchAppSettingState; public static SUCCESS: com.facebook.internal.FetchedAppSettingsManager.FetchAppSettingState; public static ERROR: com.facebook.internal.FetchedAppSettingsManager.FetchAppSettingState; public static values(): androidNative.Array<com.facebook.internal.FetchedAppSettingsManager.FetchAppSettingState>; public static valueOf(param0: string): com.facebook.internal.FetchedAppSettingsManager.FetchAppSettingState; } export class FetchedAppSettingsCallback { public static class: java.lang.Class<com.facebook.internal.FetchedAppSettingsManager.FetchedAppSettingsCallback>; /** * Constructs a new instance of the com.facebook.internal.FetchedAppSettingsManager$FetchedAppSettingsCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onSuccess(param0: com.facebook.internal.FetchedAppSettings): void; onError(): void; }); public constructor(); public onSuccess(param0: com.facebook.internal.FetchedAppSettings): void; public onError(): void; } } } } } declare module com { export module facebook { export module internal { export class FileLruCache { public static class: java.lang.Class<com.facebook.internal.FileLruCache>; public static Companion: com.facebook.internal.FileLruCache.Companion; public get(param0: string, param1: string): java.io.InputStream; public constructor(param0: string, param1: com.facebook.internal.FileLruCache.Limits); public openPutStream(param0: string, param1: string): java.io.OutputStream; public getLocation(): string; public sizeInBytesForTest(): number; public get(param0: string): java.io.InputStream; public interceptAndPut(param0: string, param1: java.io.InputStream): java.io.InputStream; public toString(): string; public clearCache(): void; public openPutStream(param0: string): java.io.OutputStream; } export module FileLruCache { export class BufferFile { public static class: java.lang.Class<com.facebook.internal.FileLruCache.BufferFile>; public static INSTANCE: com.facebook.internal.FileLruCache.BufferFile; public excludeBufferFiles(): java.io.FilenameFilter; public deleteAll(param0: java.io.File): void; public excludeNonBufferFiles(): java.io.FilenameFilter; public newFile(param0: java.io.File): java.io.File; } export class CloseCallbackOutputStream { public static class: java.lang.Class<com.facebook.internal.FileLruCache.CloseCallbackOutputStream>; public getCallback(): com.facebook.internal.FileLruCache.StreamCloseCallback; public write(param0: androidNative.Array<number>): void; public getInnerStream(): java.io.OutputStream; public close(): void; public flush(): void; public write(param0: number): void; public constructor(param0: java.io.OutputStream, param1: com.facebook.internal.FileLruCache.StreamCloseCallback); public write(param0: androidNative.Array<number>, param1: number, param2: number): void; } export class Companion { public static class: java.lang.Class<com.facebook.internal.FileLruCache.Companion>; public getTAG(): string; } export class CopyingInputStream { public static class: java.lang.Class<com.facebook.internal.FileLruCache.CopyingInputStream>; public available(): number; public read(): number; public reset(): void; public getOutput(): java.io.OutputStream; public markSupported(): boolean; public close(): void; public skip(param0: number): number; public read(param0: androidNative.Array<number>, param1: number, param2: number): number; public constructor(param0: java.io.InputStream, param1: java.io.OutputStream); public read(param0: androidNative.Array<number>): number; public getInput(): java.io.InputStream; public mark(param0: number): void; } export class Limits { public static class: java.lang.Class<com.facebook.internal.FileLruCache.Limits>; public setFileCount(param0: number): void; public constructor(); public getFileCount(): number; public getByteCount(): number; public setByteCount(param0: number): void; } export class ModifiedFile extends java.lang.Comparable<com.facebook.internal.FileLruCache.ModifiedFile> { public static class: java.lang.Class<com.facebook.internal.FileLruCache.ModifiedFile>; public static Companion: com.facebook.internal.FileLruCache.ModifiedFile.Companion; public equals(param0: any): boolean; public compareTo(param0: com.facebook.internal.FileLruCache.ModifiedFile): number; public getFile(): java.io.File; public hashCode(): number; public constructor(param0: java.io.File); public getModified(): number; } export module ModifiedFile { export class Companion { public static class: java.lang.Class<com.facebook.internal.FileLruCache.ModifiedFile.Companion>; } } export class StreamCloseCallback { public static class: java.lang.Class<com.facebook.internal.FileLruCache.StreamCloseCallback>; /** * Constructs a new instance of the com.facebook.internal.FileLruCache$StreamCloseCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onClose(): void; }); public constructor(); public onClose(): void; } export class StreamHeader { public static class: java.lang.Class<com.facebook.internal.FileLruCache.StreamHeader>; public static INSTANCE: com.facebook.internal.FileLruCache.StreamHeader; public readHeader(param0: java.io.InputStream): org.json.JSONObject; public writeHeader(param0: java.io.OutputStream, param1: org.json.JSONObject): void; } } } } } declare module com { export module facebook { export module internal { export class FragmentWrapper { public static class: java.lang.Class<com.facebook.internal.FragmentWrapper>; public getSupportFragment(): androidx.fragment.app.Fragment; public getActivity(): globalAndroid.app.Activity; public constructor(param0: androidx.fragment.app.Fragment); public startActivityForResult(param0: globalAndroid.content.Intent, param1: number): void; public getNativeFragment(): globalAndroid.app.Fragment; public constructor(param0: globalAndroid.app.Fragment); } } } } declare module com { export module facebook { export module internal { export class ImageDownloader { public static class: java.lang.Class<com.facebook.internal.ImageDownloader>; public static INSTANCE: com.facebook.internal.ImageDownloader; public static downloadAsync(param0: com.facebook.internal.ImageRequest): void; public getPendingRequests(): java.util.Map<com.facebook.internal.ImageDownloader.RequestKey,com.facebook.internal.ImageDownloader.DownloaderContext>; public static cancelRequest(param0: com.facebook.internal.ImageRequest): boolean; public static clearCache(): void; public static prioritizeRequest(param0: com.facebook.internal.ImageRequest): void; } export module ImageDownloader { export class CacheReadWorkItem { public static class: java.lang.Class<com.facebook.internal.ImageDownloader.CacheReadWorkItem>; public constructor(param0: com.facebook.internal.ImageDownloader.RequestKey, param1: boolean); public run(): void; } export class DownloadImageWorkItem { public static class: java.lang.Class<com.facebook.internal.ImageDownloader.DownloadImageWorkItem>; public run(): void; public constructor(param0: com.facebook.internal.ImageDownloader.RequestKey); } export class DownloaderContext { public static class: java.lang.Class<com.facebook.internal.ImageDownloader.DownloaderContext>; public isCancelled(): boolean; public setWorkItem(param0: com.facebook.internal.WorkQueue.WorkItem): void; public setCancelled(param0: boolean): void; public constructor(param0: com.facebook.internal.ImageRequest); public getWorkItem(): com.facebook.internal.WorkQueue.WorkItem; public getRequest(): com.facebook.internal.ImageRequest; public setRequest(param0: com.facebook.internal.ImageRequest): void; } export class RequestKey { public static class: java.lang.Class<com.facebook.internal.ImageDownloader.RequestKey>; public static Companion: com.facebook.internal.ImageDownloader.RequestKey.Companion; public equals(param0: any): boolean; public getTag(): any; public getUri(): globalAndroid.net.Uri; public hashCode(): number; public setUri(param0: globalAndroid.net.Uri): void; public setTag(param0: any): void; public constructor(param0: globalAndroid.net.Uri, param1: any); } export module RequestKey { export class Companion { public static class: java.lang.Class<com.facebook.internal.ImageDownloader.RequestKey.Companion>; } } } } } } declare module com { export module facebook { export module internal { export class ImageRequest { public static class: java.lang.Class<com.facebook.internal.ImageRequest>; public static UNSPECIFIED_DIMENSION: number; public static Companion: com.facebook.internal.ImageRequest.Companion; public getContext(): globalAndroid.content.Context; public getImageUri(): globalAndroid.net.Uri; public static getProfilePictureUri(param0: string, param1: number, param2: number): globalAndroid.net.Uri; public getCallerTag(): any; public getAllowCachedRedirects(): boolean; public getCallback(): com.facebook.internal.ImageRequest.Callback; public isCachedRedirectAllowed(): boolean; public static getProfilePictureUri(param0: string, param1: number, param2: number, param3: string): globalAndroid.net.Uri; } export module ImageRequest { export class Builder { public static class: java.lang.Class<com.facebook.internal.ImageRequest.Builder>; public setCallback(param0: com.facebook.internal.ImageRequest.Callback): com.facebook.internal.ImageRequest.Builder; public setCallerTag(param0: any): com.facebook.internal.ImageRequest.Builder; public equals(param0: any): boolean; public toString(): string; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.net.Uri); public setAllowCachedRedirects(param0: boolean): com.facebook.internal.ImageRequest.Builder; public copy(param0: globalAndroid.content.Context, param1: globalAndroid.net.Uri): com.facebook.internal.ImageRequest.Builder; public build(): com.facebook.internal.ImageRequest; public hashCode(): number; } export class Callback { public static class: java.lang.Class<com.facebook.internal.ImageRequest.Callback>; /** * Constructs a new instance of the com.facebook.internal.ImageRequest$Callback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onCompleted(param0: com.facebook.internal.ImageResponse): void; }); public constructor(); public onCompleted(param0: com.facebook.internal.ImageResponse): void; } export class Companion { public static class: java.lang.Class<com.facebook.internal.ImageRequest.Companion>; public getProfilePictureUri(param0: string, param1: number, param2: number): globalAndroid.net.Uri; public getProfilePictureUri(param0: string, param1: number, param2: number, param3: string): globalAndroid.net.Uri; } } } } } declare module com { export module facebook { export module internal { export class ImageResponse { public static class: java.lang.Class<com.facebook.internal.ImageResponse>; public constructor(param0: com.facebook.internal.ImageRequest, param1: java.lang.Exception, param2: boolean, param3: globalAndroid.graphics.Bitmap); public getRequest(): com.facebook.internal.ImageRequest; public isCachedRedirect(): boolean; public getBitmap(): globalAndroid.graphics.Bitmap; public getError(): java.lang.Exception; } } } } declare module com { export module facebook { export module internal { export class ImageResponseCache { public static class: java.lang.Class<com.facebook.internal.ImageResponseCache>; public static INSTANCE: com.facebook.internal.ImageResponseCache; public getTAG(): string; public static getCache(): com.facebook.internal.FileLruCache; public static getCachedImageStream(param0: globalAndroid.net.Uri): java.io.InputStream; public static clearCache(): void; public static interceptAndCacheImageStream(param0: java.net.HttpURLConnection): java.io.InputStream; } export module ImageResponseCache { export class BufferedHttpInputStream { public static class: java.lang.Class<com.facebook.internal.ImageResponseCache.BufferedHttpInputStream>; public constructor(param0: java.io.InputStream, param1: java.net.HttpURLConnection); public close(): void; public getConnection(): java.net.HttpURLConnection; public setConnection(param0: java.net.HttpURLConnection): void; } } } } } declare module com { export module facebook { export module internal { export class InstagramCustomTab extends com.facebook.internal.CustomTab { public static class: java.lang.Class<com.facebook.internal.InstagramCustomTab>; public constructor(param0: string, param1: globalAndroid.os.Bundle); public static getURIForAction(param0: string, param1: globalAndroid.os.Bundle): globalAndroid.net.Uri; } } } } declare module com { export module facebook { export module internal { export class InstallReferrerUtil { public static class: java.lang.Class<com.facebook.internal.InstallReferrerUtil>; public static INSTANCE: com.facebook.internal.InstallReferrerUtil; public static tryUpdateReferrerInfo(param0: com.facebook.internal.InstallReferrerUtil.Callback): void; } export module InstallReferrerUtil { export class Callback { public static class: java.lang.Class<com.facebook.internal.InstallReferrerUtil.Callback>; /** * Constructs a new instance of the com.facebook.internal.InstallReferrerUtil$Callback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onReceiveReferrerUrl(param0: string): void; }); public constructor(); public onReceiveReferrerUrl(param0: string): void; } } } } } declare module com { export module facebook { export module internal { export class InternalSettings { public static class: java.lang.Class<com.facebook.internal.InternalSettings>; public static INSTANCE: com.facebook.internal.InternalSettings; public static getCustomUserAgent(): string; public static isUnityApp(): boolean; public static setCustomUserAgent(param0: string): void; } } } } declare module com { export module facebook { export module internal { export class LockOnGetVariable<T> extends java.lang.Object { public static class: java.lang.Class<com.facebook.internal.LockOnGetVariable<any>>; public constructor(param0: T); public getValue(): T; public constructor(param0: java.util.concurrent.Callable<T>); } } } } declare module com { export module facebook { export module internal { export class Logger { public static class: java.lang.Class<com.facebook.internal.Logger>; public static LOG_TAG_BASE: string; public static Companion: com.facebook.internal.Logger.Companion; public getContents(): string; public static log(param0: com.facebook.LoggingBehavior, param1: string, param2: string, param3: androidNative.Array<any>): void; public append(param0: string): void; public logString(param0: string): void; public static log(param0: com.facebook.LoggingBehavior, param1: number, param2: string, param3: string): void; public append(param0: string, param1: androidNative.Array<any>): void; public static registerAccessToken(param0: string): void; public getPriority(): number; public static registerStringToReplace(param0: string, param1: string): void; public constructor(param0: com.facebook.LoggingBehavior, param1: string); public static log(param0: com.facebook.LoggingBehavior, param1: string, param2: string): void; public setPriority(param0: number): void; public appendKeyValue(param0: string, param1: any): void; public log(): void; public append(param0: java.lang.StringBuilder): void; public static log(param0: com.facebook.LoggingBehavior, param1: number, param2: string, param3: string, param4: androidNative.Array<any>): void; } export module Logger { export class Companion { public static class: java.lang.Class<com.facebook.internal.Logger.Companion>; public log(param0: com.facebook.LoggingBehavior, param1: string, param2: string, param3: androidNative.Array<any>): void; public log(param0: com.facebook.LoggingBehavior, param1: number, param2: string, param3: string, param4: androidNative.Array<any>): void; public registerAccessToken(param0: string): void; public registerStringToReplace(param0: string, param1: string): void; public log(param0: com.facebook.LoggingBehavior, param1: number, param2: string, param3: string): void; public log(param0: com.facebook.LoggingBehavior, param1: string, param2: string): void; } } } } } declare module com { export module facebook { export module internal { export class NativeAppCallAttachmentStore { public static class: java.lang.Class<com.facebook.internal.NativeAppCallAttachmentStore>; public static ATTACHMENTS_DIR_NAME: string; public static INSTANCE: com.facebook.internal.NativeAppCallAttachmentStore; public static cleanupAllAttachments(): void; public static createAttachment(param0: java.util.UUID, param1: globalAndroid.graphics.Bitmap): com.facebook.internal.NativeAppCallAttachmentStore.Attachment; public static ensureAttachmentsDirectoryExists(): java.io.File; public static getAttachmentFile(param0: java.util.UUID, param1: string, param2: boolean): java.io.File; public static createAttachment(param0: java.util.UUID, param1: globalAndroid.net.Uri): com.facebook.internal.NativeAppCallAttachmentStore.Attachment; public static getAttachmentsDirectoryForCall(param0: java.util.UUID, param1: boolean): java.io.File; public static addAttachments(param0: java.util.Collection<com.facebook.internal.NativeAppCallAttachmentStore.Attachment>): void; public static cleanupAttachmentsForCall(param0: java.util.UUID): void; public static openAttachment(param0: java.util.UUID, param1: string): java.io.File; public static getAttachmentsDirectory(): java.io.File; } export module NativeAppCallAttachmentStore { export class Attachment { public static class: java.lang.Class<com.facebook.internal.NativeAppCallAttachmentStore.Attachment>; public setShouldCreateFile(param0: boolean): void; public constructor(param0: java.util.UUID, param1: globalAndroid.graphics.Bitmap, param2: globalAndroid.net.Uri); public getOriginalUri(): globalAndroid.net.Uri; public getAttachmentName(): string; public getCallId(): java.util.UUID; public setContentUri(param0: boolean): void; public getBitmap(): globalAndroid.graphics.Bitmap; public getAttachmentUrl(): string; public isContentUri(): boolean; public getShouldCreateFile(): boolean; } } } } } declare module com { export module facebook { export module internal { export class NativeProtocol { public static class: java.lang.Class<com.facebook.internal.NativeProtocol>; public static NO_PROTOCOL_AVAILABLE: number; public static FACEBOOK_PROXY_AUTH_PERMISSIONS_KEY: string; public static FACEBOOK_PROXY_AUTH_APP_ID_KEY: string; public static FACEBOOK_PROXY_AUTH_E2E_KEY: string; public static FACEBOOK_SDK_VERSION_KEY: string; public static INTENT_ACTION_PLATFORM_ACTIVITY: string; public static INTENT_ACTION_PLATFORM_SERVICE: string; public static PROTOCOL_VERSION_20121101: number; public static PROTOCOL_VERSION_20130502: number; public static PROTOCOL_VERSION_20130618: number; public static PROTOCOL_VERSION_20131107: number; public static PROTOCOL_VERSION_20140204: number; public static PROTOCOL_VERSION_20140324: number; public static PROTOCOL_VERSION_20140701: number; public static PROTOCOL_VERSION_20141001: number; public static PROTOCOL_VERSION_20141028: number; public static PROTOCOL_VERSION_20141107: number; public static PROTOCOL_VERSION_20141218: number; public static PROTOCOL_VERSION_20160327: number; public static PROTOCOL_VERSION_20170213: number; public static PROTOCOL_VERSION_20170411: number; public static PROTOCOL_VERSION_20170417: number; public static PROTOCOL_VERSION_20171115: number; public static PROTOCOL_VERSION_20210906: number; public static EXTRA_PROTOCOL_VERSION: string; public static EXTRA_PROTOCOL_ACTION: string; public static EXTRA_PROTOCOL_CALL_ID: string; public static EXTRA_GET_INSTALL_DATA_PACKAGE: string; public static EXTRA_PROTOCOL_BRIDGE_ARGS: string; public static EXTRA_PROTOCOL_METHOD_ARGS: string; public static EXTRA_PROTOCOL_METHOD_RESULTS: string; public static BRIDGE_ARG_APP_NAME_STRING: string; public static BRIDGE_ARG_ACTION_ID_STRING: string; public static BRIDGE_ARG_ERROR_BUNDLE: string; public static EXTRA_DIALOG_COMPLETE_KEY: string; public static EXTRA_DIALOG_COMPLETION_GESTURE_KEY: string; public static RESULT_ARGS_DIALOG_COMPLETE_KEY: string; public static RESULT_ARGS_DIALOG_COMPLETION_GESTURE_KEY: string; public static MESSAGE_GET_ACCESS_TOKEN_REQUEST: number; public static MESSAGE_GET_ACCESS_TOKEN_REPLY: number; public static MESSAGE_GET_PROTOCOL_VERSIONS_REQUEST: number; public static MESSAGE_GET_PROTOCOL_VERSIONS_REPLY: number; public static MESSAGE_GET_INSTALL_DATA_REQUEST: number; public static MESSAGE_GET_INSTALL_DATA_REPLY: number; public static MESSAGE_GET_LIKE_STATUS_REQUEST: number; public static MESSAGE_GET_LIKE_STATUS_REPLY: number; public static MESSAGE_GET_AK_SEAMLESS_TOKEN_REQUEST: number; public static MESSAGE_GET_AK_SEAMLESS_TOKEN_REPLY: number; public static MESSAGE_GET_LOGIN_STATUS_REQUEST: number; public static MESSAGE_GET_LOGIN_STATUS_REPLY: number; public static EXTRA_PROTOCOL_VERSIONS: string; public static ACTION_FEED_DIALOG: string; public static ACTION_MESSAGE_DIALOG: string; public static ACTION_OGACTIONPUBLISH_DIALOG: string; public static ACTION_OGMESSAGEPUBLISH_DIALOG: string; public static ACTION_LIKE_DIALOG: string; public static ACTION_APPINVITE_DIALOG: string; public static ACTION_CAMERA_EFFECT: string; public static ACTION_SHARE_STORY: string; public static EXTRA_PERMISSIONS: string; public static EXTRA_APPLICATION_ID: string; public static EXTRA_APPLICATION_NAME: string; public static EXTRA_USER_ID: string; public static EXTRA_LOGGER_REF: string; public static EXTRA_TOAST_DURATION_MS: string; public static EXTRA_GRAPH_API_VERSION: string; public static EXTRA_NONCE: string; public static EXTRA_ACCESS_TOKEN: string; public static EXTRA_EXPIRES_SECONDS_SINCE_EPOCH: string; public static EXTRA_DATA_ACCESS_EXPIRATION_TIME: string; public static EXTRA_AUTHENTICATION_TOKEN: string; public static RESULT_ARGS_ACCESS_TOKEN: string; public static RESULT_ARGS_GRAPH_DOMAIN: string; public static RESULT_ARGS_SIGNED_REQUEST: string; public static RESULT_ARGS_EXPIRES_SECONDS_SINCE_EPOCH: string; public static RESULT_ARGS_PERMISSIONS: string; public static OPEN_GRAPH_CREATE_OBJECT_KEY: string; public static IMAGE_USER_GENERATED_KEY: string; public static IMAGE_URL_KEY: string; public static STATUS_ERROR_TYPE: string; public static STATUS_ERROR_DESCRIPTION: string; public static STATUS_ERROR_CODE: string; public static STATUS_ERROR_SUBCODE: string; public static STATUS_ERROR_JSON: string; public static BRIDGE_ARG_ERROR_TYPE: string; public static BRIDGE_ARG_ERROR_DESCRIPTION: string; public static BRIDGE_ARG_ERROR_CODE: string; public static BRIDGE_ARG_ERROR_SUBCODE: string; public static BRIDGE_ARG_ERROR_JSON: string; public static ERROR_UNKNOWN_ERROR: string; public static ERROR_PROTOCOL_ERROR: string; public static ERROR_USER_CANCELED: string; public static ERROR_APPLICATION_ERROR: string; public static ERROR_NETWORK_ERROR: string; public static ERROR_PERMISSION_DENIED: string; public static ERROR_SERVICE_DISABLED: string; public static WEB_DIALOG_URL: string; public static WEB_DIALOG_ACTION: string; public static WEB_DIALOG_PARAMS: string; public static WEB_DIALOG_IS_FALLBACK: string; public static AUDIENCE_ME: string; public static AUDIENCE_FRIENDS: string; public static AUDIENCE_EVERYONE: string; public static INSTANCE: com.facebook.internal.NativeProtocol; public static setupProtocolRequestIntent(param0: globalAndroid.content.Intent, param1: string, param2: string, param3: number, param4: globalAndroid.os.Bundle): void; public static validateActivityIntent(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent, param2: com.facebook.internal.NativeProtocol.NativeAppInfo): globalAndroid.content.Intent; public static createFacebookLiteIntent(param0: globalAndroid.content.Context, param1: string, param2: java.util.Collection<string>, param3: string, param4: boolean, param5: boolean, param6: com.facebook.login.DefaultAudience, param7: string, param8: string, param9: string, param10: boolean, param11: boolean, param12: boolean): globalAndroid.content.Intent; public static validateServiceIntent(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent, param2: com.facebook.internal.NativeProtocol.NativeAppInfo): globalAndroid.content.Intent; public static getLatestAvailableProtocolVersionForService(param0: number): number; public static getLatestAvailableProtocolVersionForAction(param0: string, param1: androidNative.Array<number>): com.facebook.internal.NativeProtocol.ProtocolVersionQueryResult; public static getSuccessResultsFromIntent(param0: globalAndroid.content.Intent): globalAndroid.os.Bundle; public static getErrorDataFromResultIntent(param0: globalAndroid.content.Intent): globalAndroid.os.Bundle; public static isVersionCompatibleWithBucketedIntent(param0: number): boolean; public static updateAllAvailableProtocolVersionsAsync(): void; public static createBundleForException(param0: com.facebook.FacebookException): globalAndroid.os.Bundle; public static getMethodArgumentsFromIntent(param0: globalAndroid.content.Intent): globalAndroid.os.Bundle; public static createProtocolResultIntent(param0: globalAndroid.content.Intent, param1: globalAndroid.os.Bundle, param2: com.facebook.FacebookException): globalAndroid.content.Intent; public static createProxyAuthIntents(param0: globalAndroid.content.Context, param1: string, param2: java.util.Collection<string>, param3: string, param4: boolean, param5: boolean, param6: com.facebook.login.DefaultAudience, param7: string, param8: string, param9: boolean, param10: string, param11: boolean, param12: boolean, param13: boolean, param14: string): java.util.List<globalAndroid.content.Intent>; public static computeLatestAvailableVersionFromVersionSpec(param0: java.util.TreeSet<java.lang.Integer>, param1: number, param2: androidNative.Array<number>): number; public static getCallIdFromIntent(param0: globalAndroid.content.Intent): java.util.UUID; public static getBridgeArgumentsFromIntent(param0: globalAndroid.content.Intent): globalAndroid.os.Bundle; public static createInstagramIntent(param0: globalAndroid.content.Context, param1: string, param2: java.util.Collection<string>, param3: string, param4: boolean, param5: boolean, param6: com.facebook.login.DefaultAudience, param7: string, param8: string, param9: string, param10: boolean, param11: boolean, param12: boolean): globalAndroid.content.Intent; public static createTokenRefreshIntent(param0: globalAndroid.content.Context): globalAndroid.content.Intent; public static getProtocolVersionFromIntent(param0: globalAndroid.content.Intent): number; public static getExceptionFromErrorData(param0: globalAndroid.os.Bundle): com.facebook.FacebookException; public static createPlatformServiceIntent(param0: globalAndroid.content.Context): globalAndroid.content.Intent; public static isErrorResult(param0: globalAndroid.content.Intent): boolean; public static getLatestKnownVersion(): number; public static createPlatformActivityIntent(param0: globalAndroid.content.Context, param1: string, param2: string, param3: com.facebook.internal.NativeProtocol.ProtocolVersionQueryResult, param4: globalAndroid.os.Bundle): globalAndroid.content.Intent; } export module NativeProtocol { export class EffectTestAppInfo extends com.facebook.internal.NativeProtocol.NativeAppInfo { public static class: java.lang.Class<com.facebook.internal.NativeProtocol.EffectTestAppInfo>; public getPackage(): string; public constructor(); public getLoginActivity(): string; public getLoginActivity(): java.lang.Void; } export class FBLiteAppInfo extends com.facebook.internal.NativeProtocol.NativeAppInfo { public static class: java.lang.Class<com.facebook.internal.NativeProtocol.FBLiteAppInfo>; public static FACEBOOK_LITE_ACTIVITY: string; public static Companion: com.facebook.internal.NativeProtocol.FBLiteAppInfo.Companion; public getPackage(): string; public constructor(); public getLoginActivity(): string; } export module FBLiteAppInfo { export class Companion { public static class: java.lang.Class<com.facebook.internal.NativeProtocol.FBLiteAppInfo.Companion>; } } export class InstagramAppInfo extends com.facebook.internal.NativeProtocol.NativeAppInfo { public static class: java.lang.Class<com.facebook.internal.NativeProtocol.InstagramAppInfo>; public getPackage(): string; public getResponseType(): string; public constructor(); public getLoginActivity(): string; } export class KatanaAppInfo extends com.facebook.internal.NativeProtocol.NativeAppInfo { public static class: java.lang.Class<com.facebook.internal.NativeProtocol.KatanaAppInfo>; public getPackage(): string; public constructor(); public getLoginActivity(): string; public onAvailableVersionsNullOrEmpty(): void; } export class MessengerAppInfo extends com.facebook.internal.NativeProtocol.NativeAppInfo { public static class: java.lang.Class<com.facebook.internal.NativeProtocol.MessengerAppInfo>; public getPackage(): string; public constructor(); public getLoginActivity(): string; public getLoginActivity(): java.lang.Void; } export abstract class NativeAppInfo { public static class: java.lang.Class<com.facebook.internal.NativeProtocol.NativeAppInfo>; public getPackage(): string; public getResponseType(): string; public constructor(); public fetchAvailableVersions(param0: boolean): void; public getLoginActivity(): string; public onAvailableVersionsNullOrEmpty(): void; public getAvailableVersions(): java.util.TreeSet<java.lang.Integer>; } export class ProtocolVersionQueryResult { public static class: java.lang.Class<com.facebook.internal.NativeProtocol.ProtocolVersionQueryResult>; public static Companion: com.facebook.internal.NativeProtocol.ProtocolVersionQueryResult.Companion; public static createEmpty(): com.facebook.internal.NativeProtocol.ProtocolVersionQueryResult; public getProtocolVersion(): number; public getAppInfo(): com.facebook.internal.NativeProtocol.NativeAppInfo; public static create(param0: com.facebook.internal.NativeProtocol.NativeAppInfo, param1: number): com.facebook.internal.NativeProtocol.ProtocolVersionQueryResult; } export module ProtocolVersionQueryResult { export class Companion { public static class: java.lang.Class<com.facebook.internal.NativeProtocol.ProtocolVersionQueryResult.Companion>; public create(param0: com.facebook.internal.NativeProtocol.NativeAppInfo, param1: number): com.facebook.internal.NativeProtocol.ProtocolVersionQueryResult; public createEmpty(): com.facebook.internal.NativeProtocol.ProtocolVersionQueryResult; } } export class WakizashiAppInfo extends com.facebook.internal.NativeProtocol.NativeAppInfo { public static class: java.lang.Class<com.facebook.internal.NativeProtocol.WakizashiAppInfo>; public getPackage(): string; public constructor(); public getLoginActivity(): string; } } } } } declare module com { export module facebook { export module internal { export abstract class PlatformServiceClient { public static class: java.lang.Class<com.facebook.internal.PlatformServiceClient>; public onServiceDisconnected(param0: globalAndroid.content.ComponentName): void; public onServiceConnected(param0: globalAndroid.content.ComponentName, param1: globalAndroid.os.IBinder): void; public setCompletedListener(param0: com.facebook.internal.PlatformServiceClient.CompletedListener): void; public handleMessage(param0: globalAndroid.os.Message): void; public constructor(param0: globalAndroid.content.Context, param1: number, param2: number, param3: number, param4: string, param5: string); public getContext(): globalAndroid.content.Context; public start(): boolean; public cancel(): void; public getNonce(): string; public populateRequestBundle(param0: globalAndroid.os.Bundle): void; } export module PlatformServiceClient { export class CompletedListener { public static class: java.lang.Class<com.facebook.internal.PlatformServiceClient.CompletedListener>; /** * Constructs a new instance of the com.facebook.internal.PlatformServiceClient$CompletedListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { completed(param0: globalAndroid.os.Bundle): void; }); public constructor(); public completed(param0: globalAndroid.os.Bundle): void; } } } } } declare module com { export module facebook { export module internal { export class ProfileInformationCache { public static class: java.lang.Class<com.facebook.internal.ProfileInformationCache>; public static INSTANCE: com.facebook.internal.ProfileInformationCache; public static getProfileInformation(param0: string): org.json.JSONObject; public static putProfileInformation(param0: string, param1: org.json.JSONObject): void; } } } } declare module com { export module facebook { export module internal { export class ServerProtocol { public static class: java.lang.Class<com.facebook.internal.ServerProtocol>; public static DIALOG_PATH: string; public static DIALOG_PARAM_ACCESS_TOKEN: string; public static DIALOG_PARAM_APP_ID: string; public static DIALOG_PARAM_AUTH_TYPE: string; public static DIALOG_PARAM_CBT: string; public static DIALOG_PARAM_CLIENT_ID: string; public static DIALOG_PARAM_CUSTOM_TABS_PREFETCHING: string; public static DIALOG_PARAM_DISPLAY: string; public static DIALOG_PARAM_DISPLAY_TOUCH: string; public static DIALOG_PARAM_E2E: string; public static DIALOG_PARAM_IES: string; public static DIALOG_PARAM_LEGACY_OVERRIDE: string; public static DIALOG_PARAM_LOGIN_BEHAVIOR: string; public static DIALOG_PARAM_NONCE: string; public static DIALOG_PARAM_REDIRECT_URI: string; public static DIALOG_PARAM_RESPONSE_TYPE: string; public static DIALOG_PARAM_RETURN_SCOPES: string; public static DIALOG_PARAM_SCOPE: string; public static DIALOG_PARAM_SSO_DEVICE: string; public static DIALOG_PARAM_DEFAULT_AUDIENCE: string; public static DIALOG_PARAM_SDK_VERSION: string; public static DIALOG_PARAM_STATE: string; public static DIALOG_PARAM_FAIL_ON_LOGGED_OUT: string; public static DIALOG_PARAM_CCT_OVER_LOGGED_OUT_APP_SWITCH: string; public static DIALOG_PARAM_MESSENGER_PAGE_ID: string; public static DIALOG_PARAM_RESET_MESSENGER_STATE: string; public static DIALOG_REREQUEST_AUTH_TYPE: string; public static DIALOG_PARAM_FX_APP: string; public static DIALOG_PARAM_SKIP_DEDUPE: string; public static DIALOG_RESPONSE_TYPE_TOKEN_AND_SCOPES: string; public static DIALOG_RESPONSE_TYPE_TOKEN_AND_SIGNED_REQUEST: string; public static DIALOG_RESPONSE_TYPE_ID_TOKEN_AND_SIGNED_REQUEST: string; public static DIALOG_RETURN_SCOPES_TRUE: string; public static DIALOG_REDIRECT_URI: string; public static DIALOG_REDIRECT_CHROME_OS_URI: string; public static DIALOG_CANCEL_URI: string; public static FALLBACK_DIALOG_PARAM_APP_ID: string; public static FALLBACK_DIALOG_PARAM_BRIDGE_ARGS: string; public static FALLBACK_DIALOG_PARAM_KEY_HASH: string; public static FALLBACK_DIALOG_PARAM_METHOD_ARGS: string; public static FALLBACK_DIALOG_PARAM_METHOD_RESULTS: string; public static FALLBACK_DIALOG_PARAM_VERSION: string; public static FALLBACK_DIALOG_DISPLAY_VALUE_TOUCH: string; public static INSTAGRAM_OAUTH_PATH: string; public static INSTANCE: com.facebook.internal.ServerProtocol; public static getGraphUrlBase(): string; public static getInstagramDialogAuthority(): string; public static getGraphVideoUrlBase(): string; public static getErrorsProxyAuthDisabled(): java.util.Collection<string>; public static getErrorsUserCanceled(): java.util.Collection<string>; public static getDefaultAPIVersion(): string; public static getDialogAuthority(): string; public static getFacebookGraphUrlBase(): string; public static getQueryParamsForPlatformActivityIntentWebFallback(param0: string, param1: number, param2: globalAndroid.os.Bundle): globalAndroid.os.Bundle; public static getErrorConnectionFailure(): string; public static getGraphUrlBaseForSubdomain(param0: string): string; } } } } declare module com { export module facebook { export module internal { export class SmartLoginOption { public static class: java.lang.Class<com.facebook.internal.SmartLoginOption>; public static None: com.facebook.internal.SmartLoginOption; public static Enabled: com.facebook.internal.SmartLoginOption; public static RequireConfirm: com.facebook.internal.SmartLoginOption; public static Companion: com.facebook.internal.SmartLoginOption.Companion; public static values(): androidNative.Array<com.facebook.internal.SmartLoginOption>; public static parseOptions(param0: number): java.util.EnumSet<com.facebook.internal.SmartLoginOption>; public getValue(): number; public static valueOf(param0: string): com.facebook.internal.SmartLoginOption; } export module SmartLoginOption { export class Companion { public static class: java.lang.Class<com.facebook.internal.SmartLoginOption.Companion>; public parseOptions(param0: number): java.util.EnumSet<com.facebook.internal.SmartLoginOption>; } } } } } declare module com { export module facebook { export module internal { export class UrlRedirectCache { public static class: java.lang.Class<com.facebook.internal.UrlRedirectCache>; public static INSTANCE: com.facebook.internal.UrlRedirectCache; public static getCache(): com.facebook.internal.FileLruCache; public static getRedirectedUri(param0: globalAndroid.net.Uri): globalAndroid.net.Uri; public static clearCache(): void; public static cacheUriRedirect(param0: globalAndroid.net.Uri, param1: globalAndroid.net.Uri): void; } } } } declare module com { export module facebook { export module internal { export class Utility { public static class: java.lang.Class<com.facebook.internal.Utility>; public static LOG_TAG: string; public static DEFAULT_STREAM_BUFFER_SIZE: number; public static INSTANCE: com.facebook.internal.Utility; public static getActivityName(param0: globalAndroid.content.Context): string; public static isDataProcessingRestricted(): boolean; public static logd(param0: string, param1: string): void; public static isWebUri(param0: globalAndroid.net.Uri): boolean; public static isCurrentAccessToken(param0: com.facebook.AccessToken): boolean; public static tryGetJSONObjectFromResponse(param0: org.json.JSONObject, param1: string): org.json.JSONObject; public static jsonArrayToStringList(param0: org.json.JSONArray): java.util.List<string>; public static logd(param0: string, param1: string, param2: java.lang.Throwable): void; public static mapToJsonStr(param0: java.util.Map<string,string>): string; public static arrayList(param0: androidNative.Array<any>): java.util.ArrayList; public static getResourceLocale(): java.util.Locale; public static setAppEventExtendedDeviceInfoParameters(param0: org.json.JSONObject, param1: globalAndroid.content.Context): void; public static filter(param0: java.util.List, param1: com.facebook.internal.Utility.Predicate<any>): java.util.List; public static writeStringMapToParcel(param0: globalAndroid.os.Parcel, param1: java.util.Map<string,string>): void; public static getBundleLongAsDate(param0: globalAndroid.os.Bundle, param1: string, param2: java.util.Date): java.util.Date; public static putJSONValueInBundle(param0: globalAndroid.os.Bundle, param1: string, param2: any): boolean; public static putCommaSeparatedStringList(param0: globalAndroid.os.Bundle, param1: string, param2: java.util.List<string>): void; public static unmodifiableCollection(param0: androidNative.Array<any>): java.util.Collection; public static isSubset(param0: java.util.Collection, param1: java.util.Collection): boolean; public static safeGetStringFromResponse(param0: org.json.JSONObject, param1: string): string; public static isAutofillAvailable(param0: globalAndroid.content.Context): boolean; public static closeQuietly(param0: java.io.Closeable): void; public static hashSet(param0: androidNative.Array<any>): java.util.HashSet; public static getContentSize(param0: globalAndroid.net.Uri): number; public static runOnNonUiThread(param0: java.lang.Runnable): void; public static coerceValueIfNullOrEmpty(param0: string, param1: string): string; public static isFileUri(param0: globalAndroid.net.Uri): boolean; public static clearCaches(): void; public static md5hash(param0: string): string; public static getMethodQuietly(param0: java.lang.Class<any>, param1: string, param2: androidNative.Array<java.lang.Class<any>>): java.lang.reflect.Method; public static deleteDirectory(param0: java.io.File): void; public static handlePermissionResponse(param0: org.json.JSONObject): com.facebook.internal.Utility.PermissionsLists; public static getStringPropertyAsJSON(param0: org.json.JSONObject, param1: string, param2: string): any; public static sha256hash(param0: string): string; public static readStreamToString(param0: java.io.InputStream): string; public static copyAndCloseInputStream(param0: java.io.InputStream, param1: java.io.OutputStream): number; public static isAutoAppLinkSetup(): boolean; public static convertJSONObjectToHashMap(param0: org.json.JSONObject): java.util.Map<string,any>; public static isNullOrEmpty(param0: java.util.Collection): boolean; public static clearFacebookCookies(param0: globalAndroid.content.Context): void; public static tryGetJSONArrayFromResponse(param0: org.json.JSONObject, param1: string): org.json.JSONArray; public static getCurrentLocale(): java.util.Locale; public static mustFixWindowParamsForAutofill(param0: globalAndroid.content.Context): boolean; public static parseUrlQueryString(param0: string): globalAndroid.os.Bundle; public static setAppEventAttributionParameters(param0: org.json.JSONObject, param1: com.facebook.internal.AttributionIdentifiers, param2: string, param3: boolean): void; public static getAppName(param0: globalAndroid.content.Context): string; public static logd(param0: string, param1: java.lang.Exception): void; public static sha1hash(param0: string): string; public static map(param0: java.util.List, param1: com.facebook.internal.Utility.Mapper<any,any>): java.util.List; public static sha256hash(param0: androidNative.Array<number>): string; public static jsonStrToMap(param0: string): java.util.Map<string,string>; public static isContentUri(param0: globalAndroid.net.Uri): boolean; public static hasSameId(param0: org.json.JSONObject, param1: org.json.JSONObject): boolean; public static intersectRanges(param0: androidNative.Array<number>, param1: androidNative.Array<number>): androidNative.Array<number>; public static asListNoNulls(param0: androidNative.Array<any>): java.util.List; public static sha1hash(param0: androidNative.Array<number>): string; public static readStringMapFromParcel(param0: globalAndroid.os.Parcel): java.util.Map<string,string>; public static areObjectsEqual(param0: any, param1: any): boolean; public static isChromeOS(param0: globalAndroid.content.Context): boolean; public static putUri(param0: globalAndroid.os.Bundle, param1: string, param2: globalAndroid.net.Uri): void; public static invokeMethodQuietly(param0: any, param1: java.lang.reflect.Method, param2: androidNative.Array<any>): any; public static awaitGetGraphMeRequestWithCache(param0: string): org.json.JSONObject; public static getMetadataApplicationId(param0: globalAndroid.content.Context): string; public static getGraphMeRequestWithCacheAsync(param0: string, param1: com.facebook.internal.Utility.GraphMeRequestWithCacheCallback): void; public static getUriString(param0: globalAndroid.net.Uri): string; public static convertJSONArrayToList(param0: org.json.JSONArray): java.util.List<string>; public static getDataProcessingOptions(): org.json.JSONObject; public static getAppVersion(): string; public static disconnectQuietly(param0: java.net.URLConnection): void; public static getMethodQuietly(param0: string, param1: string, param2: androidNative.Array<java.lang.Class<any>>): java.lang.reflect.Method; public static getGraphDomainFromTokenDomain(param0: string): string; public static stringsEqualOrEmpty(param0: string, param1: string): boolean; public static generateRandomString(param0: number): string; public static buildUri(param0: string, param1: string, param2: globalAndroid.os.Bundle): globalAndroid.net.Uri; public static jsonArrayToSet(param0: org.json.JSONArray): java.util.Set<string>; public static isNullOrEmpty(param0: string): boolean; public static putNonEmptyString(param0: globalAndroid.os.Bundle, param1: string, param2: string): void; public static convertJSONObjectToStringMap(param0: org.json.JSONObject): java.util.Map<string,string>; } export module Utility { export class GraphMeRequestWithCacheCallback { public static class: java.lang.Class<com.facebook.internal.Utility.GraphMeRequestWithCacheCallback>; /** * Constructs a new instance of the com.facebook.internal.Utility$GraphMeRequestWithCacheCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onSuccess(param0: org.json.JSONObject): void; onFailure(param0: com.facebook.FacebookException): void; }); public constructor(); public onFailure(param0: com.facebook.FacebookException): void; public onSuccess(param0: org.json.JSONObject): void; } export class Mapper<T, K> extends java.lang.Object { public static class: java.lang.Class<com.facebook.internal.Utility.Mapper<any,any>>; /** * Constructs a new instance of the com.facebook.internal.Utility$Mapper interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { apply(param0: T): K; }); public constructor(); public apply(param0: T): K; } export class PermissionsLists { public static class: java.lang.Class<com.facebook.internal.Utility.PermissionsLists>; public getDeclinedPermissions(): java.util.List<string>; public constructor(param0: java.util.List<string>, param1: java.util.List<string>, param2: java.util.List<string>); public getGrantedPermissions(): java.util.List<string>; public setExpiredPermissions(param0: java.util.List<string>): void; public setDeclinedPermissions(param0: java.util.List<string>): void; public getExpiredPermissions(): java.util.List<string>; public setGrantedPermissions(param0: java.util.List<string>): void; } export class Predicate<T> extends java.lang.Object { public static class: java.lang.Class<com.facebook.internal.Utility.Predicate<any>>; /** * Constructs a new instance of the com.facebook.internal.Utility$Predicate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { apply(param0: T): boolean; }); public constructor(); public apply(param0: T): boolean; } } } } } declare module com { export module facebook { export module internal { export class Validate { public static class: java.lang.Class<com.facebook.internal.Validate>; public static CUSTOM_TAB_REDIRECT_URI_PREFIX: string; public static INSTANCE: com.facebook.internal.Validate; public static hasPermission(param0: globalAndroid.content.Context, param1: string): boolean; public static hasContentProvider(param0: globalAndroid.content.Context): void; public static containsNoNullOrEmpty(param0: java.util.Collection<string>, param1: string): void; public static notEmpty(param0: java.util.Collection, param1: string): void; public static oneOf(param0: any, param1: string, param2: androidNative.Array<any>): void; public static hasFacebookActivity(param0: globalAndroid.content.Context, param1: boolean): void; public static hasInternetPermissions(param0: globalAndroid.content.Context): void; public static hasCustomTabRedirectActivity(param0: globalAndroid.content.Context, param1: string): boolean; public static containsNoNulls(param0: java.util.Collection, param1: string): void; public static hasWiFiPermission(param0: globalAndroid.content.Context): boolean; public static hasChangeWifiStatePermission(param0: globalAndroid.content.Context): boolean; public static runningOnUiThread(): void; public static hasFacebookActivity(param0: globalAndroid.content.Context): void; public static hasAppID(): string; public static hasInternetPermissions(param0: globalAndroid.content.Context, param1: boolean): void; public static notNullOrEmpty(param0: string, param1: string): void; public static notEmpty(param0: string, param1: string): void; public static hasBluetoothPermission(param0: globalAndroid.content.Context): boolean; public static hasClientToken(): string; public static notEmptyAndContainsNoNulls(param0: java.util.Collection, param1: string): void; public static sdkInitialized(): void; public static hasLocationPermission(param0: globalAndroid.content.Context): boolean; public static notNull(param0: any, param1: string): void; } } } } declare module com { export module facebook { export module internal { export class WebDialog { public static class: java.lang.Class<com.facebook.internal.WebDialog>; public isListenerCalled(): boolean; public isPageFinished(): boolean; public constructor(param0: globalAndroid.content.Context, param1: string); public static getWebDialogTheme(): number; public static newInstance(param0: globalAndroid.content.Context, param1: string, param2: globalAndroid.os.Bundle, param3: number, param4: com.facebook.login.LoginTargetApp, param5: com.facebook.internal.WebDialog.OnCompleteListener): com.facebook.internal.WebDialog; public onKeyDown(param0: number, param1: globalAndroid.view.KeyEvent): boolean; public sendSuccessToListener(param0: globalAndroid.os.Bundle): void; public static newInstance(param0: globalAndroid.content.Context, param1: string, param2: globalAndroid.os.Bundle, param3: number, param4: com.facebook.internal.WebDialog.OnCompleteListener): com.facebook.internal.WebDialog; public dismiss(): void; public sendErrorToListener(param0: java.lang.Throwable): void; public cancel(): void; public onStop(): void; public getWebView(): globalAndroid.webkit.WebView; public static setInitCallback(param0: com.facebook.internal.WebDialog.InitCallback): void; public getOnCompleteListener(): com.facebook.internal.WebDialog.OnCompleteListener; public static initDefaultTheme(param0: globalAndroid.content.Context): void; public parseResponseUri(param0: string): globalAndroid.os.Bundle; public onWindowAttributesChanged(param0: globalAndroid.view.WindowManager.LayoutParams): void; public setExpectedRedirectUrl(param0: string): void; public setOnCompleteListener(param0: com.facebook.internal.WebDialog.OnCompleteListener): void; public onCreate(param0: globalAndroid.os.Bundle): void; public onStart(): void; public static setWebDialogTheme(param0: number): void; public resize(): void; public onDetachedFromWindow(): void; public onAttachedToWindow(): void; } export module WebDialog { export class Builder { public static class: java.lang.Class<com.facebook.internal.WebDialog.Builder>; public constructor(param0: globalAndroid.content.Context, param1: string, param2: globalAndroid.os.Bundle); public getTheme(): number; public getListener(): com.facebook.internal.WebDialog.OnCompleteListener; public getParameters(): globalAndroid.os.Bundle; public constructor(param0: globalAndroid.content.Context, param1: string, param2: string, param3: globalAndroid.os.Bundle); public getApplicationId(): string; public getContext(): globalAndroid.content.Context; public setTheme(param0: number): com.facebook.internal.WebDialog.Builder; public setOnCompleteListener(param0: com.facebook.internal.WebDialog.OnCompleteListener): com.facebook.internal.WebDialog.Builder; public build(): com.facebook.internal.WebDialog; } export class DialogWebViewClient { public static class: java.lang.Class<com.facebook.internal.WebDialog.DialogWebViewClient>; public onPageFinished(param0: globalAndroid.webkit.WebView, param1: string): void; public onReceivedSslError(param0: globalAndroid.webkit.WebView, param1: globalAndroid.webkit.SslErrorHandler, param2: globalAndroid.net.http.SslError): void; public shouldOverrideUrlLoading(param0: globalAndroid.webkit.WebView, param1: string): boolean; public onReceivedError(param0: globalAndroid.webkit.WebView, param1: number, param2: string, param3: string): void; public onPageStarted(param0: globalAndroid.webkit.WebView, param1: string, param2: globalAndroid.graphics.Bitmap): void; } export class InitCallback { public static class: java.lang.Class<com.facebook.internal.WebDialog.InitCallback>; /** * Constructs a new instance of the com.facebook.internal.WebDialog$InitCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onInit(param0: globalAndroid.webkit.WebView): void; }); public constructor(); public onInit(param0: globalAndroid.webkit.WebView): void; } export class OnCompleteListener { public static class: java.lang.Class<com.facebook.internal.WebDialog.OnCompleteListener>; /** * Constructs a new instance of the com.facebook.internal.WebDialog$OnCompleteListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onComplete(param0: globalAndroid.os.Bundle, param1: com.facebook.FacebookException): void; }); public constructor(); public onComplete(param0: globalAndroid.os.Bundle, param1: com.facebook.FacebookException): void; } export class UploadStagingResourcesTask extends globalAndroid.os.AsyncTask<java.lang.Void,java.lang.Void,androidNative.Array<string>> { public static class: java.lang.Class<com.facebook.internal.WebDialog.UploadStagingResourcesTask>; public doInBackground(param0: androidNative.Array<java.lang.Void>): androidNative.Array<string>; public onPostExecute(param0: androidNative.Array<string>): void; } } } } } declare module com { export module facebook { export module internal { export class WorkQueue { public static class: java.lang.Class<com.facebook.internal.WorkQueue>; public static DEFAULT_MAX_CONCURRENT: number; public static Companion: com.facebook.internal.WorkQueue.Companion; public addActiveWorkItem(param0: java.lang.Runnable): com.facebook.internal.WorkQueue.WorkItem; public constructor(param0: number); public validate(): void; public addActiveWorkItem(param0: java.lang.Runnable, param1: boolean): com.facebook.internal.WorkQueue.WorkItem; public constructor(param0: number, param1: java.util.concurrent.Executor); public constructor(); } export module WorkQueue { export class Companion { public static class: java.lang.Class<com.facebook.internal.WorkQueue.Companion>; } export class WorkItem { public static class: java.lang.Class<com.facebook.internal.WorkQueue.WorkItem>; /** * Constructs a new instance of the com.facebook.internal.WorkQueue$WorkItem interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { cancel(): boolean; isRunning(): boolean; moveToFront(): void; }); public constructor(); public cancel(): boolean; public isRunning(): boolean; public moveToFront(): void; } export class WorkNode extends com.facebook.internal.WorkQueue.WorkItem { public static class: java.lang.Class<com.facebook.internal.WorkQueue.WorkNode>; public getNext(): com.facebook.internal.WorkQueue.WorkNode; public cancel(): boolean; public addToList(param0: com.facebook.internal.WorkQueue.WorkNode, param1: boolean): com.facebook.internal.WorkQueue.WorkNode; public constructor(param0: java.lang.Runnable); public getCallback(): java.lang.Runnable; public isRunning(): boolean; public removeFromList(param0: com.facebook.internal.WorkQueue.WorkNode): com.facebook.internal.WorkQueue.WorkNode; public verify(param0: boolean): void; public setRunning(param0: boolean): void; public moveToFront(): void; } } } } } declare module com { export module facebook { export module internal { export module gatekeeper { export class GateKeeper { public static class: java.lang.Class<com.facebook.internal.gatekeeper.GateKeeper>; public equals(param0: any): boolean; public toString(): string; public component1(): string; public getName(): string; public getValue(): boolean; public copy(param0: string, param1: boolean): com.facebook.internal.gatekeeper.GateKeeper; public constructor(param0: string, param1: boolean); public hashCode(): number; public component2(): boolean; } } } } } declare module com { export module facebook { export module internal { export module gatekeeper { export class GateKeeperRuntimeCache { public static class: java.lang.Class<com.facebook.internal.gatekeeper.GateKeeperRuntimeCache>; public setGateKeepers(param0: string, param1: java.util.List<com.facebook.internal.gatekeeper.GateKeeper>): void; public resetCache(param0: string): void; public dumpGateKeepers(param0: string): java.util.List<com.facebook.internal.gatekeeper.GateKeeper>; public constructor(); public setGateKeeper(param0: string, param1: com.facebook.internal.gatekeeper.GateKeeper): void; public getGateKeeperValue(param0: string, param1: string, param2: boolean): boolean; public getGateKeeper(param0: string, param1: string): com.facebook.internal.gatekeeper.GateKeeper; public setGateKeeperValue(param0: string, param1: string, param2: boolean): void; } } } } } declare module com { export module facebook { export module internal { export module gatekeeper { export class GateKeeperRuntimeCacheKt { public static class: java.lang.Class<com.facebook.internal.gatekeeper.GateKeeperRuntimeCacheKt>; } } } } } declare module com { export module facebook { export module internal { export module instrument { export class ExceptionAnalyzer { public static class: java.lang.Class<com.facebook.internal.instrument.ExceptionAnalyzer>; public static INSTANCE: com.facebook.internal.instrument.ExceptionAnalyzer; public static execute(param0: java.lang.Throwable): void; public static isDebug$facebook_core_release(): boolean; public sendExceptionAnalysisReports$facebook_core_release(): void; public static enable(): void; } } } } } declare module com { export module facebook { export module internal { export module instrument { export class InstrumentData { public static class: java.lang.Class<com.facebook.internal.instrument.InstrumentData>; public static Companion: com.facebook.internal.instrument.InstrumentData.Companion; public toString(): string; public save(): void; public compareTo(param0: com.facebook.internal.instrument.InstrumentData): number; public isValid(): boolean; public clear(): void; } export module InstrumentData { export class Builder { public static class: java.lang.Class<com.facebook.internal.instrument.InstrumentData.Builder>; public static INSTANCE: com.facebook.internal.instrument.InstrumentData.Builder; public static load(param0: java.io.File): com.facebook.internal.instrument.InstrumentData; public static build(param0: java.lang.Throwable, param1: com.facebook.internal.instrument.InstrumentData.Type): com.facebook.internal.instrument.InstrumentData; public static build(param0: string, param1: string): com.facebook.internal.instrument.InstrumentData; public static build(param0: org.json.JSONArray): com.facebook.internal.instrument.InstrumentData; } export class Companion { public static class: java.lang.Class<com.facebook.internal.instrument.InstrumentData.Companion>; } export class Type { public static class: java.lang.Class<com.facebook.internal.instrument.InstrumentData.Type>; public static Unknown: com.facebook.internal.instrument.InstrumentData.Type; public static Analysis: com.facebook.internal.instrument.InstrumentData.Type; public static AnrReport: com.facebook.internal.instrument.InstrumentData.Type; public static CrashReport: com.facebook.internal.instrument.InstrumentData.Type; public static CrashShield: com.facebook.internal.instrument.InstrumentData.Type; public static ThreadCheck: com.facebook.internal.instrument.InstrumentData.Type; public static valueOf(param0: string): com.facebook.internal.instrument.InstrumentData.Type; public static values(): androidNative.Array<com.facebook.internal.instrument.InstrumentData.Type>; public toString(): string; public getLogPrefix(): string; } export module Type { export class WhenMappings { public static class: java.lang.Class<com.facebook.internal.instrument.InstrumentData.Type.WhenMappings>; } } export class WhenMappings { public static class: java.lang.Class<com.facebook.internal.instrument.InstrumentData.WhenMappings>; } } } } } } declare module com { export module facebook { export module internal { export module instrument { export class InstrumentManager { public static class: java.lang.Class<com.facebook.internal.instrument.InstrumentManager>; public static INSTANCE: com.facebook.internal.instrument.InstrumentManager; public static start(): void; } } } } } declare module com { export module facebook { export module internal { export module instrument { export class InstrumentUtility { public static class: java.lang.Class<com.facebook.internal.instrument.InstrumentUtility>; public static ANALYSIS_REPORT_PREFIX: string; public static ANR_REPORT_PREFIX: string; public static CRASH_REPORT_PREFIX: string; public static CRASH_SHIELD_PREFIX: string; public static THREAD_CHECK_PREFIX: string; public static ERROR_REPORT_PREFIX: string; public static INSTANCE: com.facebook.internal.instrument.InstrumentUtility; public static writeFile(param0: string, param1: string): void; public static sendReports(param0: string, param1: org.json.JSONArray, param2: com.facebook.GraphRequest.Callback): void; public static getInstrumentReportDir(): java.io.File; public static getStackTrace(param0: java.lang.Thread): string; public static isSDKRelatedThread(param0: java.lang.Thread): boolean; public static listExceptionReportFiles(): androidNative.Array<java.io.File>; public static deleteFile(param0: string): boolean; public static getStackTrace(param0: java.lang.Throwable): string; public static readFile(param0: string, param1: boolean): org.json.JSONObject; public static listExceptionAnalysisReportFiles(): androidNative.Array<java.io.File>; public static listAnrReportFiles(): androidNative.Array<java.io.File>; public static getCause(param0: java.lang.Throwable): string; public static isSDKRelatedException(param0: java.lang.Throwable): boolean; } } } } } declare module com { export module facebook { export module internal { export module instrument { export module anrreport { export class ANRDetector { public static class: java.lang.Class<com.facebook.internal.instrument.anrreport.ANRDetector>; public static INSTANCE: com.facebook.internal.instrument.anrreport.ANRDetector; public static checkProcessError(param0: globalAndroid.app.ActivityManager): void; public static start(): void; } } } } } } declare module com { export module facebook { export module internal { export module instrument { export module anrreport { export class ANRHandler { public static class: java.lang.Class<com.facebook.internal.instrument.anrreport.ANRHandler>; public static INSTANCE: com.facebook.internal.instrument.anrreport.ANRHandler; public static enable(): void; public static sendANRReports(): void; } } } } } } declare module com { export module facebook { export module internal { export module instrument { export module crashreport { export class CrashHandler { public static class: java.lang.Class<com.facebook.internal.instrument.crashreport.CrashHandler>; public static Companion: com.facebook.internal.instrument.crashreport.CrashHandler.Companion; public static enable(): void; public uncaughtException(param0: java.lang.Thread, param1: java.lang.Throwable): void; } export module CrashHandler { export class Companion { public static class: java.lang.Class<com.facebook.internal.instrument.crashreport.CrashHandler.Companion>; public enable(): void; } } } } } } } declare module com { export module facebook { export module internal { export module instrument { export module crashshield { export class AutoHandleExceptions { public static class: java.lang.Class<com.facebook.internal.instrument.crashshield.AutoHandleExceptions>; /** * Constructs a new instance of the com.facebook.internal.instrument.crashshield.AutoHandleExceptions interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } declare module com { export module facebook { export module internal { export module instrument { export module crashshield { export class CrashShieldHandler { public static class: java.lang.Class<com.facebook.internal.instrument.crashshield.CrashShieldHandler>; public static INSTANCE: com.facebook.internal.instrument.crashshield.CrashShieldHandler; public static scheduleCrashInDebug(param0: java.lang.Throwable): void; public static enable(): void; public static methodFinished(param0: any): void; public static isObjectCrashing(param0: any): boolean; public static isDebug(): boolean; public static resetCrashingObjects(): void; public static reset(): void; public static disable(): void; public static handleThrowable(param0: java.lang.Throwable, param1: any): void; } } } } } } declare module com { export module facebook { export module internal { export module instrument { export module crashshield { export class NoAutoExceptionHandling { public static class: java.lang.Class<com.facebook.internal.instrument.crashshield.NoAutoExceptionHandling>; /** * Constructs a new instance of the com.facebook.internal.instrument.crashshield.NoAutoExceptionHandling interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } declare module com { export module facebook { export module internal { export module instrument { export module errorreport { export class ErrorReportData { public static class: java.lang.Class<com.facebook.internal.instrument.errorreport.ErrorReportData>; public static Companion: com.facebook.internal.instrument.errorreport.ErrorReportData.Companion; public constructor(param0: java.io.File); public compareTo(param0: com.facebook.internal.instrument.errorreport.ErrorReportData): number; public getParameters(): org.json.JSONObject; public save(): void; public clear(): void; public toString(): string; public isValid(): boolean; public constructor(param0: string); } export module ErrorReportData { export class Companion { public static class: java.lang.Class<com.facebook.internal.instrument.errorreport.ErrorReportData.Companion>; } } } } } } } declare module com { export module facebook { export module internal { export module instrument { export module errorreport { export class ErrorReportHandler { public static class: java.lang.Class<com.facebook.internal.instrument.errorreport.ErrorReportHandler>; public static INSTANCE: com.facebook.internal.instrument.errorreport.ErrorReportHandler; public static save(param0: string): void; public static enable(): void; public static listErrorReportFiles(): androidNative.Array<java.io.File>; public static sendErrorReports(): void; } } } } } } declare module com { export module facebook { export module internal { export module instrument { export module threadcheck { export class ThreadCheckHandler { public static class: java.lang.Class<com.facebook.internal.instrument.threadcheck.ThreadCheckHandler>; public static INSTANCE: com.facebook.internal.instrument.threadcheck.ThreadCheckHandler; public static enable(): void; public static workerThreadViolationDetected(param0: java.lang.Class<any>, param1: string, param2: string): void; public static uiThreadViolationDetected(param0: java.lang.Class<any>, param1: string, param2: string): void; } } } } } } declare module com { export module facebook { export module internal { export module logging { export module dumpsys { export class AndroidRootResolver { public static class: java.lang.Class<com.facebook.internal.logging.dumpsys.AndroidRootResolver>; public static Companion: com.facebook.internal.logging.dumpsys.AndroidRootResolver.Companion; public constructor(); public attachActiveRootListener(param0: com.facebook.internal.logging.dumpsys.AndroidRootResolver.Listener): void; public listActiveRoots(): java.util.List<com.facebook.internal.logging.dumpsys.AndroidRootResolver.Root>; } export module AndroidRootResolver { export class Companion { public static class: java.lang.Class<com.facebook.internal.logging.dumpsys.AndroidRootResolver.Companion>; } export class ListenableArrayList extends java.util.ArrayList<globalAndroid.view.View> { public static class: java.lang.Class<com.facebook.internal.logging.dumpsys.AndroidRootResolver.ListenableArrayList>; public remove(param0: number): globalAndroid.view.View; public constructor(); public contains(param0: any): boolean; public size(): number; public removeAt(param0: number): globalAndroid.view.View; public lastIndexOf(param0: any): number; public remove(param0: any): boolean; public remove(param0: globalAndroid.view.View): boolean; public indexOf(param0: any): number; public lastIndexOf(param0: globalAndroid.view.View): number; public setListener(param0: com.facebook.internal.logging.dumpsys.AndroidRootResolver.Listener): void; public getSize(): number; public indexOf(param0: globalAndroid.view.View): number; public contains(param0: globalAndroid.view.View): boolean; public add(param0: globalAndroid.view.View): boolean; } export class Listener { public static class: java.lang.Class<com.facebook.internal.logging.dumpsys.AndroidRootResolver.Listener>; /** * Constructs a new instance of the com.facebook.internal.logging.dumpsys.AndroidRootResolver$Listener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onRootAdded(param0: globalAndroid.view.View): void; onRootRemoved(param0: globalAndroid.view.View): void; onRootsChanged(param0: java.util.List<any>): void; }); public constructor(); public onRootRemoved(param0: globalAndroid.view.View): void; public onRootsChanged(param0: java.util.List<any>): void; public onRootAdded(param0: globalAndroid.view.View): void; } export class Root { public static class: java.lang.Class<com.facebook.internal.logging.dumpsys.AndroidRootResolver.Root>; public getParam(): globalAndroid.view.WindowManager.LayoutParams; public getView(): globalAndroid.view.View; public constructor(param0: globalAndroid.view.View, param1: globalAndroid.view.WindowManager.LayoutParams); } } } } } } } declare module com { export module facebook { export module internal { export module logging { export module dumpsys { export class EndToEndDumpsysHelper { public static class: java.lang.Class<com.facebook.internal.logging.dumpsys.EndToEndDumpsysHelper>; public static Companion: com.facebook.internal.logging.dumpsys.EndToEndDumpsysHelper.Companion; public constructor(); public static maybeDump(param0: string, param1: java.io.PrintWriter, param2: androidNative.Array<string>): boolean; } export module EndToEndDumpsysHelper { export class Api21Utils { public static class: java.lang.Class<com.facebook.internal.logging.dumpsys.EndToEndDumpsysHelper.Api21Utils>; public static INSTANCE: com.facebook.internal.logging.dumpsys.EndToEndDumpsysHelper.Api21Utils; public writeExtraProps(param0: java.io.PrintWriter, param1: globalAndroid.view.View): void; } export class Api24Utils { public static class: java.lang.Class<com.facebook.internal.logging.dumpsys.EndToEndDumpsysHelper.Api24Utils>; public static INSTANCE: com.facebook.internal.logging.dumpsys.EndToEndDumpsysHelper.Api24Utils; public addExtraProps(param0: org.json.JSONObject, param1: globalAndroid.view.accessibility.AccessibilityNodeInfo): void; } export class Companion { public static class: java.lang.Class<com.facebook.internal.logging.dumpsys.EndToEndDumpsysHelper.Companion>; public maybeDump(param0: string, param1: java.io.PrintWriter, param2: androidNative.Array<string>): boolean; } } } } } } } declare module com { export module facebook { export module internal { export module logging { export module dumpsys { export class ResourcesUtil { public static class: java.lang.Class<com.facebook.internal.logging.dumpsys.ResourcesUtil>; public static INSTANCE: com.facebook.internal.logging.dumpsys.ResourcesUtil; public static getIdStringQuietly(param0: globalAndroid.content.res.Resources, param1: number): string; public static getIdString(param0: globalAndroid.content.res.Resources, param1: number): string; } } } } } } declare module com { export module facebook { export module internal { export module logging { export module dumpsys { export class WebViewDumpHelper { public static class: java.lang.Class<com.facebook.internal.logging.dumpsys.WebViewDumpHelper>; public static GET_WEBVIEW_HTML_JS_SCRIPT: string; public static Companion: com.facebook.internal.logging.dumpsys.WebViewDumpHelper.Companion; public handle(param0: globalAndroid.webkit.WebView): void; public constructor(); public dump(param0: java.io.PrintWriter): void; } export module WebViewDumpHelper { export class Companion { public static class: java.lang.Class<com.facebook.internal.logging.dumpsys.WebViewDumpHelper.Companion>; } export class WebViewData { public static class: java.lang.Class<com.facebook.internal.logging.dumpsys.WebViewDumpHelper.WebViewData>; public static Companion: com.facebook.internal.logging.dumpsys.WebViewDumpHelper.WebViewData.Companion; public getWidth(): number; public getHeight(): number; public getKey(): string; public getLeft(): number; public getTop(): number; public constructor(param0: globalAndroid.webkit.WebView); } export module WebViewData { export class Companion { public static class: java.lang.Class<com.facebook.internal.logging.dumpsys.WebViewDumpHelper.WebViewData.Companion>; } } } } } } } } declare module com { export module facebook { export module internal { export module qualityvalidation { export class Excuse { public static class: java.lang.Class<com.facebook.internal.qualityvalidation.Excuse>; /** * Constructs a new instance of the com.facebook.internal.qualityvalidation.Excuse interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { type(): string; reason(): string; }); public constructor(); public reason(): string; public type(): string; } } } } } declare module com { export module facebook { export module internal { export module qualityvalidation { export class ExcusesForDesignViolations { public static class: java.lang.Class<com.facebook.internal.qualityvalidation.ExcusesForDesignViolations>; /** * Constructs a new instance of the com.facebook.internal.qualityvalidation.ExcusesForDesignViolations interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { value(): androidNative.Array<com.facebook.internal.qualityvalidation.Excuse>; }); public constructor(); public value(): androidNative.Array<com.facebook.internal.qualityvalidation.Excuse>; } } } } } declare module com { export module facebook { export module internal { export module security { export class CertificateUtil { public static class: java.lang.Class<com.facebook.internal.security.CertificateUtil>; public static DELIMITER: string; public static INSTANCE: com.facebook.internal.security.CertificateUtil; public static getCertificateHash(param0: globalAndroid.content.Context): string; } } } } } declare module com { export module facebook { export module internal { export module security { export class OidcSecurityUtil { public static class: java.lang.Class<com.facebook.internal.security.OidcSecurityUtil>; public static SIGNATURE_ALGORITHM_SHA256: string; public static TIMEOUT_IN_MILLISECONDS: number; public static INSTANCE: com.facebook.internal.security.OidcSecurityUtil; public static verify(param0: java.security.PublicKey, param1: string, param2: string): boolean; public getOPENID_KEYS_PATH(): string; public static getRawKeyFromEndPoint(param0: string): string; public static getPublicKeyFromString(param0: string): java.security.PublicKey; } } } } } declare module com { export module facebook { export module login { export class BuildConfig { public static class: java.lang.Class<com.facebook.login.BuildConfig>; public static DEBUG: boolean; public static LIBRARY_PACKAGE_NAME: string; public static APPLICATION_ID: string; public static BUILD_TYPE: string; public static FLAVOR: string; public static VERSION_CODE: number; public static VERSION_NAME: string; public constructor(); } } } } declare module com { export module facebook { export module login { export class CustomTabLoginMethodHandler extends com.facebook.login.WebLoginMethodHandler { public static class: java.lang.Class<com.facebook.login.CustomTabLoginMethodHandler>; public static calledThroughLoggedOutAppSwitch: boolean; public static OAUTH_DIALOG: string; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.login.CustomTabLoginMethodHandler>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public putChallengeParam(param0: org.json.JSONObject): void; public describeContents(): number; public getRedirectUrl(): string; public getSSODevice(): string; } } } } declare module com { export module facebook { export module login { export class CustomTabPrefetchHelper { public static class: java.lang.Class<com.facebook.login.CustomTabPrefetchHelper>; public onServiceDisconnected(param0: globalAndroid.content.ComponentName): void; public static getPreparedSessionOnce(): androidx.browser.customtabs.CustomTabsSession; public static mayLaunchUrl(param0: globalAndroid.net.Uri): void; public onCustomTabsServiceConnected(param0: globalAndroid.content.ComponentName, param1: androidx.browser.customtabs.CustomTabsClient): void; public constructor(); } } } } declare module com { export module facebook { export module login { export class DefaultAudience { public static class: java.lang.Class<com.facebook.login.DefaultAudience>; public static NONE: com.facebook.login.DefaultAudience; public static ONLY_ME: com.facebook.login.DefaultAudience; public static FRIENDS: com.facebook.login.DefaultAudience; public static EVERYONE: com.facebook.login.DefaultAudience; public static values(): androidNative.Array<com.facebook.login.DefaultAudience>; public getNativeProtocolAudience(): string; public static valueOf(param0: string): com.facebook.login.DefaultAudience; } } } } declare module com { export module facebook { export module login { export class DeviceAuthDialog { public static class: java.lang.Class<com.facebook.login.DeviceAuthDialog>; public onDismiss(param0: globalAndroid.content.DialogInterface): void; public startLogin(param0: com.facebook.login.LoginClient.Request): void; public onBackButtonPressed(): void; public onCancel(): void; public onError(param0: com.facebook.FacebookException): void; public onCreateView(param0: globalAndroid.view.LayoutInflater, param1: globalAndroid.view.ViewGroup, param2: globalAndroid.os.Bundle): globalAndroid.view.View; public onSaveInstanceState(param0: globalAndroid.os.Bundle): void; public onDestroyView(): void; public onCreateDialog(param0: globalAndroid.os.Bundle): globalAndroid.app.Dialog; public initializeContentView(param0: boolean): globalAndroid.view.View; public getLayoutResId(param0: boolean): number; public constructor(); } export module DeviceAuthDialog { export class RequestState { public static class: java.lang.Class<com.facebook.login.DeviceAuthDialog.RequestState>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.login.DeviceAuthDialog.RequestState>; public getRequestCode(): string; public constructor(param0: globalAndroid.os.Parcel); public getUserCode(): string; public getInterval(): number; public setInterval(param0: number): void; public setLastPoll(param0: number): void; public getAuthorizationUri(): string; public withinLastRefreshWindow(): boolean; public describeContents(): number; public setRequestCode(param0: string): void; public setUserCode(param0: string): void; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } declare module com { export module facebook { export module login { export class DeviceAuthMethodHandler extends com.facebook.login.LoginMethodHandler { public static class: java.lang.Class<com.facebook.login.DeviceAuthMethodHandler>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.login.DeviceAuthMethodHandler>; public createDeviceAuthDialog(): com.facebook.login.DeviceAuthDialog; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public static getBackgroundExecutor(): java.util.concurrent.ScheduledThreadPoolExecutor; public onCancel(): void; public describeContents(): number; public onSuccess(param0: string, param1: string, param2: string, param3: java.util.Collection<string>, param4: java.util.Collection<string>, param5: java.util.Collection<string>, param6: com.facebook.AccessTokenSource, param7: java.util.Date, param8: java.util.Date, param9: java.util.Date): void; public onError(param0: java.lang.Exception): void; public constructor(param0: globalAndroid.os.Parcel); } } } } declare module com { export module facebook { export module login { export class DeviceLoginManager extends com.facebook.login.LoginManager { public static class: java.lang.Class<com.facebook.login.DeviceLoginManager>; public getDeviceRedirectUri(): globalAndroid.net.Uri; public createLoginRequest(param0: java.util.Collection<string>): com.facebook.login.LoginClient.Request; public setDeviceRedirectUri(param0: globalAndroid.net.Uri): void; public static getInstance(): com.facebook.login.DeviceLoginManager; public setDeviceAuthTargetUserId(param0: string): void; public createLoginRequest(param0: java.util.Collection<string>, param1: string): com.facebook.login.LoginClient.Request; public getDeviceAuthTargetUserId(): string; public static getInstance(): com.facebook.login.LoginManager; public constructor(); } } } } declare module com { export module facebook { export module login { export class FacebookLiteLoginMethodHandler extends com.facebook.login.NativeAppLoginMethodHandler { public static class: java.lang.Class<com.facebook.login.FacebookLiteLoginMethodHandler>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.login.FacebookLiteLoginMethodHandler>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public describeContents(): number; } } } } declare module com { export module facebook { export module login { export class GetTokenClient extends com.facebook.internal.PlatformServiceClient { public static class: java.lang.Class<com.facebook.login.GetTokenClient>; public populateRequestBundle(param0: globalAndroid.os.Bundle): void; } } } } declare module com { export module facebook { export module login { export class GetTokenLoginMethodHandler extends com.facebook.login.LoginMethodHandler { public static class: java.lang.Class<com.facebook.login.GetTokenLoginMethodHandler>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.login.GetTokenLoginMethodHandler>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public describeContents(): number; } } } } declare module com { export module facebook { export module login { export class InstagramAppLoginMethodHandler extends com.facebook.login.NativeAppLoginMethodHandler { public static class: java.lang.Class<com.facebook.login.InstagramAppLoginMethodHandler>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.login.InstagramAppLoginMethodHandler>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public describeContents(): number; public getTokenSource(): com.facebook.AccessTokenSource; } } } } declare module com { export module facebook { export module login { export class KatanaProxyLoginMethodHandler extends com.facebook.login.NativeAppLoginMethodHandler { public static class: java.lang.Class<com.facebook.login.KatanaProxyLoginMethodHandler>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.login.KatanaProxyLoginMethodHandler>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public shouldKeepTrackOfMultipleIntents(): boolean; public describeContents(): number; } } } } declare module com { export module facebook { export module login { export class Login { public static class: java.lang.Class<com.facebook.login.Login>; public constructor(); } } } } declare module com { export module facebook { export module login { export class LoginBehavior { public static class: java.lang.Class<com.facebook.login.LoginBehavior>; public static NATIVE_WITH_FALLBACK: com.facebook.login.LoginBehavior; public static NATIVE_ONLY: com.facebook.login.LoginBehavior; public static KATANA_ONLY: com.facebook.login.LoginBehavior; public static WEB_ONLY: com.facebook.login.LoginBehavior; public static WEB_VIEW_ONLY: com.facebook.login.LoginBehavior; public static DIALOG_ONLY: com.facebook.login.LoginBehavior; public static DEVICE_AUTH: com.facebook.login.LoginBehavior; public static values(): androidNative.Array<com.facebook.login.LoginBehavior>; public static valueOf(param0: string): com.facebook.login.LoginBehavior; } } } } declare module com { export module facebook { export module login { export class LoginClient { public static class: java.lang.Class<com.facebook.login.LoginClient>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.login.LoginClient>; public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): boolean; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getHandlersToTry(param0: com.facebook.login.LoginClient.Request): androidNative.Array<com.facebook.login.LoginMethodHandler>; public static getLoginRequestCode(): number; public constructor(param0: androidx.fragment.app.Fragment); public describeContents(): number; public getFragment(): androidx.fragment.app.Fragment; public getPendingRequest(): com.facebook.login.LoginClient.Request; public constructor(param0: globalAndroid.os.Parcel); } export module LoginClient { export class BackgroundProcessingListener { public static class: java.lang.Class<com.facebook.login.LoginClient.BackgroundProcessingListener>; /** * Constructs a new instance of the com.facebook.login.LoginClient$BackgroundProcessingListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onBackgroundProcessingStarted(): void; onBackgroundProcessingStopped(): void; }); public constructor(); public onBackgroundProcessingStarted(): void; public onBackgroundProcessingStopped(): void; } export class OnCompletedListener { public static class: java.lang.Class<com.facebook.login.LoginClient.OnCompletedListener>; /** * Constructs a new instance of the com.facebook.login.LoginClient$OnCompletedListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onCompleted(param0: com.facebook.login.LoginClient.Result): void; }); public constructor(); public onCompleted(param0: com.facebook.login.LoginClient.Result): void; } export class Request { public static class: java.lang.Class<com.facebook.login.LoginClient.Request>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.login.LoginClient.Request>; public getNonce(): string; public getMessengerPageId(): string; public setResetMessengerState(param0: boolean): void; public describeContents(): number; public setMessengerPageId(param0: string): void; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getResetMessengerState(): boolean; } export class Result { public static class: java.lang.Class<com.facebook.login.LoginClient.Result>; public loggingExtras: java.util.Map<string,string>; public extraData: java.util.Map<string,string>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.login.LoginClient.Result>; public describeContents(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } export module Result { export class Code { public static class: java.lang.Class<com.facebook.login.LoginClient.Result.Code>; public static SUCCESS: com.facebook.login.LoginClient.Result.Code; public static CANCEL: com.facebook.login.LoginClient.Result.Code; public static ERROR: com.facebook.login.LoginClient.Result.Code; public static values(): androidNative.Array<com.facebook.login.LoginClient.Result.Code>; public static valueOf(param0: string): com.facebook.login.LoginClient.Result.Code; } } } } } } declare module com { export module facebook { export module login { export class LoginConfiguration { public static class: java.lang.Class<com.facebook.login.LoginConfiguration>; public static OPENID: string; public static Companion: com.facebook.login.LoginConfiguration.Companion; public constructor(param0: java.util.Collection<string>); public getPermissions(): java.util.Set<string>; public constructor(param0: java.util.Collection<string>, param1: string); public getNonce(): string; } export module LoginConfiguration { export class Companion { public static class: java.lang.Class<com.facebook.login.LoginConfiguration.Companion>; } } } } } declare module com { export module facebook { export module login { export class LoginFragment { public static class: java.lang.Class<com.facebook.login.LoginFragment>; public createLoginClient(): com.facebook.login.LoginClient; public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): void; public onCreate(param0: globalAndroid.os.Bundle): void; public onResume(): void; public getLayoutResId(): number; public onPause(): void; public onCreateView(param0: globalAndroid.view.LayoutInflater, param1: globalAndroid.view.ViewGroup, param2: globalAndroid.os.Bundle): globalAndroid.view.View; public onDestroy(): void; public onSaveInstanceState(param0: globalAndroid.os.Bundle): void; public constructor(); } } } } declare module com { export module facebook { export module login { export class LoginLogger { public static class: java.lang.Class<com.facebook.login.LoginLogger>; public logCompleteLogin(param0: string, param1: java.util.Map<string,string>, param2: com.facebook.login.LoginClient.Result.Code, param3: java.util.Map<string,string>, param4: java.lang.Exception, param5: string): void; public logStartLogin(param0: com.facebook.login.LoginClient.Request): void; public logAuthorizationMethodStart(param0: string, param1: string, param2: string): void; public logCompleteLogin(param0: string, param1: java.util.Map<string,string>, param2: com.facebook.login.LoginClient.Result.Code, param3: java.util.Map<string,string>, param4: java.lang.Exception): void; public logAuthorizationMethodNotTried(param0: string, param1: string, param2: string): void; public logLoginStatusStart(param0: string): void; public logAuthorizationMethodStart(param0: string, param1: string): void; public logAuthorizationMethodComplete(param0: string, param1: string, param2: string, param3: string, param4: string, param5: java.util.Map<string,string>): void; public logLoginStatusError(param0: string, param1: java.lang.Exception): void; public logStartLogin(param0: com.facebook.login.LoginClient.Request, param1: string): void; public logAuthorizationMethodNotTried(param0: string, param1: string): void; public getApplicationId(): string; public logAuthorizationMethodComplete(param0: string, param1: string, param2: string, param3: string, param4: string, param5: java.util.Map<string,string>, param6: string): void; public logUnexpectedError(param0: string, param1: string, param2: string): void; public logLoginStatusFailure(param0: string): void; public logLoginStatusSuccess(param0: string): void; public logUnexpectedError(param0: string, param1: string): void; } } } } declare module com { export module facebook { export module login { export class LoginManager { public static class: java.lang.Class<com.facebook.login.LoginManager>; public setLoginTargetApp(param0: com.facebook.login.LoginTargetApp): com.facebook.login.LoginManager; public setDefaultAudience(param0: com.facebook.login.DefaultAudience): com.facebook.login.LoginManager; public logOut(): void; public logIn(param0: globalAndroid.app.Activity, param1: com.facebook.login.LoginConfiguration): void; public setShouldSkipAccountDeduplication(param0: boolean): com.facebook.login.LoginManager; public logIn(param0: com.facebook.internal.FragmentWrapper, param1: java.util.Collection<string>, param2: string): void; public isFamilyLogin(): boolean; public logIn(param0: androidx.activity.result.ActivityResultRegistryOwner, param1: com.facebook.CallbackManager, param2: java.util.Collection<string>, param3: string): void; public retrieveLoginStatus(param0: globalAndroid.content.Context, param1: number, param2: com.facebook.LoginStatusCallback): void; public getFacebookActivityIntent(param0: com.facebook.login.LoginClient.Request): globalAndroid.content.Intent; public setFamilyLogin(param0: boolean): com.facebook.login.LoginManager; public resolveError(param0: androidx.fragment.app.Fragment, param1: com.facebook.CallbackManager, param2: com.facebook.GraphResponse): void; public resolveError(param0: androidx.activity.result.ActivityResultRegistryOwner, param1: com.facebook.CallbackManager, param2: com.facebook.GraphResponse): void; public logIn(param0: globalAndroid.app.Activity, param1: java.util.Collection<string>, param2: string): void; public createLoginRequestWithConfig(param0: com.facebook.login.LoginConfiguration): com.facebook.login.LoginClient.Request; public getLoginBehavior(): com.facebook.login.LoginBehavior; public unregisterCallback(param0: com.facebook.CallbackManager): void; public reauthorizeDataAccess(param0: androidx.fragment.app.Fragment): void; public createReauthorizeRequest(): com.facebook.login.LoginClient.Request; public logInWithConfiguration(param0: androidx.fragment.app.Fragment, param1: com.facebook.login.LoginConfiguration): void; public setAuthType(param0: string): com.facebook.login.LoginManager; public logInWithReadPermissions(param0: globalAndroid.app.Fragment, param1: java.util.Collection<string>): void; public logInWithPublishPermissions(param0: androidx.activity.result.ActivityResultRegistryOwner, param1: com.facebook.CallbackManager, param2: java.util.Collection<string>): void; public registerCallback(param0: com.facebook.CallbackManager, param1: com.facebook.FacebookCallback<com.facebook.login.LoginResult>): void; public logIn(param0: androidx.activity.result.ActivityResultRegistryOwner, param1: com.facebook.CallbackManager, param2: java.util.Collection<string>): void; public logInWithReadPermissions(param0: globalAndroid.app.Activity, param1: java.util.Collection<string>): void; public logIn(param0: androidx.fragment.app.Fragment, param1: java.util.Collection<string>): void; public logIn(param0: androidx.fragment.app.Fragment, param1: java.util.Collection<string>, param2: string): void; public logInWithPublishPermissions(param0: androidx.fragment.app.Fragment, param1: com.facebook.CallbackManager, param2: java.util.Collection<string>): void; public logInWithReadPermissions(param0: androidx.activity.result.ActivityResultRegistryOwner, param1: com.facebook.CallbackManager, param2: java.util.Collection<string>): void; public logIn(param0: com.facebook.internal.FragmentWrapper, param1: java.util.Collection<string>): void; public reauthorizeDataAccess(param0: globalAndroid.app.Activity): void; /** @deprecated */ public resolveError(param0: androidx.fragment.app.Fragment, param1: com.facebook.GraphResponse): void; public resolveError(param0: globalAndroid.app.Fragment, param1: com.facebook.GraphResponse): void; public setMessengerPageId(param0: string): com.facebook.login.LoginManager; public getAuthType(): string; public createLoginRequest(param0: java.util.Collection<string>, param1: string): com.facebook.login.LoginClient.Request; public static getInstance(): com.facebook.login.LoginManager; public resolveError(param0: globalAndroid.app.Activity, param1: com.facebook.GraphResponse): void; public logIn(param0: globalAndroid.app.Fragment, param1: java.util.Collection<string>, param2: string): void; public setLoginBehavior(param0: com.facebook.login.LoginBehavior): com.facebook.login.LoginManager; public logInWithPublishPermissions(param0: globalAndroid.app.Activity, param1: java.util.Collection<string>): void; public getDefaultAudience(): com.facebook.login.DefaultAudience; public retrieveLoginStatus(param0: globalAndroid.content.Context, param1: com.facebook.LoginStatusCallback): void; public getShouldSkipAccountDeduplication(): boolean; public logInWithReadPermissions(param0: androidx.fragment.app.Fragment, param1: com.facebook.CallbackManager, param2: java.util.Collection<string>): void; public logIn(param0: globalAndroid.app.Activity, param1: java.util.Collection<string>): void; public logIn(param0: com.facebook.internal.FragmentWrapper, param1: com.facebook.login.LoginConfiguration): void; public getLoginTargetApp(): com.facebook.login.LoginTargetApp; /** @deprecated */ public logInWithPublishPermissions(param0: androidx.fragment.app.Fragment, param1: java.util.Collection<string>): void; public setResetMessengerState(param0: boolean): com.facebook.login.LoginManager; public createLoginRequest(param0: java.util.Collection<string>): com.facebook.login.LoginClient.Request; /** @deprecated */ public logInWithReadPermissions(param0: androidx.fragment.app.Fragment, param1: java.util.Collection<string>): void; public loginWithConfiguration(param0: globalAndroid.app.Activity, param1: com.facebook.login.LoginConfiguration): void; public logIn(param0: globalAndroid.app.Fragment, param1: java.util.Collection<string>): void; public logInWithPublishPermissions(param0: globalAndroid.app.Fragment, param1: java.util.Collection<string>): void; } export module LoginManager { export class ActivityStartActivityDelegate extends com.facebook.login.StartActivityDelegate { public static class: java.lang.Class<com.facebook.login.LoginManager.ActivityStartActivityDelegate>; public startActivityForResult(param0: globalAndroid.content.Intent, param1: number): void; public getActivityContext(): globalAndroid.app.Activity; } export class AndroidxActivityResultRegistryOwnerStartActivityDelegate extends com.facebook.login.StartActivityDelegate { public static class: java.lang.Class<com.facebook.login.LoginManager.AndroidxActivityResultRegistryOwnerStartActivityDelegate>; public startActivityForResult(param0: globalAndroid.content.Intent, param1: number): void; public getActivityContext(): globalAndroid.app.Activity; } export class FragmentStartActivityDelegate extends com.facebook.login.StartActivityDelegate { public static class: java.lang.Class<com.facebook.login.LoginManager.FragmentStartActivityDelegate>; public startActivityForResult(param0: globalAndroid.content.Intent, param1: number): void; public getActivityContext(): globalAndroid.app.Activity; } export class LoginLoggerHolder { public static class: java.lang.Class<com.facebook.login.LoginManager.LoginLoggerHolder>; } } } } } declare module com { export module facebook { export module login { export abstract class LoginMethodHandler { public static class: java.lang.Class<com.facebook.login.LoginMethodHandler>; public loginClient: com.facebook.login.LoginClient; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public shouldKeepTrackOfMultipleIntents(): boolean; public static createAuthenticationTokenFromWebBundle(param0: globalAndroid.os.Bundle, param1: string): com.facebook.AuthenticationToken; public getClientState(param0: string): string; public addLoggingExtra(param0: string, param1: any): void; public logWebLoginCompleted(param0: string): void; public static createAccessTokenFromWebBundle(param0: java.util.Collection<string>, param1: globalAndroid.os.Bundle, param2: com.facebook.AccessTokenSource, param3: string): com.facebook.AccessToken; } } } } declare module com { export module facebook { export module login { export class LoginResult { public static class: java.lang.Class<com.facebook.login.LoginResult>; public component3(): java.util.Set<string>; public copy(param0: com.facebook.AccessToken, param1: com.facebook.AuthenticationToken, param2: java.util.Set<string>, param3: java.util.Set<string>): com.facebook.login.LoginResult; public getRecentlyGrantedPermissions(): java.util.Set<string>; public getAccessToken(): com.facebook.AccessToken; public component1(): com.facebook.AccessToken; public toString(): string; public component4(): java.util.Set<string>; public constructor(param0: com.facebook.AccessToken, param1: java.util.Set<string>, param2: java.util.Set<string>); public getAuthenticationToken(): com.facebook.AuthenticationToken; public hashCode(): number; public component2(): com.facebook.AuthenticationToken; public getRecentlyDeniedPermissions(): java.util.Set<string>; public equals(param0: any): boolean; public constructor(param0: com.facebook.AccessToken, param1: com.facebook.AuthenticationToken, param2: java.util.Set<string>, param3: java.util.Set<string>); } } } } declare module com { export module facebook { export module login { export class LoginStatusClient extends com.facebook.internal.PlatformServiceClient { public static class: java.lang.Class<com.facebook.login.LoginStatusClient>; public populateRequestBundle(param0: globalAndroid.os.Bundle): void; } } } } declare module com { export module facebook { export module login { export class LoginTargetApp { public static class: java.lang.Class<com.facebook.login.LoginTargetApp>; public static FACEBOOK: com.facebook.login.LoginTargetApp; public static INSTAGRAM: com.facebook.login.LoginTargetApp; public static Companion: com.facebook.login.LoginTargetApp.Companion; public static valueOf(param0: string): com.facebook.login.LoginTargetApp; public static values(): androidNative.Array<com.facebook.login.LoginTargetApp>; public static fromString(param0: string): com.facebook.login.LoginTargetApp; public toString(): string; } export module LoginTargetApp { export class Companion { public static class: java.lang.Class<com.facebook.login.LoginTargetApp.Companion>; public fromString(param0: string): com.facebook.login.LoginTargetApp; } } } } } declare module com { export module facebook { export module login { export abstract class NativeAppLoginMethodHandler extends com.facebook.login.LoginMethodHandler { public static class: java.lang.Class<com.facebook.login.NativeAppLoginMethodHandler>; public handleResultCancel(param0: com.facebook.login.LoginClient.Request, param1: globalAndroid.content.Intent): void; public tryIntent(param0: globalAndroid.content.Intent, param1: number): boolean; public getErrorMessage(param0: globalAndroid.os.Bundle): string; public getTokenSource(): com.facebook.AccessTokenSource; public handleResultError(param0: com.facebook.login.LoginClient.Request, param1: string, param2: string, param3: string): void; public getError(param0: globalAndroid.os.Bundle): string; public handleResultOk(param0: com.facebook.login.LoginClient.Request, param1: globalAndroid.os.Bundle): void; } } } } declare module com { export module facebook { export module login { export class NonceUtil { public static class: java.lang.Class<com.facebook.login.NonceUtil>; public static INSTANCE: com.facebook.login.NonceUtil; public static isValidNonce(param0: string): boolean; } } } } declare module com { export module facebook { export module login { export class StartActivityDelegate { public static class: java.lang.Class<com.facebook.login.StartActivityDelegate>; /** * Constructs a new instance of the com.facebook.login.StartActivityDelegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { startActivityForResult(param0: globalAndroid.content.Intent, param1: number): void; getActivityContext(): globalAndroid.app.Activity; }); public constructor(); public startActivityForResult(param0: globalAndroid.content.Intent, param1: number): void; public getActivityContext(): globalAndroid.app.Activity; } } } } declare module com { export module facebook { export module login { export abstract class WebLoginMethodHandler extends com.facebook.login.LoginMethodHandler { public static class: java.lang.Class<com.facebook.login.WebLoginMethodHandler>; public tokenSource: com.facebook.AccessTokenSource; public getParameters(param0: com.facebook.login.LoginClient.Request): globalAndroid.os.Bundle; public addExtraParameters(param0: globalAndroid.os.Bundle, param1: com.facebook.login.LoginClient.Request): globalAndroid.os.Bundle; public onComplete(param0: com.facebook.login.LoginClient.Request, param1: globalAndroid.os.Bundle, param2: com.facebook.FacebookException): void; public getRedirectUrl(): string; public getSSODevice(): string; } } } } declare module com { export module facebook { export module login { export class WebViewLoginMethodHandler extends com.facebook.login.WebLoginMethodHandler { public static class: java.lang.Class<com.facebook.login.WebViewLoginMethodHandler>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.login.WebViewLoginMethodHandler>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public describeContents(): number; } export module WebViewLoginMethodHandler { export class AuthDialogBuilder extends com.facebook.internal.WebDialog.Builder { public static class: java.lang.Class<com.facebook.login.WebViewLoginMethodHandler.AuthDialogBuilder>; public setLoginBehavior(param0: com.facebook.login.LoginBehavior): com.facebook.login.WebViewLoginMethodHandler.AuthDialogBuilder; public setAuthType(param0: string): com.facebook.login.WebViewLoginMethodHandler.AuthDialogBuilder; public constructor(param0: globalAndroid.content.Context, param1: string, param2: globalAndroid.os.Bundle); public setShouldSkipDedupe(param0: boolean): com.facebook.login.WebViewLoginMethodHandler.AuthDialogBuilder; public setLoginTargetApp(param0: com.facebook.login.LoginTargetApp): com.facebook.login.WebViewLoginMethodHandler.AuthDialogBuilder; public constructor(param0: globalAndroid.content.Context, param1: string, param2: string, param3: globalAndroid.os.Bundle); public setE2E(param0: string): com.facebook.login.WebViewLoginMethodHandler.AuthDialogBuilder; /** @deprecated */ public setIsRerequest(param0: boolean): com.facebook.login.WebViewLoginMethodHandler.AuthDialogBuilder; public setIsChromeOS(param0: boolean): com.facebook.login.WebViewLoginMethodHandler.AuthDialogBuilder; public setFamilyLogin(param0: boolean): com.facebook.login.WebViewLoginMethodHandler.AuthDialogBuilder; public build(): com.facebook.internal.WebDialog; } } } } } declare module com { export module facebook { export module login { export module widget { export class DeviceLoginButton extends com.facebook.login.widget.LoginButton { public static class: java.lang.Class<com.facebook.login.widget.DeviceLoginButton>; public constructor(param0: globalAndroid.content.Context); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet); public getDeviceRedirectUri(): globalAndroid.net.Uri; public getNewLoginClickListener(): com.facebook.login.widget.LoginButton.LoginClickListener; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet, param2: number, param3: number, param4: string, param5: string); public setDeviceRedirectUri(param0: globalAndroid.net.Uri): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet, param2: number); } export module DeviceLoginButton { export class DeviceLoginClickListener extends com.facebook.login.widget.LoginButton.LoginClickListener { public static class: java.lang.Class<com.facebook.login.widget.DeviceLoginButton.DeviceLoginClickListener>; public getLoginManager(): com.facebook.login.LoginManager; } } } } } } declare module com { export module facebook { export module login { export module widget { export class LoginButton extends com.facebook.FacebookButtonBase { public static class: java.lang.Class<com.facebook.login.widget.LoginButton>; public setToolTipStyle(param0: com.facebook.login.widget.ToolTipPopup.Style): void; public setPermissions(param0: java.util.List<string>): void; /** @deprecated */ public setPublishPermissions(param0: androidNative.Array<string>): void; public onAttachedToWindow(): void; public setLogoutText(param0: string): void; public onVisibilityChanged(param0: globalAndroid.view.View, param1: number): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet); public clearPermissions(): void; public getLoginBehavior(): com.facebook.login.LoginBehavior; public getDefaultStyleResource(): number; public getDefaultRequestCode(): number; public getMessengerPageId(): string; public setToolTipDisplayTime(param0: number): void; public getDefaultAudience(): com.facebook.login.DefaultAudience; public setPermissions(param0: androidNative.Array<string>): void; public registerCallback(param0: com.facebook.CallbackManager, param1: com.facebook.FacebookCallback<com.facebook.login.LoginResult>): void; public getResetMessengerState(): boolean; /** @deprecated */ public setPublishPermissions(param0: java.util.List<string>): void; public onDetachedFromWindow(): void; public setAuthType(param0: string): void; public onMeasure(param0: number, param1: number): void; public onDraw(param0: globalAndroid.graphics.Canvas): void; public getToolTipMode(): com.facebook.login.widget.LoginButton.ToolTipMode; public setResetMessengerState(param0: boolean): void; public getToolTipDisplayTime(): number; public dismissToolTip(): void; public configureButton(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet, param2: number, param3: number): void; public setMessengerPageId(param0: string): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet, param2: number); public setDefaultAudience(param0: com.facebook.login.DefaultAudience): void; public getAuthType(): string; public constructor(param0: globalAndroid.content.Context); /** @deprecated */ public setReadPermissions(param0: androidNative.Array<string>): void; public getNewLoginClickListener(): com.facebook.login.widget.LoginButton.LoginClickListener; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet, param2: number, param3: number, param4: string, param5: string); public onLayout(param0: boolean, param1: number, param2: number, param3: number, param4: number): void; public setToolTipMode(param0: com.facebook.login.widget.LoginButton.ToolTipMode): void; public setLoginBehavior(param0: com.facebook.login.LoginBehavior): void; public setLoginText(param0: string): void; /** @deprecated */ public setReadPermissions(param0: java.util.List<string>): void; public unregisterCallback(param0: com.facebook.CallbackManager): void; } export module LoginButton { export class LoginButtonProperties { public static class: java.lang.Class<com.facebook.login.widget.LoginButton.LoginButtonProperties>; public clearPermissions(): void; public getMessengerPageId(): string; public setResetMessengerState(param0: boolean): void; public getResetMessengerState(): boolean; public setPermissions(param0: java.util.List<string>): void; public setLoginBehavior(param0: com.facebook.login.LoginBehavior): void; public getDefaultAudience(): com.facebook.login.DefaultAudience; public getAuthType(): string; public setMessengerPageId(param0: string): void; public setDefaultAudience(param0: com.facebook.login.DefaultAudience): void; public setAuthType(param0: string): void; public getLoginBehavior(): com.facebook.login.LoginBehavior; } export class LoginClickListener { public static class: java.lang.Class<com.facebook.login.widget.LoginButton.LoginClickListener>; public constructor(param0: com.facebook.login.widget.LoginButton); public performLogin(): void; public performLogout(param0: globalAndroid.content.Context): void; public onClick(param0: globalAndroid.view.View): void; public getLoginManager(): com.facebook.login.LoginManager; } export class ToolTipMode { public static class: java.lang.Class<com.facebook.login.widget.LoginButton.ToolTipMode>; public static AUTOMATIC: com.facebook.login.widget.LoginButton.ToolTipMode; public static DISPLAY_ALWAYS: com.facebook.login.widget.LoginButton.ToolTipMode; public static NEVER_DISPLAY: com.facebook.login.widget.LoginButton.ToolTipMode; public static DEFAULT: com.facebook.login.widget.LoginButton.ToolTipMode; public static values(): androidNative.Array<com.facebook.login.widget.LoginButton.ToolTipMode>; public static valueOf(param0: string): com.facebook.login.widget.LoginButton.ToolTipMode; public static fromInt(param0: number): com.facebook.login.widget.LoginButton.ToolTipMode; public toString(): string; public getValue(): number; } } } } } } declare module com { export module facebook { export module login { export module widget { export class ProfilePictureView { public static class: java.lang.Class<com.facebook.login.widget.ProfilePictureView>; public static TAG: string; public static CUSTOM: number; public static SMALL: number; public static NORMAL: number; public static LARGE: number; public onDetachedFromWindow(): void; public onMeasure(param0: number, param1: number): void; public getPresetSize(): number; public setProfileId(param0: string): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet, param2: number); public getProfileId(): string; public constructor(param0: globalAndroid.content.Context); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet); public setOnErrorListener(param0: com.facebook.login.widget.ProfilePictureView.OnErrorListener): void; public setCropped(param0: boolean): void; public getOnErrorListener(): com.facebook.login.widget.ProfilePictureView.OnErrorListener; public onRestoreInstanceState(param0: globalAndroid.os.Parcelable): void; public onLayout(param0: boolean, param1: number, param2: number, param3: number, param4: number): void; public onSaveInstanceState(): globalAndroid.os.Parcelable; public setPresetSize(param0: number): void; public isCropped(): boolean; public setDefaultProfilePicture(param0: globalAndroid.graphics.Bitmap): void; } export module ProfilePictureView { export class OnErrorListener { public static class: java.lang.Class<com.facebook.login.widget.ProfilePictureView.OnErrorListener>; /** * Constructs a new instance of the com.facebook.login.widget.ProfilePictureView$OnErrorListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onError(param0: com.facebook.FacebookException): void; }); public constructor(); public onError(param0: com.facebook.FacebookException): void; } } } } } } declare module com { export module facebook { export module login { export module widget { export class ToolTipPopup { public static class: java.lang.Class<com.facebook.login.widget.ToolTipPopup>; public static DEFAULT_POPUP_DISPLAY_TIME: number; public show(): void; public setStyle(param0: com.facebook.login.widget.ToolTipPopup.Style): void; public setNuxDisplayTime(param0: number): void; public constructor(param0: string, param1: globalAndroid.view.View); public dismiss(): void; } export module ToolTipPopup { export class PopupContentView { public static class: java.lang.Class<com.facebook.login.widget.ToolTipPopup.PopupContentView>; public showTopArrow(): void; public showBottomArrow(): void; public constructor(param0: com.facebook.login.widget.ToolTipPopup, param1: globalAndroid.content.Context); } export class Style { public static class: java.lang.Class<com.facebook.login.widget.ToolTipPopup.Style>; public static BLUE: com.facebook.login.widget.ToolTipPopup.Style; public static BLACK: com.facebook.login.widget.ToolTipPopup.Style; public static values(): androidNative.Array<com.facebook.login.widget.ToolTipPopup.Style>; public static valueOf(param0: string): com.facebook.login.widget.ToolTipPopup.Style; } } } } } } declare module com { export module facebook { export module ppml { export module receiver { export class IReceiverService { public static class: java.lang.Class<com.facebook.ppml.receiver.IReceiverService>; /** * Constructs a new instance of the com.facebook.ppml.receiver.IReceiverService interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { sendEvents(param0: globalAndroid.os.Bundle): number; }); public constructor(); public sendEvents(param0: globalAndroid.os.Bundle): number; } export module IReceiverService { export class Default extends com.facebook.ppml.receiver.IReceiverService { public static class: java.lang.Class<com.facebook.ppml.receiver.IReceiverService.Default>; public constructor(); public sendEvents(param0: globalAndroid.os.Bundle): number; public asBinder(): globalAndroid.os.IBinder; } export abstract class Stub implements com.facebook.ppml.receiver.IReceiverService { public static class: java.lang.Class<com.facebook.ppml.receiver.IReceiverService.Stub>; public constructor(); public sendEvents(param0: globalAndroid.os.Bundle): number; public static setDefaultImpl(param0: com.facebook.ppml.receiver.IReceiverService): boolean; public onTransact(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public asBinder(): globalAndroid.os.IBinder; public static asInterface(param0: globalAndroid.os.IBinder): com.facebook.ppml.receiver.IReceiverService; public static getDefaultImpl(): com.facebook.ppml.receiver.IReceiverService; } export module Stub { export class Proxy extends com.facebook.ppml.receiver.IReceiverService { public static class: java.lang.Class<com.facebook.ppml.receiver.IReceiverService.Stub.Proxy>; public static sDefaultImpl: com.facebook.ppml.receiver.IReceiverService; public getInterfaceDescriptor(): string; public sendEvents(param0: globalAndroid.os.Bundle): number; public asBinder(): globalAndroid.os.IBinder; } } } } } } } declare module com { export module facebook { export module referrals { export class ReferralClient { public static class: java.lang.Class<com.facebook.referrals.ReferralClient>; public expectedChallenge: string; } } } } declare module com { export module facebook { export module referrals { export class ReferralFragment { public static class: java.lang.Class<com.facebook.referrals.ReferralFragment>; public static TAG: string; public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): void; public onCreate(param0: globalAndroid.os.Bundle): void; public onResume(): void; public constructor(); } } } } declare module com { export module facebook { export module referrals { export class ReferralLogger { public static class: java.lang.Class<com.facebook.referrals.ReferralLogger>; public logError(param0: java.lang.Exception): void; public logCancel(): void; public logSuccess(): void; public logStartReferral(): void; } } } } declare module com { export module facebook { export module referrals { export class ReferralManager { public static class: java.lang.Class<com.facebook.referrals.ReferralManager>; public startReferral(param0: com.facebook.internal.FragmentWrapper): void; public startReferral(param0: androidx.fragment.app.Fragment): void; public static getInstance(): com.facebook.referrals.ReferralManager; public startReferral(param0: globalAndroid.app.Fragment): void; public registerCallback(param0: com.facebook.CallbackManager, param1: com.facebook.FacebookCallback<com.facebook.referrals.ReferralResult>): void; public startReferral(param0: globalAndroid.app.Activity): void; } export module ReferralManager { export class ActivityStartActivityDelegate extends com.facebook.referrals.StartActivityDelegate { public static class: java.lang.Class<com.facebook.referrals.ReferralManager.ActivityStartActivityDelegate>; public startActivityForResult(param0: globalAndroid.content.Intent, param1: number): void; public getActivityContext(): globalAndroid.app.Activity; } export class FragmentStartActivityDelegate extends com.facebook.referrals.StartActivityDelegate { public static class: java.lang.Class<com.facebook.referrals.ReferralManager.FragmentStartActivityDelegate>; public startActivityForResult(param0: globalAndroid.content.Intent, param1: number): void; public getActivityContext(): globalAndroid.app.Activity; } } } } } declare module com { export module facebook { export module referrals { export class ReferralResult { public static class: java.lang.Class<com.facebook.referrals.ReferralResult>; public getReferralCodes(): java.util.List<string>; public hashCode(): number; public equals(param0: any): boolean; public constructor(param0: java.util.List<string>); } } } } declare module com { export module facebook { export module referrals { export class StartActivityDelegate { public static class: java.lang.Class<com.facebook.referrals.StartActivityDelegate>; /** * Constructs a new instance of the com.facebook.referrals.StartActivityDelegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { startActivityForResult(param0: globalAndroid.content.Intent, param1: number): void; getActivityContext(): globalAndroid.app.Activity; }); public constructor(); public startActivityForResult(param0: globalAndroid.content.Intent, param1: number): void; public getActivityContext(): globalAndroid.app.Activity; } } } } declare module com { export module facebook { export module share { export class ShareBuilder<P, E> extends java.lang.Object { public static class: java.lang.Class<com.facebook.share.ShareBuilder<any,any>>; /** * Constructs a new instance of the com.facebook.share.ShareBuilder<any,any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { build(): P; }); public constructor(); public build(): P; } } } } declare module com { export module facebook { export module share { export class Sharer { public static class: java.lang.Class<com.facebook.share.Sharer>; /** * Constructs a new instance of the com.facebook.share.Sharer interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getShouldFailOnDataError(): boolean; setShouldFailOnDataError(param0: boolean): void; }); public constructor(); public getShouldFailOnDataError(): boolean; public setShouldFailOnDataError(param0: boolean): void; } export module Sharer { export class Result { public static class: java.lang.Class<com.facebook.share.Sharer.Result>; public constructor(param0: string); public getPostId(): string; } } } } } declare module com { export module facebook { export module share { export module internal { export class CameraEffectFeature extends com.facebook.internal.DialogFeature { public static class: java.lang.Class<com.facebook.share.internal.CameraEffectFeature>; public static SHARE_CAMERA_EFFECT: com.facebook.share.internal.CameraEffectFeature; public getMinVersion(): number; public name(): string; public static valueOf(param0: string): com.facebook.share.internal.CameraEffectFeature; public static values(): androidNative.Array<com.facebook.share.internal.CameraEffectFeature>; public getAction(): string; } } } } } declare module com { export module facebook { export module share { export module internal { export class CameraEffectJSONUtility { public static class: java.lang.Class<com.facebook.share.internal.CameraEffectJSONUtility>; public static convertToJSON(param0: com.facebook.share.model.CameraEffectArguments): org.json.JSONObject; public constructor(); public static convertToCameraEffectArguments(param0: org.json.JSONObject): com.facebook.share.model.CameraEffectArguments; } export module CameraEffectJSONUtility { export class Setter { public static class: java.lang.Class<com.facebook.share.internal.CameraEffectJSONUtility.Setter>; /** * Constructs a new instance of the com.facebook.share.internal.CameraEffectJSONUtility$Setter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { setOnArgumentsBuilder(param0: com.facebook.share.model.CameraEffectArguments.Builder, param1: string, param2: any): void; setOnJSON(param0: org.json.JSONObject, param1: string, param2: any): void; }); public constructor(); public setOnArgumentsBuilder(param0: com.facebook.share.model.CameraEffectArguments.Builder, param1: string, param2: any): void; public setOnJSON(param0: org.json.JSONObject, param1: string, param2: any): void; } } } } } } declare module com { export module facebook { export module share { export module internal { export class DeviceShareDialogFragment { public static class: java.lang.Class<com.facebook.share.internal.DeviceShareDialogFragment>; public static TAG: string; public onSaveInstanceState(param0: globalAndroid.os.Bundle): void; public constructor(); public onCreateView(param0: globalAndroid.view.LayoutInflater, param1: globalAndroid.view.ViewGroup, param2: globalAndroid.os.Bundle): globalAndroid.view.View; public onDismiss(param0: globalAndroid.content.DialogInterface): void; public onCreateDialog(param0: globalAndroid.os.Bundle): globalAndroid.app.Dialog; public setShareContent(param0: com.facebook.share.model.ShareContent<any,any>): void; } export module DeviceShareDialogFragment { export class RequestState { public static class: java.lang.Class<com.facebook.share.internal.DeviceShareDialogFragment.RequestState>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.internal.DeviceShareDialogFragment.RequestState>; public constructor(param0: globalAndroid.os.Parcel); public setExpiresIn(param0: number): void; public describeContents(): number; public getUserCode(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public setUserCode(param0: string): void; public getExpiresIn(): number; } } } } } } declare module com { export module facebook { export module share { export module internal { export class LegacyNativeDialogParameters { public static class: java.lang.Class<com.facebook.share.internal.LegacyNativeDialogParameters>; public constructor(); public static create(param0: java.util.UUID, param1: com.facebook.share.model.ShareContent<any,any>, param2: boolean): globalAndroid.os.Bundle; } } } } } declare module com { export module facebook { export module share { export module internal { export class LikeActionController { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController>; public static ACTION_LIKE_ACTION_CONTROLLER_UPDATED: string; public static ACTION_LIKE_ACTION_CONTROLLER_DID_ERROR: string; public static ACTION_LIKE_ACTION_CONTROLLER_DID_RESET: string; public static ACTION_OBJECT_ID_KEY: string; public static ERROR_INVALID_OBJECT_ID: string; public static ERROR_PUBLISH_ERROR: string; /** @deprecated */ public shouldEnableView(): boolean; /** @deprecated */ public static getControllerForObjectId(param0: string, param1: com.facebook.share.widget.LikeView.ObjectType, param2: com.facebook.share.internal.LikeActionController.CreationCallback): void; /** @deprecated */ public getSocialSentence(): string; /** @deprecated */ public static handleOnActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): boolean; /** @deprecated */ public getLikeCountString(): string; /** @deprecated */ public getObjectId(): string; /** @deprecated */ public toggleLike(param0: globalAndroid.app.Activity, param1: com.facebook.internal.FragmentWrapper, param2: globalAndroid.os.Bundle): void; /** @deprecated */ public isObjectLiked(): boolean; } export module LikeActionController { export abstract class AbstractRequestWrapper extends com.facebook.share.internal.LikeActionController.RequestWrapper { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.AbstractRequestWrapper>; public objectId: string; public objectType: com.facebook.share.widget.LikeView.ObjectType; public error: com.facebook.FacebookRequestError; public addToBatch(param0: com.facebook.GraphRequestBatch): void; public getError(): com.facebook.FacebookRequestError; public constructor(param0: com.facebook.share.internal.LikeActionController, param1: string, param2: com.facebook.share.widget.LikeView.ObjectType); public setRequest(param0: com.facebook.GraphRequest): void; public processError(param0: com.facebook.FacebookRequestError): void; public processSuccess(param0: com.facebook.GraphResponse): void; } export class CreateLikeActionControllerWorkItem { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.CreateLikeActionControllerWorkItem>; public run(): void; } export class CreationCallback { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.CreationCallback>; /** * Constructs a new instance of the com.facebook.share.internal.LikeActionController$CreationCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onComplete(param0: com.facebook.share.internal.LikeActionController, param1: com.facebook.FacebookException): void; }); public constructor(); public onComplete(param0: com.facebook.share.internal.LikeActionController, param1: com.facebook.FacebookException): void; } export class GetEngagementRequestWrapper extends com.facebook.share.internal.LikeActionController.AbstractRequestWrapper { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.GetEngagementRequestWrapper>; public addToBatch(param0: com.facebook.GraphRequestBatch): void; public getError(): com.facebook.FacebookRequestError; public processError(param0: com.facebook.FacebookRequestError): void; public processSuccess(param0: com.facebook.GraphResponse): void; } export class GetOGObjectIdRequestWrapper extends com.facebook.share.internal.LikeActionController.AbstractRequestWrapper { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.GetOGObjectIdRequestWrapper>; public addToBatch(param0: com.facebook.GraphRequestBatch): void; public getError(): com.facebook.FacebookRequestError; public processError(param0: com.facebook.FacebookRequestError): void; public processSuccess(param0: com.facebook.GraphResponse): void; } export class GetOGObjectLikesRequestWrapper extends com.facebook.share.internal.LikeActionController.AbstractRequestWrapper implements com.facebook.share.internal.LikeActionController.LikeRequestWrapper { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.GetOGObjectLikesRequestWrapper>; public getUnlikeToken(): string; public addToBatch(param0: com.facebook.GraphRequestBatch): void; public isObjectLiked(): boolean; public getError(): com.facebook.FacebookRequestError; public processError(param0: com.facebook.FacebookRequestError): void; public processSuccess(param0: com.facebook.GraphResponse): void; } export class GetPageIdRequestWrapper extends com.facebook.share.internal.LikeActionController.AbstractRequestWrapper { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.GetPageIdRequestWrapper>; public addToBatch(param0: com.facebook.GraphRequestBatch): void; public getError(): com.facebook.FacebookRequestError; public processError(param0: com.facebook.FacebookRequestError): void; public processSuccess(param0: com.facebook.GraphResponse): void; } export class GetPageLikesRequestWrapper extends com.facebook.share.internal.LikeActionController.AbstractRequestWrapper implements com.facebook.share.internal.LikeActionController.LikeRequestWrapper { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.GetPageLikesRequestWrapper>; public getUnlikeToken(): string; public addToBatch(param0: com.facebook.GraphRequestBatch): void; public isObjectLiked(): boolean; public getError(): com.facebook.FacebookRequestError; public processError(param0: com.facebook.FacebookRequestError): void; public processSuccess(param0: com.facebook.GraphResponse): void; } export class LikeRequestWrapper extends com.facebook.share.internal.LikeActionController.RequestWrapper { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.LikeRequestWrapper>; /** * Constructs a new instance of the com.facebook.share.internal.LikeActionController$LikeRequestWrapper interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { isObjectLiked(): boolean; getUnlikeToken(): string; getError(): com.facebook.FacebookRequestError; addToBatch(param0: com.facebook.GraphRequestBatch): void; }); public constructor(); public getUnlikeToken(): string; public addToBatch(param0: com.facebook.GraphRequestBatch): void; public isObjectLiked(): boolean; public getError(): com.facebook.FacebookRequestError; } export class MRUCacheWorkItem { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.MRUCacheWorkItem>; public run(): void; } export class PublishLikeRequestWrapper extends com.facebook.share.internal.LikeActionController.AbstractRequestWrapper { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.PublishLikeRequestWrapper>; public addToBatch(param0: com.facebook.GraphRequestBatch): void; public getError(): com.facebook.FacebookRequestError; public processError(param0: com.facebook.FacebookRequestError): void; public processSuccess(param0: com.facebook.GraphResponse): void; } export class PublishUnlikeRequestWrapper extends com.facebook.share.internal.LikeActionController.AbstractRequestWrapper { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.PublishUnlikeRequestWrapper>; public addToBatch(param0: com.facebook.GraphRequestBatch): void; public getError(): com.facebook.FacebookRequestError; public processError(param0: com.facebook.FacebookRequestError): void; public processSuccess(param0: com.facebook.GraphResponse): void; } export class RequestCompletionCallback { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.RequestCompletionCallback>; /** * Constructs a new instance of the com.facebook.share.internal.LikeActionController$RequestCompletionCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onComplete(): void; }); public constructor(); public onComplete(): void; } export class RequestWrapper { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.RequestWrapper>; /** * Constructs a new instance of the com.facebook.share.internal.LikeActionController$RequestWrapper interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getError(): com.facebook.FacebookRequestError; addToBatch(param0: com.facebook.GraphRequestBatch): void; }); public constructor(); public addToBatch(param0: com.facebook.GraphRequestBatch): void; public getError(): com.facebook.FacebookRequestError; } export class SerializeToDiskWorkItem { public static class: java.lang.Class<com.facebook.share.internal.LikeActionController.SerializeToDiskWorkItem>; public run(): void; } } } } } } declare module com { export module facebook { export module share { export module internal { export class LikeBoxCountView { public static class: java.lang.Class<com.facebook.share.internal.LikeBoxCountView>; /** @deprecated */ public setText(param0: string): void; public onDraw(param0: globalAndroid.graphics.Canvas): void; /** @deprecated */ public constructor(param0: globalAndroid.content.Context); /** @deprecated */ public setCaretPosition(param0: com.facebook.share.internal.LikeBoxCountView.LikeBoxCountViewCaretPosition): void; } export module LikeBoxCountView { export class LikeBoxCountViewCaretPosition { public static class: java.lang.Class<com.facebook.share.internal.LikeBoxCountView.LikeBoxCountViewCaretPosition>; public static LEFT: com.facebook.share.internal.LikeBoxCountView.LikeBoxCountViewCaretPosition; public static TOP: com.facebook.share.internal.LikeBoxCountView.LikeBoxCountViewCaretPosition; public static RIGHT: com.facebook.share.internal.LikeBoxCountView.LikeBoxCountViewCaretPosition; public static BOTTOM: com.facebook.share.internal.LikeBoxCountView.LikeBoxCountViewCaretPosition; public static valueOf(param0: string): com.facebook.share.internal.LikeBoxCountView.LikeBoxCountViewCaretPosition; public static values(): androidNative.Array<com.facebook.share.internal.LikeBoxCountView.LikeBoxCountViewCaretPosition>; } } } } } } declare module com { export module facebook { export module share { export module internal { export class LikeButton extends com.facebook.FacebookButtonBase { public static class: java.lang.Class<com.facebook.share.internal.LikeButton>; public getDefaultStyleResource(): number; public getDefaultRequestCode(): number; /** @deprecated */ public constructor(param0: globalAndroid.content.Context, param1: boolean); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet, param2: number, param3: number, param4: string, param5: string); public configureButton(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet, param2: number, param3: number): void; /** @deprecated */ public setSelected(param0: boolean): void; } } } } } declare module com { export module facebook { export module share { export module internal { export class LikeContent extends com.facebook.share.model.ShareModel { public static class: java.lang.Class<com.facebook.share.internal.LikeContent>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.internal.LikeContent>; /** @deprecated */ public getObjectType(): string; /** @deprecated */ public getObjectId(): string; /** @deprecated */ public describeContents(): number; /** @deprecated */ public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } export module LikeContent { export class Builder extends com.facebook.share.model.ShareModelBuilder<com.facebook.share.internal.LikeContent,com.facebook.share.internal.LikeContent.Builder> { public static class: java.lang.Class<com.facebook.share.internal.LikeContent.Builder>; /** @deprecated */ public setObjectType(param0: string): com.facebook.share.internal.LikeContent.Builder; public constructor(); /** @deprecated */ public setObjectId(param0: string): com.facebook.share.internal.LikeContent.Builder; public readFrom(param0: any): any; /** @deprecated */ public readFrom(param0: com.facebook.share.internal.LikeContent): com.facebook.share.internal.LikeContent.Builder; /** @deprecated */ public build(): com.facebook.share.internal.LikeContent; public build(): any; } } } } } } declare module com { export module facebook { export module share { export module internal { export class LikeDialog extends com.facebook.internal.FacebookDialogBase<com.facebook.share.internal.LikeContent,com.facebook.share.internal.LikeDialog.Result> { public static class: java.lang.Class<com.facebook.share.internal.LikeDialog>; /** @deprecated */ public constructor(param0: globalAndroid.app.Activity); public createBaseAppCall(): com.facebook.internal.AppCall; public registerCallbackImpl(param0: com.facebook.internal.CallbackManagerImpl, param1: com.facebook.FacebookCallback<any>): void; public registerCallback(param0: com.facebook.CallbackManager, param1: com.facebook.FacebookCallback<any>, param2: number): void; /** @deprecated */ public constructor(param0: androidx.fragment.app.Fragment); /** @deprecated */ public static canShowWebFallback(): boolean; public registerCallback(param0: com.facebook.CallbackManager, param1: com.facebook.FacebookCallback<any>): void; public getOrderedModeHandlers(): java.util.List<com.facebook.internal.FacebookDialogBase.ModeHandler>; /** @deprecated */ public static canShowNativeDialog(): boolean; public show(param0: any): void; public registerCallbackImpl(param0: com.facebook.internal.CallbackManagerImpl, param1: com.facebook.FacebookCallback<com.facebook.share.internal.LikeDialog.Result>): void; public canShow(param0: any): boolean; /** @deprecated */ public show(param0: com.facebook.share.internal.LikeContent): void; public constructor(param0: globalAndroid.app.Activity, param1: number); public constructor(param0: com.facebook.internal.FragmentWrapper, param1: number); /** @deprecated */ public constructor(param0: globalAndroid.app.Fragment); /** @deprecated */ public constructor(param0: com.facebook.internal.FragmentWrapper); } export module LikeDialog { export class NativeHandler extends com.facebook.internal.FacebookDialogBase.ModeHandler { public static class: java.lang.Class<com.facebook.share.internal.LikeDialog.NativeHandler>; public createAppCall(param0: com.facebook.share.internal.LikeContent): com.facebook.internal.AppCall; public canShow(param0: com.facebook.share.internal.LikeContent, param1: boolean): boolean; public createAppCall(param0: any): com.facebook.internal.AppCall; public canShow(param0: any, param1: boolean): boolean; } export class Result { public static class: java.lang.Class<com.facebook.share.internal.LikeDialog.Result>; public constructor(param0: globalAndroid.os.Bundle); public getData(): globalAndroid.os.Bundle; } export class WebFallbackHandler extends com.facebook.internal.FacebookDialogBase.ModeHandler { public static class: java.lang.Class<com.facebook.share.internal.LikeDialog.WebFallbackHandler>; public createAppCall(param0: com.facebook.share.internal.LikeContent): com.facebook.internal.AppCall; public canShow(param0: com.facebook.share.internal.LikeContent, param1: boolean): boolean; public createAppCall(param0: any): com.facebook.internal.AppCall; public canShow(param0: any, param1: boolean): boolean; } } } } } } declare module com { export module facebook { export module share { export module internal { export class LikeDialogFeature extends com.facebook.internal.DialogFeature { public static class: java.lang.Class<com.facebook.share.internal.LikeDialogFeature>; public static LIKE_DIALOG: com.facebook.share.internal.LikeDialogFeature; public getMinVersion(): number; public name(): string; public static valueOf(param0: string): com.facebook.share.internal.LikeDialogFeature; public static values(): androidNative.Array<com.facebook.share.internal.LikeDialogFeature>; public getAction(): string; } } } } } declare module com { export module facebook { export module share { export module internal { export class LikeStatusClient extends com.facebook.internal.PlatformServiceClient { public static class: java.lang.Class<com.facebook.share.internal.LikeStatusClient>; public populateRequestBundle(param0: globalAndroid.os.Bundle): void; } } } } } declare module com { export module facebook { export module share { export module internal { export class MessengerShareContentUtility { public static class: java.lang.Class<com.facebook.share.internal.MessengerShareContentUtility>; public static FACEBOOK_DOMAIN: java.util.regex.Pattern; public static TITLE: string; public static SUBTITLE: string; public static URL: string; public static IMAGE_URL: string; public static BUTTONS: string; public static FALLBACK_URL: string; public static MESSENGER_EXTENSIONS: string; public static WEBVIEW_SHARE_BUTTON: string; public static SHARABLE: string; public static ATTACHMENT: string; public static ATTACHMENT_ID: string; public static ELEMENTS: string; public static DEFAULT_ACTION: string; public static SHARE_BUTTON_HIDE: string; public static BUTTON_TYPE: string; public static BUTTON_URL_TYPE: string; public static PREVIEW_DEFAULT: string; public static PREVIEW_OPEN_GRAPH: string; public static TEMPLATE_TYPE: string; public static TEMPLATE_GENERIC_TYPE: string; public static TEMPLATE_OPEN_GRAPH_TYPE: string; public static TEMPLATE_MEDIA_TYPE: string; public static ATTACHMENT_TYPE: string; public static ATTACHMENT_PAYLOAD: string; public static ATTACHMENT_TEMPLATE_TYPE: string; public static WEBVIEW_RATIO: string; public static WEBVIEW_RATIO_FULL: string; public static WEBVIEW_RATIO_TALL: string; public static WEBVIEW_RATIO_COMPACT: string; public static IMAGE_ASPECT_RATIO: string; public static IMAGE_RATIO_SQUARE: string; public static IMAGE_RATIO_HORIZONTAL: string; public static MEDIA_TYPE: string; public static MEDIA_VIDEO: string; public static MEDIA_IMAGE: string; public static addGenericTemplateContent(param0: globalAndroid.os.Bundle, param1: com.facebook.share.model.ShareMessengerGenericTemplateContent): void; public constructor(); public static addMediaTemplateContent(param0: globalAndroid.os.Bundle, param1: com.facebook.share.model.ShareMessengerMediaTemplateContent): void; public static addOpenGraphMusicTemplateContent(param0: globalAndroid.os.Bundle, param1: com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent): void; } } } } } declare module com { export module facebook { export module share { export module internal { export class NativeDialogParameters { public static class: java.lang.Class<com.facebook.share.internal.NativeDialogParameters>; public constructor(); public static create(param0: java.util.UUID, param1: com.facebook.share.model.ShareContent<any,any>, param2: boolean): globalAndroid.os.Bundle; } } } } } declare module com { export module facebook { export module share { export module internal { export class OpenGraphActionDialogFeature extends com.facebook.internal.DialogFeature { public static class: java.lang.Class<com.facebook.share.internal.OpenGraphActionDialogFeature>; public static OG_ACTION_DIALOG: com.facebook.share.internal.OpenGraphActionDialogFeature; public getMinVersion(): number; public name(): string; public static valueOf(param0: string): com.facebook.share.internal.OpenGraphActionDialogFeature; public static values(): androidNative.Array<com.facebook.share.internal.OpenGraphActionDialogFeature>; public getAction(): string; } } } } } declare module com { export module facebook { export module share { export module internal { export class OpenGraphJSONUtility { public static class: java.lang.Class<com.facebook.share.internal.OpenGraphJSONUtility>; public static toJSONObject(param0: com.facebook.share.model.ShareOpenGraphAction, param1: com.facebook.share.internal.OpenGraphJSONUtility.PhotoJSONProcessor): org.json.JSONObject; public static toJSONValue(param0: any, param1: com.facebook.share.internal.OpenGraphJSONUtility.PhotoJSONProcessor): any; } export module OpenGraphJSONUtility { export class PhotoJSONProcessor { public static class: java.lang.Class<com.facebook.share.internal.OpenGraphJSONUtility.PhotoJSONProcessor>; /** * Constructs a new instance of the com.facebook.share.internal.OpenGraphJSONUtility$PhotoJSONProcessor interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { toJSONObject(param0: com.facebook.share.model.SharePhoto): org.json.JSONObject; }); public constructor(); public toJSONObject(param0: com.facebook.share.model.SharePhoto): org.json.JSONObject; } } } } } } declare module com { export module facebook { export module share { export module internal { export abstract class ResultProcessor { public static class: java.lang.Class<com.facebook.share.internal.ResultProcessor>; public onError(param0: com.facebook.internal.AppCall, param1: com.facebook.FacebookException): void; public onSuccess(param0: com.facebook.internal.AppCall, param1: globalAndroid.os.Bundle): void; public onCancel(param0: com.facebook.internal.AppCall): void; public constructor(param0: com.facebook.FacebookCallback<any>); } } } } } declare module com { export module facebook { export module share { export module internal { export class ShareConstants { public static class: java.lang.Class<com.facebook.share.internal.ShareConstants>; public static WEB_DIALOG_PARAM_ACTION_TYPE: string; public static WEB_DIALOG_PARAM_DATA: string; public static WEB_DIALOG_PARAM_MESSAGE: string; public static WEB_DIALOG_PARAM_TO: string; public static WEB_DIALOG_PARAM_TITLE: string; public static WEB_DIALOG_PARAM_OBJECT_ID: string; public static WEB_DIALOG_PARAM_FILTERS: string; public static WEB_DIALOG_PARAM_SUGGESTIONS: string; public static WEB_DIALOG_PARAM_HREF: string; public static WEB_DIALOG_PARAM_ACTION_PROPERTIES: string; public static WEB_DIALOG_PARAM_QUOTE: string; public static WEB_DIALOG_PARAM_HASHTAG: string; public static WEB_DIALOG_PARAM_MEDIA: string; public static WEB_DIALOG_PARAM_LINK: string; public static WEB_DIALOG_PARAM_PICTURE: string; public static WEB_DIALOG_PARAM_NAME: string; public static WEB_DIALOG_PARAM_DESCRIPTION: string; public static WEB_DIALOG_PARAM_ID: string; public static WEB_DIALOG_PARAM_PRIVACY: string; public static WEB_DIALOG_RESULT_PARAM_POST_ID: string; public static WEB_DIALOG_RESULT_PARAM_REQUEST_ID: string; public static WEB_DIALOG_RESULT_PARAM_TO_ARRAY_MEMBER: string; public static LEGACY_PLACE_TAG: string; public static LEGACY_FRIEND_TAGS: string; public static LEGACY_LINK: string; public static LEGACY_IMAGE: string; public static LEGACY_TITLE: string; public static LEGACY_DESCRIPTION: string; public static LEGACY_REF: string; public static LEGACY_DATA_FAILURES_FATAL: string; public static LEGACY_PHOTOS: string; public static PLACE_ID: string; public static PEOPLE_IDS: string; public static PAGE_ID: string; public static CONTENT_URL: string; public static MESSENGER_URL: string; public static HASHTAG: string; public static IMAGE_URL: string; public static TITLE: string; public static SUBTITLE: string; public static ITEM_URL: string; public static BUTTON_TITLE: string; public static BUTTON_URL: string; public static PREVIEW_TYPE: string; public static TARGET_DISPLAY: string; public static ATTACHMENT_ID: string; public static OPEN_GRAPH_URL: string; public static DESCRIPTION: string; public static REF: string; public static DATA_FAILURES_FATAL: string; public static PHOTOS: string; public static VIDEO_URL: string; public static QUOTE: string; public static MEDIA: string; public static MESSENGER_PLATFORM_CONTENT: string; public static MEDIA_TYPE: string; public static MEDIA_URI: string; public static MEDIA_EXTENSION: string; public static EFFECT_ID: string; public static EFFECT_ARGS: string; public static EFFECT_TEXTURES: string; public static LEGACY_ACTION: string; public static LEGACY_ACTION_TYPE: string; public static LEGACY_PREVIEW_PROPERTY_NAME: string; public static ACTION: string; public static ACTION_TYPE: string; public static PREVIEW_PROPERTY_NAME: string; public static OBJECT_ID: string; public static OBJECT_TYPE: string; public static APPLINK_URL: string; public static PREVIEW_IMAGE_URL: string; public static PROMO_CODE: string; public static PROMO_TEXT: string; public static DEEPLINK_CONTEXT: string; public static DESTINATION: string; public static EXTRA_OBJECT_ID: string; public static EXTRA_OBJECT_IS_LIKED: string; public static EXTRA_LIKE_COUNT_STRING_WITH_LIKE: string; public static EXTRA_LIKE_COUNT_STRING_WITHOUT_LIKE: string; public static EXTRA_SOCIAL_SENTENCE_WITH_LIKE: string; public static EXTRA_SOCIAL_SENTENCE_WITHOUT_LIKE: string; public static EXTRA_UNLIKE_TOKEN: string; public static EXTRA_RESULT_POST_ID: string; public static RESULT_POST_ID: string; public static MAXIMUM_PHOTO_COUNT: number; public static MAXIMUM_MEDIA_COUNT: number; public static FEED_TO_PARAM: string; public static FEED_LINK_PARAM: string; public static FEED_PICTURE_PARAM: string; public static FEED_SOURCE_PARAM: string; public static FEED_NAME_PARAM: string; public static FEED_CAPTION_PARAM: string; public static FEED_DESCRIPTION_PARAM: string; public static STORY_INTERACTIVE_COLOR_LIST: string; public static STORY_DEEP_LINK_URL: string; public static STORY_BG_ASSET: string; public static STORY_INTERACTIVE_ASSET_URI: string; public constructor(); } } } } } declare module com { export module facebook { export module share { export module internal { export class ShareContentValidation { public static class: java.lang.Class<com.facebook.share.internal.ShareContentValidation>; public static validateMedium(param0: com.facebook.share.model.ShareMedia, param1: com.facebook.share.internal.ShareContentValidation.Validator): void; public static validateForMessage(param0: com.facebook.share.model.ShareContent<any,any>): void; public static validateForNativeShare(param0: com.facebook.share.model.ShareContent<any,any>): void; public constructor(); public static validateForApiShare(param0: com.facebook.share.model.ShareContent<any,any>): void; public static validateForStoryShare(param0: com.facebook.share.model.ShareContent<any,any>): void; public static validateForWebShare(param0: com.facebook.share.model.ShareContent<any,any>): void; } export module ShareContentValidation { export class ApiValidator extends com.facebook.share.internal.ShareContentValidation.Validator { public static class: java.lang.Class<com.facebook.share.internal.ShareContentValidation.ApiValidator>; public validate(param0: com.facebook.share.model.ShareMedia): void; public validate(param0: com.facebook.share.model.ShareMessengerMediaTemplateContent): void; public validate(param0: com.facebook.share.model.SharePhotoContent): void; public validate(param0: com.facebook.share.model.ShareCameraEffectContent): void; public validate(param0: com.facebook.share.model.ShareMediaContent): void; public validate(param0: com.facebook.share.model.ShareStoryContent): void; public validate(param0: com.facebook.share.model.ShareOpenGraphContent): void; public validate(param0: com.facebook.share.model.ShareLinkContent): void; public validate(param0: com.facebook.share.model.ShareVideoContent): void; public validate(param0: com.facebook.share.model.ShareOpenGraphAction): void; public validate(param0: com.facebook.share.model.ShareOpenGraphObject): void; public validate(param0: com.facebook.share.model.SharePhoto): void; public validate(param0: com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent): void; public validate(param0: com.facebook.share.model.ShareMessengerGenericTemplateContent): void; public validate(param0: com.facebook.share.model.ShareVideo): void; public validate(param0: com.facebook.share.model.ShareOpenGraphValueContainer<any,any>, param1: boolean): void; } export class StoryShareValidator extends com.facebook.share.internal.ShareContentValidation.Validator { public static class: java.lang.Class<com.facebook.share.internal.ShareContentValidation.StoryShareValidator>; public validate(param0: com.facebook.share.model.ShareMedia): void; public validate(param0: com.facebook.share.model.ShareMessengerMediaTemplateContent): void; public validate(param0: com.facebook.share.model.SharePhotoContent): void; public validate(param0: com.facebook.share.model.ShareCameraEffectContent): void; public validate(param0: com.facebook.share.model.ShareMediaContent): void; public validate(param0: com.facebook.share.model.ShareStoryContent): void; public validate(param0: com.facebook.share.model.ShareOpenGraphContent): void; public validate(param0: com.facebook.share.model.ShareLinkContent): void; public validate(param0: com.facebook.share.model.ShareVideoContent): void; public validate(param0: com.facebook.share.model.ShareOpenGraphAction): void; public validate(param0: com.facebook.share.model.ShareOpenGraphObject): void; public validate(param0: com.facebook.share.model.SharePhoto): void; public validate(param0: com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent): void; public validate(param0: com.facebook.share.model.ShareMessengerGenericTemplateContent): void; public validate(param0: com.facebook.share.model.ShareVideo): void; public validate(param0: com.facebook.share.model.ShareOpenGraphValueContainer<any,any>, param1: boolean): void; } export class Validator { public static class: java.lang.Class<com.facebook.share.internal.ShareContentValidation.Validator>; public validate(param0: com.facebook.share.model.ShareMedia): void; public validate(param0: com.facebook.share.model.ShareMessengerMediaTemplateContent): void; public validate(param0: com.facebook.share.model.SharePhotoContent): void; public validate(param0: com.facebook.share.model.ShareCameraEffectContent): void; public validate(param0: com.facebook.share.model.ShareMediaContent): void; public validate(param0: com.facebook.share.model.ShareStoryContent): void; public validate(param0: com.facebook.share.model.ShareOpenGraphContent): void; public validate(param0: com.facebook.share.model.ShareLinkContent): void; public validate(param0: com.facebook.share.model.ShareVideoContent): void; public validate(param0: com.facebook.share.model.ShareOpenGraphAction): void; public isOpenGraphContent(): boolean; public validate(param0: com.facebook.share.model.ShareOpenGraphObject): void; public validate(param0: com.facebook.share.model.SharePhoto): void; public validate(param0: com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent): void; public validate(param0: com.facebook.share.model.ShareMessengerGenericTemplateContent): void; public validate(param0: com.facebook.share.model.ShareVideo): void; public validate(param0: com.facebook.share.model.ShareOpenGraphValueContainer<any,any>, param1: boolean): void; } export class WebShareValidator extends com.facebook.share.internal.ShareContentValidation.Validator { public static class: java.lang.Class<com.facebook.share.internal.ShareContentValidation.WebShareValidator>; public validate(param0: com.facebook.share.model.ShareMedia): void; public validate(param0: com.facebook.share.model.ShareMessengerMediaTemplateContent): void; public validate(param0: com.facebook.share.model.SharePhotoContent): void; public validate(param0: com.facebook.share.model.ShareCameraEffectContent): void; public validate(param0: com.facebook.share.model.ShareMediaContent): void; public validate(param0: com.facebook.share.model.ShareStoryContent): void; public validate(param0: com.facebook.share.model.ShareOpenGraphContent): void; public validate(param0: com.facebook.share.model.ShareLinkContent): void; public validate(param0: com.facebook.share.model.ShareVideoContent): void; public validate(param0: com.facebook.share.model.ShareOpenGraphAction): void; public validate(param0: com.facebook.share.model.ShareOpenGraphObject): void; public validate(param0: com.facebook.share.model.SharePhoto): void; public validate(param0: com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent): void; public validate(param0: com.facebook.share.model.ShareMessengerGenericTemplateContent): void; public validate(param0: com.facebook.share.model.ShareVideo): void; public validate(param0: com.facebook.share.model.ShareOpenGraphValueContainer<any,any>, param1: boolean): void; } } } } } } declare module com { export module facebook { export module share { export module internal { export class ShareDialogFeature extends com.facebook.internal.DialogFeature { public static class: java.lang.Class<com.facebook.share.internal.ShareDialogFeature>; public static SHARE_DIALOG: com.facebook.share.internal.ShareDialogFeature; public static PHOTOS: com.facebook.share.internal.ShareDialogFeature; public static VIDEO: com.facebook.share.internal.ShareDialogFeature; public static MULTIMEDIA: com.facebook.share.internal.ShareDialogFeature; public static HASHTAG: com.facebook.share.internal.ShareDialogFeature; public static LINK_SHARE_QUOTES: com.facebook.share.internal.ShareDialogFeature; public getMinVersion(): number; public name(): string; public static valueOf(param0: string): com.facebook.share.internal.ShareDialogFeature; public static values(): androidNative.Array<com.facebook.share.internal.ShareDialogFeature>; public getAction(): string; } } } } } declare module com { export module facebook { export module share { export module internal { export class ShareFeedContent extends com.facebook.share.model.ShareContent<com.facebook.share.internal.ShareFeedContent,com.facebook.share.internal.ShareFeedContent.Builder> { public static class: java.lang.Class<com.facebook.share.internal.ShareFeedContent>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.internal.ShareFeedContent>; public getPicture(): string; public getLinkName(): string; public describeContents(): number; public getLink(): string; public getLinkCaption(): string; public getLinkDescription(): string; public getToId(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getMediaSource(): string; } export module ShareFeedContent { export class Builder extends com.facebook.share.model.ShareContent.Builder<com.facebook.share.internal.ShareFeedContent,com.facebook.share.internal.ShareFeedContent.Builder> { public static class: java.lang.Class<com.facebook.share.internal.ShareFeedContent.Builder>; public constructor(); public setLinkCaption(param0: string): com.facebook.share.internal.ShareFeedContent.Builder; public readFrom(param0: any): any; public readFrom(param0: com.facebook.share.internal.ShareFeedContent): com.facebook.share.internal.ShareFeedContent.Builder; public setPicture(param0: string): com.facebook.share.internal.ShareFeedContent.Builder; public build(): com.facebook.share.internal.ShareFeedContent; public setToId(param0: string): com.facebook.share.internal.ShareFeedContent.Builder; public setLink(param0: string): com.facebook.share.internal.ShareFeedContent.Builder; public setLinkName(param0: string): com.facebook.share.internal.ShareFeedContent.Builder; public setMediaSource(param0: string): com.facebook.share.internal.ShareFeedContent.Builder; public setLinkDescription(param0: string): com.facebook.share.internal.ShareFeedContent.Builder; } } } } } } declare module com { export module facebook { export module share { export module internal { export class ShareInternalUtility { public static class: java.lang.Class<com.facebook.share.internal.ShareInternalUtility>; public static MY_PHOTOS: string; public static getTextureUrlBundle(param0: com.facebook.share.model.ShareCameraEffectContent, param1: java.util.UUID): globalAndroid.os.Bundle; public static registerStaticShareCallback(param0: number): void; public static invokeCallbackWithException(param0: com.facebook.FacebookCallback<com.facebook.share.Sharer.Result>, param1: java.lang.Exception): void; public static getFieldNameAndNamespaceFromFullName(param0: string): globalAndroid.util.Pair<string,string>; public constructor(); public static getPhotoUrls(param0: com.facebook.share.model.SharePhotoContent, param1: java.util.UUID): java.util.List<string>; public static getMediaInfos(param0: com.facebook.share.model.ShareMediaContent, param1: java.util.UUID): java.util.List<globalAndroid.os.Bundle>; public static getShareDialogPostId(param0: globalAndroid.os.Bundle): string; public static newUploadStagingResourceWithImageRequest(param0: com.facebook.AccessToken, param1: globalAndroid.graphics.Bitmap, param2: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public static getStickerUrl(param0: com.facebook.share.model.ShareStoryContent, param1: java.util.UUID): globalAndroid.os.Bundle; public static getNativeDialogCompletionGesture(param0: globalAndroid.os.Bundle): string; public static getBackgroundAssetMediaInfo(param0: com.facebook.share.model.ShareStoryContent, param1: java.util.UUID): globalAndroid.os.Bundle; public static getUriExtension(param0: globalAndroid.net.Uri): string; public static newUploadStagingResourceWithImageRequest(param0: com.facebook.AccessToken, param1: globalAndroid.net.Uri, param2: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; public static getMostSpecificObjectType(param0: com.facebook.share.widget.LikeView.ObjectType, param1: com.facebook.share.widget.LikeView.ObjectType): com.facebook.share.widget.LikeView.ObjectType; public static toJSONObjectForWeb(param0: com.facebook.share.model.ShareOpenGraphContent): org.json.JSONObject; public static removeNamespacesFromOGJsonArray(param0: org.json.JSONArray, param1: boolean): org.json.JSONArray; public static handleActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent, param3: com.facebook.share.internal.ResultProcessor): boolean; public static registerSharerCallback(param0: number, param1: com.facebook.CallbackManager, param2: com.facebook.FacebookCallback<com.facebook.share.Sharer.Result>): void; public static getVideoUrl(param0: com.facebook.share.model.ShareVideoContent, param1: java.util.UUID): string; public static removeNamespacesFromOGJsonObject(param0: org.json.JSONObject, param1: boolean): org.json.JSONObject; public static invokeCallbackWithResults(param0: com.facebook.FacebookCallback<com.facebook.share.Sharer.Result>, param1: string, param2: com.facebook.GraphResponse): void; public static toJSONObjectForCall(param0: java.util.UUID, param1: com.facebook.share.model.ShareOpenGraphContent): org.json.JSONObject; public static invokeCallbackWithError(param0: com.facebook.FacebookCallback<com.facebook.share.Sharer.Result>, param1: string): void; public static getShareResultProcessor(param0: com.facebook.FacebookCallback<com.facebook.share.Sharer.Result>): com.facebook.share.internal.ResultProcessor; public static newUploadStagingResourceWithImageRequest(param0: com.facebook.AccessToken, param1: java.io.File, param2: com.facebook.GraphRequest.Callback): com.facebook.GraphRequest; } } } } } declare module com { export module facebook { export module share { export module internal { export class ShareStoryFeature extends com.facebook.internal.DialogFeature { public static class: java.lang.Class<com.facebook.share.internal.ShareStoryFeature>; public static SHARE_STORY_ASSET: com.facebook.share.internal.ShareStoryFeature; public getMinVersion(): number; public name(): string; public static values(): androidNative.Array<com.facebook.share.internal.ShareStoryFeature>; public static valueOf(param0: string): com.facebook.share.internal.ShareStoryFeature; public getAction(): string; } } } } } declare module com { export module facebook { export module share { export module internal { export class WebDialogParameters { public static class: java.lang.Class<com.facebook.share.internal.WebDialogParameters>; public static create(param0: com.facebook.share.model.ShareOpenGraphContent): globalAndroid.os.Bundle; public static create(param0: com.facebook.share.model.GameRequestContent): globalAndroid.os.Bundle; public static createBaseParameters(param0: com.facebook.share.model.ShareContent<any,any>): globalAndroid.os.Bundle; public static createForFeed(param0: com.facebook.share.internal.ShareFeedContent): globalAndroid.os.Bundle; public constructor(); public static create(param0: com.facebook.share.model.ShareLinkContent): globalAndroid.os.Bundle; public static create(param0: com.facebook.share.model.SharePhotoContent): globalAndroid.os.Bundle; public static createForFeed(param0: com.facebook.share.model.ShareLinkContent): globalAndroid.os.Bundle; public static create(param0: com.facebook.share.model.AppGroupCreationContent): globalAndroid.os.Bundle; } } } } } declare module com { export module facebook { export module share { export module model { export class AppGroupCreationContent extends com.facebook.share.model.ShareModel { public static class: java.lang.Class<com.facebook.share.model.AppGroupCreationContent>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.AppGroupCreationContent>; public getName(): string; public getAppGroupPrivacy(): com.facebook.share.model.AppGroupCreationContent.AppGroupPrivacy; public describeContents(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getDescription(): string; } export module AppGroupCreationContent { export class AppGroupPrivacy { public static class: java.lang.Class<com.facebook.share.model.AppGroupCreationContent.AppGroupPrivacy>; public static Open: com.facebook.share.model.AppGroupCreationContent.AppGroupPrivacy; public static Closed: com.facebook.share.model.AppGroupCreationContent.AppGroupPrivacy; public static values(): androidNative.Array<com.facebook.share.model.AppGroupCreationContent.AppGroupPrivacy>; public static valueOf(param0: string): com.facebook.share.model.AppGroupCreationContent.AppGroupPrivacy; } export class Builder extends com.facebook.share.model.ShareModelBuilder<com.facebook.share.model.AppGroupCreationContent,com.facebook.share.model.AppGroupCreationContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.AppGroupCreationContent.Builder>; public constructor(); public setDescription(param0: string): com.facebook.share.model.AppGroupCreationContent.Builder; public readFrom(param0: any): any; public setAppGroupPrivacy(param0: com.facebook.share.model.AppGroupCreationContent.AppGroupPrivacy): com.facebook.share.model.AppGroupCreationContent.Builder; public build(): com.facebook.share.model.AppGroupCreationContent; public setName(param0: string): com.facebook.share.model.AppGroupCreationContent.Builder; public readFrom(param0: com.facebook.share.model.AppGroupCreationContent): com.facebook.share.model.AppGroupCreationContent.Builder; public build(): any; } } } } } } declare module com { export module facebook { export module share { export module model { export class CameraEffectArguments extends com.facebook.share.model.ShareModel { public static class: java.lang.Class<com.facebook.share.model.CameraEffectArguments>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.CameraEffectArguments>; public get(param0: string): any; public describeContents(): number; public getStringArray(param0: string): androidNative.Array<string>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getString(param0: string): string; public keySet(): java.util.Set<string>; } export module CameraEffectArguments { export class Builder extends com.facebook.share.model.ShareModelBuilder<com.facebook.share.model.CameraEffectArguments,com.facebook.share.model.CameraEffectArguments.Builder> { public static class: java.lang.Class<com.facebook.share.model.CameraEffectArguments.Builder>; public readFrom(param0: com.facebook.share.model.CameraEffectArguments): com.facebook.share.model.CameraEffectArguments.Builder; public constructor(); public readFrom(param0: any): any; public readFrom(param0: globalAndroid.os.Parcel): com.facebook.share.model.CameraEffectArguments.Builder; public putArgument(param0: string, param1: androidNative.Array<string>): com.facebook.share.model.CameraEffectArguments.Builder; public build(): com.facebook.share.model.CameraEffectArguments; public putArgument(param0: string, param1: string): com.facebook.share.model.CameraEffectArguments.Builder; public build(): any; } } } } } } declare module com { export module facebook { export module share { export module model { export class CameraEffectTextures extends com.facebook.share.model.ShareModel { public static class: java.lang.Class<com.facebook.share.model.CameraEffectTextures>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.CameraEffectTextures>; public getTextureBitmap(param0: string): globalAndroid.graphics.Bitmap; public get(param0: string): any; public describeContents(): number; public getTextureUri(param0: string): globalAndroid.net.Uri; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public keySet(): java.util.Set<string>; } export module CameraEffectTextures { export class Builder extends com.facebook.share.model.ShareModelBuilder<com.facebook.share.model.CameraEffectTextures,com.facebook.share.model.CameraEffectTextures.Builder> { public static class: java.lang.Class<com.facebook.share.model.CameraEffectTextures.Builder>; public readFrom(param0: globalAndroid.os.Parcel): com.facebook.share.model.CameraEffectTextures.Builder; public constructor(); public readFrom(param0: any): any; public putTexture(param0: string, param1: globalAndroid.graphics.Bitmap): com.facebook.share.model.CameraEffectTextures.Builder; public readFrom(param0: com.facebook.share.model.CameraEffectTextures): com.facebook.share.model.CameraEffectTextures.Builder; public build(): com.facebook.share.model.CameraEffectTextures; public putTexture(param0: string, param1: globalAndroid.net.Uri): com.facebook.share.model.CameraEffectTextures.Builder; public build(): any; } } } } } } declare module com { export module facebook { export module share { export module model { export class GameRequestContent extends com.facebook.share.model.ShareModel { public static class: java.lang.Class<com.facebook.share.model.GameRequestContent>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.GameRequestContent>; public getTitle(): string; public getData(): string; /** @deprecated */ public getTo(): string; public getActionType(): com.facebook.share.model.GameRequestContent.ActionType; public getRecipients(): java.util.List<string>; public describeContents(): number; public getMessage(): string; public getCta(): string; public getSuggestions(): java.util.List<string>; public getObjectId(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getFilters(): com.facebook.share.model.GameRequestContent.Filters; } export module GameRequestContent { export class ActionType { public static class: java.lang.Class<com.facebook.share.model.GameRequestContent.ActionType>; public static SEND: com.facebook.share.model.GameRequestContent.ActionType; public static ASKFOR: com.facebook.share.model.GameRequestContent.ActionType; public static TURN: com.facebook.share.model.GameRequestContent.ActionType; public static INVITE: com.facebook.share.model.GameRequestContent.ActionType; public static valueOf(param0: string): com.facebook.share.model.GameRequestContent.ActionType; public static values(): androidNative.Array<com.facebook.share.model.GameRequestContent.ActionType>; } export class Builder extends com.facebook.share.model.ShareModelBuilder<com.facebook.share.model.GameRequestContent,com.facebook.share.model.GameRequestContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.GameRequestContent.Builder>; public setMessage(param0: string): com.facebook.share.model.GameRequestContent.Builder; public setRecipients(param0: java.util.List<string>): com.facebook.share.model.GameRequestContent.Builder; public constructor(); public setTitle(param0: string): com.facebook.share.model.GameRequestContent.Builder; public readFrom(param0: any): any; public setData(param0: string): com.facebook.share.model.GameRequestContent.Builder; public build(): any; public setFilters(param0: com.facebook.share.model.GameRequestContent.Filters): com.facebook.share.model.GameRequestContent.Builder; public setCta(param0: string): com.facebook.share.model.GameRequestContent.Builder; /** @deprecated */ public setTo(param0: string): com.facebook.share.model.GameRequestContent.Builder; public setSuggestions(param0: java.util.List<string>): com.facebook.share.model.GameRequestContent.Builder; public build(): com.facebook.share.model.GameRequestContent; public setActionType(param0: com.facebook.share.model.GameRequestContent.ActionType): com.facebook.share.model.GameRequestContent.Builder; public readFrom(param0: com.facebook.share.model.GameRequestContent): com.facebook.share.model.GameRequestContent.Builder; public setObjectId(param0: string): com.facebook.share.model.GameRequestContent.Builder; } export class Filters { public static class: java.lang.Class<com.facebook.share.model.GameRequestContent.Filters>; public static APP_USERS: com.facebook.share.model.GameRequestContent.Filters; public static APP_NON_USERS: com.facebook.share.model.GameRequestContent.Filters; public static EVERYBODY: com.facebook.share.model.GameRequestContent.Filters; public static values(): androidNative.Array<com.facebook.share.model.GameRequestContent.Filters>; public static valueOf(param0: string): com.facebook.share.model.GameRequestContent.Filters; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareCameraEffectContent extends com.facebook.share.model.ShareContent<com.facebook.share.model.ShareCameraEffectContent,com.facebook.share.model.ShareCameraEffectContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareCameraEffectContent>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareCameraEffectContent>; public getArguments(): com.facebook.share.model.CameraEffectArguments; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getTextures(): com.facebook.share.model.CameraEffectTextures; public getEffectId(): string; } export module ShareCameraEffectContent { export class Builder extends com.facebook.share.model.ShareContent.Builder<com.facebook.share.model.ShareCameraEffectContent,com.facebook.share.model.ShareCameraEffectContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareCameraEffectContent.Builder>; public build(): com.facebook.share.model.ShareCameraEffectContent; public readFrom(param0: com.facebook.share.model.ShareCameraEffectContent): com.facebook.share.model.ShareCameraEffectContent.Builder; public constructor(); public readFrom(param0: any): any; public setArguments(param0: com.facebook.share.model.CameraEffectArguments): com.facebook.share.model.ShareCameraEffectContent.Builder; public setTextures(param0: com.facebook.share.model.CameraEffectTextures): com.facebook.share.model.ShareCameraEffectContent.Builder; public setEffectId(param0: string): com.facebook.share.model.ShareCameraEffectContent.Builder; } } } } } } declare module com { export module facebook { export module share { export module model { export abstract class ShareContent<P, E> extends com.facebook.share.model.ShareModel { public static class: java.lang.Class<com.facebook.share.model.ShareContent<any,any>>; public getPlaceId(): string; public constructor(param0: globalAndroid.os.Parcel); public constructor(param0: com.facebook.share.model.ShareContent.Builder<any,any>); public getRef(): string; public getContentUrl(): globalAndroid.net.Uri; public getPeopleIds(): java.util.List<string>; public describeContents(): number; public getPageId(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getShareHashtag(): com.facebook.share.model.ShareHashtag; } export module ShareContent { export abstract class Builder<P, E> extends com.facebook.share.model.ShareModelBuilder<any,any> { public static class: java.lang.Class<com.facebook.share.model.ShareContent.Builder<any,any>>; public constructor(); public readFrom(param0: any): any; public setPeopleIds(param0: java.util.List<string>): any; public setShareHashtag(param0: com.facebook.share.model.ShareHashtag): any; public setPageId(param0: string): any; public setContentUrl(param0: globalAndroid.net.Uri): any; public setPlaceId(param0: string): any; public setRef(param0: string): any; public build(): any; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareHashtag extends com.facebook.share.model.ShareModel { public static class: java.lang.Class<com.facebook.share.model.ShareHashtag>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareHashtag>; public describeContents(): number; public getHashtag(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } export module ShareHashtag { export class Builder extends com.facebook.share.model.ShareModelBuilder<com.facebook.share.model.ShareHashtag,com.facebook.share.model.ShareHashtag.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareHashtag.Builder>; public constructor(); public readFrom(param0: any): any; public getHashtag(): string; public build(): com.facebook.share.model.ShareHashtag; public readFrom(param0: com.facebook.share.model.ShareHashtag): com.facebook.share.model.ShareHashtag.Builder; public setHashtag(param0: string): com.facebook.share.model.ShareHashtag.Builder; public build(): any; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareLinkContent extends com.facebook.share.model.ShareContent<com.facebook.share.model.ShareLinkContent,com.facebook.share.model.ShareLinkContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareLinkContent>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareLinkContent>; /** @deprecated */ public getContentDescription(): string; /** @deprecated */ public getContentTitle(): string; public getQuote(): string; public describeContents(): number; /** @deprecated */ public getImageUrl(): globalAndroid.net.Uri; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } export module ShareLinkContent { export class Builder extends com.facebook.share.model.ShareContent.Builder<com.facebook.share.model.ShareLinkContent,com.facebook.share.model.ShareLinkContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareLinkContent.Builder>; public setQuote(param0: string): com.facebook.share.model.ShareLinkContent.Builder; public constructor(); /** @deprecated */ public setContentDescription(param0: string): com.facebook.share.model.ShareLinkContent.Builder; public readFrom(param0: any): any; public build(): com.facebook.share.model.ShareLinkContent; /** @deprecated */ public setImageUrl(param0: globalAndroid.net.Uri): com.facebook.share.model.ShareLinkContent.Builder; public readFrom(param0: com.facebook.share.model.ShareLinkContent): com.facebook.share.model.ShareLinkContent.Builder; /** @deprecated */ public setContentTitle(param0: string): com.facebook.share.model.ShareLinkContent.Builder; } } } } } } declare module com { export module facebook { export module share { export module model { export abstract class ShareMedia extends com.facebook.share.model.ShareModel { public static class: java.lang.Class<com.facebook.share.model.ShareMedia>; /** @deprecated */ public getParameters(): globalAndroid.os.Bundle; public describeContents(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: com.facebook.share.model.ShareMedia.Builder<any,any>); public getMediaType(): com.facebook.share.model.ShareMedia.Type; } export module ShareMedia { export abstract class Builder<M, B> extends com.facebook.share.model.ShareModelBuilder<any,any> { public static class: java.lang.Class<com.facebook.share.model.ShareMedia.Builder<any,any>>; public constructor(); /** @deprecated */ public setParameter(param0: string, param1: string): any; /** @deprecated */ public setParameters(param0: globalAndroid.os.Bundle): any; public readFrom(param0: any): any; public build(): any; } export class Type { public static class: java.lang.Class<com.facebook.share.model.ShareMedia.Type>; public static PHOTO: com.facebook.share.model.ShareMedia.Type; public static VIDEO: com.facebook.share.model.ShareMedia.Type; public static values(): androidNative.Array<com.facebook.share.model.ShareMedia.Type>; public static valueOf(param0: string): com.facebook.share.model.ShareMedia.Type; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareMediaContent extends com.facebook.share.model.ShareContent<com.facebook.share.model.ShareMediaContent,com.facebook.share.model.ShareMediaContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareMediaContent>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareMediaContent>; public getMedia(): java.util.List<com.facebook.share.model.ShareMedia>; public describeContents(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } export module ShareMediaContent { export class Builder extends com.facebook.share.model.ShareContent.Builder<com.facebook.share.model.ShareMediaContent,com.facebook.share.model.ShareMediaContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareMediaContent.Builder>; public addMedium(param0: com.facebook.share.model.ShareMedia): com.facebook.share.model.ShareMediaContent.Builder; public readFrom(param0: com.facebook.share.model.ShareMediaContent): com.facebook.share.model.ShareMediaContent.Builder; public constructor(); public build(): com.facebook.share.model.ShareMediaContent; public readFrom(param0: any): any; public setMedia(param0: java.util.List<com.facebook.share.model.ShareMedia>): com.facebook.share.model.ShareMediaContent.Builder; public addMedia(param0: java.util.List<com.facebook.share.model.ShareMedia>): com.facebook.share.model.ShareMediaContent.Builder; } } } } } } declare module com { export module facebook { export module share { export module model { export abstract class ShareMessengerActionButton extends com.facebook.share.model.ShareModel { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerActionButton>; public getTitle(): string; public constructor(param0: com.facebook.share.model.ShareMessengerActionButton.Builder<any,any>); public describeContents(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } export module ShareMessengerActionButton { export abstract class Builder<M, B> extends com.facebook.share.model.ShareModelBuilder<any,any> { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerActionButton.Builder<any,any>>; public constructor(); public readFrom(param0: any): any; public setTitle(param0: string): any; public build(): any; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareMessengerGenericTemplateContent extends com.facebook.share.model.ShareContent<com.facebook.share.model.ShareMessengerGenericTemplateContent,com.facebook.share.model.ShareMessengerGenericTemplateContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerGenericTemplateContent>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareMessengerGenericTemplateContent>; public constructor(param0: globalAndroid.os.Parcel); public constructor(param0: com.facebook.share.model.ShareContent.Builder<any,any>); public describeContents(): number; public constructor(param0: com.facebook.share.model.ShareMessengerGenericTemplateContent.Builder); public getIsSharable(): boolean; public getGenericTemplateElement(): com.facebook.share.model.ShareMessengerGenericTemplateElement; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getImageAspectRatio(): com.facebook.share.model.ShareMessengerGenericTemplateContent.ImageAspectRatio; } export module ShareMessengerGenericTemplateContent { export class Builder extends com.facebook.share.model.ShareContent.Builder<com.facebook.share.model.ShareMessengerGenericTemplateContent,com.facebook.share.model.ShareMessengerGenericTemplateContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerGenericTemplateContent.Builder>; public setImageAspectRatio(param0: com.facebook.share.model.ShareMessengerGenericTemplateContent.ImageAspectRatio): com.facebook.share.model.ShareMessengerGenericTemplateContent.Builder; public constructor(); public setGenericTemplateElement(param0: com.facebook.share.model.ShareMessengerGenericTemplateElement): com.facebook.share.model.ShareMessengerGenericTemplateContent.Builder; public readFrom(param0: any): any; public build(): com.facebook.share.model.ShareMessengerGenericTemplateContent; public readFrom(param0: com.facebook.share.model.ShareMessengerGenericTemplateContent): com.facebook.share.model.ShareMessengerGenericTemplateContent.Builder; public setIsSharable(param0: boolean): com.facebook.share.model.ShareMessengerGenericTemplateContent.Builder; } export class ImageAspectRatio { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerGenericTemplateContent.ImageAspectRatio>; public static HORIZONTAL: com.facebook.share.model.ShareMessengerGenericTemplateContent.ImageAspectRatio; public static SQUARE: com.facebook.share.model.ShareMessengerGenericTemplateContent.ImageAspectRatio; public static values(): androidNative.Array<com.facebook.share.model.ShareMessengerGenericTemplateContent.ImageAspectRatio>; public static valueOf(param0: string): com.facebook.share.model.ShareMessengerGenericTemplateContent.ImageAspectRatio; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareMessengerGenericTemplateElement extends com.facebook.share.model.ShareModel { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerGenericTemplateElement>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareMessengerGenericTemplateElement>; public getTitle(): string; public getImageUrl(): globalAndroid.net.Uri; public getSubtitle(): string; public getDefaultAction(): com.facebook.share.model.ShareMessengerActionButton; public describeContents(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getButton(): com.facebook.share.model.ShareMessengerActionButton; } export module ShareMessengerGenericTemplateElement { export class Builder extends com.facebook.share.model.ShareModelBuilder<com.facebook.share.model.ShareMessengerGenericTemplateElement,com.facebook.share.model.ShareMessengerGenericTemplateElement.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerGenericTemplateElement.Builder>; public setDefaultAction(param0: com.facebook.share.model.ShareMessengerActionButton): com.facebook.share.model.ShareMessengerGenericTemplateElement.Builder; public build(): com.facebook.share.model.ShareMessengerGenericTemplateElement; public constructor(); public setTitle(param0: string): com.facebook.share.model.ShareMessengerGenericTemplateElement.Builder; public setSubtitle(param0: string): com.facebook.share.model.ShareMessengerGenericTemplateElement.Builder; public readFrom(param0: any): any; public setImageUrl(param0: globalAndroid.net.Uri): com.facebook.share.model.ShareMessengerGenericTemplateElement.Builder; public setButton(param0: com.facebook.share.model.ShareMessengerActionButton): com.facebook.share.model.ShareMessengerGenericTemplateElement.Builder; public readFrom(param0: com.facebook.share.model.ShareMessengerGenericTemplateElement): com.facebook.share.model.ShareMessengerGenericTemplateElement.Builder; public build(): any; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareMessengerMediaTemplateContent extends com.facebook.share.model.ShareContent<com.facebook.share.model.ShareMessengerMediaTemplateContent,com.facebook.share.model.ShareMessengerMediaTemplateContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerMediaTemplateContent>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareMessengerMediaTemplateContent>; public describeContents(): number; public getMediaType(): com.facebook.share.model.ShareMessengerMediaTemplateContent.MediaType; public getMediaUrl(): globalAndroid.net.Uri; public getAttachmentId(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getButton(): com.facebook.share.model.ShareMessengerActionButton; } export module ShareMessengerMediaTemplateContent { export class Builder extends com.facebook.share.model.ShareContent.Builder<com.facebook.share.model.ShareMessengerMediaTemplateContent,com.facebook.share.model.ShareMessengerMediaTemplateContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerMediaTemplateContent.Builder>; public setMediaUrl(param0: globalAndroid.net.Uri): com.facebook.share.model.ShareMessengerMediaTemplateContent.Builder; public constructor(); public setButton(param0: com.facebook.share.model.ShareMessengerActionButton): com.facebook.share.model.ShareMessengerMediaTemplateContent.Builder; public readFrom(param0: any): any; public setAttachmentId(param0: string): com.facebook.share.model.ShareMessengerMediaTemplateContent.Builder; public build(): com.facebook.share.model.ShareMessengerMediaTemplateContent; public readFrom(param0: com.facebook.share.model.ShareMessengerMediaTemplateContent): com.facebook.share.model.ShareMessengerMediaTemplateContent.Builder; public setMediaType(param0: com.facebook.share.model.ShareMessengerMediaTemplateContent.MediaType): com.facebook.share.model.ShareMessengerMediaTemplateContent.Builder; } export class MediaType { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerMediaTemplateContent.MediaType>; public static IMAGE: com.facebook.share.model.ShareMessengerMediaTemplateContent.MediaType; public static VIDEO: com.facebook.share.model.ShareMessengerMediaTemplateContent.MediaType; public static values(): androidNative.Array<com.facebook.share.model.ShareMessengerMediaTemplateContent.MediaType>; public static valueOf(param0: string): com.facebook.share.model.ShareMessengerMediaTemplateContent.MediaType; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareMessengerOpenGraphMusicTemplateContent extends com.facebook.share.model.ShareContent<com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent,com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent>; public describeContents(): number; public getUrl(): globalAndroid.net.Uri; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getButton(): com.facebook.share.model.ShareMessengerActionButton; } export module ShareMessengerOpenGraphMusicTemplateContent { export class Builder extends com.facebook.share.model.ShareContent.Builder<com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent,com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent.Builder>; public constructor(); public readFrom(param0: com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent): com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent.Builder; public setButton(param0: com.facebook.share.model.ShareMessengerActionButton): com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent.Builder; public readFrom(param0: any): any; public setUrl(param0: globalAndroid.net.Uri): com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent.Builder; public build(): com.facebook.share.model.ShareMessengerOpenGraphMusicTemplateContent; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareMessengerURLActionButton extends com.facebook.share.model.ShareMessengerActionButton { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerURLActionButton>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareMessengerURLActionButton>; public getWebviewHeightRatio(): com.facebook.share.model.ShareMessengerURLActionButton.WebviewHeightRatio; public getIsMessengerExtensionURL(): boolean; public getUrl(): globalAndroid.net.Uri; public getShouldHideWebviewShareButton(): boolean; public getFallbackUrl(): globalAndroid.net.Uri; } export module ShareMessengerURLActionButton { export class Builder extends com.facebook.share.model.ShareMessengerActionButton.Builder<com.facebook.share.model.ShareMessengerURLActionButton,com.facebook.share.model.ShareMessengerURLActionButton.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerURLActionButton.Builder>; public setFallbackUrl(param0: globalAndroid.net.Uri): com.facebook.share.model.ShareMessengerURLActionButton.Builder; public constructor(); public setWebviewHeightRatio(param0: com.facebook.share.model.ShareMessengerURLActionButton.WebviewHeightRatio): com.facebook.share.model.ShareMessengerURLActionButton.Builder; public build(): com.facebook.share.model.ShareMessengerURLActionButton; public readFrom(param0: any): any; public setUrl(param0: globalAndroid.net.Uri): com.facebook.share.model.ShareMessengerURLActionButton.Builder; public setIsMessengerExtensionURL(param0: boolean): com.facebook.share.model.ShareMessengerURLActionButton.Builder; public readFrom(param0: com.facebook.share.model.ShareMessengerURLActionButton): com.facebook.share.model.ShareMessengerURLActionButton.Builder; public setShouldHideWebviewShareButton(param0: boolean): com.facebook.share.model.ShareMessengerURLActionButton.Builder; } export class WebviewHeightRatio { public static class: java.lang.Class<com.facebook.share.model.ShareMessengerURLActionButton.WebviewHeightRatio>; public static WebviewHeightRatioFull: com.facebook.share.model.ShareMessengerURLActionButton.WebviewHeightRatio; public static WebviewHeightRatioTall: com.facebook.share.model.ShareMessengerURLActionButton.WebviewHeightRatio; public static WebviewHeightRatioCompact: com.facebook.share.model.ShareMessengerURLActionButton.WebviewHeightRatio; public static values(): androidNative.Array<com.facebook.share.model.ShareMessengerURLActionButton.WebviewHeightRatio>; public static valueOf(param0: string): com.facebook.share.model.ShareMessengerURLActionButton.WebviewHeightRatio; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareModel { public static class: java.lang.Class<com.facebook.share.model.ShareModel>; /** * Constructs a new instance of the com.facebook.share.model.ShareModel interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } declare module com { export module facebook { export module share { export module model { export class ShareModelBuilder<P, E> extends com.facebook.share.ShareBuilder<any,any> { public static class: java.lang.Class<com.facebook.share.model.ShareModelBuilder<any,any>>; /** * Constructs a new instance of the com.facebook.share.model.ShareModelBuilder<any,any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { readFrom(param0: any): any; build(): any; }); public constructor(); public build(): any; public readFrom(param0: any): any; } } } } } declare module com { export module facebook { export module share { export module model { export class ShareOpenGraphAction extends com.facebook.share.model.ShareOpenGraphValueContainer<com.facebook.share.model.ShareOpenGraphAction,com.facebook.share.model.ShareOpenGraphAction.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareOpenGraphAction>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareOpenGraphAction>; public getActionType(): string; } export module ShareOpenGraphAction { export class Builder extends com.facebook.share.model.ShareOpenGraphValueContainer.Builder<com.facebook.share.model.ShareOpenGraphAction,com.facebook.share.model.ShareOpenGraphAction.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareOpenGraphAction.Builder>; public readFrom(param0: com.facebook.share.model.ShareOpenGraphAction): com.facebook.share.model.ShareOpenGraphAction.Builder; public constructor(); public readFrom(param0: any): any; public build(): com.facebook.share.model.ShareOpenGraphAction; public setActionType(param0: string): com.facebook.share.model.ShareOpenGraphAction.Builder; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareOpenGraphContent extends com.facebook.share.model.ShareContent<com.facebook.share.model.ShareOpenGraphContent,com.facebook.share.model.ShareOpenGraphContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareOpenGraphContent>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareOpenGraphContent>; public getAction(): com.facebook.share.model.ShareOpenGraphAction; public getPreviewPropertyName(): string; public describeContents(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } export module ShareOpenGraphContent { export class Builder extends com.facebook.share.model.ShareContent.Builder<com.facebook.share.model.ShareOpenGraphContent,com.facebook.share.model.ShareOpenGraphContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareOpenGraphContent.Builder>; public setAction(param0: com.facebook.share.model.ShareOpenGraphAction): com.facebook.share.model.ShareOpenGraphContent.Builder; public constructor(); public readFrom(param0: any): any; public setPreviewPropertyName(param0: string): com.facebook.share.model.ShareOpenGraphContent.Builder; public build(): com.facebook.share.model.ShareOpenGraphContent; public readFrom(param0: com.facebook.share.model.ShareOpenGraphContent): com.facebook.share.model.ShareOpenGraphContent.Builder; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareOpenGraphObject extends com.facebook.share.model.ShareOpenGraphValueContainer<com.facebook.share.model.ShareOpenGraphObject,com.facebook.share.model.ShareOpenGraphObject.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareOpenGraphObject>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareOpenGraphObject>; } export module ShareOpenGraphObject { export class Builder extends com.facebook.share.model.ShareOpenGraphValueContainer.Builder<com.facebook.share.model.ShareOpenGraphObject,com.facebook.share.model.ShareOpenGraphObject.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareOpenGraphObject.Builder>; public constructor(); public readFrom(param0: any): any; public build(): com.facebook.share.model.ShareOpenGraphObject; } } } } } } declare module com { export module facebook { export module share { export module model { export abstract class ShareOpenGraphValueContainer<P, E> extends com.facebook.share.model.ShareModel { public static class: java.lang.Class<com.facebook.share.model.ShareOpenGraphValueContainer<any,any>>; public get(param0: string): any; public getBooleanArray(param0: string): androidNative.Array<boolean>; public getDouble(param0: string, param1: number): number; public getObjectArrayList(param0: string): java.util.ArrayList<com.facebook.share.model.ShareOpenGraphObject>; public describeContents(): number; public getBoolean(param0: string, param1: boolean): boolean; public getString(param0: string): string; public getPhotoArrayList(param0: string): java.util.ArrayList<com.facebook.share.model.SharePhoto>; public getLong(param0: string, param1: number): number; public getObject(param0: string): com.facebook.share.model.ShareOpenGraphObject; public getIntArray(param0: string): androidNative.Array<number>; public getPhoto(param0: string): com.facebook.share.model.SharePhoto; public getLongArray(param0: string): androidNative.Array<number>; public getDoubleArray(param0: string): androidNative.Array<number>; public getBundle(): globalAndroid.os.Bundle; public getStringArrayList(param0: string): java.util.ArrayList<string>; public constructor(param0: com.facebook.share.model.ShareOpenGraphValueContainer.Builder<any,any>); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public keySet(): java.util.Set<string>; public getInt(param0: string, param1: number): number; } export module ShareOpenGraphValueContainer { export abstract class Builder<P, E> extends com.facebook.share.model.ShareModelBuilder<any,any> { public static class: java.lang.Class<com.facebook.share.model.ShareOpenGraphValueContainer.Builder<any,any>>; public constructor(); public putIntArray(param0: string, param1: androidNative.Array<number>): any; public putPhoto(param0: string, param1: com.facebook.share.model.SharePhoto): any; public readFrom(param0: any): any; public putDouble(param0: string, param1: number): any; public putInt(param0: string, param1: number): any; public putString(param0: string, param1: string): any; public putDoubleArray(param0: string, param1: androidNative.Array<number>): any; public putBoolean(param0: string, param1: boolean): any; public build(): any; public putObject(param0: string, param1: com.facebook.share.model.ShareOpenGraphObject): any; public putPhotoArrayList(param0: string, param1: java.util.ArrayList<com.facebook.share.model.SharePhoto>): any; public putLong(param0: string, param1: number): any; public putBooleanArray(param0: string, param1: androidNative.Array<boolean>): any; public putStringArrayList(param0: string, param1: java.util.ArrayList<string>): any; public putObjectArrayList(param0: string, param1: java.util.ArrayList<com.facebook.share.model.ShareOpenGraphObject>): any; public putLongArray(param0: string, param1: androidNative.Array<number>): any; } } } } } } declare module com { export module facebook { export module share { export module model { export class SharePhoto extends com.facebook.share.model.ShareMedia { public static class: java.lang.Class<com.facebook.share.model.SharePhoto>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.SharePhoto>; public getImageUrl(): globalAndroid.net.Uri; public getUserGenerated(): boolean; public describeContents(): number; public getCaption(): string; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getBitmap(): globalAndroid.graphics.Bitmap; public getMediaType(): com.facebook.share.model.ShareMedia.Type; } export module SharePhoto { export class Builder extends com.facebook.share.model.ShareMedia.Builder<com.facebook.share.model.SharePhoto,com.facebook.share.model.SharePhoto.Builder> { public static class: java.lang.Class<com.facebook.share.model.SharePhoto.Builder>; public setBitmap(param0: globalAndroid.graphics.Bitmap): com.facebook.share.model.SharePhoto.Builder; public setImageUrl(param0: globalAndroid.net.Uri): com.facebook.share.model.SharePhoto.Builder; public constructor(); public readFrom(param0: any): any; public setUserGenerated(param0: boolean): com.facebook.share.model.SharePhoto.Builder; public build(): com.facebook.share.model.SharePhoto; public setCaption(param0: string): com.facebook.share.model.SharePhoto.Builder; public readFrom(param0: com.facebook.share.model.SharePhoto): com.facebook.share.model.SharePhoto.Builder; } } } } } } declare module com { export module facebook { export module share { export module model { export class SharePhotoContent extends com.facebook.share.model.ShareContent<com.facebook.share.model.SharePhotoContent,com.facebook.share.model.SharePhotoContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.SharePhotoContent>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.SharePhotoContent>; public describeContents(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getPhotos(): java.util.List<com.facebook.share.model.SharePhoto>; } export module SharePhotoContent { export class Builder extends com.facebook.share.model.ShareContent.Builder<com.facebook.share.model.SharePhotoContent,com.facebook.share.model.SharePhotoContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.SharePhotoContent.Builder>; public constructor(); public build(): com.facebook.share.model.SharePhotoContent; public readFrom(param0: any): any; public addPhoto(param0: com.facebook.share.model.SharePhoto): com.facebook.share.model.SharePhotoContent.Builder; public setPhotos(param0: java.util.List<com.facebook.share.model.SharePhoto>): com.facebook.share.model.SharePhotoContent.Builder; public addPhotos(param0: java.util.List<com.facebook.share.model.SharePhoto>): com.facebook.share.model.SharePhotoContent.Builder; public readFrom(param0: com.facebook.share.model.SharePhotoContent): com.facebook.share.model.SharePhotoContent.Builder; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareStoryContent extends com.facebook.share.model.ShareContent<com.facebook.share.model.ShareStoryContent,com.facebook.share.model.ShareStoryContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareStoryContent>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareStoryContent>; public getBackgroundAsset(): com.facebook.share.model.ShareMedia; public getStickerAsset(): com.facebook.share.model.SharePhoto; public getAttributionLink(): string; public describeContents(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getBackgroundColorList(): java.util.List<string>; } export module ShareStoryContent { export class Builder extends com.facebook.share.model.ShareContent.Builder<com.facebook.share.model.ShareStoryContent,com.facebook.share.model.ShareStoryContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareStoryContent.Builder>; public constructor(); public build(): com.facebook.share.model.ShareStoryContent; public setAttributionLink(param0: string): com.facebook.share.model.ShareStoryContent.Builder; public readFrom(param0: any): any; public setBackgroundAsset(param0: com.facebook.share.model.ShareMedia): com.facebook.share.model.ShareStoryContent.Builder; public readFrom(param0: com.facebook.share.model.ShareStoryContent): com.facebook.share.model.ShareStoryContent.Builder; public setBackgroundColorList(param0: java.util.List<string>): com.facebook.share.model.ShareStoryContent.Builder; public setStickerAsset(param0: com.facebook.share.model.SharePhoto): com.facebook.share.model.ShareStoryContent.Builder; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareVideo extends com.facebook.share.model.ShareMedia { public static class: java.lang.Class<com.facebook.share.model.ShareVideo>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareVideo>; public describeContents(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getLocalUrl(): globalAndroid.net.Uri; public getMediaType(): com.facebook.share.model.ShareMedia.Type; } export module ShareVideo { export class Builder extends com.facebook.share.model.ShareMedia.Builder<com.facebook.share.model.ShareVideo,com.facebook.share.model.ShareVideo.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareVideo.Builder>; public constructor(); public readFrom(param0: any): any; public setLocalUrl(param0: globalAndroid.net.Uri): com.facebook.share.model.ShareVideo.Builder; public readFrom(param0: com.facebook.share.model.ShareVideo): com.facebook.share.model.ShareVideo.Builder; public build(): com.facebook.share.model.ShareVideo; } } } } } } declare module com { export module facebook { export module share { export module model { export class ShareVideoContent extends com.facebook.share.model.ShareContent<com.facebook.share.model.ShareVideoContent,com.facebook.share.model.ShareVideoContent.Builder> implements com.facebook.share.model.ShareModel { public static class: java.lang.Class<com.facebook.share.model.ShareVideoContent>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.facebook.share.model.ShareVideoContent>; public describeContents(): number; public getVideo(): com.facebook.share.model.ShareVideo; public getPreviewPhoto(): com.facebook.share.model.SharePhoto; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getContentDescription(): string; public getContentTitle(): string; } export module ShareVideoContent { export class Builder extends com.facebook.share.model.ShareContent.Builder<com.facebook.share.model.ShareVideoContent,com.facebook.share.model.ShareVideoContent.Builder> { public static class: java.lang.Class<com.facebook.share.model.ShareVideoContent.Builder>; public readFrom(param0: com.facebook.share.model.ShareVideoContent): com.facebook.share.model.ShareVideoContent.Builder; public constructor(); public setVideo(param0: com.facebook.share.model.ShareVideo): com.facebook.share.model.ShareVideoContent.Builder; public readFrom(param0: any): any; public setContentTitle(param0: string): com.facebook.share.model.ShareVideoContent.Builder; public build(): com.facebook.share.model.ShareVideoContent; public setContentDescription(param0: string): com.facebook.share.model.ShareVideoContent.Builder; public setPreviewPhoto(param0: com.facebook.share.model.SharePhoto): com.facebook.share.model.ShareVideoContent.Builder; } } } } } } declare module com { export module facebook { export module share { export module widget { export class LikeView { public static class: java.lang.Class<com.facebook.share.widget.LikeView>; public onDetachedFromWindow(): void; /** @deprecated */ public setObjectIdAndType(param0: string, param1: com.facebook.share.widget.LikeView.ObjectType): void; /** @deprecated */ public setLikeViewStyle(param0: com.facebook.share.widget.LikeView.Style): void; /** @deprecated */ public getOnErrorListener(): com.facebook.share.widget.LikeView.OnErrorListener; /** @deprecated */ public setFragment(param0: globalAndroid.app.Fragment): void; /** @deprecated */ public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet); /** @deprecated */ public setForegroundColor(param0: number): void; /** @deprecated */ public setHorizontalAlignment(param0: com.facebook.share.widget.LikeView.HorizontalAlignment): void; /** @deprecated */ public constructor(param0: globalAndroid.content.Context); /** @deprecated */ public setAuxiliaryViewPosition(param0: com.facebook.share.widget.LikeView.AuxiliaryViewPosition): void; /** @deprecated */ public setFragment(param0: androidx.fragment.app.Fragment): void; /** @deprecated */ public setOnErrorListener(param0: com.facebook.share.widget.LikeView.OnErrorListener): void; /** @deprecated */ public setEnabled(param0: boolean): void; } export module LikeView { export class AuxiliaryViewPosition { public static class: java.lang.Class<com.facebook.share.widget.LikeView.AuxiliaryViewPosition>; public static BOTTOM: com.facebook.share.widget.LikeView.AuxiliaryViewPosition; public static INLINE: com.facebook.share.widget.LikeView.AuxiliaryViewPosition; public static TOP: com.facebook.share.widget.LikeView.AuxiliaryViewPosition; public static values(): androidNative.Array<com.facebook.share.widget.LikeView.AuxiliaryViewPosition>; public static valueOf(param0: string): com.facebook.share.widget.LikeView.AuxiliaryViewPosition; public toString(): string; } export class HorizontalAlignment { public static class: java.lang.Class<com.facebook.share.widget.LikeView.HorizontalAlignment>; public static CENTER: com.facebook.share.widget.LikeView.HorizontalAlignment; public static LEFT: com.facebook.share.widget.LikeView.HorizontalAlignment; public static RIGHT: com.facebook.share.widget.LikeView.HorizontalAlignment; public static valueOf(param0: string): com.facebook.share.widget.LikeView.HorizontalAlignment; public static values(): androidNative.Array<com.facebook.share.widget.LikeView.HorizontalAlignment>; public toString(): string; } export class LikeActionControllerCreationCallback extends com.facebook.share.internal.LikeActionController.CreationCallback { public static class: java.lang.Class<com.facebook.share.widget.LikeView.LikeActionControllerCreationCallback>; public onComplete(param0: com.facebook.share.internal.LikeActionController, param1: com.facebook.FacebookException): void; public cancel(): void; } export class LikeControllerBroadcastReceiver { public static class: java.lang.Class<com.facebook.share.widget.LikeView.LikeControllerBroadcastReceiver>; public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void; } export class ObjectType { public static class: java.lang.Class<com.facebook.share.widget.LikeView.ObjectType>; public static UNKNOWN: com.facebook.share.widget.LikeView.ObjectType; public static OPEN_GRAPH: com.facebook.share.widget.LikeView.ObjectType; public static PAGE: com.facebook.share.widget.LikeView.ObjectType; public static DEFAULT: com.facebook.share.widget.LikeView.ObjectType; public static values(): androidNative.Array<com.facebook.share.widget.LikeView.ObjectType>; public static valueOf(param0: string): com.facebook.share.widget.LikeView.ObjectType; public static fromInt(param0: number): com.facebook.share.widget.LikeView.ObjectType; public toString(): string; public getValue(): number; } export class OnErrorListener { public static class: java.lang.Class<com.facebook.share.widget.LikeView.OnErrorListener>; /** * Constructs a new instance of the com.facebook.share.widget.LikeView$OnErrorListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onError(param0: com.facebook.FacebookException): void; }); public constructor(); public onError(param0: com.facebook.FacebookException): void; } export class Style { public static class: java.lang.Class<com.facebook.share.widget.LikeView.Style>; public static STANDARD: com.facebook.share.widget.LikeView.Style; public static BUTTON: com.facebook.share.widget.LikeView.Style; public static BOX_COUNT: com.facebook.share.widget.LikeView.Style; public static values(): androidNative.Array<com.facebook.share.widget.LikeView.Style>; public static valueOf(param0: string): com.facebook.share.widget.LikeView.Style; public toString(): string; } } } } } } declare module com { export module facebook { export module share { export module widget { export class ShareDialog extends com.facebook.internal.FacebookDialogBase<com.facebook.share.model.ShareContent<any,any>,com.facebook.share.Sharer.Result> implements com.facebook.share.Sharer { public static class: java.lang.Class<com.facebook.share.widget.ShareDialog>; public static WEB_SHARE_DIALOG: string; public show(param0: com.facebook.share.model.ShareContent<any,any>, param1: com.facebook.share.widget.ShareDialog.Mode): void; public constructor(param0: globalAndroid.app.Fragment); public createBaseAppCall(): com.facebook.internal.AppCall; public static canShow(param0: java.lang.Class<any>): boolean; public registerCallbackImpl(param0: com.facebook.internal.CallbackManagerImpl, param1: com.facebook.FacebookCallback<any>): void; public canShow(param0: com.facebook.share.model.ShareContent<any,any>, param1: com.facebook.share.widget.ShareDialog.Mode): boolean; public registerCallback(param0: com.facebook.CallbackManager, param1: com.facebook.FacebookCallback<any>, param2: number): void; public static show(param0: androidx.fragment.app.Fragment, param1: com.facebook.share.model.ShareContent<any,any>): void; public static show(param0: globalAndroid.app.Fragment, param1: com.facebook.share.model.ShareContent<any,any>): void; public constructor(param0: androidx.fragment.app.Fragment); public registerCallback(param0: com.facebook.CallbackManager, param1: com.facebook.FacebookCallback<any>): void; public constructor(param0: globalAndroid.app.Activity); public getOrderedModeHandlers(): java.util.List<com.facebook.internal.FacebookDialogBase.ModeHandler>; public setShouldFailOnDataError(param0: boolean): void; public show(param0: any): void; public canShow(param0: any): boolean; public constructor(param0: globalAndroid.app.Activity, param1: number); public constructor(param0: com.facebook.internal.FragmentWrapper, param1: number); public registerCallbackImpl(param0: com.facebook.internal.CallbackManagerImpl, param1: com.facebook.FacebookCallback<com.facebook.share.Sharer.Result>): void; public getShouldFailOnDataError(): boolean; public static show(param0: globalAndroid.app.Activity, param1: com.facebook.share.model.ShareContent<any,any>): void; } export module ShareDialog { export class CameraEffectHandler extends com.facebook.internal.FacebookDialogBase.ModeHandler { public static class: java.lang.Class<com.facebook.share.widget.ShareDialog.CameraEffectHandler>; public getMode(): any; public createAppCall(param0: any): com.facebook.internal.AppCall; public createAppCall(param0: com.facebook.share.model.ShareContent<any,any>): com.facebook.internal.AppCall; public canShow(param0: com.facebook.share.model.ShareContent<any,any>, param1: boolean): boolean; public canShow(param0: any, param1: boolean): boolean; } export class FeedHandler extends com.facebook.internal.FacebookDialogBase.ModeHandler { public static class: java.lang.Class<com.facebook.share.widget.ShareDialog.FeedHandler>; public getMode(): any; public createAppCall(param0: any): com.facebook.internal.AppCall; public createAppCall(param0: com.facebook.share.model.ShareContent<any,any>): com.facebook.internal.AppCall; public canShow(param0: com.facebook.share.model.ShareContent<any,any>, param1: boolean): boolean; public canShow(param0: any, param1: boolean): boolean; } export class Mode { public static class: java.lang.Class<com.facebook.share.widget.ShareDialog.Mode>; public static AUTOMATIC: com.facebook.share.widget.ShareDialog.Mode; public static NATIVE: com.facebook.share.widget.ShareDialog.Mode; public static WEB: com.facebook.share.widget.ShareDialog.Mode; public static FEED: com.facebook.share.widget.ShareDialog.Mode; public static valueOf(param0: string): com.facebook.share.widget.ShareDialog.Mode; public static values(): androidNative.Array<com.facebook.share.widget.ShareDialog.Mode>; } export class NativeHandler extends com.facebook.internal.FacebookDialogBase.ModeHandler { public static class: java.lang.Class<com.facebook.share.widget.ShareDialog.NativeHandler>; public getMode(): any; public createAppCall(param0: any): com.facebook.internal.AppCall; public createAppCall(param0: com.facebook.share.model.ShareContent<any,any>): com.facebook.internal.AppCall; public canShow(param0: com.facebook.share.model.ShareContent<any,any>, param1: boolean): boolean; public canShow(param0: any, param1: boolean): boolean; } export class ShareStoryHandler extends com.facebook.internal.FacebookDialogBase.ModeHandler { public static class: java.lang.Class<com.facebook.share.widget.ShareDialog.ShareStoryHandler>; public getMode(): any; public createAppCall(param0: any): com.facebook.internal.AppCall; public createAppCall(param0: com.facebook.share.model.ShareContent<any,any>): com.facebook.internal.AppCall; public canShow(param0: com.facebook.share.model.ShareContent<any,any>, param1: boolean): boolean; public canShow(param0: any, param1: boolean): boolean; } export class WebShareHandler extends com.facebook.internal.FacebookDialogBase.ModeHandler { public static class: java.lang.Class<com.facebook.share.widget.ShareDialog.WebShareHandler>; public getMode(): any; public createAppCall(param0: any): com.facebook.internal.AppCall; public createAppCall(param0: com.facebook.share.model.ShareContent<any,any>): com.facebook.internal.AppCall; public canShow(param0: com.facebook.share.model.ShareContent<any,any>, param1: boolean): boolean; public canShow(param0: any, param1: boolean): boolean; } } } } } } //Generics information: //com.facebook.FacebookCallback:1 //com.facebook.FacebookDialog:2 //com.facebook.GraphRequest.ParcelableResourceWithMimeType:1 //com.facebook.bolts.Continuation:2 //com.facebook.bolts.Task:1 //com.facebook.bolts.TaskCompletionSource:1 //com.facebook.internal.FacebookDialogBase:2 //com.facebook.internal.LockOnGetVariable:1 //com.facebook.internal.Utility.Mapper:2 //com.facebook.internal.Utility.Predicate:1 //com.facebook.share.ShareBuilder:2 //com.facebook.share.model.ShareContent:2 //com.facebook.share.model.ShareContent.Builder:2 //com.facebook.share.model.ShareMedia.Builder:2 //com.facebook.share.model.ShareMessengerActionButton.Builder:2 //com.facebook.share.model.ShareModelBuilder:2 //com.facebook.share.model.ShareOpenGraphValueContainer:2 //com.facebook.share.model.ShareOpenGraphValueContainer.Builder:2
the_stack
import moment, { Moment } from 'moment'; import { Frame, Page } from 'puppeteer'; import { BaseScraperWithBrowser, LoginOptions, LoginResults } from './base-scraper-with-browser'; import { clickButton, elementPresentOnPage, pageEval, pageEvalAll, setValue, waitUntilElementFound, } from '../helpers/elements-interactions'; import { Transaction, TransactionInstallments, TransactionsAccount, TransactionStatuses, TransactionTypes, } from '../transactions'; import { ScaperOptions, ScaperScrapingResult, ScraperCredentials } from './base-scraper'; import { waitForNavigationAndDomLoad } from '../helpers/navigation'; import { DOLLAR_CURRENCY, DOLLAR_CURRENCY_SYMBOL, SHEKEL_CURRENCY, SHEKEL_CURRENCY_SYMBOL, } from '../constants'; import { waitUntil } from '../helpers/waiting'; import { filterOldTransactions } from '../helpers/transactions'; const LOGIN_URL = 'https://www.cal-online.co.il/'; const TRANSACTIONS_URL = 'https://services.cal-online.co.il/Card-Holders/Screens/Transactions/Transactions.aspx'; const LONG_DATE_FORMAT = 'DD/MM/YYYY'; const DATE_FORMAT = 'DD/MM/YY'; const InvalidPasswordMessage = 'שם המשתמש או הסיסמה שהוזנו שגויים'; interface ScrapedTransaction { date: string; processedDate: string; description: string; originalAmount: string; chargedAmount: string; memo: string; } async function getLoginFrame(page: Page) { let frame: Frame | null = null; await waitUntil(() => { frame = page .frames() .find((f) => f.url().includes('connect.cal-online')) || null; return Promise.resolve(!!frame); }, 'wait for iframe with login form', 10000, 1000); if (!frame) { throw new Error('failed to extract login iframe'); } return frame; } async function hasInvalidPasswordError(page: Page) { const frame = await getLoginFrame(page); const errorFound = await elementPresentOnPage(frame, 'div.general-error > div'); const errorMessage = errorFound ? await pageEval(frame, 'div.general-error > div', '', (item) => { return (item as HTMLDivElement).innerText; }) : ''; return errorMessage === InvalidPasswordMessage; } function getPossibleLoginResults() { const urls: LoginOptions['possibleResults'] = { [LoginResults.Success]: [/AccountManagement/i], [LoginResults.InvalidPassword]: [async (options?: { page?: Page}) => { const page = options?.page; if (!page) { return false; } return hasInvalidPasswordError(page); }], // [LoginResults.AccountBlocked]: [], // TODO add when reaching this scenario // [LoginResults.ChangePassword]: [], // TODO add when reaching this scenario }; return urls; } function createLoginFields(credentials: ScraperCredentials) { return [ { selector: '[formcontrolname="userName"]', value: credentials.username }, { selector: '[formcontrolname="password"]', value: credentials.password }, ]; } function getAmountData(amountStr: string) { const amountStrCln = amountStr.replace(',', ''); let currency: string | null = null; let amount: number | null = null; if (amountStrCln.includes(SHEKEL_CURRENCY_SYMBOL)) { amount = -parseFloat(amountStrCln.replace(SHEKEL_CURRENCY_SYMBOL, '')); currency = SHEKEL_CURRENCY; } else if (amountStrCln.includes(DOLLAR_CURRENCY_SYMBOL)) { amount = -parseFloat(amountStrCln.replace(DOLLAR_CURRENCY_SYMBOL, '')); currency = DOLLAR_CURRENCY; } else { const parts = amountStrCln.split(' '); amount = -parseFloat(parts[0]); [, currency] = parts; } return { amount, currency, }; } function getTransactionInstallments(memo: string): TransactionInstallments | null { const parsedMemo = (/תשלום (\d+) מתוך (\d+)/).exec(memo || ''); if (!parsedMemo || parsedMemo.length === 0) { return null; } return { number: parseInt(parsedMemo[1], 10), total: parseInt(parsedMemo[2], 10), }; } function convertTransactions(txns: ScrapedTransaction[]): Transaction[] { return txns.map((txn) => { const originalAmountTuple = getAmountData(txn.originalAmount || ''); const chargedAmountTuple = getAmountData(txn.chargedAmount || ''); const installments = getTransactionInstallments(txn.memo); const txnDate = moment(txn.date, DATE_FORMAT); const processedDateFormat = txn.processedDate.length === 8 ? DATE_FORMAT : txn.processedDate.length === 9 || txn.processedDate.length === 10 ? LONG_DATE_FORMAT : null; if (!processedDateFormat) { throw new Error('invalid processed date'); } const txnProcessedDate = moment(txn.processedDate, processedDateFormat); const result: Transaction = { type: installments ? TransactionTypes.Installments : TransactionTypes.Normal, status: TransactionStatuses.Completed, date: installments ? txnDate.add(installments.number - 1, 'month').toISOString() : txnDate.toISOString(), processedDate: txnProcessedDate.toISOString(), originalAmount: originalAmountTuple.amount, originalCurrency: originalAmountTuple.currency, chargedAmount: chargedAmountTuple.amount, chargedCurrency: chargedAmountTuple.currency, description: txn.description || '', memo: txn.memo || '', }; if (installments) { result.installments = installments; } return result; }); } async function fetchTransactionsForAccount(page: Page, startDate: Moment, accountNumber: string, scraperOptions: ScaperOptions): Promise<TransactionsAccount> { const startDateValue = startDate.format('MM/YYYY'); const dateSelector = '[id$="FormAreaNoBorder_FormArea_clndrDebitDateScope_TextBox"]'; const dateHiddenFieldSelector = '[id$="FormAreaNoBorder_FormArea_clndrDebitDateScope_HiddenField"]'; const buttonSelector = '[id$="FormAreaNoBorder_FormArea_ctlSubmitRequest"]'; const nextPageSelector = '[id$="FormAreaNoBorder_FormArea_ctlGridPager_btnNext"]'; const billingLabelSelector = '[id$=FormAreaNoBorder_FormArea_ctlMainToolBar_lblCaption]'; const options = await pageEvalAll(page, '[id$="FormAreaNoBorder_FormArea_clndrDebitDateScope_OptionList"] li', [], (items) => { return items.map((el: any) => el.innerText); }); const startDateIndex = options.findIndex((option) => option === startDateValue); const accountTransactions: Transaction[] = []; for (let currentDateIndex = startDateIndex; currentDateIndex < options.length; currentDateIndex += 1) { await waitUntilElementFound(page, dateSelector, true); await setValue(page, dateHiddenFieldSelector, `${currentDateIndex}`); await clickButton(page, buttonSelector); await waitForNavigationAndDomLoad(page); const billingDateLabel = await pageEval(page, billingLabelSelector, '', ((element) => { return (element as HTMLSpanElement).innerText; })); const billingDate = /\d{1,2}[/]\d{2}[/]\d{2,4}/.exec(billingDateLabel)?.[0]; if (!billingDate) { throw new Error('failed to fetch process date'); } let hasNextPage = false; do { const rawTransactions = await pageEvalAll<(ScrapedTransaction | null)[]>(page, '#ctlMainGrid > tbody tr, #ctlSecondaryGrid > tbody tr', [], (items, billingDate) => { return (items).map((el) => { const columns = el.getElementsByTagName('td'); if (columns.length === 6) { return { processedDate: columns[0].innerText, date: columns[1].innerText, description: columns[2].innerText, originalAmount: columns[3].innerText, chargedAmount: columns[4].innerText, memo: columns[5].innerText, }; } if (columns.length === 5) { return { processedDate: billingDate, date: columns[0].innerText, description: columns[1].innerText, originalAmount: columns[2].innerText, chargedAmount: columns[3].innerText, memo: columns[4].innerText, }; } return null; }); }, billingDate); accountTransactions.push(...convertTransactions((rawTransactions as ScrapedTransaction[]) .filter((item) => !!item))); hasNextPage = await elementPresentOnPage(page, nextPageSelector); if (hasNextPage) { await clickButton(page, '[id$=FormAreaNoBorder_FormArea_ctlGridPager_btnNext]'); await waitForNavigationAndDomLoad(page); } } while (hasNextPage); } const txns = filterOldTransactions(accountTransactions, startDate, scraperOptions.combineInstallments || false); return { accountNumber, txns, }; } async function fetchTransactions(page: Page, startDate: Moment, scraperOptions: ScaperOptions): Promise<TransactionsAccount[]> { const accounts: TransactionsAccount[] = []; const accountId = await pageEval(page, '[id$=cboCardList_categoryList_lblCollapse]', '', (item) => { return (item as HTMLInputElement).value; }, []); const accountNumber = /\d+$/.exec(accountId.trim())?.[0] ?? ''; accounts.push(await fetchTransactionsForAccount(page, startDate, accountNumber, scraperOptions)); return accounts; } class VisaCalScraper extends BaseScraperWithBrowser { openLoginPopup = async () => { await waitUntilElementFound(this.page, '#ccLoginDesktopBtn', true); await clickButton(this.page, '#ccLoginDesktopBtn'); const frame = await getLoginFrame(this.page); await waitUntilElementFound(frame, '#regular-login'); await clickButton(frame, '#regular-login'); await waitUntilElementFound(frame, 'regular-login'); return frame; }; getLoginOptions(credentials: Record<string, string>) { return { loginUrl: `${LOGIN_URL}`, fields: createLoginFields(credentials), submitButtonSelector: 'button[type="submit"]', possibleResults: getPossibleLoginResults(), checkReadiness: async () => waitUntilElementFound(this.page, '#ccLoginDesktopBtn'), preAction: this.openLoginPopup, userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36', }; } async fetchData(): Promise<ScaperScrapingResult> { const defaultStartMoment = moment().subtract(1, 'years').add(1, 'day'); const startDate = this.options.startDate || defaultStartMoment.toDate(); const startMoment = moment.max(defaultStartMoment, moment(startDate)); await this.navigateTo(TRANSACTIONS_URL, undefined, 60000); const accounts = await fetchTransactions(this.page, startMoment, this.options); return { success: true, accounts, }; } } export default VisaCalScraper;
the_stack
import lockfile from 'proper-lockfile' import Queue from './Queue' import { Metadata, PublicMetadata } from './Metadata' import { Actor, ActorMsg } from './Actor' import * as Clock from './Clock' import { ToBackendQueryMsg, ToBackendRepoMsg, ToFrontendRepoMsg, DocumentMsg, SignReplyMsg, SealedBoxReplyMsg, OpenSealedBoxReplyMsg, BoxReplyMsg, OpenBoxReplyMsg, } from './RepoMsg' import { Backend, Change } from 'automerge' import * as DocBackend from './DocBackend' import path from 'path' import fs from 'fs' import { notEmpty, ID, ActorId, DocId, RepoId, encodeRepoId, encodeDocId, rootActorId, encodeActorId, toDiscoveryId, errorMessage, } from './Misc' import Debug from './Debug' import * as Keys from './Keys' import FeedStore from './FeedStore' import FileStore from './FileStore' import FileServer from './FileServer' import Network from './Network' import NetworkPeer, { PeerId } from './NetworkPeer' import { Swarm, JoinOptions } from './SwarmInterface' import { PeerMsg } from './PeerMsg' import ClockStore from './ClockStore' import CursorStore from './CursorStore' import * as SqlDatabase from './SqlDatabase' import MessageRouter, { Routed } from './MessageRouter' import ram from 'random-access-memory' import raf from 'random-access-file' import KeyStore from './KeyStore' import ReplicationManager, { Discovery } from './ReplicationManager' import * as Crypto from './Crypto' const log = Debug('RepoBackend') export interface FeedData { actorId: ActorId writable: Boolean changes: Change[] } export interface Options { path?: string memory?: boolean } export class RepoBackend { path?: string storage: Function feeds: FeedStore keys: KeyStore files: FileStore clocks: ClockStore cursors: CursorStore actors: Map<ActorId, Actor> = new Map() docs: Map<DocId, DocBackend.DocBackend> = new Map() meta: Metadata opts: Options toFrontend: Queue<ToFrontendRepoMsg> = new Queue('repo:back:toFrontend') id: RepoId network: Network messages: MessageRouter<PeerMsg> replication: ReplicationManager lockRelease?: () => void swarmKey: Buffer // TODO: Remove this once we no longer use discovery-swarm/discovery-cloud private db: SqlDatabase.Database private fileServer: FileServer constructor(opts: Options) { this.opts = opts this.path = opts.path || 'default' // initialize storage if (!opts.memory) { ensureDirectoryExists(this.path) // Attempt to acquite a lock on the repo to prevent concurrent corrupting access. this.lockRelease = lockfile.lockSync(this.path) } this.storage = opts.memory ? ram : raf this.db = SqlDatabase.open(path.resolve(this.path, 'hypermerge.db'), opts.memory || false) this.keys = new KeyStore(this.db) this.feeds = new FeedStore(this.db, (path: string) => this.storageFn('feeds/' + path)) this.files = new FileStore(this.feeds) // init repo const repoKeys = this.keys.get('self.repo') || this.keys.set('self.repo', Keys.createBuffer()) this.swarmKey = repoKeys.publicKey this.id = encodeRepoId(repoKeys.publicKey) // initialize the various stores this.cursors = new CursorStore(this.db) this.clocks = new ClockStore(this.db) this.fileServer = new FileServer(this.files) this.replication = new ReplicationManager(this.feeds) this.meta = new Metadata(this.storageFn) this.network = new Network(toPeerId(this.id)) this.messages = new MessageRouter('HypermergeMessages') for (const docId of this.cursors.getAllDocumentIds(this.id)) { this.network.join(toDiscoveryId(docId)) } this.cursors.updateQ.subscribe(([_, docId]) => { this.network.join(toDiscoveryId(docId)) }) this.files.writeLog.subscribe((header) => { this.meta.addFile(header.url, header.size, header.mimeType) }) this.messages.inboxQ.subscribe(this.onMessage) this.replication.discoveryQ.subscribe(this.onDiscovery) this.network.peerQ.subscribe(this.onPeer) } startFileServer = (path: string) => { if (this.fileServer.isListening()) return this.fileServer.listen(path).then(() => { this.toFrontend.push({ type: 'FileServerReadyMsg', path, }) }) } private create(keys: Keys.KeyBuffer): DocBackend.DocBackend { const docId = encodeDocId(keys.publicKey) log('create', docId) const doc = new DocBackend.DocBackend(docId, Backend.init()) doc.updateQ.subscribe(this.documentNotify) // HACK: We set a clock value of zero so we have a clock in the clock store // TODO: This isn't right. this.clocks.set(this.id, doc.id, { [doc.id]: 0 }) this.docs.set(docId, doc) this.cursors.addActor(this.id, doc.id, rootActorId(doc.id)) this.initActor(keys) return doc } // TODO: Temporary solution to replace meta.localActorId // We only know if an actor is local/writable if we have already // opened that actor. We should be storing this information somewhere // more readily available - either in FeedStore or DocumentStore. localActorId(docId: DocId) { const cursor = this.cursors.get(this.id, docId) const actors = Clock.actors(cursor) return actors.find((actorId) => this.meta.isWritable(actorId)) } private debug(id: DocId) { const doc = this.docs.get(id) const short = id.substr(0, 5) if (doc === undefined) { console.log(`doc:backend NOT FOUND id=${short}`) } else { console.log(`doc:backend id=${short}`) console.log(`doc:backend clock=${Clock.clockDebug(doc.clock)}`) const local = this.localActorId(id) const cursor = this.cursors.get(this.id, id) const actors = Clock.actors(cursor) const info = actors .map((actor) => { const nm = actor.substr(0, 5) return local === actor ? `*${nm}` : nm }) .sort() console.log(`doc:backend actors=${info.join(',')}`) } } // private destroy(id: DocId) { // this.meta.delete(id) // const doc = this.docs.get(id) // if (doc) { // this.docs.delete(id) // } // const actors = this.meta.allActors() // this.actors.forEach((actor, id) => { // if (!actors.has(id)) { // console.log('Orphaned actors - will purge', id) // this.actors.delete(id) // this.leave(actor.id) // actor.destroy() // } // }) // } // opening a file fucks it up private open(docId: DocId): DocBackend.DocBackend { // log("open", docId, this.meta.forDoc(docId)); // TODO: FileStore should answer this. // NOTE: This isn't guaranteed to be correct. `meta.isFile` can return an incorrect answer // if the metadata ledger hasn't finished loading. if (this.meta.isFile(docId)) { throw new Error('trying to open a file like a document') } let doc = this.docs.get(docId) if (!doc) { doc = new DocBackend.DocBackend(docId) doc.updateQ.subscribe(this.documentNotify) } if (!this.docs.has(docId)) { this.docs.set(docId, doc) // TODO: It isn't always correct to add this actor with an Infinity cursor entry. // If we don't have a cursor for the document, we should wait to get one from a peer. // For now, we're mirroring legacy behavior. this.cursors.addActor(this.id, docId, rootActorId(docId)) this.loadDocument(doc) } return doc } merge(id: DocId, clock: Clock.Clock) { // TODO: Should we do anything additional to note a merge? this.cursors.update(this.id, id, clock) this.syncReadyActors(Clock.actors(clock)) } close = () => { this.actors.forEach((actor) => actor.close()) this.actors.clear() this.db.close() return Promise.all([ this.feeds.close(), this.replication.close(), this.network.close(), this.fileServer.close(), ]).then(() => { this.lockRelease?.() }) } private async allReadyActors(docId: DocId): Promise<Actor[]> { const cursor = this.cursors.get(this.id, docId) const actorIds = Clock.actors(cursor) return Promise.all(actorIds.map(this.getReadyActor)) } private async loadDocument(doc: DocBackend.DocBackend) { const actors = await this.allReadyActors(doc.id) log(`load document 2 actors=${actors.map((a) => a.id)}`) const changes: Change[] = [] actors.forEach((actor) => { const max = this.cursors.entry(this.id, doc.id, actor.id) const slice = actor.changes.slice(0, max) doc.changes.set(actor.id, slice.length) log(`change actor=${ID(actor.id)} changes=0..${slice.length}`) changes.push(...slice) }) log(`loading doc=${ID(doc.id)} changes=${changes.length}`) // Check to see if we already have a local actor id. If so, re-use it. // TODO: DocumentStore can answer this. const localActorId = this.localActorId(doc.id) const actorId = localActorId ? (await this.getReadyActor(localActorId)).id : this.initActorFeed(doc) doc.init(changes, actorId) } private getReadyActor = (actorId: ActorId): Promise<Actor> => { const publicKey = Keys.decode(actorId) const actor = this.actors.get(actorId) || this.initActor({ publicKey }) const actorPromise = new Promise<Actor>((resolve, reject) => { try { actor.onReady(resolve) } catch (e) { reject(e) } }) return actorPromise } storageFn = (path: string) => { return (name: string) => { return this.storage(this.path + '/' + path + '/' + name) } } initActorFeed(doc: DocBackend.DocBackend): ActorId { log('initActorFeed', doc.id) const keys = Keys.createBuffer() const actorId = encodeActorId(keys.publicKey) this.cursors.addActor(this.id, doc.id, actorId) this.initActor(keys) return actorId } actorIds(doc: DocBackend.DocBackend): ActorId[] { const cursor = this.cursors.get(this.id, doc.id) return Clock.actors(cursor) } docActors(doc: DocBackend.DocBackend): Actor[] { return this.actorIds(doc) .map((id) => this.actors.get(id)) .filter(notEmpty) } syncReadyActors = (ids: ActorId[]) => { ids.forEach(async (id) => { const actor = await this.getReadyActor(id) this.syncChanges(actor) }) } private getGoodClock(doc: DocBackend.DocBackend): Clock.Clock | undefined { const minimumClockSatisfied = this.clocks.has(this.id, doc.id) return minimumClockSatisfied ? doc.clock : this.clocks.getMaximumSatisfiedClock(doc.id, doc.clock) } private documentNotify = (msg: DocBackend.DocBackendMessage) => { switch (msg.type) { case 'ReadyMsg': { const doc = msg.doc const goodClock = this.getGoodClock(doc) this.toFrontend.push({ type: 'ReadyMsg', id: doc.id, minimumClockSatisfied: !!goodClock, actorId: doc.actorId, history: msg.history, patch: msg.patch, }) break } case 'ActorIdMsg': { this.toFrontend.push({ type: 'ActorIdMsg', id: msg.id, actorId: msg.actorId, }) break } case 'RemotePatchMsg': { const doc = msg.doc const goodClock = this.getGoodClock(doc) if (goodClock) { this.clocks.update(this.id, doc.id, goodClock) } this.toFrontend.push({ type: 'PatchMsg', id: doc.id, minimumClockSatisfied: !!goodClock, patch: msg.patch, history: msg.history, }) break } case 'LocalPatchMsg': { const doc = msg.doc if (!doc.actorId) return this.actor(doc.actorId)!.writeChange(msg.change) const goodClock = this.getGoodClock(doc) if (goodClock) { this.clocks.update(this.id, doc.id, goodClock) } this.toFrontend.push({ type: 'PatchMsg', id: doc.id, minimumClockSatisfied: !!goodClock, patch: msg.patch, history: msg.history, }) break } default: { console.log('Unknown message type', msg) } } } onPeer = (peer: NetworkPeer): void => { this.messages.listenTo(peer) this.replication.onPeer(peer) } onDiscovery = ({ feedId, peer }: Discovery) => { const actorId = feedId as ActorId const docsWithActor = this.cursors.docsWithActor(this.id, actorId) const cursors = docsWithActor.map((docId) => ({ docId: docId, cursor: this.cursors.get(this.id, docId), })) const clocks = docsWithActor.map((docId) => ({ docId: docId, clock: this.clocks.get(this.id, docId), })) this.messages.sendToPeer(peer, { type: 'CursorMessage', cursors, clocks, }) } private onMessage = ({ sender, msg }: Routed<PeerMsg>) => { switch (msg.type) { case 'CursorMessage': { const { clocks, cursors } = msg // TODO: ClockStore and CursorStore will both have updateQs, but we probably want to // wait to act for any given doc until both the ClockStore and CursorStore are updated // for that doc. clocks.forEach((clock) => this.clocks.update(sender.id, clock.docId, clock.clock)) cursors.forEach((cursor) => { // TODO: Current behavior is to always expand our own cursor with our peers' cursors. // In the future, we might want to be more selective. this.cursors.update(sender.id, cursor.docId, cursor.cursor) this.cursors.update(this.id, cursor.docId, cursor.cursor) }) // TODO: This emulates the syncReadyActors behavior from RemotaMetadata messages, // but is extremely wasteful. We'll able to trim this once we have DocumentStore. // TODO: Use a CursorStore updateQ to manage this behavior. cursors.forEach(({ cursor }) => { const actors = Clock.actors(cursor) this.syncReadyActors(actors) }) break } case 'DocumentMessage': { const { contents, id } = msg as DocumentMsg this.toFrontend.push({ type: 'DocumentMessage', id, contents, }) break } } } private actorNotify = (msg: ActorMsg) => { switch (msg.type) { case 'ActorFeedReady': { const actor = msg.actor // Record whether or not this actor is writable. // TODO: DocumentStore or FeedStore should manage this. this.meta.setWritable(actor.id, msg.writable) // Broadcast latest document information to peers. const docsWithActor = this.cursors.docsWithActor(this.id, actor.id) const cursors = docsWithActor.map((docId) => ({ docId: docId, cursor: this.cursors.get(this.id, docId), })) const clocks = docsWithActor.map((docId) => ({ docId: docId, clock: this.clocks.get(this.id, docId), })) const discoveryIds = docsWithActor.map(toDiscoveryId) const peers = this.replication.getPeersWith(discoveryIds) this.messages.sendToPeers(peers, { type: 'CursorMessage', cursors: cursors, clocks: clocks, }) break } case 'ActorSync': log('ActorSync', msg.actor.id) this.syncChanges(msg.actor) break case 'Download': this.cursors.docsWithActor(this.id, msg.actor.id).forEach((docId) => { this.toFrontend.push({ type: 'ActorBlockDownloadedMsg', id: docId, actorId: msg.actor.id, index: msg.index, size: msg.size, time: msg.time, }) }) break } } private initActor(keys: Keys.KeyBuffer): Actor { const actor = new Actor({ keys, notify: this.actorNotify, store: this.feeds, }) this.actors.set(actor.id, actor) return actor } syncChanges = (actor: Actor) => { const actorId = actor.id const docIds = this.cursors.docsWithActor(this.id, actorId) docIds.forEach((docId) => { const doc = this.docs.get(docId) if (doc) { doc.ready.push(() => { const max = this.cursors.entry(this.id, docId, actorId) const min = doc.changes.get(actorId) || 0 const changes = [] let i = min for (; i < max && actor.changes.hasOwnProperty(i); i++) { const change = actor.changes[i] log(`change found xxx id=${ID(actor.id)} seq=${change.seq}`) changes.push(change) } doc.changes.set(actorId, i) // log(`changes found xxx doc=${ID(docId)} actor=${ID(actor.id)} n=[${min}+${changes.length}/${max}]`); if (changes.length > 0) { log(`applyremotechanges ${changes.length}`) doc.applyRemoteChanges(changes) } }) } }) } /** @deprecated Use addSwarm */ setSwarm = (swarm: Swarm, joinOptions?: JoinOptions) => { this.addSwarm(swarm, joinOptions) } addSwarm = (swarm: Swarm, joinOptions?: JoinOptions) => { this.network.addSwarm(swarm, joinOptions) } removeSwarm = (swarm: Swarm) => { this.network.removeSwarm(swarm) } subscribe = (subscriber: (message: ToFrontendRepoMsg) => void) => { this.toFrontend.subscribe(subscriber) } handleQuery = async (id: number, query: ToBackendQueryMsg) => { switch (query.type) { case 'EncryptionKeyPairMsg': { const keyPair = Crypto.encodedEncryptionKeyPair() this.toFrontend.push({ type: 'Reply', id, payload: { type: 'EncryptionKeyPairReplyMsg', success: true, keyPair }, }) break } case 'BoxMsg': { let payload: BoxReplyMsg try { const box = Crypto.box( query.senderSecretKey, query.recipientPublicKey, Buffer.from(query.message) ) payload = { type: 'BoxReplyMsg', success: true, box } } catch (e) { payload = { type: 'BoxReplyMsg', success: false, error: errorMessage(e) } } this.toFrontend.push({ type: 'Reply', id, payload }) break } case 'OpenBoxMsg': { let payload: OpenBoxReplyMsg try { const message = Crypto.openBox(query.senderPublicKey, query.recipientSecretKey, query.box) payload = { type: 'OpenBoxReplyMsg', success: true, message: message.toString() } } catch (e) { payload = { type: 'OpenBoxReplyMsg', success: false, error: errorMessage(e) } } this.toFrontend.push({ type: 'Reply', id, payload }) break } case 'SealedBoxMsg': { let payload: SealedBoxReplyMsg try { const sealedBox = Crypto.sealedBox(query.publicKey, Buffer.from(query.message)) payload = { type: 'SealedBoxReplyMsg', success: true, sealedBox } } catch (e) { payload = { type: 'SealedBoxReplyMsg', success: false, error: errorMessage(e) } } this.toFrontend.push({ type: 'Reply', id, payload }) break } case 'OpenSealedBoxMsg': { let payload: OpenSealedBoxReplyMsg try { const message = Crypto.openSealedBox(query.keyPair, query.sealedBox) payload = { type: 'OpenSealedBoxReplyMsg', success: true, message: message.toString() } } catch (e) { payload = { type: 'OpenSealedBoxReplyMsg', success: false, error: errorMessage(e) } } this.toFrontend.push({ type: 'Reply', id, payload }) break } case 'SignMsg': { let payload: SignReplyMsg try { const { signature } = await this.feeds.sign(query.docId, Buffer.from(query.message)) payload = { type: 'SignReplyMsg', success: true, signedMessage: { message: query.message, signature }, } } catch (e) { payload = { type: 'SignReplyMsg', success: false, error: errorMessage(e) } } this.toFrontend.push({ type: 'Reply', id, payload, }) break } case 'VerifyMsg': { let success try { const signedMessage = { ...query.signedMessage, message: Buffer.from(query.signedMessage.message), } success = this.feeds.verify(query.docId, signedMessage) } catch (e) { success = false } this.toFrontend.push({ type: 'Reply', id, payload: { type: 'VerifyReplyMsg', success, }, }) break } case 'MetadataMsg': { // TODO: We're recreating the MetadataMsg which used to live in Metadata.ts // Its not clear if this is used or useful. It looks like the data (which is faithfully // represented below - empty clock and 0 history in all) is already somewhat broken. // NOTE: Responses to file metadata won't reply until the ledger is fully loaded. Document // responses will respond immediately. this.meta.readyQ.push(() => { let payload: PublicMetadata | null if (this.meta.isDoc(query.id)) { const cursor = this.cursors.get(this.id, query.id) const actors = Clock.actors(cursor) payload = { type: 'Document', clock: {}, history: 0, actor: this.localActorId(query.id), actors, } } else if (this.meta.isFile(query.id)) { payload = this.meta.fileMetadata(query.id) } else { payload = null } this.toFrontend.push({ type: 'Reply', id, payload: { type: 'MetadataReplyMsg', metadata: payload }, }) }) break } case 'MaterializeMsg': { const doc = this.docs.get(query.id)! const changes = (doc.back as any) .getIn(['opSet', 'history']) .slice(0, query.history) .toArray() const [, patch] = Backend.applyChanges(Backend.init(), changes) this.toFrontend.push({ type: 'Reply', id, payload: { type: 'MaterializeReplyMsg', patch } }) break } } } receive = (msg: ToBackendRepoMsg) => { switch (msg.type) { case 'NeedsActorIdMsg': { const doc = this.docs.get(msg.id)! const actorId = this.initActorFeed(doc) doc.initActor(actorId) break } case 'RequestMsg': { const doc = this.docs.get(msg.id)! doc.applyLocalChange(msg.request) break } case 'Query': { const query = msg.query const id = msg.id this.handleQuery(id, query) break } case 'CreateMsg': { this.create(Keys.decodePair(msg)) break } case 'MergeMsg': { this.merge(msg.id, Clock.strs2clock(msg.actors)) break } /* case "FollowMsg": { this.follow(msg.id, msg.target); break; } */ case 'OpenMsg': { this.open(msg.id) break } case 'DocumentMessage': { // Note: 'id' is the document id of the document to send the message to. const { id, contents } = msg const peers = this.replication.getPeersWith([toDiscoveryId(id)]) this.messages.sendToPeers(peers, { type: 'DocumentMessage', id, contents, }) break } case 'DestroyMsg': { console.log('Destroy is a noop') //this.destroy(msg.id) break } case 'DebugMsg': { this.debug(msg.id) break } case 'CloseMsg': { this.close() break } } } actor(id: ActorId): Actor | undefined { return this.actors.get(id) } } function ensureDirectoryExists(path: string) { try { fs.mkdirSync(path, { recursive: true }) } catch (e) { // On slightly older versions of node, this will throw if the directory already exists } } function toPeerId(repoId: RepoId): PeerId { return repoId as PeerId }
the_stack
import React, { useEffect } from 'react' import * as d3 from 'd3' import { D3Selector, D3Transition, useD3 } from 'lib/hooks/useD3' import { FunnelLayout } from 'lib/constants' import { createRoundedRectPath, getConfig, INITIAL_CONFIG, D3HistogramDatum } from './histogramUtils' import { getOrCreateEl, animate, wrap } from 'lib/utils/d3Utils' import './Histogram.scss' import { useActions, useValues } from 'kea' import { histogramLogic } from 'scenes/insights/Histogram/histogramLogic' export interface HistogramDatum { id: string | number bin0: number bin1: number count: number label: string | number } interface HistogramProps { data: HistogramDatum[] layout?: FunnelLayout isAnimated?: boolean isDashboardItem?: boolean width?: number height?: number formatXTickLabel?: (value: number) => number | string formatYTickLabel?: (value: number) => number } export function Histogram({ data, layout = FunnelLayout.vertical, width = INITIAL_CONFIG.width, height = INITIAL_CONFIG.height, isAnimated = false, isDashboardItem = false, formatXTickLabel = (value: number) => value, formatYTickLabel = (value: number) => value, }: HistogramProps): JSX.Element { const { config } = useValues(histogramLogic) const { setConfig } = useActions(histogramLogic) const isEmpty = data.length === 0 || d3.sum(data.map((d) => d.count)) === 0 // Initialize x-axis and y-axis scales const xMin = data?.[0]?.bin0 || 0 const xMax = data?.[data.length - 1]?.bin1 || 1 const x = d3.scaleLinear().domain([xMin, xMax]).range(config.ranges.x).nice() const xAxis = config.axisFn .x(x) .tickValues([...data.map((d) => d.bin0), xMax]) // v === -2 || v === -1 represent bins that catch grouped outliers. // TODO: (-2, -1) are temporary placeholders for (-inf, +inf) and should be changed when backend specs are finalized .tickFormat((v: number) => { const label = formatXTickLabel(v) if (v === -2) { return `<${label}` } if (v === -1) { return `>=${label}` } return label }) // y-axis scale const yMax = d3.max(data, (d: HistogramDatum) => d.count) as number const y = d3.scaleLinear().domain([0, yMax]).range(config.ranges.y).nice() const yAxis = config.axisFn .y(y) .tickValues(y.ticks().filter((tick) => Number.isInteger(tick))) .tickSize(0) .tickFormat((v: number) => { const count = formatYTickLabel(v) // SI-prefix with trailing zeroes trimmed off return d3.format('~s')(count) }) // y-axis gridline scale const yAxisGrid = config.axisFn.y(y).tickSize(-config.gridlineTickSize).tickFormat('').ticks(y.ticks().length) // Update config to new values if dimensions change useEffect( () => { const minWidth = Math.max( width, data.length * (config.spacing.minBarWidth + config.spacing.btwnBins) + config.margin.left + config.margin.right ) setConfig(getConfig(layout, isDashboardItem ? width : minWidth, height)) }, // eslint-disable-next-line react-hooks/exhaustive-deps [data.length, layout, width, height] ) const ref = useD3( (container) => { const isVertical = config.layout === FunnelLayout.vertical const renderCanvas = (parentNode: D3Selector): D3Selector => { // Update config to reflect dimension changes x.range(config.ranges.x) y.range(config.ranges.y) yAxisGrid.tickSize(-config.gridlineTickSize) // Get or create svg > g const _svg = getOrCreateEl(parentNode, 'svg > g', () => parentNode .append('svg:svg') .attr('viewBox', `0 0 ${config.inner.width} ${config.inner.height}`) .attr('width', '100%') .append('svg:g') .classed(config.layout, true) ) // update dimensions parentNode.select('svg').attr('viewBox', `0 0 ${config.width} ${config.height}`) // if class doesn't exist on svg>g, layout has changed. after we learn this, reset // the layout const layoutChanged = !_svg.classed(config.layout) _svg.attr('class', null).classed(config.layout, true) // if layout changes, redraw axes from scratch if (layoutChanged) { _svg.selectAll('#x-axis,#y-axis,#y-gridlines').remove() } // x-axis const _xAxis = getOrCreateEl(_svg, 'g#x-axis', () => _svg.append('svg:g').attr('id', 'x-axis').attr('transform', config.transforms.x) ) _xAxis.call(animate, !layoutChanged ? config.transitionDuration : 0, isAnimated, (it: D3Transition) => it.call(xAxis).attr('transform', config.transforms.x) ) const binWidth = x(data?.[0]?.bin1 || data?.[data.length - 1]?.bin1 || 1) - x(data?.[0]?.bin0 || 0) _xAxis .selectAll('.tick text') .call( wrap, isVertical ? binWidth : config.margin.left, config.spacing.labelLineHeight, isVertical, config.spacing.xLabel ) // Don't draw y-axis or y-gridline if the data is empty if (!isEmpty) { // y-axis const _yAxis = getOrCreateEl(_svg, 'g#y-axis', () => _svg.append('svg:g').attr('id', 'y-axis').attr('transform', config.transforms.y) ) _yAxis.call( animate, !layoutChanged ? config.transitionDuration : 0, isAnimated, (it: D3Transition) => it .call(yAxis) .attr('transform', config.transforms.y) .call((g) => g.selectAll('.tick text').attr('dx', isVertical ? `-${config.spacing.yLabel}` : 0) ) ) // y-gridlines const _yGridlines = getOrCreateEl(_svg, 'g#y-gridlines', () => _svg.append('svg:g').attr('id', 'y-gridlines').attr('transform', config.transforms.yGrid) ) _yGridlines.call( animate, !layoutChanged ? config.transitionDuration : 0, isAnimated, (it: D3Transition) => it.call(yAxisGrid).attr('transform', config.transforms.yGrid) ) } const d3Data = data as D3HistogramDatum[] // bars const _bars = getOrCreateEl(_svg, 'g#bars', () => _svg.append('svg:g').attr('id', 'bars')) _bars .selectAll('path') .data(d3Data) .join('path') .call(animate, config.transitionDuration, isAnimated, (it: D3Transition) => { return it.attr('d', (d: HistogramDatum) => { if (!isVertical) { // is horizontal return createRoundedRectPath( y(0), x(d.bin0) + config.spacing.btwnBins / 2, y(d.count) - y(0), Math.max(0, x(d.bin1) - x(d.bin0) - config.spacing.btwnBins), config.borderRadius, 'right' ) } return createRoundedRectPath( x(d.bin0) + config.spacing.btwnBins / 2, y(d.count), Math.max(0, x(d.bin1) - x(d.bin0) - config.spacing.btwnBins), y(0) - y(d.count), config.borderRadius, 'top' ) }) }) // Always move bar above everything else _svg.node().appendChild(_bars.node()) // text labels if (!isDashboardItem) { const _labels = getOrCreateEl(_svg, 'g#labels', () => _svg.append('svg:g').attr('id', 'labels')) _labels .selectAll('text') .data(d3Data) .join('text') .text((d) => d.label) .classed('bar-label', true) .each(function (this: any, d) { const { width: labelWidth, height: labelHeight } = this.getBBox() d.labelWidth = labelWidth d.labelHeight = labelHeight d.shouldShowInBar = false }) .attr('x', (d) => { if (!isVertical) { const labelWidth = (d.labelWidth || 0) + 2 * config.spacing.barLabelPadding const shouldShowInBar = labelWidth <= y(d.count) - y(0) const labelDx = shouldShowInBar ? -(labelWidth - config.spacing.barLabelPadding) : config.spacing.barLabelPadding d.shouldShowInBar = shouldShowInBar return y(d.count) + labelDx } // x + bin width + dx + dy return x(d.bin0) + binWidth / 2 - (d.labelWidth || 0) / 2 }) .attr('y', (d) => { if (!isVertical) { return x(d.bin0) + binWidth / 2 } // determine if label should be in the bar or above it. const labelHeight = (d.labelHeight || 0) + 2 * config.spacing.barLabelPadding const shouldShowInBar = labelHeight <= y(0) - y(d.count) const labelDy = shouldShowInBar ? labelHeight - config.spacing.barLabelPadding : -config.spacing.barLabelPadding d.shouldShowInBar = shouldShowInBar return y(d.count) + labelDy }) .classed('outside', (d) => !d.shouldShowInBar) // Always move labels to top _svg.node().appendChild(_labels.node()) } return _svg } renderCanvas(container) }, [data, config] ) return <div className="histogram-container" ref={ref} style={{ minWidth: config.width }} /> }
the_stack
// Controller for Settings screen which controls what is being displayed // and which UI to use. const ParentFrame = (function () { "use strict"; class Choice { label: string; url: string; checked: boolean; } let iFrame = null; let currentChoice = {} as Choice; let deferredErrors = []; let deferredStatus = []; let headers = ""; let modelToString = ""; const choices: Array<Choice> = [ { label: "classic", url: "classicDesktopFrame.html", checked: false }, { label: "new", url: "newDesktopFrame.html", checked: true }, { label: "new-mobile", url: "newMobilePaneIosFrame.html", checked: false } ]; function getQueryVariable(variable) { const vars = window.location.search.substring(1).split("&"); for (let i = 0; i < vars.length; i++) { const pair = vars[i].split("="); if (pair[0] === variable) { return pair[1]; } } return null; } function setDefault() { let uiDefault = getQueryVariable("default"); if (uiDefault === null) { uiDefault = "new"; } for (let iChoice = 0; iChoice < choices.length; iChoice++) { if (uiDefault === choices[iChoice].label) { choices[iChoice].checked = true; } else { choices[iChoice].checked = false; } } } function postMessageToFrame(eventName, data) { poster.postMessageToFrame(iFrame, eventName, data); } function render() { if (appInsights && headers) appInsights.trackEvent("analyzeHeaders"); postMessageToFrame("renderItem", headers); } function setFrame(frame) { iFrame = frame; if (iFrame) { // If we have any deferred status, signal them for (let iStatus = 0; iStatus < deferredStatus.length; iStatus++) { postMessageToFrame("updateStatus", deferredStatus[iStatus]); } // Clear out the now displayed status deferredStatus = []; // If we have any deferred errors, signal them for (let iError = 0; iError < deferredErrors.length; iError++) { postMessageToFrame("showError", { error: JSON.stringify(deferredErrors[iError][0]), message: deferredErrors[iError][1] }); } // Clear out the now displayed errors deferredErrors = []; render(); } } function eventListener(event) { if (!event || event.origin !== poster.site()) return; if (event.data) { switch (event.data.eventName) { case "frameActive": setFrame(event.source); break; case "LogError": Errors.log(JSON.parse(event.data.data.error), event.data.data.message); break; case "modelToString": modelToString = event.data.data; break; } } } function loadNewItem() { if (Office.context.mailbox.item) { GetHeaders.send(function (_headers, apiUsed) { headers = _headers; Diagnostics.set("API used", apiUsed); render(); }); } } function registerItemChangedEvent() { try { if (Office.context.mailbox.addHandlerAsync !== undefined) { Office.context.mailbox.addHandlerAsync(Office.EventType.ItemChanged, function () { Errors.clear(); Diagnostics.clear(); loadNewItem(); }); } } catch (e) { Errors.log(e, "Could not register item changed event"); } } // Tells the UI to show an error. function showError(error, message: string, suppressTracking?: boolean) { Errors.log(error, message, suppressTracking); if (iFrame) { postMessageToFrame("showError", { error: JSON.stringify(error), message: message }); } else { // We don't have an iFrame, so defer the message deferredErrors.push([error, message]); } } // Tells the UI to show an error. function updateStatus(statusText) { if (iFrame) { postMessageToFrame("updateStatus", statusText); } else { // We don't have an iFrame, so defer the status deferredStatus.push(statusText); } } function getSettingsKey() { try { return "frame" + Office.context.mailbox.diagnostics.hostName; } catch (e) { return "frame"; } } // Display primary UI function go(choice: Choice) { iFrame = null; currentChoice = choice; document.getElementById("uiFrame").src = choice.url; if (Office.context) { Office.context.roamingSettings.set(getSettingsKey(), choice); Office.context.roamingSettings.saveAsync(); } } function goDefaultChoice() { for (let iChoice = 0; iChoice < choices.length; iChoice++) { const choice = choices[iChoice]; if (choice.checked) { go(choice); return; } } } function create(parentElement, newType, newClass) { const newElement = $(document.createElement(newType)); if (newClass) { newElement.addClass(newClass); } if (parentElement) { parentElement.append(newElement); } return newElement; } // Create list of choices to display for the UI types function addChoices() { const list = $("#uiChoice-list"); list.empty(); for (let iChoice = 0; iChoice < choices.length; iChoice++) { const choice = choices[iChoice]; // Create html: <li class="ms-RadioButton"> const listItem = create(list, "li", "ms-RadioButton"); // Create html: <input tabindex="-1" type="radio" class="ms-RadioButton-input" value="classic"> const input = create(listItem, "input", "ms-RadioButton-input"); input.attr("tabindex", "-1"); input.attr("type", "radio"); input.attr("value", iChoice); // Create html: <label role="radio" class="ms-RadioButton-field" tabindex="0" aria-checked="false" name="uiChoice"> const label = create(listItem, "label", "ms-RadioButton-field"); label.attr("role", "radio"); label.attr("tabindex", "0"); label.attr("name", "uiChoice"); label.attr("value", choice.label); // Create html: <span class="ms-Label">classic</span> const inputSpan = create(label, "span", "ms-Label"); inputSpan.text(choice.label); } } // Hook the UI together for display function initFabric() { let i; const header = document.querySelector(".header-row"); const dialogSettings = header.querySelector("#dialog-Settings"); // Wire up the dialog const dialogSettingsComponent = new fabric["Dialog"](dialogSettings); const dialogDiagnostics = header.querySelector("#dialog-Diagnostics"); // Wire up the dialog const dialogDiagnosticsComponent = new fabric["Dialog"](dialogDiagnostics); const actionButtonElements = header.querySelectorAll(".ms-Dialog-action"); function actionHandler() { const action = this.id; function getDiagnostics() { let diagnostics = ""; try { const diagnosticMap = Diagnostics.get(); for (const diag in diagnosticMap) { if (diagnosticMap.hasOwnProperty(diag)) { diagnostics += diag + " = " + diagnosticMap[diag] + "\n"; } } } catch (e) { diagnostics += "ERROR: Failed to get diagnostics\n"; } const errors = Errors.get(); for (let iError = 0; iError < errors.length; iError++) { if (errors[iError]) { diagnostics += "ERROR: " + errors[iError] + "\n"; } } return diagnostics; } switch (action) { case "actionsSettings-OK": { // How did the user say to display it (UI to display) const iChoice = $("#uiChoice input:checked")[0].value; const choice: Choice = choices[iChoice]; if (choice.label !== currentChoice.label) { go(choice); } break; } case "actionsSettings-diag": { const diagnostics = getDiagnostics(); $("#diagnostics").text(diagnostics); dialogDiagnosticsComponent.open(); break; } } } // Wire up the buttons for (i = 0; i < actionButtonElements.length; i++) { new fabric["Button"](actionButtonElements[i], actionHandler); } const choiceGroup = dialogSettings.querySelectorAll(".ms-ChoiceFieldGroup"); new fabric["ChoiceFieldGroup"](choiceGroup[0]); const choiceFieldGroupElements = dialogSettings.querySelectorAll(".ms-ChoiceFieldGroup"); for (i = 0; i < choiceFieldGroupElements.length; i++) { new fabric["ChoiceFieldGroup"](choiceFieldGroupElements[i]); } const settingsButton = header.querySelector(".gear-button"); // When clicking the button, open the dialog settingsButton.onclick = function () { // Set the current choice in the UI. $("#uiChoice input").attr("checked", false); const labels = $("#uiChoice label"); labels.removeClass("is-checked"); labels.attr("aria-checked", "false"); const currentSelected = $("#uiChoice label[value=" + currentChoice.label + "]"); currentSelected.addClass("is-checked"); currentSelected.attr("aria-checked", "true"); const input = currentSelected.prevAll("input:first"); input.prop("checked", "true"); dialogSettingsComponent.open(); }; const copyButton = header.querySelector(".copy-button"); copyButton.onclick = function () { mhaStrings.copyToClipboard(modelToString); }; } function initUI() { setDefault(); addChoices(); initFabric(); try { const choice: Choice = Office.context.roamingSettings.get(getSettingsKey()); const input = $("#uiToggle" + choice.label); input.prop("checked", true); go(choice); } catch (e) { goDefaultChoice(); } registerItemChangedEvent(); window.addEventListener("message", eventListener, false); loadNewItem(); } return { initUI: initUI, updateStatus: updateStatus, showError: showError, get choice(): Choice { return currentChoice; } }; })(); Office.initialize = function () { $(document).ready(function () { ParentFrame.initUI(); }); };
the_stack
import {Values, Severity} from "@swim/util"; import type {Tag} from "./Tag"; import type {Mark} from "./Mark"; import type {Input} from "../input/Input"; import type {OutputSettings} from "../output/OutputSettings"; import type {Output} from "../output/Output"; import type {Display} from "../format/Display"; import {OutputStyle} from "../format/OutputStyle"; import {Format} from "../format/Format"; import {Unicode} from "../unicode/Unicode"; import {Base10} from "../number/Base10"; /** * Informational message attached to an input location. * @public */ export class Diagnostic implements Display { constructor(input: Input, tag: Tag, severity: Severity, message: string | undefined, note: string | undefined, cause: Diagnostic | null) { this.input = input; this.tag = tag; this.severity = severity; this.message = message; this.note = note; this.cause = cause; } /** @internal */ readonly input: Input; /** * The location in the `input` to which this diagnostic is attached. */ readonly tag: Tag; /** * The level of importance of this diagnostic. */ readonly severity: Severity; /** * The help message that describes this diagnostic. */ readonly message: string | undefined; /** * An informative comment on the source context to which this diagnostic is attached. */ readonly note: string | undefined; /** * The `Diagnostic` cause of this diagnostic, forming a linked chain of * diagnostics, or `null` if this diagnostic has no cause. */ readonly cause: Diagnostic | null; private lineDigits(): number { let digits = Base10.countDigits(this.tag.end.line); if (this.cause !== null) { digits = Math.max(digits, this.cause.lineDigits()); } return digits; } display<T>(output: Output<T>): Output<T> { const input = this.input.clone(); const start = this.tag.start; const end = this.tag.end; const severity = this.severity; const message = this.message; const note = this.note; const cause = this.cause; const contextLines = 2; const lineDigits = this.lineDigits(); output = Diagnostic.display(output, input, start, end, severity, message, note, cause, contextLines, lineDigits); return output; } private static display<T>(output: Output<T>, input: Input, start: Mark, end: Mark, severity: Severity, message: string | undefined, note: string | undefined, cause: Diagnostic | null, contextLines: number, lineDigits: number): Output<T> { do { if (message !== void 0) { output = Diagnostic.displayMessage(output, severity, message); output = output.writeln(); } output = Diagnostic.displayAnchor(output, input, start, lineDigits); output = output.writeln(); const cont = Diagnostic.displayContext(output, input, start, end, severity, note, cause, contextLines, lineDigits); const next = cont[0]; output = cont[1]; if (next !== null) { output = output.writeln(); input = next.input.clone(); start = next.tag.start; end = next.tag.end; severity = next.severity; message = next.message; note = next.note; cause = next.cause; } else { break; } } while (true); return output; } /** @internal */ static displayMessage<T>(output: Output<T>, severity: Severity, message: string | undefined): Output<T> { output = Diagnostic.formatSeverity(output, severity); output = output.write(severity.label); output = OutputStyle.reset(output); output = OutputStyle.bold(output); output = output.write(58/*':'*/); if (message !== void 0) { output = output.write(32/*' '*/).write(message); } output = OutputStyle.reset(output); return output; } private static displayAnchor<T>(output: Output<T>, input: Input, start: Mark, lineDigits: number): Output<T> { output = Diagnostic.displayLineLeadArrow(output, lineDigits); output = output.write(32/*' '*/); const id = input.id; if (id !== void 0) { output = Format.displayAny(output, id); } output = output.write(58/*':'*/); output = Format.displayNumber(output, start.line); output = output.write(58/*':'*/); output = Format.displayNumber(output, start.column); output = output.writeln(); output = Diagnostic.displayLineLead(output, lineDigits); return output; } private static displayContext<T>(output: Output<T>, input: Input, start: Mark, end: Mark, severity: Severity, note: string | undefined, cause: Diagnostic | null, contextLines: number, lineDigits: number): [Diagnostic | null, Output<T>] { let next = cause; const sameCause = cause !== null && cause.message === void 0 && Values.equal(input.id, cause.input.id); const causeOrder = sameCause ? (start.offset <= cause!.tag.start.offset ? -1 : 1) : 0; if (causeOrder === 1) { const cont = Diagnostic.displayContext(output, cause!.input.clone(), cause!.tag.start, cause!.tag.end, cause!.severity, cause!.note, cause!.cause, contextLines, lineDigits); next = cont[0]; output = cont[1]; output = output.writeln(); output = Diagnostic.displayLineLeadEllipsis(output, lineDigits); output = output.writeln(); } output = Diagnostic.displayLines(output, input, start, end, severity, contextLines, lineDigits); if (note !== void 0) { output = Diagnostic.displayNote(output, note, lineDigits); } if (causeOrder === -1) { output = output.writeln(); output = Diagnostic.displayLineLeadEllipsis(output, lineDigits); output = output.writeln(); const cont = Diagnostic.displayContext(output, cause!.input.clone(), cause!.tag.start, cause!.tag.end, cause!.severity, cause!.note, cause!.cause, contextLines, lineDigits); next = cont[0]; output = cont[1]; } return [next, output]; } private static displayLines<T>(output: Output<T>, input: Input, start: Mark, end: Mark, severity: Severity, contextLines: number, lineDigits: number): Output<T> { const startLine = start.line; const endLine = end.line; let line = input.line; while (line < startLine) { Diagnostic.consumeLineText(input, line); line += 1; } if (endLine - startLine > 2 * contextLines + 2) { while (line <= startLine + contextLines) { output = Diagnostic.displayLine(output, input, start, end, severity, line, lineDigits); line += 1; } output = Diagnostic.displayLineLeadEllipsis(output, lineDigits); output = output.write(32/*' '*/); output = Diagnostic.formatSeverity(output, severity); output = output.write(124/*'|'*/); output = OutputStyle.reset(output); output = output.writeln(); while (line < endLine - contextLines) { Diagnostic.consumeLineText(input, line); line += 1; } } while (line <= endLine) { output = Diagnostic.displayLine(output, input, start, end, severity, line, lineDigits); line += 1; } return output; } private static displayNote<T>(output: Output<T>, note: string | undefined, lineDigits: number): Output<T> { output = output.writeln(); output = Diagnostic.displayLineLead(output, lineDigits); output = output.writeln(); output = Diagnostic.displayLineComment(output, 'note', note, lineDigits); return output; } private static displayLine<T>(output: Output<T>, input: Input, start: Mark, end: Mark, severity: Severity, line: number, lineDigits: number): Output<T> { if (start.line === line && end.line === line) { output = Diagnostic.displaySingleLine(output, input, start, end, severity, line, lineDigits); } else if (start.line === line) { output = Diagnostic.displayStartLine(output, input, start, severity, line, lineDigits); } else if (end.line === line) { output = Diagnostic.displayEndLine(output, input, end, severity, line, lineDigits); } else { output = Diagnostic.displayMidLine(output, input, severity, line, lineDigits); } return output; } private static displaySingleLine<T>(output: Output<T>, input: Input, start: Mark, end: Mark, severity: Severity, line: number, lineDigits: number): Output<T> { output = Diagnostic.displayLineLeadNumber(output, line, lineDigits); output = output.write(32/*' '*/); for (let i = 1; i < input.column; i += 1) { output = output.write(32/*' '*/); } output = Diagnostic.displayLineText(output, input, line); output = Diagnostic.displayLineLead(output, lineDigits); output = output.write(32/*' '*/); let i = 1; while (i < start.column) { output = output.write(32/*' '*/); i += 1; } output = Diagnostic.formatSeverity(output, severity); while (i <= end.column) { output = output.write(94/*'^'*/); i += 1; } if (end.note !== void 0) { output = output.write(32/*' '*/).write(end.note); } output = OutputStyle.reset(output); return output; } private static displayStartLine<T>(output: Output<T>, input: Input, start: Mark, severity: Severity, line: number, lineDigits: number): Output<T> { output = Diagnostic.displayLineLeadNumber(output, line, lineDigits); output = output.write(32/*' '*/).write(32/*' '*/).write(32/*' '*/); for (let i = 1; i < input.column; i += 1) { output = output.write(32/*' '*/); } output = Diagnostic.displayLineText(output, input, line); output = Diagnostic.displayLineLead(output, lineDigits); output = output.write(32/*' '*/).write(32/*' '*/); output = Diagnostic.formatSeverity(output, severity); output = output.write(95/*'_'*/); let i = 1; while (i < start.column) { output = output.write(95/*'_'*/); i += 1; } output = output.write(94/*'^'*/); if (start.note !== void 0) { output = output.write(32/*' '*/).write(start.note); } output = OutputStyle.reset(output); output = output.writeln(); return output; } private static displayEndLine<T>(output: Output<T>, input: Input, end: Mark, severity: Severity, line: number, lineDigits: number): Output<T> { output = Diagnostic.displayLineLeadNumber(output, line, lineDigits); output = output.write(32/*' '*/); output = Diagnostic.formatSeverity(output, severity); output = output.write(124/*'|'*/); output = OutputStyle.reset(output); output = output.write(32/*' '*/); output = Diagnostic.displayLineText(output, input, line); output = Diagnostic.displayLineLead(output, lineDigits); output = output.write(32/*' '*/); output = Diagnostic.formatSeverity(output, severity); output = output.write(124/*'|'*/).write(95/*'_'*/); let i = 1; while (i < end.column) { output = output.write(95/*'_'*/); i += 1; } output = output.write(94/*'^'*/); if (end.note !== void 0) { output = output.write(32/*' '*/).write(end.note); } output = OutputStyle.reset(output); return output; } private static displayMidLine<T>(output: Output<T>, input: Input, severity: Severity, line: number, lineDigits: number): Output<T> { output = Diagnostic.displayLineLeadNumber(output, line, lineDigits); output = output.write(32/*' '*/); output = Diagnostic.formatSeverity(output, severity); output = output.write(124/*'|'*/); output = OutputStyle.reset(output); output = output.write(32/*' '*/); output = Diagnostic.displayLineText(output, input, line); return output; } private static displayLineComment<T>(output: Output<T>, label: string, comment: string | undefined, lineDigits: number): Output<T> { output = Diagnostic.displayLineLeadComment(output, lineDigits); output = output.write(32/*' '*/); output = OutputStyle.bold(output); output = output.write(label).write(58/*':'*/); output = OutputStyle.reset(output); if (comment !== void 0) { output = output.write(32/*' '*/).write(comment); } return output; } private static displayLineLead<T>(output: Output<T>, lineDigits: number): Output<T> { output = OutputStyle.blueBold(output); const padding = 1 + lineDigits; for (let i = 0; i < padding; i += 1) { output = output.write(32/*' '*/); } output = output.write(124/*'|'*/); output = OutputStyle.reset(output); return output; } private static displayLineLeadComment<T>(output: Output<T>, lineDigits: number): Output<T> { output = OutputStyle.blueBold(output); const padding = 1 + lineDigits; for (let i = 0; i < padding; i += 1) { output = output.write(32/*' '*/); } output = output.write(61/*'='*/); output = OutputStyle.reset(output); return output; } private static displayLineLeadArrow<T>(output: Output<T>, lineDigits: number): Output<T> { for (let i = 0; i < lineDigits; i += 1) { output = output.write(32/*' '*/); } output = OutputStyle.blueBold(output); output = output.write(45/*'-'*/).write(45/*'-'*/).write(62/*'>'*/); output = OutputStyle.reset(output); return output; } private static displayLineLeadEllipsis<T>(output: Output<T>, lineDigits: number): Output<T> { output = OutputStyle.blueBold(output); for (let i = 0; i < lineDigits; i += 1) { output = output.write(46/*'.'*/); } output = OutputStyle.reset(output); output = output.write(32/*' '*/).write(32/*' '*/); return output; } private static displayLineLeadNumber<T>(output: Output<T>, line: number, lineDigits: number): Output<T> { const padding = lineDigits - Base10.countDigits(line); for (let i = 0; i < padding; i += 1) { output = output.write(32/*' '*/); } output = OutputStyle.blueBold(output); output = Format.displayNumber(output, line); output = output.write(32/*' '*/).write(124/*'|'*/); output = OutputStyle.reset(output); return output; } private static displayLineText<T>(output: Output<T>, input: Input, line: number): Output<T> { while (input.isCont() && input.line === line) { output = output.write(input.head()); input = input.step(); } if (input.line === line) { output = output.writeln(); } return output; } private static consumeLineText(input: Input, line: number): void { while (input.isCont() && input.line === line) { input = input.step(); } } private static formatSeverity<T>(output: Output<T>, severity: Severity): Output<T> { switch (severity.level) { case Severity.FATAL_LEVEL: case Severity.ALERT_LEVEL: case Severity.ERROR_LEVEL: output = OutputStyle.redBold(output); break; case Severity.WARNING_LEVEL: output = OutputStyle.yellowBold(output); break; case Severity.NOTE_LEVEL: output = OutputStyle.greenBold(output); break; case Severity.INFO_LEVEL: output = OutputStyle.cyanBold(output); break; case Severity.DEBUG_LEVEL: case Severity.TRACE_LEVEL: default: output = OutputStyle.magentaBold(output); } return output; } toString(settings?: OutputSettings): string { return Format.display(this, settings); } static create(input: Input, tag: Tag, severity: Severity, cause?: Diagnostic | null): Diagnostic; static create(input: Input, tag: Tag, severity: Severity, message: string | undefined, cause?: Diagnostic | null): Diagnostic; static create(input: Input, tag: Tag, severity: Severity, message: string | undefined, note: string | undefined, cause?: Diagnostic | null): Diagnostic; static create(input: Input, tag: Tag, severity: Severity, message?: Diagnostic | null | string | undefined, note?: Diagnostic | null | string | undefined, cause?: Diagnostic | null): Diagnostic { if (arguments.length === 3) { // (input, tag, severity) cause = null; note = void 0; message = void 0; } else if (arguments.length === 4) { if (message === null || message instanceof Diagnostic) { // (input, tag, severity, cause) cause = message; message = void 0; } else { // (input, tag, severity, message) cause = null; } } else if (arguments.length === 5) { if (note === null || note instanceof Diagnostic) { // (input, tag, severity, message, cause) cause = note; note = void 0; } else { // (input, tag, severity, message, note) cause = null; } } else { // (input, tag, severity, message, note, cause) if (cause === void 0) { cause = null; } } return new Diagnostic(input.clone(), tag, severity, message as string | undefined, note as string | undefined, cause); } static message(message: string, input: Input, cause?: Diagnostic | null): Diagnostic; static message(message: string, input: Input, note: string, cause?: Diagnostic | null): Diagnostic; static message(message: string, input: Input, severity: Severity, cause?: Diagnostic | null): Diagnostic; static message(message: string, input: Input, severity?: Severity, note?: string, cause?: Diagnostic | null): Diagnostic; static message(message: string, input: Input, severity?: Diagnostic | null | Severity | string | undefined, note?: Diagnostic | null | string | undefined, cause?: Diagnostic | null): Diagnostic { if (arguments.length === 2) { // (message, input) cause = null; note = void 0; severity = Severity.error(); } else if (arguments.length === 3) { if (severity === null || severity instanceof Diagnostic) { // (message, input, cause) cause = severity; severity = Severity.error(); } else if (typeof severity === "string") { // (message, input, note) cause = null; note = severity; severity = Severity.error(); } else { // (message, input, severity) cause = null; } } else if (arguments.length === 4) { if (typeof severity === "string") { // (message, input, note, cause) cause = note as Diagnostic | null; note = severity; severity = Severity.error(); } else if (note === null || note instanceof Diagnostic) { // (message, input, severity, cause) cause = note; note = void 0; } else { // (message, input, severity, note) cause = null; } } else { // (message, input, severity, note, cause) if (cause === void 0) { cause = null; } } const mark = input.mark; const source = input.clone(); source.seek(); return new Diagnostic(source, mark, severity as Severity, message, note as string | undefined, cause); } static unexpected(input: Input, cause?: Diagnostic | null): Diagnostic; static unexpected(input: Input, note: string, cause?: Diagnostic | null): Diagnostic; static unexpected(input: Input, severity: Severity, cause?: Diagnostic | null): Diagnostic; static unexpected(input: Input, severity?: Severity, note?: string, cause?: Diagnostic | null): Diagnostic; static unexpected(input: Input, severity?: Diagnostic | null | Severity | string | undefined, note?: Diagnostic | null | string | undefined, cause?: Diagnostic | null): Diagnostic { if (arguments.length === 1) { // (input) cause = null; severity = Severity.error(); } else if (arguments.length === 2) { if (severity === null || severity instanceof Diagnostic) { // (input, cause) cause = severity; severity = Severity.error(); } else if (typeof severity === "string") { // (input, note) cause = null; note = severity; severity = Severity.error(); } else { // (input, severity) cause = null; } } else if (arguments.length === 3) { if (typeof severity === "string") { // (input, note, cause) cause = note as Diagnostic | null; note = severity; severity = Severity.error(); } else if (note === null || note instanceof Diagnostic) { // (input, severity, cause) cause = note; note = void 0; } else { // (input, severity, note) cause = null; } } else { // (input, severity, note, cause) if (cause === void 0) { cause = null; } } let message; if (input.isCont()) { let output = Unicode.stringOutput().write("unexpected").write(32/*' '*/); output = Format.debugChar(output, input.head()); message = output.bind(); } else { message = "unexpected end of input"; } const mark = input.mark; const source = input.clone(); source.seek(); return new Diagnostic(source, mark, severity as Severity, message, note as string | undefined, cause); } static expected(expected: string | number, input: Input, cause?: Diagnostic | null): Diagnostic; static expected(expected: string | number, input: Input, note: string, cause?: Diagnostic | null): Diagnostic; static expected(expected: string | number, input: Input, severity: Severity, cause?: Diagnostic | null): Diagnostic; static expected(expected: string | number, input: Input, severity?: Severity, note?: string, cause?: Diagnostic | null): Diagnostic; static expected(expected: string | number, input: Input, severity?: Diagnostic | null | Severity | string | undefined, note?: Diagnostic | null | string | undefined, cause?: Diagnostic | null): Diagnostic { if (arguments.length === 2) { // (excpected, input) cause = null; severity = Severity.error(); } else if (arguments.length === 3) { if (severity === null || severity instanceof Diagnostic) { // (excpected, input, cause) cause = severity; severity = Severity.error(); } else if (typeof severity === "string") { // (excpected, input, note) cause = null; note = severity; severity = Severity.error(); } else { // (expected, input, severity) cause = null; } } else if (arguments.length === 4) { if (typeof severity === "string") { // (excpected, input, note, cause) cause = note as Diagnostic | null; note = severity; severity = Severity.error(); } else if (note === null || note instanceof Diagnostic) { // (excpected, input, severity, cause) cause = note; note = void 0; } else { // (excpected, input, severity, note) cause = null; } } else { // (excpected, input, severity, note, cause) if (cause === void 0) { cause = null; } } let output = Unicode.stringOutput().write("expected").write(32/*' '*/); if (typeof expected === "number") { output = Format.debugChar(output, expected); } else { output = output.write(expected); } output = output.write(44/*','*/).write(32/*' '*/).write("but found").write(32/*' '*/); if (input.isCont()) { output = Format.debugChar(output, input.head()); } else { output = output.write("end of input"); } const message = output.bind(); const mark = input.mark; const source = input.clone(); source.seek(); return new Diagnostic(source, mark, severity as Severity, message, note as string | undefined, cause); } }
the_stack
import { useState } from 'react'; import { message, Modal } from 'antd'; import { Content, Header } from '@dtinsight/molecule/esm/workbench/sidebar'; import { FolderTree } from '@dtinsight/molecule/esm/workbench/sidebar/explore/index'; import { debounce } from 'lodash'; import type { IActionBarItemProps, IMenuItemProps, ITreeNodeItemProps, } from '@dtinsight/molecule/esm/components'; import { ActionBar } from '@dtinsight/molecule/esm/components'; import type { IFolderTree } from '@dtinsight/molecule/esm/model'; import { FileTypes } from '@dtinsight/molecule/esm/model'; import { connect } from '@dtinsight/molecule/esm/react'; import { catalogueService } from '@/services'; import { CATELOGUE_TYPE, ID_COLLECTIONS, RESOURCE_ACTIONS } from '@/constant'; import resourceManagerTree from '../../services/resourceManagerService'; import type { IFormFieldProps } from './resModal'; import ResModal from './resModal'; import ajax from '../../api'; import FolderModal from '../function/folderModal'; import type molecule from '@dtinsight/molecule'; import type { CatalogueDataProps, IResourceProps } from '@/interface'; import { DetailInfoModal } from '@/components/detailInfo'; import './index.scss'; const { confirm } = Modal; const FolderTreeView = connect(resourceManagerTree, FolderTree); interface IResourceViewProps { panel: molecule.model.IActivityBarItem; headerToolBar: IActionBarItemProps[]; } enum DELETE_SOURCE { folder, file, } type IRightClickDataProps = IFormFieldProps | undefined; export default ({ panel, headerToolBar, entry }: IResourceViewProps & IFolderTree) => { const [isModalShow, setModalShow] = useState(false); const [isViewModalShow, setViewModalShow] = useState(false); const [detailLoading, setDetailLoading] = useState(false); const [detailData, setDetailData] = useState<Record<string, any> | undefined>(undefined); const [isCoverUpload, setCoverUpload] = useState(false); const [rightClickData, setData] = useState<IRightClickDataProps>(undefined); const [folderVisible, setFolderVisible] = useState(false); const [expandKeys, setExpandKeys] = useState<string[]>([]); const [folderData, setFolderData] = useState< Partial<Pick<CatalogueDataProps, 'id' | 'parentId' | 'name'>> | undefined >(undefined); const updateNodePid = async (node: ITreeNodeItemProps) => { catalogueService.loadTreeNode(node.data, CATELOGUE_TYPE.RESOURCE); }; const handleUpload = () => { setModalShow(true); setCoverUpload(false); }; const handleReplace = () => { setModalShow(true); setCoverUpload(true); }; const toggleUploadModal = () => { setModalShow(false); setData(undefined); }; const handleCreate = () => { setFolderVisible(true); setFolderData(undefined); }; const debounceRefreshNode = debounce(() => { const { folderTree } = resourceManagerTree.getState(); if (folderTree?.current) { if (folderTree?.current.fileType === FileTypes.File) { const parentNode = resourceManagerTree.get( `${folderTree?.current.data.parentId}-folder`, ); // 更新父节点 updateNodePid(parentNode!); } else { // 更新 update 目录 updateNodePid(folderTree.current); } } else { const rootFolder = catalogueService.getRootFolder(CATELOGUE_TYPE.RESOURCE); if (rootFolder) { updateNodePid(rootFolder); } } }, 300); const handleHeaderClick = (e: React.MouseEvent<Element, MouseEvent>, item: IMenuItemProps) => { e.preventDefault(); switch (item?.id) { // 刷新 case 'refresh': debounceRefreshNode(); break; default: break; } }; const handleHeaderContextClick = ( e: React.MouseEvent<Element, MouseEvent>, item?: IMenuItemProps, ) => { e.preventDefault(); switch (item?.id) { case ID_COLLECTIONS.RESOURCE_UPLOAD: handleUpload(); break; case ID_COLLECTIONS.RESOURCE_REPLACE: handleReplace(); break; case ID_COLLECTIONS.RESOURCE_CREATE: handleCreate(); break; default: break; } }; const handleRightClick = (treeNode: ITreeNodeItemProps) => { const ROOT_FOLDER_ACTIONS = [RESOURCE_ACTIONS.UPLOAD, RESOURCE_ACTIONS.CREATE]; switch (treeNode.fileType) { case FileTypes.File: { return [RESOURCE_ACTIONS.REPLACE, RESOURCE_ACTIONS.DELETE]; } case FileTypes.Folder: { if (treeNode.name === '资源管理') { return ROOT_FOLDER_ACTIONS; } return ROOT_FOLDER_ACTIONS.concat([RESOURCE_ACTIONS.EDIT, RESOURCE_ACTIONS.DELETE]); } case FileTypes.RootFolder: { // In general, root folder have no contextMenu, because it can't be clicked return ROOT_FOLDER_ACTIONS; } default: return []; } }; const handleExpandKeys = (keys: string[]) => { setExpandKeys(keys); }; const handleDelete = (treeNode: ITreeNodeItemProps, source: keyof typeof DELETE_SOURCE) => { if (source === 'file') { confirm({ title: '确认要删除此资源吗?', content: '删除的资源无法找回!', onOk() { const params = { resourceId: treeNode.data.id, }; ajax.delOfflineRes(params).then((res) => { if (res.code === 1) { message.success('资源删除成功'); const parentNode = resourceManagerTree.get( `${treeNode.data.parentId}-folder`, )!; // update the parent updateNodePid(parentNode); } }); }, onCancel() {}, }); } else { confirm({ title: '确认要删除此文件夹吗?', content: '删除的文件夹无法恢复!', onOk() { const params = { id: treeNode.data.id, }; ajax.delOfflineFolder(params).then((res) => { if (res.code === 1) { message.success('文件夹删除成功'); const parentNode = resourceManagerTree.get( `${treeNode.data.parentId}-folder`, )!; // update the parent updateNodePid(parentNode); } }); }, onCancel() {}, }); } }; const handleContextMenu = (contextMenu: IMenuItemProps, treeNode?: ITreeNodeItemProps) => { const menuId = contextMenu.id; switch (menuId) { case ID_COLLECTIONS.RESOURCE_DELETE: { handleDelete(treeNode!, treeNode!.fileType === FileTypes.File ? 'file' : 'folder'); break; } case ID_COLLECTIONS.RESOURCE_EDIT: { setFolderData(treeNode!.data); setFolderVisible(true); break; } case ID_COLLECTIONS.RESOURCE_UPLOAD: { setData({ nodePid: treeNode!.data.id, }); handleUpload(); break; } case ID_COLLECTIONS.RESOURCE_REPLACE: { ajax.getOfflineRes({ resourceId: treeNode?.data.id, }).then((res) => { if (res.code === 1) { const { originFileName, resourceType, computeType, resourceDesc } = res.data as IResourceProps; setData({ id: treeNode?.data.id, originFileName, resourceType, computeType, resourceDesc, }); handleReplace(); } }); break; } case ID_COLLECTIONS.RESOURCE_CREATE: { setFolderData({ parentId: treeNode!.data.id }); setFolderVisible(true); break; } default: break; } }; const handleSelect = (file?: ITreeNodeItemProps) => { resourceManagerTree.setActive(file?.id); if (file) { if (file.isLeaf) { setViewModalShow(true); setDetailLoading(true); ajax.getOfflineRes({ resourceId: file.data.id, }) .then((res) => { if (res.code === 1) { setDetailData(res.data); } }) .finally(() => { setDetailLoading(false); }); } } }; const handleCloseViewModal = () => { setViewModalShow(false); setDetailData(undefined); }; const handleCloseFolderModal = () => { setFolderVisible(false); setFolderData(undefined); }; // 添加文件夹 const handleAddCatalogue = (params: { nodePid: number; nodeName: string }) => { return ajax.addOfflineCatalogue(params).then((res) => { if (res.code === 1) { const parentNode = resourceManagerTree.get(`${params.nodePid}-folder`); if (parentNode) { updateNodePid(parentNode); } return true; } return false; }); }; // 编辑文件夹 const handleEditCatalogue = (params: { nodePid: number; nodeName: string; id: number; type: string; }) => { return ajax .editOfflineCatalogue({ ...params, type: 'folder' }) // 文件夹编辑,新增参数固定为folder .then((res) => { if (res.code === 1) { const currentNode = resourceManagerTree.get(`${params.id}-folder`); const parentNode = resourceManagerTree.get(`${params.nodePid}-folder`); // the saving position has been changed if (currentNode?.data.parentId !== params.nodePid) { const nextParentNode = resourceManagerTree.get(currentNode?.data.parentId); updateNodePid(nextParentNode!); } if (parentNode) { updateNodePid(parentNode); } return true; } return false; }); }; // 新增资源 const handleAddResource = (params: any) => { return ajax.addOfflineResource(params).then((res) => { if (res.code === 1) { message.success('资源上传成功!'); const parentNode = resourceManagerTree.get(`${params.nodePid}-folder`)!; updateNodePid(parentNode); return true; } return false; }); }; // 替换资源 const handleReplaceResource = (params: any) => { return ajax.replaceOfflineResource(params).then((res) => { if (res.code === 1) { message.success('资源替换成功!'); return true; } return false; }); }; return ( <div className="resourceManager-container"> <Header title="资源管理" toolbar={ <ActionBar data={headerToolBar} onClick={handleHeaderClick} onContextMenuClick={handleHeaderContextClick} /> } /> <Content> <div tabIndex={0} className="resourceManager-content"> <FolderTreeView onExpandKeys={handleExpandKeys} expandKeys={expandKeys} onRightClick={handleRightClick} draggable={false} onSelectFile={handleSelect} onLoadData={updateNodePid} onClickContextMenu={handleContextMenu} entry={entry} panel={panel} /> </div> </Content> <ResModal visible={isModalShow} defaultValue={rightClickData} isCoverUpload={isCoverUpload} onAddResource={handleAddResource} onReplaceResource={handleReplaceResource} onClose={toggleUploadModal} /> <DetailInfoModal title="资源详情" data={detailData} type={CATELOGUE_TYPE.RESOURCE} loading={detailLoading} visible={isViewModalShow} onCancel={handleCloseViewModal} /> <FolderModal dataType={CATELOGUE_TYPE.RESOURCE} isModalShow={folderVisible} toggleCreateFolder={handleCloseFolderModal} treeData={catalogueService.getRootFolder(CATELOGUE_TYPE.RESOURCE)?.data} defaultData={folderData} addOfflineCatalogue={handleAddCatalogue} editOfflineCatalogue={handleEditCatalogue} /> </div> ); };
the_stack
import { Component, OnDestroy, ChangeDetectorRef, ViewContainerRef, ViewChild, Input, AfterContentInit, AfterViewChecked, AfterViewInit, ElementRef, OnChanges } from '@angular/core'; import { Subscription, Subject, Observable } from 'rxjs'; import { ComplexScrollBoxSBVComponent } from './sbv/component'; import { ComplexScrollBoxSBHComponent } from './sbh/component'; import guid from '../../tools/tools.guid'; export interface IScrollBoxSelection { selection: string; original: string; anchor: number; anchorOffset: number; focus: number; focusOffset: number; } export interface IRange { start: number; end: number; } export interface IRow { [key: string]: any; } export interface IStorageInformation { count: number; } export interface IRowsPacket { range: IRange; rows: IRow[]; } export interface IBoxSize { width: number; height: number; } export interface IDataAPI { getRange: (range: IRange) => IRowsPacket; getLastFrame: () => IRange; getStorageInfo: () => IStorageInformation; getComponentFactory: () => any; getItemHeight: () => number; updatingDone: (range: IRange) => void; cleanUpClipboard?: (str: string) => string; onStorageUpdated: Subject<IStorageInformation>; onScrollTo: Subject<number>; onScrollUntil: Subject<number>; onRowsDelivered: Subject<IRowsPacket>; onSourceUpdated: Subject<void>; onRerequest: Subject<void>; onRedraw: Subject<void>; } export interface ISettings { minScrollTopScale: number; // To "catch" scroll event in reverse direction (to up) we should always keep minimal scroll offset minScrollTopNotScale: number; // To "catch" scroll event in reverse direction (to up) we should always keep minimal scroll offset maxScrollHeight: number; // Maximum scroll area height in px. scrollToOffset: number; // How many items show before item defined on scrollTo scrollBarSize: number; // Size of scroll bar: height for horizontal; width for vertical. In px. } interface IRowNodeInfo { path: string; index: number; } interface ISelectedNodeInfo { index: number; path: string; offset: number; node: Node | undefined; fragment: string; } enum EKeys { ArrowUp = 'ArrowUp', ArrowDown = 'ArrowDown', ArrowLeft = 'ArrowLeft', ArrowRight = 'ArrowRight', PageUp = 'PageUp', PageDown = 'PageDown', Home = 'Home', End = 'End', KeyC = 'KeyC', KeyX = 'KeyX', undefined = 'undefined' } enum EDirection { Down, Up, } const DefaultSettings = { minScrollTopScale : 100, // To "catch" scroll event in reverse direction (to up) we should always keep minimal scroll offset minScrollTopNotScale : 0, // To "catch" scroll event in reverse direction (to up) we should always keep minimal scroll offset maxScrollHeight : 100000, // Maximum scroll area height in px. scrollToOffset : 5, // How many items show before item defined on scrollTo scrollBarSize : 8, // Size of scroll bar: height for horizontal; width for vertical. In px. }; const CRowIndexAttr = 'data-sb-row-index'; export function copyTextToClipboard(text: string) { [ { r: /\u00a0/g, m: '&nbsp;' }, { r: /\t/g, m: '&#9;' }, { r: /</g, m: '&lt;' }, { r: />/g, m: '&gt;' }, { r: /[\n\r]/g, m: '<br>' }, { r: /\s/g, m: '&nbsp;' }, // &#32; { r: /&#9;/g, m: '\u0009' } ].forEach((toBeChecked) => { text = text.replace(toBeChecked.r, toBeChecked.m); }); // Oldschool (modern class Clipboard gives exeptions for this moment: 13.09.2019) const selection = document.getSelection(); const element = document.createElement('pre'); // This is important to use tag <PRE> - it allows delivery into clipboard such "things" like tabs element.style.opacity = '0.0001'; element.style.position = 'absolute'; element.style.userSelect = 'all'; element.style.width = '1px'; element.style.height = '1px'; element.style.overflow = 'hidden'; element.className = 'noreset'; element.innerHTML = text; document.body.appendChild(element); const range = document.createRange(); range.selectNode(element); selection.empty(); selection.addRange(range); document.execCommand('copy'); selection.empty(); document.body.removeChild(element); } @Component({ selector: 'lib-complex-scrollbox', templateUrl: './template.html', styleUrls: ['./styles.less'], }) export class ComplexScrollBoxComponent implements OnDestroy, AfterContentInit, AfterViewChecked, AfterViewInit, OnChanges { @ViewChild('container', {static: false}) _ng_nodeContainer: ElementRef; @ViewChild('holder', {static: false}) _ng_nodeHolder: ElementRef; @ViewChild(ComplexScrollBoxSBVComponent, {static: false}) _ng_sbvCom: ComplexScrollBoxSBVComponent; @ViewChild(ComplexScrollBoxSBHComponent, {static: false}) _ng_sbhCom: ComplexScrollBoxSBHComponent; @Input() public API: IDataAPI | undefined; @Input() public settings: ISettings | undefined; public _ng_rows: Array<IRow | number> = []; public _ng_factory: any; public _ng_rowHeight: number = 0; public _ng_horOffset: number = 0; public _ng_horScrolling: boolean = false; public _ng_guid: string = guid(); public _ng_containerSize: IBoxSize | undefined; public _ng_holderSize: { width: number, hash: string } = { width: 0, hash: '' }; private _subjects = { onScrolled: new Subject<IRange>(), onOffset: new Subject<number>(), }; private _injected: { rows: Array<IRow | number>, offset: number, count: number, } = { rows: [], offset: 0, count: 0, }; private _settings: ISettings = DefaultSettings; private _storageInfo: IStorageInformation | undefined; private _subscriptions: { [key: string]: Subscription | undefined } = { }; private _destroyed: boolean = false; private _horScrollingTimer: any = -1; private _localMouseDown: boolean = false; private _selection: { focus: ISelectedNodeInfo, anchor: ISelectedNodeInfo, going: boolean, out: boolean; selection: string | undefined; restored: boolean; } = { focus: { index: -1, path: '', offset: -1, node: undefined, fragment: '' }, anchor: { index: -1, path: '', offset: -1, node: undefined, fragment: '' }, going: false, out: false, selection: undefined, restored: true, }; private _item: { height: number, } = { height: 0, }; private _state: { start: number; end: number; count: number; } = { start: 0, end: 0, count: 0, }; private _renderState: { timer: any, requests: number, } = { timer: -1, requests: 0, }; constructor(private _cdRef: ChangeDetectorRef, private _vcRef: ViewContainerRef) { } public ngAfterContentInit() { if (this.API === undefined) { return; } if (this.settings !== undefined) { this._settings = Object.assign(DefaultSettings, this._settings); } this._ng_factory = this.API.getComponentFactory(); // Get information about storage this._storageInfo = this.API.getStorageInfo(); // Store item height this._item.height = this.API.getItemHeight(); this._ng_rowHeight = this._item.height; // Update data about sizes this._updateContainerSize(); // Subscribe this._subscriptions.onRowsDelivered = this.API.onRowsDelivered.asObservable().subscribe(this._onRowsDelivered.bind(this)); this._subscriptions.onScrollTo = this.API.onScrollTo.asObservable().subscribe(this._onScrollTo.bind(this, true)); this._subscriptions.onScrollUntil = this.API.onScrollUntil.asObservable().subscribe(this._onScrollUntil.bind(this)); this._subscriptions.onStorageUpdated = this.API.onStorageUpdated.asObservable().subscribe(this._onStorageUpdated.bind(this)); this._subscriptions.onRedraw = this.API.onRedraw.asObservable().subscribe(this._onRedraw.bind(this)); this._subscriptions.onRerequest = this.API.onRerequest.asObservable().subscribe(this._onRerequest.bind(this)); this._subscriptions.onSourceUpdated = this.API.onSourceUpdated.asObservable().subscribe(this._onSourceUpdated.bind(this)); // Init first range this._getInitalRange(); // Binding this._ng_sbv_update = this._ng_sbv_update.bind(this); this._ng_sbv_pgUp = this._ng_sbv_pgUp.bind(this); this._ng_sbv_pgDown = this._ng_sbv_pgDown.bind(this); this._updateSbvPosition = this._updateSbvPosition.bind(this); this._ng_sbv_getRowsCount = this._ng_sbv_getRowsCount.bind(this); this._ng_sbh_update = this._ng_sbh_update.bind(this); this._ng_sbh_left = this._ng_sbh_left.bind(this); this._ng_sbh_right = this._ng_sbh_right.bind(this); } public ngAfterViewInit() { // Update data about sizes this._updateContainerSize(true); this._updateHolderSize(true); // Update vertical scroll bar this._updateSbvPosition(); // Update this._forceUpdate(); } public ngAfterViewChecked() { // this._selection_restore(); } public ngOnDestroy() { this._destroyed = true; Object.keys(this._subscriptions).forEach((key: string) => { this._subscriptions[key].unsubscribe(); }); this._ng_rows = [];     } public ngOnChanges() { } public setFocus() { if (this._ng_nodeContainer === undefined || this._ng_nodeContainer === null) { return; } this._ng_nodeContainer.nativeElement.focus(); } public _ng_onWindowMouseMove(event: MouseEvent) { if (!this._selection.going) { return; } this._ng_nodeHolder.nativeElement.focus(); } public _ng_onSelectStart(event: Event) { // Set selection as started this._ng_nodeHolder.nativeElement.focus(); this._selection_drop(true); this._selection.going = true; } public _ng_onWindowMouseUp(event: MouseEvent) { if (!this._selection.going) { return; } // Set selection as started this._selection.going = false; // Check selection const selection: Selection = document.getSelection(); if (selection.toString() === '') { this._selection_drop(); } } public _ng_onMouseLeaveHolder(event: MouseEvent) { this._selection.out = true; } public _ng_onMouseOverHolder(event: MouseEvent) { this._selection.out = false; } public _ng_onMouseDownHolder(event: MouseEvent) { this._localMouseDown = true; if (event.button !== 0) { return; } this._selection_drop(true); } public _ng_onSelectChange(event: Event) { if (!this._selection.going) { // This selection isn't on element return; } this._ng_nodeHolder.nativeElement.focus(); if (!this._selection.restored) { return false; } if (this._selection.out) { this._selection.restored = false; this._selection_UpdateFocus(undefined); this._selection_scroll(); return false; } const selection: Selection = document.getSelection(); this._selection_UpdateFocus(selection); this._selection_UpdateAnchor(selection); this._selection_scroll(); this._selection_save(selection); } public _ng_getHolderStyles(): { [key: string]: any } { return { marginLeft: `-${this._ng_horOffset}px`, }; } public _ng_isRowPending(row: IRow): boolean { return typeof row === 'number'; } public _ng_isSBVVisible(): boolean { return this._state.count < this._storageInfo.count; } public _ng_onBrowserWindowMouseDown(event: MouseEvent) { if (!this._localMouseDown) { this._selection_drop(true); } this._localMouseDown = false; } public _ng_onBrowserWindowResize(event?: Event) { // Update data about sizes this._updateContainerSize(true); // Check currect state if (this._state.start + this._state.count > this._state.end) { this._state.end = this._state.start + this._state.count; if (this._state.end > this._storageInfo.count - 1) { this._state.end = this._storageInfo.count - 1; this._state.start = (this._state.end - this._state.count) > 0 ? (this._state.end - this._state.count) : 0; } this._render(); // Notification: update is done this.API.updatingDone({ start: this._state.start, end: this._state.end }); } // Update scrollbar if (this._ng_sbvCom !== undefined && this._ng_sbvCom !== null) { this._ng_sbvCom.recalc(); } } public _ng_onWheel(event: WheelEvent) { if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) { this._ng_sbh_update(this._ng_horOffset + event.deltaX, true); } else { this._ng_sbv_update(Math.abs(event.deltaY), event.deltaY > 0 ? 1 : -1, false); } event.preventDefault(); return false; } public _ng_onKeyDown(event: KeyboardEvent) { if (event.code === EKeys.KeyC) { if (!(event.ctrlKey || event.metaKey)) { return true; } } if (event.code === EKeys.KeyX) { if (!(event.ctrlKey || event.metaKey)) { return true; } } if ([EKeys.KeyC, EKeys.KeyX, EKeys.ArrowLeft, EKeys.ArrowRight, EKeys.ArrowDown, EKeys.ArrowUp, EKeys.End, EKeys.Home, EKeys.PageDown, EKeys.PageUp].indexOf(event.code as EKeys) === -1) { return true; } event.preventDefault(); this._onKeyboardAction(event.code as EKeys); return false; } public _ng_getItemStyles(): { [key: string]: any } { return { height: `${this._item.height}px`, }; } public _ng_sbv_update(change: number, direction: number, outside: boolean) { if (this._state.start === 0 && direction < 0 && this._injected.offset === 0) { return; } // Calculate first row let offset: number = Math.round(change / this._item.height); if (offset === 0) { offset = 1; } this._setFrame(this._state.start + offset * direction, outside); this._softRender(); } public _ng_sbv_pgUp() { this._onKeyboardAction(EKeys.PageUp); } public _ng_sbv_pgDown() { this._onKeyboardAction(EKeys.PageDown); } public _ng_sbv_getRowsCount(): number { return this._storageInfo.count; } public _ng_sbh_left() { this._updateHolderSize(); this._ng_sbhCom.toLeft(); } public _ng_sbh_right() { this._updateHolderSize(); this._ng_sbhCom.toRight(); } public _ng_sbh_onMouseOver() { this._updateHolderSize(); } public _ng_sbh_update(offset: number, setOffsetOnBar: boolean = false) { if (this._ng_sbhCom === undefined || this._ng_sbhCom === null) { return; } this._updateHolderSize(); clearTimeout(this._horScrollingTimer); this._ng_horScrolling = true; if (offset < 0) { offset = 0; } if (offset > this._ng_holderSize.width - this._ng_containerSize.width + this._ng_sbhCom.getMinOffset()) { offset = this._ng_holderSize.width - this._ng_containerSize.width + this._ng_sbhCom.getMinOffset(); } offset = isNaN(offset) ? 0 : (isFinite(offset) ? offset : 0); if (this._ng_horOffset !== offset) { this._subjects.onOffset.next(offset); } this._ng_horOffset = offset; this._horScrollingTimer = setTimeout(() => { this._ng_horScrolling = false; this._forceUpdate(); }, 1000); this._forceUpdate(); if (setOffsetOnBar) { this._ng_sbhCom.setOffset(this._ng_horOffset); } } public _ng_getFrameStart(): number { return this._state.start; } public getObservable(): { onScrolled: Observable<IRange>, onOffset: Observable<number>, } { return { onScrolled: this._subjects.onScrolled.asObservable(), onOffset: this._subjects.onOffset.asObservable(), }; } public getFrame(): IRange { return { start: this._state.start, end: this._state.end }; } public getSelection(): IScrollBoxSelection | undefined { if (this._selection.focus.index === -1) { return undefined; } let selection: string = this._selection.selection; if (this.API.cleanUpClipboard !== undefined) { selection = this.API.cleanUpClipboard(selection); } return { selection: selection, original: this._selection.selection, anchor: this._selection.anchor.index, anchorOffset: this._selection.anchor.offset, focus: this._selection.focus.index, focusOffset: this._selection.focus.offset, }; } public copySelection() { this._selection_copy(); } public scrollToBegin() { if (this._state.start === 0) { return; } this._onScrollTo(false, 0, true); } public scrollToEnd() { if (this._state.start === this._storageInfo.count - 1) { return; } this._onScrollTo(false, this._storageInfo.count - 1, true); } private _setFrame(start: number, outside: boolean) { this._state.start = start; if (this._state.start < 0) { this._state.start = 0; } this._state.end = this._state.start + this._state.count; if (this._state.end > this._storageInfo.count - 1) { this._state.end = this._storageInfo.count - 1; this._state.start = (this._storageInfo.count - this._state.count) > 0 ? (this._storageInfo.count - this._state.count) : 0; } if (!outside) { this._subjects.onScrolled.next({ start: this._state.start, end: this._state.end }); } } private _getInitalRange() { // Try to get last frame const frame: IRange = this.API.getLastFrame(); if (frame.end - frame.start > this._state.count) { frame.end = frame.start + this._state.count; } if (frame.end > this._storageInfo.count - 1) { frame.end = this._storageInfo.count - 1; frame.start = frame.end - this._state.count > 0 ? frame.end - this._state.count : 0; } // Get rows const rows = this.API.getRange({ start: frame.start, end: frame.end }).rows; this._ng_rows = rows; this._state.start = frame.start; this._state.end = frame.end; } private _onKeyboardAction(key: EKeys) { switch (key) { case EKeys.ArrowLeft: this._ng_sbh_left(); break; case EKeys.ArrowRight: this._ng_sbh_right(); break; case EKeys.ArrowDown: if (this._state.start + 1 > this._storageInfo.count - 1) { return; } this._onScrollTo(false, this._state.start + 1, true); break; case EKeys.ArrowUp: if (this._state.start - 1 < 0) { return; } this._onScrollTo(false, this._state.start - 1, true); break; case EKeys.PageDown: if (this._state.start + this._state.count > this._storageInfo.count - 1) { this._onScrollTo(false, this._storageInfo.count - 1, true); return; } this._onScrollTo(false, this._state.start + this._state.count, true); break; case EKeys.PageUp: if (this._state.start - this._state.count < 0) { this._onScrollTo(false, 0, true); return; } this._onScrollTo(false, this._state.start - this._state.count, true); break; case EKeys.End: if (this._state.start === this._storageInfo.count - 1) { return; } this._onScrollTo(false, this._storageInfo.count - 1, true); break; case EKeys.Home: if (this._state.start === 0) { return; } this._onScrollTo(false, 0, true); break; case EKeys.KeyC: case EKeys.KeyX: this._selection_copy(); this._selection_restore(); break; } } private _updateContainerSize(force: boolean = false) { if (this._ng_nodeContainer === undefined) { return; } if (!force && this._ng_containerSize !== undefined) { return; } this._ng_containerSize = (this._ng_nodeContainer.nativeElement as HTMLElement).getBoundingClientRect(); this._ng_containerSize.height -= this._settings.scrollBarSize; this._state.count = Math.floor(this._ng_containerSize.height / this._item.height); } private _updateHolderSize(ignoreHash: boolean = false) { if (this._ng_nodeHolder === undefined) { return; } const hash: string = `${this._state.start}-${this._state.end}`; if (this._ng_holderSize.hash === hash && !ignoreHash) { return; } this._ng_holderSize.hash = hash; this._ng_holderSize.width = (this._ng_nodeHolder.nativeElement as HTMLElement).getBoundingClientRect().width; } private _updateSbvPosition() { if (this._ng_sbvCom === undefined || this._ng_sbvCom === null) { return; } this._ng_sbvCom.setFrame(this._state.start, this._state.end, this._storageInfo.count); } private _onRowsDelivered(packet: IRowsPacket) { // Check: is packet still actual if (packet.range.start !== this._state.start || packet.range.end !== this._state.end) { this._render(); return; } // Replace rows this._ng_rows = packet.rows; // Force update this._forceUpdate(); // Update holder size this._updateHolderSize(true); } private _onRerequest() { this._render(); // Update holder size this._updateHolderSize(true); } private _onSourceUpdated() { const storage: IStorageInformation = this.API.getStorageInfo(); // Update storage info this._storageInfo.count = storage.count; // Read initial state this._getInitalRange(); // Update data about sizes this._updateContainerSize(true); this._updateHolderSize(true); // Update vertical scroll bar this._updateSbvPosition(); // Update this._forceUpdate(); } private _onScrollTo(outside: boolean, row: number, noOffset: boolean = false) { // Correct row value row = row > this._storageInfo.count - 1 ? (this._storageInfo.count - 1) : row; row = row < 0 ? 0 : row; // Detect start of frame const start: number = noOffset ? row : (row - this._settings.scrollToOffset > 0 ? (row - this._settings.scrollToOffset) : 0); // Set frame this._setFrame(start, outside); // Trigger scrolling this._ng_sbv_update(0, 0, outside); } private _onScrollUntil(row: number) { // Correct row value row = row > this._storageInfo.count - 1 ? (this._storageInfo.count - 1) : row; row = row < 0 ? 0 : row; // Detect start of frame const start: number = row - this._state.count < 0 ? 0 : (row - this._state.count); // Set frame this._setFrame(start, true); // Trigger scrolling this._ng_sbv_update(0, 0, true); } private _reset() { this._state.start = 0; this._state.end = 0; this._ng_rows = []; } private _onStorageUpdated(info: IStorageInformation) { if (info.count < 0 || isNaN(info.count) || !isFinite(info.count)) { return console.error(new Error(`Fail to proceed event "onStorageUpdated" with count = ${info.count}. Please check trigger of this event.`)); } let shouldBeUpdated: boolean; if (info.count === 0) { this._reset(); shouldBeUpdated = true; } else if (this._state.start + this._state.count > info.count - 1) { this._state.end = info.count - 1; shouldBeUpdated = true; } else if (this._storageInfo.count < this._state.count && info.count > this._state.count) { this._state.end = this._state.start + this._state.count; shouldBeUpdated = true; } // Update storage data this._storageInfo.count = info.count; // Scroll bar this._updateSbvPosition(); if (shouldBeUpdated) { // Render this._render(); if (info.count === 0) { // No need to do other actions, because no data return; } // Notification: scroll is done this.API.updatingDone({ start: this._state.start, end: this._state.end }); } } private _isStateValid(): boolean { if (this._state.start < 0 || this._state.end < 0) { return false; } if (this._state.start > this._state.end) { return false; } if (isNaN(this._state.start) || isNaN(this._state.end)) { return false; } if (!isFinite(this._state.start) || !isFinite(this._state.end)) { return false; } return true; } private _softRender() { clearTimeout(this._renderState.timer); if (this._renderState.requests > 10) { this._renderState.requests = 0; this._render(); } else { this._renderState.requests += 1; this._renderState.timer = setTimeout(this._render.bind(this), 0); } } private _render() { if (!this._isStateValid() || ((this._state.end - this._state.start) === 0 && (this._state.end !== 0 || this._state.start !== 0))) { // This case can be in case of asynch calls usage this._ng_rows = []; return this._forceUpdate(); } let requested: number = this._state.end - this._state.start + 1; // Correct frame if it's needed if (requested < this._state.count && this._storageInfo.count > this._state.count) { this._state.start = this._state.end - (this._state.count - 1); requested = this._state.end - this._state.start + 1; } const frame = this.API.getRange({ start: this._state.start, end: this._state.end}); const rows: Array<IRow | number> = frame.rows; const pending = requested - rows.length; if (pending > 0) { // Not all rows were gotten if (frame.range.start === this._state.start) { // Not load from the end rows.push(...Array.from({ length: pending }).map((_, i) => { return i + this._state.start; })); } else { // Not load from beggining rows.unshift(...Array.from({ length: pending }).map((_, i) => { return i + this._state.start; })); } } this._ng_rows = rows; this._updateSbvPosition(); this._forceUpdate(); // Notification: scroll is done this.API.updatingDone({ start: this._state.start, end: this._state.end }); // Update holder size // this._updateHolderSize(); // Restore selection this._selection_restore(); } private _onRedraw() { this._ng_onBrowserWindowResize(); } private _selection_UpdateFocus(selection: Selection | undefined) { const direction = this._selection_getCloseBorder(); if (selection === undefined) { this._selection.focus.offset = 0; if (direction === EDirection.Down) { // Direction: down this._selection.focus.path = `li[${CRowIndexAttr}="${this._state.end}"]`; this._selection.focus.index = this._state.end; this._selection.focus.node = this._selection_restore(); } else if (direction === EDirection.Up) { // Direction: up this._selection.focus.path = `li[${CRowIndexAttr}="${this._state.start}"]`; this._selection.focus.index = this._state.start; this._selection.focus.node = this._selection_restore(); } return; } if (this._selection.focus.node !== selection.focusNode) { const focusRowInfo: IRowNodeInfo | undefined = this._selection_getRowInfo(selection.focusNode as HTMLElement); if (focusRowInfo !== undefined) { this._selection.focus.path = focusRowInfo.path; this._selection.focus.index = focusRowInfo.index; this._selection.focus.node = selection.focusNode; this._selection.focus.offset = selection.focusOffset; } else { this._selection.focus.offset = 0; if (direction === EDirection.Down) { // Direction: down this._selection.focus.path = `li[${CRowIndexAttr}="${this._state.end}"]`; this._selection.focus.index = this._state.end; this._selection.focus.node = this._selection_restore(); } else if (direction === EDirection.Up) { // Direction: up this._selection.focus.path = `li[${CRowIndexAttr}="${this._state.start}"]`; this._selection.focus.index = this._state.start; this._selection.focus.node = this._selection_restore(); } } } else { this._selection.focus.offset = selection.focusOffset; } } private _selection_UpdateAnchor(selection: Selection) { if (this._selection.anchor.index !== -1) { return; } const anchorRowInfo: IRowNodeInfo | undefined = this._selection_getRowInfo(selection.anchorNode as HTMLElement); if (anchorRowInfo !== undefined) { this._selection.anchor.path = anchorRowInfo.path; this._selection.anchor.index = anchorRowInfo.index; this._selection.anchor.node = selection.anchorNode; this._selection.anchor.offset = selection.anchorOffset; } } private _selection_save(selection: Selection) { if (!this._selection.restored) { return; } if (!this._selection.going) { return; } if (this._selection_isInView()) { this._selection.selection = selection.toString(); return; } if (this._selection.selection === undefined) { return; } const current: string = selection.toString().replace(/[\n\r]$/, ''); if (this._selection.focus.index > this._selection.anchor.index) { // Direction: down const hiddenCount: number = this._state.start - this._selection.anchor.index; const hiddenContent: string = this._selection.selection.split(/[\n\r]/).slice(0, hiddenCount).join('\n'); this._selection.selection = `${hiddenContent}\n${current}`; } else if (this._selection.focus.index < this._selection.anchor.index) { // Direction: up const hiddenCount: number = this._selection.anchor.index - this._state.end + 1; const storedRows: string[] = this._selection.selection.split(/[\n\r]/); const hiddenContent: string = storedRows.slice(storedRows.length - hiddenCount, storedRows.length).join('\n'); this._selection.selection = `${current}\n${hiddenContent}`; } } private _selection_getRowInfo(node: HTMLElement, path: string = ''): IRowNodeInfo | undefined { if (node === undefined || node === null) { return undefined; } if (node.parentNode === undefined || node.parentNode === null) { return undefined; } if (node.nodeName.toLowerCase() === 'body') { return undefined; } let rowIndex: string | undefined = node.getAttribute === undefined ? undefined : node.getAttribute(CRowIndexAttr); rowIndex = rowIndex === null ? undefined : (rowIndex === '' ? undefined : rowIndex); if (rowIndex !== undefined) { path = `${node.nodeName.toLowerCase()}[${CRowIndexAttr}="${rowIndex}"]${path !== '' ? ' ' : ''}${path}`; } else if (node.nodeType === Node.TEXT_NODE) { let textNodeIndex: number = -1; Array.prototype.forEach.call(node.parentNode.childNodes, (child: Node, index: number) => { if (textNodeIndex === -1 && node === child) { textNodeIndex = index; } }); if (textNodeIndex === -1) { return undefined; } return this._selection_getRowInfo(node.parentNode as HTMLElement, `#text:${textNodeIndex}`); } else if (node.parentNode.children.length !== 0 && rowIndex === undefined) { let index: number = -1; Array.prototype.forEach.call(node.parentNode.children, (children: Node, i: number) => { if (children === node) { index = i; } }); if (index === -1) { return undefined; } path = `${node.nodeName.toLowerCase()}:nth-child(${index + 1})${path !== '' ? ' ' : ''}${path}`; } else { path = `${node.nodeName.toLowerCase()}${path !== '' ? ' ' : ''}${path}`; } const attr: string | null | undefined = node.getAttribute === undefined ? undefined : node.getAttribute(CRowIndexAttr); if (attr === null || attr === undefined) { return this._selection_getRowInfo(node.parentNode as HTMLElement, path); } return { index: parseInt(attr, 10), path: path }; } private _selection_drop(soft: boolean = false) { this._selection.focus.path = ''; this._selection.focus.index = -1; this._selection.focus.offset = -1; this._selection.focus.node = undefined; this._selection.focus.fragment = ''; this._selection.anchor.path = ''; this._selection.anchor.index = -1; this._selection.anchor.offset = -1; this._selection.anchor.node = undefined; this._selection.anchor.fragment = ''; this._selection.going = false; this._selection.selection = undefined; this._selection.restored = true; if (!soft) { document.getSelection().removeAllRanges(); } } private _selection_getCloseBorder(): EDirection | undefined { if (this._selection.focus.index === -1 || this._state.end === -1 || this._state.start === -1) { return undefined; } const toEnd = this._state.end - this._selection.focus.index; const toBegin = this._selection.focus.index - this._state.start; if (toEnd < toBegin) { return EDirection.Down; } else if (toEnd > toBegin) { return EDirection.Up; } return undefined; } private _selection_scroll() { if (!this._selection.going) { return; } const direction = this._selection_getCloseBorder(); if (direction === EDirection.Down) { // Direction: down if (this._selection.focus.index >= this._storageInfo.count - 1) { this._selection.restored = true; return; } if (this._selection.focus.index >= this._state.end - 1) { // Have to do scroll down this._selection.restored = false; this._onScrollTo(false, this._state.start + 1, true); } } else if (direction === EDirection.Up) { // Direction: up if (this._selection.focus.index === 0) { this._selection.restored = true; return; } if (this._selection.focus.index <= this._state.start + 1) { // Scroll up this._selection.restored = false; this._onScrollTo(false, this._state.start - 1, true); } } } private _selection_getRowNode(path: string): Node | undefined { if (this._ng_nodeHolder === undefined || this._ng_nodeHolder === null) { return undefined; } let selector: string = path; let textNodeIndex: number = -1; if (selector.indexOf('#text') !== -1) { const parts: string[] = selector.split(`#text:`); if (parts.length !== 2) { return undefined; } textNodeIndex = parseInt(parts[1], 10); if (isNaN(textNodeIndex) || !isFinite(textNodeIndex)) { return undefined; } selector = selector.replace(/#text:\d*/gi, '').trim(); } let node: Node = this._ng_nodeHolder.nativeElement.querySelector(selector); if (node === undefined || node === null) { return undefined; } if (textNodeIndex !== -1 && node.childNodes.length === 0) { return undefined; } if (textNodeIndex !== -1 && node.childNodes.length !== 0) { node = node.childNodes[textNodeIndex] === undefined ? undefined : node.childNodes[textNodeIndex]; node = node === undefined ? undefined : (node.nodeType !== Node.TEXT_NODE ? undefined : node); } return node; } private _selection_isInView(): boolean { if (this._selection.focus.index < this._state.start || this._selection.anchor.index < this._state.start) { return false; } if (this._selection.focus.index > this._state.end || this._selection.anchor.index > this._state.end) { return false; } return true; } private _selection_copy() { if (this._selection.focus.index === -1) { return undefined; } let selection: string = this._selection.selection; if (this.API.cleanUpClipboard !== undefined) { selection = this.API.cleanUpClipboard(selection); } copyTextToClipboard(selection); this._selection_restore(); } private _selection_restore(): Node | undefined { const getMaxOffset = (node: Node): number => { if (node.nodeType === Node.TEXT_NODE) { return node.textContent.length - 1; } else if (node.childNodes !== undefined && node.childNodes !== null) { return node.childNodes.length - 1; } else { return 0; } }; if (this._selection.focus.index === -1) { this._selection.restored = true; return; } if (this._selection.focus.index < this._state.start && this._selection.anchor.index < this._state.start) { this._selection.restored = true; return; } if (this._selection.focus.index > this._state.end && this._selection.anchor.index > this._state.end) { this._selection.restored = true; return; } let anchorOffset: number = -1; let focusOffset: number = -1; let anchorPath: string = ''; let focusPath: string = ''; if (this._selection.focus.index === this._selection.anchor.index) { anchorOffset = this._selection.anchor.offset; focusOffset = this._selection.focus.offset; anchorPath = this._selection.anchor.path; focusPath = this._selection.focus.path; } else if (this._selection.focus.index > this._selection.anchor.index) { // Direction: down anchorOffset = this._selection.anchor.index < this._state.start ? 0 : this._selection.anchor.offset; focusOffset = this._selection.focus.index > this._state.end ? Infinity : this._selection.focus.offset; anchorPath = this._selection.anchor.index < this._state.start ? `li[${CRowIndexAttr}="${this._state.start}"]` : this._selection.anchor.path; focusPath = this._selection.focus.index > this._state.end ? `li[${CRowIndexAttr}="${this._state.end}"]` : this._selection.focus.path; } else if (this._selection.focus.index < this._selection.anchor.index) { // Direction: up anchorOffset = this._selection.anchor.index > this._state.end ? Infinity : this._selection.anchor.offset; focusOffset = this._selection.focus.index < this._state.start ? 0 : this._selection.focus.offset; anchorPath = this._selection.anchor.index > this._state.end ? `li[${CRowIndexAttr}="${this._state.end}"]` : this._selection.anchor.path; focusPath = this._selection.focus.index < this._state.start ? `li[${CRowIndexAttr}="${this._state.start}"]` : this._selection.focus.path; } const selection: Selection = document.getSelection(); selection.removeAllRanges(); const anchorNode = this._selection_getRowNode(anchorPath); const focusNode = this._selection_getRowNode(focusPath); if (anchorNode === undefined || focusNode === undefined) { return; } if (!isFinite(anchorOffset)) { anchorOffset = getMaxOffset(anchorNode); } if (!isFinite(focusOffset)) { focusOffset = getMaxOffset(focusNode); } try { selection.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset); } catch (e) { let details: string = 'Error with restoring selection:'; details += `\n\t-\tanchorPath: ${anchorPath}`; details += `\n\t-\tfocusNode: ${focusPath}`; if (typeof anchorNode.textContent === 'string') { details += `\n\t-\t${anchorNode.textContent.length <= anchorOffset ? '[WRONG]' : ''}anchor (${anchorNode.nodeName}): "${anchorNode.textContent}" (${anchorNode.textContent.length}): ${anchorOffset}`; } if (typeof focusNode.textContent === 'string') { details += `\n\t-\t${focusNode.textContent.length <= focusOffset ? '[WRONG]' : ''}focus (${focusNode.nodeName}): "${focusNode.textContent}" (${focusNode.textContent.length}): ${focusOffset}`; } details += `\n\t-\terror: ${e.message}`; console.log(anchorNode); console.log(focusNode); console.warn(details); } this._selection.restored = true; this._selection_save(selection); return focusNode; } private _forceUpdate() { if (this._destroyed) { return; } this._cdRef.detectChanges(); } }
the_stack
import { IonicNativePlugin } from '@ionic-native/core'; export declare class HMSScanOriginal extends IonicNativePlugin { Colors: typeof Colors; ScanTypes: typeof ScanTypes; RectStyle: typeof RectStyle; Permission: typeof HMSPermission; ErrorCorrectionLevel: typeof ErrorCorrectionLevel; /** * Checks whether necessary permissions are granted to use the services. * @param {Permission} permission Represents the list in which permission names are kept. * @returns Promise<any> */ hasPermission(permission: HMSPermission): Promise<any>; /** * Obtains a permission to use the services. * @param {Permission} permission Represents the list in which permission names are kept. * @returns Promise<any> */ requestPermission(permission: HMSPermission): Promise<any>; /** * Obtains a permissions to use the services. * @param {Permission[]} permissions Represents the list in which permission names are kept. * @returns Promise<any> */ requestPermissions(permissions: HMSPermission[]): Promise<any>; /** * Enables the HMSLogger capability which is used for sending usage analytics of Scan SDK's methods to improve the service quality. * @returns Promise<any> */ enableLogger(): Promise<any>; /** * Disables the HMSLogger capability which is used for sending usage analytics of Scan SDK's methods to improve the service quality. * @returns Promise<any> */ disableLogger(): Promise<any>; /** * In Default View mode, Scan Kit scans barcodes using the camera or from images in the album, and also provides activities that can be directly used. * @param {ScanTypes[]} scanTypes Sets the barcode scanning format.. * @returns Promise<any> */ defaultViewMode(scanTypes: ScanTypes[]): Promise<any>; /** * This service works asynchronously, defines the bitmap given as a parameter, and returns the Scan results. * @param {string} filePath The URI of the photo requested to be scanned by the service. * @param {ScanTypes[]} scanTypes Sets the barcode scanning format. * @returns Promise<any> */ analyzInAsyn(filePath: string, scanTypes: ScanTypes[]): Promise<any>; /** * This service works synchronously, defines the bitmap given as a parameter, and returns the Scan results. * @param {string} filePath The URI of the photo requested to be scanned by the service. * @param {ScanTypes[]} scanTypes Sets the barcode scanning format. * @returns Promise<any> */ analyseFrame(filePath: string, scanTypes: ScanTypes[]): Promise<any>; /** * The service recognition scanning barcodes from images in Bitmap mode. * @param {string} filePath The URI of the photo requested to be scanned by the service. * @param {ScanTypes[]} scanTypes Sets the barcode scanning format. * @returns Promise<any> */ decodeWithBitmap(filePath: string, scanTypes: ScanTypes[]): Promise<any>; /** * Scan Kit can convert character strings into 1D or 2D barcodes in 13 formats, including EAN-8, EAN-13, UPC-A, UPC-E, Codabar, Code 39, Code 93, Code 128, ITF, QR code, Data Matrix, PDF417, and Aztec. Besides a character string, you still need to specify the format and size for generating a barcode. * @param {BuildBitmapRequest} buildBitmapRequest Contains the settings of the barcode generation service. * @returns Promise<any> */ buildBitmap(buildBitmapRequest: BuildBitmapRequest): Promise<any>; /** * Obtains the bitmap from the corresponding file path, performs sampling rate compression, and returns the bitmap that meets the size requirements. * @param {string} filePath The URI of the photo requested to be scanned by the service. * @param {ScanTypes[]} scanTypes Sets the barcode scanning format. * @returns Promise<any> */ detectForHmsDector(filePath: string, scanTypes: ScanTypes[]): Promise<any>; } export declare class MultiProcessorOriginal extends IonicNativePlugin { Colors: typeof Colors; ScanTypes: typeof ScanTypes; RectStyle: typeof RectStyle; Permission: typeof HMSPermission; ErrorCorrectionLevel: typeof ErrorCorrectionLevel; /** * The service process of using the MultiProcessor mode in synchronous mode. * @param {string} divId ScanArea * @param {MultiProcessorSynModeRequest} multiProcessorSynModeRequest Contains the settings of the multiProcessorSynMode service. * @returns Promise<any> */ multiProcessorSynMode(divId: string, multiProcessorSynModeRequest: MultiProcessorModeRequest): Promise<any>; /** * The service process of using the MultiProcessor mode in asynchronous mode * @param {string} divId ScanArea * @param {MultiProcessorSynModeRequest} multiProcessorSynModeRequest Contains the settings of the multiProcessorSynMode service. * @returns Promise<any> */ multiProcessorAsynMode(divId: string, multiProcessorAsynModeRequest: MultiProcessorModeRequest): Promise<any>; /** * It recognizes barcodes using the camera in Bitmap mode. * @param {string} divId ScanArea * @param {BitmapModeRequest} bitmapModeRequest Contains the settings of the BitmapMode service. * @returns Promise<any> */ bitmapMode(divId: string, bitmapModeRequest: BitmapModeRequest): Promise<any>; /** * The service process of using the MultiProcessor and bitmap mode * @param {string} eventName Event name. * @param {(value: any) => void} call Method. * @returns void */ on(eventName: string, call: (value: any) => void): void; /** * It stops the custom view mode service. * @returns Promise<any> */ stopViewService(): Promise<any>; } export declare class CustomViewOriginal extends IonicNativePlugin { Colors: typeof Colors; ScanTypes: typeof ScanTypes; RectStyle: typeof RectStyle; Permission: typeof HMSPermission; ErrorCorrectionLevel: typeof ErrorCorrectionLevel; /** * In Customized View mode, you do not need to worry about developing the scanning process or camera control. * @param {string} divId ScanArea * @param {CustomViewModeRequest} customViewModeRequest Contains the settings of the customViewMode service. * @returns Promise<any> */ customViewMode(divId: string, customViewModeRequest: CustomViewModeRequest): Promise<any>; /** * It opens flush light. * @returns Promise<any> */ openFlushLight(): Promise<any>; /** * It pause the continuously scan. * @returns Promise<any> */ pauseContinuouslyScan(): Promise<any>; /** * The service process of using the MultiProcessor and bitmap mode * @param {string} eventName Event name. * @param {(value: any) => void} call Method. * @returns void */ on(eventName: string, call: (value: any) => void): void; /** * It resume the continuously scan. * @returns Promise<any> */ resumeContinuouslyScan(): Promise<any>; /** * It stops the custom view mode service. * @returns Promise<any> */ stopViewService(): Promise<any>; } export interface CustomViewModeRequest { scanTypes: ScanTypes[] | ScanTypes; isContinuouslyScan?: boolean; enableReturnBitmap?: boolean; enableScanAreaBox?: boolean; scanFrameSize?: number; } export interface MultiProcessorModeRequest { scanTypes: ScanTypes[] | ScanTypes; scanFrameSize?: number; enableScanAreaBox?: boolean; enableDrawScanResult?: boolean; viewAttributes?: ViewAttributes; } export interface ViewAttributes { textColor?: Colors; textSize?: number; strokeWitdh?: number; rectColor?: Colors; rectStyle?: RectStyle; } export interface BuildBitmapRequest { inputContent: string; barcodeFormat: ScanTypes; barcodeWidth?: number; barcodeHeight?: number; hmsBuildBitmapOptions?: HMSBuildBitmapOptions; } export interface HMSBuildBitmapOptions { bitmapMargin?: number; bitmapColor?: Colors; bitmapBackgroundColor?: Colors; qrErrorCorrectionLevel?: ErrorCorrectionLevel; qrLogoBitmap?: string; } export interface BitmapModeRequest { scanTypes: ScanTypes[]; scanFrameSize?: number; enableScanAreaBox?: boolean; } export interface ScanBounds { marginTop?: number; marginBottom?: number; } export declare enum HMSPermission { CAMERA = "android.permission.CAMERA", READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE" } export declare enum ErrorCorrectionLevel { L = "L", M = "M", Q = "Q", H = "H" } export declare enum Colors { RED = -65536, DKGRAY = -12303292, GRAY = -7829368, WHITE = -1, BLUE = -16776961, BLACK = -16777216, LTGRAY = -3355444, MAGENTA = -65281, YELLOW = -256, CYAN = -16711681, GREEN = -16711936, TRANSPARENT = 0 } export declare enum ScanTypes { OTHER_SCAN_TYPE = -1, ALL_SCAN_TYPE = 0, CODE128_SCAN_TYPE = 64, CODE39_SCAN_TYPE = 16, CODE93_SCAN_TYPE = 32, CODABAR_SCAN_TYPE = 4096, DATAMATRIX_SCAN_TYPE = 4, EAN13_SCAN_TYPE = 128, EAN8_SCAN_TYPE = 256, ITF14_SCAN_TYPE = 512, QRCODE_SCAN_TYPE = 1, UPCCODE_A_SCAN_TYPE = 1024, UPCCODE_E_SCAN_TYPE = 2048, PDF417_SCAN_TYPE = 8, AZTEC_SCAN_TYPE = 2 } export declare enum RectStyle { STROKE = 0, FILL = 1, FILL_AND_STROKE = 2 } export interface LayoutBounds { marginLeft?: number; marginRight?: number; marginTop?: number; marginBottom?: number; } export interface Props { x: number; y: number; width: number; height: number; marginLeft?: number; marginRight?: number; marginTop?: number; marginBottom?: number; pageXOffset?: number; pageYOffset?: number; } export declare const HMSScan: HMSScanOriginal; export declare const MultiProcessor: MultiProcessorOriginal; export declare const CustomView: CustomViewOriginal;
the_stack
import { EventEmitter } from '@angular/core'; import { configureTestSuite } from '../test-utils/configure-suite'; import { IgxTree, IgxTreeNode, IgxTreeSelectionType, ITreeNodeSelectionEvent } from './common'; import { TreeTestFunctions } from './tree-functions.spec'; import { IgxTreeNodeComponent } from './tree-node/tree-node.component'; import { IgxTreeSelectionService } from './tree-selection.service'; describe('IgxTreeSelectionService - Unit Tests #treeView', () => { configureTestSuite(); let selectionService: IgxTreeSelectionService; let mockEmitter: EventEmitter<ITreeNodeSelectionEvent>; let mockTree: IgxTree; let mockNodesLevel1: IgxTreeNodeComponent<any>[]; let mockNodesLevel2_1: IgxTreeNodeComponent<any>[]; let mockNodesLevel2_2: IgxTreeNodeComponent<any>[]; let mockNodesLevel3_1: IgxTreeNodeComponent<any>[]; let mockNodesLevel3_2: IgxTreeNodeComponent<any>[]; let allNodes: IgxTreeNodeComponent<any>[]; const mockQuery1: any = {}; const mockQuery2: any = {}; const mockQuery3: any = {}; const mockQuery4: any = {}; const mockQuery5: any = {}; const mockQuery6: any = {}; beforeEach(() => { selectionService = new IgxTreeSelectionService(); mockNodesLevel1 = TreeTestFunctions.createNodeSpies(0, 3, null, [mockQuery2, mockQuery3], [mockQuery6, mockQuery3]); mockNodesLevel2_1 = TreeTestFunctions.createNodeSpies(1, 2, mockNodesLevel1[0], [mockQuery4, mockQuery5], [mockQuery4, mockQuery5]); mockNodesLevel2_2 = TreeTestFunctions.createNodeSpies(1, 1, mockNodesLevel1[1], null); mockNodesLevel3_1 = TreeTestFunctions.createNodeSpies(2, 2, mockNodesLevel2_1[0], null); mockNodesLevel3_2 = TreeTestFunctions.createNodeSpies(2, 2, mockNodesLevel2_1[1], null); allNodes = [ mockNodesLevel1[0], mockNodesLevel2_1[0], ...mockNodesLevel3_1, mockNodesLevel2_1[1], ...mockNodesLevel3_2, mockNodesLevel1[1], ...mockNodesLevel2_2, mockNodesLevel1[2] ]; Object.assign(mockQuery1, TreeTestFunctions.createQueryListSpy(allNodes)); Object.assign(mockQuery2, TreeTestFunctions.createQueryListSpy(mockNodesLevel2_1)); Object.assign(mockQuery3, TreeTestFunctions.createQueryListSpy(mockNodesLevel2_2)); Object.assign(mockQuery4, TreeTestFunctions.createQueryListSpy(mockNodesLevel3_1)); Object.assign(mockQuery5, TreeTestFunctions.createQueryListSpy(mockNodesLevel3_2)); Object.assign(mockQuery6, TreeTestFunctions.createQueryListSpy([ mockNodesLevel2_1[0], ...mockNodesLevel3_1, mockNodesLevel2_1[1], ...mockNodesLevel3_2 ])); }); describe('IgxTreeSelectionService - BiState & None', () => { beforeEach(() => { mockEmitter = jasmine.createSpyObj('emitter', ['emit']); mockTree = jasmine.createSpyObj('tree', [''], { selection: IgxTreeSelectionType.BiState, nodeSelection: mockEmitter, nodes: mockQuery1 }); selectionService.register(mockTree); }); it('Should properly register the specified tree', () => { selectionService = new IgxTreeSelectionService(); expect((selectionService as any).tree).toBeFalsy(); selectionService.register(mockTree); expect((selectionService as any).tree).toEqual(mockTree); }); it('Should return proper value when isNodeSelected is called', () => { const selectionSet: Set<IgxTreeNode<any>> = (selectionService as any).nodeSelection; expect(selectionSet.size).toBe(0); spyOn(selectionSet, 'clear').and.callThrough(); const mockNode1 = TreeTestFunctions.createNodeSpy(); const mockNode2 = TreeTestFunctions.createNodeSpy(); expect(selectionService.isNodeSelected(mockNode1)).toBeFalsy(); expect(selectionService.isNodeSelected(mockNode2)).toBeFalsy(); selectionSet.add(mockNode1); expect(selectionService.isNodeSelected(mockNode1)).toBeTruthy(); expect(selectionService.isNodeSelected(mockNode2)).toBeFalsy(); expect(selectionSet.size).toBe(1); selectionService.clearNodesSelection(); expect(selectionService.isNodeSelected(mockNode1)).toBeFalsy(); expect(selectionService.isNodeSelected(mockNode2)).toBeFalsy(); expect(selectionSet.clear).toHaveBeenCalled(); expect(selectionSet.size).toBe(0); }); it('Should handle selection based on tree.selection', () => { const mockSelectedChangeEmitter: EventEmitter<boolean> = jasmine.createSpyObj('emitter', ['emit']); const mockNode = TreeTestFunctions.createNodeSpy({ selectedChange: mockSelectedChangeEmitter }); // None (Object.getOwnPropertyDescriptor(mockTree, 'selection').get as jasmine.Spy<any>).and.returnValue(IgxTreeSelectionType.None); selectionService.selectNode(mockNode); expect(selectionService.isNodeSelected(mockNode)).toBeFalsy(); expect(mockTree.nodeSelection.emit).not.toHaveBeenCalled(); expect(mockNode.selectedChange.emit).not.toHaveBeenCalled(); // BiState (Object.getOwnPropertyDescriptor(mockTree, 'selection').get as jasmine.Spy<any>) .and.returnValue(IgxTreeSelectionType.BiState); let expected: ITreeNodeSelectionEvent = { oldSelection: [], newSelection: [mockNode], added: [mockNode], removed: [], event: undefined, cancel: false, owner: mockTree }; selectionService.selectNode(mockNode); expect(selectionService.isNodeSelected(mockNode)).toBeTruthy(); expect(mockTree.nodeSelection.emit).toHaveBeenCalledTimes(1); expect(mockTree.nodeSelection.emit).toHaveBeenCalledWith(expected); expect(mockNode.selectedChange.emit).toHaveBeenCalledTimes(1); expect(mockNode.selectedChange.emit).toHaveBeenCalledWith(true); // Cascading selectionService.deselectNode(mockNode); (Object.getOwnPropertyDescriptor(mockTree, 'selection').get as jasmine.Spy<any>) .and.returnValue(IgxTreeSelectionType.Cascading); selectionService.selectNode(allNodes[1]); expected = { oldSelection: [], newSelection: [allNodes[1], allNodes[2], allNodes[3]], added: [allNodes[1], allNodes[2], allNodes[3]], removed: [], event: undefined, cancel: false, owner: mockTree }; expect(selectionService.isNodeSelected(allNodes[1])).toBeTruthy(); expect(selectionService.isNodeSelected(allNodes[2])).toBeTruthy(); expect(selectionService.isNodeSelected(allNodes[3])).toBeTruthy(); expect(selectionService.isNodeIndeterminate(allNodes[0])).toBeTruthy(); expect(mockTree.nodeSelection.emit).toHaveBeenCalledTimes(3); expect(mockTree.nodeSelection.emit).toHaveBeenCalledWith(expected); for (let i = 1; i < 4; i++) { expect(allNodes[i].selectedChange.emit).toHaveBeenCalled(); expect(allNodes[i].selectedChange.emit).toHaveBeenCalledWith(true); } }); it('Should deselect nodes', () => { const mockSelectedChangeEmitter: EventEmitter<boolean> = jasmine.createSpyObj('emitter', ['emit']); const mockNode1 = TreeTestFunctions.createNodeSpy({ selectedChange: mockSelectedChangeEmitter }); const mockNode2 = TreeTestFunctions.createNodeSpy({ selectedChange: mockSelectedChangeEmitter }); selectionService.deselectNode(mockNode1); expect(selectionService.isNodeSelected(mockNode1)).toBeFalsy(); expect(selectionService.isNodeSelected(mockNode2)).toBeFalsy(); expect(mockTree.nodeSelection.emit).not.toHaveBeenCalled(); expect(mockNode1.selectedChange.emit).not.toHaveBeenCalled(); // mark a node as selected selectionService.selectNode(mockNode1); expect(selectionService.isNodeSelected(mockNode1)).toBeTruthy(); expect(selectionService.isNodeSelected(mockNode2)).toBeFalsy(); expect(mockTree.nodeSelection.emit).toHaveBeenCalledTimes(1); expect(mockNode1.selectedChange.emit).toHaveBeenCalledTimes(1); expect(mockNode1.selectedChange.emit).toHaveBeenCalledWith(true); // deselect node const expected: ITreeNodeSelectionEvent = { newSelection: [], oldSelection: [mockNode1], removed: [mockNode1], added: [], event: undefined, cancel: false, owner: mockTree }; selectionService.deselectNode(mockNode1); expect(selectionService.isNodeSelected(mockNode1)).toBeFalsy(); expect(selectionService.isNodeSelected(mockNode2)).toBeFalsy(); expect(mockTree.nodeSelection.emit).toHaveBeenCalledTimes(2); expect(mockTree.nodeSelection.emit).toHaveBeenCalledWith(expected); expect(mockNode1.selectedChange.emit).toHaveBeenCalledTimes(2); expect(mockNode1.selectedChange.emit).toHaveBeenCalledWith(false); }); it('Should be able to deselect all nodes', () => { selectionService.selectNodesWithNoEvent(allNodes.slice(0, 3)); for (const node of allNodes.slice(0, 3)) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } expect(mockTree.nodeSelection.emit).not.toHaveBeenCalled(); selectionService.deselectNodesWithNoEvent(); for (const node of allNodes.slice(0, 3)) { expect(selectionService.isNodeSelected(node)).toBeFalsy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(false); } expect(mockTree.nodeSelection.emit).not.toHaveBeenCalled(); }); it('Should be able to deselect range of nodes', () => { selectionService.selectNodesWithNoEvent(allNodes.slice(0, 3)); for (const node of allNodes.slice(0, 3)) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } expect(mockTree.nodeSelection.emit).not.toHaveBeenCalled(); selectionService.deselectNodesWithNoEvent([allNodes[0], allNodes[2]]); expect(selectionService.isNodeSelected(allNodes[0])).toBeFalsy(); expect(selectionService.isNodeSelected(allNodes[2])).toBeFalsy(); expect(allNodes[0].selectedChange.emit).toHaveBeenCalled(); expect(allNodes[0].selectedChange.emit).toHaveBeenCalledWith(false); expect(allNodes[2].selectedChange.emit).toHaveBeenCalled(); expect(allNodes[2].selectedChange.emit).toHaveBeenCalledWith(false); expect(mockTree.nodeSelection.emit).not.toHaveBeenCalled(); }); it('Should be able to select multiple nodes', () => { selectionService.selectNodesWithNoEvent(allNodes.slice(0, 3)); for (const node of allNodes.slice(0, 3)) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } expect(selectionService.isNodeSelected(allNodes[3])).toBeFalsy(); selectionService.selectNodesWithNoEvent([allNodes[3]]); for (const node of allNodes.slice(0, 4)) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); } expect(allNodes[3].selectedChange.emit).toHaveBeenCalled(); expect(allNodes[3].selectedChange.emit).toHaveBeenCalledWith(true); expect(mockTree.nodeSelection.emit).not.toHaveBeenCalled(); }); it('Should be able to clear selection when adding multiple nodes', () => { selectionService.selectNodesWithNoEvent(allNodes.slice(0, 3)); for (const node of allNodes.slice(0, 3)) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } expect(selectionService.isNodeSelected(allNodes[3])).toBeFalsy(); selectionService.selectNodesWithNoEvent(allNodes.slice(1, 4), true); for (const node of allNodes.slice(1, 4)) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } expect(selectionService.isNodeSelected(allNodes[0])).toBeFalsy(); expect(mockTree.nodeSelection.emit).not.toHaveBeenCalled(); }); it('Should add newly selected nodes to the existing selection', () => { selectionService.selectNode(mockTree.nodes.first); let expected: ITreeNodeSelectionEvent = { oldSelection: [], newSelection: [mockQuery1.first], added: [mockQuery1.first], removed: [], event: undefined, cancel: false, owner: mockTree }; expect(selectionService.isNodeSelected(allNodes[0])).toBeTruthy(); expect(mockTree.nodes.first.selectedChange.emit).toHaveBeenCalled(); expect(mockTree.nodes.first.selectedChange.emit).toHaveBeenCalledWith(true); for (let i = 1; i < allNodes.length; i++) { expect(selectionService.isNodeSelected(allNodes[i])).toBeFalsy(); } expect(mockTree.nodeSelection.emit).toHaveBeenCalledWith(expected); expect(mockTree.nodeSelection.emit).toHaveBeenCalledTimes(1); expected = { oldSelection: [allNodes[0]], newSelection: [allNodes[0], allNodes[1]], added: [allNodes[1]], removed: [], event: undefined, cancel: false, owner: mockTree }; selectionService.selectNode(mockTree.nodes.toArray()[1]); expect(mockTree.nodes.toArray()[1].selectedChange.emit).toHaveBeenCalled(); expect(mockTree.nodes.toArray()[1].selectedChange.emit).toHaveBeenCalledWith(true); expect(mockTree.nodeSelection.emit).toHaveBeenCalledWith(expected); expect(mockTree.nodeSelection.emit).toHaveBeenCalledTimes(2); expect(selectionService.isNodeSelected(allNodes[0])).toBeTruthy(); expect(selectionService.isNodeSelected(allNodes[1])).toBeTruthy(); }); it('Should be able to select a range of nodes', () => { selectionService.selectNode(allNodes[3]); // only third node is selected expect(selectionService.isNodeSelected(allNodes[3])).toBeTruthy(); expect(allNodes[3].selectedChange.emit).toHaveBeenCalled(); expect(allNodes[3].selectedChange.emit).toHaveBeenCalledWith(true); for (let i = 0; i < allNodes.length; i++) { if (i !== 3) { expect(selectionService.isNodeSelected(allNodes[i])).toBeFalsy(); } } // select all nodes from third to eighth selectionService.selectMultipleNodes(allNodes[8]); allNodes.forEach((node, index) => { if (index >= 3 && index <= 8) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } else { expect(selectionService.isNodeSelected(node)).toBeFalsy(); } }); const expected: ITreeNodeSelectionEvent = { oldSelection: [allNodes[3]], newSelection: allNodes.slice(3, 9), added: allNodes.slice(4, 9), removed: [], event: undefined, cancel: false, owner: mockTree }; expect(mockTree.nodeSelection.emit).toHaveBeenCalledWith(expected); }); it('Should be able to select a range of nodes in reverse order', () => { selectionService.selectNode(allNodes[8]); // only eighth node is selected expect(selectionService.isNodeSelected(allNodes[8])).toBeTruthy(); expect(allNodes[8].selectedChange.emit).toHaveBeenCalled(); expect(allNodes[8].selectedChange.emit).toHaveBeenCalledWith(true); for (let i = 0; i < allNodes.length; i++) { if (i !== 8) { expect(selectionService.isNodeSelected(allNodes[i])).toBeFalsy(); } } // select all nodes from eighth to second selectionService.selectMultipleNodes(allNodes[2]); allNodes.forEach((node, index) => { if (index >= 2 && index <= 8) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } else { expect(selectionService.isNodeSelected(node)).toBeFalsy(); } }); const expected: ITreeNodeSelectionEvent = { oldSelection: [allNodes[8]], newSelection: [allNodes[8], ...allNodes.slice(2, 8)], added: allNodes.slice(2, 8), removed: [], event: undefined, cancel: false, owner: mockTree }; expect(mockTree.nodeSelection.emit).toHaveBeenCalledWith(expected); }); }); describe('IgxTreeSelectionService - Cascading', () => { beforeEach(() => { mockEmitter = jasmine.createSpyObj('emitter', ['emit']); mockTree = jasmine.createSpyObj('tree', [''], { selection: IgxTreeSelectionType.Cascading, nodeSelection: mockEmitter, nodes: mockQuery1 }); selectionService.register(mockTree); }); it('Should deselect nodes', () => { selectionService.deselectNode(allNodes[1]); for (const node of allNodes.slice(1, 4)) { expect(selectionService.isNodeSelected(node)).toBeFalsy(); expect(node.selectedChange.emit).not.toHaveBeenCalled(); } expect(mockTree.nodeSelection.emit).not.toHaveBeenCalled(); // mark a node as selected selectionService.selectNode(allNodes[1]); for (const node of allNodes.slice(1, 4)) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } expect(selectionService.isNodeIndeterminate(allNodes[0])).toBeTruthy(); expect(allNodes[0].selectedChange.emit).not.toHaveBeenCalled(); expect(mockTree.nodeSelection.emit).toHaveBeenCalledTimes(1); const expected: ITreeNodeSelectionEvent = { newSelection: [], oldSelection: [allNodes[1], allNodes[2], allNodes[3]], removed: [allNodes[1], allNodes[2], allNodes[3]], added: [], event: undefined, cancel: false, owner: mockTree }; // deselect node selectionService.deselectNode(allNodes[1]); for (const node of allNodes.slice(1, 4)) { expect(selectionService.isNodeSelected(node)).toBeFalsy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(false); } expect(selectionService.isNodeIndeterminate(allNodes[0])).toBeFalse(); expect(mockTree.nodeSelection.emit).toHaveBeenCalledTimes(2); expect(mockTree.nodeSelection.emit).toHaveBeenCalledWith(expected); }); it('Should be able to deselect range of nodes', () => { selectionService.selectNodesWithNoEvent([allNodes[1], allNodes[4]]); for (const node of allNodes.slice(0, 7)) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } expect(mockTree.nodeSelection.emit).not.toHaveBeenCalled(); selectionService.deselectNodesWithNoEvent([allNodes[1], allNodes[5]]); for (const node of allNodes.slice(1, 4)) { expect(selectionService.isNodeSelected(node)).toBeFalsy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(false); } expect(selectionService.isNodeSelected(allNodes[5])).toBeFalsy(); expect(selectionService.isNodeSelected(allNodes[6])).toBeTruthy(); expect(selectionService.isNodeIndeterminate(allNodes[0])).toBeTruthy(); expect(selectionService.isNodeIndeterminate(allNodes[4])).toBeTruthy(); expect(mockTree.nodeSelection.emit).not.toHaveBeenCalled(); }); it('Should be able to select multiple nodes', () => { selectionService.selectNodesWithNoEvent([allNodes[1], allNodes[8]]); for (const node of allNodes.slice(1, 4)) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } expect(selectionService.isNodeSelected(allNodes[7])).toBeTruthy(); expect(selectionService.isNodeSelected(allNodes[8])).toBeTruthy(); expect(selectionService.isNodeIndeterminate(allNodes[0])).toBeTruthy(); expect(mockTree.nodeSelection.emit).not.toHaveBeenCalled(); }); it('Should be able to clear selection when adding multiple nodes', () => { selectionService.selectNodesWithNoEvent([allNodes[1]], true); for (const node of allNodes.slice(1, 4)) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } expect(selectionService.isNodeIndeterminate(allNodes[0])).toBeTruthy(); expect(mockTree.nodeSelection.emit).not.toHaveBeenCalled(); selectionService.selectNodesWithNoEvent([allNodes[3], allNodes[4]], true); for (const node of allNodes.slice(3, 7)) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } expect(selectionService.isNodeIndeterminate(allNodes[0])).toBeTruthy(); expect(selectionService.isNodeIndeterminate(allNodes[1])).toBeTruthy(); expect(selectionService.isNodeSelected(allNodes[2])).toBeFalsy(); expect(mockTree.nodeSelection.emit).not.toHaveBeenCalled(); }); it('Should add newly selected nodes to the existing selection', () => { selectionService.selectNode(allNodes[1]); let expected: ITreeNodeSelectionEvent = { oldSelection: [], newSelection: allNodes.slice(1, 4), added: allNodes.slice(1, 4), removed: [], event: undefined, cancel: false, owner: mockTree }; for (const node of allNodes.slice(1, 4)) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } for (let i = 4; i < allNodes.length; i++) { expect(selectionService.isNodeSelected(allNodes[i])).toBeFalsy(); } expect(selectionService.isNodeIndeterminate(allNodes[0])).toBeTruthy(); expect(mockTree.nodeSelection.emit).toHaveBeenCalledWith(expected); expect(mockTree.nodeSelection.emit).toHaveBeenCalledTimes(1); expected = { oldSelection: allNodes.slice(1, 4), newSelection: [allNodes[1], allNodes[2], allNodes[3], allNodes[5]], added: [allNodes[5]], removed: [], event: undefined, cancel: false, owner: mockTree }; selectionService.selectNode(allNodes[5]); for (const node of allNodes.slice(1, 4)) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } expect(selectionService.isNodeSelected(allNodes[5])).toBeTruthy(); expect(selectionService.isNodeIndeterminate(allNodes[0])).toBeTruthy(); expect(mockTree.nodeSelection.emit).toHaveBeenCalledWith(expected); expect(mockTree.nodeSelection.emit).toHaveBeenCalledTimes(2); }); it('Should be able to select a range of nodes', () => { selectionService.selectNode(allNodes[3]); expect(selectionService.isNodeSelected(allNodes[3])).toBeTruthy(); // select all nodes from first to eighth selectionService.selectMultipleNodes(allNodes[8]); allNodes.forEach((node, index) => { if (index >= 4 && index <= 8) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } else if (index === 3) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); } else { expect(selectionService.isNodeSelected(node)).toBeFalsy(); } }); const expected: ITreeNodeSelectionEvent = { oldSelection: [allNodes[3]], newSelection: allNodes.slice(3, 9), added: allNodes.slice(4, 9), removed: [], event: undefined, cancel: false, owner: mockTree }; expect(mockTree.nodeSelection.emit).toHaveBeenCalledWith(expected); expect(selectionService.isNodeIndeterminate(allNodes[0])).toBeTruthy(); expect(selectionService.isNodeIndeterminate(allNodes[1])).toBeTruthy(); }); it('Should be able to select a range of nodes in reverse order', () => { selectionService.selectNode(allNodes[8]); // only seventh and eighth node are selected expect(selectionService.isNodeSelected(allNodes[7])).toBeTruthy(); expect(selectionService.isNodeSelected(allNodes[8])).toBeTruthy(); expect(allNodes[7].selectedChange.emit).toHaveBeenCalled(); expect(allNodes[7].selectedChange.emit).toHaveBeenCalledWith(true); expect(allNodes[8].selectedChange.emit).toHaveBeenCalled(); expect(allNodes[8].selectedChange.emit).toHaveBeenCalledWith(true); expect(mockTree.nodeSelection.emit).toHaveBeenCalledTimes(1); for (let i = 0; i < allNodes.length; i++) { if (i !== 7 && i !== 8) { expect(selectionService.isNodeSelected(allNodes[i])).toBeFalsy(); } } // select all nodes from eight to second selectionService.selectMultipleNodes(allNodes[2]); allNodes.forEach((node, index) => { if (index <= 8) { expect(selectionService.isNodeSelected(node)).toBeTruthy(); if (index < 7) { expect(node.selectedChange.emit).toHaveBeenCalled(); expect(node.selectedChange.emit).toHaveBeenCalledWith(true); } } else { expect(selectionService.isNodeSelected(node)).toBeFalsy(); } }); const expected: ITreeNodeSelectionEvent = { oldSelection: [allNodes[8], allNodes[7]], newSelection: [allNodes[8], allNodes[7], ...allNodes.slice(2, 7), allNodes[1], allNodes[0]], added: [...allNodes.slice(2, 7), allNodes[1], allNodes[0]], removed: [], event: undefined, cancel: false, owner: mockTree }; expect(mockTree.nodeSelection.emit).toHaveBeenCalledWith(expected); }); it('Should ensure correct state after a node entry is destroyed', () => { // instant frames go 'BRRRR' spyOn(window, 'requestAnimationFrame').and.callFake((callback: any) => callback()); const deselectSpy = spyOn(selectionService, 'deselectNodesWithNoEvent'); const selectSpy = spyOn(selectionService, 'selectNodesWithNoEvent'); const tree = { selection: IgxTreeSelectionType.None } as any; const selectedNodeSpy = spyOn(selectionService, 'isNodeSelected').and.returnValue(false); const mockNode = { selected: false } as any; selectionService.register(tree); selectionService.ensureStateOnNodeDelete(mockNode); expect(deselectSpy).not.toHaveBeenCalled(); expect(selectSpy).not.toHaveBeenCalled(); expect(selectedNodeSpy).not.toHaveBeenCalled(); tree.selection = IgxTreeSelectionType.BiState; selectionService.ensureStateOnNodeDelete(mockNode); expect(deselectSpy).not.toHaveBeenCalled(); expect(selectSpy).not.toHaveBeenCalled(); expect(selectedNodeSpy).not.toHaveBeenCalled(); tree.selection = IgxTreeSelectionType.Cascading; selectedNodeSpy.and.returnValue(true); selectionService.ensureStateOnNodeDelete(mockNode); expect(selectedNodeSpy).toHaveBeenCalledTimes(1); expect(selectedNodeSpy).toHaveBeenCalledWith(mockNode); expect(deselectSpy).toHaveBeenCalledTimes(1); expect(deselectSpy).toHaveBeenCalledWith([mockNode], false); expect(selectSpy).not.toHaveBeenCalled(); mockNode.parentNode = false; selectedNodeSpy.and.returnValue(false); selectionService.ensureStateOnNodeDelete(mockNode); expect(selectedNodeSpy).toHaveBeenCalledTimes(2); expect(deselectSpy).toHaveBeenCalledTimes(1); expect(selectSpy).not.toHaveBeenCalled(); const childrenSpy = jasmine.createSpyObj('creep', ['find']); childrenSpy.find.and.returnValue(null); mockNode.parentNode = { allChildren: childrenSpy }; selectionService.ensureStateOnNodeDelete(mockNode); expect(selectedNodeSpy).toHaveBeenCalledTimes(3); expect(deselectSpy).toHaveBeenCalledTimes(1); expect(selectSpy).not.toHaveBeenCalled(); const mockChild = { selected: true } as any; childrenSpy.find.and.returnValue(mockChild); selectionService.ensureStateOnNodeDelete(mockNode); expect(selectedNodeSpy).toHaveBeenCalledTimes(4); expect(deselectSpy).toHaveBeenCalledTimes(1); expect(selectSpy).toHaveBeenCalledTimes(1); expect(selectSpy).toHaveBeenCalledWith([mockChild], false, false); mockChild.selected = false; selectionService.ensureStateOnNodeDelete(mockNode); expect(selectedNodeSpy).toHaveBeenCalledTimes(5); expect(deselectSpy).toHaveBeenCalledTimes(2); expect(deselectSpy).toHaveBeenCalledWith([mockChild], false); expect(selectSpy).toHaveBeenCalledTimes(1); }); }); });
the_stack
import { OrderedMap } from "../../common"; // A representation of a type can be either an extended type, or a non-extended type. // Non-extended types are the types you traditionally find in Power Query, eg. `number`, `text`, etc. // // Extended types are an extension to the Power Query language. // For example, you can treat `1` as a subtype of `number`. export type TPowerQueryType = TPrimitiveType | TExtendedType; export type TExtendedType = | AnyUnion | DefinedFunction | DefinedList | DefinedListType | DefinedRecord | DefinedTable | FunctionType | ListType | LogicalLiteral | NumberLiteral | PrimaryPrimitiveType | RecordType | TableType | TableTypePrimaryExpression | TextLiteral; export type TExtendedTypeKind = | TypeKind.Any | TypeKind.Function | TypeKind.List | TypeKind.Logical | TypeKind.Number | TypeKind.Record | TypeKind.Table | TypeKind.Text | TypeKind.Type; export type TLiteral = LogicalLiteral | NumberLiteral | TextLiteral; export type TLiteralKind = | ExtendedTypeKind.LogicalLiteral | ExtendedTypeKind.NumberLiteral | ExtendedTypeKind.TextLiteral; export type TAny = Any | AnyUnion; export type TList = List | DefinedList; export type TLogical = Logical | LogicalLiteral; export type TFunction = Function | DefinedFunction; export type TNumber = Number | NumberLiteral; export type TRecord = Record | DefinedRecord; export type TTable = Table | DefinedTable; export type TText = Text | TextLiteral; export type TType = | Type | DefinedListType | FunctionType | ListType | PrimaryPrimitiveType | RecordType | TableType | TableTypePrimaryExpression; export type Action = IPrimitiveType<TypeKind.Action>; export type Any = IPrimitiveType<TypeKind.Any>; export type AnyNonNull = IPrimitiveType<TypeKind.AnyNonNull>; export type Binary = IPrimitiveType<TypeKind.Binary>; export type Date = IPrimitiveType<TypeKind.Date>; export type DateTime = IPrimitiveType<TypeKind.DateTime>; export type DateTimeZone = IPrimitiveType<TypeKind.DateTimeZone>; export type Duration = IPrimitiveType<TypeKind.Duration>; export type Function = IPrimitiveType<TypeKind.Function>; export type List = IPrimitiveType<TypeKind.List>; export type Logical = IPrimitiveType<TypeKind.Logical>; export type None = IPrimitiveType<TypeKind.None>; export type NotApplicable = IPrimitiveType<TypeKind.NotApplicable>; export type Null = IPrimitiveType<TypeKind.Null>; export type Number = IPrimitiveType<TypeKind.Number>; export type Record = IPrimitiveType<TypeKind.Record>; export type Table = IPrimitiveType<TypeKind.Table>; export type Text = IPrimitiveType<TypeKind.Text>; export type Time = IPrimitiveType<TypeKind.Time>; export type Type = IPrimitiveType<TypeKind.Type>; export type Unknown = IPrimitiveType<TypeKind.Unknown>; export type TPrimitiveType = | Action | Any | AnyNonNull | Binary | Date | DateTime | DateTimeZone | Duration | Function | List | Logical | None | NotApplicable | Null | Number | Record | Table | Text | Time | Type | Unknown; // Key value pairs for Records and Tables, // where tables have ordered pairs and records have unordered pairs. export type TFieldSpecificationList = FieldSpecificationList<TFields>; export type TFields = OrderedFields | UnorderedFields; export type OrderedFields = OrderedMap<string, TPowerQueryType>; export type UnorderedFields = Map<string, TPowerQueryType>; export const enum TypeKind { Any = "Any", AnyNonNull = "AnyNonNull", Binary = "Binary", Date = "Date", DateTime = "DateTime", DateTimeZone = "DateTimeZone", Duration = "Duration", Function = "Function", List = "List", Logical = "Logical", None = "None", Null = "Null", Number = "Number", Record = "Record", Table = "Table", Text = "Text", Type = "Type", // Types that are not defined in the standard. Action = "Action", Time = "Time", // Some NodeKinds are non-typeable, such as ArrayWrapper. // There can be nodes which are typable but contain non-typable children, such as RecordExpressions. NotApplicable = "NotApplicable", // Something that can't be typed due to a lack of information. // Eg. '[', a RecordExpression where the user hasn't entered any fields for. Unknown = "Unknown", } export const enum ExtendedTypeKind { // In Power Query if you want a union type, such as when a function returns either a `text` OR a `number`, // then you're only option is to give it the 'any' type. // This is a narrower definition which restricts that typing to the union `text | number`. AnyUnion = "AnyUnion", // A function with known paramaters and a known return type. DefinedFunction = "DefinedFunction", // A list of known size and a typing for each element in the list. // Eg. `{1, "foo"} DefinedList = "DefinedList", // A narrower typing for ListType, used to validate a DefinedList. DefinedListType = "DefinedListType", // A list of known fields and typing for each field. // An open record: `[a=1, b=2, ...]` // A closed record: `[a=1, b=2]` DefinedRecord = "DefinedRecord", // See details on DefinedRecord. They are functionally the same. DefinedTable = "DefinedTable", // `type function (x as number, optional y) => number` FunctionType = "FunctionType", // `type list { number }` ListType = "ListType", // true LogicalLiteral = "LogicalLiteral", // `1` NumberLiteral = "NumberLiteral", // `type number` PrimaryPrimitiveType = "PrimaryPrimitiveType", // `type record [ a, b = number, ...]` RecordType = "RecordType", // '"foo"` TextLiteral = "TextLiteral", // `type table [a, b = text] TableType = "TableType", // The docs say `table-type` only accepts a `field-specification-list` for `row-type`, // but the parser also accepts primary-expression. This handles that edge case. TableTypePrimaryExpression = "TableTypePrimaryExpression", } export interface IType<T extends TypeKind = TypeKind> { readonly kind: T; readonly maybeExtendedKind: ExtendedTypeKind | undefined; readonly isNullable: boolean; } export interface IExtendedType extends IType { readonly kind: TExtendedTypeKind; readonly maybeExtendedKind: ExtendedTypeKind; } export interface IPrimitiveLiteral<T> extends IExtendedType { readonly literal: string; readonly normalizedLiteral: T; } export interface IPrimitiveType<T extends TypeKind = TypeKind> extends IType<T> { readonly maybeExtendedKind: undefined; } // ------------------------------------------ // ---------- Non-IType Interfaces ---------- // ------------------------------------------ export interface FieldSpecificationList<T extends TFields> { readonly fields: T; readonly isOpen: boolean; } export interface FunctionSignature { readonly parameters: ReadonlyArray<FunctionParameter>; readonly returnType: TPowerQueryType; } export interface SimplifiedNullablePrimitiveType { readonly typeKind: TypeKind; readonly isNullable: boolean; } export interface FunctionParameter { // Technically a parameter's name isn't part of its type, // but it's useful to have when inspecting parameters. readonly nameLiteral: string; readonly isOptional: boolean; readonly isNullable: boolean; readonly maybeType: TypeKind | undefined; } // ------------------------------------------- // ---------- IType Implementations ---------- // ------------------------------------------- export interface AnyUnion extends IExtendedType { readonly kind: TypeKind.Any; readonly maybeExtendedKind: ExtendedTypeKind.AnyUnion; readonly unionedTypePairs: ReadonlyArray<TPowerQueryType>; } export type DefinedFunction = IExtendedType & FunctionSignature & { readonly kind: TypeKind.Function; readonly maybeExtendedKind: ExtendedTypeKind.DefinedFunction; }; // A list which has a finite number of elements. export interface DefinedList extends IExtendedType { readonly kind: TypeKind.List; readonly maybeExtendedKind: ExtendedTypeKind.DefinedList; readonly elements: ReadonlyArray<TPowerQueryType>; } // A ListType for DefinedList export interface DefinedListType extends IExtendedType { readonly kind: TypeKind.Type; readonly maybeExtendedKind: ExtendedTypeKind.DefinedListType; readonly itemTypes: ReadonlyArray<TPowerQueryType>; } export type DefinedRecord = IExtendedType & FieldSpecificationList<UnorderedFields> & { readonly kind: TypeKind.Record; readonly maybeExtendedKind: ExtendedTypeKind.DefinedRecord; }; export type DefinedTable = IExtendedType & FieldSpecificationList<OrderedFields> & { readonly kind: TypeKind.Table; readonly maybeExtendedKind: ExtendedTypeKind.DefinedTable; }; export type FunctionType = IExtendedType & FunctionSignature & { readonly kind: TypeKind.Type; readonly maybeExtendedKind: ExtendedTypeKind.FunctionType; }; export interface ListType extends IExtendedType { readonly kind: TypeKind.Type; readonly maybeExtendedKind: ExtendedTypeKind.ListType; readonly itemType: TPowerQueryType; } export interface LogicalLiteral extends IPrimitiveLiteral<boolean> { readonly kind: TypeKind.Logical; readonly maybeExtendedKind: ExtendedTypeKind.LogicalLiteral; } export interface NumberLiteral extends IPrimitiveLiteral<number> { readonly kind: TypeKind.Number; readonly maybeExtendedKind: ExtendedTypeKind.NumberLiteral; } export interface PrimaryPrimitiveType extends IExtendedType { readonly kind: TypeKind.Type; readonly maybeExtendedKind: ExtendedTypeKind.PrimaryPrimitiveType; readonly primitiveType: TPrimitiveType; } export type RecordType = IExtendedType & FieldSpecificationList<UnorderedFields> & { readonly kind: TypeKind.Type; readonly maybeExtendedKind: ExtendedTypeKind.RecordType; }; export type TableType = IExtendedType & FieldSpecificationList<UnorderedFields> & { readonly kind: TypeKind.Type; readonly maybeExtendedKind: ExtendedTypeKind.TableType; }; export interface TableTypePrimaryExpression extends IExtendedType { readonly kind: TypeKind.Type; readonly maybeExtendedKind: ExtendedTypeKind.TableTypePrimaryExpression; readonly primaryExpression: TPowerQueryType; } export interface TextLiteral extends IPrimitiveLiteral<string> { readonly kind: TypeKind.Text; readonly maybeExtendedKind: ExtendedTypeKind.TextLiteral; } // ------------------------------------------------------- // ---------- Non-nullable primitive singletons ---------- // ------------------------------------------------------- export const ActionInstance: IPrimitiveType<TypeKind.Action> = createPrimitiveType(TypeKind.Action, false); export const AnyInstance: IPrimitiveType<TypeKind.Any> = createPrimitiveType(TypeKind.Any, false); export const AnyNonNullInstance: IPrimitiveType<TypeKind.AnyNonNull> = createPrimitiveType(TypeKind.AnyNonNull, false); export const BinaryInstance: IPrimitiveType<TypeKind.Binary> = createPrimitiveType(TypeKind.Binary, false); export const DateInstance: IPrimitiveType<TypeKind.Date> = createPrimitiveType(TypeKind.Date, false); export const DateTimeInstance: IPrimitiveType<TypeKind.DateTime> = createPrimitiveType(TypeKind.DateTime, false); export const DateTimeZoneInstance: IPrimitiveType<TypeKind.DateTimeZone> = createPrimitiveType( TypeKind.DateTimeZone, false, ); export const DurationInstance: IPrimitiveType<TypeKind.Duration> = createPrimitiveType(TypeKind.Duration, false); export const FunctionInstance: IPrimitiveType<TypeKind.Function> = createPrimitiveType(TypeKind.Function, false); export const ListInstance: IPrimitiveType<TypeKind.List> = createPrimitiveType(TypeKind.List, false); export const LogicalInstance: IPrimitiveType<TypeKind.Logical> = createPrimitiveType(TypeKind.Logical, false); export const NoneInstance: IPrimitiveType<TypeKind.None> = createPrimitiveType(TypeKind.None, false); export const NotApplicableInstance: IPrimitiveType<TypeKind.NotApplicable> = createPrimitiveType( TypeKind.NotApplicable, false, ); export const NullInstance: IPrimitiveType<TypeKind.Null> = createPrimitiveType(TypeKind.Null, true); export const NumberInstance: IPrimitiveType<TypeKind.Number> = createPrimitiveType(TypeKind.Number, false); export const RecordInstance: IPrimitiveType<TypeKind.Record> = createPrimitiveType(TypeKind.Record, false); export const TableInstance: IPrimitiveType<TypeKind.Table> = createPrimitiveType(TypeKind.Table, false); export const TextInstance: IPrimitiveType<TypeKind.Text> = createPrimitiveType(TypeKind.Text, false); export const TimeInstance: IPrimitiveType<TypeKind.Time> = createPrimitiveType(TypeKind.Time, false); export const TypePrimitiveInstance: IPrimitiveType<TypeKind.Type> = createPrimitiveType(TypeKind.Type, false); export const UnknownInstance: IPrimitiveType<TypeKind.Unknown> = createPrimitiveType(TypeKind.Unknown, false); // --------------------------------------------------- // ---------- Nullable primitive singletons ---------- // --------------------------------------------------- export const NullableActionInstance: IPrimitiveType<TypeKind.Action> = createPrimitiveType(TypeKind.Action, true); export const NullableAnyInstance: IPrimitiveType<TypeKind.Any> = createPrimitiveType(TypeKind.Any, true); export const NullableBinaryInstance: IPrimitiveType<TypeKind.Binary> = createPrimitiveType(TypeKind.Binary, true); export const NullableDateInstance: IPrimitiveType<TypeKind.Date> = createPrimitiveType(TypeKind.Date, true); export const NullableDateTimeInstance: IPrimitiveType<TypeKind.DateTime> = createPrimitiveType(TypeKind.DateTime, true); export const NullableDateTimeZoneInstance: IPrimitiveType<TypeKind.DateTimeZone> = createPrimitiveType( TypeKind.DateTimeZone, true, ); export const NullableDurationInstance: IPrimitiveType<TypeKind.Duration> = createPrimitiveType(TypeKind.Duration, true); export const NullableFunctionInstance: IPrimitiveType<TypeKind.Function> = createPrimitiveType(TypeKind.Function, true); export const NullableListInstance: IPrimitiveType<TypeKind.List> = createPrimitiveType(TypeKind.List, true); export const NullableLogicalInstance: IPrimitiveType<TypeKind.Logical> = createPrimitiveType(TypeKind.Logical, true); export const NullableNoneInstance: IPrimitiveType<TypeKind.None> = createPrimitiveType(TypeKind.None, true); export const NullableNotApplicableInstance: IPrimitiveType<TypeKind.NotApplicable> = createPrimitiveType( TypeKind.NotApplicable, true, ); export const NullableNumberInstance: IPrimitiveType<TypeKind.Number> = createPrimitiveType(TypeKind.Number, true); export const NullableRecordInstance: IPrimitiveType<TypeKind.Record> = createPrimitiveType(TypeKind.Record, true); export const NullableTableInstance: IPrimitiveType<TypeKind.Table> = createPrimitiveType(TypeKind.Table, true); export const NullableTextInstance: IPrimitiveType<TypeKind.Text> = createPrimitiveType(TypeKind.Text, true); export const NullableTimeInstance: IPrimitiveType<TypeKind.Time> = createPrimitiveType(TypeKind.Time, true); export const NullableTypeInstance: IPrimitiveType<TypeKind.Type> = createPrimitiveType(TypeKind.Type, true); export const NullableUnknownInstance: IPrimitiveType<TypeKind.Unknown> = createPrimitiveType(TypeKind.Unknown, true); // ---------------------------------------------- // ---------- Non-primitive singletons ---------- // ---------------------------------------------- export const FalseInstance: LogicalLiteral = createLogicalLiteral(false, false); export const TrueInstance: LogicalLiteral = createLogicalLiteral(false, true); export const NullableFalseInstance: LogicalLiteral = createLogicalLiteral(true, false); export const NullableTrueInstance: LogicalLiteral = createLogicalLiteral(true, true); export const PrimitiveInstance: AnyUnion = { kind: TypeKind.Any, maybeExtendedKind: ExtendedTypeKind.AnyUnion, isNullable: false, unionedTypePairs: [ ActionInstance, AnyInstance, AnyNonNullInstance, BinaryInstance, DateInstance, DateTimeInstance, DateTimeZoneInstance, DurationInstance, FunctionInstance, ListInstance, LogicalInstance, NoneInstance, NotApplicableInstance, NullInstance, NumberInstance, RecordInstance, TableInstance, TextInstance, TimeInstance, TypePrimitiveInstance, ], }; export const NullablePrimitiveInstance: AnyUnion = { kind: TypeKind.Any, maybeExtendedKind: ExtendedTypeKind.AnyUnion, isNullable: true, unionedTypePairs: [ NullableActionInstance, NullableAnyInstance, NullableBinaryInstance, NullableDateInstance, NullableDateTimeInstance, NullableDateTimeZoneInstance, NullableDurationInstance, NullableFunctionInstance, NullableListInstance, NullableLogicalInstance, NullableNoneInstance, NullableNotApplicableInstance, NullableNumberInstance, NullableRecordInstance, NullableTableInstance, NullableTextInstance, NullableTimeInstance, NullableTypeInstance, ], }; export const ExpressionInstance: AnyUnion = { kind: TypeKind.Any, maybeExtendedKind: ExtendedTypeKind.AnyUnion, isNullable: PrimitiveInstance.isNullable || NullablePrimitiveInstance.isNullable, unionedTypePairs: [...PrimitiveInstance.unionedTypePairs, ...NullablePrimitiveInstance.unionedTypePairs], }; export const LiteralExpressionInstance: AnyUnion = { kind: TypeKind.Any, maybeExtendedKind: ExtendedTypeKind.AnyUnion, isNullable: LogicalInstance.isNullable || NumberInstance.isNullable || TextInstance.isNullable || NullInstance.isNullable, unionedTypePairs: [LogicalInstance, NumberInstance, TextInstance, NullInstance], }; export const PrimaryExpressionInstance: AnyUnion = { kind: TypeKind.Any, maybeExtendedKind: ExtendedTypeKind.AnyUnion, isNullable: LiteralExpressionInstance.isNullable || ListInstance.isNullable || RecordInstance.isNullable, unionedTypePairs: [...LiteralExpressionInstance.unionedTypePairs, ListInstance, RecordInstance], }; export const PrimaryTypeInstance: AnyUnion = { kind: TypeKind.Any, maybeExtendedKind: ExtendedTypeKind.AnyUnion, isNullable: true, unionedTypePairs: [...PrimitiveInstance.unionedTypePairs, ...NullablePrimitiveInstance.unionedTypePairs], }; export const TypeProductionInstance: AnyUnion = { kind: TypeKind.Any, maybeExtendedKind: ExtendedTypeKind.AnyUnion, isNullable: ExpressionInstance.isNullable || PrimaryTypeInstance.isNullable, unionedTypePairs: [...ExpressionInstance.unionedTypePairs, ...PrimaryTypeInstance.unionedTypePairs], }; export const TypeExpressionInstance: AnyUnion = { kind: TypeKind.Any, maybeExtendedKind: ExtendedTypeKind.AnyUnion, isNullable: PrimaryExpressionInstance.isNullable || PrimaryTypeInstance.isNullable, unionedTypePairs: [PrimaryExpressionInstance, PrimaryTypeInstance], }; export const AnyLiteralInstance: AnyUnion = { kind: TypeKind.Any, maybeExtendedKind: ExtendedTypeKind.AnyUnion, isNullable: RecordInstance.isNullable || ListInstance.isNullable || LogicalInstance.isNullable || NumberInstance.isNullable || TextInstance.isNullable || NullInstance.isNullable, unionedTypePairs: [RecordInstance, ListInstance, LogicalInstance, NumberInstance, TextInstance, NullInstance], }; // -------------------------------------- // ---------- Helper functions ---------- // -------------------------------------- // Creates IPrimitiveType<T> singleton instances. function createPrimitiveType<T extends TypeKind>(typeKind: T, isNullable: boolean): IPrimitiveType<T> { return { kind: typeKind, maybeExtendedKind: undefined, isNullable, }; } function createLogicalLiteral(isNullable: boolean, normalizedLiteral: boolean): LogicalLiteral { return { isNullable, kind: TypeKind.Logical, maybeExtendedKind: ExtendedTypeKind.LogicalLiteral, literal: normalizedLiteral ? "true" : "false", normalizedLiteral, }; }
the_stack
import { BehaviorSubject } from 'rxjs'; import { filter, take } from 'rxjs/operators'; import { DexieCloudDB } from '../db/DexieCloudDB'; import { WSConnectionMsg } from '../WSObservable'; import { triggerSync } from './triggerSync'; import Dexie from 'dexie'; import { computeRealmSetHash } from '../helpers/computeRealmSetHash'; import { DBOperationsSet } from 'dexie-cloud-common'; import { getSyncableTables } from '../helpers/getSyncableTables'; import { getMutationTable } from '../helpers/getMutationTable'; import { listClientChanges } from './listClientChanges'; import { applyServerChanges, filterServerChangesThroughAddedClientChanges, } from './sync'; import { updateBaseRevs } from './updateBaseRevs'; import { getLatestRevisionsPerTable } from './getLatestRevisionsPerTable'; import { refreshAccessToken } from '../authentication/authenticate'; export type MessagesFromServerConsumer = ReturnType< typeof MessagesFromServerConsumer >; export function MessagesFromServerConsumer(db: DexieCloudDB) { const queue: WSConnectionMsg[] = []; const readyToServe = new BehaviorSubject(true); const event = new BehaviorSubject(null); let isWorking = false; let loopWarning = 0; let loopDetection = [0,0,0,0,0,0,0,0,0,Date.now()]; event.subscribe(async () => { if (isWorking) return; if (queue.length > 0) { isWorking = true; loopDetection.shift(); loopDetection.push(Date.now()); readyToServe.next(false); try { await consumeQueue(); } finally { if (loopDetection[loopDetection.length-1] - loopDetection[0] < 10000) { // Ten loops within 10 seconds. Slow down! if (Date.now() - loopWarning < 5000) { // Last time we did this, we ended up here too. Wait for a minute. console.warn(`Slowing down websocket loop for one minute`) loopWarning = Date.now() + 60000; await new Promise(resolve => setTimeout(resolve, 60000)); } else { // This is a one-time event. Just pause 10 seconds. console.warn(`Slowing down websocket loop for 10 seconds`); loopWarning = Date.now() + 10000; await new Promise(resolve => setTimeout(resolve, 10000)); } } isWorking = false; readyToServe.next(true); } } }); function enqueue(msg: WSConnectionMsg) { queue.push(msg); event.next(null); } async function consumeQueue() { while (queue.length > 0) { const msg = queue.shift(); try { console.debug('processing msg', msg); // If the sync worker or service worker is syncing, wait 'til thei're done. // It's no need to have two channels at the same time - even though it wouldnt // be a problem - this is an optimization. await db.cloud.syncState .pipe( filter(({ phase }) => phase === 'in-sync' || phase === 'error'), take(1) ) .toPromise(); console.debug('processing msg', msg); const persistedSyncState = db.cloud.persistedSyncState.value; //syncState. if (!msg) continue; switch (msg.type) { case 'token-expired': console.debug( 'WebSocket observable: Token expired. Refreshing token...' ); const user = db.cloud.currentUser.value; // Refresh access token const refreshedLogin = await refreshAccessToken( db.cloud.options!.databaseUrl, user ); // Persist updated access token await db.table('$logins').update(user.userId, { accessToken: refreshedLogin.accessToken, accessTokenExpiration: refreshedLogin.accessTokenExpiration, }); // Updating $logins will trigger emission of db.cloud.currentUser observable, which // in turn will lead to that connectWebSocket.ts will reconnect the socket with the // new token. So we don't need to do anything more here. break; case 'realm-added': if (!persistedSyncState?.realms?.includes(msg.realm)) { triggerSync(db, 'pull'); } break; case 'realm-removed': if (persistedSyncState?.realms?.includes(msg.realm)) { triggerSync(db, 'pull'); } break; case 'realms-changed': triggerSync(db, 'pull'); break; case 'changes': console.debug('changes'); if (db.cloud.syncState.value?.phase === 'error') { triggerSync(db, 'pull'); break; } await db.transaction('rw', db.dx.tables, async (tx) => { // @ts-ignore tx.idbtrans.disableChangeTracking = true; // @ts-ignore tx.idbtrans.disableAccessControl = true; const [schema, syncState, currentUser] = await Promise.all([ db.getSchema(), db.getPersistedSyncState(), db.getCurrentUser(), ]); console.debug('ws message queue: in transaction'); if (!syncState || !schema || !currentUser) { console.debug('required vars not present', { syncState, schema, currentUser, }); return; // Initial sync must have taken place - otherwise, ignore this. } // Verify again in ACID tx that we're on same server revision. if (msg.baseRev !== syncState.serverRevision) { console.debug( `baseRev (${msg.baseRev}) differs from our serverRevision in syncState (${syncState.serverRevision})` ); // Should we trigger a sync now? No. This is a normal case // when another local peer (such as the SW or a websocket channel on other tab) has // updated syncState from new server information but we are not aware yet. It would // be unnescessary to do a sync in that case. Instead, the caller of this consumeQueue() // function will do readyToServe.next(true) right after this return, which will lead // to a "ready" message being sent to server with the new accurate serverRev we have, // so that the next message indeed will be correct. if ( typeof msg.baseRev === 'string' && // v2 format (typeof syncState.serverRevision === 'bigint' || // v1 format typeof syncState.serverRevision === 'object') // v1 format old browser ) { // The reason for the diff seems to be that server has migrated the revision format. // Do a full sync to update revision format. // If we don't do a sync request now, we could stuck in an endless loop. triggerSync(db, 'pull'); } return; // Ignore message } // Verify also that the message is based on the exact same set of realms const ourRealmSetHash = await Dexie.waitFor( // Keep TX in non-IDB work computeRealmSetHash(syncState) ); console.debug('ourRealmSetHash', ourRealmSetHash); if (ourRealmSetHash !== msg.realmSetHash) { console.debug('not same realmSetHash', msg.realmSetHash); triggerSync(db, 'pull'); // The message isn't based on the same realms. // Trigger a sync instead to resolve all things up. return; } // Get clientChanges let clientChanges: DBOperationsSet = []; if (currentUser.isLoggedIn) { const mutationTables = getSyncableTables(db).map((tbl) => db.table(getMutationTable(tbl.name)) ); clientChanges = await listClientChanges(mutationTables, db); console.debug('msg queue: client changes', clientChanges); } if (msg.changes.length > 0) { const filteredChanges = filterServerChangesThroughAddedClientChanges( msg.changes, clientChanges ); // // apply server changes // console.debug( 'applying filtered server changes', filteredChanges ); await applyServerChanges(filteredChanges, db); } // Update latest revisions per table in case there are unsynced changes // This can be a real case in future when we allow non-eagery sync. // And it can actually be realistic now also, but very rare. syncState.latestRevisions = getLatestRevisionsPerTable( clientChanges, syncState.latestRevisions ); syncState.serverRevision = msg.newRev; // Update base revs console.debug('Updating baseRefs', syncState.latestRevisions); await updateBaseRevs( db, schema!, syncState.latestRevisions, msg.newRev ); // // Update syncState // console.debug('Updating syncState', syncState); await db.$syncState.put(syncState, 'syncState'); }); console.debug('msg queue: done with rw transaction'); break; } } catch (error) { console.error(`Error in msg queue`, error); } } } return { enqueue, readyToServe, }; }
the_stack
import * as React from 'react' import { createApi, setupListeners } from '@reduxjs/toolkit/query/react' import { act, fireEvent, render, waitFor, screen } from '@testing-library/react' import { setupApiStore, waitMs } from './helpers' import { AnyAction } from '@reduxjs/toolkit' // Just setup a temporary in-memory counter for tests that `getIncrementedAmount`. // This can be used to test how many renders happen due to data changes or // the refetching behavior of components. let amount = 0 const defaultApi = createApi({ baseQuery: async (arg: any) => { await waitMs() if ('amount' in arg?.body) { amount += 1 } return { data: arg?.body ? { ...arg.body, ...(amount ? { amount } : {}) } : undefined, } }, endpoints: (build) => ({ getIncrementedAmount: build.query<any, void>({ query: () => ({ url: '', body: { amount, }, }), }), }), refetchOnFocus: true, refetchOnReconnect: true, }) const storeRef = setupApiStore(defaultApi) afterEach(() => { amount = 0 }) describe('refetchOnFocus tests', () => { test('useQuery hook respects refetchOnFocus: true when set in createApi options', async () => { let data, isLoading, isFetching function User() { ;({ data, isFetching, isLoading } = defaultApi.endpoints.getIncrementedAmount.useQuery()) return ( <div> <div data-testid="isLoading">{String(isLoading)}</div> <div data-testid="isFetching">{String(isFetching)}</div> <div data-testid="amount">{String(data?.amount)}</div> </div> ) } render(<User />, { wrapper: storeRef.wrapper }) await waitFor(() => expect(screen.getByTestId('isLoading').textContent).toBe('true') ) await waitFor(() => expect(screen.getByTestId('isLoading').textContent).toBe('false') ) await waitFor(() => expect(screen.getByTestId('amount').textContent).toBe('1') ) act(() => { fireEvent.focus(window) }) await waitMs() await waitFor(() => expect(screen.getByTestId('amount').textContent).toBe('2') ) }) test('useQuery hook respects refetchOnFocus: false from a hook and overrides createApi defaults', async () => { let data, isLoading, isFetching function User() { ;({ data, isFetching, isLoading } = defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, { refetchOnFocus: false, })) return ( <div> <div data-testid="isLoading">{String(isLoading)}</div> <div data-testid="isFetching">{String(isFetching)}</div> <div data-testid="amount">{String(data?.amount)}</div> </div> ) } render(<User />, { wrapper: storeRef.wrapper }) await waitFor(() => expect(screen.getByTestId('isLoading').textContent).toBe('true') ) await waitFor(() => expect(screen.getByTestId('isLoading').textContent).toBe('false') ) await waitFor(() => expect(screen.getByTestId('amount').textContent).toBe('1') ) act(() => { fireEvent.focus(window) }) await waitMs() await waitFor(() => expect(screen.getByTestId('amount').textContent).toBe('1') ) }) test('useQuery hook prefers refetchOnFocus: true when multiple components have different configurations', async () => { let data, isLoading, isFetching function User() { ;({ data, isFetching, isLoading } = defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, { refetchOnFocus: false, })) return ( <div> <div data-testid="isLoading">{String(isLoading)}</div> <div data-testid="isFetching">{String(isFetching)}</div> <div data-testid="amount">{String(data?.amount)}</div> </div> ) } function UserWithRefetchTrue() { ;({ data, isFetching, isLoading } = defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, { refetchOnFocus: true, })) return <div /> } render( <div> <User /> <UserWithRefetchTrue /> </div>, { wrapper: storeRef.wrapper } ) await waitFor(() => expect(screen.getByTestId('isLoading').textContent).toBe('true') ) await waitFor(() => expect(screen.getByTestId('isLoading').textContent).toBe('false') ) await waitFor(() => expect(screen.getByTestId('amount').textContent).toBe('1') ) act(() => { fireEvent.focus(window) }) expect(screen.getByTestId('isLoading').textContent).toBe('false') await waitFor(() => expect(screen.getByTestId('isFetching').textContent).toBe('true') ) await waitFor(() => expect(screen.getByTestId('isFetching').textContent).toBe('false') ) await waitFor(() => expect(screen.getByTestId('amount').textContent).toBe('2') ) }) }) describe('refetchOnReconnect tests', () => { test('useQuery hook respects refetchOnReconnect: true when set in createApi options', async () => { let data, isLoading, isFetching function User() { ;({ data, isFetching, isLoading } = defaultApi.endpoints.getIncrementedAmount.useQuery()) return ( <div> <div data-testid="isLoading">{String(isLoading)}</div> <div data-testid="isFetching">{String(isFetching)}</div> <div data-testid="amount">{String(data?.amount)}</div> </div> ) } render(<User />, { wrapper: storeRef.wrapper }) await waitFor(() => expect(screen.getByTestId('isLoading').textContent).toBe('true') ) await waitFor(() => expect(screen.getByTestId('isLoading').textContent).toBe('false') ) await waitFor(() => expect(screen.getByTestId('amount').textContent).toBe('1') ) act(() => { window.dispatchEvent(new Event('offline')) window.dispatchEvent(new Event('online')) }) await waitFor(() => expect(screen.getByTestId('isFetching').textContent).toBe('true') ) await waitFor(() => expect(screen.getByTestId('isFetching').textContent).toBe('false') ) await waitFor(() => expect(screen.getByTestId('amount').textContent).toBe('2') ) }) test('useQuery hook should not refetch when refetchOnReconnect: false from a hook and overrides createApi defaults', async () => { let data, isLoading, isFetching function User() { ;({ data, isFetching, isLoading } = defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, { refetchOnReconnect: false, })) return ( <div> <div data-testid="isLoading">{String(isLoading)}</div> <div data-testid="isFetching">{String(isFetching)}</div> <div data-testid="amount">{String(data?.amount)}</div> </div> ) } render(<User />, { wrapper: storeRef.wrapper }) await waitFor(() => expect(screen.getByTestId('isLoading').textContent).toBe('true') ) await waitFor(() => expect(screen.getByTestId('isLoading').textContent).toBe('false') ) await waitFor(() => expect(screen.getByTestId('amount').textContent).toBe('1') ) act(() => { window.dispatchEvent(new Event('offline')) window.dispatchEvent(new Event('online')) }) expect(screen.getByTestId('isFetching').textContent).toBe('false') await waitFor(() => expect(screen.getByTestId('amount').textContent).toBe('1') ) }) test('useQuery hook prefers refetchOnReconnect: true when multiple components have different configurations', async () => { let data, isLoading, isFetching function User() { ;({ data, isFetching, isLoading } = defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, { refetchOnReconnect: false, })) return ( <div> <div data-testid="isLoading">{String(isLoading)}</div> <div data-testid="isFetching">{String(isFetching)}</div> <div data-testid="amount">{String(data?.amount)}</div> </div> ) } function UserWithRefetchTrue() { ;({ data, isFetching, isLoading } = defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, { refetchOnReconnect: true, })) return <div /> } render( <div> <User /> <UserWithRefetchTrue /> </div>, { wrapper: storeRef.wrapper } ) await waitFor(() => expect(screen.getByTestId('isLoading').textContent).toBe('true') ) await waitFor(() => expect(screen.getByTestId('isLoading').textContent).toBe('false') ) await waitFor(() => expect(screen.getByTestId('amount').textContent).toBe('1') ) act(() => { window.dispatchEvent(new Event('offline')) window.dispatchEvent(new Event('online')) }) await waitFor(() => expect(screen.getByTestId('isFetching').textContent).toBe('true') ) await waitFor(() => expect(screen.getByTestId('isFetching').textContent).toBe('false') ) await waitFor(() => expect(screen.getByTestId('amount').textContent).toBe('2') ) }) }) describe('customListenersHandler', () => { const storeRef = setupApiStore(defaultApi, undefined, true) test('setupListeners accepts a custom callback and executes it', async () => { const consoleSpy = jest.spyOn(console, 'log') consoleSpy.mockImplementation(() => {}) const dispatchSpy = jest.spyOn(storeRef.store, 'dispatch') let unsubscribe = () => {} unsubscribe = setupListeners( storeRef.store.dispatch, (dispatch, actions) => { const handleOnline = () => dispatch(defaultApi.internalActions.onOnline()) window.addEventListener('online', handleOnline, false) console.log('setup!') return () => { window.removeEventListener('online', handleOnline) console.log('cleanup!') } } ) await waitMs() let data, isLoading, isFetching function User() { ;({ data, isFetching, isLoading } = defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, { refetchOnReconnect: true, })) return ( <div> <div data-testid="isLoading">{String(isLoading)}</div> <div data-testid="isFetching">{String(isFetching)}</div> <div data-testid="amount">{String(data?.amount)}</div> </div> ) } render(<User />, { wrapper: storeRef.wrapper }) expect(consoleSpy).toHaveBeenCalledWith('setup!') await waitFor(() => expect(screen.getByTestId('isLoading').textContent).toBe('true') ) await waitFor(() => expect(screen.getByTestId('isLoading').textContent).toBe('false') ) await waitFor(() => expect(screen.getByTestId('amount').textContent).toBe('1') ) act(() => { window.dispatchEvent(new Event('offline')) window.dispatchEvent(new Event('online')) }) expect(dispatchSpy).toHaveBeenCalled() expect( defaultApi.internalActions.onOnline.match( dispatchSpy.mock.calls[1][0] as any ) ).toBe(true) await waitFor(() => expect(screen.getByTestId('isFetching').textContent).toBe('true') ) await waitFor(() => expect(screen.getByTestId('isFetching').textContent).toBe('false') ) await waitFor(() => expect(screen.getByTestId('amount').textContent).toBe('2') ) unsubscribe() expect(consoleSpy).toHaveBeenCalledWith('cleanup!') }) })
the_stack
import { Dictionary } from '../../base/dictionary'; import { LineStyle } from '../../base/types'; import { WBorders } from './borders'; import { WUniqueFormat } from '../../base/unique-format'; import { WUniqueFormats } from '../../base/unique-formats'; import { isNullOrUndefined } from '@syncfusion/ej2-base'; /** * @private */ export class WBorder { private uniqueBorderFormat: WUniqueFormat = undefined; private static uniqueBorderFormats: WUniqueFormats = new WUniqueFormats(); private static uniqueFormatType: number = 1; public ownerBase: WBorders = undefined; public get color(): string { return this.getPropertyValue('color') as string; } public set color(value: string) { this.setPropertyValue('color', value); } public get lineStyle(): LineStyle { return this.getPropertyValue('lineStyle') as LineStyle; } public set lineStyle(value: LineStyle) { this.setPropertyValue('lineStyle', value); } public get lineWidth(): number { return this.getPropertyValue('lineWidth') as number; } public set lineWidth(value: number) { this.setPropertyValue('lineWidth', value); } public get shadow(): boolean { return this.getPropertyValue('shadow') as boolean; } public set shadow(value: boolean) { this.setPropertyValue('shadow', value); } public get space(): number { return this.getPropertyValue('space') as number; } public set space(value: number) { this.setPropertyValue('space', value); } public get hasNoneStyle(): boolean { return this.getPropertyValue('hasNoneStyle') as boolean; } public set hasNoneStyle(value: boolean) { this.setPropertyValue('hasNoneStyle', value); } public get isBorderDefined(): boolean { return (this.lineStyle !== 'None' || (this.hasNoneStyle && this.hasValue('hasNoneStyle'))); } public constructor(node?: WBorders) { this.ownerBase = node; } /* eslint-disable */ private getPropertyValue(property: string): Object { const hasValue: boolean = this.hasValue(property); if (hasValue) { const propertyType: number = WUniqueFormat.getPropertyType(WBorder.uniqueFormatType, property); if (!isNullOrUndefined(this.uniqueBorderFormat)) { const propValue: Object = this.uniqueBorderFormat.propertiesHash.get(propertyType); if (!isNullOrUndefined(propValue)) { return propValue; } } } return WBorder.getPropertyDefaultValue(property); } private setPropertyValue(property: string, value: Object): void { if (isNullOrUndefined(value) || value === '') { value = WBorder.getPropertyDefaultValue(property); } if (isNullOrUndefined(this.uniqueBorderFormat)) { this.initializeUniqueBorder(property, value); } else { const propertyType: number = WUniqueFormat.getPropertyType(this.uniqueBorderFormat.uniqueFormatType, property); if (this.uniqueBorderFormat.propertiesHash.containsKey(propertyType) && this.uniqueBorderFormat.propertiesHash.get(propertyType) === value) { //Do nothing, since no change in property value and return return; } this.uniqueBorderFormat = WBorder.uniqueBorderFormats.updateUniqueFormat(this.uniqueBorderFormat, property, value); } } private initializeUniqueBorder(property: string, propValue: Object): void { const uniqueBorderFormatTemp: Dictionary<number, object> = new Dictionary<number, object>(); this.addUniqueBorderFormat('color', property, propValue, uniqueBorderFormatTemp); this.addUniqueBorderFormat('lineStyle', property, propValue, uniqueBorderFormatTemp); this.addUniqueBorderFormat('lineWidth', property, propValue, uniqueBorderFormatTemp); this.addUniqueBorderFormat('shadow', property, propValue, uniqueBorderFormatTemp); this.addUniqueBorderFormat('space', property, propValue, uniqueBorderFormatTemp); this.addUniqueBorderFormat('hasNoneStyle', property, propValue, uniqueBorderFormatTemp); this.uniqueBorderFormat = WBorder.uniqueBorderFormats.addUniqueFormat(uniqueBorderFormatTemp, WBorder.uniqueFormatType); } private addUniqueBorderFormat(property: string, modifiedProperty: string, propValue: Object, uniqueBorderFormatTemp: Dictionary<number, object>): void { const propertyType: number = WUniqueFormat.getPropertyType(WBorder.uniqueFormatType, property); if (property === modifiedProperty) { uniqueBorderFormatTemp.add(propertyType, propValue); } } private static getPropertyDefaultValue(property: string): Object { let value: Object = undefined; /* eslint-enable */ switch (property) { case 'color': value = '#000000'; break; case 'lineStyle': value = 'None'; break; case 'lineWidth': value = 0; break; case 'shadow': value = false; break; case 'space': value = 0; break; case 'hasNoneStyle': value = false; break; } return value; } public getLineWidth(): number { /* eslint-disable */ switch (this.lineStyle) { case 'None': case 'Cleared': return 0; case 'Triple': case 'Double': case 'ThinThickSmallGap': case 'ThickThinSmallGap': case 'ThinThickThinSmallGap': case 'ThinThickMediumGap': case 'ThickThinMediumGap': case 'ThinThickThinMediumGap': case 'ThinThickLargeGap': case 'ThickThinLargeGap': case 'ThinThickThinLargeGap': case 'Emboss3D': case 'Engrave3D': { let lineArray: number[] = this.getBorderLineWidthArray(this.lineStyle, this.lineWidth); let width: number = 0; for (let i: number = 0; i < lineArray.length; i++) { width += lineArray[i]; } return width; } case 'Single': case 'DashLargeGap': case 'DashSmallGap': case 'Dot': case 'DashDot': case 'DashDotDot': case 'Thick': return this.lineWidth; case 'SingleWavy': return (this.lineWidth === 1.5 ? 3 : 2.5); //Double wave border only draw with the fixed width case 'DoubleWavy': return (6.75); //Double wave border only draw with the fixed width case 'DashDotStroked': case 'Outset': return this.lineWidth; } return this.lineWidth; /* eslint-enable */ } private getBorderLineWidthArray(lineStyle: LineStyle, lineWidth: number): number[] { let borderLineArray: number[] = [lineWidth]; switch (lineStyle) { case 'Double': borderLineArray = [1, 1, 1]; break; case 'ThinThickSmallGap': borderLineArray = [1, -0.75, -0.75]; break; case 'ThickThinSmallGap': borderLineArray = [-0.75, -0.75, 1]; break; case 'ThinThickMediumGap': borderLineArray = [1, 0.5, 0.5]; break; case 'ThickThinMediumGap': borderLineArray = [0.5, 0.5, 1]; break; case 'ThinThickLargeGap': borderLineArray = [-1.5, 1, -0.75]; break; case 'ThickThinLargeGap': borderLineArray = [-0.75, 1, -1.5]; break; case 'Triple': borderLineArray = [1, 1, 1, 1, 1]; break; case 'ThinThickThinSmallGap': borderLineArray = [-0.75, -0.75, 1, -0.75, -0.75]; break; case 'ThinThickThinMediumGap': borderLineArray = [0.5, 0.5, 1, 0.5, 0.5]; break; case 'ThinThickThinLargeGap': borderLineArray = [-0.75, 1, -1.5, 1, -0.75]; break; case 'Emboss3D': case 'Engrave3D': borderLineArray = [0.25, 0, 1, 0, 0.25]; break; } if (borderLineArray.length === 1) { return [lineWidth]; } for (let i: number = 0; i < borderLineArray.length; i++) { if (borderLineArray[i] >= 0) { borderLineArray[i] = borderLineArray[i] * lineWidth; } else { borderLineArray[i] = Math.abs(borderLineArray[i]); } } return borderLineArray; } public getBorderWeight(): number { let weight: number = 0; const numberOfLines: number = this.getNumberOfLines(); const borderNumber: number = this.getBorderNumber(); switch (this.lineStyle) { case 'Single': case 'DashSmallGap': case 'DashDot': case 'DashDotDot': case 'Double': case 'Triple': case 'ThinThickSmallGap': case 'ThickThinSmallGap': case 'ThinThickThinSmallGap': case 'ThinThickMediumGap': case 'ThickThinMediumGap': case 'ThinThickThinMediumGap': case 'ThinThickLargeGap': case 'ThickThinLargeGap': case 'ThinThickThinLargeGap': case 'SingleWavy': case 'DoubleWavy': case 'DashDotStroked': case 'Emboss3D': case 'Engrave3D': case 'Outset': case 'Inset': case 'Thick': weight = numberOfLines * borderNumber; break; case 'Dot': case 'DashLargeGap': weight = 1; break; } return weight; } private getBorderNumber(): number { let borderNumber: number = 0; switch (this.lineStyle) { case 'Single': borderNumber = 1; break; case 'Thick': borderNumber = 2; break; case 'Double': borderNumber = 3; break; case 'Dot': borderNumber = 4; break; case 'DashLargeGap': //dashed. borderNumber = 5; break; case 'DashDot': borderNumber = 6; break; case 'DashDotDot': borderNumber = 7; break; case 'Triple': borderNumber = 8; break; case 'ThinThickSmallGap': borderNumber = 9; break; case 'ThickThinSmallGap': borderNumber = 10; break; case 'ThinThickThinSmallGap': borderNumber = 11; break; case 'ThinThickMediumGap': borderNumber = 12; break; case 'ThickThinMediumGap': borderNumber = 13; break; case 'ThinThickThinMediumGap': borderNumber = 14; break; case 'ThinThickLargeGap': borderNumber = 15; break; case 'ThickThinLargeGap': borderNumber = 16; break; case 'ThinThickThinLargeGap': borderNumber = 17; break; case 'SingleWavy': //wave. borderNumber = 18; break; case 'DoubleWavy': borderNumber = 19; break; case 'DashSmallGap': borderNumber = 20; break; case 'DashDotStroked': borderNumber = 21; break; case 'Emboss3D': borderNumber = 22; break; case 'Engrave3D': borderNumber = 23; break; case 'Outset': borderNumber = 24; break; case 'Inset': borderNumber = 25; break; } return borderNumber; } private getNumberOfLines(): number { //ToDo: Need to analyze more on this. let value: number = 0; switch (this.lineStyle) { case 'Single': case 'Dot': case 'DashSmallGap': case 'DashLargeGap': case 'DashDot': case 'DashDotDot': value = 1; break; case 'Double': value = 3; break; case 'Triple': value = 5; break; case 'ThinThickSmallGap': value = 3; break; case 'ThickThinSmallGap': value = 3; break; case 'ThinThickThinSmallGap': value = 5; break; case 'ThinThickMediumGap': value = 3; break; case 'ThickThinMediumGap': value = 3; break; case 'ThinThickThinMediumGap': value = 5; break; case 'ThinThickLargeGap': value = 3; break; case 'ThickThinLargeGap': value = 3; break; case 'ThinThickThinLargeGap': value = 5; break; case 'SingleWavy': value = 1; break; case 'DoubleWavy': value = 2; break; case 'DashDotStroked': value = 1; break; case 'Emboss3D': case 'Engrave3D': value = 3; break; case 'Outset': case 'Inset': case 'Thick': value = 1; break; } return value; } public getPrecedence(): number { let value: number = 0; switch (this.lineStyle) { case 'Single': value = 1; break; case 'Thick': value = 2; break; case 'Double': value = 3; break; case 'Dot': value = 4; break; case 'DashLargeGap': //dashed. value = 5; break; case 'DashDot': value = 6; break; case 'DashDotDot': value = 7; break; case 'Triple': value = 8; break; case 'ThinThickSmallGap': value = 9; break; case 'ThickThinSmallGap': value = 10; break; case 'ThinThickThinSmallGap': value = 11; break; case 'ThinThickMediumGap': value = 12; break; case 'ThickThinMediumGap': value = 13; break; case 'ThinThickThinMediumGap': value = 14; break; case 'ThinThickLargeGap': value = 15; break; case 'ThickThinLargeGap': value = 16; break; case 'ThinThickThinLargeGap': value = 17; break; case 'SingleWavy': //wave. value = 18; break; case 'DoubleWavy': value = 19; break; case 'DashSmallGap': value = 20; break; case 'DashDotStroked': value = 21; break; case 'Emboss3D': value = 22; break; case 'Engrave3D': value = 23; break; case 'Outset': value = 24; break; case 'Inset': value = 25; break; } return value; } public hasValue(property: string): boolean { if (!isNullOrUndefined(this.uniqueBorderFormat)) { const propertyType: number = WUniqueFormat.getPropertyType(this.uniqueBorderFormat.uniqueFormatType, property); return this.uniqueBorderFormat.propertiesHash.containsKey(propertyType); } return false; } public cloneFormat(): WBorder { const border: WBorder = new WBorder(undefined); border.color = this.color; border.lineStyle = this.lineStyle; border.lineWidth = this.lineWidth; border.shadow = this.shadow; border.space = this.space; return border; } public destroy(): void { if (!isNullOrUndefined(this.uniqueBorderFormat)) { WBorder.uniqueBorderFormats.remove(this.uniqueBorderFormat); } this.uniqueBorderFormat = undefined; } public copyFormat(border: WBorder): void { if (!isNullOrUndefined(border) && !isNullOrUndefined(border.uniqueBorderFormat)) { if (border.hasValue('color')) { this.color = border.color; } if (border.hasValue('lineStyle')) { this.lineStyle = border.lineStyle; } if (border.hasValue('lineWidth')) { this.lineWidth = border.lineWidth; } if (border.hasValue('shadow')) { this.shadow = border.shadow; } if (border.hasValue('space')) { this.space = border.space; } } } public static clear(): void { this.uniqueBorderFormats.clear(); } }
the_stack
import { Injectable, EventEmitter, Output } from '@angular/core'; import { Link } from './models/link'; import { Node } from './models/node'; import { SubwayMap } from './models/subway-map'; import { Commit } from '../prototypes/commit'; import * as d3 from 'd3'; import { Color } from './models/color'; import { ElectronService } from '../../infrastructure/electron.service'; import { CiIntegrationService } from '../services/ci-integration.service'; @Injectable() export class D3Service { colors = [ '#058ED9', '#880044', '#875053', '#129490', '#E5A823', '#0055A2', '#96C5F7']; currentMap: SubwayMap = null; @Output() mapChange = new EventEmitter(); private ciEnabled = false; constructor( private ci: CiIntegrationService, ) { ci.enabledChanged.subscribe(en => { this.ciEnabled = en; this.getCIStatus(); }); ci.buildsUpdated.subscribe(newBuilds => { if (this.ciEnabled) { Object.keys(newBuilds).map(key => { let b = newBuilds[key]; this.updateCommitStatus(b.commit, b.overall); }); this.mapChange.emit(); } }); } init() { } getCIStatus() { if (this.ciEnabled) { Object.keys(this.ci.buildResults).map(key => { let b = this.ci.buildResults[key]; this.updateCommitStatus(b.commit, b.overall); }); this.mapChange.emit(); } else { this.clearCommitsCIStatus(); } } getSubwayMap(commits: Commit[]) { let _start = 25; let _offset = Node.height; let _infinityY = Node.height * (commits.length + 1); let nodeDict = {}; let nodes = []; let links = []; let treeOffset = 0; let that = this; commits.forEach((c, i) => { let node = new Node(c.sha); // Y offset, just increment; node.y = _start; // X is tricky, do it later node.x = _start; node.commit = c; node.color = Color.parseHex(that.colors[0]); node.secondColor = Color.parseHex(that.colors[0]); nodes.push(node); nodeDict[node.commit.sha] = node; }, this); // edge creation commits.forEach((c) => { if (c.parents.length === 0) { let infinityNode = new Node('infty-' + c.sha); infinityNode.x = nodeDict[c.sha].x; infinityNode.y = _infinityY; let newLink = new Link(nodeDict[c.sha], infinityNode); newLink.color = nodeDict[c.sha].color; links.push(newLink); } else { c.parents.forEach((p) => { if (nodeDict[p]) { let newLink = new Link(nodeDict[c.sha], nodeDict[p]); if (c.parents.length > 1) { newLink.color = nodeDict[p].color; nodeDict[c.sha].secondColor = nodeDict[p].color; newLink.merge = true; } else { newLink.color = nodeDict[c.sha].color; newLink.merge = false; } links.push(newLink); } }); } }); this.currentMap = new SubwayMap(nodes, links, nodeDict); this.updateMapLayout(this.currentMap); this.mapChange.emit(); return this.currentMap; } updateCommits(newCommits: Commit[]) { let links = this.currentMap.links; let nodes = this.currentMap.nodes; let nodeDict = this.currentMap.nodeDict; let _start = 25; let _offset = Node.height; if (this.currentMap) { // remove not exist commits let removed = []; let newKeys = newCommits.map(c => c.sha); let oldKeys = Object.keys(nodeDict); oldKeys.forEach(k => { if (newKeys.indexOf(k) === -1) { removed.push(k); } }); removed.forEach(k => { this.currentMap.nodes.splice(this.currentMap.nodes.indexOf(nodeDict[k]), 1); delete nodeDict[k]; }); // add in new commits in correct place let i = 0; let j = 0; // newCommits will be >= than old nodes now // since we remove all nodes in old that's not in new while (i < newCommits.length || j < nodes.length) { if (j >= nodes.length || nodes[j].commit.sha !== newCommits[i].sha) { // if node is not in already, create new one let node = new Node(newCommits[i].sha); // Y offset, just increment; node.y = _start; // X is tricky, do it later node.x = _start; node.commit = newCommits[i]; node.color = Color.parseHex(this.colors[0]); node.secondColor = Color.parseHex(this.colors[0]); if (j < nodes.length) { nodes.splice(j, 0, node); } else { nodes.splice(nodes.length, 0, node); } nodeDict[node.commit.sha] = node; } j += 1; i += 1; } this.currentMap.nodes.map(n => { n.processed = false; }); this.currentMap.links = []; // edge creation let _infinityY = Node.height * (nodes.length + 1); nodes.forEach((n) => { let c = n.commit; if (c.parents.length === 0) { let infinityNode = new Node('infty-' + c.sha); infinityNode.x = nodeDict[c.sha].x; infinityNode.y = _infinityY; let newLink = new Link(nodeDict[c.sha], infinityNode); newLink.color = nodeDict[c.sha].color; this.currentMap.links.push(newLink); } else { c.parents.forEach((p) => { if (nodeDict[p]) { let newLink = new Link(nodeDict[c.sha], nodeDict[p]); if (c.parents.length > 1) { newLink.color = nodeDict[p].color; nodeDict[c.sha].secondColor = nodeDict[p].color; newLink.merge = true; } else { newLink.color = nodeDict[c.sha].color; newLink.merge = false; } this.currentMap.links.push(newLink); } }); } }); this.updateMapLayout(this.currentMap); this.getCIStatus(); this.mapChange.emit(); return this.currentMap; } } updateMapLayout(map: SubwayMap) { let _start = 25; let _offset = Node.height; let nodes = map.nodes; let nodeDict = map.nodeDict; // New x algorithm, branch lines, closed and open concept // let's see, start from top, start a "branch line" and add that commit, mark as open // a merge commit comes in, add one parent in it's line, add another to "new branch", mark open // a commit is removed from nodeDict if processed // any new commits, add to a existing branch if "it's sha is any of existing's parent", if all fail, put it in new branch line // a branch line can only close if "a commit with only 1 parent and that parent is already in a branch" comes in let branchLines: BranchLine[] = []; function placeNodeInNewOrClosed(node: Node): BranchLine { let addedToBl = null; branchLines.forEach(bl => { if (!node.processed) { // now a bl can be closed if all the commits in there is after this node // let allAfter = bl.nodes.every(bln => nodes.indexOf(bln) > nodes.indexOf(node)); // check if any parent is above this node but that node is after this node // let's see if this works better // let parentAbove = bl.nodes.find(bln => { // if (!bln.commit.parents.length) { // return false; // } else { // return (!bln.commit.parents.every(parent => nodes.indexOf(nodeDict[parent]) > nodes.indexOf(node)) && nodes.indexOf(bln) > nodes.indexOf(node)); // } // }); let lastCross = !bl.nodes[bl.nodes.length - 1].commit.parents.every(parent => { return nodes.indexOf(nodeDict[parent]) > nodes.indexOf(node); }); if (lastCross) { // bl.open = false; } if (!bl.open) { addedToBl = bl; bl.nodes.push(node); bl.open = true; node.processed = true; } } }); if (!addedToBl) { // still can't add, create a new branch branchLines.push({ nodes: [node], open: true }); addedToBl = branchLines[branchLines.length - 1]; node.processed = true; } return addedToBl; } function placeNodeInExisting(node: Node): BranchLine { let addedToBl = null; branchLines.forEach(bl => { if (!node.processed) { if (bl.nodes[bl.nodes.length - 1].commit.parents[0] === node.commit.sha) { // else if a bl's last node is it's parent // it's impossible for anything other than the last one to be the parent // because that whould have been a merge which is processed in special case addedToBl = bl; bl.nodes.push(node); node.processed = true; } } }); return addedToBl; } function processParents(n: Node, bl: BranchLine) { // pecial case for it's parents, always put the first with itself let parent0 = nodeDict[n.commit.parents[0]]; let processGrandparent0 = false; if (parent0 && !parent0.processed) { bl.nodes.push(parent0); if (nodeDict[n.commit.parents[0]].commit.parents.length > 1) { processGrandparent0 = true; } nodeDict[n.commit.parents[0]].processed = true; } // if there's a second parent, try to place that too let parent1 = nodeDict[n.commit.parents[1]]; let newbl; let processGrandparent = false; if (parent1 && !parent1.processed) { if (!placeNodeInExisting(parent1)) { if (parent1.commit.parents.length > 1) { processGrandparent = true; } newbl = placeNodeInNewOrClosed(parent1); } } if (processGrandparent0) { processParents(nodeDict[n.commit.parents[0]], bl); } if (processGrandparent) { processParents(parent1, newbl); } } nodes.forEach((n, i) => { n.y = _start + i * _offset; let currentSha = n.commit.sha; // if this node is unprocessed if (!n.processed) { let addedToBl = null; // see if I can add to an existing branch addedToBl = placeNodeInExisting(n); if (!addedToBl) { addedToBl = placeNodeInNewOrClosed(n); // this method must return a bl } processParents(n, addedToBl); } // check for closed branch line, make it available for adding branchLines.forEach(bl => { if (bl.nodes[bl.nodes.length - 1].commit.parents.indexOf(currentSha) !== -1) { bl.open = false; } }); }); // process all branch lines let that = this; branchLines.forEach((bl, i) => { bl.nodes.forEach(n => { n.x = _start + i * _offset; n.color.setHex(that.colors[i % that.colors.length]); n.x_order = i; }); }); map.width = branchLines.length; } scrollTo(commit: string) { this.currentMap.scrollTo(commit); } updateCommitStatus(commit: string, status: string) { if (this.ciEnabled && this.currentMap) { this.currentMap.updateCommitStatus(commit, status); } } clearCommitsCIStatus() { if (this.currentMap) { this.currentMap.nodes.map(n => { n.commit.ci = ''; }); } } getAuthor(author) { let firstChars = author.split(' ').map(n => n.length > 0 ? n[0].toUpperCase() : ""); let name = ""; firstChars.forEach(f => { if (f > 'A' && f < 'Z' && name.length < 2) { name += f; } }); return name; } private hashCode(str) { // java String#hashCode let hash = 0; for (let i = 0; i < str.length; i++) { // tslint:disable-next-line:no-bitwise hash = str.charCodeAt(i) + (((hash << 4) + hash * 2) >> 2); } return hash; } private intToRGB(i) { // tslint:disable-next-line:no-bitwise let c = (i & 0x00FFFFFF) .toString(16) .toUpperCase(); return "00000".substring(0, 6 - c.length) + c; } getColorByAuthor(email: string) { return `#${this.intToRGB(this.hashCode(email))}`; } } interface BranchLine { nodes: Node[]; open: boolean; }
the_stack
import {VideoTexture} from 'three/src/textures/VideoTexture'; import {TextureLoader} from 'three/src/loaders/TextureLoader'; import {Texture} from 'three/src/textures/Texture'; import {CoreWalker} from '../Walker'; import {BaseNodeType} from '../../engine/nodes/_Base'; import {BaseParamType} from '../../engine/params/_Base'; import {BaseCopNodeClass} from '../../engine/nodes/cop/_Base'; import {TextureContainer} from '../../engine/containers/Texture'; import {Poly} from '../../engine/Poly'; import {ModuleName} from '../../engine/poly/registers/modules/Common'; import {CoreUserAgent} from '../UserAgent'; import {ASSETS_ROOT} from './AssetsUtils'; import {PolyScene} from '../../engine/scene/PolyScene'; import {CoreBaseLoader} from './_Base'; interface VideoSourceTypeByExt { ogg: string; ogv: string; mp4: string; } // interface ImageScriptUrlByExt { // exr: string; // basis: string; // } interface ThreeLoaderByExt { exr: string; basis: string; hdr: string; } enum Extension { JPG = 'jpg', JPEG = 'jpeg', PNG = 'png', EXR = 'exr', BASIS = 'basis', HDR = 'hdr', } export const TEXTURE_IMAGE_EXTENSIONS: Extension[] = [ Extension.JPEG, Extension.JPG, Extension.PNG, Extension.EXR, Extension.BASIS, Extension.HDR, ]; export const TEXTURE_VIDEO_EXTENSIONS: string[] = ['ogg', 'ogv', 'mp4']; interface TextureLoadOptions { tdataType: boolean; dataType: number; } type MaxConcurrentLoadsCountMethod = () => number; type OnTextureLoadedCallback = (url: string, texture: Texture) => void; export class CoreLoaderTexture extends CoreBaseLoader { static PARAM_DEFAULT = `${ASSETS_ROOT}/textures/uv.jpg`; static PARAM_ENV_DEFAULT = `${ASSETS_ROOT}/textures/piz_compressed.exr`; static VIDEO_EXTENSIONS = ['mp4', 'webm', 'ogv']; static VIDEO_SOURCE_TYPE_BY_EXT: VideoSourceTypeByExt = { ogg: 'video/ogg; codecs="theora, vorbis"', ogv: 'video/ogg; codecs="theora, vorbis"', mp4: 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"', }; constructor( _url: string, private _param: BaseParamType, protected _node: BaseNodeType, protected _scene: PolyScene ) { super(_url, _scene, _node); } static _onTextureLoadedCallback: OnTextureLoadedCallback | undefined; static onTextureLoaded(callback: OnTextureLoadedCallback | undefined) { this._onTextureLoadedCallback = callback; } async load_texture_from_url_or_op(options: TextureLoadOptions): Promise<Texture | VideoTexture | null> { let texture: Texture | null = null; let foundNode: BaseNodeType | null = null; if (this._url.substring(0, 3) == 'op:') { const node_path = this._url.substring(3); foundNode = CoreWalker.findNode(this._node, node_path); if (foundNode) { if (foundNode instanceof BaseCopNodeClass) { const container: TextureContainer = await foundNode.compute(); texture = container.texture(); } else { this._node.states.error.set(`found node is not a texture node`); } // this._assign_texture(attrib, texture) } else { this._node.states.error.set(`no node found in path '${node_path}'`); } } else { texture = await this._loadUrl(options); if (texture) { } else { this._node.states.error.set(`could not load texture ${this._url}`); } } // NOTE: if this._param gets its value from an expression like `ch('/CONTROL/photoUrl')` // then found_node will be null, so the graph should not be changed if (foundNode && this._param.graphPredecessors()[0] != foundNode) { this._param.graphDisconnectPredecessors(); this._param.addGraphInput(foundNode); } // this._assign_texture(attrib, texture) return texture; } private async _loadUrl(options: TextureLoadOptions): Promise<Texture> { return new Promise(async (resolve, reject) => { // let resolvedUrl = paramUrl; // const ext = CoreLoaderTexture.get_extension(resolvedUrl); // const blobUrl = Poly.blobs.blobUrl(resolvedUrl); // if (blobUrl) { // resolvedUrl = blobUrl; // } else { // if (resolvedUrl[0] != 'h') { // const assets_root = this._node.scene().assets.root(); // if (assets_root) { // resolvedUrl = `${assets_root}${resolvedUrl}`; // } // } // } const ext = this.extension(); const url = await this._urlToLoad(); if (CoreLoaderTexture.VIDEO_EXTENSIONS.includes(ext)) { const texture: VideoTexture = await this._load_as_video(url); resolve(texture); } else { this.loader_for_ext(ext, options).then(async (loader) => { if (loader) { CoreLoaderTexture.increment_in_progress_loads_count(); await CoreLoaderTexture.wait_for_max_concurrent_loads_queue_freed(); loader.load( url, (texture: Texture) => { CoreLoaderTexture.decrement_in_progress_loads_count(); const callback = CoreLoaderTexture._onTextureLoadedCallback; if (callback) { callback(url, texture); } resolve(texture); }, undefined, (error: any) => { CoreLoaderTexture.decrement_in_progress_loads_count(); Poly.warn('error', error); reject(); } ); } else { reject(); } }); } }); } static module_names(ext: string): ModuleName[] | void { switch (ext) { case Extension.EXR: return [ModuleName.EXRLoader]; case Extension.HDR: return [ModuleName.RGBELoader]; case Extension.BASIS: return [ModuleName.BasisTextureLoader]; } } async loader_for_ext(ext: string, options: TextureLoadOptions) { const ext_lowercase = ext.toLowerCase() as keyof ThreeLoaderByExt; switch (ext_lowercase) { case Extension.EXR: { return await this._exr_loader(options); } case Extension.HDR: { return await this._hdr_loader(options); } case Extension.BASIS: { return await CoreLoaderTexture._basis_loader(this._node); } } return new TextureLoader(this.loadingManager); } private async _exr_loader(options: TextureLoadOptions) { const EXRLoader = await Poly.modulesRegister.module(ModuleName.EXRLoader); if (EXRLoader) { const loader = new EXRLoader(this.loadingManager); if (options.tdataType) { loader.setDataType(options.dataType); } return loader; } } private async _hdr_loader(options: TextureLoadOptions) { const RGBELoader = await Poly.modulesRegister.module(ModuleName.RGBELoader); if (RGBELoader) { const loader = new RGBELoader(this.loadingManager); if (options.tdataType) { loader.setDataType(options.dataType); } return loader; } } private static async _basis_loader(node: BaseNodeType) { const BasisTextureLoader = await Poly.modulesRegister.module(ModuleName.BasisTextureLoader); if (BasisTextureLoader) { const BASISLoader = new BasisTextureLoader(this.loadingManager); const root = Poly.libs.root(); const BASISPath = Poly.libs.BASISPath(); if (root || BASISPath) { const decoder_path = `${root || ''}${BASISPath || ''}/`; if (node) { const files = ['basis_transcoder.js', 'basis_transcoder.wasm']; await this._loadMultipleBlobGlobal({ files: files.map((file) => { return { storedUrl: `${BASISPath}/${file}`, fullUrl: `${decoder_path}${file}`, }; }), node, error: 'failed to load basis libraries. Make sure to install them to load .basis files', }); } BASISLoader.setTranscoderPath(decoder_path); } else { (BASISLoader as any).setTranscoderPath(undefined); } const renderer = await Poly.renderersController.waitForRenderer(); if (renderer) { BASISLoader.detectSupport(renderer); } else { Poly.warn('texture loader found no renderer for basis texture loader'); } return BASISLoader; } } _load_as_video(url: string): Promise<VideoTexture> { return new Promise((resolve, reject) => { const video = document.createElement('video'); video.setAttribute('crossOrigin', 'anonymous'); video.setAttribute('autoplay', `${true}`); // to ensure it loads video.setAttribute('loop', `${true}`); // wait for onloadedmetadata to ensure that we have a duration video.onloadedmetadata = function () { video.pause(); const texture = new VideoTexture(video); resolve(texture); }; // video.setAttribute('controls', true) // video.style="display:none" // add source as is const original_source = document.createElement('source'); const original_ext = CoreBaseLoader.extension(url) as keyof VideoSourceTypeByExt; let type: string = CoreLoaderTexture.VIDEO_SOURCE_TYPE_BY_EXT[original_ext]; type = type || CoreLoaderTexture._default_video_source_type(url); original_source.setAttribute('type', type); original_source.setAttribute('src', url); video.appendChild(original_source); // add secondary source, either mp4 or ogv depending on the first url let secondary_url = url; if (original_ext == 'mp4') { // add ogv secondary_url = CoreLoaderTexture.replaceExtension(url, 'ogv'); } else { // add mp4 secondary_url = CoreLoaderTexture.replaceExtension(url, 'mp4'); } const secondary_source = document.createElement('source'); const secondary_ext = CoreBaseLoader.extension(secondary_url) as keyof VideoSourceTypeByExt; type = CoreLoaderTexture.VIDEO_SOURCE_TYPE_BY_EXT[secondary_ext]; type = type || CoreLoaderTexture._default_video_source_type(url); secondary_source.setAttribute('type', type); secondary_source.setAttribute('src', url); video.appendChild(secondary_source); }); } static _default_video_source_type(url: string) { const ext = CoreBaseLoader.extension(url); return `video/${ext}`; } static pixel_data(texture: Texture) { const img = texture.image; const canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; const context = canvas.getContext('2d'); if (context) { context.drawImage(img, 0, 0, img.width, img.height); return context.getImageData(0, 0, img.width, img.height); } } // TODO: typescript: check what type the pixel_data is // static pixel_data_to_attribute(pixel_data: Pixel, geometry: BufferGeometry, attrib_name_with_component:string, convert_method: (x:number, y:number, z:number, w:number)=>number) { // const {data} = pixel_data; // const core_geometry = new CoreGeometry(geometry); // // TODO: add error if no uvs // const values = []; // const points = core_geometry.points(); // for (let point of points) { // const uv = point.attribValue('uv'); // const x = Math.floor((pixel_data.width - 1) * uv.x); // const y = Math.floor((pixel_data.height - 1) * (1 - uv.y)); // const i = y * pixel_data.width + x; // // const val = data[4*i] / 255.0; // if (convert_method) { // const val = convert_method(data[4 * i + 0], data[4 * i + 1], data[4 * i + 2], data[4 * i + 3]); // values.push(val); // } else { // values.push([data[4 * i + 0], data[4 * i + 1], data[4 * i + 2]]); // } // } // const attrib_name_elements = attrib_name_with_component.split('.'); // let attrib_name = attrib_name_elements[0]; // let component_offset = null; // if (attrib_name_elements.length > 1) { // const component = attrib_name_elements[1] as keyof Vector4Like // component_offset = {x: 0, y: 1, z: 2, w: 3}[component]; // } // let attrib = geometry.attributes[attrib_name]; // if (attrib) { // const array = attrib.array; // let index = 0; // let is_array = null; // for (let value of values) { // if (is_array || CoreType.isArray(value)) { // is_array = true; // let component_index = 0; // for (let value_c of value) { // array[attrib.itemSize * index + component_index] = value_c; // component_index++; // } // } else { // array[attrib.itemSize * index + component_offset] = value; // } // index++; // } // } else { // attrib = geometry.setAttribute(attrib_name, new Float32BufferAttribute(values, 1)); // } // attrib.needsUpdate = true; // } static replaceExtension(url: string, new_extension: string) { const elements = url.split('?'); const url_without_params = elements[0]; const url_elements = url_without_params.split('.'); url_elements.pop(); url_elements.push(new_extension); return [url_elements.join('.'), elements[1]].join('?'); } // // // CONCURRENT LOADS // // private static MAX_CONCURRENT_LOADS_COUNT: number = CoreLoaderTexture._init_max_concurrent_loads_count(); private static CONCURRENT_LOADS_DELAY: number = CoreLoaderTexture._init_concurrent_loads_delay(); private static in_progress_loads_count: number = 0; private static _queue: Array<() => void> = []; private static _maxConcurrentLoadsCountMethod: MaxConcurrentLoadsCountMethod | undefined; public static setMaxConcurrentLoadsCount(method: MaxConcurrentLoadsCountMethod | undefined) { this._maxConcurrentLoadsCountMethod = method; } private static _init_max_concurrent_loads_count(): number { if (this._maxConcurrentLoadsCountMethod) { return this._maxConcurrentLoadsCountMethod(); } return CoreUserAgent.isChrome() ? 10 : 4; // const parser = new UAParser(); // const name = parser.getBrowser().name; // // limit to 4 for non chrome, // // as firefox was seen hanging trying to load multiple glb files // // limit to 1 for safari, // if (name) { // const loads_count_by_browser: PolyDictionary<number> = { // Chrome: 10, // Firefox: 4, // }; // const loads_count = loads_count_by_browser[name]; // if (loads_count != null) { // return loads_count; // } // } // return 1; } private static _init_concurrent_loads_delay(): number { return CoreUserAgent.isChrome() ? 0 : 10; // const parser = new UAParser(); // const name = parser.getBrowser().name; // // add a delay for browsers other than Chrome and Firefox // if (name) { // const delay_by_browser: PolyDictionary<number> = { // Chrome: 0, // Firefox: 10, // }; // const delay = delay_by_browser[name]; // if (delay != null) { // return delay; // } // } // return 100; } // public static override_max_concurrent_loads_count(count: number) { // this.MAX_CONCURRENT_LOADS_COUNT = count; // } private static increment_in_progress_loads_count() { this.in_progress_loads_count++; } private static decrement_in_progress_loads_count() { this.in_progress_loads_count--; const queued_resolve = this._queue.pop(); if (queued_resolve) { const delay = this.CONCURRENT_LOADS_DELAY; setTimeout(() => { queued_resolve(); }, delay); } } private static async wait_for_max_concurrent_loads_queue_freed(): Promise<void> { if (this.in_progress_loads_count <= this.MAX_CONCURRENT_LOADS_COUNT) { return; } else { return new Promise((resolve) => { this._queue.push(resolve); }); } } }
the_stack
import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpEvent } from '@angular/common/http'; import { Inject, Injectable, InjectionToken, Optional } from '@angular/core'; import { APIClientInterface } from './api-client.interface'; import { Observable } from 'rxjs';import { DefaultHttpOptions, HttpOptions } from './types'; import * as models from './models'; export const USE_DOMAIN = new InjectionToken<string>('APIClient_USE_DOMAIN'); export const USE_HTTP_OPTIONS = new InjectionToken<HttpOptions>('APIClient_USE_HTTP_OPTIONS'); type APIHttpOptions = HttpOptions & { headers: HttpHeaders; params: HttpParams; }; @Injectable() export class APIClient implements APIClientInterface { readonly options: APIHttpOptions; readonly domain: string = `https://firestore.googleapis.com/v1beta1`; constructor( private readonly http: HttpClient, @Optional() @Inject(USE_DOMAIN) domain?: string, @Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions, ) { if (domain != null) { this.domain = domain; } this.options = { headers: new HttpHeaders(options && options.headers ? options.headers : {}), params: new HttpParams(options && options.params ? options.params : {}), ...(options && options.reportProgress ? { reportProgress: options.reportProgress } : {}), ...(options && options.withCredentials ? { withCredentials: options.withCredentials } : {}) }; } /** * Gets multiple documents. * * * Documents returned by this method are not guaranteed to be returned in the * same order that they were requested. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsBatchGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBatchGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.BatchGetDocumentsResponse>; firestoreProjectsDatabasesDocumentsBatchGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBatchGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.BatchGetDocumentsResponse>>; firestoreProjectsDatabasesDocumentsBatchGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBatchGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.BatchGetDocumentsResponse>>; firestoreProjectsDatabasesDocumentsBatchGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBatchGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.BatchGetDocumentsResponse | HttpResponse<models.BatchGetDocumentsResponse> | HttpEvent<models.BatchGetDocumentsResponse>> { const path = `/${args.database}/documents:batchGet`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } return this.http.post<models.BatchGetDocumentsResponse>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Starts a new transaction. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsBeginTransaction( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBeginTransactionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.BeginTransactionResponse>; firestoreProjectsDatabasesDocumentsBeginTransaction( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBeginTransactionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.BeginTransactionResponse>>; firestoreProjectsDatabasesDocumentsBeginTransaction( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBeginTransactionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.BeginTransactionResponse>>; firestoreProjectsDatabasesDocumentsBeginTransaction( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBeginTransactionParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.BeginTransactionResponse | HttpResponse<models.BeginTransactionResponse> | HttpEvent<models.BeginTransactionResponse>> { const path = `/${args.database}/documents:beginTransaction`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } return this.http.post<models.BeginTransactionResponse>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Commits a transaction, while optionally updating documents. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsCommit( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.CommitResponse>; firestoreProjectsDatabasesDocumentsCommit( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.CommitResponse>>; firestoreProjectsDatabasesDocumentsCommit( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.CommitResponse>>; firestoreProjectsDatabasesDocumentsCommit( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.CommitResponse | HttpResponse<models.CommitResponse> | HttpEvent<models.CommitResponse>> { const path = `/${args.database}/documents:commit`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } return this.http.post<models.CommitResponse>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Listens to changes. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsListen( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListenParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ListenResponse>; firestoreProjectsDatabasesDocumentsListen( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListenParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ListenResponse>>; firestoreProjectsDatabasesDocumentsListen( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListenParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ListenResponse>>; firestoreProjectsDatabasesDocumentsListen( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListenParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.ListenResponse | HttpResponse<models.ListenResponse> | HttpEvent<models.ListenResponse>> { const path = `/${args.database}/documents:listen`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } return this.http.post<models.ListenResponse>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Rolls back a transaction. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsRollback( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRollbackParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Empty>; firestoreProjectsDatabasesDocumentsRollback( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRollbackParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Empty>>; firestoreProjectsDatabasesDocumentsRollback( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRollbackParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Empty>>; firestoreProjectsDatabasesDocumentsRollback( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRollbackParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Empty | HttpResponse<models.Empty> | HttpEvent<models.Empty>> { const path = `/${args.database}/documents:rollback`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } return this.http.post<models.Empty>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Streams batches of document updates and deletes, in order. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsWrite( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsWriteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.WriteResponse>; firestoreProjectsDatabasesDocumentsWrite( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsWriteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.WriteResponse>>; firestoreProjectsDatabasesDocumentsWrite( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsWriteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.WriteResponse>>; firestoreProjectsDatabasesDocumentsWrite( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsWriteParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.WriteResponse | HttpResponse<models.WriteResponse> | HttpEvent<models.WriteResponse>> { const path = `/${args.database}/documents:write`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } return this.http.post<models.WriteResponse>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Deletes an index. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesIndexesDelete( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesDeleteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Empty>; firestoreProjectsDatabasesIndexesDelete( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesDeleteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Empty>>; firestoreProjectsDatabasesIndexesDelete( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesDeleteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Empty>>; firestoreProjectsDatabasesIndexesDelete( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesDeleteParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Empty | HttpResponse<models.Empty> | HttpEvent<models.Empty>> { const path = `/${args.name}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } if ('currentDocumentExists' in args) { options.params = options.params.set('currentDocument.exists', String(args.currentDocumentExists)); } if ('currentDocumentUpdateTime' in args) { options.params = options.params.set('currentDocument.updateTime', String(args.currentDocumentUpdateTime)); } return this.http.delete<models.Empty>(`${this.domain}${path}`, options); } /** * Gets an index. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesIndexesGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Index>; firestoreProjectsDatabasesIndexesGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Index>>; firestoreProjectsDatabasesIndexesGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Index>>; firestoreProjectsDatabasesIndexesGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Index | HttpResponse<models.Index> | HttpEvent<models.Index>> { const path = `/${args.name}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } if ('maskFieldPaths' in args) { options.params = options.params.set('mask.fieldPaths', String(args.maskFieldPaths)); } if ('readTime' in args) { options.params = options.params.set('readTime', String(args.readTime)); } if ('transaction' in args) { options.params = options.params.set('transaction', String(args.transaction)); } return this.http.get<models.Index>(`${this.domain}${path}`, options); } /** * Updates or inserts a document. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsPatch( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsPatchParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Document>; firestoreProjectsDatabasesDocumentsPatch( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsPatchParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Document>>; firestoreProjectsDatabasesDocumentsPatch( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsPatchParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Document>>; firestoreProjectsDatabasesDocumentsPatch( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsPatchParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Document | HttpResponse<models.Document> | HttpEvent<models.Document>> { const path = `/${args.name}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } if ('currentDocumentExists' in args) { options.params = options.params.set('currentDocument.exists', String(args.currentDocumentExists)); } if ('currentDocumentUpdateTime' in args) { options.params = options.params.set('currentDocument.updateTime', String(args.currentDocumentUpdateTime)); } if ('maskFieldPaths' in args) { options.params = options.params.set('mask.fieldPaths', String(args.maskFieldPaths)); } if ('updateMaskFieldPaths' in args) { options.params = options.params.set('updateMask.fieldPaths', String(args.updateMaskFieldPaths)); } return this.http.patch<models.Document>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Lists the indexes that match the specified filters. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesIndexesList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ListIndexesResponse>; firestoreProjectsDatabasesIndexesList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ListIndexesResponse>>; firestoreProjectsDatabasesIndexesList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ListIndexesResponse>>; firestoreProjectsDatabasesIndexesList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.ListIndexesResponse | HttpResponse<models.ListIndexesResponse> | HttpEvent<models.ListIndexesResponse>> { const path = `/${args.parent}/indexes`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } if ('filter' in args) { options.params = options.params.set('filter', String(args.filter)); } if ('pageSize' in args) { options.params = options.params.set('pageSize', String(args.pageSize)); } if ('pageToken' in args) { options.params = options.params.set('pageToken', String(args.pageToken)); } return this.http.get<models.ListIndexesResponse>(`${this.domain}${path}`, options); } /** * Creates the specified index. * A newly created index's initial state is `CREATING`. On completion of the * returned google.longrunning.Operation, the state will be `READY`. * If the index already exists, the call will return an `ALREADY_EXISTS` * status. * * * During creation, the process could result in an error, in which case the * index will move to the `ERROR` state. The process can be recovered by * fixing the data that caused the error, removing the index with * delete, then re-creating the index with * create. * * * Indexes with a single field cannot be created. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesIndexesCreate( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesCreateParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Operation>; firestoreProjectsDatabasesIndexesCreate( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesCreateParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Operation>>; firestoreProjectsDatabasesIndexesCreate( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesCreateParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Operation>>; firestoreProjectsDatabasesIndexesCreate( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesCreateParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Operation | HttpResponse<models.Operation> | HttpEvent<models.Operation>> { const path = `/${args.parent}/indexes`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } return this.http.post<models.Operation>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Lists documents. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ListDocumentsResponse>; firestoreProjectsDatabasesDocumentsList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ListDocumentsResponse>>; firestoreProjectsDatabasesDocumentsList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ListDocumentsResponse>>; firestoreProjectsDatabasesDocumentsList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.ListDocumentsResponse | HttpResponse<models.ListDocumentsResponse> | HttpEvent<models.ListDocumentsResponse>> { const path = `/${args.parent}/${args.collectionId}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } if ('maskFieldPaths' in args) { options.params = options.params.set('mask.fieldPaths', String(args.maskFieldPaths)); } if ('orderBy' in args) { options.params = options.params.set('orderBy', String(args.orderBy)); } if ('pageSize' in args) { options.params = options.params.set('pageSize', String(args.pageSize)); } if ('pageToken' in args) { options.params = options.params.set('pageToken', String(args.pageToken)); } if ('readTime' in args) { options.params = options.params.set('readTime', String(args.readTime)); } if ('showMissing' in args) { options.params = options.params.set('showMissing', String(args.showMissing)); } if ('transaction' in args) { options.params = options.params.set('transaction', String(args.transaction)); } return this.http.get<models.ListDocumentsResponse>(`${this.domain}${path}`, options); } /** * Creates a new document. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsCreateDocument( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCreateDocumentParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Document>; firestoreProjectsDatabasesDocumentsCreateDocument( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCreateDocumentParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Document>>; firestoreProjectsDatabasesDocumentsCreateDocument( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCreateDocumentParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Document>>; firestoreProjectsDatabasesDocumentsCreateDocument( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCreateDocumentParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Document | HttpResponse<models.Document> | HttpEvent<models.Document>> { const path = `/${args.parent}/${args.collectionId}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } if ('documentId' in args) { options.params = options.params.set('documentId', String(args.documentId)); } if ('maskFieldPaths' in args) { options.params = options.params.set('mask.fieldPaths', String(args.maskFieldPaths)); } return this.http.post<models.Document>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Lists all the collection IDs underneath a document. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsListCollectionIds( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListCollectionIdsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ListCollectionIdsResponse>; firestoreProjectsDatabasesDocumentsListCollectionIds( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListCollectionIdsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ListCollectionIdsResponse>>; firestoreProjectsDatabasesDocumentsListCollectionIds( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListCollectionIdsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ListCollectionIdsResponse>>; firestoreProjectsDatabasesDocumentsListCollectionIds( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListCollectionIdsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.ListCollectionIdsResponse | HttpResponse<models.ListCollectionIdsResponse> | HttpEvent<models.ListCollectionIdsResponse>> { const path = `/${args.parent}:listCollectionIds`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } return this.http.post<models.ListCollectionIdsResponse>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Runs a query. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsRunQuery( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRunQueryParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.RunQueryResponse>; firestoreProjectsDatabasesDocumentsRunQuery( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRunQueryParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.RunQueryResponse>>; firestoreProjectsDatabasesDocumentsRunQuery( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRunQueryParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.RunQueryResponse>>; firestoreProjectsDatabasesDocumentsRunQuery( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRunQueryParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.RunQueryResponse | HttpResponse<models.RunQueryResponse> | HttpEvent<models.RunQueryResponse>> { const path = `/${args.parent}:runQuery`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('$Xgafv' in args) { options.params = options.params.set('$.xgafv', String(args.$Xgafv)); } if ('accessToken' in args) { options.params = options.params.set('access_token', String(args.accessToken)); } if ('alt' in args) { options.params = options.params.set('alt', String(args.alt)); } if ('bearerToken' in args) { options.params = options.params.set('bearer_token', String(args.bearerToken)); } if ('callback' in args) { options.params = options.params.set('callback', String(args.callback)); } if ('fields' in args) { options.params = options.params.set('fields', String(args.fields)); } if ('key' in args) { options.params = options.params.set('key', String(args.key)); } if ('oauthToken' in args) { options.params = options.params.set('oauth_token', String(args.oauthToken)); } if ('pp' in args) { options.params = options.params.set('pp', String(args.pp)); } if ('prettyPrint' in args) { options.params = options.params.set('prettyPrint', String(args.prettyPrint)); } if ('quotaUser' in args) { options.params = options.params.set('quotaUser', String(args.quotaUser)); } if ('uploadType' in args) { options.params = options.params.set('uploadType', String(args.uploadType)); } if ('uploadProtocol' in args) { options.params = options.params.set('upload_protocol', String(args.uploadProtocol)); } return this.http.post<models.RunQueryResponse>(`${this.domain}${path}`, JSON.stringify(args.body), options); } }
the_stack
import { addDisposer, cast, resolveIdentifier, getSnapshot, types, SnapshotIn, Instance, } from 'mobx-state-tree' import { autorun } from 'mobx' import assemblyManagerFactory, { assemblyConfigSchemas as AssemblyConfigSchemasFactory, } from '@jbrowse/core/assemblyManager' import PluginManager from '@jbrowse/core/PluginManager' import RpcManager from '@jbrowse/core/rpc/RpcManager' import { MenuItem } from '@jbrowse/core/ui' import TextSearchManager from '@jbrowse/core/TextSearch/TextSearchManager' import { AnyConfigurationSchemaType } from '@jbrowse/core/configuration/configurationSchema' import { UriLocation } from '@jbrowse/core/util/types' import { ipcRenderer } from 'electron' // icons import OpenIcon from '@material-ui/icons/FolderOpen' import ExtensionIcon from '@material-ui/icons/Extension' import AppsIcon from '@material-ui/icons/Apps' import StorageIcon from '@material-ui/icons/Storage' import MeetingRoomIcon from '@material-ui/icons/MeetingRoom' import { Save, SaveAs, DNA, Cable } from '@jbrowse/core/ui/Icons' // locals import sessionModelFactory from './sessionModelFactory' import JBrowseDesktop from './jbrowseModel' import OpenSequenceDialog from './OpenSequenceDialog' // @ts-ignore import RenderWorker from './rpc.worker' function getSaveSession(model: RootModel) { return { ...getSnapshot(model.jbrowse), defaultSession: model.session ? getSnapshot(model.session) : {}, } } interface Menu { label: string menuItems: MenuItem[] } export default function rootModelFactory(pluginManager: PluginManager) { const { assemblyConfigSchemas, dispatcher } = AssemblyConfigSchemasFactory(pluginManager) const assemblyConfigSchemasType = types.union( { dispatcher }, ...assemblyConfigSchemas, ) const Session = sessionModelFactory(pluginManager, assemblyConfigSchemasType) const assemblyManagerType = assemblyManagerFactory( assemblyConfigSchemasType, pluginManager, ) return types .model('Root', { jbrowse: JBrowseDesktop( pluginManager, Session, assemblyConfigSchemasType as AnyConfigurationSchemaType, ), session: types.maybe(Session), assemblyManager: assemblyManagerType, savedSessionNames: types.maybe(types.array(types.string)), version: types.maybe(types.string), internetAccounts: types.array( pluginManager.pluggableMstType('internet account', 'stateModel'), ), isAssemblyEditing: false, sessionPath: types.optional(types.string, ''), }) .volatile(() => ({ error: undefined as unknown, textSearchManager: new TextSearchManager(pluginManager), openNewSessionCallback: async (path: string) => { console.error('openNewSessionCallback unimplemented') }, })) .actions(self => ({ async saveSession(val: unknown) { if (self.sessionPath) { await ipcRenderer.invoke('saveSession', self.sessionPath, val) } }, setOpenNewSessionCallback(cb: (arg: string) => Promise<void>) { self.openNewSessionCallback = cb }, setSavedSessionNames(sessionNames: string[]) { self.savedSessionNames = cast(sessionNames) }, setSessionPath(path: string) { self.sessionPath = path }, setSession(sessionSnapshot?: SnapshotIn<typeof Session>) { self.session = cast(sessionSnapshot) }, setError(error: unknown) { self.error = error }, setDefaultSession() { this.setSession(self.jbrowse.defaultSession) }, setAssemblyEditing(flag: boolean) { self.isAssemblyEditing = flag }, async renameCurrentSession(newName: string) { if (self.session) { this.setSession({ ...getSnapshot(self.session), name: newName }) } }, duplicateCurrentSession() { if (self.session) { const snapshot = JSON.parse(JSON.stringify(getSnapshot(self.session))) let newSnapshotName = `${self.session.name} (copy)` if (self.jbrowse.savedSessionNames.includes(newSnapshotName)) { let newSnapshotCopyNumber = 2 do { newSnapshotName = `${self.session.name} (copy ${newSnapshotCopyNumber})` newSnapshotCopyNumber += 1 } while (self.jbrowse.savedSessionNames.includes(newSnapshotName)) } snapshot.name = newSnapshotName this.setSession(snapshot) } }, initializeInternetAccount( internetAccountId: string, initialSnapshot = {}, ) { const internetAccountConfigSchema = pluginManager.pluggableConfigSchemaType('internet account') const configuration = resolveIdentifier( internetAccountConfigSchema, self, internetAccountId, ) const internetAccountType = pluginManager.getInternetAccountType( configuration.type, ) if (!internetAccountType) { throw new Error(`unknown internet account type ${configuration.type}`) } const internetAccount = internetAccountType.stateModel.create({ ...initialSnapshot, type: configuration.type, configuration, }) self.internetAccounts.push(internetAccount) return internetAccount }, createEphemeralInternetAccount( internetAccountId: string, initialSnapshot = {}, location: UriLocation, ) { let hostUri try { hostUri = new URL(location.uri).origin } catch (e) { // ignore } // id of a custom new internaccount is `${type}-${name}` const internetAccountSplit = internetAccountId.split('-') const configuration = { type: internetAccountSplit[0], internetAccountId: internetAccountId, name: internetAccountSplit.slice(1).join('-'), description: '', domains: [hostUri], } const internetAccountType = pluginManager.getInternetAccountType( configuration.type, ) const internetAccount = internetAccountType.stateModel.create({ ...initialSnapshot, type: configuration.type, configuration, }) self.internetAccounts.push(internetAccount) return internetAccount }, findAppropriateInternetAccount(location: UriLocation) { // find the existing account selected from menu const selectedId = location.internetAccountId if (selectedId) { const selectedAccount = self.internetAccounts.find(account => { return account.internetAccountId === selectedId }) if (selectedAccount) { return selectedAccount } } // if no existing account or not found, try to find working account for (const account of self.internetAccounts) { const handleResult = account.handlesLocation(location) if (handleResult) { return account } } // if still no existing account, create ephemeral config to use return selectedId ? this.createEphemeralInternetAccount(selectedId, {}, location) : null }, afterCreate() { addDisposer( self, autorun(() => { self.jbrowse.internetAccounts.forEach(account => { this.initializeInternetAccount(account.internetAccountId) }) }), ) }, })) .volatile(self => ({ history: {}, menus: [ { label: 'File', menuItems: [ { label: 'Open', icon: OpenIcon, onClick: async () => { try { const path = await ipcRenderer.invoke('promptOpenFile') if (path) { await self.openNewSessionCallback(path) } } catch (e) { console.error(e) self.session?.notify(`${e}`, 'error') } }, }, { label: 'Save', icon: Save, onClick: async () => { if (self.session) { try { await self.saveSession(getSaveSession(self as RootModel)) } catch (e) { console.error(e) self.session?.notify(`${e}`, 'error') } } }, }, { label: 'Save as...', icon: SaveAs, onClick: async () => { try { const saveAsPath = await ipcRenderer.invoke( 'promptSessionSaveAs', ) self.setSessionPath(saveAsPath) await self.saveSession(getSaveSession(self as RootModel)) } catch (e) { console.error(e) self.session?.notify(`${e}`, 'error') } }, }, { type: 'divider', }, { label: 'Open assembly...', icon: DNA, onClick: () => { if (self.session) { self.session.queueDialog(doneCallback => [ OpenSequenceDialog, { model: self, onClose: doneCallback }, ]) } }, }, { label: 'Open track...', icon: StorageIcon, // eslint-disable-next-line @typescript-eslint/no-explicit-any onClick: (session: any) => { if (session.views.length === 0) { session.notify('Please open a view to add a track first') } else if (session.views.length >= 1) { const widget = session.addWidget( 'AddTrackWidget', 'addTrackWidget', { view: session.views[0].id }, ) session.showWidget(widget) if (session.views.length > 1) { session.notify( `This will add a track to the first view. Note: if you want to open a track in a specific view open the track selector for that view and use the add track (plus icon) in the bottom right`, ) } } }, }, { label: 'Open connection...', icon: Cable, onClick: () => { if (self.session) { const widget = self.session.addWidget( 'AddConnectionWidget', 'addConnectionWidget', ) self.session.showWidget(widget) } }, }, { type: 'divider', }, { label: 'Return to start screen', icon: AppsIcon, onClick: () => { self.setSession(undefined) }, }, { label: 'Exit', icon: MeetingRoomIcon, onClick: () => { ipcRenderer.invoke('quit') }, }, ], }, { label: 'Add', menuItems: [], }, { label: 'Tools', menuItems: [ { label: 'Plugin store', icon: ExtensionIcon, onClick: () => { if (self.session) { const widget = self.session.addWidget( 'PluginStoreWidget', 'pluginStoreWidget', ) self.session.showWidget(widget) } }, }, ], }, ] as Menu[], rpcManager: new RpcManager( pluginManager, self.jbrowse.configuration.rpc, { WebWorkerRpcDriver: { WorkerClass: RenderWorker }, MainThreadRpcDriver: {}, }, ), adminMode: true, })) .actions(self => ({ activateSession(sessionSnapshot: SnapshotIn<typeof Session>) { self.setSession(sessionSnapshot) }, // eslint-disable-next-line @typescript-eslint/no-explicit-any setHistory(history: any) { self.history = history }, setMenus(newMenus: Menu[]) { self.menus = newMenus }, async setPluginsUpdated() { if (self.session) { await self.saveSession(getSaveSession(self as RootModel)) } await self.openNewSessionCallback(self.sessionPath) }, /** * Add a top-level menu * @param menuName - Name of the menu to insert. * @returns The new length of the top-level menus array */ appendMenu(menuName: string) { return self.menus.push({ label: menuName, menuItems: [] }) }, /** * Insert a top-level menu * @param menuName - Name of the menu to insert. * @param position - Position to insert menu. If negative, counts from th * end, e.g. `insertMenu('My Menu', -1)` will insert the menu as the * second-to-last one. * @returns The new length of the top-level menus array */ insertMenu(menuName: string, position: number) { const insertPosition = position < 0 ? self.menus.length + position : position self.menus.splice(insertPosition, 0, { label: menuName, menuItems: [] }) return self.menus.length }, /** * Add a menu item to a top-level menu * @param menuName - Name of the top-level menu to append to. * @param menuItem - Menu item to append. * @returns The new length of the menu */ appendToMenu(menuName: string, menuItem: MenuItem) { const menu = self.menus.find(m => m.label === menuName) if (!menu) { self.menus.push({ label: menuName, menuItems: [menuItem] }) return 1 } return menu.menuItems.push(menuItem) }, /** * Insert a menu item into a top-level menu * @param menuName - Name of the top-level menu to insert into * @param menuItem - Menu item to insert * @param position - Position to insert menu item. If negative, counts * from the end, e.g. `insertMenu('My Menu', -1)` will insert the menu as * the second-to-last one. * @returns The new length of the menu */ insertInMenu(menuName: string, menuItem: MenuItem, position: number) { const menu = self.menus.find(m => m.label === menuName) if (!menu) { self.menus.push({ label: menuName, menuItems: [menuItem] }) return 1 } const insertPosition = position < 0 ? menu.menuItems.length + position : position menu.menuItems.splice(insertPosition, 0, menuItem) return menu.menuItems.length }, /** * Add a menu item to a sub-menu * @param menuPath - Path to the sub-menu to add to, starting with the * top-level menu (e.g. `['File', 'Insert']`). * @param menuItem - Menu item to append. * @returns The new length of the sub-menu */ appendToSubMenu(menuPath: string[], menuItem: MenuItem) { let topMenu = self.menus.find(m => m.label === menuPath[0]) if (!topMenu) { const idx = this.appendMenu(menuPath[0]) topMenu = self.menus[idx - 1] } let { menuItems: subMenu } = topMenu const pathSoFar = [menuPath[0]] menuPath.slice(1).forEach(menuName => { pathSoFar.push(menuName) let sm = subMenu.find(mi => 'label' in mi && mi.label === menuName) if (!sm) { const idx = subMenu.push({ label: menuName, subMenu: [] }) sm = subMenu[idx - 1] } if (!('subMenu' in sm)) { throw new Error( `"${menuName}" in path "${pathSoFar}" is not a subMenu`, ) } subMenu = sm.subMenu }) return subMenu.push(menuItem) }, /** * Insert a menu item into a sub-menu * @param menuPath - Path to the sub-menu to add to, starting with the * top-level menu (e.g. `['File', 'Insert']`). * @param menuItem - Menu item to insert. * @param position - Position to insert menu item. If negative, counts * from the end, e.g. `insertMenu('My Menu', -1)` will insert the menu as * the second-to-last one. * @returns The new length of the sub-menu */ insertInSubMenu( menuPath: string[], menuItem: MenuItem, position: number, ) { let topMenu = self.menus.find(m => m.label === menuPath[0]) if (!topMenu) { const idx = this.appendMenu(menuPath[0]) topMenu = self.menus[idx - 1] } let { menuItems: subMenu } = topMenu const pathSoFar = [menuPath[0]] menuPath.slice(1).forEach(menuName => { pathSoFar.push(menuName) let sm = subMenu.find(mi => 'label' in mi && mi.label === menuName) if (!sm) { const idx = subMenu.push({ label: menuName, subMenu: [] }) sm = subMenu[idx - 1] } if (!('subMenu' in sm)) { throw new Error( `"${menuName}" in path "${pathSoFar}" is not a subMenu`, ) } subMenu = sm.subMenu }) subMenu.splice(position, 0, menuItem) return subMenu.length }, afterCreate() { addDisposer( self, autorun( async () => { if (self.session) { try { await self.saveSession(getSaveSession(self as RootModel)) } catch (e) { console.error(e) } } }, { delay: 1000 }, ), ) }, })) } export type RootModelType = ReturnType<typeof rootModelFactory> export type RootModel = Instance<RootModelType>
the_stack
import { TestBed, async } from '@angular/core/testing'; import { ChangeDetectorRef } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; // APP import { RenderPipe } from './Render'; import { NovoLabelService } from '../../services/novo-label-service'; // TODO fix specs xdescribe('Render', () => { let fixture: any; let pipe; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [RenderPipe], providers: [{ provide: NovoLabelService, useClass: NovoLabelService }, ChangeDetectorRef, DomSanitizer], }).compileComponents(); fixture = TestBed.createComponent(RenderPipe); pipe = fixture.debugElement.componentInstance; })); it('should initialize with its defaults.', () => { expect(pipe).toBeDefined(); expect(pipe.onLangChange).toBeDefined(); }); describe('Function: equals(objectOne, objectTwo)', () => { let a: any; beforeEach(() => { a = { id: 1, sub: { subSub: { id: 1, }, }, }; }); it('should return true when two objects are identical.', () => { expect(pipe.equals).toBeDefined(); const b: any = a; expect(pipe.equals(a, b)).toBeTruthy(); }); it('should return false when two objects are not identical.', () => { const b: any = { id: 1, sub: { subSub: { id: 2, }, }, }; expect(pipe.equals).toBeDefined(); expect(pipe.equals(a, b)).toBeFalsy(); }); it('should return false when either object is null.', () => { expect(pipe.equals).toBeDefined(); expect(pipe.equals(a, null)).toBeFalsy(); }); it('should return true when both objects are NaN.', () => { expect(pipe.equals(NaN, NaN)).toBeTruthy(); }); it('should return false when object one is an array and object two is not.', () => { expect(pipe.equals([], {})).toBeFalsy(); }); it('should return false when two arrays are different lengths.', () => { expect(pipe.equals(['stuff', 'thing'], ['bears'])).toBeFalsy(); }); it('should return false when two arrays are the same length with different objects.', () => { expect(pipe.equals([{ bacon: 'burger' }], [{ bacon: 'buck' }])).toBeFalsy(); }); it('should return true when two arrays are the same.', () => { expect(pipe.equals([{ bacon: 'burger' }], [{ bacon: 'burger' }])).toBeTruthy(); }); it('should return false object one is not an array, but object two is.', () => { expect(pipe.equals({}, [])).toBeFalsy(); }); }); describe('Function: render(value, args)', () => { it('should return text when there is no value or args.', () => { expect(pipe.render).toBeDefined(); expect(pipe.render('Derp')).toBe('Derp'); expect(pipe.render(null, 'Derp')).toBe(null); }); it('should render an address.', () => { expect(pipe.render).toBeDefined(); const mockValue: any = { address1: 'Derp', address2: '264 Hess Rd', city: 'Leola', state: 'PA', zip: '17540', }; const mockArgs: any = { type: 'Address', }; expect(pipe.render(mockValue, mockArgs)).toBe(mockValue); }); it('should render an SecondaryAddress.', () => { expect(pipe.render).toBeDefined(); const mockValue: any = { address1: 'Derp', address2: '264 Hess Rd', city: 'Leola', state: 'PA', zip: '17540', }; const mockArgs: any = { type: 'SecondaryAddress', }; expect(pipe.render(mockValue, mockArgs)).toBe(mockValue); }); it('should render an BillingAddress.', () => { expect(pipe.render).toBeDefined(); const mockValue: any = { address1: 'Derp', address2: '264 Hess Rd', city: 'Leola', state: 'PA', zip: '17540', }; const mockArgs: any = { type: 'BillingAddress', }; expect(pipe.render(mockValue, mockArgs)).toBe(mockValue); }); // TODO: DateTime // WILL BREAK THE NEXT DAY xit('should render a timestamp.', () => { expect(pipe.render).toBeDefined(); const mockValue: any = new Date(); const mockArgs: any = { dataType: 'Timestamp', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toEqual('12/02/2016'); }); it('should render a timestamp with conversion skipped.', () => { expect(pipe.render).toBeDefined(); const mockValue: any = new Date('5/10/2017 23:59:59').getTime(); const mockArgs: any = { dataType: 'Timestamp', optionsType: 'skipConversion', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toEqual('5/10/2017'); }); // TODO: Phone/Email it('should render money.', () => { expect(pipe.render).toBeDefined(); const mockValue: any = 123.56; const mockArgs: any = { dataSpecialization: 'MONEY', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toEqual('$123.56'); }); it('should render a percentage.', () => { expect(pipe.render).toBeDefined(); const mockValue: any = 0.1556; const mockArgs: any = { dataSpecialization: 'PERCENTAGE', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toEqual('15.56%'); }); // TODO: Double/BigDecimal it('should render a Integer.', () => { expect(pipe.render).toBeDefined(); const mockValue: any = 103; const mockArgs: any = { dataType: 'Integer', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe(103); }); // TODO: Lead/Candidate/ClientContact/CorporateUser/Person // TODO: Opportunity/JobOrder // TODO: JobSubmission // TODO: WorkersCompensationRate it('should render a Options.', () => { expect(pipe.render).toBeDefined(); const mockValue: any = 'John'; const mockArgs: any = { inputType: 'SELECT', options: [ { value: 'John', label: 'John Snow', }, ], }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('John Snow'); }); it('should render a ToMany.', () => { expect(pipe.render).toBeDefined(); const mockValue: any = { data: [ { firstName: 'Jane', lastName: 'Smith', }, ], }; const mockArgs: any = { type: 'TO_MANY', associatedEntity: { entity: 'Candidate', }, }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('Jane Smith'); }); it('should render a Country.', () => { expect(pipe.render).toBeDefined(); const mockValue: any = 1; const mockArgs: any = { optionsType: 'Country', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('United States'); }); it('should render a DistributionList', () => { expect(pipe.render).toBeDefined(); const mockArgs: any = { type: 'TO_ONE', associatedEntity: { entity: 'DistributionList', }, }; const mockValue: any = { name: 'distributionList', label: 'List of Cheese Farmers', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('List of Cheese Farmers'); }); it('should render a Tearsheet', () => { expect(pipe.render).toBeDefined(); const mockArgs: any = { type: 'TO_ONE', associatedEntity: { entity: 'Tearsheet', }, }; const mockValue: any = { name: 'tearsheet', label: 'ShortList of Cheese Farmers', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('ShortList of Cheese Farmers'); }); it('should render a Skill', () => { expect(pipe.render).toBeDefined(); const mockArgs: any = { type: 'TO_ONE', associatedEntity: { entity: 'Skill', }, }; const mockValue: any = { name: 'skill', label: 'Makes awesome cheese', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('Makes awesome cheese'); }); it('should render a Category', () => { expect(pipe.render).toBeDefined(); const mockArgs: any = { type: 'TO_ONE', associatedEntity: { entity: 'Category', }, }; const mockValue: any = { name: 'category', label: 'Cheese Making', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('Cheese Making'); }); it('should render a Business Sector', () => { expect(pipe.render).toBeDefined(); const mockArgs: any = { type: 'TO_ONE', associatedEntity: { entity: 'BusinessSector', }, }; const mockValue: any = { name: 'businessSector', label: 'Dairy', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('Dairy'); }); it('should render a Certification', () => { expect(pipe.render).toBeDefined(); const mockArgs: any = { type: 'TO_ONE', associatedEntity: { entity: 'Certification', }, }; const mockValue: any = { name: 'certification', label: 'CMP - Cheese Making Professional', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('CMP - Cheese Making Professional'); }); it('should render a ClientCorporation', () => { expect(pipe.render).toBeDefined(); const mockArgs: any = { type: 'TO_ONE', associatedEntity: { entity: 'ClientCorporation', }, }; const mockValue: any = { name: 'clientCorporation', label: 'Cheese R Us', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('Cheese R Us'); }); it('should render a CorporationDepartment', () => { expect(pipe.render).toBeDefined(); const mockArgs: any = { type: 'TO_ONE', associatedEntity: { entity: 'CorporationDepartment', }, }; const mockValue: any = { name: 'corporationDepartment', label: 'Bringers of Cheese', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('Bringers of Cheese'); }); // checking name conditional for TO_ONE it('should render a CorporationDepartment', () => { expect(pipe.render).toBeDefined(); const mockArgs: any = { type: 'TO_ONE', associatedEntity: { entity: 'CorporationDepartment', }, }; const mockValue: any = { name: 'corporationDepartment', label: '', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('corporationDepartment'); }); // checking blank conditional for TO_ONE it('should render a CorporationDepartment', () => { expect(pipe.render).toBeDefined(); const mockArgs: any = { type: 'TO_ONE', associatedEntity: { entity: 'CorporationDepartment', }, }; const mockValue: any = { name: '', label: '', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe(''); }); it('should render a CandidateComment.', () => { expect(pipe.render).toBeDefined(); const mockArgs: any = { type: 'TO_ONE', associatedEntity: { entity: 'CandidateComment', }, }; const mockValue: any = { name: 'David S. Pumpkins', comments: 'I am so in the weeds with David Pumpkins!', dateLastModified: 1500999002330, }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('7/25/2017 (David S. Pumpkins) - I am so in the weeds with David Pumpkins!'); }); it('should render a CandidateComment.', () => { expect(pipe.render).toBeDefined(); const mockArgs: any = { type: 'TO_ONE', associatedEntity: { entity: 'CandidateComment', }, }; const mockValue: any = { name: 'David S. Pumpkins', comments: '', dateLastModified: 1500999002330, }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe(''); }); it('should render SkillText if array passed in', () => { expect(pipe.render).toBeDefined(); const mockValue: any = ['Skill1', 'Skill2', 'Skill3']; const mockArgs: any = { optionsType: 'SkillText', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('Skill1, Skill2, Skill3'); }); it('should render SkillText if array not passed in', () => { expect(pipe.render).toBeDefined(); const mockValue: any = 'Skill1'; const mockArgs: any = { optionsType: 'SkillText', }; const result: any = pipe.render(mockValue, mockArgs); expect(result).toBe('Skill1'); }); it('should render Html strings as sanitized Html content.', () => { const mockArgs: any = { type: 'SCALAR', dataType: 'String', dataSpecialization: 'HTML', }; const mockValue: any = '<span style="color:#c0392b">Some Green Text</span>'; const result: any = pipe.render(mockValue, mockArgs); expect(result).toEqual('TrustedHTML'); }); }); describe('Function: ngOnDestroy()', () => { it('should be defined.', () => { expect(pipe.ngOnDestroy).toBeDefined(); }); }); describe('Function: transform(value, args)', () => { it('should be defined.', () => { expect(pipe.transform).toBeDefined(); }); }); describe('Function: concat(list, ...fields)', () => { it('should concatenate properties of the object being passed in.', () => { expect(pipe.concat).toBeDefined(); const result: any = pipe.concat([{ firstName: 'Jane', lastName: 'Smith' }], 'firstName', 'lastName'); expect(result).toBe('Jane Smith'); }); }); describe('Function: options(value, list)', () => { it('should be defined.', () => { expect(pipe.options).toBeDefined(); }); it('should return an array of corresponding labels for values passed', () => { const values = ['1', '3']; const list = [{ label: 'Archived', value: '1' }, { label: 'New Lead', value: '2' }, { label: 'Old Lead', value: '3' }]; expect(pipe.options(values, list)).toEqual(['Archived', 'Old Lead']); }); }); describe('Function: getNumberDecimalPlaces(number)', () => { it('should return 1 zero to the right of the decimal point when a whole number is passed in', () => { expect(pipe.getNumberDecimalPlaces(1)).toBe(1); }); it('should return 1 zero to the right of the decimal point when the number passed in has 1 decimal place', () => { expect(pipe.getNumberDecimalPlaces(1.2)).toBe(1); }); it('should return 2 zeroes to the right of the decimal point when the number passed in has 2 decimal places', () => { expect(pipe.getNumberDecimalPlaces(1.23)).toBe(2); }); it('should return 3 zeroes to the right of the decimal point when the number passed in has 3 decimal places', () => { expect(pipe.getNumberDecimalPlaces(1.232)).toBe(3); }); it('should return 4 zeroes to the right of the decimal point when the number passed in has 4 decimal places', () => { expect(pipe.getNumberDecimalPlaces(1.2323)).toBe(4); }); it('should return 4 zeroes to the right of the decimal point when the number passed in has more than 4 decimal places', () => { expect(pipe.getNumberDecimalPlaces(1.232324)).toBe(6); }); it('should return 2 zeroes to the right of the decimal point when the number passed in has 3 decimal places and one is non-numeric', () => { expect(pipe.getNumberDecimalPlaces('1.23o')).toBe(2); }); }); describe('Function: capitalize(string)', () => { it('should capitalize a string.', () => { expect(pipe.capitalize).toBeDefined(); expect(pipe.capitalize('hello world!')).toBe('Hello world!'); }); }); });
the_stack
import { ApplySchemaAttributes, command, CommandFunction, ErrorConstant, extension, ExtensionTag, Handler, invariant, isElementDomNode, isString, kebabCase, NodeExtension, NodeExtensionSpec, NodeSpecOverride, NodeWithPosition, omitExtraAttributes, pick, ProsemirrorAttributes, replaceText, Static, } from '@remirror/core'; import type { CreateEventHandlers } from '@remirror/extension-events'; import { DEFAULT_SUGGESTER, MatchValue, RangeWithCursor, SuggestChangeHandlerProps, Suggester, } from '@remirror/pm/suggest'; import { ExtensionMentionAtomTheme as Theme } from '@remirror/theme'; /** * Options available to the [[`MentionAtomExtension`]]. */ export interface MentionAtomOptions extends Pick< Suggester, 'invalidNodes' | 'validNodes' | 'invalidMarks' | 'validMarks' | 'isValidPosition' > { /** * When `true` the atom node which wraps the mention will be selectable. * * @default true */ selectable?: Static<boolean>; /** * Whether mentions should be draggable. * * @default false */ draggable?: Static<boolean>; /** * Provide a custom tag for the mention */ mentionTag?: Static<string>; /** * Provide the custom matchers that will be used to match mention text in the * editor. * * TODO - add customized tags here. */ matchers: Static<MentionAtomExtensionMatcher[]>; /** * Text to append after the mention has been added. * * **NOTE**: If it seems that your editor is swallowing up empty whitespace, * make sure you've imported the core css from the `@remirror/styles` library. * * @default ' ' */ appendText?: string; /** * Tag for the prosemirror decoration which wraps an active match. * * @default 'span' */ suggestTag?: string; /** * When true, decorations are not created when this mention is being edited. */ disableDecorations?: boolean; /** * Called whenever a suggestion becomes active or changes in any way. * * @remarks * * It receives a parameters object with the `reason` for the change for more * granular control. */ onChange?: Handler<MentionAtomChangeHandler>; /** * Listen for click events to the mention atom extension. */ onClick?: Handler< (event: MouseEvent, nodeWithPosition: NodeWithPosition) => boolean | undefined | void >; } /** * This is the atom version of the `MentionExtension` * `@remirror/extension-mention`. * * It provides mentions as atom nodes which don't support editing once being * inserted into the document. */ @extension<MentionAtomOptions>({ defaultOptions: { selectable: true, draggable: false, mentionTag: 'span' as const, matchers: [], appendText: ' ', suggestTag: 'span' as const, disableDecorations: false, invalidMarks: [], invalidNodes: [], isValidPosition: () => true, validMarks: null, validNodes: null, }, handlerKeyOptions: { onClick: { earlyReturnValue: true } }, handlerKeys: ['onChange', 'onClick'], staticKeys: ['selectable', 'draggable', 'mentionTag', 'matchers'], }) export class MentionAtomExtension extends NodeExtension<MentionAtomOptions> { get name() { return 'mentionAtom' as const; } createTags() { return [ExtensionTag.InlineNode, ExtensionTag.Behavior]; } createNodeSpec(extra: ApplySchemaAttributes, override: NodeSpecOverride): NodeExtensionSpec { const dataAttributeId = 'data-mention-atom-id'; const dataAttributeName = 'data-mention-atom-name'; return { inline: true, selectable: this.options.selectable, draggable: this.options.draggable, atom: true, ...override, attrs: { ...extra.defaults(), id: {}, label: {}, name: {}, }, parseDOM: [ ...this.options.matchers.map((matcher) => ({ tag: `${matcher.mentionTag ?? this.options.mentionTag}[${dataAttributeId}]`, getAttrs: (node: string | Node) => { if (!isElementDomNode(node)) { return false; } const id = node.getAttribute(dataAttributeId); const name = node.getAttribute(dataAttributeName); const label = node.textContent; return { ...extra.parse(node), id, label, name }; }, })), ...(override.parseDOM ?? []), ], toDOM: (node) => { const { label, id, name } = omitExtraAttributes( node.attrs, extra, ) as NamedMentionAtomNodeAttributes; const matcher = this.options.matchers.find((matcher) => matcher.name === name); const mentionClassName = matcher ? matcher.mentionClassName ?? DEFAULT_MATCHER.mentionClassName : DEFAULT_MATCHER.mentionClassName; const attrs = { ...extra.dom(node), class: name ? `${mentionClassName} ${mentionClassName}-${kebabCase(name)}` : mentionClassName, [dataAttributeId]: id, [dataAttributeName]: name, }; return [matcher?.mentionTag ?? this.options.mentionTag, attrs, label]; }, }; } /** * Creates a mention atom at the the provided range. * * A variant of this method is provided to the `onChange` handler for this * extension. * * @param details - the range and name of the mention to be created. * @param attrs - the attributes that should be passed through. Required * values are `id` and `label`. */ @command() createMentionAtom(details: CreateMentionAtom, attrs: MentionAtomNodeAttributes): CommandFunction { const { name, range } = details; const validNameExists = this.options.matchers.some((matcher) => name === matcher.name); // Check that the name is valid. invariant(validNameExists, { code: ErrorConstant.EXTENSION, message: `Invalid name '${name}' provided when creating a mention. Please ensure you only use names that were configured on the matchers when creating the \`MentionAtomExtension\`.`, }); const { appendText, ...rest } = attrs; return replaceText({ type: this.type, appendText: getAppendText(appendText, this.options.appendText), attrs: { name, ...rest }, range, }); } /** * Track click events passed through to the editor. */ createEventHandlers(): CreateEventHandlers { return { click: (event, clickState) => { // Check if this is a direct click which must be the case for atom // nodes. if (!clickState.direct) { return; } const nodeWithPosition = clickState.getNode(this.type); if (!nodeWithPosition) { return; } return this.options.onClick(event, nodeWithPosition); }, }; } createSuggesters(): Suggester[] { const options = pick(this.options, [ 'invalidMarks', 'invalidNodes', 'isValidPosition', 'validMarks', 'validNodes', 'suggestTag', 'disableDecorations', 'appendText', ]); return this.options.matchers.map<Suggester>((matcher) => { return { ...DEFAULT_MATCHER, ...options, ...matcher, onChange: (props) => { const { name, range } = props; const { createMentionAtom } = this.store.commands; function command(attrs: MentionAtomNodeAttributes) { createMentionAtom({ name, range }, attrs); } this.options.onChange(props, command); }, }; }); } } /** * The default matcher to use when none is provided in options */ const DEFAULT_MATCHER = { ...pick(DEFAULT_SUGGESTER, [ 'startOfLine', 'supportedCharacters', 'validPrefixCharacters', 'invalidPrefixCharacters', ]), appendText: '', matchOffset: 1, suggestClassName: Theme.SUGGEST_ATOM, mentionClassName: Theme.MENTION_ATOM, }; export interface OptionalMentionAtomExtensionProps { /** * The text to append to the replacement. * * @default '' */ appendText?: string; /** * The type of replacement to use. By default the command will only replace text up the the cursor position. * * To force replacement of the whole match regardless of where in the match the cursor is placed set this to * `full`. * * @default 'full' */ replacementType?: keyof MatchValue; } export interface CreateMentionAtom { /** * The name of the matcher used to create this mention. */ name: string; /** * The range of the current selection */ range: RangeWithCursor; } /** * The attrs that will be added to the node. * ID and label are plucked and used while attributes like href and role can be assigned as desired. */ export type MentionAtomNodeAttributes = ProsemirrorAttributes< OptionalMentionAtomExtensionProps & { /** * A unique identifier for the suggesters node */ id: string; /** * The text to be placed within the suggesters node */ label: string; } >; export type NamedMentionAtomNodeAttributes = MentionAtomNodeAttributes & { /** * The name of the matcher used to create this mention. */ name: string; }; /** * This change handler is called whenever there is an update in the matching * suggester. The second parameter `command` is available to automatically * create the mention with the required attributes. */ export type MentionAtomChangeHandler = ( handlerState: SuggestChangeHandlerProps, command: (attrs: MentionAtomNodeAttributes) => void, ) => void; /** * The options for the matchers which can be created by this extension. */ export interface MentionAtomExtensionMatcher extends Pick< Suggester, | 'char' | 'name' | 'startOfLine' | 'supportedCharacters' | 'validPrefixCharacters' | 'invalidPrefixCharacters' | 'suggestClassName' > { /** * See [[``Suggester.matchOffset`]] for more details. * * @default 1 */ matchOffset?: number; /** * Provide customs class names for the completed mention. */ mentionClassName?: string; /** * An override for the default mention tag. This allows different mentions to * use different tags. */ mentionTag?: string; } /** * Get the append text value which needs to be handled carefully since it can * also be an empty string. */ function getAppendText(preferred: string | undefined, fallback: string | undefined) { if (isString(preferred)) { return preferred; } if (isString(fallback)) { return fallback; } return DEFAULT_MATCHER.appendText; } declare global { namespace Remirror { interface AllExtensions { mentionAtom: MentionAtomExtension; } } }
the_stack
import { BooleanInput, coerceBooleanProperty } from '@angular/cdk/coercion'; import { Platform } from '@angular/cdk/platform'; import { CdkPortalOutlet, TemplatePortal } from '@angular/cdk/portal'; import { DOCUMENT } from '@angular/common'; import { Attribute, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, ElementRef, Inject, Input, IterableDiffers, OnDestroy, Optional, QueryList, SkipSelf, TemplateRef, ViewChild, ViewContainerRef, ViewEncapsulation, } from '@angular/core'; import { Subject, Subscription, BehaviorSubject } from 'rxjs'; import { mapTo } from 'rxjs/operators'; import { DtEmptyState } from '@dynatrace/barista-components/empty-state'; import { _DtTableBase } from './base-table'; import { DtSimpleColumnComparatorFunction, DtSimpleColumnDisplayAccessorFunction, DtSimpleColumnSortAccessorFunction, } from './simple-columns/simple-column-base'; import { _DisposeViewRepeaterStrategy, _ViewRepeater, _VIEW_REPEATER_STRATEGY, } from '@angular/cdk/collections'; import { RenderRow, RowContext, StickyPositioningListener, STICKY_POSITIONING_LISTENER, _CoalescedStyleScheduler, _COALESCED_STYLE_SCHEDULER, } from '@angular/cdk/table'; import { ViewportRuler } from '@angular/cdk/scrolling'; import { DtTableSelection } from './selection/selection'; interface SimpleColumnsAccessorMaps<T> { displayAccessorMap: Map<string, DtSimpleColumnDisplayAccessorFunction<T>>; sortAccessorMap: Map<string, DtSimpleColumnSortAccessorFunction<T>>; comparatorMap: Map<string, DtSimpleColumnComparatorFunction<T>>; } let nextUniqueId = 0; @Component({ selector: 'dt-table', styleUrls: ['./table.scss'], templateUrl: './table.html', exportAs: 'dtTable', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.Emulated, preserveWhitespaces: false, host: { class: 'dt-table', '[class.dt-table-interactive-rows]': 'interactiveRows', '[class.dt-table-expandable-rows]': '_hasExpandableRows', }, providers: [ { provide: _COALESCED_STYLE_SCHEDULER, useClass: _CoalescedStyleScheduler }, { provide: _VIEW_REPEATER_STRATEGY, useClass: _DisposeViewRepeaterStrategy, }, ], }) export class DtTable<T> extends _DtTableBase<T> implements OnDestroy { private _multiExpand: boolean; // TODO: discuss default value with UX, should maybe change from false to true private _loading: boolean; private _destroy$ = new Subject<void>(); private _showExportButton: boolean = false; //Revert to opt-in instead of opt-out per request /** Sort accessor map that holds all sort accessor functions from the registered simple columns. */ private _sortAccessorMap = new Map< string, DtSimpleColumnSortAccessorFunction<T> >(); /** Sort accessor map that holds all display accessor functions from the registered simple columns. */ private _displayAccessorMap = new Map< string, DtSimpleColumnDisplayAccessorFunction<T> >(); /** Sort accessor map that holds all comparator accessor functions from the registered simple columns. */ private _comparatorFunctionMap = new Map< string, DtSimpleColumnComparatorFunction<T> >(); /** @internal A generated UID */ _uniqueId = `dt-table-${nextUniqueId++}`; /** @internal Whether a expandable row is registered with the table */ _hasExpandableRows = false; /** @internal Reference to filteredData in table-data-source */ _filteredData: T[]; /** @internal Reference to exportable data. */ _exporter: { filteredData: T[]; selection: DtTableSelection<T> | null; }; /** @internal Determine if selection is enabled and properly connected. */ get _selectionEnabledAndConnected(): boolean { if (this._exporter && this._exporter.selection) return true; else return false; } /** The number of rows that have been selected by the user. */ get numSelectedRows(): number { if ( this._exporter && this._exporter.selection != null && this._exporter.selection.selected ) return this._exporter.selection.selected.length; else return 0; } /** Whether the loading state should be displayed. */ @Input() get loading(): boolean { return this._loading; } set loading(value: boolean) { this._loading = coerceBooleanProperty(value); } /** Whether multiple rows can be expanded at a time. */ @Input() get multiExpand(): boolean { return this._multiExpand; } set multiExpand(value: boolean) { this._multiExpand = coerceBooleanProperty(value); } /** Whether the datasource is empty. */ get isEmptyDataSource(): boolean { return !(this._data && this._data.length); } /** * Experimental! * Opt-in to the possibility to export all table data, visible table data or * selected table data into a csv file. */ @Input() get showExportButton(): boolean { return this._showExportButton; } set showExportButton(value: boolean) { this._showExportButton = coerceBooleanProperty(value); } static ngAcceptInputType_showExportButton: BooleanInput; /** @internal The snapshot of the current data */ get _dataSnapshot(): T[] | readonly T[] { return this._data; } /** @internal The QueryList that holds the empty state component */ @ContentChildren(DtEmptyState) _emptyState: QueryList<DtEmptyState>; /** @internal The template where the empty state component gets rendered inside */ @ViewChild('emptyStateTemplate', { static: true }) _emptyStateTemplate: TemplateRef<DtEmptyState>; /** @internal The portal where the component will be projected in when we have to show the empty state. */ @ViewChild(CdkPortalOutlet, { static: true }) _portalOutlet: CdkPortalOutlet; /** @internal Stream of all simple dataAccessor functions for all SimpleColumns */ _dataAccessors = new BehaviorSubject<SimpleColumnsAccessorMaps<T>>({ displayAccessorMap: this._displayAccessorMap, sortAccessorMap: this._sortAccessorMap, comparatorMap: this._comparatorFunctionMap, }); /** Updates the dataAccessors subject for the connected datasource. */ private _updateAccessors(): void { this._dataAccessors.next({ displayAccessorMap: this._displayAccessorMap, sortAccessorMap: this._sortAccessorMap, comparatorMap: this._comparatorFunctionMap, }); } /** Subscription of attached stream of the portal outlet */ private _portalOutletSubscription = Subscription.EMPTY; constructor( differs: IterableDiffers, changeDetectorRef: ChangeDetectorRef, elementRef: ElementRef, @Attribute('role') role: string, // tslint:disable-next-line: no-any @Inject(DOCUMENT) document: any, platform: Platform, private _viewContainerRef: ViewContainerRef, @Inject(_VIEW_REPEATER_STRATEGY) _viewRepeater: _ViewRepeater<T, RenderRow<T>, RowContext<T>>, @Inject(_COALESCED_STYLE_SCHEDULER) _coalescedStyleScheduler: _CoalescedStyleScheduler, _viewportRuler: ViewportRuler, @Optional() @SkipSelf() @Inject(STICKY_POSITIONING_LISTENER) _stickyPositioningListener: StickyPositioningListener, ) { super( differs, changeDetectorRef, elementRef, document, platform, _viewRepeater, _coalescedStyleScheduler, _viewportRuler, role, _stickyPositioningListener, ); } ngOnDestroy(): void { super.ngOnDestroy(); this._destroy$.next(); this._destroy$.complete(); this._portalOutletSubscription.unsubscribe(); } /** * Renders rows based on the table's latest set of data, * which was either provided directly as an input or retrieved * through an Observable stream (directly or from a DataSource). */ renderRows(): void { // To prevent an error that was thrown when the the component containing // the table was destroyed. `"Cannot move a destroyed View in a ViewContainer!"` // // This check is necessary because the cdkTable does not check // if the view is already destroyed before moving it // https://github.com/angular/components/blob/c68791db9a0b4107d04fa924c27a087cd00a8989/src/cdk/table/table.ts#L637 // // The dependency for the _rowOutlet internal is safe, as we already // depend on this one for the template as well. const rowOutletViewContainer = this._rowOutlet.viewContainer; let shouldRender = false; // Figure out if all views within the viewContainer are already // destroyed. for (let i = 0; i < rowOutletViewContainer.length; i += 1) { const view = rowOutletViewContainer.get(i); if (view!.destroyed === false) { shouldRender = true; break; } } // Only if not all view containers have been destroyed, or if // there are no viewContainers at all. if (shouldRender || rowOutletViewContainer.length === 0) { super.renderRows(); } // no need if there is no empty state provided via content projection if (!this._emptyState.first) { return; } // if we have a subscription we need to unsubscribe to re-subscribe later on // we need to subscribe in this function in case that there is no other hook // where we can hook into the cdk Table if (this._portalOutletSubscription) { this._portalOutletSubscription.unsubscribe(); } this._portalOutletSubscription = this._portalOutlet.attached .pipe(mapTo(this._emptyState.first)) .subscribe((emptyState) => { // Update the layout of the empty state after it was attached emptyState._visible = true; }); if (this.isEmptyDataSource) { if (!this._portalOutlet.hasAttached()) { const template = new TemplatePortal( this._emptyStateTemplate, this._viewContainerRef, ); this._portalOutlet.attachTemplatePortal(template); } this._emptyState.first._visible = true; this._changeDetectorRef.markForCheck(); } else { // ned to unset the visibility to have every time the component will be attached a fading animation. this._emptyState.first._visible = false; this._portalOutlet.detach(); } } /** Update the column accessor functions */ _updateColumnAccessors( name: string, displayAccessor?: DtSimpleColumnDisplayAccessorFunction<T>, sortAccessor?: DtSimpleColumnSortAccessorFunction<T>, comparatorFunction?: DtSimpleColumnComparatorFunction<T>, ): void { if (displayAccessor) { this._displayAccessorMap.set(name, displayAccessor); } else { this._displayAccessorMap.delete(name); } if (sortAccessor) { this._sortAccessorMap.set(name, sortAccessor); } else { this._sortAccessorMap.delete(name); } if (comparatorFunction) { this._comparatorFunctionMap.set(name, comparatorFunction); } else { this._comparatorFunctionMap.delete(name); } this._updateAccessors(); } /** @internal Helper function for simple columns to unregister their sort accessors. */ _removeColumnAccessors(name: string): void { this._sortAccessorMap.delete(name); this._displayAccessorMap.delete(name); this._comparatorFunctionMap.delete(name); this._updateAccessors(); } /** CSS class added to any row or cell that has sticky positioning applied. */ protected stickyCssClass = 'dt-table-sticky'; /** @internal Exports the filtered source data from the dataSource. */ // Note: this is different from the display text, see instead _exportDisplayData(). _exportFilteredData(): void { const exportData = this._filteredData; if (this.isEmptyDataSource || typeof exportData[0] != 'object') { return; } const csvObj = { csv: '' }; const keys: string[] = Object.keys(exportData[0]); if (!keys.length) { return; } //check for objects, expand properties into new columns for (let i = keys.length - 1; i > -1; i--) { const key = keys[i]; const val = exportData[0][key]; if (typeof val == 'object') { const subkeys = Object.keys(val).map((sk) => `${key}.${sk}`); keys.splice(i, 1, ...subkeys); } } // header row csvObj.csv += keys.join(',') + '\n'; for (const row of exportData) { for (let idx = 0; idx < keys.length; idx++) { const key = keys[idx]; let val: any; if (key.includes('.') && typeof row[key] == 'undefined') { //derived key object.property const keyArr = key.split('.'); const objKey = keyArr[0]; const prop = keyArr[1]; const obj = row[objKey] || {}; val = obj[prop]; } else { val = row[key]; } this._appendValToCSV(csvObj, val, idx, keys.length); } csvObj.csv += '\n'; } this._downloadCSV(csvObj.csv); } /** @internal Exports the filtered display data from the dataSource after being formatted by a displayAccessor. */ _exportDisplayData(exportData: T[] = this._filteredData): void { if (this.isEmptyDataSource || typeof exportData[0] != 'object') { return; } const csvObj = { csv: '' }; const keys: string[] = [...this._contentHeaderRowDefs.first.columns].filter( (h: string) => h !== 'checkbox', ); //skip selection column if (!keys.length) { return; } //get column names const headerList = this._elementRef.nativeElement.querySelectorAll( 'dt-header-row dt-header-cell', ); const headersArr = Array.from(headerList); const headers = headersArr .map((h: HTMLElement): String => { const txt = h.innerText; if (txt.includes(',')) return `"${txt}"`; else return txt; }) .filter((h: string) => h !== ''); //skip selection column if (headers.length !== keys.length) { console.warn( '_exportDisplayData: mismatched column count. Data may be shifted.', ); } // header row csvObj.csv += headers.join(',') + '\n'; for (const row of exportData) { for (let idx = 0; idx < keys.length; idx++) { const key = keys[idx]; const accessor = this._displayAccessorMap.get(key); const val = accessor ? accessor(row, key) : row[key]; this._appendValToCSV(csvObj, val, idx, keys.length); } csvObj.csv += '\n'; } this._downloadCSV(csvObj.csv); } /** Assemble the CSV while safely handling types. */ private _appendValToCSV( csvObj: { csv: string }, val: any, idx: number, len: number, ): void { switch (typeof val) { case 'string': break; case 'object': //if it's still complex, just convert to JSON and move on val = JSON.stringify(val); break; case 'undefined': val = ''; break; default: val = val.toString(); } if (val.includes(',')) { val = val.replace(/"/g, '""'); //escape any existing double quotes csvObj.csv += `"${val}"`; // } else { csvObj.csv += val; } if (idx < len) { csvObj.csv += ','; } } /** @internal Export only the rows which are currently selected. */ _exportSelection(): void { if (this._exporter.selection) { this._exportDisplayData(this._exporter.selection.selected); } else { console.log('no selection'); } } /** Take a CSV string and trigger a download in browser */ private _downloadCSV(csv: string): void { //make csv document const blob = new Blob([csv], { type: 'text/csv' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.target = '_blank'; link.download = 'table-' + new Date().getTime() + '.csv'; link.click(); link.remove(); } }
the_stack
import { leftPad, createDescribe, createTest, printMethodValues, printTable, } from '../text' import {forIn} from '../forIn' import { DataDecl, BoolDecl, Grouping, Declarator, WordValue, CaseItem, } from './types' import {isDataDecl, isBoolDecl, assertRef, isRef} from './isRef' import {assert} from './assert' type Obj = Record<string, any> function createReader<T, O extends Obj>( item: ((obj: O) => T) | DataDecl<T> | T, config?: {defaultVal?: T; isBool: never}, ): (obj: O) => T function createReader<O extends Obj>( item: ((obj: O) => boolean) | BoolDecl | boolean, config?: {defaultVal?: boolean; isBool: true}, ): (obj: O) => boolean function createReader<T, O extends Obj>( item: ((obj: O) => T) | DataDecl<T> | T, {defaultVal, isBool = false}: {defaultVal?: T; isBool?: boolean} = {}, ) { if (typeof item === 'function') return item as Exclude<typeof item, T & Function> if ((isBool && !isBoolDecl(item)) || (!isBool && !isDataDecl(item))) { return (obj: O) => { return item } } assertRef(item) return (obj: O) => { const result = obj[item.name] if (result === undefined) { if (defaultVal !== undefined) return defaultVal throw Error(`no field "${item.name}"`) } return result } } function createHashReader<T extends Obj>(getHash: Grouping<T>['getHash']) { if (isDataDecl(getHash)) return createReader(getHash) const declList = Array.isArray(getHash) ? getHash : Object.values(getHash) declList.forEach(value => { assertRef(value) }) return (obj: T) => { const values: string[] = [] declList.forEach(decl => { const value = obj[decl.name] assert(value !== undefined, `undefined getHash for ${decl.name}`) values.push(String(value)) }) return values.join(' ') } } function createDedupeReader<T extends Obj>( objectToLines: ( value: T, ) => string | Array<string | null | undefined | false>, ) { return (value: T) => { const linesRaw = objectToLines(value) const textLines = Array.isArray(linesRaw) ? linesRaw : [linesRaw] return textLines .filter((line): line is string => typeof line === 'string') .map(line => line.replace(/ /gim, '')) .filter(line => !line.includes(`@ts-expect-error`)) .join(`\n`) } } export function createGroupedCases<T extends Obj>( casesDefs: T[], { createTestLines, getHash, describeGroup, sortByFields, filter, pass, tags, }: Grouping<T>, ) { let caseSerializer: (value: T) => any = value => ({}) if (tags) { caseSerializer = value => { const result: any = {} forIn(tags, (decl, field) => { result[field] = value[decl.id] }) return result } } let dedupeGetter: ((obj: T) => string) | undefined const hashGetter = createHashReader(getHash) const groupDescriber = createReader( describeGroup as DataDecl< | string | { description: string noGroup?: boolean | undefined largeGroup?: string | null | undefined } >, ) const passGetter = createReader(pass!, { isBool: true, defaultVal: true, }) if (filter) { casesDefs = casesDefs.filter(filter) } let renderMode: 'table' | 'text' | 'method' = 'method' let createLinesForTestList: ( values: T[], pass: boolean, description: string, ) => { items: Array<CaseItem<T>> textLines: string[] } let mode: | { type: 'text' // passReader?: (obj: T) => boolean textValueReader: (obj: T) => WordValue | WordValue[] } | { type: 'table' } | { type: 'method' } const testLinesSet = new Map<string, any>() if (typeof createTestLines === 'object' && createTestLines !== null) { if ('type' in createTestLines) { switch (createTestLines.type) { case 'table': { mode = {type: 'table'} renderMode = 'table' let header: string[] | void let fields: Declarator[] if (!Array.isArray(createTestLines.fields)) { header = Object.keys(createTestLines.fields) fields = Object.values(createTestLines.fields) } else { fields = createTestLines.fields } const only = fields.map(e => e.name) createLinesForTestList = (values: T[]) => ({ items: [], textLines: printTable({ values, only, header, }), }) break } case 'text': { renderMode = 'text' //prettier-ignore const renderer: Extract<typeof mode, {type: 'text'}> = mode = { type: 'text', textValueReader: createReader(createTestLines.value) } // if ('pass' in createTestLines) { // mode.passReader = createReader(createTestLines.pass!, { // isBool: true, // }) // } const renderVisibleValues = ( values: WordValue[], isPass: boolean, ) => { const lines: string[] = [] for (let i = 0; i < values.length; i++) { const value = values[i] if (value === null || value === undefined) continue lines.push(String(value)) } if (lines.length === 0) return [] if (!isPass) lines.push('//' + '@ts-expect-error') return lines } function createLineBlock(value: T) { const linesRaw = renderer.textValueReader(value) return renderVisibleValues( Array.isArray(linesRaw) ? linesRaw : [linesRaw], true, ) } if (!dedupeGetter) { dedupeGetter = createDedupeReader(createLineBlock) } createLinesForTestList = (values: T[], pass, description) => { const lineBlocks = values.map(createLineBlock) const items = values.map((value, i) => { const lines = lineBlocks[i] return { value: caseSerializer(value), pass, text: lines.join(`\n`), description, } }) return { items, textLines: lineBlocks.flat(), } } break } default: //@ts-expect-error createTestLines.type } } else { mode = {type: 'method'} renderMode = 'method' const { method, shape, addExpectError = (obj: T) => !passGetter(obj), } = createTestLines const readExpectError = createReader(addExpectError, {isBool: true}) const printShape: Record<string, string | {field: string; when: string}> = {} forIn(shape, (value, key) => { printShape[key] = isRef(value) ? value.name : {field: value.field.name, when: value.when.name} }) if (!dedupeGetter) { dedupeGetter = createDedupeReader(value => printMethodValues({ method, values: [value], shape: printShape, addExpectError: () => false, }), ) } createLinesForTestList = (values: T[], pass, description) => { const textLines = printMethodValues({ method, values, shape: printShape, addExpectError: readExpectError, }) return { textLines, items: values.map((value, i) => ({ value: caseSerializer(value), text: textLines[i], pass, description, })), } } } } else { if (!dedupeGetter) { dedupeGetter = createDedupeReader(createTestLines) } createLinesForTestList = (values: T[], pass, description) => { const lineBlocks = values.map(value => createTestLines(value).filter(line => typeof line === 'string'), ) const items = values.map((value, i) => { const lines = lineBlocks[i] return { value: caseSerializer(value), pass, text: lines.join(`\n`), description, } }) return { items, textLines: lineBlocks.flat(), } } } const isAafterB = (sortByFields && skewHeapSortFieldsComparator(sortByFields))! function sortList<T>(list: T[]) { if (!sortByFields) return [...list] return [...list].sort((a, b) => { const ab = isAafterB(a, b) const ba = isAafterB(b, a) if (!ab && !ba) return 0 if (ab && ba) return 0 return ab ? -1 : 1 }) } const casesDefsPending = sortList([...casesDefs]) if (sortByFields) { casesDefsPending.forEach((e, id) => { //@ts-ignore e.__casesDefsID = id }) } type Group = { itemsPass: T[] itemsFail: T[] description: string largeGroup: string | null noGroup: boolean } const defsGroups = new Map<string, Group>() let cur while ((cur = casesDefsPending.shift())) { // console.log('cur', cur) if (dedupeGetter) { const caseDefHash = dedupeGetter(cur) if (testLinesSet.has(caseDefHash)) continue testLinesSet.set(caseDefHash, cur) } const hash = hashGetter(cur) let set = defsGroups.get(hash) if (!set) { set = { itemsPass: [], itemsFail: [], description: '', largeGroup: null, noGroup: false, } defsGroups.set(hash, set) } ;(passGetter(cur) ? set.itemsPass : set.itemsFail).push(cur) const description = groupDescriber(cur) if (typeof description === 'string') { set.description = description } else { set.noGroup = description.noGroup ?? false set.description = description.description set.largeGroup = description.largeGroup || null } } const descriptions = {} as Record<string, Group> for (const [hash, group] of [...defsGroups]) { const text = `${group.largeGroup || ''} ${group.description}` if (text in descriptions) { defsGroups.delete(hash) const {itemsPass, itemsFail} = descriptions[text] itemsPass.splice(itemsPass.length, 0, ...group.itemsPass) itemsFail.splice(itemsFail.length, 0, ...group.itemsFail) continue } descriptions[text] = group } const largeGroups = {} as Record<string, string[]> const resultCases = [] as string[] const resultCasesItems = [] as Array<CaseItem<T>> const createTestSuiteItem = ({ pass, items, description, textLinesFlat, }: { items: T[] pass: boolean description: string textLinesFlat: string[] }) => { switch (renderMode) { case 'table': { const passText = description ? pass ? ' (pass)' : ' (fail)' : pass ? 'pass' : 'fail' return [`\n## ${description}${passText}`, ...textLinesFlat].join(`\n`) } case 'text': case 'method': { const passText = pass ? '(should pass)' : '(should fail)' const blockOpen = items.length === 1 ? null : '{' const blockClose = items.length === 1 ? null : '}' const itemsLines = items.length === 1 ? textLinesFlat : leftPad(textLinesFlat) return createTest(`${description} ${passText}`, [ '//prettier-ignore', blockOpen, ...itemsLines, blockClose, 'expect(typecheck).toMatchInlineSnapshot()', ]) } } } for (let { description, itemsPass, itemsFail, noGroup, largeGroup, } of defsGroups.values()) { if (itemsPass.length === 0 && itemsFail.length === 0) continue const testSuiteItems = [] as string[] if (itemsPass.length > 0) { const itemsFull = createLinesForTestList!(itemsPass, true, description) testSuiteItems.push( createTestSuiteItem({ items: itemsPass, pass: true, description, textLinesFlat: itemsFull.textLines, }), ) resultCasesItems.push(...itemsFull.items) } if (itemsFail.length > 0) { const itemsFull = createLinesForTestList!(itemsFail, false, description) testSuiteItems.push( createTestSuiteItem({ items: itemsFail, pass: false, description, textLinesFlat: itemsFull.textLines, }), ) resultCasesItems.push(...itemsFull.items) } const lines = [] as string[] if (noGroup || testSuiteItems.length === 1) { lines.push(...testSuiteItems) } else { let line: string switch (renderMode) { case 'table': line = [`# ${description}`, ...leftPad(testSuiteItems)].join(`\n`) break case 'method': case 'text': line = createDescribe(description, testSuiteItems) break } lines.push(line) } if (largeGroup !== null) { if (!(largeGroup in largeGroups)) { largeGroups[largeGroup] = [] } largeGroups[largeGroup].push(...lines) } else { resultCases.push(...lines) } } if (renderMode === 'table') resultCases.push(``) const largeGroupsContent = Object.entries(largeGroups).map( ([text, items]) => { switch (renderMode) { case 'table': return [`# ${text}`, ...leftPad(items)].join(`\n`) case 'text': case 'method': return createDescribe(text, items) } }, ) const finalLines = [...largeGroupsContent, ...resultCases] return { finalLines, resultCasesItems, } } const collator = new Intl.Collator('en', { caseFirst: 'upper', usage: 'sort', sensitivity: 'variant', numeric: true, }) function skewHeapSortFieldsComparator< Obj extends Record<string, ReadonlyArray<any> | 'string'>, >(sortByFields: Obj) { const fields = [] as Array< | { field: keyof Obj isVoidFalse: boolean type: 'prioritySet' prioritySet: ReadonlyArray<any> } | { field: keyof Obj isVoidFalse: boolean type: 'string' } > forIn(sortByFields, (prioritySet: ReadonlyArray<any> | 'string', field) => { if (prioritySet === 'string') { fields.push({ field, isVoidFalse: false, type: 'string', }) } else { const isVoidFalse = prioritySet.includes(false) && !prioritySet.includes(undefined) fields.push({ field, isVoidFalse, type: 'prioritySet', prioritySet: [...prioritySet].reverse(), }) } }) return function isAafterB(a: any, b: any) { for (let i = 0; i < fields.length; i++) { const item = fields[i] const {field, isVoidFalse} = item let aVal = a[field] let bVal = b[field] if (isVoidFalse) { if (aVal === undefined) aVal = false if (bVal === undefined) bVal = false } if (aVal === bVal) continue switch (item.type) { case 'prioritySet': { const {prioritySet} = item const ai = prioritySet.indexOf(aVal) const bi = prioritySet.indexOf(bVal) const hasA = ai !== -1 const hasB = bi !== -1 if (hasA && !hasB) return false if (!hasA && hasB) return true if (!hasA && !hasB) continue return ai > bi } case 'string': { return collator.compare(aVal, bVal) > 0 } } } const idDiff = a.__casesDefsID - b.__casesDefsID if (idDiff !== 0) return idDiff > 0 console.count('indifferentiated elements') console.log(a, b) return false } }
the_stack
export type BigQueryDataset = object; // BigQueryDatasetList is a list of BigQueryDataset export class BigQueryDatasetList { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources public apiVersion: string; // List of bigquerydatasets. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md public items: BigQueryDataset[]; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds public kind: string; // ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}. public metadata?: BigQueryDatasetList.Metadata; constructor(desc: BigQueryDatasetList) { this.apiVersion = BigQueryDatasetList.apiVersion; this.items = desc.items; this.kind = BigQueryDatasetList.kind; this.metadata = desc.metadata; } } export function isBigQueryDatasetList(o: any): o is BigQueryDatasetList { return ( o && o.apiVersion === BigQueryDatasetList.apiVersion && o.kind === BigQueryDatasetList.kind ); } export namespace BigQueryDatasetList { export const apiVersion = 'bigquery.cnrm.cloud.google.com/v1beta1'; export const group = 'bigquery.cnrm.cloud.google.com'; export const version = 'v1beta1'; export const kind = 'BigQueryDatasetList'; // BigQueryDatasetList is a list of BigQueryDataset export interface Interface { // List of bigquerydatasets. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md items: BigQueryDataset[]; // ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}. metadata?: BigQueryDatasetList.Metadata; } // ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}. export class Metadata { // continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message. public continue?: string; // remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact. public remainingItemCount?: number; // String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency public resourceVersion?: string; // selfLink is a URL representing this object. Populated by the system. Read-only. // // DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release. public selfLink?: string; } } export type BigQueryJob = object; // BigQueryJobList is a list of BigQueryJob export class BigQueryJobList { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources public apiVersion: string; // List of bigqueryjobs. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md public items: BigQueryJob[]; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds public kind: string; // ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}. public metadata?: BigQueryJobList.Metadata; constructor(desc: BigQueryJobList) { this.apiVersion = BigQueryJobList.apiVersion; this.items = desc.items; this.kind = BigQueryJobList.kind; this.metadata = desc.metadata; } } export function isBigQueryJobList(o: any): o is BigQueryJobList { return ( o && o.apiVersion === BigQueryJobList.apiVersion && o.kind === BigQueryJobList.kind ); } export namespace BigQueryJobList { export const apiVersion = 'bigquery.cnrm.cloud.google.com/v1beta1'; export const group = 'bigquery.cnrm.cloud.google.com'; export const version = 'v1beta1'; export const kind = 'BigQueryJobList'; // BigQueryJobList is a list of BigQueryJob export interface Interface { // List of bigqueryjobs. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md items: BigQueryJob[]; // ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}. metadata?: BigQueryJobList.Metadata; } // ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}. export class Metadata { // continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message. public continue?: string; // remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact. public remainingItemCount?: number; // String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency public resourceVersion?: string; // selfLink is a URL representing this object. Populated by the system. Read-only. // // DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release. public selfLink?: string; } } export type BigQueryTable = object; // BigQueryTableList is a list of BigQueryTable export class BigQueryTableList { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources public apiVersion: string; // List of bigquerytables. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md public items: BigQueryTable[]; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds public kind: string; // ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}. public metadata?: BigQueryTableList.Metadata; constructor(desc: BigQueryTableList) { this.apiVersion = BigQueryTableList.apiVersion; this.items = desc.items; this.kind = BigQueryTableList.kind; this.metadata = desc.metadata; } } export function isBigQueryTableList(o: any): o is BigQueryTableList { return ( o && o.apiVersion === BigQueryTableList.apiVersion && o.kind === BigQueryTableList.kind ); } export namespace BigQueryTableList { export const apiVersion = 'bigquery.cnrm.cloud.google.com/v1beta1'; export const group = 'bigquery.cnrm.cloud.google.com'; export const version = 'v1beta1'; export const kind = 'BigQueryTableList'; // BigQueryTableList is a list of BigQueryTable export interface Interface { // List of bigquerytables. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md items: BigQueryTable[]; // ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}. metadata?: BigQueryTableList.Metadata; } // ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}. export class Metadata { // continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message. public continue?: string; // remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact. public remainingItemCount?: number; // String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency public resourceVersion?: string; // selfLink is a URL representing this object. Populated by the system. Read-only. // // DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release. public selfLink?: string; } }
the_stack
import {describe, it, afterEach} from 'mocha'; import * as path from 'path'; import * as is from 'is'; import * as sinon from 'sinon'; import * as prototypes from '../protos/protos'; import * as assert from 'assert'; // eslint-disable-next-line @typescript-eslint/no-var-requires const vision = require('../src'); describe('Vision helper methods', () => { const CREDENTIALS = { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }; const sandbox = sinon.createSandbox(); afterEach(() => { sandbox.restore(); }); describe('annotateImage', () => { it('calls batchAnnotateImages correctly', () => { const client = new vision.v1.ImageAnnotatorClient(CREDENTIALS); const batchAnnotate = sandbox.stub(client, 'batchAnnotateImages'); batchAnnotate.callsArgWith(2, undefined, { responses: [ { logoAnnotations: [{description: 'Google'}], }, ], }); // Ensure that the annotateImage method arrifies the request and // passes it through to the batch annotation method. const request = { image: {content: Buffer.from('bogus==')}, features: {type: ['LOGO_DETECTION']}, }; return client .annotateImage(request) .then( (r: [prototypes.google.cloud.vision.v1.IAnnotateImageResponse]) => { const response = r[0]; // Ensure that we got the slice of the response that we expected. assert.deepStrictEqual(response, { logoAnnotations: [{description: 'Google'}], }); // Inspect the calls to batchAnnotateImages and ensure they matched // the expected signature. assert(batchAnnotate.callCount === 1); assert(batchAnnotate.calledWith({requests: [request]})); } ); }); it('understands buffers in a request object', () => { const client = new vision.v1.ImageAnnotatorClient(CREDENTIALS); // Stub out the batch annotation method. const batchAnnotate = sandbox.stub(client, 'batchAnnotateImages'); batchAnnotate.callsArgWith(2, undefined, { responses: [ { logoAnnotations: [{description: 'Google'}], }, ], }); // Ensure that the annotateImage method arrifies the request and // passes it through to the batch annotation method. const request = { image: Buffer.from('fakeImage'), features: {type: ['LOGO_DETECTION']}, }; return client .annotateImage(request) .then( (r: [prototypes.google.cloud.vision.v1.IAnnotateImageResponse]) => { const response = r[0]; // Ensure that we got the slice of the response that we expected. assert.deepStrictEqual(response, { logoAnnotations: [{description: 'Google'}], }); // Inspect the calls to batchAnnotateImages and ensure they matched // the expected signature. assert(batchAnnotate.callCount === 1); assert.deepStrictEqual(request, { image: {content: 'ZmFrZUltYWdl'}, features: {type: ['LOGO_DETECTION']}, }); assert(batchAnnotate.calledWith({requests: [request]})); } ); }); it('understands filenames', () => { const client = new vision.v1.ImageAnnotatorClient(CREDENTIALS); // Stub out the batch annotation method as before. const batchAnnotate = sandbox.stub(client, 'batchAnnotateImages'); batchAnnotate.callsArgWith(2, undefined, { responses: [ { logoAnnotations: [{description: 'Google'}], }, ], }); // Ensure that the annotateImage method arrifies the request and // passes it through to the batch annotation method. const imagePath = path.join( __dirname, '..', '..', 'test', 'fixtures', 'image.jpg' ); const request = { image: {source: {filename: imagePath}}, features: {type: ['LOGO_DETECTION']}, }; return client .annotateImage(request) .then( (r: [prototypes.google.cloud.vision.v1.IAnnotateImageResponse]) => { const response = r[0]; // Ensure that we got the slice of the response that we expected. assert.deepStrictEqual(response, { logoAnnotations: [{description: 'Google'}], }); // Inspect the calls to batchAnnotateImages and ensure they matched // the expected signature. assert(batchAnnotate.callCount === 1); assert.deepStrictEqual(request, { image: {content: ''}, features: {type: ['LOGO_DETECTION']}, }); assert(batchAnnotate.calledWith({requests: [request]})); } ); }); it('propagates the error if a file is not found', () => { const client = new vision.v1.ImageAnnotatorClient(CREDENTIALS); // Ensure that the annotateImage method arrifies the request and // passes it through to the batch annotation method. const request = { image: {source: {filename: 'image.jpg'}}, features: {type: ['LOGO_DETECTION']}, }; return client.annotateImage(request).catch((err: string) => { assert( err.toString().match(/Error: ENOENT: no such file or directory/) ); }); }); it('retains call options sent', () => { const client = new vision.v1.ImageAnnotatorClient(CREDENTIALS); const batchAnnotate = sandbox.stub(client, 'batchAnnotateImages'); batchAnnotate.callsArgWith(2, undefined, { responses: [ { logoAnnotations: [{description: 'Google'}], }, ], }); // Ensure that the annotateImage method arrifies the request and // passes it through to the batch annotation method. const request = { image: {content: Buffer.from('bogus==')}, features: {type: ['LOGO_DETECTION']}, }; return client .annotateImage(request, {foo: 'bar'}) .then( (r: [prototypes.google.cloud.vision.v1.IAnnotateImageResponse]) => { const response = r[0]; // Ensure that we got the slice of the response that we expected. assert.deepStrictEqual(response, { logoAnnotations: [{description: 'Google'}], }); // Inspect the calls to batchAnnotateImages and ensure they matched // the expected signature. assert(batchAnnotate.callCount === 1); assert( batchAnnotate.calledWith({requests: [request]}, {foo: 'bar'}) ); } ); }); it('fires a callback if provided', done => { const client = new vision.v1.ImageAnnotatorClient(CREDENTIALS); const batchAnnotate = sandbox.stub(client, 'batchAnnotateImages'); batchAnnotate.callsArgWith(2, undefined, { responses: [ { logoAnnotations: [{description: 'Google'}], }, ], }); // Ensure that the annotateImage method does *not* pass the callback // on to batchAnnotateImages, but rather handles it itself. const request = { image: {content: Buffer.from('bogus==')}, features: {type: ['LOGO_DETECTION']}, }; client.annotateImage(request, (err: {}, response: {}) => { // Establish that we got the expected response. assert(is.undefined(err)); assert.deepStrictEqual(response, { logoAnnotations: [{description: 'Google'}], }); // Inspect the calls to batchAnnotate and ensure that they match // what we expected. assert(batchAnnotate.callCount === 1); assert(batchAnnotate.calledWith({requests: [request]}, undefined)); done(); }); }); it('fires the callback on error', () => { const client = new vision.v1.ImageAnnotatorClient(CREDENTIALS); const batchAnnotate = sandbox.stub(client, 'batchAnnotateImages'); batchAnnotate.callsArgWith(2, {message: 'Bad things!'}); // Ensure that the annotateImage method does *not* pass the callback // on to batchAnnotateImages, but rather handles it itself. const request = { image: {content: Buffer.from('bogus==')}, features: {type: ['LOGO_DETECTION']}, }; return client.annotateImage(request).catch((err: {}) => { // Establish that we got the expected response. assert.deepStrictEqual(err, {message: 'Bad things!'}); // Inspect the calls to batchAnnotate and ensure that they match // what we expected. assert(batchAnnotate.callCount === 1); assert(batchAnnotate.calledWith({requests: [request]}, undefined)); }); }); it('requires an image and throws without one', () => { const client = new vision.v1.ImageAnnotatorClient(CREDENTIALS); const request = {}; return client.annotateImage(request).catch((err: string) => { assert(err.toString().match(/Error: No image present./)); }); }); }); describe('single-feature methods', () => { it('call `annotateImage` with the correct feature', () => { const client = new vision.v1.ImageAnnotatorClient(CREDENTIALS); const annotate = sandbox.spy(client, 'annotateImage'); const batchAnnotate = sandbox.stub(client, 'batchAnnotateImages'); batchAnnotate.callsArgWith(2, undefined, { responses: [ { logoAnnotations: [{description: 'Google'}], }, ], }); // Ensure that the annotateImage method does *not* pass the callback // on to batchAnnotateImages, but rather handles it itself. const imageRequest = {image: {content: Buffer.from('bogus==')}}; return client .logoDetection(Object.assign({}, imageRequest)) .then( (r: [prototypes.google.cloud.vision.v1.IAnnotateImageResponse]) => { const response = r[0]; // Ensure that we got the slice of the response that we expected. assert.deepStrictEqual(response, { logoAnnotations: [{description: 'Google'}], }); // Inspect the calls to annotateImage and batchAnnotateImages and // ensure they matched the expected signature. assert(annotate.callCount === 1); assert( annotate.calledWith({ features: [{type: 3}], image: imageRequest.image, }) ); assert(batchAnnotate.callCount === 1); assert( batchAnnotate.calledWith({ requests: [{image: imageRequest.image, features: [{type: 3}]}], }) ); } ); }); it('accept a URL as a string', () => { const client = new vision.v1.ImageAnnotatorClient(CREDENTIALS); // Stub out the batch annotation method. const batchAnnotate = sandbox.stub(client, 'batchAnnotateImages'); batchAnnotate.callsArgWith(2, undefined, { responses: [ { logoAnnotations: [{description: 'Google'}], }, ], }); // Call a request to a single-feature method using a URL. return client .logoDetection('https://goo.gl/logo.png') .then( (r: [prototypes.google.cloud.vision.v1.IAnnotateImageResponse]) => { const response = r[0]; // Ensure we got the slice of the response that we expected. assert.deepStrictEqual(response, { logoAnnotations: [{description: 'Google'}], }); // Inspect the calls to batchAnnotateImages and ensure they matched // the expected signature. assert(batchAnnotate.callCount === 1); assert( batchAnnotate.calledWith({ requests: [ { image: {source: {imageUri: 'https://goo.gl/logo.png'}}, features: [{type: 3}], }, ], }) ); } ); }); it('accept a filename as a string', () => { const client = new vision.v1.ImageAnnotatorClient(CREDENTIALS); // Stub out the batch annotation method. const annotate = sandbox.stub(client, 'annotateImage'); annotate.callsArgWith(2, undefined, { logoAnnotations: [{description: 'Google'}], }); // Call a request to a single-feature method using a URL. return client.logoDetection('/path/to/logo.png').then((response: {}) => { // Ensure we got the slice of the response that we expected. assert.deepStrictEqual(response, [ { logoAnnotations: [{description: 'Google'}], }, ]); // Inspect the calls to annotateImages and ensure they matched // the expected signature. assert(annotate.callCount === 1); assert( annotate.calledWith({ image: {source: {filename: '/path/to/logo.png'}}, features: [{type: 3}], }) ); }); }); it('understand a buffer sent directly', () => { const client = new vision.v1.ImageAnnotatorClient(CREDENTIALS); // Stub out the batch annotation method. const batchAnnotate = sandbox.stub(client, 'batchAnnotateImages'); batchAnnotate.callsArgWith(2, undefined, { responses: [ { logoAnnotations: [{description: 'Google'}], }, ], }); // Ensure that the annotateImage method arrifies the request and // passes it through to the batch annotation method. return client .logoDetection(Buffer.from('fakeImage')) .then( (r: [prototypes.google.cloud.vision.v1.IAnnotateImageResponse]) => { const response = r[0]; // Ensure that we got the slice of the response that we expected. assert.deepStrictEqual(response, { logoAnnotations: [{description: 'Google'}], }); // Inspect the calls to batchAnnotateImages and ensure they matched // the expected signature. assert(batchAnnotate.callCount === 1); assert( batchAnnotate.calledWith({ requests: [ { image: {content: 'ZmFrZUltYWdl'}, features: [{type: 3}], }, ], }) ); } ); }); it('handle being sent call options', () => { const client = new vision.v1.ImageAnnotatorClient(CREDENTIALS); const opts = {foo: 'bar'}; // Stub out the batchAnnotateImages method as usual. const batchAnnotate = sandbox.stub(client, 'batchAnnotateImages'); batchAnnotate.callsArgWith(2, undefined, { responses: [ { logoAnnotations: [{description: 'Google'}], }, ], }); // Perform the request. Send `opts` as an explicit second argument // to ensure that sending call options works appropriately. return client .logoDetection(Buffer.from('fakeImage'), opts) .then( (r: [prototypes.google.cloud.vision.v1.IAnnotateImageResponse]) => { const response = r[0]; assert.deepStrictEqual(response, { logoAnnotations: [{description: 'Google'}], }); // Inspect the calls to batchAnnotateImages and ensure they matched // the expected signature. assert(batchAnnotate.callCount === 1); assert( batchAnnotate.calledWith({ requests: [ { image: {content: 'ZmFrZUltYWdl'}, features: [{type: 3}], }, ], }) ); } ); }); it('throw an exception if conflicting features are given', () => { const client = new vision.v1.ImageAnnotatorClient(CREDENTIALS); const imageRequest = { image: {content: Buffer.from('bogus==')}, features: [{type: 0}], }; client.logoDetection(imageRequest).catch((err: string) => { assert(err.toString().match(/Setting explicit/)); }); }); it('creates and promisify methods that are available in certain versions', () => { const client = new vision.v1p3beta1.ImageAnnotatorClient(CREDENTIALS); const request = { image: { source: { imageUri: 'https://cloud.google.com/vision/docs/images/bicycle.jpg', }, }, }; const batchAnnotate = sandbox.stub(client, 'batchAnnotateImages'); batchAnnotate.callsArgWith(2, undefined, { responses: [ { localizedObjectAnnotations: [{dummy: 'response'}], }, ], }); client .productSearch(request) .then( (r: [prototypes.google.cloud.vision.v1.IAnnotateImageResponse]) => { const response = r[0]; assert.deepStrictEqual(response, { localizedObjectAnnotations: [{dummy: 'response'}], }); assert(batchAnnotate.callCount === 1); assert(batchAnnotate.calledWith({requests: [request]})); } ) .catch(assert.ifError); }); it('throws an error if trying to invoke a method not available in current version', () => { // Use v1p1beta1 version of client. const client = new vision.v1p1beta1.ImageAnnotatorClient(CREDENTIALS); if (typeof client['objectLocalization'] === 'function') { assert.fail('objectLocalization does not exist in v1p1beta1'); } }); }); });
the_stack
module TDev { export class IntelliItem { public score = 0; public prop:IProperty; public decl:AST.Decl; public nameOverride:string; public imageOverride:string; public lowSearch:boolean; // demote in keyboard search public descOverride:string; public colorOverride:string; public tick = Ticks.noEvent; public iconOverride:string; public cbOverride:(i:IntelliItem)=>void; public isWide = false; public lastMatchScore = 0; public isAttachedTo:Kind = null; public usageKey:string; public cornerIcon:string; public noButton: boolean; public matchAny: boolean; public getName() { if (!!this.nameOverride) return this.nameOverride; if (!!this.prop) return this.prop.getName(); if (this.decl instanceof AST.SingletonDef && this.decl.getName() == AST.libSymbol) return "libs"; return this.decl.getName(); } public alphaOverride() { if (this.cbOverride) return 30; if (this.decl instanceof AST.LocalDef) return 20; if (this.prop instanceof AST.GlobalDef) return 15; if (this.decl && this.decl.getKind() instanceof ThingSetKind) return -1; if (this.prop instanceof AST.LibraryRef) return 5; if (this.prop && !Script.canUseProperty(this.prop)) return -10; if (this.matchAny) return -1e10; if (Cloud.isRestricted() && TheEditor.intelliProfile) { if (this.decl instanceof AST.SingletonDef) { var order = TheEditor.intelliProfile.getSingletonOrder(this.decl.getName()) if (!order) return 0; else return (1000 - order) / 1000 } if (this.prop instanceof AST.LibraryRefAction) { return (<AST.LibraryRefAction>this.prop)._weight * 1e-10; } } return 0; } public getLongName() { if (!!this.nameOverride) return "\u00a0[" + this.nameOverride + "]"; var d:any = this.decl; if (!d && this.prop) d = this.prop.forwardsTo(); if (!d) d = this.prop; var n = d.getName(); if (!(d instanceof AST.LibraryRefAction) && d.getNamespace) { n = d.getNamespace() + n; } else if (d.getNamespaces && d.getNamespaces()[0]) { n = d.getNamespaces()[0] + (this.prop ? this.prop.getArrow() : " ") + n; } else if (this.isAttachedTo) n = this.isAttachedTo.getPropPrefix() + (this.prop ? this.prop.getArrow() : " ") + n; else if (this.prop) n = this.prop.getArrow() + n; return n; } private shortName() { if (!!this.decl && this.decl instanceof AST.SingletonDef) return this.decl.getKind().shortName(); else if (this.prop && this.prop instanceof AST.LibraryRef) return AST.libSymbol; else if (this.prop && this.prop instanceof AST.GlobalDef) return (<AST.GlobalDef>this.prop).isResource ? AST.artSymbol : AST.dataSymbol; return null; } private getDesc(skip?:boolean) { if (!!this.descOverride) return this.descOverride; return "" //if (!!this.prop) return this.prop.getDescription(skip); //return this.decl.getDescription(skip); } private onClick() { var calc = TDev.TheEditor.calculator; if (this.tick) tick(this.tick) calc.searchApi.cancelImplicitInsert(); if (!!this.cbOverride) this.cbOverride(this); else { if (!!this.prop) { calc.insertProp(this.prop, this.isAttachedTo != null); } else if (!!this.decl) { calc.insertThing(this.decl); } } calc.hideBottomScroller(); } public mkBox(options?: DeclBoxOptions) : HTMLElement { var box:HTMLElement = null; if (this.decl) box = DeclRender.mkBox(this.decl, options); else if (this.prop) { if (!this.isAttachedTo) { box = DeclRender.mkPropBox(this.prop, options); } else { this.prop.useFullName = true; box = DeclRender.mkPropBox(this.prop, options); this.prop.useFullName = false; } } else { var de = new DeclEntry(this.getName()); de.color = this.getColor(); de.description = this.getDesc(); if (this.imageOverride) { de.icon = this.imageOverride; de.color = 'white'; } else if (this.iconOverride) de.icon = this.iconOverride; box = DeclRender.mkBox(<any> de); } if (!!this.isAttachedTo) box.className += " attachedItem"; return box.withClick(() => this.onClick()); } private nameIsOp() { var n = this.getName(); return n == ":=" || (n.length == 1 && !/[a-zA-Z]/.test(n)); } public apply(c:CalcButton, idx:number) : void { var par = this.prop ? this.prop.parentKind : null var arrow = null if (!SizeMgr.phoneMode && par && !par.shortName() && !this.prop.getInfixPriority()) arrow = span("calcArrow", this.prop.getArrow()) var sn = this.shortName(); var inner:HTMLElement; if (sn) inner = div("calcOp", [span("symbol", sn + " "), span("", this.getName())]) else inner = div("calcOp", [arrow, text(this.getName())]) var triangle = idx >= 0; inner.style.fontSize = this.nameIsOp() ? "1.2em" : (this.getName().length >= 18 ? "0.6em" : "0.8em"); var help = this.getDesc() if (help.length > 14) help = "" var fn = () => { if (idx >= 0) { tick(Ticks.calcIntelliButton) tickN(Ticks.calcIntelliButton0, idx) } TDev.Browser.EditorSoundManager.intellibuttonClick(); this.onClick() } if (this.imageOverride) c.setImage(this.imageOverride, help, Ticks.noEvent, fn) else c.setHtml(inner, help, fn); var b = c.getButton(); if (triangle) { if (this.cornerIcon) { var d = div("calcButtonCornerIcon", SVG.getIconSVG(this.cornerIcon)) b.appendChild(d) } else { var cc = this.getColor(); if (DeclRender.propColor(this.prop)) { d = div("calcButtonColorMarker"); b.appendChild(d); d.style.backgroundColor = cc; } else { d = div("calcButtonTriangle", ""); b.appendChild(d); d.style.borderTopColor = cc; d.style.borderRightColor = cc; } } c._theButton.className = "calcButton calcIntelliButton" } else { c._theButton.className = "calcButton calcStmtButton" } // display picture art in button if (this.prop instanceof TDev.AST.GlobalDef) { var gd = <TDev.AST.GlobalDef>this.prop; if (gd.isResource && gd.getKind().getName() == "Picture" && Cloud.isArtUrl(gd.url)) { c.setBackgroundImage(gd.url); inner.style.backgroundColor = 'rgba(238,238,255,0.5)'; } } c.intelliItem = this; } private getColor() { var c = "blue"; if (!!this.colorOverride) return this.colorOverride; if (!!this.decl) c = DeclRender.declColor[this.decl.nodeType()](this.decl); else if (this.prop instanceof AST.PropertyDecl) c = DeclRender.declColor[(<any>this.prop).nodeType()](this.prop); else if (!!this.prop) c = DeclRender.declColor["property"](this.prop); return c; } static matchString(s:string, terms:string[], begMatch:number, wordMatch:number, match:number) { if (terms.length == 0) return begMatch; var res = 0; for (var i = 0; i < terms.length; ++i) { var idx = s.indexOf(terms[i]); if (idx < 0) return 0; if (idx >= 0) { if (idx == 0) { res += begMatch; } else { idx = s.indexOf(" " + terms[i]); if (idx >= 0) res += wordMatch; else res += match; } } } return res; } static matchProp(p:IProperty, terms:string[], fullName:string) { if (!p.isBrowsable()) return 0; if (terms.length == 0) return 10000; var pp:IPropertyWithCache = p.canCacheSearch() ? <IPropertyWithCache>p : null; var n:string; if (pp && pp.cacheShort) { n = pp.cacheShort; } else { n = (p.getName() + " " + (!p.parentKind ? "" : p.parentKind.toString())).toLowerCase(); if (pp) pp.cacheShort = n; } var r = IntelliItem.matchString(n, terms, 10000, 1000, 100); if (r > 0) { if (p.getName().toLowerCase().replace(/[^a-z0-9]/g, "") == fullName) r += 100000; return r; } var lng:string; if (pp && pp.cacheLong) { lng = pp.cacheLong; } else { lng = (n + p.getSignature() + " " + p.getDescription(true)).toLowerCase(); if ((<any>p).forSearch) lng += " " + (<any>p).forSearch().toLowerCase() if (pp) pp.cacheLong = lng } return IntelliItem.matchString(lng, terms, 100, 10, 1); } static thereIsMore() { var dotdotdot = new IntelliItem(); dotdotdot.nameOverride = lf("... there's more ..."); dotdotdot.descOverride = lf("just keep typing the search terms!"); return dotdotdot.mkBox(); } // Returns match quality public match(terms:string[], fullName:string) { if (this.matchAny) return this.score; if (!!this.prop) return IntelliItem.matchProp(this.prop, terms, fullName); if (terms.length == 0) return 1; var lowerName = this.getName().toLowerCase(); var r = IntelliItem.matchString(lowerName, terms, 10000, 1000, 100); if (r > 0) { if (lowerName.replace(/[^a-z0-9]/g, "") == fullName) r += 100000; return r; } return IntelliItem.matchString((this.getName() + " " + this.getDesc(true)).toLowerCase(), terms, 100, 10, 1); } static cmpName(a: IntelliItem, b: IntelliItem) { return b.alphaOverride() - a.alphaOverride() || Util.stringCompare(a.getName(), b.getName()); } static cmpScoreThenName(a: IntelliItem, b: IntelliItem) { return b.lastMatchScore - a.lastMatchScore || b.score - a.score || IntelliItem.cmpName(a, b); } } }
the_stack
* Common utilities used in the hparams plugin. */ import * as d3 from 'd3'; import * as _ from 'lodash'; // ----------------------------------------------------------------------- // Functions for dealing with HParams, Metrics, Columns, // SessionGroups and Schema objects. // In the following routines we use the following naming conventions for // parameters: // // hparamInfo, metricInfo: A JavaScript object representation of the // HParamInfo proto defined in api.proto. // schema: The object storing metadata on the metrics and hparams used // in the experiment. See the documentation in // 'tf-hparams-query-pane.html'. // visibleSchema: The object storing metadata on just the visible metrics // and hparams in 'schema'. This is the object stored in the property // 'visibleSchema' of 'configuration' (see the documentation in // tf-hparams-query-pane.html' for more details). This object and the // utility functions below that accept it are deprecated and the // intention is to eventually remove them. // New code should instead filter the entries in the schema object // directly to find all the visible columns and only use the functions // below that take a 'schema' object. // sessionGroup: A JavaScript object representation of the SessionGroup // proto defined in api.proto. // sessionGroups: An array of 'sessionGroup' objects. // columnIndex: An index of a 'column' of a sessionGroup with respect // to a schema or visibleSchema object. We regard a // sessionGroup as a row in a table where the columns represent // hparams and metric values for the session group. The columns are // ordered by listing the hparam columns first in the same order as // the corresponding elements of schema.hparamColumns or // visibleSchema.hparamInfos, followed by the // metric columns in the same order as the corresponding elements of // schema.metricColumns or visibleSchema.metricInfos. Whether the // index is given with respect to a schema or a visibleScheme depends // on the type of schema parameter the utility function below accepts // in addition to the columnIndex parameter. // ----------------------------------------------------------------------- // Computes the name to display for the given 'hparamInfo' object. export function hparamName(hparamInfo) { if (hparamInfo.displayName !== '' && hparamInfo.displayName !== undefined) { return hparamInfo.displayName; } return hparamInfo.name; } // Computes the name to display for the given metricInfo object. export function metricName(metricInfo) { if (metricInfo.displayName !== '' && metricInfo.displayName !== undefined) { return metricInfo.displayName; } let group = metricInfo.name.group; let tag = metricInfo.name.tag; if (group === undefined) { group = ''; } if (tag === undefined) { tag = ''; } if (group === '') { return tag; } return group + '.' + tag; } export function schemaColumnName(schema, columnIndex) { if (columnIndex < schema.hparamColumns.length) { return hparamName(schema.hparamColumns[columnIndex].hparamInfo); } const metricIndex = columnIndex - schema.hparamColumns.length; return metricName(schema.metricColumns[metricIndex].metricInfo); } // Returns the number of hparams in schema (visible and invisible). export function numHParams(schema) { return schema.hparamColumns.length; } // Returns the number of metrics in schema (visible and invisible). export function numMetrics(schema) { return schema.metricColumns.length; } // Returns the number of columns in schema (visible and invisible). export function numColumns(schema) { return numHParams(schema) + numMetrics(schema); } // Returns hparamValues[hparamName]. To be used in a Polymer databinding // annotation (as Polymer doesn't have an annotation for looking up a // property in an JS object). export function hparamValueByName(hparamValues, hparamName) { return hparamValues[hparamName]; } // Given an array 'metricValues' of (javascript object representation) of // tensorboard.hparams.MetricValue's protocol buffers, returns the first // element whose metric name is 'metricName' or undefined if no such // element exists. export function metricValueByName(metricValues, metricName) { return metricValues.find((mv) => _.isEqual(mv.name, metricName)); } // Returns sessionGroup's metric value of the metric with index // 'metricIndex' in schema.metricColumns. export function hparamValueByIndex(schema, sessionGroup, hparamIndex) { return sessionGroup.hparams[ schema.hparamColumns[hparamIndex].hparamInfo.name ]; } // Returns sessionGroup's metric value of the metric with index // 'metricIndex' in schema.metricColumns. export function metricValueByIndex(schema, sessionGroup, metricIndex) { const metricName = schema.metricColumns[metricIndex].metricInfo.name; const metricValue = metricValueByName(sessionGroup.metricValues, metricName); return metricValue === undefined ? undefined : metricValue.value; } // Returns sessionGroup's column value of the column with index // 'columnIndex' in schema. export function columnValueByIndex(schema, sessionGroup, columnIndex) { if (columnIndex < schema.hparamColumns.length) { return hparamValueByIndex(schema, sessionGroup, columnIndex); } return metricValueByIndex( schema, sessionGroup, columnIndex - schema.hparamColumns.length ); } // Returns an array [min, max] representing the minimum and maximum // value of the given column in the sessionGroups array. // Ignores session groups with missing values for the column. export function numericColumnExtent(schema, sessionGroups, columnIndex) { return d3.extent(sessionGroups, (sg) => columnValueByIndex(schema, sg, columnIndex) ); } // Converts a visibleSchema columnIndex to a schema columnIndex. // Returns the schema-relative columnIndex for the visible column with // visibleSchema-releative columnIndex given by 'visibleColumnIndex'. export function getAbsoluteColumnIndex( schema, visibleSchema, visibleColumnIndex ) { let result; if (visibleColumnIndex < visibleSchema.hparamInfos.length) { result = schema.hparamColumns.findIndex( (c) => c.hparamInfo.name === visibleSchema.hparamInfos[visibleColumnIndex].name ); } else { const metricIndex = visibleColumnIndex - visibleSchema.hparamInfos.length; const metricName = visibleSchema.metricInfos[metricIndex].name; result = schema.hparamColumns.length + schema.metricColumns.findIndex((c) => c.metricInfo.name === metricName); } console.assert(result !== -1); return result; } // DEPRECATED. Use schemaColumnName instead (with an "absolute" // columnIndex). // Computes the name to display for the given visible column index. export function schemaVisibleColumnName(visibleSchema, columnIndex) { if (columnIndex < visibleSchema.hparamInfos.length) { return hparamName(visibleSchema.hparamInfos[columnIndex]); } const metricIndex = columnIndex - visibleSchema.hparamInfos.length; return metricName(visibleSchema.metricInfos[metricIndex]); } // DEPRECATED. Use numDisplayedHParams instead. // Returns the number of hparams in visibleSchema. This is the same // value as numDisplayedHParams(schema) with schema being the "containing" // schema of visibleSchema. export function numVisibleHParams(visibleSchema) { return visibleSchema.hparamInfos.length; } // DEPRECATED. Use numDisplayedMetrics instead. // Returns the number of hparams in visibleSchema. This is the same // value as numDisplayedMetrics(schema) with schema being the "containing" // schema of visibleSchema. export function numVisibleMetrics(visibleSchema) { return visibleSchema.metricInfos.length; } // DEPRECATED. // Returns the number of visible columns (having 'displayed' true). // This is the same value as numDisplayedColumns(schema) with schema // being the "containing" schema of visibleSchema. export function numVisibleColumns(visibleSchema) { return numVisibleHParams(visibleSchema) + numVisibleMetrics(visibleSchema); } // DEPRECATED. Use numericColumnExtent with a schema columnIndex instead. // Returns an array [min, max] representing the minimum and maximum // value of the given visible column in the sessionGroups array. // Ignores session groups with missing values for the column. export function visibleNumericColumnExtent( visibleSchema, sessionGroups, columnIndex ) { return d3.extent(sessionGroups, (sg) => columnValueByVisibleIndex(visibleSchema, sg, columnIndex) ); } // Returns a string representation of hparamValues[hparamName] suitable // for display. export function prettyPrintHParamValueByName(hparamValues, hparamName) { return prettyPrint(hparamValueByName(hparamValues, hparamName)); } // Returns a string representation of metricValueByName suitable for // display. export function prettyPrintMetricValueByName(metricValues, metricName) { return prettyPrint(metricValueByName(metricValues, metricName)); } // Returns the session group with name 'name' in sessionGroups or // undefined of no such element exist. export function sessionGroupWithName(sessionGroups, name) { return sessionGroups.find((sg) => sg.name === name); } // DEPRECATED. Use hparamValueByIndex with a schema hparamIndex instead. // Returns sessionGroup's hparam value of the visible hparam with index // 'hparamIndex' in visibleSchema.hparamInfos. export function hparamValueByVisibleIndex( visibleSchema, sessionGroup, hparamIndex ) { return sessionGroup.hparams[visibleSchema.hparamInfos[hparamIndex].name]; } // DEPRECATED. Use metricValueByIndex with a schema metricIndex instead. // Returns sessionGroup's metric value of the visible metric with index // 'metricIndex' in visibleSchema.metricInfos. export function metricValueByVisibleIndex( visibleSchema, sessionGroup, visibleMetricIndex ) { const metricName = visibleSchema.metricInfos[visibleMetricIndex].name; const metricValue = metricValueByName(sessionGroup.metricValues, metricName); return metricValue === undefined ? undefined : metricValue.value; } // DEPRECATED. Use columnValueByIndex with a schema columnIndex instead. // Returns sessionGroup's column value of the visible column with index // 'columnIndex' in visibleSchema. export function columnValueByVisibleIndex( visibleSchema, sessionGroup, columnIndex ) { if (columnIndex < visibleSchema.hparamInfos.length) { return hparamValueByVisibleIndex(visibleSchema, sessionGroup, columnIndex); } return metricValueByVisibleIndex( visibleSchema, sessionGroup, columnIndex - visibleSchema.hparamInfos.length ); } // ---- Misc functions --------------------------------------------------- // Returns a string representation of 'value' suitable for display. export function prettyPrint(value) { if (_.isNumber(value)) { // TODO(erez):Make the precision user-configurable. return value.toPrecision(5); } if (value === undefined) { return ''; } return value.toString(); } // Returns the square of the L2-norm of (x, y). export function l2NormSquared(x, y) { return x * x + y * y; } // Returns the euclidean distance between (x0, y0) and (x1, y1). export function euclideanDist(x0, y0, x1, y1) { return Math.sqrt(l2NormSquared(x0 - x1, y0 - y1)); } // Returns the (euclidean) distance between the point (x, y) and the // rectangle [x0, x1) x [y0, y1). export function pointToRectangleDist(x, y, x0, y0, x1, y1) { if (x < x0 && y < y0) { return euclideanDist(x, y, x0, y0); } else if (x0 <= x && x < x1 && y < y0) { return y0 - y; } else if (x1 <= x && y < y0) { return euclideanDist(x, y, x1, y0); } else if (x < x0 && y0 <= y && y < y1) { return x0 - x; } else if (x0 <= x && x < x1 && y0 <= y && y < y1) { return 0; } else if (x1 <= x && y0 <= y && y < y1) { return x - x1; } else if (x < x0 && y1 <= y) { return euclideanDist(x, y, x0, y1); } else if (x0 <= x && x < x1 && y1 <= y) { return y - y1; } else if (x1 <= x && y1 <= y) { return euclideanDist(x, y, x1, y1); } else { throw 'Point (x,y) must be in one of the regions defined above.'; } } // SVG elements such as <g> can optionally have a "transform" attribute // the alters the way the element and its children are drawn. // The following function helps generate a "translate function" value // for this attribute. // See // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform // for more details. export function translateStr(x, opt_y?: any) { if (opt_y === undefined) { return 'translate(' + x + ')'; } return 'translate(' + x + ',' + opt_y + ')'; } // SVG elements such as <g> can optionally have a "transform" attribute // the alters the way the element and its children are drawn. // The following function helps generate a "rotate function" value // for this attribute. // See // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform // for more details. export function rotateStr(angle, x, y) { let result = 'rotate(' + angle; if (x !== undefined && y !== undefined) { result = result + ',' + x + ',' + y; } result = result + ')'; return result; } export function isNullOrUndefined(x) { return x === null || x === undefined; } // Given a d3.quadTree object, visits all the points in it // that lie inside the rectangle [x0, x1) x [y0, y1). // For each such point calls the given callback, passing the // point's quadtree data. export function quadTreeVisitPointsInRect(quadTree, x0, y0, x1, y1, callback) { quadTree.visit((node, nx0, ny0, nx1, ny1) => { // Represents the set of points [nx0, nx1) x [ny0, ny1). if (node.length === undefined) { do { const x = quadTree.x()(node.data); const y = quadTree.y()(node.data); if (x0 <= x && x < x1 && y0 <= y && y < y1) { callback(node.data); } } while ((node = node.next)); return true; } // Skip this node if Intersection([nx0, nx1) x [ny0, ny1), // [x0, x1) x [y0, y1)) is empty, or equivalently, if // either Intersection([nx0, nx1), [x0, x1)) or // Intersection([ny0, ny1), [y0, y1)) is empty. return nx0 >= x1 || nx1 <= x0 || ny0 >= y1 || ny1 <= y0; }); } // Given a d3.quadTree object, visits all the points in it // that lie inside the closed disk centered at (centerX, centerY) // with the given radius. // For each such point calls the given callback, passing the // point's quadtree data and the distance from the point to the center // of the disk. export function quadTreeVisitPointsInDisk( quadTree, centerX, centerY, radius, callback ) { quadTree.visit((node, x0, y0, x1, y1) => { // Represents the set of points [x0, x1) x [y0, y1). if (node.length === undefined) { do { const x = quadTree.x()(node.data); const y = quadTree.y()(node.data); const centerDist = euclideanDist(centerX, centerY, x, y); if (centerDist <= radius) { callback(node.data, centerDist); } } while ((node = node.next)); return true; } // Skip nodes that represent a rectangle that does not intersect the // disk. Equivalently, skip nodes that represent a rectangle whose // distance to (centerX, centerY) is larger than radius. return pointToRectangleDist(centerX, centerY, x0, y0, x1, y1) > radius; }); } // Returns a Set consisting of all elements in 'set' for which // predicateFn evaluates to a truthy value. export function filterSet(set, predicateFn) { const result = new Set(); set.forEach((val) => { if (predicateFn(val)) { result.add(val); } }); return result; } // Sets the array property of polymerElement to 'newArray' in // a Polymer-"observable" manner, so that other elements that have // the array as a property (like a dom-repeat) would update correctly. // Args: // polymerElement: the polymer element whose array property we want // to change. // pathToArray: a polymer dot-separated path string to the array // newArray: the new array to set. export function setArrayObservably(polymerElement, pathToArray, newArray) { const currentArray = polymerElement.get(pathToArray, polymerElement); // If the current value is not an array, then we use // 'polymerElement.set' to replace it with newArray. if (!Array.isArray(currentArray)) { polymerElement.set(pathToArray, newArray); return; } // Call Polymer.Base.splice() removing the old elements and inserting // the new ones. // We need to call polymerElement.splice with 'apply' since splice // receives a variable argument-list and we want to pass it an array // (newArray). polymerElement.splice.apply( polymerElement, [pathToArray, 0, currentArray.length].concat(newArray) ); } // Computes a simple not-secure 32-bit integer hash value for a string. export function hashOfString(str) { let result = 0; for (let i = 0; i < str.length; ++i) { result = (result * 31 + str.charCodeAt(i)) & 4294967295; } // Bitwise operations in JavaScript convert operands to 32-bit 2's // complement representation in the range [-2**31,(2**31)-1]. Shift it // to the range [0, (2**32)-1]. return result + 2 ** 31; }
the_stack
import { Component, OnInit, Input } from '@angular/core'; import { CloudGemMetricApi } from './api-handler.class'; import { AwsService } from 'app/aws/aws.service'; import { Http } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { ToastsManager } from 'ng2-toastr/ng2-toastr'; import 'rxjs/add/operator/distinctUntilChanged' @Component({ selector: 'metric-filtering', template: ` <ng-template #loading> <loading-spinner></loading-spinner> </ng-template> <div class="filter-section-container"> <p> What events would you like to filter out? These metrics will not be recorded and cannot be recovered. </p> <div class="filter-events-container container" *ngIf="!isLoadingFilters; else loading"> <div class="row labels"> <div class="col-2"> <label> EVENT NAME </label> </div> <div class="col-2"> <label> PLATFORM </label> </div> <div class="col-2"> <label> TYPE </label> </div> <div class="col-2" *ngIf="hasAttributes"> <label> ATTRIBUTES </label> </div> </div> <div class="row filters" *ngFor="let filter of filters"> <div class="col-2"> <input type="text" class="form-control" [ngbTypeahead]="searchEvents" [(ngModel)]="filter.event" /> </div> <div class="col-2"> <dropdown [options]="platformOptions" (dropdownChanged)="updateFilterPlatform($event, filter)" placeholderText="Platform" [currentOption]="filter.platformDropdownValue" name="dropdown" ></dropdown> </div> <div class="col-2"> <dropdown [options]="typeOptions" (dropdownChanged)="updateFilterType($event, filter)" placeholderText="Type" [currentOption]="filter.typeDropdownValue" name="dropdown" ></dropdown> </div> <div class="col-4" class="event-attributes" *ngIf="filter.type === 'Attribute'"> <div class="row" *ngFor="let attribute of filter.attributes; let i = index;"> <div class="col-6"> <input type="text" class="form-control" [(ngModel)]="filter.attributes[i]" /> </div> <div *ngIf="i === filter.attributes.length - 1" class="col-6"> <button type="button" class="btn btn-outline-primary" (click)="addAttribute(filter)"> + Add Attribute </button> </div> <div *ngIf="filter.attributes.length > 1 && i < filter.attributes.length - 1" class="col-6"> <button type="button" class="btn btn-outline-primary" (click)="removeAttribute(filter, attribute)"> - Remove Attribute </button> </div> </div> </div> <i (click)="removeFilter(filter)" class="fa fa-trash-o float-right"> </i> </div> <div class="row add-filter"> <div class="col-lg-2"> <button type="button" class="btn btn-outline-primary" (click)="addFilter()"> + Add Filter </button> </div> </div> <h2> Priority </h2> <p> Event priority is used to define what events should take priority when the local game disk space is low. The threshold for when prioritization takes place can be changed in the Cloud Gem Metric settings facet. It is labelled as "Prioritization Threshold". Priority for events goes from highest priority at the top to lowest priority at the bottom. Events without priortization defined are dropped when local disk space is limited. <div class="priority-dragable-container" *ngIf="!isLoadingFilters; else loading"> <div class="priority-label-high"> <label> Highest Priority </label> </div> <dragable [drop]="onPriorityChanged"> <div *ngFor="let priority of priorities; let i = index" [id]="priorities[i]"> <div class="row"> <div class="valign-middle col-4">Rank {{i+1}}:</div> <div class="col-7"><input type="text" class="form-control" [ngbTypeahead]="searchEvents" [ngModel]="priorities[i]" (change)="onValueUpdate($event, i)" /></div> <div class="col-1"><i (click)="removePriority(i)" class="fa fa-trash-o float-right cursor-pointer"></i></div> </div> </div> </dragable> <div class="priority-label-low"> <label class="priority-label-low"> Lowest Priority </label> </div> </div> <div class="row add-priority"> <div class="col-lg-2"> <button type="button" class="btn btn-outline-primary" (click)="addPriority()"> + Add Priority </button> </div> </div> <div class="row update-event-filters"> <div class="col-lg-2"> <button type="submit" (click)="updateFilters(filters)" class="btn l-primary"> Update Filters </button> </div> </div> </div> </div> `, styles: [` .row { margin-bottom: 15px; } .filter-events-container dropdown { margin-right: 15px; } .filter-section-container { margin-bottom: 20px; max-width: 1000px; } .filter-priority-container { max-width: 1000px; } .add-filter { margin-top: 20px; margin-bottom: 30px; } .update-event-filters { margin-bottom: 15px; } .labels { margin-bottom: 10px; } .row.event-attributes { padding: 0; } .row i { line-height: 30px; } .filters.row button { width: 135px; text-align: center; } .priority-dragable-container { width: 450px; margin-left: 15px; } .priority-label-high { margin-bottom: 10px; } .priority-label-low { margin-top: 10px; margin-bottom: 20px; } .priority-update { margin-top: 15px; } .cursor-pointer { cursor: pointer !important; } `] }) export class MetricFilteringComponent implements OnInit { @Input() context: any; private _apiHandler: CloudGemMetricApi; // Dropdown & Typeahead lists events = []; platformOptions = [{ text: "All" }] typeOptions = [ { text: "All" }, { text: "Attribute" } ] isLoadingFilters: boolean = true; // Filter lists filters: Array<Filter>; priorities: Array<string>; hasAttributes: boolean = false; constructor(private http: Http, private aws: AwsService, private toastr: ToastsManager) { } ngOnInit() { this._apiHandler = new CloudGemMetricApi(this.context.ServiceUrl, this.http, this.aws); // Get any events and platforms from current metrics this._apiHandler.getFilterEvents().subscribe((res) => { let filterEvents = JSON.parse(res.body.text()).result; filterEvents.map( filterEvent => this.events.push(filterEvent) ); }); this._apiHandler.getFilterPlatforms().subscribe((res) => { let filterPlatforms = JSON.parse(res.body.text()).result; filterPlatforms.map((platform) => { this.platformOptions.push({ text: platform }) }) }); this.getExistingFilters(); this.getExistingPriorities(); } getExistingFilters = () => { // Get any existing filters this.filters = new Array<Filter>(); this._apiHandler.getFilters().subscribe((res) => { var filters = JSON.parse(res.body.text()).result.filters; filters.map((filter: Filter, index: number) => { // If the attributes array is empty add a string so it will register in the template and provide an input to add an attribute if (filter.attributes.length > 0) { this.hasAttributes = true; } // If the filter doesn't have a priority assign one here if (!filter.precedence) filter.precedence = index; this.filters.push( new Filter(filter.event, filter.platform, filter.type, filter.attributes, filter.precedence)); }); this.isLoadingFilters = false; }) } getExistingPriorities = () => { // Get any existing filters this.priorities = new Array<string>(); this._apiHandler.getPriorities().subscribe((res) => { var priorities = JSON.parse(res.body.text()).result.priorities; priorities.map((priority: string, index: number) => { this.priorities.push(priority); }); this.isLoadingFilters = false; }) } /** Add a new filter row locally. Not saved to the server until #UpdateFilters is called */ addFilter = () => this.filters.push(Filter.default()); /** Remove a filter from the filter list locally */ removeFilter = (filter) => this.filters.splice(this.filters.indexOf(filter), 1); /** Add a new priority row locally. Not saved to the server until #UpdateFilters is called */ addPriority = () => this.priorities.push(""); /** Remove a filter from the filter list locally */ removePriority = (priority) => this.priorities.splice(this.priorities.indexOf(priority), 1); /** Add a row to the filter attribute list */ addAttribute = (filter: Filter) => filter.attributes.push(""); /** Remove a row from the attributes of a filter */ removeAttribute = (filter: Filter, attribute: string) => filter.attributes.splice(filter.attributes.indexOf(attribute), 1); /** Update the type for a filter when the dropdown input is changed.*/ updateFilterType = (typeDropdownValue, filter) => { filter.type = typeDropdownValue.text if (filter.type === 'Attribute') { this.hasAttributes = true; } } /* Update the platform value when the dropdown input is changed */ updateFilterPlatform = (platformDropdownValue, filter) => filter.platform = platformDropdownValue.text onValueUpdate = (value, idx) => { this.priorities[idx] = value.target.value } /** Update the server with the current list of filters */ updateFilters = (filters: Filter[]) => { this.isLoadingFilters = true; filters.map((filter) => { delete filter.platformDropdownValue; delete filter.typeDropdownValue; // Comment this block to not allow submission of attribute types with no actual attributes values specified filter.attributes.forEach((attribute, index) => { if (!attribute) { filter.attributes.splice(index, 1); } }) }) // parse out dropdown field values and add a parent filter property let filtersObj = { filters: filters } this._apiHandler.updateFilters(filtersObj).subscribe(() => { this.toastr.success("Updated filters"); this.getExistingFilters(); this._apiHandler.updatePriorities({ priorities: this.priorities }).subscribe(() => { this.toastr.success("Updated filter priorities"); }, (err) => { this.toastr.error("Unable to update filter priorities.", err); console.error(err); }); }, (err) => { this.toastr.error("Unable to update Filters", err); this.isLoadingFilters = false; console.error(err); }); } /** Update the priorities given the ordering of the events in the dragable section */ onPriorityChanged = (element, targetContainer, subContainer): void => { let prioritizedEvents = []; // Get filter event name from target container and add it to an ordered list for (let filterEle of targetContainer.children) { prioritizedEvents.push(filterEle['id']); } this.priorities = prioritizedEvents; } /** Typeahead function for searching through filter events */ searchEvents = (text$: Observable<string>) => text$.debounceTime(200) .distinctUntilChanged() .map(term => this.events.filter(v => v.toLocaleLowerCase().indexOf(term.toLocaleLowerCase()) > -1).slice(0, 10)); changeFilterOrdering(filterEvents: string[], filters: Filter[]): Filter[] { let prioritizedFilters = []; filterEvents.map((filterEvent) => { filters.map(filter => { if (filter.event === filterEvent) { prioritizedFilters.push(filter); } }); }); return prioritizedFilters; } } /** Filter model */ export class Filter { event: string; platform: string platformDropdownValue: { text: string }; type: string; typeDropdownValue: { text: string }; precedence: number; attributes: string[]; constructor(event: string, platform: string, type: string, attributes: string[], precedence?: number) { this.event = event; this.platform = platform ; this.attributes = attributes; this.precedence = precedence; // Type can be lowercased in the DB so check that case here if (type === "all") this.type = 'All' ; else if (type === "attribute") this.type = "Attribute"; else this.type = type; // assign dropdown object values this.platformDropdownValue = { text: this.platform }; this.typeDropdownValue = { text: this.type }; } static default = () => new Filter( "", "All", "All", [""]); }
the_stack
import { ReactNode, forwardRef, Ref, ButtonHTMLAttributes, AnchorHTMLAttributes, HTMLAttributes, FC, } from 'react'; import { css } from '@emotion/react'; import isPropValid from '@emotion/is-prop-valid'; import { ChevronRight, IconProps } from '@sumup/icons'; import styled, { StyleProps } from '../../styles/styled'; import { disableVisually, focusVisible, spacing, } from '../../styles/style-mixins'; import { ReturnType } from '../../types/return-type'; import { ClickEvent } from '../../types/events'; import { AsPropType } from '../../types/prop-types'; import { isFunction } from '../../util/type-check'; import { warn } from '../../util/logger'; import { useClickEvent, TrackingProps } from '../../hooks/useClickEvent'; import { useComponents } from '../ComponentsContext'; import Body from '../Body'; type Variant = 'action' | 'navigation'; interface BaseProps { /** * Choose between 'action' and 'navigation' variant. Default: 'action'. * The `navigation` variant renders a chevron in the trailing section. */ variant?: Variant; /** * Display a leading icon, status image, checkbox, etc. in addition to the text content. */ prefix?: FC<IconProps> | ReactNode; /** * Display a main label. */ label: ReactNode; /** * Display a details line below the main label. */ details?: ReactNode; /** * Display a trailing label. * If using the `navigation` variant, the chevron icon will be center aligned with this label. */ suffixLabel?: ReactNode; /** * Display a trailing details label. */ suffixDetails?: ReactNode; /** * Display a custom trailing component. * If using the `navigation` variant, the chevron icon will be center aligned with this component. */ suffix?: ReactNode; /** * Visually mark the list item as selected. */ selected?: boolean; /** * Visually and functionally disable the list item. */ disabled?: boolean; /** * Function that is called when the list item is clicked. */ onClick?: (event: ClickEvent) => void; /** * Link to another part of the application or external page. */ href?: string; /** * Additional data that is dispatched with the tracking event. */ tracking?: TrackingProps; /** * The ref to the HTML DOM element */ ref?: Ref<HTMLDivElement & HTMLAnchorElement & HTMLButtonElement>; } type DivElProps = Omit<HTMLAttributes<HTMLDivElement>, 'prefix' | 'onClick'>; type LinkElProps = Omit< AnchorHTMLAttributes<HTMLAnchorElement>, 'prefix' | 'onClick' >; type ButtonElProps = Omit< ButtonHTMLAttributes<HTMLButtonElement>, 'prefix' | 'onClick' >; export type ListItemProps = BaseProps & DivElProps & LinkElProps & ButtonElProps; type InteractiveProps = { isInteractive: boolean }; type StyledListItemProps = Pick<BaseProps, 'selected'> & InteractiveProps & DivElProps & LinkElProps & ButtonElProps; const baseStyles = ({ theme }: StyleProps) => css` background-color: ${theme.colors.white}; color: ${theme.colors.bodyColor}; border: ${theme.borderWidth.mega} solid ${theme.colors.n200}; border-radius: ${theme.borderRadius.mega}; display: flex; align-items: center; padding: ${theme.spacings.kilo} ${theme.spacings.mega}; margin: 0; width: 100%; text-align: left; text-decoration: none; position: relative; &:focus { border-color: transparent; z-index: 2; } &:focus:not(:focus-visible) { border-color: ${theme.colors.n200}; z-index: auto; } &:disabled, &[disabled] { ${disableVisually()}; } `; const interactiveStyles = ({ theme, isInteractive, }: StyleProps & StyledListItemProps) => isInteractive && css` cursor: pointer; &:hover { background-color: ${theme.colors.n100}; } &:active { background-color: ${theme.colors.n200}; border-color: ${theme.colors.n200}; } `; const selectedStyles = ({ theme, selected, }: StyleProps & StyledListItemProps) => selected && css` background-color: ${theme.colors.p100}; &:hover, &:active { background-color: ${theme.colors.p100}; } &:after { content: ''; position: absolute; top: -${theme.borderWidth.mega}; bottom: -${theme.borderWidth.mega}; left: -${theme.borderWidth.mega}; right: -${theme.borderWidth.mega}; border: ${theme.borderWidth.mega} solid ${theme.colors.p500}; border-radius: ${theme.borderRadius.mega}; z-index: 1; pointer-events: none; } `; const StyledListItem = styled('div', { shouldForwardProp: (prop) => isPropValid(prop) && prop !== 'label', })<StyledListItemProps>( focusVisible, baseStyles, interactiveStyles, selectedStyles, ); const prefixContainerStyles = ({ theme }: StyleProps) => css` flex: none; display: flex; margin-right: ${theme.spacings.mega}; `; const PrefixContainer = styled.div(prefixContainerStyles); const contentContainerStyles = css` flex: auto; display: flex; align-items: center; min-width: 0; `; const ContentContainer = styled.div(contentContainerStyles); const mainContainerStyles = css` flex: auto; display: flex; flex-direction: column; align-items: flex-start; min-width: 0; `; const MainContainer = styled.div(mainContainerStyles); const labelStyles = css` max-width: 100%; overflow-x: hidden; white-space: nowrap; text-overflow: ellipsis; `; const Label = styled(Body)(labelStyles); const detailsContainerStyles = ({ theme }: StyleProps) => css` display: flex; align-items: center; max-width: 100%; min-height: ${theme.typography.body.one.lineHeight}; `; const DetailsContainer = styled.div(detailsContainerStyles); type NavigationProps = { isNavigation: boolean }; type SuffixContainerProps = { hasLabel: boolean } & NavigationProps; const suffixContainerStyles = ({ theme, hasLabel, }: StyleProps & SuffixContainerProps) => css` flex: none; align-self: stretch; display: flex; flex-direction: column; align-items: flex-end; justify-content: ${hasLabel ? 'flex-start' : 'center'}; margin-left: ${theme.spacings.mega}; `; const suffixContainerNavigationStyles = ({ theme, isNavigation, }: StyleProps & SuffixContainerProps) => isNavigation && css` margin-right: -${theme.spacings.bit}; `; const SuffixContainer = styled.div( suffixContainerStyles, suffixContainerNavigationStyles, ); const suffixChevronContainerStyles = css` display: flex; align-items: center; `; const SuffixChevronContainer = styled.div(suffixChevronContainerStyles); const suffixDetailsContainerNavigationStyles = ({ theme, isNavigation, }: StyleProps & NavigationProps) => isNavigation && css` margin-right: calc(${theme.spacings.mega} + ${theme.spacings.bit}); height: ${theme.typography.body.one.lineHeight}; `; const SuffixDetailsContainer = styled.div( detailsContainerStyles, suffixDetailsContainerNavigationStyles, ); /** * The ListItem component enables the user to render a list item with various * textual and visual elements. */ export const ListItem = forwardRef( ( { variant = 'action', prefix: Prefix, label, details, suffixLabel, suffixDetails, suffix, tracking, ...props }: ListItemProps, ref?: BaseProps['ref'], ): ReturnType => { const hasOnlySuffixDetails = suffixDetails && !suffixLabel; const hasCustomAndLabelSuffix = suffix && suffixLabel; if ( process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test' ) { if (hasOnlySuffixDetails) { warn( 'ListItem', 'Using `suffixDetails` without `suffixLabel` is not supported.', ); } if (hasCustomAndLabelSuffix) { warn( 'ListItem', 'Using `suffixLabel` and `suffix` at the same time is not supported.', ); } } const components = useComponents(); let as: AsPropType = 'div'; if (props.href) { as = components.Link as AsPropType; } else if (props.onClick) { as = 'button'; } const handleClick = useClickEvent(props.onClick, tracking, 'ListItem'); const isInteractive = !!props.href || !!props.onClick; const isNavigation = variant === 'navigation'; const hasSuffix = !!suffixLabel || !!suffix; const hasInvalidSuffix = hasOnlySuffixDetails || hasCustomAndLabelSuffix; const shouldRenderSuffixContainer = !hasInvalidSuffix && (hasSuffix || isNavigation); return ( <StyledListItem {...props} ref={ref} as={as} isInteractive={isInteractive} onClick={handleClick} > {Prefix && ( <PrefixContainer> {isFunction(Prefix) ? ( <Prefix size="24" role="presentation" /> ) : ( Prefix )} </PrefixContainer> )} <ContentContainer> <MainContainer> {typeof label === 'string' ? ( <Label size="one" noMargin> {label} </Label> ) : ( label )} {details && ( <DetailsContainer> {typeof details === 'string' ? ( <Body size="two" variant="subtle" noMargin> {details} </Body> ) : ( details )} </DetailsContainer> )} </MainContainer> {shouldRenderSuffixContainer && ( <SuffixContainer hasLabel={!!suffixLabel} isNavigation={isNavigation} > <SuffixChevronContainer> {typeof suffixLabel === 'string' ? ( <Body size="one" variant="highlight" noMargin> {suffixLabel} </Body> ) : ( suffixLabel )} {suffix} {isNavigation && ( <ChevronRight size="16" role="presentation" css={hasSuffix && spacing({ left: 'bit' })} /> )} </SuffixChevronContainer> {suffixDetails && ( <SuffixDetailsContainer isNavigation={isNavigation}> {typeof suffixDetails === 'string' ? ( <Body size="two" variant="subtle" noMargin> {suffixDetails} </Body> ) : ( suffixDetails )} </SuffixDetailsContainer> )} </SuffixContainer> )} </ContentContainer> </StyledListItem> ); }, ); ListItem.displayName = 'ListItem';
the_stack
module TDev.RT { export module BingServices { function readBingSearchResponse(response: WebResponse): BingSearchResult[] { var links: BingSearchResult[] = []; try { var json = response.content_as_json(); if (json) { for (var i = 0; i < json.count(); ++i) { var jlink = json.at(i); var url = jlink.string('address'); var name = jlink.string('name'); var thumb = jlink.string('thumb'); var web = jlink.string('web'); if (url != null && url.length > 0) links.push({ url: url, name: name, thumbUrl: thumb, web: web }); } } return links; } catch (ex) {} return links; } export var searchAsync = (kind: string, query: string, loc: Location_): Promise => { if (!query) return Promise.as([]); var url = 'runtime/web/search?kind=' + encodeURIComponent(kind) + '&query=' + encodeURIComponent(query); if (loc) { url += '&latitude=' + encodeURIComponent(loc.latitude().toString()) + '&longitude=' + encodeURIComponent(loc.longitude().toString()); } var request = WebRequest.mk(Cloud.getPrivateApiUrl(url), undefined); return request.sendAsync() .then((response: WebResponse) => readBingSearchResponse(response)); } } export interface BingSearchResult { name: string; url: string; thumbUrl: string; web: string; } export interface EventSource { addEventListener(msg: string, cb: (e: any) => void, replace: boolean); close(); readyState: number; } //? A Server-Sent-Events client //@ stem("source") export class WebEventSource extends RTDisposableValue { private onMessages = {}; private onOpen: Event_; private onError: Event_; constructor(rt : Runtime, private source : EventSource) { super(rt); } //? Sets an event to run when a message is received. Change name to receive custom events. //@ [name].defl('message') ignoreReturnValue writesMutable public on_message(name: string, handler: TextAction): EventBinding { if (!name || /^close|error$/i.test(name)) Util.userError(lf("name cannot be 'close' or 'error'")); var onMessage = <Event_>this.onMessages[name]; if (!onMessage) { onMessage = new Event_(); if (this.source) this.source.addEventListener(name, (e: MessageEvent) => { if (this.source && onMessage.handlers) { var d = e.data || ""; this.rt.queueLocalEvent(onMessage, [d]); } }, false); } return onMessage.addHandler(handler); } //? Gets the current connection state (`connecting`, `open`, `closed`) public state(): string { if (!this.source) return "closed"; else switch (this.source.readyState) { case 0: return "connecting"; case 1: return "open"; case 2: return "closed"; default: return "unkown"; } } //? Sets an event to run when the event source is opened //@ ignoreReturnValue writesMutable public on_open(body: Action): EventBinding { if (!this.onOpen) { this.onOpen = new Event_(); if (this.source) this.source.addEventListener('open', (e) => { if (this.source && this.onOpen.handlers) this.rt.queueLocalEvent(this.onOpen); }, false); } return this.onOpen.addHandler(body); } //? Sets an event to run when an error occurs //@ ignoreReturnValue writesMutable public on_error(body: Action): EventBinding { if (!this.onError) { this.onError = new Event_(); if (this.source) this.source.addEventListener('error', (e) => { if (this.source && this.onError.handlers) this.rt.queueLocalEvent(this.onError); }, false); } return this.onError.addHandler(body); } //? Closes the EventSource. No further event will be raised. //@ writesMutable public close() { if (this.source) { try { this.source.close(); } catch (e) {} this.source = undefined; } } public dispose() { this.close(); super.dispose(); } } //? Search and browse the web... //@ skill(2) export module Web { export interface MessageWaiter { origin: string; handler: (js:JsonObject)=>void; } export interface State { _onReceivedMessageEvent: Event_; _messageWaiters: MessageWaiter[]; receiveMessage: (event: MessageEvent) => void; } export function rt_start(rt: Runtime): void { clearReceivedMessageEvent(rt); } export function rt_stop(rt: Runtime) { clearReceivedMessageEvent(rt); } function toLink(jlink: BingSearchResult, kind: LinkKind): Link { var link: Link = Link.mk(jlink.url, kind); var idx = jlink.name.indexOf(' : '); if (idx > 0) { link.set_title(jlink.name.slice(0, idx)); link.set_description(jlink.name.slice(idx + 3)); } else { link.set_name(jlink.name); } return link; } function bingSearch(kind: string, query: string, loc: Location_, linkKind: LinkKind, r: ResumeCtx) { BingServices.searchAsync(kind, query, loc) .done((results: BingSearchResult[]) => { var links = Collections.create_link_collection(); results.forEach(result => { links.add(toLink(result, linkKind)); }); r.resumeVal(links); }); } //? Searching the web using Bing //@ async cap(search) flow(SinkSafe) returns(Collection<Link>) //@ [result].writesMutable export function search(query: string, r: ResumeCtx) //: Collection<Link> { bingSearch("Web", query, undefined, LinkKind.hyperlink, r); } //? Searching the web near a location using Bing. Distance in meters, negative to ignore. //@ async cap(search) flow(SinkSafe) returns(Collection<Link>) //@ [result].writesMutable //@ [location].deflExpr('senses->current_location') [distance].defl(1000) export function search_nearby(query: string, location: Location_, distance: number, r: ResumeCtx) // : Collection<Link> { bingSearch("Web", query, location, LinkKind.hyperlink, r); } //? Searching images using Bing //@ async cap(search) flow(SinkSafe) returns(Collection<Link>) //@ [result].writesMutable export function search_images(query: string, r: ResumeCtx) // : Collection<Link> { bingSearch("Images", query, undefined, LinkKind.image, r); } //? Searching images near a location using Bing. Distance in meters, negative to ignore. //@ async cap(search) flow(SinkSafe) returns(Collection<Link>) //@ [result].writesMutable //@ [location].deflExpr('senses->current_location') [distance].defl(1000) export function search_images_nearby(query: string, location: Location_, distance: number, r: ResumeCtx) // : Collection<Link> { bingSearch("Images", query, location, LinkKind.image, r); } //? Search phone numbers using Bing //@ obsolete cap(search) flow(SinkSafe) //@ [result].writesMutable export function search_phone_numbers(query: string): Collection<Link> { return undefined; } //? Search phone numbers near a location using Bing. Distance in meters, negative to ignore. //@ obsolete cap(search) flow(SinkSafe) //@ [result].writesMutable //@ [location].deflExpr('senses->current_location') [distance].defl(1000) export function search_phone_numbers_nearby(query: string, location: Location_, distance: number): Collection<Link> { return undefined; } //? Searching news using Bing //@ async cap(search) flow(SinkSafe) returns(Collection<Link>) //@ [result].writesMutable export function search_news(query: string, r: ResumeCtx) // : Collection<Link> { bingSearch("News", query, undefined, LinkKind.hyperlink, r); } //? Searching news near a location using Bing. Distance in meters, negative to ignore. //@ async cap(search) flow(SinkSafe) returns(Collection<Link>) //@ [result].writesMutable //@ [location].deflExpr('senses->current_location') [distance].defl(1000) export function search_news_nearby(query: string, location: Location_, distance: number, r: ResumeCtx) // : Collection<Link> { bingSearch("News", query, location, LinkKind.hyperlink, r); } //? Indicates whether any network connection is available export function is_connected(): boolean { return window.navigator.onLine; } //? Gets the type of the network servicing Internet requests (unknown, none, ethernet, wifi, mobile) //@ quickAsync returns(string) //@ import("cordova", "cordova-plugin-network-information") export function connection_type(r: ResumeCtx) { //: string var res = 'unknown'; var connection = (<any>navigator).connection; if (connection) { res = connection.type || 'unknown'; } r.resumeVal(res); } //? Gets a name of the currently connected network servicing Internet requests. Empty string if no connection. //@ quickAsync returns(string) export function connection_name(r : ResumeCtx) { // : string r.resumeVal(''); } //? Opens a connection settings page (airplanemode, bluetooth, wifi, cellular) //@ cap(phone) uiAsync //@ [page].defl("airplanemode") [page].deflStrings("airplanemode", "bluetooth", "wifi", "cellular") export function open_connection_settings(page:string, r : ResumeCtx) : void { r.resume(); } //? Opens a web browser to a url //@ cap(network) flow(SinkWeb) uiAsync export function browse(url: string, r : ResumeCtx): void { Web.browseAsync(url).done(() => r.resume()); } //? Redirects the browser to a url; only available when exporting //@ betaOnly uiAsync export function redirect(url:string, r: ResumeCtx) : void { if (r.rt.devMode) Util.userError(lf("web->redirect not available when running in the editor")) else { // TODO this is a hack // give it some time to save data etc // we never resume Util.setTimeout(1500, () => Util.navigateInWindow(url)) } } export var browseAsync = (url: string) => { var win = window.open(url, "_blank"); try { win.focus() return Promise.as() } catch (e) { // popup blocked the url return new Promise((onSuccess, onError, onProgress) => { var d = new ModalDialog(); d.onDismiss = () => onSuccess(undefined); d.add(div("wall-dialog-header", lf("web browsing..."))); d.add(div("wall-dialog-body", lf("We tried to open the following web page: {0}",url))) d.add(div("wall-dialog-body", lf("If the page did not open, tap the 'open' button below, otherwise tap 'done'."))) d.add(div("wall-dialog-buttons", HTML.mkA("button wall-button", url, "_blank", "open"), HTML.mkButton(lf("done"), () => { d.dismiss(); }))) d.show(); }); } } //? Plays an internet audio/video in full screen //@ cap(network) flow(SinkWeb) export function play_media(url: string): void { window.open(url); } //? Creates a link to an internet audio/video //@ [result].writesMutable export function link_media(url: string): Link { return Link.mk(url, LinkKind.media); } //? Creates a link to an internet image //@ [result].writesMutable export function link_image(url: string): Link { return Link.mk(url, LinkKind.image); } //? Creates a link to an internet page //@ [result].writesMutable export function link_url(name: string, url: string): Link { var l = Link.mk(url, LinkKind.hyperlink); l.set_name(name); return l; } //? Creates a multi-scale image from an image url //@ obsolete //@ [result].writesMutable export function link_deep_zoom(url: string): Link { return undefined; } export function proxy(url: string) { // don't proxy when not authenticated if (!Cloud.hasAccessToken()) return url; // don't proxy localhost if (!url || /^http:\/\/localhost(:[0-9]+)?\//i.test(url)) return url; // don't proxy private ip ranges // 10.0.0.0 - 10.255.255.255 // 172.16.0.0 - 172.31.255.255 // 192.168.0.0 - 192.168.255.255 var m = url.match(/^http:\/\/([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)(:[0-9]+)?\//i); if (m) { var a = parseInt(m[1]); if (a == 10) return url; var b = parseInt(m[2]); if (a == 172 && b >= 16 && b <= 31) return url; if (a == 192 && b == 168) return url; } return Cloud.getPrivateApiUrl("runtime/web/proxy?url=" + encodeURIComponent(url)); } //? Downloads the content of an internet page (http get) //@ async cap(network) flow(SinkWeb) returns(string) export function download(url: string, r: ResumeCtx) { r.progress('Downloading...'); var request = create_request(url); request .sendAsync() .done((response: WebResponse) => r.resumeVal(response.content()), (e) => r.resumeVal(undefined)); } //? Downloads a web service response as a JSON data structure (http get) //@ async cap(network) flow(SinkWeb) returns(JsonObject) export function download_json(url: string, r: ResumeCtx) { r.progress('Downloading...'); var request = create_request(url); request.set_accept('application/json'); request .sendAsync() .done((response: WebResponse) => r.resumeVal(response.content_as_json()), (e) => r.resumeVal(undefined)); } //? Downloads a web service response as a XML data structure (http get) //@ cap(network) async flow(SinkWeb) returns(XmlObject) //@ import("npm", "xmldom", "0.1.*") export function download_xml(url: string, r: ResumeCtx) { var request = create_request(url); r.progress('Downloading...'); request.set_accept('text/xml'); request .sendAsync() .done((response: WebResponse) => r.resumeVal(response.content_as_xml()), (e) => r.resumeVal(undefined)); } //? Downloads a WAV sound file from internet //@ async cap(network) flow(SinkWeb) returns(Sound) export function download_sound(url: string, r: ResumeCtx) // : Sound { r.progress("Downloading..."); Sound .fromUrl(url) .done(snd => r.resumeVal(snd)); } //? Create a streamed song file from internet (download happens when playing) //@ cap(media,network) flow(SinkWeb) //@ [name].defl("a song") export function download_song(url: string, name: string): Song { return Song.mk(url, undefined, name); } //? Uploads text to an internet page (http post) //@ async cap(network) flow(SinkWeb) returns(string) export function upload(url:string, body:string, r : ResumeCtx) { var request = create_request(url); r.progress('Uploading...'); request.set_method('post'); request.set_content(body); request .sendAsync() .done((response : WebResponse) => r.resumeVal(response.content()), (e) => r.resumeVal(undefined)); } //? Uploads a sound to an internet page (http post). The sound must have been recorded from the microphone. //@ async cap(network) flow(SinkWeb) returns(string) export function upload_sound(url: string, snd: Sound, r : ResumeCtx) //: string { var request = create_request(url); r.progress('Uploading...'); request.set_method('post'); request.setContentAsSoundInternal(snd); request.sendAsync() .done((response : WebResponse) => r.resumeVal(response.content()), (e) => r.resumeVal(undefined)); } //? Uploads a picture to an internet page (http post) //@ async cap(network) flow(SinkWeb) returns(string) export function upload_picture(url: string, pic: Picture, r : ResumeCtx) //: string { var request = create_request(url); r.progress('Uploading...'); request.set_method('post'); pic.initAsync() .then(() => { request.setContentAsPictureInternal(pic, 0.85); return request.sendAsync(); }).done((response : WebResponse) => r.resumeVal(response.content()), (e) => r.resumeVal(undefined)); } //? Downloads a picture from internet //@ async cap(network) flow(SinkWeb) returns(Picture) //@ [result].writesMutable export function download_picture(url:string, r : ResumeCtx) { r.progress('Downloading...'); var pic = undefined; Picture.fromUrl(url) .then((p : Picture) => { pic = p; return p.initAsync(); }) .done(() => r.resumeVal(pic), (e) => r.resumeVal(undefined)); } //? Decodes a string that has been HTML-encoded export function html_decode(html: string): string { return Util.htmlUnescape(html); } //? Converts a text string into an HTML-encoded string export function html_encode(text: string): string { return Util.htmlEscape(text); } //? Decodes a URI component export function decode_uri(url: string): string { return decodeURI(url); } //? Encodes a uri component export function encode_uri(text: string): string { return encodeURI(text); } //? Decodes a URI component export function decode_uri_component(url: string): string { return decodeURIComponent(url); } //? Encodes a uri component export function encode_uri_component(text: string): string { return encodeURIComponent(text); } //? Use `web->decode uri component` instead. //@ obsolete export function url_decode(url:string) : string { return decodeURIComponent(url); } //? Use `web->encode uri component` instead. //@ obsolete export function url_encode(text:string) : string { return encodeURIComponent(text); } //? Parses the string as a json object //@ [value].lang("json") //@ [value].defl("{}") export function json(value: string): JsonObject { return JsonObject.mk(value, function (msg) { App.logEvent(App.DEBUG, 'json', lf("error parsing json: {0}", msg), undefined); }); } //? Returns an empty json object export function json_object(): JsonObject { return JsonObject.wrap({}); } //? Returns an empty json array export function json_array(): JsonObject { return JsonObject.wrap([]); } //? Parses the string as a xml element //@ import("npm", "xmldom", "0.1.*") export function xml(value:string) : XmlObject { return XmlObject.mk(value); } //? Obsolete. Use 'feed' instead. //@ obsolete //@ [result].writesMutable export function rss(value: string): Collection<Message> { return feed(value); } //? Creates a web request export function create_request(url: string): WebRequest { return WebRequest.mk(url, "text"); } //? Creates a web socket //@ async returns(WebSocket_) export function open_web_socket(url: string, r:ResumeCtx) { var ws = new WebSocket(url) ws.onopen = () => { ws.onerror = null; ws.onopen = null; r.resumeVal(WebSocket_.mk(ws, r.rt)) } ws.onerror = err => { App.log("Error opening WebSocket to " + url + ": " + err.message) r.resumeVal(undefined) } } //? Decodes a string that has been base64-encoded (assuming utf8 encoding) export function base64_decode(text: string): string { var decoded = Util.base64Decode(text) try { return Util.fromUTF8(decoded); } catch (e) { return decoded; } } //? Converts a string into an base64-encoded string (with utf8 encoding) export function base64_encode(text: string): string { return Util.base64Encode(Util.toUTF8(text)); } function htmlToPictureUrl(value: string) { if (!value) return value; var m = value.match(/<img.*?src=['"](.*?)['"].*?\/?>/i); if (m) return m[1]; return null; } function htmlToText(value : string) { if (!value) return value; var r = value.replace(/<[^>]+>/ig, ''); var decoded = Web.html_decode(r); var decodedescaped = decoded.replace(/<[^>]+>/ig, ''); return decodedescaped; } function parseRss(rssx: XmlObject, msgs: Collection<Message>) { var channel = rssx.child('channel'); if (!channel) return; var imgRx = /^image\/(png|jpg|jpeg)$/i; var mediaRx = Browser.isGecko ? /^video\/webm|audio\/mp3$/i : /^video\/mp4|audio\/mp3$/i; var items = channel.children('item'); for (var i = 0; i < items.count(); ++i) { var item = items.at(i); var msg = Message.mk(""); msg.set_from(undefined); msgs.add(msg); var description = item.child('description'); if (description) parseHtmlContent(msg, description.value()); var title = item.child('title'); if (title) msg.set_title(htmlToText(title.value())); var link = item.child('link'); if (link) msg.set_link(link.value()); var pubDate = item.child('pubDate'); if (pubDate) msg.set_time(DateTime.parse(pubDate.value())); var speaker = item.child('{http://www.microsoft.com/dtds/mavis/}speaker'); if (speaker) msg.set_from(htmlToText(speaker.value())); var author = item.child('{http://www.itunes.com/dtds/podcast-1.0.dtd}author'); if (author) msg.set_from(htmlToText(author.value())); var creator = item.child('creator'); if (creator) msg.set_from(htmlToText(creator.value())); var img = item.child('{http://www.itunes.com/dtds/podcast-1.0.dtd}image'); if (img && img.attr('href')) msg.set_picture_link(img.attr('href')); var enclosure = item.child('enclosure'); if (enclosure) { var enclosureType = enclosure.attr('type') || ""; if (imgRx.test(enclosureType)) msg.set_picture_link(enclosure.attr('url')); else if (mediaRx.test(enclosureType)) msg.set_media_link(enclosure.attr('url')); } var thumbnails = item.children('{http://search.yahoo.com/mrss/}thumbnail'); var tisize = -1; for (var ti = 0; ti < thumbnails.count(); ++ti) { var thumbnail = thumbnails.at(ti); var cisize = (String_.to_number(thumbnail.attr('width')) || 1) * (String_.to_number(thumbnail.attr('height')) || 1); if (thumbnail.attr('url') && cisize > tisize) { msg.set_picture_link(thumbnail.attr('url')); tisize = cisize; } } var group = item.child('{http://search.yahoo.com/mrss/}group'); if (group) { var contents = group.children('{http://search.yahoo.com/mrss/}content'); var mcsize = 0; for (var ci = 0; ci < contents.count(); ++ci) { var content = contents.at(ci); var csize = String_.to_number(content.attr('fileSize')) || 0; var curl = content.attr('url'); var ctype = content.attr('type'); if (curl && mediaRx.test(ctype) && csize > mcsize) { msg.set_media_link(curl); mcsize = csize; } } } parseGeoRss(msg, item); } } function parseGeoRss(msg: Message, item: XmlObject) { var point = item.child('{http://www.georss.org/georss}point'); if (point) { var txt = point.value(); var i = txt.indexOf(' '); if (i > 0) { var lat = parseFloat(txt.substr(0, i)); var long = parseFloat(txt.substr(i + 1)); if (!isNaN(lat) && !isNaN(long)) msg.set_location(Location_.mkShort(lat, long)); } } } function parseProperties(msg: Message, entry: XmlObject) { var properties = entry.child('{http://schemas.microsoft.com/ado/2007/08/dataservices/metadata}properties'); if (properties) { var props = properties.children(""); for (var j = 0; j < props.count(); ++j) { var prop = props.at(j); msg.values().set_at(prop.local_name(), prop.value()); } } } function parseHtmlContent(msg: Message, value: string) { if (!value) return; msg.set_message(htmlToText(value)); var pic = htmlToPictureUrl(value); if (pic) msg.set_picture_link(pic); } function parseAtom(feed: XmlObject, msgs: Collection<Message>) { var channelTitlex = feed.child('title'); var channelTitle = channelTitlex ? channelTitlex.value() : "atom"; var entries = feed.children('entry'); if (entries) { for (var i = 0; i < entries.count(); ++i) { var entry = entries.at(i); var msg = Message.mk(""); msg.set_from(undefined); msgs.add(msg); var summary = entry.child('summary'); if (summary) parseHtmlContent(msg, summary.value()); var title = entry.child('title'); if (title) msg.set_title(htmlToText(title.value())); var updated = entry.child('updated'); if (updated) { var updatedd = DateTime.parse(updated.value()); if (updatedd) msg.set_time(updatedd); } var content = entry.child('content'); if (content) { var contentType = content.attr('type') || ""; if (/^image\//i.test(contentType) && content.attr('src')) msg.set_picture_link(content.attr('src')); else if (/^application\/xml/i.test(contentType)) parseProperties(msg, content); else if (/html/i.test(contentType)) parseHtmlContent(msg, content.value()); } var author = entry.child('author'); if (author) { var authorName = author.child('name'); if (authorName) msg.set_from(authorName.value()); } parseGeoRss(msg, entry); } } } //? Parses the newsfeed string (RSS 2.0 or Atom 1.0) into a message collection //@ [result].writesMutable //@ import("npm", "xmldom", "0.1.*") export function feed(value: string): Collection<Message> { var msgs = Collections.create_message_collection(); var xml = XmlObject.mk(value); while(xml != null) { if (xml.name() === 'rss') { parseRss(xml, msgs); break; } else if (xml.name() === 'feed') { parseAtom(xml, msgs); break; } else { xml = xml.next_sibling(); } } return msgs; } //? Creates a json builder //@ [result].writesMutable export function create_json_builder(): JsonBuilder { return new (<any>JsonBuilder)(); //TS9 } //? Parses a Command Separated Values document into a JsonObject where the `headers` is a string array of column names; `records` is an array of rows where each row is itself an array of strings. The delimiter is inferred if not specified. //@ [delimiter].defl("\t") export function csv(text: string, delimiter : string): JsonObject { var file = new CsvParser().parse(text, delimiter); return JsonObject.wrap(file); } //? Creates a picture from a web address. The resulting picture cannot be modified, use clone if you want to change it. export function picture(url: string): Picture { return Picture.fromUrlSync(url, true); } interface OAuthRedirect { redirect_url: string; user_id: string; time: number; } //? Authenticate with OAuth 2.0 and receives the access token or error. See [](/oauthv2) for more information on which Redirect URI to choose. //@ cap(network) flow(SinkWeb) returns(OAuthResponse) uiAsync export function oauth_v2(oauth_url: string, r : ResumeCtx) { // validating url if (!oauth_url) { r.resumeVal(OAuthResponse.mkError("access_denied", "Empty oauth url.", null)); return; } // dissallow state and redirect uris. if (/state=|redirect_uri=/i.test(oauth_url)) { r.resumeVal(OAuthResponse.mkError("access_denied", "The `redirect_uri` and `state` query arguments are not allowed.", null)); return; } // check connection if (!Web.is_connected()) { r.resumeVal(OAuthResponse.mkError("access_denied", "No internet connection.", null)); return; } var userid = r.rt.currentAuthorId; Web.oauth_v2_async(oauth_url, userid).done((v) => { r.resumeVal(v); }) } export function oauth_v2_async(oauth_url: string, userid: string): Promise // : OAuthResponse { var redirectURI = "https://www.touchdevelop.com/" + userid + "/oauth"; var state = Util.guidGen(); var stateArg = "state=" + state.replace('-', ''); var hostM = /^([^\/]+:\/\/[^\/]+)/.exec(document.URL) var host = hostM ? hostM[1] : "" if (host && !/\.touchdevelop\.com$/i.test(host)) { redirectURI = host + "/api/oauth" userid = "web-app" } var actualRedirectURI = redirectURI; // special subdomain scheme? var subdomainRx = /&tdredirectdomainid=([a-z0-9]{1,64})/i; var msubdomain = oauth_url.match(subdomainRx); if (msubdomain) { var appid = msubdomain[1]; actualRedirectURI = 'https://' + appid + '-' + userid + '.users.touchdevelop.com/oauth'; redirectURI = "https://www.touchdevelop.com/" + appid + '-' + userid + "/oauth"; App.log('oauth appid redirect: ' + appid); oauth_url = oauth_url.replace(subdomainRx, ''); } // state variable needed in redirect uri? var stateRx = /&tdstateinredirecturi=true/i; if (stateRx.test(oauth_url)) { actualRedirectURI += "?" + stateArg; Time.log('oauth adding state to url'); oauth_url = oauth_url.replace(stateRx, ''); } App.log('oauth login uri: ' + oauth_url); App.log('oauth redirect uri: ' + actualRedirectURI); // craft url login; var url = oauth_url + (/\?/.test(oauth_url) ? '&' : '?') + 'redirect_uri=' + encodeURIComponent(actualRedirectURI) + "&" + stateArg; if (!/response_type=(token|code)/i.test(url)) url += "&response_type=token"; App.log('oauth auth url: ' + url); return Web.oauth_v2_dance_async(url, actualRedirectURI, userid, stateArg); } export function oauth_v2_dance_async(url: string, redirect_uri: string, userid: string, stateArg: string): Promise { var res = new PromiseInv(); var response: OAuthResponse; var oauthWindow: Window; var m = new ModalDialog(); function handleMessage(event) { var origin = document.URL.replace(/(.*:\/\/[^\/]+).*/, (a, b) => b) if (event.origin == origin && Array.isArray(event.data)) { processRedirects(event.data) } } function handleStorage(event) { // console.log("Storage: " + event.key) if (event.key == "oauth_redirect") processRedirects(JSON.parse(event.newValue || "[]")) } function dismiss() { window.removeEventListener("message", handleMessage, false) window.removeEventListener("storage", handleStorage, false) if (!response) response = OAuthResponse.mkError("access_denied", "The user cancelled the authentication.", null); if (oauthWindow) oauthWindow.close(); res.success(response); } function processRedirects(redirects:OAuthRedirect[]) { redirects.reverse(); // pick the latest oauth message var matches = redirects.filter(redirect => userid == redirect.user_id && redirect.redirect_url.indexOf(stateArg) > -1); if (matches.length > 0) { Time.log('oauth redirect_uri: ' + matches[0].redirect_url); response = OAuthResponse.parse(matches[0].redirect_url); m.dismiss(); return; } // is the window still opened? if (!response && oauthWindow && oauthWindow.closed) { response = OAuthResponse.mkError("access_denied", "The authentication window was closed", null); m.dismiss(); return; } } // monitors local storage for the url function tracker() { if (response) return; // we've gotten a response or the user dismissed window.localStorage.setItem("last_oauth_check", Date.now() + "") // array of access tokens processRedirects(JSON.parse(window.localStorage.getItem("oauth_redirect") || "[]")) if (!response) Util.setTimeout(100, tracker); } // start the oauth dance... var woptions = 'menubar=no,toolbar=no'; oauthWindow = window.open(url, '_blank', woptions); m.add(div('wall-dialog-header', lf("authenticating..."))); m.add(div('wall-dialog-body', lf("A separate window with the sign in dialog has opened, please sign in in that window."))); m.add(div('wall-dialog-body', lf("Can't see any window? Try tapping the button below to log in manually."))); m.add(div('wall-dialog-buttons', HTML.mkA("button wall-button", url, "_blank", "log in"))); m.onDismiss = () => { dismiss(); }; m.show(); // and start listening... Util.setTimeout(100, tracker); // window.addEventListener("message", handleMessage, false) // window.addEventListener("storage", handleStorage, false) return res; } //? Create a form builder //@ [result].writesMutable export function create_form_builder(): FormBuilder { return new FormBuilder(); } //? Posts a message to the parent window if any. The `target origin` must match the domain of the parent window, * is not accepted. //@ readsMutable [target_origin].defl('https://www.touchdevelop.com') export function post_message_to_parent(target_origin: string, message: JsonObject, s:IStackFrame) { if (!target_origin || target_origin == "*") Util.userError(lf("target origin cannot be empty or *")); if (isWebWorker) { var msg = message.value() if (s && s.rt.pluginSlotId) { msg = Util.jsonClone(msg) msg.tdSlotId = s.rt.pluginSlotId } (<any>self).postMessage(msg) return } var parent = window.parent; if (parent && parent != window && parent.postMessage) { try { parent.postMessage(message.value(), target_origin); } catch (e) { App.log("web: posting message to parent failed"); } } } function receiveMessage(rt:Runtime, event: MessageEvent) { var s = rt.webState if (window != window.parent && event.source === window.parent && s._onReceivedMessageEvent) { App.log("web: receiving message from parent"); var json = JsonObject.wrap(event.data) var waiters = s._messageWaiters.filter(m => m.origin === event.origin) if (waiters.length > 0) { // remove them s._messageWaiters = s._messageWaiters.filter(m => m.origin !== event.origin) waiters.forEach(w => w.handler(json)) } if (s._onReceivedMessageEvent.handlers) { rt.queueLocalEvent(s._onReceivedMessageEvent, [json], false, false, (binding) => { var origin = <string>binding.data; return event.origin === origin; }); } } } export function receiveWorkerMessage(rt:Runtime, data:any) { var s = rt.webState if (s._onReceivedMessageEvent) { var json = JsonObject.wrap(data) var waiters = s._messageWaiters if (waiters.length > 0) { // remove them s._messageWaiters = [] waiters.forEach(w => w.handler(json)) } if (s._onReceivedMessageEvent.handlers) { rt.queueLocalEvent(s._onReceivedMessageEvent, [json], false, false) } } } function installReceiveMessage(rt:Runtime, origin:string) { if (!origin) Util.userError(lf("origin cannot be empty")); var s = rt.webState if (!s._onReceivedMessageEvent) { s._onReceivedMessageEvent = new Event_(); s._messageWaiters = []; if (!isWebWorker) { s.receiveMessage = (e) => receiveMessage(rt, e) window.addEventListener("message", s.receiveMessage, false); } } } //? Waits for the next message from the parent window in `origin`. //@ async //@ returns(JsonObject) export function wait_for_message_from_parent(origin: string, r: ResumeCtx) { installReceiveMessage(r.rt, origin) r.rt.webState._messageWaiters.push({ origin: origin, handler: (j) => r.resumeVal(j) }) } //? Attaches code to run when a message is received. Only messages from the parent window and `origin` will be received. //@ ignoreReturnValue export function on_received_message_from_parent(origin: string, received: JsonAction, s:IStackFrame): EventBinding { installReceiveMessage(s.rt, origin) var st = s.rt.webState var binding = st._onReceivedMessageEvent.addHandler(received); binding.data = origin; return binding; } function clearReceivedMessageEvent(rt:Runtime) { var s = rt.webState if (s._onReceivedMessageEvent) { if (s.receiveMessage) window.removeEventListener("message", s.receiveMessage, false); s._onReceivedMessageEvent = undefined; s._messageWaiters = undefined; } } //? Opens an Server-Sent-Events client on the given URL. If not supported, returns invalid. The server must implement CORS to allow https://www.touchdevelop.com to receive messages. // [result].writesMutable export function create_event_source(url: string, s: IStackFrame): WebEventSource { if (!url) Util.userError(lf("url cannot be empty"), s.pc); if (!!(<any>window).EventSource) { var source = new (<any>window).EventSource(url); return new WebEventSource(s.rt, source); } else { // Result to xhr polling :( return undefined; } } //? Parses a OAuth v2.0 access token from a redirect uri as described in http://tools.ietf.org/html/rfc6749. Returns invalid if the url does not contain an OAuth token. export function oauth_token_from_url(redirect_url : string) : OAuthResponse { return OAuthResponse.parse(redirect_url); } //? Parses a OAuth v2.0 access token from a JSON payload as described in http://tools.ietf.org/html/rfc6749. Returns invalid if the payload is not an OAuth token. export function oauth_token_from_json(response: JsonObject): OAuthResponse { return OAuthResponse.parseJSON(response); } } }
the_stack
import { skip } from "rxjs/operators"; import { PLATFORM } from "aurelia-pal"; import { PerformanceMeasurement } from "../../src/store"; import { LogLevel } from "../../src/aurelia-store"; import { createTestStore, testState, createStoreWithStateAndOptions } from "./helpers"; describe("store", () => { const UNREGISTERED_ACTION_ERROR_PREFIX = "Tried to dispatch an unregistered action "; const MINIMUM_ONE_PARAMETER_ERROR_PREFIX = "The reducer is expected to have one or more parameters"; const NOT_RETURNING_NEW_STATE_ERROR = "The reducer has to return a new state"; it("should accept an initial state", done => { const { initialState, store } = createTestStore(); store.state.subscribe((state) => { expect(state).toEqual(initialState); done(); }); }); it("should fail when dispatching unknown actions", async () => { const { store } = createTestStore(); const unregisteredAction = (currentState: testState, param1: number, param2: number) => { return Object.assign({}, currentState, { foo: param1 + param2 }) }; expect((store.dispatch as any)(unregisteredAction)).rejects.toThrowError(UNREGISTERED_ACTION_ERROR_PREFIX + "unregisteredAction"); }) it("should fail when dispatching non actions", async () => { const { store } = createTestStore(); expect(store.dispatch(undefined as any)).rejects.toThrowError(UNREGISTERED_ACTION_ERROR_PREFIX + "undefined"); }) it("should only accept reducers taking at least one parameter", () => { const { store } = createTestStore(); const fakeAction = () => { }; expect(() => { store.registerAction("FakeAction", fakeAction as any); }).toThrowError(MINIMUM_ONE_PARAMETER_ERROR_PREFIX); }); it("should force reducers to return a new state", async () => { const { store } = createTestStore(); const fakeAction = (_: testState) => { }; store.registerAction("FakeAction", fakeAction as any); expect(store.dispatch(fakeAction as any)).rejects.toThrowError(NOT_RETURNING_NEW_STATE_ERROR); }); it("should also accept false and stop queue", async () => { const { store } = createTestStore(); const nextSpy = spyOn((store as any)._state, "next").and.callThrough(); const fakeAction = (_: testState): false => false; store.registerAction("FakeAction", fakeAction); store.dispatch(fakeAction); expect(nextSpy).toHaveBeenCalledTimes(0); }); it("should also accept async false and stop queue", async () => { const { store } = createTestStore(); const nextSpy = spyOn((store as any)._state, "next").and.callThrough(); const fakeAction = (_: testState): Promise<false> => Promise.resolve<false>(false); store.registerAction("FakeAction", fakeAction); store.dispatch(fakeAction); expect(nextSpy).toHaveBeenCalledTimes(0); }); it("should unregister previously registered actions", async () => { const { store } = createTestStore(); const fakeAction = (currentState: testState) => currentState; store.registerAction("FakeAction", fakeAction); expect(store.dispatch(fakeAction)).resolves; store.unregisterAction(fakeAction); expect(store.dispatch(fakeAction)).rejects.toThrowError(UNREGISTERED_ACTION_ERROR_PREFIX + "fakeAction"); }); it("should not try to unregister previously unregistered actions", async () => { const { store } = createTestStore(); const fakeAction = (currentState: testState) => currentState; expect(() => store.unregisterAction(fakeAction)).not.toThrow(); }); it("should allow checking for already registered functions via Reducer", () => { const { store } = createTestStore(); const fakeAction = (currentState: testState) => currentState; store.registerAction("FakeAction", fakeAction); expect(store.isActionRegistered(fakeAction)).toBe(true); }); it("should allow checking for already registered functions via previously registered name", () => { const { store } = createTestStore(); const fakeAction = (currentState: testState) => currentState; store.registerAction("FakeAction", fakeAction); expect(store.isActionRegistered("FakeAction")).toBe(true); }); it("should accept reducers taking multiple parameters", done => { const { store } = createTestStore(); const fakeAction = (currentState: testState, param1: string, param2: string) => { return Object.assign({}, currentState, { foo: param1 + param2 }) }; store.registerAction("FakeAction", fakeAction as any); store.dispatch(fakeAction, "A", "B"); store.state.pipe( skip(1) ).subscribe((state) => { expect(state.foo).toEqual("AB"); done(); }); }); it("should queue the next state after dispatching an action", done => { const { store } = createTestStore(); const modifiedState = { foo: "bert" }; const fakeAction = (currentState: testState) => { return Object.assign({}, currentState, modifiedState); }; store.registerAction("FakeAction", fakeAction); store.dispatch(fakeAction); store.state.pipe( skip(1) ).subscribe((state) => { expect(state).toEqual(modifiedState); done(); }); }); it("should the previously registered action name as dispatch argument", done => { const { store } = createTestStore(); const modifiedState = { foo: "bert" }; const fakeAction = (_: testState) => Promise.resolve(modifiedState); const fakeActionRegisteredName = "FakeAction"; store.registerAction(fakeActionRegisteredName, fakeAction); store.dispatch(fakeActionRegisteredName); // since the async action is coming at a later time we need to skip the initial state store.state.pipe( skip(1) ).subscribe((state) => { expect(state).toEqual(modifiedState); done(); }); }); it("should support promised actions", done => { const { store } = createTestStore(); const modifiedState = { foo: "bert" }; const fakeAction = (_: testState) => Promise.resolve(modifiedState); store.registerAction("FakeAction", fakeAction); store.dispatch(fakeAction); // since the async action is coming at a later time we need to skip the initial state store.state.pipe( skip(1) ).subscribe((state) => { expect(state).toEqual(modifiedState); done(); }); }); it("should dispatch actions one after another", (done) => { const { store } = createTestStore(); const actionA = (currentState: testState) => Promise.resolve({ foo: currentState.foo + "A" }); const actionB = (currentState: testState) => Promise.resolve({ foo: currentState.foo + "B" }); store.registerAction("Action A", actionA); store.registerAction("Action B", actionB); store.dispatch(actionA); store.dispatch(actionB); store.state.pipe( skip(2) ).subscribe((state) => { expect(state.foo).toEqual("barAB"); done(); }); }); it("should maintain queue of execution in concurrency constraints", () => { const { store } = createTestStore(); spyOn((store as any).dispatchQueue, "push"); const handleQueueSpy = spyOn(store, "handleQueue"); const actionA = (_: testState) => Promise.resolve({ foo: "A" }); store.registerAction("Action A", actionA); store.dispatch(actionA); expect(handleQueueSpy).not.toHaveBeenCalled(); }); it("should log info about dispatched action if turned on via options", () => { const initialState: testState = { foo: "bar" }; const store = createStoreWithStateAndOptions<testState>(initialState, { logDispatchedActions: true }); const loggerSpy = spyOn((store as any).logger, "info"); const actionA = (_: testState) => Promise.resolve({ foo: "A" }); store.registerAction("Action A", actionA); store.dispatch(actionA); expect(loggerSpy).toHaveBeenCalled(); }); it("should log info about dispatched action if turned on via options via custom loglevel", () => { const initialState: testState = { foo: "bar" }; const store = createStoreWithStateAndOptions<testState>(initialState, { logDispatchedActions: true, logDefinitions: { dispatchedActions: LogLevel.debug } }); const loggerSpy = spyOn((store as any).logger, LogLevel.debug); const actionA = (_: testState) => Promise.resolve({ foo: "A" }); store.registerAction("Action A", actionA); store.dispatch(actionA); expect(loggerSpy).toHaveBeenCalled(); }); it("should log info about dispatched action and return to default log level if wrong one provided", () => { const initialState: testState = { foo: "bar" }; const store = createStoreWithStateAndOptions<testState>(initialState, { logDispatchedActions: true, logDefinitions: { dispatchedActions: "foo" as any } }); const loggerSpy = spyOn((store as any).logger, "info"); const actionA = (_: testState) => Promise.resolve({ foo: "A" }); store.registerAction("Action A", actionA); store.dispatch(actionA); expect(loggerSpy).toHaveBeenCalled(); }); it("should log start-end dispatch duration if turned on via options", async () => { const initialState: testState = { foo: "bar" }; const store = createStoreWithStateAndOptions<testState>( initialState, { measurePerformance: PerformanceMeasurement.StartEnd } ); const expectedMeasures = [ { duration: 1 }, { duration: 2 } ]; spyOn(PLATFORM.performance, "mark").and.callThrough(); spyOn(PLATFORM.performance, "measure").and.callThrough(); spyOn(PLATFORM.performance, "getEntriesByName").and.returnValue(expectedMeasures); const loggerSpy = spyOn((store as any).logger, "info"); const actionA = (_: testState) => { return new Promise<testState>((resolve) => { setTimeout(() => resolve({ foo: "A" }), 1); }); }; store.registerAction("Action A", actionA); await store.dispatch(actionA); expect(PLATFORM.performance.mark).toHaveBeenNthCalledWith(1, "dispatch-start"); expect(PLATFORM.performance.mark).toHaveBeenNthCalledWith(2, "dispatch-after-reducer-Action A"); expect(PLATFORM.performance.mark).toHaveBeenNthCalledWith(3, "dispatch-end"); expect(PLATFORM.performance.measure).toHaveBeenCalledWith( "startEndDispatchDuration", "dispatch-start", "dispatch-end" ); expect(PLATFORM.performance.getEntriesByName).toHaveBeenCalledWith("startEndDispatchDuration", "measure"); expect(loggerSpy).toHaveBeenCalledWith("Total duration 1 of dispatched action Action A:", expectedMeasures); }); it("should log all dispatch durations if turned on via options", async () => { const initialState: testState = { foo: "bar" }; const store = createStoreWithStateAndOptions<testState>( initialState, { measurePerformance: PerformanceMeasurement.All } ); const expectedMarks = [ { startTime: 1 }, { startTime: 10 }, { startTime: 100 }, ]; const expectedDuration = expectedMarks[2].startTime - expectedMarks[0].startTime; spyOn(PLATFORM.performance, "mark").and.callThrough(); spyOn(PLATFORM.performance, "getEntriesByType").and.returnValue(expectedMarks); const loggerSpy = spyOn((store as any).logger, "info"); const actionA = (_: testState) => { return new Promise<testState>((resolve) => { setTimeout(() => resolve({ foo: "A" }), 1); }); }; store.registerAction("Action A", actionA); await store.dispatch(actionA); expect(PLATFORM.performance.mark).toHaveBeenNthCalledWith(1, "dispatch-start"); expect(PLATFORM.performance.mark).toHaveBeenNthCalledWith(2, "dispatch-after-reducer-Action A"); expect(PLATFORM.performance.mark).toHaveBeenNthCalledWith(3, "dispatch-end"); expect(PLATFORM.performance.getEntriesByType).toHaveBeenCalledWith("mark"); expect(loggerSpy).toHaveBeenCalledWith( `Total duration ${expectedDuration} of dispatched action Action A:`, expectedMarks ); }); it("should clear only store marks and measures if log start-end dispatch duration turned on via options", async () => { const initialState: testState = { foo: "bar" }; const store = createStoreWithStateAndOptions<testState>( initialState, { measurePerformance: PerformanceMeasurement.StartEnd } ); PLATFORM.performance.mark("user mark 1"); PLATFORM.performance.mark("user mark 2"); PLATFORM.performance.measure("user measure", "user mark 1", "user mark 2"); spyOn(PLATFORM.performance, "clearMarks").and.callThrough(); spyOn(PLATFORM.performance, "clearMeasures").and.callThrough(); const actionA = (_: testState) => { return new Promise<testState>((resolve) => { setTimeout(() => resolve({ foo: "A" }), 1); }); }; store.registerAction("Action A", actionA); await store.dispatch(actionA); expect(PLATFORM.performance.clearMarks).toHaveBeenCalledWith("dispatch-start"); expect(PLATFORM.performance.clearMarks).toHaveBeenCalledWith("dispatch-after-reducer-Action A"); expect(PLATFORM.performance.clearMarks).toHaveBeenCalledWith("dispatch-end"); expect(PLATFORM.performance.clearMeasures).toHaveBeenCalledWith("startEndDispatchDuration"); expect(PLATFORM.performance.clearMarks).not.toHaveBeenCalledWith("user mark 1"); expect(PLATFORM.performance.clearMarks).not.toHaveBeenCalledWith("user mark 2"); expect(PLATFORM.performance.clearMeasures).not.toHaveBeenCalledWith("user measure"); }); it("should clear only store marks and measures if log all dispatch duration turned on via options", async () => { const initialState: testState = { foo: "bar" }; const store = createStoreWithStateAndOptions<testState>( initialState, { measurePerformance: PerformanceMeasurement.All } ); PLATFORM.performance.mark("user mark 1"); PLATFORM.performance.mark("user mark 2"); PLATFORM.performance.measure("user measure", "user mark 1", "user mark 2"); spyOn(PLATFORM.performance, "clearMarks").and.callThrough(); spyOn(PLATFORM.performance, "clearMeasures").and.callThrough(); const actionA = (_: testState) => { return new Promise<testState>((resolve) => { setTimeout(() => resolve({ foo: "A" }), 1); }); }; store.registerAction("Action A", actionA); await store.dispatch(actionA); expect(PLATFORM.performance.clearMarks).toHaveBeenCalledWith("dispatch-start"); expect(PLATFORM.performance.clearMarks).toHaveBeenCalledWith("dispatch-after-reducer-Action A"); expect(PLATFORM.performance.clearMarks).toHaveBeenCalledWith("dispatch-end"); expect(PLATFORM.performance.clearMarks).not.toHaveBeenCalledWith("user mark 1"); expect(PLATFORM.performance.clearMarks).not.toHaveBeenCalledWith("user mark 2"); expect(PLATFORM.performance.clearMeasures).not.toHaveBeenCalledWith("user measure"); }); it("should reset the state without going through the internal dispatch queue", async (done) => { const { initialState, store } = createTestStore(); const internalDispatchSpy = jest.spyOn((store as any), "internalDispatch"); const demoAction = (currentState: testState) => { return Object.assign({}, currentState, { foo: "demo" }) }; store.registerAction("demoAction", demoAction); await store.dispatch(demoAction); internalDispatchSpy.mockReset(); store.resetToState(initialState); store.state.subscribe((state) => { expect(internalDispatchSpy).not.toHaveBeenCalled(); expect(state.foo).toBe(initialState.foo); done(); }); }); describe("piped dispatch", () => { it("should fail when dispatching unknown actions", async () => { const { store } = createTestStore(); const unregisteredAction = (currentState: testState, param1: string) => { return Object.assign({}, currentState, { foo: param1 }); }; expect(() => store.pipe(unregisteredAction, "foo")).toThrowError(UNREGISTERED_ACTION_ERROR_PREFIX + "unregisteredAction"); }); it("should fail when at least one action is unknown", async () => { const { store } = createTestStore(); const fakeAction = (currentState: testState) => Object.assign({}, currentState); store.registerAction("FakeAction", fakeAction); const unregisteredAction = (currentState: testState, param1: string) => Object.assign({}, currentState, { foo: param1 }); const pipedDispatch = store.pipe(fakeAction); expect(() => pipedDispatch.pipe(unregisteredAction, "foo")).toThrowError(UNREGISTERED_ACTION_ERROR_PREFIX + "fakeAction"); }); it("should fail when dispatching non actions", async () => { const { store } = createTestStore(); expect(() => store.pipe(undefined as any)).toThrowError(UNREGISTERED_ACTION_ERROR_PREFIX + "undefined"); }); it("should fail when at least one action is no action", async () => { const { store } = createTestStore(); const fakeAction = (currentState: testState) => Object.assign({}, currentState); store.registerAction("FakeAction", fakeAction); const pipedDispatch = store.pipe(fakeAction); expect(() => pipedDispatch.pipe(undefined as any)).toThrowError(UNREGISTERED_ACTION_ERROR_PREFIX + "fakeAction"); }); it("should force reducer to return a new state", async () => { const { store } = createTestStore(); const fakeAction = (_: testState) => { }; store.registerAction("FakeAction", fakeAction as any); expect(store.pipe(fakeAction as any).dispatch()).rejects.toThrowError(NOT_RETURNING_NEW_STATE_ERROR); }); it("should force all reducers to return a new state", async () => { const { store } = createTestStore(); const fakeActionOk = (currentState: testState) => Object.assign({}, currentState); const fakeActionNok = (_: testState) => { }; store.registerAction("FakeActionOk", fakeActionOk); store.registerAction("FakeActionNok", fakeActionNok as any); expect(store.pipe(fakeActionNok as any).pipe(fakeActionOk).dispatch()).rejects.toThrowError(NOT_RETURNING_NEW_STATE_ERROR); }); it("should also accept false and stop queue", async () => { const { store } = createTestStore(); const nextSpy = spyOn((store as any)._state, "next").and.callThrough(); const fakeAction = (_: testState): false => false; store.registerAction("FakeAction", fakeAction); store.pipe(fakeAction).dispatch(); expect(nextSpy).toHaveBeenCalledTimes(0); }); it("should also accept async false and stop queue", async () => { const { store } = createTestStore(); const nextSpy = spyOn((store as any)._state, "next").and.callThrough(); const fakeAction = (_: testState): Promise<false> => Promise.resolve<false>(false); store.registerAction("FakeAction", fakeAction); store.pipe(fakeAction).dispatch(); expect(nextSpy).toHaveBeenCalledTimes(0); }); it("should accept reducers taking multiple parameters", done => { const { store } = createTestStore(); const fakeAction = (currentState: testState, param1: string, param2: string) => { return Object.assign({}, currentState, { foo: param1 + param2 }) }; store.registerAction("FakeAction", fakeAction as any); store.pipe(fakeAction, "A", "B").dispatch(); store.state.pipe( skip(1) ).subscribe((state) => { expect(state.foo).toEqual("AB"); done(); }); }); it("should queue the next state after dispatching an action", done => { const { store } = createTestStore(); const modifiedState = { foo: "bert" }; const fakeAction = (currentState: testState) => { return Object.assign({}, currentState, modifiedState); }; store.registerAction("FakeAction", fakeAction); store.pipe(fakeAction).dispatch(); store.state.pipe( skip(1) ).subscribe((state) => { expect(state).toEqual(modifiedState); done(); }); }); it("should accept the previously registered action name as pipe argument", done => { const { store } = createTestStore(); const modifiedState = { foo: "bert" }; const fakeAction = (_: testState) => Promise.resolve(modifiedState); const fakeActionRegisteredName = "FakeAction"; store.registerAction(fakeActionRegisteredName, fakeAction); store.pipe(fakeActionRegisteredName).dispatch(); // since the async action is coming at a later time we need to skip the initial state store.state.pipe( skip(1) ).subscribe((state) => { expect(state).toEqual(modifiedState); done(); }); }); it("should not accept an unregistered action name as pipe argument", () => { const { store } = createTestStore(); const unregisteredActionId = "UnregisteredAction"; expect(() => store.pipe(unregisteredActionId)).toThrowError(UNREGISTERED_ACTION_ERROR_PREFIX + unregisteredActionId); }); it("should support promised actions", done => { const { store } = createTestStore(); const modifiedState = { foo: "bert" }; const fakeAction = (_: testState) => Promise.resolve(modifiedState); store.registerAction("FakeAction", fakeAction); store.pipe(fakeAction).dispatch(); // since the async action is coming at a later time we need to skip the initial state store.state.pipe( skip(1) ).subscribe((state) => { expect(state).toEqual(modifiedState); done(); }); }); it("should dispatch actions one after another", (done) => { const { store } = createTestStore(); const actionA = (currentState: testState) => Promise.resolve({ foo: currentState.foo + "A" }); const actionB = (currentState: testState) => Promise.resolve({ foo: currentState.foo + "B" }); store.registerAction("Action A", actionA); store.registerAction("Action B", actionB); store.pipe(actionA).dispatch(); store.pipe(actionB).dispatch(); store.state.pipe( skip(2) ).subscribe((state) => { expect(state.foo).toEqual("barAB"); done(); }); }); it("should maintain queue of execution in concurrency constraints", () => { const { store } = createTestStore(); spyOn((store as any).dispatchQueue, "push"); const handleQueueSpy = spyOn(store, "handleQueue"); const actionA = (_: testState) => Promise.resolve({ foo: "A" }); store.registerAction("Action A", actionA); store.pipe(actionA).dispatch(); expect(handleQueueSpy).not.toHaveBeenCalled(); }); it("should log info about dispatched action if turned on via options", () => { const initialState: testState = { foo: "bar" }; const store = createStoreWithStateAndOptions<testState>(initialState, { logDispatchedActions: true }); const loggerSpy = spyOn((store as any).logger, "info"); const actionA = (_: testState) => Promise.resolve({ foo: "A" }); store.registerAction("Action A", actionA); store.pipe(actionA).dispatch(); expect(loggerSpy).toHaveBeenCalled(); }); it("should log info about dispatched action if turned on via options via custom loglevel", () => { const initialState: testState = { foo: "bar" }; const store = createStoreWithStateAndOptions<testState>(initialState, { logDispatchedActions: true, logDefinitions: { dispatchedActions: LogLevel.debug } }); const loggerSpy = spyOn((store as any).logger, LogLevel.debug); const actionA = (_: testState) => Promise.resolve({ foo: "A" }); store.registerAction("Action A", actionA); store.pipe(actionA).dispatch(); expect(loggerSpy).toHaveBeenCalled(); }); it("should log info about dispatched action and return to default log level if wrong one provided", () => { const initialState: testState = { foo: "bar" }; const store = createStoreWithStateAndOptions<testState>(initialState, { logDispatchedActions: true, logDefinitions: { dispatchedActions: "foo" as any } }); const loggerSpy = spyOn((store as any).logger, "info"); const actionA = (_: testState) => Promise.resolve({ foo: "A" }); store.registerAction("Action A", actionA); store.pipe(actionA).dispatch(); expect(loggerSpy).toHaveBeenCalled(); }); it("should log start-end dispatch duration if turned on via options", async () => { const initialState: testState = { foo: "bar" }; const store = createStoreWithStateAndOptions<testState>( initialState, { measurePerformance: PerformanceMeasurement.StartEnd } ); const expectedMeasures = [ { duration: 1 }, { duration: 2 } ]; spyOn(PLATFORM.performance, "mark").and.callThrough(); spyOn(PLATFORM.performance, "measure").and.callThrough(); spyOn(PLATFORM.performance, "getEntriesByName").and.returnValue(expectedMeasures); const loggerSpy = spyOn((store as any).logger, "info"); const actionA = (_: testState) => { return new Promise<testState>((resolve) => { setTimeout(() => resolve({ foo: "A" }), 1); }); }; store.registerAction("Action A", actionA); await store.pipe(actionA).dispatch(); expect(PLATFORM.performance.mark).toHaveBeenNthCalledWith(1, "dispatch-start"); expect(PLATFORM.performance.mark).toHaveBeenNthCalledWith(2, "dispatch-after-reducer-Action A"); expect(PLATFORM.performance.mark).toHaveBeenNthCalledWith(3, "dispatch-end"); expect(PLATFORM.performance.measure).toHaveBeenCalledWith( "startEndDispatchDuration", "dispatch-start", "dispatch-end" ); expect(PLATFORM.performance.getEntriesByName).toHaveBeenCalledWith("startEndDispatchDuration", "measure"); expect(loggerSpy).toHaveBeenCalledWith("Total duration 1 of dispatched action Action A:", expectedMeasures); }); it("should log all dispatch durations if turned on via options", async () => { const initialState: testState = { foo: "bar" }; const store = createStoreWithStateAndOptions<testState>( initialState, { measurePerformance: PerformanceMeasurement.All } ); const expectedMarks = [ { startTime: 1 }, { startTime: 10 }, { startTime: 100 }, ]; const expectedDuration = expectedMarks[2].startTime - expectedMarks[0].startTime; spyOn(PLATFORM.performance, "mark").and.callThrough(); spyOn(PLATFORM.performance, "getEntriesByType").and.returnValue(expectedMarks); const loggerSpy = spyOn((store as any).logger, "info"); const actionA = (_: testState) => { return new Promise<testState>((resolve) => { setTimeout(() => resolve({ foo: "A" }), 1); }); }; store.registerAction("Action A", actionA); await store.pipe(actionA).dispatch(); expect(PLATFORM.performance.mark).toHaveBeenNthCalledWith(1, "dispatch-start"); expect(PLATFORM.performance.mark).toHaveBeenNthCalledWith(2, "dispatch-after-reducer-Action A"); expect(PLATFORM.performance.mark).toHaveBeenNthCalledWith(3, "dispatch-end"); expect(PLATFORM.performance.getEntriesByType).toHaveBeenCalledWith("mark"); expect(loggerSpy).toHaveBeenCalledWith( `Total duration ${expectedDuration} of dispatched action Action A:`, expectedMarks ); }); it("should clear only store marks and measures if log start-end dispatch duration turned on via options", async () => { const initialState: testState = { foo: "bar" }; const store = createStoreWithStateAndOptions<testState>( initialState, { measurePerformance: PerformanceMeasurement.StartEnd } ); PLATFORM.performance.mark("user mark 1"); PLATFORM.performance.mark("user mark 2"); PLATFORM.performance.measure("user measure", "user mark 1", "user mark 2"); spyOn(PLATFORM.performance, "clearMarks").and.callThrough(); spyOn(PLATFORM.performance, "clearMeasures").and.callThrough(); const actionA = (_: testState) => { return new Promise<testState>((resolve) => { setTimeout(() => resolve({ foo: "A" }), 1); }); }; store.registerAction("Action A", actionA); await store.pipe(actionA).dispatch(); expect(PLATFORM.performance.clearMarks).toHaveBeenCalledWith("dispatch-start"); expect(PLATFORM.performance.clearMarks).toHaveBeenCalledWith("dispatch-after-reducer-Action A"); expect(PLATFORM.performance.clearMarks).toHaveBeenCalledWith("dispatch-end"); expect(PLATFORM.performance.clearMeasures).toHaveBeenCalledWith("startEndDispatchDuration"); expect(PLATFORM.performance.clearMarks).not.toHaveBeenCalledWith("user mark 1"); expect(PLATFORM.performance.clearMarks).not.toHaveBeenCalledWith("user mark 2"); expect(PLATFORM.performance.clearMeasures).not.toHaveBeenCalledWith("user measure"); }); it("should clear only store marks and measures if log all dispatch duration turned on via options", async () => { const initialState: testState = { foo: "bar" }; const store = createStoreWithStateAndOptions<testState>( initialState, { measurePerformance: PerformanceMeasurement.All } ); PLATFORM.performance.mark("user mark 1"); PLATFORM.performance.mark("user mark 2"); PLATFORM.performance.measure("user measure", "user mark 1", "user mark 2"); spyOn(PLATFORM.performance, "clearMarks").and.callThrough(); spyOn(PLATFORM.performance, "clearMeasures").and.callThrough(); const actionA = (_: testState) => { return new Promise<testState>((resolve) => { setTimeout(() => resolve({ foo: "A" }), 1); }); }; store.registerAction("Action A", actionA); await store.pipe(actionA).dispatch(); expect(PLATFORM.performance.clearMarks).toHaveBeenCalledWith("dispatch-start"); expect(PLATFORM.performance.clearMarks).toHaveBeenCalledWith("dispatch-after-reducer-Action A"); expect(PLATFORM.performance.clearMarks).toHaveBeenCalledWith("dispatch-end"); expect(PLATFORM.performance.clearMarks).not.toHaveBeenCalledWith("user mark 1"); expect(PLATFORM.performance.clearMarks).not.toHaveBeenCalledWith("user mark 2"); expect(PLATFORM.performance.clearMeasures).not.toHaveBeenCalledWith("user measure"); }); }); describe("internalDispatch", () => { it("should throw an error when called with unregistered actions", () => { const { store } = createTestStore(); const unregisteredAction = (currentState: testState, param1: string) => { return Object.assign({}, currentState, { foo: param1 }); }; expect((store as any).internalDispatch([{ reducer: unregisteredAction, params: ["foo"] }])).rejects.toThrowError(UNREGISTERED_ACTION_ERROR_PREFIX + "unregisteredAction"); }); it("should throw an error when one action of multiple actions is unregistered", () => { const { store } = createTestStore(); const registeredAction = (currentState: testState) => currentState; const unregisteredAction = (currentState: testState) => currentState; store.registerAction("RegisteredAction", registeredAction); expect((store as any).internalDispatch([ { reducer: registeredAction, params: [] }, { reducer: unregisteredAction, params: [] } ])).rejects.toThrowError(UNREGISTERED_ACTION_ERROR_PREFIX + "unregisteredAction"); }); it("should throw an error about the first of many unregistered actions", () => { const { store } = createTestStore(); const registeredAction = (currentState: testState) => currentState; const firstUnregisteredAction = (currentState: testState) => currentState; const secondUnregisteredAction = (currentState: testState) => currentState; store.registerAction("RegisteredAction", registeredAction); expect((store as any).internalDispatch([ { reducer: registeredAction, params: [] }, { reducer: firstUnregisteredAction, params: [] }, { reducer: secondUnregisteredAction, params: [] } ])).rejects.toThrowError(UNREGISTERED_ACTION_ERROR_PREFIX + "firstUnregisteredAction"); }); }); });
the_stack
import * as THREE from 'three'; import { GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js'; import * as glu from './gl_utils'; // @ts-ignore import { mergeBufferGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js'; import { SimpleTriangleBVH } from './bvh'; import { MaterialData, TexInfo, MaterialTextureInfo } from './material'; type DebugMode = "None" | "Albedo" | "Metalness" | "Roughness" | "Normals" | "Tangents" | "Bitangents" | "Transparency" | "UV0" | "Clearcoat"; type TonemappingMode = "None" | "Reinhard" | "Cineon" | "AcesFilm"; type SheenMode = "Charlie" | "Ashikhmin"; class Light { position = [1, 1, 1]; type = 0; emission = [1, 1, 1]; pad = 0; } export interface PathtracingRendererParameters { canvas?: HTMLCanvasElement; context?: WebGL2RenderingContext; } export class PathtracingRenderer { private gl: any; private canvas: any | undefined; private texArrayList: any[] = []; private texArrayDict: { [idx: string]: any; } = {}; private ibl: WebGLTexture | null = null; private renderBuffer: WebGLTexture | null = null; private copyBuffer: WebGLTexture | null = null; private copyFbo: WebGLFramebuffer | null = null; private fbo: WebGLFramebuffer | null = null; private quadVao: WebGLVertexArrayObject | null = null; private ptProgram: WebGLProgram | null = null; private copyProgram: WebGLProgram | null = null; private displayProgram: WebGLProgram | null = null; private quadVertexBuffer: WebGLBuffer | null = null; private pathtracingDataTextures: { [k: string]: WebGLTexture | null } = {}; private pathtracingTexturesArrays: { [k: string]: WebGLTexture | null } = {}; private renderRes: [number, number] = [0, 0]; private displayRes: [number, number] = [0, 0]; private _exposure = 1.0; public get exposure() { return this._exposure; } public set exposure(val) { this._exposure = val; this.resetAccumulation(); } public debugModes = ["None", "Albedo", "Metalness", "Roughness", "Normals", "Tangents", "Bitangents", "Transparency", "UV0", "Clearcoat"]; private _debugMode: DebugMode = "None"; public get debugMode() { return this._debugMode; } public set debugMode(val) { this._debugMode = val; this.resetAccumulation(); } public tonemappingModes = ["None", "Reinhard", "Cineon", "AcesFilm"]; private _tonemapping: TonemappingMode = "None"; public get tonemapping() { return this._tonemapping; } public set tonemapping(val) { this._tonemapping = val; this.resetAccumulation(); } public sheenGModes = ["Charlie", "Ashikhmin"]; private _sheenG: SheenMode = "Charlie"; public get sheenG() { return this._sheenG; } public set sheenG(val) { this._sheenG = val; this.resetAccumulation(); } private _maxBounces = 4; public get maxBounces() { return this._maxBounces; } public set maxBounces(val) { this._maxBounces = val; this.resetAccumulation(); } private _useIBL = true; public get useIBL() { return this._useIBL; } public set useIBL(val) { this._useIBL = val; this.resetAccumulation(); } private _showBackground = true; public get showBackground() { return this._showBackground; } public set showBackground(val) { this._showBackground = val; this.resetAccumulation(); } private _forceIBLEval = false; public get forceIBLEval() { return this._forceIBLEval; } public set forceIBLEval(val) { this._forceIBLEval = val; this.resetAccumulation(); } private _enableGamma = true; public get enableGamma() { return this._enableGamma; } public set enableGamma(val) { this._enableGamma = val; this.resetAccumulation(); } private _iblRotation = 0.0; public get iblRotation() { return this._iblRotation / Math.PI * 180.0; } public set iblRotation(val) { this._iblRotation = val / 180.0 * Math.PI; this.resetAccumulation(); } private _iblSampling = false; public get iblSampling() { return this._iblSampling; } public set iblSampling(val) { this._iblSampling = val; this.resetAccumulation(); } private _pixelRatio = 1.0; public get pixelRatio() { return this._pixelRatio; } public set pixelRatio(val) { this._pixelRatio = val; this.resize(this.canvas.width, this.canvas.height); this.resetAccumulation(); } private _backgroundColor = [0.0, 0.0, 0.0]; public get backgroundColor() { return this._backgroundColor; } public set backgroundColor(val) { this._backgroundColor = val; this.resetAccumulation(); } private _rayEps = 0.0001; public get rayEps() { return this._rayEps; } public set rayEps(val) { this._rayEps = val; this.resetAccumulation(); } private _frameCount = 1; private _isRendering = false; constructor(parameters: PathtracingRendererParameters = {}) { this.canvas = parameters.canvas ? parameters.canvas : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas'); this.gl = parameters.context ? parameters.context : this.canvas.getContext('webgl2', {alpha: true, powerPreference:"high-performance"}); this.gl.getExtension('EXT_color_buffer_float'); this.gl.getExtension('OES_texture_float_linear'); this.initRenderer(); } resetAccumulation() { this._frameCount = 1; } resize(width: number, height: number) { this._isRendering = false; this.displayRes = [width, height]; this.renderRes = [Math.ceil(this.displayRes[0] * this._pixelRatio), Math.ceil(this.displayRes[1] * this._pixelRatio)]; this.initFramebuffers(this.renderRes[0], this.renderRes[1]); this.resetAccumulation(); this._isRendering = true; } stopRendering() { this._isRendering = false; }; render(camera: THREE.PerspectiveCamera, num_samples: number, frameFinishedCB: (frameCount: number) => void, renderingFinishedCB: () => void) { if (camera instanceof THREE.Camera === false) { console.error('PathtracingRenderer.render: camera is not an instance of THREE.Camera.'); return; } this._isRendering = true; this.resetAccumulation(); let renderFrame = () => { if (!this._isRendering) { return; } let gl = this.gl; gl.useProgram(this.ptProgram); let numTextureSlots = 0; for (let t in this.pathtracingDataTextures) { gl.activeTexture(gl.TEXTURE0 + numTextureSlots++); gl.bindTexture(gl.TEXTURE_2D, this.pathtracingDataTextures[t]); } for (let t in this.pathtracingTexturesArrays) { gl.activeTexture(gl.TEXTURE0 + numTextureSlots++); gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.pathtracingTexturesArrays[t]); } gl.activeTexture(gl.TEXTURE0 + numTextureSlots) gl.bindTexture(gl.TEXTURE_2D, this.ibl); gl.uniform1i(gl.getUniformLocation(this.ptProgram, "u_samplerCube_EnvMap"), numTextureSlots++); let filmHeight = Math.tan(camera.fov * 0.5 * Math.PI / 180.0) * camera.near; gl.uniform1f(gl.getUniformLocation(this.ptProgram, "u_float_FilmHeight"), filmHeight); gl.uniformMatrix4fv(gl.getUniformLocation(this.ptProgram, "u_mat4_ViewMatrix"), false, new Float32Array(camera.matrixWorld.elements)); gl.uniform3f(gl.getUniformLocation(this.ptProgram, "u_vec3_CameraPosition"), camera.position.x, camera.position.y, camera.position.z); gl.uniform1i(gl.getUniformLocation(this.ptProgram, "u_int_FrameCount"), this._frameCount); gl.uniform1i(gl.getUniformLocation(this.ptProgram, "u_int_DebugMode"), this.debugModes.indexOf(this._debugMode)); gl.uniform1i(gl.getUniformLocation(this.ptProgram, "u_int_SheenG"), this.sheenGModes.indexOf(this._sheenG)); gl.uniform1i(gl.getUniformLocation(this.ptProgram, "u_bool_UseIBL"), this._useIBL); gl.uniform1f(gl.getUniformLocation(this.ptProgram, "u_float_iblRotation"), this._iblRotation); gl.uniform1i(gl.getUniformLocation(this.ptProgram, "u_bool_iblSampling"), this._iblSampling); gl.uniform1i(gl.getUniformLocation(this.ptProgram, "u_bool_ShowBackground"), this._showBackground); gl.uniform3fv(gl.getUniformLocation(this.ptProgram, "u_vec3_BackgroundColor"), this._backgroundColor); gl.uniform1i(gl.getUniformLocation(this.ptProgram, "u_int_maxBounces"), this._maxBounces); gl.uniform2f(gl.getUniformLocation(this.ptProgram, "u_vec2_InverseResolution"), 1.0 / this.renderRes[0], 1.0 / this.renderRes[1]); gl.uniform1f(gl.getUniformLocation(this.ptProgram, "u_float_FocalLength"), camera.near); gl.uniform1i(gl.getUniformLocation(this.ptProgram, "u_bool_forceIBLEval"), this._forceIBLEval); gl.uniform1f(gl.getUniformLocation(this.ptProgram, "u_float_rayEps"), this._rayEps); gl.bindVertexArray(this.quadVao); gl.viewport(0, 0, this.renderRes[0], this.renderRes[1]); // pathtracing render pass gl.bindFramebuffer(gl.FRAMEBUFFER, this.fbo); gl.activeTexture(gl.TEXTURE0 + numTextureSlots) gl.bindTexture(gl.TEXTURE_2D, this.copyBuffer); gl.uniform1i(gl.getUniformLocation(this.ptProgram, "u_sampler2D_PreviousTexture"), numTextureSlots); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.useProgram(null); // copy pathtracing render buffer // to be used as accumulation input for next frames raytracing pass gl.useProgram(this.copyProgram); gl.bindFramebuffer(gl.FRAMEBUFFER, this.copyFbo); gl.activeTexture(gl.TEXTURE0 + numTextureSlots) gl.bindTexture(gl.TEXTURE_2D, this.renderBuffer); gl.uniform1i(gl.getUniformLocation(this.copyProgram, "tex"), numTextureSlots); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); gl.bindFramebuffer(gl.FRAMEBUFFER, null); // display render pass gl.useProgram(this.displayProgram); gl.viewport(0, 0, this.displayRes[0], this.displayRes[1]); gl.uniform1i(gl.getUniformLocation(this.displayProgram, "tex"), numTextureSlots); gl.uniform1f(gl.getUniformLocation(this.displayProgram, "exposure"), this._exposure); gl.uniform1i(gl.getUniformLocation(this.displayProgram, "gamma"), this._enableGamma); gl.uniform1i(gl.getUniformLocation(this.displayProgram, "tonemappingMode"), this.tonemappingModes.indexOf(this._tonemapping)); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); gl.bindTexture(gl.TEXTURE_2D, null); gl.useProgram(null); gl.bindVertexArray(null); this._frameCount++; if (num_samples !== -1 && this._frameCount >= num_samples) { renderingFinishedCB(); // finished rendering num_samples this._isRendering = false; } frameFinishedCB(this._frameCount); requestAnimationFrame(renderFrame); }; requestAnimationFrame(renderFrame); // start render loop } private initFramebuffers(width: number, height: number) { const gl = this.gl; if (this.fbo !== undefined) { gl.deleteFramebuffer(this.fbo); gl.deleteFramebuffer(this.copyFbo); } if (this.renderBuffer !== undefined) { gl.deleteTexture(this.renderBuffer); gl.deleteTexture(this.copyBuffer); } this.renderBuffer = glu.createRenderBufferTexture(gl, null, width, height); this.fbo = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, this.fbo); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.renderBuffer, 0); gl.drawBuffers([ gl.COLOR_ATTACHMENT0 ]); // console.log(gl.checkFramebufferStatus(gl.FRAMEBUFFER)); this.copyBuffer = glu.createRenderBufferTexture(gl, null, width, height); this.copyFbo = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, this.copyFbo); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.copyBuffer, 0); gl.drawBuffers([ gl.COLOR_ATTACHMENT0 ]); // console.log(gl.checkFramebufferStatus(gl.FRAMEBUFFER)); gl.bindFramebuffer(gl.FRAMEBUFFER, null); } private async initRenderer() { this.resize(Math.floor(this.canvas.width), Math.floor(this.canvas.height)); let gl = this.gl; // glu.printGLInfo(gl); let vertexShader = ` #version 300 es layout(location = 0) in vec4 position; out vec2 uv; void main() { uv = (position.xy + vec2(1.0)) * 0.5; gl_Position = position; }`; let copyFragmentShader = `#version 300 es precision highp float; precision highp int; precision highp sampler2D; uniform sampler2D tex; in vec2 uv; out vec4 out_FragColor; void main() { // out_FragColor = texelFetch(tex, ivec2(gl_FragCoord.xy), 0); out_FragColor = texture(tex, uv); }`; let displayFragmentShader = await <Promise<string>>filePromiseLoader('./shader/display.frag'); this.copyProgram = glu.createProgramFromSource(gl, vertexShader, copyFragmentShader); this.displayProgram = glu.createProgramFromSource(gl, vertexShader, displayFragmentShader); // fullscreen quad position buffer const positions = new Float32Array([-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0]); this.quadVertexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); // fullscreen quad vao this.quadVao = gl.createVertexArray(); gl.bindVertexArray(this.quadVao); gl.enableVertexAttribArray(0); gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVertexBuffer); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, null); gl.bindVertexArray(null); } private parseTexture(tex: THREE.Texture) { let texInfo = new TexInfo(); let findTextureInList = (tex: THREE.Texture, texList: THREE.Texture[]) => { for (let i = 0; i < texList.length; i++) { if (tex.uuid === texList[i].uuid) return i; } return -1; }; let res = [tex.image.width, tex.image.height].join(','); if (res in this.texArrayDict) { let texArrayIdx = this.texArrayDict[res]; let texIdxInArray = findTextureInList(tex, this.texArrayList[texArrayIdx]); if (texIdxInArray < 0) { this.texArrayList[texArrayIdx].push(tex); texIdxInArray = this.texArrayList[texArrayIdx].length - 1; } texInfo.texArrayIdx = texArrayIdx; texInfo.texIdx = texIdxInArray; } else { this.texArrayDict[res] = this.texArrayList.length; let tex_array = [tex]; this.texArrayList.push(tex_array); texInfo.texArrayIdx = this.texArrayList.length - 1; texInfo.texIdx = 0; } texInfo.texOffset = [tex.offset.x, tex.offset.y]; texInfo.texScale = [tex.repeat.x, tex.repeat.y]; texInfo.texCoordSet = 0; // TODO Handle second uv set return texInfo; } private async parseMaterial(mat: any, gltf?: GLTF) { let matInfo = new MaterialData(); let matTexInfo = new MaterialTextureInfo(); matInfo.albedo = mat.color.toArray(); if (mat.map) { matTexInfo.albedoTexture = this.parseTexture(mat.map); } matInfo.metallic = mat.metalness || 0; matInfo.roughness = mat.roughness || 0; matInfo.doubleSided = mat.side == THREE.DoubleSide ? 1 : 0; matInfo.cutoutOpacity = mat.opacity; matInfo.alphaCutoff = mat.alphaTest; if (mat.alphaTest == 0.0 && !mat.transparent) matInfo.alphaCutoff = 1.0; if (mat.metalnessMap) { matTexInfo.metallicRoughnessTexture = this.parseTexture(mat.metalnessMap); } if (mat.normalMap) { matTexInfo.normalTexture = this.parseTexture(mat.normalMap); matInfo.normalScale = mat.normalScale.x; } if(mat.emissive) { matInfo.emission = mat.emissive.toArray(); if (mat.emissiveMap) { matTexInfo.emissionTexture = this.parseTexture(mat.emissiveMap); } } matInfo.clearcoat = mat.clearcoat || 0; if (mat.clearcoatMap) { matTexInfo.clearcoatTexture = this.parseTexture(mat.clearcoatMap); } matInfo.clearcoatRoughness = mat.clearcoatRoughness || 0; if (mat.clearcoatRoughnessMap) { matTexInfo.clearcoatRoughnessTexture = this.parseTexture(mat.clearcoatRoughnessMap); } matInfo.transparency = mat.transmission || 0; if (mat.transmissionMap) { matTexInfo.transmissionTexture = this.parseTexture(mat.transmissionMap); } matInfo.specular = (mat.specularIntensity === undefined) ? 1.0 : mat.specularIntensity; if(mat.specularTint) matInfo.specularTint = mat.specularTint.toArray(); if (mat.specularIntensityMap) { matTexInfo.specularTexture = this.parseTexture(mat.specularIntensityMap); } if (mat.specularTintMap) { matTexInfo.specularColorTexture = this.parseTexture(mat.specularTintMap); } // KHR_materials_volume if(mat.thickness) matInfo.thinWalled = mat.thickness == 0.01 ? 1 : 0; //hack: three.js defaults thickness to 0.01 when volume extensions doesn't exist. if(mat.attenuationTint) matInfo.attenuationColor = mat.attenuationTint.toArray(); matInfo.attenuationDistance = mat.attenuationDistance || matInfo.attenuationDistance; if(matInfo.attenuationDistance == 0.0) matInfo.attenuationDistance = Number.MAX_VALUE; // KHR_materials_ior matInfo.ior = mat.ior || matInfo.ior; if (gltf) { let setTextureTransformFromExt = (texInfo: TexInfo, ext: any) => { if ("extensions" in ext && "KHR_texture_transform" in ext.extensions) { let transform = ext.extensions["KHR_texture_transform"]; if ("offset" in transform) texInfo.texOffset = transform["offset"]; if ("scale" in transform) texInfo.texScale = transform["scale"]; } }; if ("gltfExtensions" in mat.userData) { let get_param = function (name: string, obj: any, default_value: any) { return (name in obj) ? obj[name] : default_value; }; let extensions = mat.userData.gltfExtensions; if ('3DS_materials_anisotropy' in extensions) { let ext = extensions["3DS_materials_anisotropy"]; matInfo.anisotropy = get_param("anisotropyFactor", ext, matInfo.anisotropy); matInfo.anisotropyRotation = get_param("anisotropyRotationFactor", ext, matInfo.anisotropyRotation); } if ('KHR_materials_anisotropy' in extensions) { let ext = extensions["KHR_materials_anisotropy"]; matInfo.anisotropy = get_param("anisotropyFactor", ext, matInfo.anisotropy); matInfo.anisotropyRotation = get_param("anisotropyRotationFactor", ext, matInfo.anisotropyRotation); } if ('3DS_materials_transparency' in extensions) { let ext = extensions["3DS_materials_transparency"]; matInfo.transparency = get_param("transparencyFactor", ext, matInfo.transparency); } if ('3DS_materials_specular' in extensions) { let ext = extensions["3DS_materials_specular"]; matInfo.specular = get_param("specularFactor", ext, matInfo.specular); matInfo.specularTint = get_param("specularColorFactor", ext, matInfo.specularTint); if ("specularTexture" in ext) { await gltf.parser.getDependency('texture', ext.specularTexture.index) .then((tex: THREE.Texture) => { matTexInfo.specularTexture = this.parseTexture(tex); setTextureTransformFromExt(matTexInfo.specularTexture, ext.specularTexture); }); } if ("specularColorTexture" in ext) { await gltf.parser.getDependency('texture', ext.specularColorTexture.index) .then((tex: THREE.Texture) => { matTexInfo.specularColorTexture = this.parseTexture(tex); setTextureTransformFromExt(matTexInfo.specularColorTexture, ext.specularColorTexture); }); } } if ('3DS_materials_ior' in extensions) { matInfo.ior = get_param("ior", extensions["3DS_materials_ior"], matInfo.ior); } if ('3DS_materials_clearcoat' in extensions) { let ext = extensions["3DS_materials_clearcoat"]; matInfo.clearcoat = get_param("clearcoatFactor", ext, matInfo.clearcoat); matInfo.clearcoatRoughness = get_param("clearcoatRoughnessFactor", ext, matInfo.clearcoatRoughness); } if ('KHR_materials_sheen' in extensions) { let ext = extensions["KHR_materials_sheen"]; matInfo.sheenColor = get_param("sheenColorFactor", ext, matInfo.sheenColor); matInfo.sheenRoughness = get_param("sheenRoughnessFactor", ext, matInfo.sheenRoughness); if ("sheenColorTexture" in ext) { await gltf.parser.getDependency('texture', ext.sheenColorTexture.index) .then((tex: THREE.Texture) => { matTexInfo.sheenColorTexture = this.parseTexture(tex); setTextureTransformFromExt(matTexInfo.sheenColorTexture, ext.sheenColorTexture); }); } if ("sheenRoughnessTexture" in ext) { await gltf.parser.getDependency('texture', ext.sheenRoughnessTexture.index) .then((tex: THREE.Texture) => { matTexInfo.sheenRoughnessTexture = this.parseTexture(tex); setTextureTransformFromExt(matTexInfo.sheenRoughnessTexture, ext.sheenRoughnessTexture); }); } } if ('KHR_materials_translucency' in extensions) { let ext = extensions["KHR_materials_translucency"]; matInfo.translucency = get_param("translucencyFactor", ext, matInfo.transparency); // if ("translucencyTexture" in ext) { // await this._gltf.parser.getDependency('texture', ext.translucencyTexture.index) // .then((tex) => { // matTexInfo.translucencyTexture = this.parseTexture(tex); // setTextureTransformFromExt(matTexInfo.translucencyTexture, ext.translucencyTexture); // }); // } } if ('3DS_materials_translucency' in extensions) { let ext = extensions["3DS_materials_translucency"]; matInfo.translucency = get_param("translucencyFactor", ext, matInfo.transparency); // if ("translucencyTexture" in ext) { // await this._gltf.parser.getDependency('texture', ext.translucencyTexture.index) // .then((tex) => { // matTexInfo.translucencyTexture = this.parseTexture(tex); // setTextureTransformFromExt(matTexInfo.translucencyTexture, ext.translucencyTexture); // }); // } } if ('3DS_materials_volume' in extensions) { let ext = extensions["3DS_materials_volume"]; matInfo.thinWalled = get_param("thinWalled", ext, matInfo.thinWalled); matInfo.attenuationColor = get_param("attenuationColor", ext, matInfo.attenuationColor); matInfo.attenuationDistance = get_param("attenuationDistance", ext, matInfo.attenuationDistance); matInfo.subsurfaceColor = get_param("subsurfaceColor", ext, matInfo.subsurfaceColor); } // if ('KHR_materials_sss' in extensions) { // let ext = extensions["KHR_materials_sss"]; // matInfo.scatterColor = get_param("scatterColor", ext, matInfo.scatterColor); // matInfo.scatterDistance = get_param("scatterDistance", ext, matInfo.scatterDistance); // } } } return [matInfo, matTexInfo]; } setIBL(texture: any) { let gl = this.gl; if (this.ibl !== undefined) this.gl.deleteTexture(this.ibl); this.ibl = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, this.ibl); // gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB32F, texture.image.width, texture.image.height, 0, gl.RGB, gl.FLOAT, texture.image.data); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); gl.bindTexture(gl.TEXTURE_2D, null); this.resetAccumulation(); } setScene(scene: THREE.Group, gltf?: GLTF) { this.stopRendering(); return new Promise<void>((resolve) => { this.createPathTracingScene(scene, gltf).then(() => { this.resetAccumulation(); resolve(); }); }); } // Initializes all necessary pathtracing related data structures from three scene private async createPathTracingScene(scene: THREE.Group, gltf?: GLTF) { console.time("Inititialized path-tracer"); this.texArrayDict = {}; for (let ta in this.texArrayList) { for (let t in this.texArrayList[ta]) { this.texArrayList[ta][t].dispose(); } } this.texArrayList = []; let lights: Light[] = []; let meshes: THREE.Mesh[] = []; let materialBuffer: MaterialData[] = []; let materialTextureInfoBuffer: MaterialTextureInfo[] = []; let triangleMaterialMarkers: number[] = []; let materials: THREE.MeshPhysicalMaterial[] = []; scene.traverse((child: any) => { if (child.isMesh || child.isLight) { if (child.isMesh) { if (child.material.length > 0) { materials.push(child.material[0]); } else { materials.push(child.material); } if (child.geometry.groups.length > 0) { for (let i = 0; i < child.geometry.groups.length; i++) { triangleMaterialMarkers.push((triangleMaterialMarkers.length > 0 ? triangleMaterialMarkers[triangleMaterialMarkers.length - 1] : 0) + child.geometry.groups[i].count / 3); } } else { triangleMaterialMarkers.push((triangleMaterialMarkers.length > 0 ? triangleMaterialMarkers[triangleMaterialMarkers.length - 1] : 0) + child.geometry.index.count / 3); } meshes.push(child); } else if (child.isLight) { let l = new Light(); let pos = new THREE.Vector3().setFromMatrixPosition(child.matrixWorld); l.position = pos.toArray(); // TODO clarify why l.type = (child.type === "PointLight") ? 0 : 1; l.emission = child.color.multiplyScalar(child.intensity).toArray(); lights.push(l); } } }); for (let m in materials) { const [matInfo, matTexInfo] = await this.parseMaterial(materials[m], gltf); materialBuffer.push(<MaterialData>matInfo); materialTextureInfoBuffer.push(<MaterialTextureInfo>matTexInfo); } await this.prepareDataBuffers(meshes, lights, materialBuffer, materialTextureInfoBuffer, triangleMaterialMarkers); console.timeEnd("Inititialized path-tracer"); }; private async prepareDataBuffers(meshList: THREE.Mesh[], lightList: Light[], materialBuffer: MaterialData[], materialTextureInfoBuffer: MaterialTextureInfo[], triangleMaterialMarkers: number[]) { let gl = this.gl; let geoList: THREE.BufferGeometry[] = []; for (let i = 0; i < meshList.length; i++) { let geo: THREE.BufferGeometry = <THREE.BufferGeometry>meshList[i].geometry.clone(); geo.applyMatrix4(meshList[i].matrixWorld); // mergeBufferGeometries expects consitent attributes throughout all geometries, otherwise it fails // we need to get rid of unsupported attributes const supportedAttributes = ["position", "normal", "tangent", "uv", "uv2", "color"]; for (let attr in geo.attributes) { if (!supportedAttributes.includes(attr)) delete geo.attributes[attr]; } if (!geo.attributes.normal) geo.computeVertexNormals(); if (geo.attributes.uv && !geo.attributes.tangent) geo.computeTangents(); const numVertices = geo.attributes.position.count; if (!geo.attributes.uv) { const uvs = new Float32Array(numVertices * 2); geo.setAttribute('uv', new THREE.BufferAttribute(uvs, 2)); } if (!geo.attributes.uv2) { const uvs = new Float32Array(numVertices * 2); geo.setAttribute('uv2', new THREE.BufferAttribute(uvs, 2)); } if (!geo.attributes.tangent) { const tangents = new Float32Array(numVertices * 4); geo.setAttribute('tangent', new THREE.BufferAttribute(tangents, 4)); } if (!geo.attributes.color) { const col = new Float32Array(numVertices * 4); geo.setAttribute('color', new THREE.BufferAttribute(col, 4)); } geo.morphAttributes = {}; geo.morphTargetsRelative = false;; geoList.push(geo); } // Merge geometry from all models into a single mesh // TODO get rid of this extra merge step and merge directly into the render data buffer let modelMesh = new THREE.Mesh(mergeBufferGeometries(geoList)); let bufferGeometry = <THREE.BufferGeometry>modelMesh.geometry; if (bufferGeometry.index) bufferGeometry = bufferGeometry.toNonIndexed(); let total_number_of_triangles = bufferGeometry.attributes.position.count / 3; console.time("BvhGeneration"); var vpa = new Float32Array(total_number_of_triangles * 12); var vna = bufferGeometry.attributes.normal.array; var vuv = bufferGeometry.attributes.uv.array; var vuv2 = bufferGeometry.attributes.uv2.array; let tga = bufferGeometry.attributes.tangent.array; let col = bufferGeometry.attributes.color.array; let materialIdx = 0; let pos = bufferGeometry.attributes.position.array; for (let i = 0; i < total_number_of_triangles; i++) { if (i >= triangleMaterialMarkers[materialIdx]) { materialIdx++; } vpa[i * 12 + 0] = pos[i * 9 + 0]; vpa[i * 12 + 1] = pos[i * 9 + 1]; vpa[i * 12 + 2] = pos[i * 9 + 2]; vpa[i * 12 + 3] = materialIdx; vpa[i * 12 + 4] = pos[i * 9 + 3]; vpa[i * 12 + 5] = pos[i * 9 + 4]; vpa[i * 12 + 6] = pos[i * 9 + 5]; vpa[i * 12 + 7] = materialIdx; vpa[i * 12 + 8] = pos[i * 9 + 6]; vpa[i * 12 + 9] = pos[i * 9 + 7]; vpa[i * 12 + 10] = pos[i * 9 + 8]; vpa[i * 12 + 11] = materialIdx; } let bvh = new SimpleTriangleBVH(4); bvh.build(vpa); const numFloatsPerVertex = 20; var combinedMeshBuffer = new Float32Array(total_number_of_triangles * 3 * numFloatsPerVertex); for (let i = 0; i < total_number_of_triangles; i++) { let srcTriangleIdx = bvh.m_pTriIndices[i]; for (let vertIdx = 0; vertIdx < 3; vertIdx++) { let dstIdx = i * numFloatsPerVertex * 3 + vertIdx * numFloatsPerVertex; // position let srcIdx = srcTriangleIdx * 12 + vertIdx * 4; combinedMeshBuffer[dstIdx + 0] = vpa[srcIdx + 0]; combinedMeshBuffer[dstIdx + 1] = vpa[srcIdx + 1]; combinedMeshBuffer[dstIdx + 2] = vpa[srcIdx + 2]; combinedMeshBuffer[dstIdx + 3] = vpa[srcIdx + 3]; // normal srcIdx = srcTriangleIdx * 9 + vertIdx * 3; combinedMeshBuffer[dstIdx + 4] = vna[srcIdx + 0]; combinedMeshBuffer[dstIdx + 5] = vna[srcIdx + 1]; combinedMeshBuffer[dstIdx + 6] = vna[srcIdx + 2]; combinedMeshBuffer[dstIdx + 7] = 0.0; // uv0 srcIdx = srcTriangleIdx * 6 + vertIdx * 2; combinedMeshBuffer[dstIdx + 8] = vuv[srcIdx]; combinedMeshBuffer[dstIdx + 9] = vuv[srcIdx + 1]; // uv1 combinedMeshBuffer[dstIdx + 10] = vuv2[srcIdx]; combinedMeshBuffer[dstIdx + 11] = vuv2[srcIdx + 1]; // tangent srcIdx = srcTriangleIdx * 12 + vertIdx * 4; combinedMeshBuffer[dstIdx + 12] = tga[srcIdx + 0]; combinedMeshBuffer[dstIdx + 13] = tga[srcIdx + 1]; combinedMeshBuffer[dstIdx + 14] = tga[srcIdx + 2]; combinedMeshBuffer[dstIdx + 15] = tga[srcIdx + 3]; // color combinedMeshBuffer[dstIdx + 16] = col[srcIdx + 0]; combinedMeshBuffer[dstIdx + 17] = col[srcIdx + 1]; combinedMeshBuffer[dstIdx + 18] = col[srcIdx + 2]; combinedMeshBuffer[dstIdx + 19] = col[srcIdx + 3]; } } bufferGeometry.dispose(); let flatBVHData = bvh.createAndCopyToFlattenedArray_StandardFormat(); let flatMaterialParamList = materialBuffer.map((matInfo) => { return Object.values(matInfo.data); }); let flatTextureParamList = materialTextureInfoBuffer.map(matTexInfo => { let texInfos = Object.values(matTexInfo); return texInfos.map(texInfo => { return flattenArray(texInfo.data); }); }); // clear data textures and texture arrays for (let t in this.pathtracingTexturesArrays) { if (this.pathtracingTexturesArrays[t] !== undefined) { gl.deleteTexture(this.pathtracingTexturesArrays[t]); } } this.pathtracingTexturesArrays = {}; for (let t in this.pathtracingDataTextures) { if (this.pathtracingDataTextures[t] !== undefined) { gl.deleteTexture(this.pathtracingDataTextures[t]); } } this.pathtracingDataTextures = {} as { [k: string]: WebGLTexture | null }; this.pathtracingDataTextures["u_sampler2D_BVHData"] = glu.createDataTexture(gl, flatBVHData); this.pathtracingDataTextures["u_sampler2D_TriangleData"] = glu.createDataTexture(gl, combinedMeshBuffer); this.pathtracingDataTextures["u_sampler2D_MaterialData"] = glu.createDataTexture(gl, new Float32Array(flattenArray(flatMaterialParamList))); this.pathtracingDataTextures["u_sampler2D_MaterialTexInfoData"] = glu.createDataTexture(gl, new Float32Array(flattenArray(flatTextureParamList))); // TODO can be byte type let shaderChunks: { [k: string]: string } = {}; // single pointlight as static define sufficient for now, need to reduce texture usage :/ shaderChunks['pathtracing_lights'] = ` ` if (lightList.length > 0) { // lightTexture = createDataTexture(lightList, THREE.RGBAFormat, THREE.FloatType); // THREE.ShaderChunk[ 'pathtracing_lights' ] = ` // #define HAS_LIGHTS 1 // const uint LIGHT_SIZE = 2u; // uniform sampler2D u_sampler2D_LightData; // const int numLights = ${lightList.length}; //` //_pathTracingUniforms["u_sampler2D_LightData"] = {type: "t", value: lightTexture}; let pos = lightList[0].position; let em = lightList[0].emission; shaderChunks['pathtracing_lights'] = ` #define HAS_LIGHTS 1 const vec3 cPointLightPosition = vec3(${pos[0]}, ${pos[1]}, ${pos[2]}); const vec3 cPointLightEmission = vec3(${em[0]}, ${em[1]}, ${em[2]}); ` } // create texture arrays function getImageData(image: ImageBitmap) { const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; const context = canvas.getContext('2d'); if (context) { context.drawImage(image, 0, 0); return context.getImageData(0, 0, image.width, image.height); } else { throw Error("Couldn't parse image data from texture"); } } // create texture arrays for current scene and // create shader snippet for texture array access let tex_array_shader_snippet = ""; for (let i = 0; i < this.texArrayList.length; i++) { const texList = this.texArrayList[i]; const texSize = texList[0].image.width * texList[0].image.height * 4; let data = new Uint8Array(texSize * texList.length); data.set(getImageData(texList[0].image).data); for (let t = 1; t < texList.length; t++) { data.set(getImageData(texList[t].image).data, texSize * t); } let texArray = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D_ARRAY, texArray); gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_WRAP_T, gl.REPEAT); gl.texImage3D( gl.TEXTURE_2D_ARRAY, 0, gl.RGBA, texList[0].image.width, texList[0].image.height, texList.length, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); gl.bindTexture(gl.TEXTURE_2D_ARRAY, null); console.log(`Create texture array: ${texList[0].image.width} x ${texList[0].image.height} x ${texList.length}`) this.pathtracingTexturesArrays[`u_sampler2DArray_MaterialTextures_${i}`] = texArray; tex_array_shader_snippet += `uniform sampler2DArray u_sampler2DArray_MaterialTextures_${i};\n` } tex_array_shader_snippet += "\n"; tex_array_shader_snippet += "vec4 evaluateMaterialTextureValue(const in TexInfo texInfo, const in vec2 texCoord) { \n"; for (let i = 0; i < this.texArrayList.length; i++) { tex_array_shader_snippet += ` if(texInfo.texArrayIdx == ${i}) {\n` tex_array_shader_snippet += ` vec2 tuv = texCoord * texInfo.texScale + texInfo.texOffset;` tex_array_shader_snippet += ` return texture(u_sampler2DArray_MaterialTextures_${i}, vec3(tuv, texInfo.texIdx));\n` tex_array_shader_snippet += " }\n"; } tex_array_shader_snippet += ` return vec4(1.0);\n` tex_array_shader_snippet += "}\n"; shaderChunks['pathtracing_tex_array_lookup'] = tex_array_shader_snippet; let vertexShader = await <Promise<string>>filePromiseLoader('./shader/pt.vert'); let fragmentShader = await <Promise<string>>filePromiseLoader('./shader/pt.frag'); shaderChunks['pathtracing_rng'] = await <Promise<string>>filePromiseLoader('./shader/rng.glsl'); shaderChunks['pathtracing_utils'] = await <Promise<string>>filePromiseLoader('./shader/utils.glsl'); shaderChunks['pathtracing_material'] = await <Promise<string>>filePromiseLoader('./shader/material.glsl'); shaderChunks['pathtracing_dspbr'] = await <Promise<string>>filePromiseLoader('./shader/dspbr.glsl'); shaderChunks['pathtracing_rt_kernel'] = await <Promise<string>>filePromiseLoader('./shader/rt_kernel.glsl'); shaderChunks['pathtracing_defines'] = ` const float PI = 3.14159265358979323; const float TWO_PI = 6.28318530717958648; const float FOUR_PI = 12.5663706143591729; const float ONE_OVER_PI = 0.31830988618379067; const float ONE_OVER_TWO_PI = 0.15915494309; const float ONE_OVER_FOUR_PI = 0.07957747154594767; const float PI_OVER_TWO = 1.57079632679489662; const float ONE_OVER_THREE = 0.33333333333333333; const float E = 2.71828182845904524; const float INFINITY = 1000000.0; const float EPS_COS = 0.001; const float EPS_PDF = 0.001; const float EPSILON = 1e-8; const float MINIMUM_ROUGHNESS = 0.0001; const float TFAR_MAX = 100000.0; const float RR_TERMINATION_PROB = 0.9; const uint MATERIAL_SIZE = 9u; const uint MATERIAL_TEX_INFO_SIZE = 11u; const uint TEX_INFO_SIZE = 2u; const uint VERTEX_STRIDE = 5u; const uint TRIANGLE_STRIDE = 3u*VERTEX_STRIDE; const uint POSITION_OFFSET = 0u; const uint NORMAL_OFFSET = 1u; const uint UV_OFFSET = 2u; const uint TANGENT_OFFSET = 3u; const uint COLOR_OFFSET = 4u; const uint NUM_TRIANGLES = ${total_number_of_triangles}u; const uint MAX_TEXTURE_SIZE = ${glu.getMaxTextureSize(gl)}u; `; this.ptProgram = glu.createProgramFromSource(gl, vertexShader, fragmentShader, shaderChunks); gl.useProgram(this.ptProgram); let numTextureSlots = 0; for (let t in this.pathtracingDataTextures) { let loc = gl.getUniformLocation(this.ptProgram, t); gl.uniform1i(loc, numTextureSlots++); } for (let t in this.pathtracingTexturesArrays) { let loc = gl.getUniformLocation(this.ptProgram, t); gl.uniform1i(loc, numTextureSlots++); } gl.useProgram(null); console.timeEnd("BvhGeneration"); this.resetAccumulation(); } } const fileLoader = new THREE.FileLoader(); function filePromiseLoader(url: string, onProgress?: () => void) { return new Promise<string | ArrayBuffer>((resolve, reject) => { fileLoader.load(url, resolve, onProgress, reject); }); }; function flattenArray(arr: any, result: number[] = []) { for (let i = 0, length = arr.length; i < length; i++) { const value: any = arr[i]; if (Array.isArray(value)) { flattenArray(value, result); } else { result.push(<number>value); } } return result; };
the_stack
/// <reference types="node" /> export interface ClientOptions { /** * How many seconds to wait until retrying a failed server. * @default 60 */ failoverTime?: number; /** * The number of times to retry an operation in lieu of failures. * @default 2 */ retries?: number; /** * @default 0.2 */ retry_delay?: number; /** * The default expiration in seconds to use. A `0` means never expire, * if it is greater than 30 days (60 x 60 x 24 x 30), it is * treated as a UNIX time (number of seconds since January 1, 1970). * @default 0 */ expires?: number; /** * A logger object that responds to `log(string)` method calls. * @default console */ logger?: { log(...args: any[]): void; }; } export class Client { /** * Creates a new client given an optional config string and optional hash of * options. The config string should be of the form: * * "[user:pass@]server1[:11211],[user:pass@]server2[:11211],..." * * If the argument is not given, fallback on the `MEMCACHIER_SERVERS` environment * variable, `MEMCACHE_SERVERS` environment variable or `"localhost:11211"`. * * The options hash may contain the options: * * * `retries` - the number of times to retry an operation in lieu of failures * (default 2) * * `expires` - the default expiration in seconds to use (default 0 - never * expire). If `expires` is greater than 30 days (60 x 60 x 24 x 30), it is * treated as a UNIX time (number of seconds since January 1, 1970). * * `logger` - a logger object that responds to `log(string)` method calls. * * `failover` - whether to failover to next server. Defaults to false. * * `failoverTime` - how much to wait until retring a failed server. Default * is 60 seconds. * * ~~~~ * log(msg1[, msg2[, msg3[...]]]) * ~~~~ * * Defaults to `console`. * * Or options for the servers including: * * `username` and `password` for fallback SASL authentication credentials. * * `timeout` in seconds to determine failure for operations. Default is 0.5 * seconds. * * 'conntimeout' in seconds to connection failure. Default is twice the value * of `timeout`. * * `keepAlive` whether to enable keep-alive functionality. Defaults to false. * * `keepAliveDelay` in seconds to the initial delay before the first keepalive * probe is sent on an idle socket. Defaults is 30 seconds. */ static create(serversStr?: string, options?: ClientOptions): Client; servers: string[]; /** * Client initializer takes a list of Servers and an options dictionary. See Client.create for details. * @param servers * @param options */ constructor(servers: string, options?: ClientOptions); /** * Chooses the server to talk to by hashing the given key. * @param key */ server(key: string): string; /** * GET * * Retrieves the value at the given key in memcache. * * The callback signature is: * * callback(err, value, flags) * * _value_ and _flags_ are both `Buffer`s. If the key is not found, the * callback is invoked with null for both arguments and no error * @param key * @param callback */ get(key: string): Promise<{ value: Buffer; flags: Buffer }>; get( key: string, callback: (err: Error | null, value: Buffer | null, flags: Buffer | null) => void ): void; /** * SET * * Sets the given _key_ and _value_ in memcache. * * The options dictionary takes: * * _expires_: overrides the default expiration (see `Client.create`) for this * particular key-value pair. * * The callback signature is: * * callback(err, success) * @param key * @param value * @param options * @param callback */ set(key: string, value: string | Buffer, options: { expires?: number }): Promise<boolean>; set( key: string, value: string | Buffer, options: { expires?: number }, callback: (err: Error | null, success: boolean | null) => void ): void; /** * ADD * * Adds the given _key_ and _value_ to memcache. The operation only succeeds * if the key is not already set. * * The options dictionary takes: * * _expires_: overrides the default expiration (see `Client.create`) for this * particular key-value pair. * * The callback signature is: * * callback(err, success) * @param key * @param value * @param options * @param callback */ add(key: string, value: string | Buffer, options: { expires?: number }): Promise<boolean>; add( key: string, value: string | Buffer, options: { expires?: number }, callback: (err: Error | null, success: boolean | null) => void ): void; /** * REPLACE * * Replaces the given _key_ and _value_ to memcache. The operation only succeeds * if the key is already present. * * The options dictionary takes: * * _expires_: overrides the default expiration (see `Client.create`) for this * particular key-value pair. * * The callback signature is: * * callback(err, success) * @param key * @param value * @param options * @param callback */ replace(key: string, value: string | Buffer, options: { expires?: number }): Promise<boolean>; replace( key: string, value: string | Buffer, options: { expires?: number }, callback: (err: Error | null, success: boolean | null) => void ): void; /** * DELETE * * Deletes the given _key_ from memcache. The operation only succeeds * if the key is already present. * * The callback signature is: * * callback(err, success) * @param key * @param callback */ delete(key: string): Promise<boolean>; delete(key: string, callback: (err: Error | null, success: boolean | null) => void): void; /** * INCREMENT * * Increments the given _key_ in memcache. * * The options dictionary takes: * * _initial_: the value for the key if not already present, defaults to 0. * * _expires_: overrides the default expiration (see `Client.create`) for this * particular key-value pair. * * The callback signature is: * * callback(err, success, value) * @param key * @param amount * @param options * @param callback */ increment( key: string, amount: number, options: { initial?: number; expires?: number } ): Promise<{ success: boolean; value?: number | null }>; increment( key: string, amount: number, options: { initial?: number; expires?: number }, callback: (err: Error | null, success: boolean | null, value?: number | null) => void ): void; /** * DECREMENT * * Decrements the given _key_ in memcache. * * The options dictionary takes: * * _initial_: the value for the key if not already present, defaults to 0. * * _expires_: overrides the default expiration (see `Client.create`) for this * particular key-value pair. * * The callback signature is: * * callback(err, success, value) * @param key * @param amount * @param options * @param callback */ decrement( key: string, amount: number, options: { initial?: number; expires?: number } ): Promise<{ success: boolean; value?: number | null }>; decrement( key: string, amount: number, options: { initial?: number; expires?: number }, callback: (err: Error | null, success: boolean | null, value?: number | null) => void ): void; /** * APPEND * * Append the given _value_ to the value associated with the given _key_ in * memcache. The operation only succeeds if the key is already present. The * callback signature is: * * callback(err, success) * @param key * @param value * @param callback */ append(key: string, value: string | Buffer): Promise<boolean>; append( key: string, value: string | Buffer, callback: (err: Error | null, success: boolean | null) => void ): void; /** * PREPEND * * Prepend the given _value_ to the value associated with the given _key_ in * memcache. The operation only succeeds if the key is already present. The * callback signature is: * * callback(err, success) * @param key * @param value * @param callback */ prepend(key: string, value: string | Buffer): Promise<boolean>; prepend( key: string, value: string | Buffer, callback: (err: Error | null, success: boolean | null) => void ): void; /** * TOUCH * * Touch sets an expiration value, given by _expires_, on the given _key_ in * memcache. The operation only succeeds if the key is already present. The * callback signature is: * * callback(err, success) * @param key * @param expires * @param callback */ touch(key: string, expires: number): Promise<boolean>; touch( key: string, expires: number, callback: (err: Error | null, success: boolean | null) => void ): void; /** * FLUSH * * Flushes the cache on each connected server. The callback signature is: * * callback(lastErr, results) * * where _lastErr_ is the last error encountered (or null, in the common case * of no errors). _results_ is a dictionary mapping `"hostname:port"` to either * `true` (if the operation was successful), or an error. * @param callback */ flush(): Promise<Record<string, boolean>>; flush(callback: (err: Error | null, results: Record<string, boolean>) => void): void; /** * STATS_WITH_KEY * * Sends a memcache stats command with a key to each connected server. The * callback is invoked **ONCE PER SERVER** and has the signature: * * callback(err, server, stats) * * _server_ is the `"hostname:port"` of the server, and _stats_ is a dictionary * mapping the stat name to the value of the statistic as a string. * @param key * @param callback */ statsWithKey( key: string, callback?: (err: Error | null, server: string, stats: Record<string, string> | null) => void ): void; /** * STATS * * Fetches memcache stats from each connected server. The callback is invoked * **ONCE PER SERVER** and has the signature: * * callback(err, server, stats) * * _server_ is the `"hostname:port"` of the server, and _stats_ is a * dictionary mapping the stat name to the value of the statistic as a string. * @param callback */ stats( callback?: (err: Error | null, server: string, stats: Record<string, string> | null) => void ): void; /** * RESET_STATS * * Reset the statistics each server is keeping back to zero. This doesn't clear * stats such as item count, but temporary stats such as total number of * connections over time. * * The callback is invoked **ONCE PER SERVER** and has the signature: * * callback(err, server) * * _server_ is the `"hostname:port"` of the server. * @param callback */ resetStats( callback?: (err: Error | null, server: string, stats: Record<string, string> | null) => void ): void; /** * QUIT * * Closes the connection to each server, notifying them of this intention. Note * that quit can race against already outstanding requests when those requests * fail and are retried, leading to the quit command winning and closing the * connection before the retries complete. */ quit(): void; /** * CLOSE * * Closes (abruptly) connections to all the servers. */ close(): void; /** * Perform a generic single response operation (get, set etc) on a server * serv: the server to perform the operation on * request: a buffer containing the request * seq: the sequence number of the operation. It is used to pin the callbacks * to a specific operation and should never change during a `perform`. * callback: a callback invoked when a response is received or the request * fails * retries: number of times to retry request on failure * @param key * @param request * @param seq * @param callback * @param retries */ perform( key: string, request: Buffer, seq: number, callback?: (err: Error | null, ...args: any[]) => void, retries?: number ): void; }
the_stack
import { EventEmitter } from 'events'; import { ErrorDetails, ErrorTypes } from '../core/errors'; import LasEvents from '../core/events'; import { LasMainConfig } from '../types/core'; import { AudioSample, AudioTrack, MP4AudioSample, MP4VideoSample, TrackType, VideoSample, VideoTrack, MP4Segment } from '../types/remux'; import { AAC_SAMPLE_DURATION, getAACFrameDuration, getAACSilentFrame } from '../utils/aac-helper'; import { Log } from '../utils/log'; import MP4 from './mp4-generator'; // 100 seconds const MAX_FILL_FRAME_DURATION = 100 * 1000; const DEFAULT_VIDEO_SAMPLE_DURATION = 40; type VideoTimeReferenceInfo = { track: VideoTrack; sample?: VideoSample }; class MP4Remuxer { private tag = 'MP4Remuxer'; private _eventEmitter: EventEmitter; private _forceFirstIDR: boolean; private _videoTimeReference: boolean; private _videoTimeReferenceInfo: VideoTimeReferenceInfo; private _extra: any; private _nextAudioPTS?: number; private _nextVideoDTS?: number; private _initPTS?: number; private _videoLastPTS: number = 0; private _audioLastPTS: number = 0; private _videoSampleDuration: number = DEFAULT_VIDEO_SAMPLE_DURATION; private _moovs?: Partial<Record<TrackType, Uint8Array>>; constructor(eventEmitter: EventEmitter, config: LasMainConfig) { this._eventEmitter = eventEmitter; this._videoTimeReference = !config.gopRemux; // 计算平均sampleDuration this._videoTimeReferenceInfo = <VideoTimeReferenceInfo>{}; this._forceFirstIDR = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; } public resetMoov(): void { this._moovs = undefined; this._clearVideoTimeReference(); } public setExtra(data: any) { this._extra = data; } public resetTimeStamp() { this._initPTS = undefined; this._audioLastPTS = this._videoLastPTS = 0; } public getLastPTS() { return { video: this._videoLastPTS, audio: this._audioLastPTS }; } public flush() { let videoData; const info = this._videoTimeReferenceInfo; if (this._videoTimeReference && info.sample) { info.track.samples = [info.sample]; info.track.sequenceNumber++; info.sample = undefined; videoData = this._remuxVideo(info.track, true, false); } this._clearVideoTimeReference(); return videoData; } public remux(audioTrack: AudioTrack, videoTrack: VideoTrack, timeOffset: number, isContinuous: boolean, isFlush: boolean = false) { if (!this._moovs) { this._initMP4(audioTrack, videoTrack, timeOffset); } if (this._moovs) { let audioData: MP4Segment | undefined; let videoData: MP4Segment | undefined; if (audioTrack.samples.length && videoTrack.samples.length) { if (!isContinuous) { // 起始位置音视频不对齐,音频开始时间小于视频开始时间,填帧 if (audioTrack.samples[0].pts < videoTrack.samples[0].pts) { const sample = Object.assign({}, videoTrack.samples[0]); sample.dts = sample.pts = audioTrack.samples[0].pts; videoTrack.samples.unshift(sample); } } } // 兼容safari if (!isContinuous && videoTrack.samples.length) { videoTrack.samples[0].pts = videoTrack.samples[0].dts; } audioData = this._remuxAudio(audioTrack, isContinuous); videoData = this._remuxVideo(videoTrack, isContinuous, !isFlush); if (!videoData && isFlush && this._videoTimeReferenceInfo.sample) { videoData = this.flush(); } if (videoData && !audioData && audioTrack.codec) { audioData = this._fillEmptyAudio(audioTrack, isContinuous, videoData.startPTS, videoData.endPTS, videoData.streamDTS); } const segments = []; if (audioData) { segments.push(audioData); } if (videoData) { segments.push(videoData); } if (segments.length) { this._eventEmitter.emit(LasEvents.MP4_SEGMENT, { segments, extra: this._extra }); } } } /** * 初始化mp4,生成moov,获取mediainfo * @param audioTrack 音频track * @param videoTrack 视频track * @param timeOffset 时间偏移量 */ private _initMP4(audioTrack: AudioTrack, videoTrack: VideoTrack, timeOffset: number): void { const eventEmitter = this._eventEmitter, audioSamples = audioTrack.samples, videoSamples = videoTrack.samples, mediaInfo: any = {}, moovs: Partial<Record<TrackType, Uint8Array>> = {}; let initPTS; if (audioTrack.config && audioSamples.length) { audioTrack.timescale = audioTrack.samplerate; moovs.audio = MP4.moov([audioTrack]); mediaInfo.audioCodec = audioTrack.codec; mediaInfo.channelCount = audioTrack.channelCount; mediaInfo.audioSampleRate = audioTrack.samplerate; mediaInfo.hasAudio = true; mediaInfo.defaultAudioCodec = audioTrack.defaultCodec initPTS = audioSamples[0].pts - audioTrack.inputTimescale * timeOffset; } if (videoTrack.sps && videoTrack.pps && videoSamples.length) { const inputTimeScale = videoTrack.inputTimescale; videoTrack.timescale = inputTimeScale; moovs.video = MP4.moov([videoTrack]); mediaInfo.videoCodec = videoTrack.codec; mediaInfo.width = videoTrack.width; mediaInfo.height = videoTrack.height; mediaInfo.fps = videoTrack.fps; mediaInfo.profile = videoTrack.profile; mediaInfo.level = videoTrack.level; mediaInfo.chromaFormat = videoTrack.chromaFormat; mediaInfo.hasVideo = true; let videoInitPTS = videoSamples[0].pts - inputTimeScale * timeOffset; let videoInitDTS = videoSamples[0].dts - inputTimeScale * timeOffset; initPTS = initPTS ? Math.min(initPTS, videoInitDTS) : videoInitPTS; } if (mediaInfo.hasAudio || mediaInfo.hasVideo) { if (typeof this._initPTS === 'undefined') { this._initPTS = initPTS; } this._moovs = moovs; eventEmitter.emit(LasEvents.MEDIA_INFO, mediaInfo); } else { eventEmitter.emit(LasEvents.ERROR, { type: ErrorTypes.MUX_ERROR, details: ErrorDetails.DEMUX_ERROR, fatal: false, info: { reason: 'no audio/video samples found' } }); } } /** * remux视频数据 * 输出fmp4数据 * @param track VideoTrack * @param isContinuous 数据是否连续 * @param activeTimeReference 是否开启视频帧时间参考功能 */ private _remuxVideo(track: VideoTrack, isContinuous: boolean, activeTimeReference: boolean = true): MP4Segment | undefined { if (!track.samples.length) { return; } const initPTS = this._initPTS; let timescale = track.timescale, samples = track.samples as VideoSample[], sampleDuration = 0, samplesCount = samples.length, mp4Samples: MP4VideoSample[] = [], nextVideoDTS = this._nextVideoDTS; if (typeof initPTS === 'undefined' || samplesCount === 0 || timescale === 0) { return; } if (!isContinuous || typeof nextVideoDTS === 'undefined') { nextVideoDTS = samples[0].dts; } // 处理offset samples.forEach((sample) => { sample.pts = sample.pts - initPTS; sample.dts = sample.dts - initPTS; }); // dts递增 samples.sort((a, b) => { return a.dts - b.dts || a.pts - b.pts; }); // 删除最后一个sample并缓存,用于计算remux最后一个sampleDuration if (this._videoTimeReference) { this._videoTimeReferenceInfo.track = track; if (this._videoTimeReferenceInfo.sample) { samplesCount++; samples.unshift(this._videoTimeReferenceInfo.sample); this._videoTimeReferenceInfo.sample = undefined; } if (samples.length > 1 && activeTimeReference) { this._videoTimeReferenceInfo.sample = samples.pop(); samplesCount--; } } // 计算调整首个sample时间戳 let sample = samples[0]; let firstDTS = Math.max(sample.dts, 0); let firstPTS = Math.max(sample.pts, 0); if (isContinuous) { const delta = Math.round(firstDTS - nextVideoDTS); if (delta) { firstPTS = samples[0].pts = firstPTS - (firstDTS - nextVideoDTS); firstDTS = samples[0].dts = firstDTS = nextVideoDTS; } } for (let i = 0; i < samplesCount; i++) { const videoSample = samples[i]; let mp4SampleLength = 0, cts; // 计算帧长度 if (i < samplesCount - 1) { // 非末尾 let nextSample = samples[i + 1]; if (nextSample.dts <= videoSample.dts) { let nextSampleCts = nextSample.pts - nextSample.dts; nextSample.dts = videoSample.dts + 1; nextSample.pts = nextSample.dts + nextSampleCts; } sampleDuration = nextSample.dts - videoSample.dts; } else { // 末尾 let duration = track.sampleDuration || this._videoSampleDuration; // 参考暂存帧计算长度 if (this._videoTimeReferenceInfo.sample) { duration = this._videoTimeReferenceInfo.sample.dts - videoSample.dts; } sampleDuration = Math.floor(duration); } cts = Math.round(videoSample.pts - videoSample.dts); mp4SampleLength = videoSample.units.reduce((prev: number, unit: Uint8Array) => { return unit.byteLength + 4 + prev; }, 0); mp4Samples.push({ len: mp4SampleLength, units: videoSample.units, duration: sampleDuration, cts, streamDTS: videoSample.streamDTS, flags: { isLeading: 0, isDependedOn: 0, hasRedundancy: 0, degradPrio: 0, dependsOn: videoSample.key ? 2 : 1, isNonSync: videoSample.key ? 0 : 1 } }); } let lastSample = samples[samples.length - 1]; this._nextVideoDTS = lastSample.dts + sampleDuration; let nextVideoPTS = lastSample.pts + sampleDuration; if (mp4Samples.length && this._forceFirstIDR) { const flags = mp4Samples[0].flags; flags.dependsOn = 2; flags.isNonSync = 0; } track.mp4Samples = mp4Samples; let payload = MP4.videoMediaSegment(track.sequenceNumber++, firstDTS, track, this._getMoovByType(TrackType.video)); const data: MP4Segment = { payload: payload, startPTS: firstPTS / timescale, endPTS: nextVideoPTS / timescale, startDTS: firstDTS / timescale, endDTS: this._nextVideoDTS / timescale, type: TrackType.video, streamDTS: sample.streamDTS / timescale }; this._videoLastPTS = data.endPTS; this._videoSampleDuration = Math.max(sampleDuration, 1); track.samples = []; track.mp4Samples = []; return data; } /** * remux音频数据 * 输出fmp4数据 * @param track AudioTrack * @param isContinuous 是否是连续数据 */ private _remuxAudio(track: AudioTrack, isContinuous: boolean): MP4Segment | undefined { if (!track.samples.length) { return; } const initPTS = this._initPTS; let inputAudioTimeScale = track.inputTimescale, scaleFactor = inputAudioTimeScale / track.timescale, inputSampleDuration = AAC_SAMPLE_DURATION * scaleFactor, mp4Samples: MP4AudioSample[] = [], firstAudioPTS = 0, lastPTS, inputSamples = track.samples as AudioSample[], nextAudioPTS = this._nextAudioPTS, frameDuration = getAACFrameDuration(track.samplerate); if (typeof initPTS === 'undefined') { return; } inputSamples.forEach(function (sample) { sample.pts = sample.dts = sample.pts - initPTS; }); if (!isContinuous || typeof nextAudioPTS === 'undefined') { nextAudioPTS = inputSamples[0].pts; } if (typeof nextAudioPTS === 'undefined') { return; } for (let i = 0, nextPTS = nextAudioPTS; i < inputSamples.length; i++) { const audioSample = inputSamples[i], unit = audioSample.unit, pts = audioSample.pts, delta = Math.round(pts - nextPTS), duration = Math.abs((1000 * delta) / inputAudioTimeScale); if (delta <= -inputSampleDuration) { // 丢帧 Log.v(this.tag, `drop audio frame. pts: ${pts}`); continue; } else if (delta >= inputSampleDuration && duration < MAX_FILL_FRAME_DURATION && nextPTS) { // 填空帧 let fillCount = Math.round(delta / inputSampleDuration); Log.v(this.tag, `fill audio frame. count: ${fillCount} pts: ${pts}`); for (let j = 0; j < fillCount; j++) { let fillFrame = getAACSilentFrame(track.defaultCodec || track.codec, track.channelCount); if (!fillFrame) { Log.v(this.tag, 'fill copy audio frame'); fillFrame = unit.subarray(); } mp4Samples.push({ len: fillFrame.byteLength, unit: fillFrame, cts: 0, duration: AAC_SAMPLE_DURATION, streamDTS: Math.round(audioSample.streamDTS - fillCount * frameDuration), flags: { isLeading: 0, isDependedOn: 0, hasRedundancy: 0, degradPrio: 0, dependsOn: 1, isNonSync: 0 } }); firstAudioPTS = firstAudioPTS || Math.max(nextPTS, 0); nextPTS += inputSampleDuration; } } else { firstAudioPTS = firstAudioPTS || pts; nextPTS += inputSampleDuration; } mp4Samples.push({ len: unit.byteLength, cts: 0, duration: AAC_SAMPLE_DURATION, unit: unit, streamDTS: audioSample.streamDTS, flags: { isLeading: 0, isDependedOn: 0, hasRedundancy: 0, degradPrio: 0, dependsOn: 1, isNonSync: 0 } }); lastPTS = pts; } if (mp4Samples.length && typeof lastPTS === 'number') { this._nextAudioPTS = nextAudioPTS = lastPTS + scaleFactor * AAC_SAMPLE_DURATION; track.mp4Samples = mp4Samples; let payload = MP4.audioMediaSegment(track.sequenceNumber++, firstAudioPTS / scaleFactor, track, this._getMoovByType(TrackType.audio)); track.samples = []; track.mp4Samples = []; const start = firstAudioPTS / inputAudioTimeScale; const end = nextAudioPTS / inputAudioTimeScale; const audioData: MP4Segment = { payload: payload, startPTS: start, endPTS: end, startDTS: start, endDTS: end, type: TrackType.audio, streamDTS: mp4Samples[0].streamDTS/ inputAudioTimeScale }; this._audioLastPTS = audioData.endPTS; return audioData; } track.samples = []; track.mp4Samples = []; return; } /** * 填空audio * @param track audiotrack * @param isContinuous 是否是连续数据 * @param startPTS 开始填充时间 * @param endPTS 结束填充时间 * @param streamDTS start对应的流时间戳 */ private _fillEmptyAudio(track: AudioTrack, isContinuous: boolean, startPTS: number, endPTS: number, streamDTS: number) { Log.v(this.tag, 'fill empty Audio'); const fillFrame = getAACSilentFrame(track.defaultCodec || track.codec, track.channelCount); if (typeof this._initPTS === 'undefined' || !fillFrame) { return; } const timescale = track.inputTimescale, start = (typeof this._nextAudioPTS !== 'undefined' ? this._nextAudioPTS : startPTS * timescale) + this._initPTS, end = endPTS * timescale + this._initPTS, frameDuration = getAACFrameDuration(track.samplerate), fillCount = Math.ceil((end - start) / frameDuration); const samples: AudioSample[] = []; for (let i = 0; i < fillCount; i++) { const time = start + i * frameDuration; samples.push({ unit: fillFrame, pts: time, dts: time, streamDTS: Math.round(streamDTS * timescale + i * frameDuration) }); } track.samples = samples; return this._remuxAudio(track, isContinuous); } /** * 获取音/视频moov头 * @param type track type */ private _getMoovByType(type: TrackType): Uint8Array | undefined { let result: Uint8Array | undefined; if (this._moovs && this._moovs[type]) { result = this._moovs[type]; delete this._moovs[type]; } return result; } /** * 清理暂存数据 */ private _clearVideoTimeReference() { this._videoTimeReferenceInfo = <VideoTimeReferenceInfo>{}; } } export default MP4Remuxer;
the_stack
import * as S from "../../sexpr" import { token } from "../../token" import * as Path from "../../path" import { assertEq, assertEqList, assertEqObj, assertThrows, quickcheck } from "../../test" import { Mode as ScanMode } from "../../scanner" import * as ast from "../../ast" import * as api from "../../api" import * as utf8 from "../../utf8" import { mstr, bufcopy } from "../../util" function getFixturesDir() { // Note: __dirname is the directory of the co program, not this source file return Path.clean(__dirname + "/../src/ast/test") + "/" } function rpath(fn :string) :string { // version of relPath that doesn't rely on the environment let dir = Path.dir(__dirname) + "/" return fn.startsWith(dir) ? fn.substr(dir.length) : fn } TEST('empty', async () => { let chost = api.createCompilerHost() let dir = getFixturesDir() // parse empty file by having compiler host read it from disk if (!api.isNoFileSystem(chost.fs)) { let file = await chost.parseFile(dir + "empty.co") assert(file instanceof ast.File) assertEq(file.imports.length, 0) assertEq(file.decls.length, 0) assertEq(api.getDiagnostics(file).length, 0) } // parse empty file by providing source content { let file = await chost.parseFile("empty.co", new Uint8Array()) assert(file instanceof ast.File) assertEq(file.imports.length, 0) assertEq(file.decls.length, 0) assertEq(api.getDiagnostics(file).length, 0) } // parse empty package { let pkg = await chost.parsePackage("test1", [["empty1.co", ""], ["empty2.co", ""]]) assert(pkg instanceof ast.Package) assertEq(pkg.files.length, 2) assertEq(api.getDiagnostics(pkg).length, 0) } // parse empty package (no source files) { let pkg = await chost.parsePackage("test1", []) assert(pkg instanceof ast.Package) assertEq(pkg.files.length, 0) assertEq(api.getDiagnostics(pkg).length, 0) } }) TEST('#directive', () => { let chost = getCompilerHost() { // #end offset at EOF let source = utf8.encodeString(`x = 1\n#end`) let file = parseFile("a.co", source) ; assertEq(api.getErrorCount(file), 0) assertEq(file.endPos!.offset, 10) // #end|<EOF> assertEq(file.endPos!.line, 2) } { // #end offset at EOF with semicolon let source = utf8.encodeString(`x = 1\n#end;`) let file = parseFile("a.co", source) ; assertEq(api.getErrorCount(file), 0) assertEq(file.endPos!.offset, 11) // #end;|<EOF> } { // #end offset at EOF with whitespace and semicolon let source = utf8.encodeString(`x = 1\n#end \t ;`) let file = parseFile("a.co", source) ; assertEq(api.getErrorCount(file), 0) assertEq(file.endPos!.offset, 14) // #end;|<EOF> } { // #end at beginning of file and at EOF let source = utf8.encodeString(`#end`) let file = parseFile("a.co", source) ; assertEq(api.getErrorCount(file), 0) assertEq(file.endPos!.offset, 4) // #end|<EOF> assertEq(file.endPos!.line, 1) } { // #end offset with implicit semicolon let source = utf8.encodeString(mstr(` x = 1 #end hello `)) let file = parseFile("a.co", source) ; assertEq(api.getErrorCount(file), 0) assertEq(file.endPos!.offset, 11) // #end\n|hello } { // #end offset with explicit semicolon let source = utf8.encodeString(mstr(` x = 1 #end; hello `)) let file = parseFile("a.co", source) ; assertEq(api.getErrorCount(file), 0) assertEq(file.endPos!.offset, 12) // #end;\n|hello } { // #end offset with explicit semicolon and CR let source = utf8.encodeString(`x = 1\r\n#end;\r\nhello`) let file = parseFile("a.co", source) ; assertEq(api.getErrorCount(file), 0) assertEq(file.endPos!.offset, 14) // #end;\r\n|hello } { // #end offset with implicit semicolon and comment let source = utf8.encodeString(mstr(` x = 1 #end // comment hello `)) let file = parseFile("a.co", source) ; assertEq(api.getErrorCount(file), 0) assertEq(file.endPos!.offset, 22) } { // #end offset with implicit semicolon and comment (with comment scanning enabled) let source = utf8.encodeString(mstr(` x = 1 #end // comment hello `)) let file = parseFile("a.co", source, api.ScanMode.ScanComments) assertEq(api.getErrorCount(file), 0) assertEq(file.endPos!.offset, 22) } { // #end offset with explicit semicolon and comment let source = utf8.encodeString(mstr(` x = 1 #end; // comment hello `)) let file = parseFile("a.co", source) ; assertEq(api.getErrorCount(file), 0) assertEq(file.endPos!.offset, 23) } { // #end with data let source = utf8.encodeString(mstr(` x = 1 #end // comment hello world `)) let file = parseFile("a.co", source) assertEq(api.getErrorCount(file), 0) // print(file.repr({colors:true})) assertEq(file.endPos!.offset, 22) // beginning of "hello world" assertEq(file.endMeta.length, 0) // no directive metadata let data = source.subarray(file.endPos!.offset) assertEq(utf8.decodeToString(data), "hello world\n") } { // #end with arbitrary data let source = utf8.encodeString(mstr(` x = 1 #end `)) // append data to end of source let dataIn = [0, 1, 2, 0xFF] let i = source.length source = bufcopy(source, dataIn.length) for (let b of dataIn) { source[i++] = b } let file = parseFile("a.co", source) assertEq(api.getErrorCount(file), 0) assertEq(file.endPos!.offset, 11) // beginning of data let dataOut = source.subarray(file.endPos!.offset) assertEq(dataOut.length, dataIn.length) for (let i = 0; i < dataIn.length; i++) { assertEq(dataOut[i], dataIn[i]) } } { // #end with metadata let file = parseFile("a.co", mstr(` x = 1 #end foo "bar" 45 6.78 hello world `)) // print("file:", file.repr()) assertEq(api.getErrorCount(file), 0) assert(file.endPos) // in this test we only care about endPos being set assertEq(file.endMeta.length, 4) assertEq(file.endMeta[0].repr(), "(id foo)") assertEq(file.endMeta[1].repr(), '(StringLit "bar" str<3>)') assertEq(file.endMeta[2].repr(), "(IntLit 45 int)") assertEq(file.endMeta[3].repr(), "(FloatLit 6.78 f64)") } // invalid directive assertParseError(mstr(` x = 1 #lol `), /invalid directive/i) // invalid metadata (not just expressions) assertParseError(mstr(` x = 1 #end x = 1 `), /expecting expression/i) }) TEST("cyclic-type-ref", () => { // This tests parser-state checks for cyclic type references, // which would cause infinite recursion when default-initialized. // When a type references itself or a parent in a chain, it must // break the cycle with "optional": let file = parseFile("a.co", `type A { a A? }`) assertEq(api.getErrorCount(file), 0) assertParseError(mstr(` type A { a A } `), /cyclic type reference/i) assertParseError(mstr(` type A { a B } type B { b A } `), /cyclic type reference/i) assertParseError(mstr(` type A { a B } type B { b C } type C { c A } `), /cyclic type reference/i) assertParseError(mstr(` type A { a B } type B { b C } type C { c D } type D { c E } type E { c F } type F { c G } type G { c H } type H { c I } type I { c A } `), /cyclic type reference/i) }) TEST('suite', async () => { let chost = getCompilerHost() if (api.isNoFileSystem(chost.fs)) { return } let fs = chost.fs let dir = getFixturesDir() for (let name of fs.readdirSync(dir)) { if (name.endsWith(".co")) { await testFile(dir + name) } } async function testFile(filename :string) { // Parses a file and compares the resulting AST to an "expected" AST defined // in a comment in the source file. // // The "expect" comment should have the prefix "!expect" (no leading spaces) // and the remainder of the comment is parsed as s-expression AST. // // The actual parsed AST need only match the parts defined in the expected // structure, allowing some leeway in terms of irrelevant information. // For instance, a test case that doesn't case about Node.pos can simply omit // (pos N) from "expected". // print(` test ${rpath(filename)}`) let data = await fs.readfile(filename) let file = parseFile(filename, data) if (!file.endPos) { return } let actual = fileToSExpr(file) let expectCode = utf8.decodeToString(data.subarray(file.endPos.offset)) let expect = parseSExpr(filename, expectCode, file.endPos.line) assert(expect instanceof S.List, `"expected" s-expr should be a single list (got ${expect})`) expect = expect[0] as S.List // find difference between what is expected and what was actually parsed let diff = S.diff(expect, actual) if (diff) { // TODO: use a textual diff library that we load lazily here and show any diff chunk // which has different prefix (L vs R) print("---\nexpect:\n" + expect.toString("\n")) print("---\nactual:\n" + actual.toString("\n")) // diff is rarely useful, it's been disabled here below // print("---\ndiff:\n" + (diff && diff.toString("\n"))) assert(false, `unexpected parse result for ${rpath(filename)}`) } } }) // -------------------------------------------------------------------------------- // helpers function parseFile(filename :string, code :api.SourceData, mode? :api.ScanMode) :api.ast.File { let chost = getCompilerHost() // TODO: Find a way to collect diagnostic messages and only print them when a test fails. // This so that we can ignore messages like "x declared but not used". return chost.parseFile(filename, code, undefined, d => console.error(d.toString()), mode) } function fileToSExpr(file :api.ast.File) :S.List { let aststr = file.repr({ noRefs: true, // disable e.g. "$4" and "#4" in output noScope: true, // exclude scope }) let decls = (parseSExpr(file.sfile.name, aststr, 0)[0] as S.List).get("decls") as S.List decls.shift() // pop "decls" keyword at beginning of list return decls } function parseSExpr(filename :string, source :string, lineOffset :int) :S.List { return S.parse(source, { filename, ltgt: S.AS_SYM, // treat <...> as part of sym (instead of list) lineOffset: lineOffset > 0 ? lineOffset-1 : 0, }) } let _chost :api.CompilerHost|null = null function getCompilerHost() { if (!_chost) { _chost = api.createCompilerHost() _chost.traceInDebugMode = false // disable trace-level log messages } return _chost } // assertParseError tests that source produces errors.length number of errors, // each matching errors[N] in order. // function assertParseError(source :string, ...errors :(RegExp|string)[]) { let chost = getCompilerHost() let diags :api.Diagnostic[] = [] let file = chost.parseFile("a.co", source, undefined, d => { if (d.kind == "error") { diags.push(d) } }) assertEq(api.getErrorCount(file), errors.length) for (let i = 0; i < diags.length; i++) { let d = diags[i] let match = errors[i] assert( (typeof match == "string") ? d.message === match : match.test(d.message), `expected error ${repr(d.message)} to match ${repr(match)}` ) } } // // parseExpect takes a source file as input and returns the Co code and the "expected" sepxr. // function parseExpect(filename :string, code :string) :[string, S.List|null] { // const prefix = "!expect" // let expect :S.List|null = null // let chost = getCompilerHost() // chost.scanFile(filename, code, (t, s) :any => { // if (t == token.COMMENT) { // let comment = s.stringValue() // if (comment.startsWith(prefix)) { // let pos = s.currentPosition() // let ai = pos.offset // let bi = code.indexOf("\n", ai) // if (bi != -1) { // let expectCode = code.substr(bi) // code = code.substr(0, ai) // expect = parseSExpr(filename, expectCode, pos.line) // assert(expect instanceof S.List, `${prefix} should be a single list (got ${expect})`) // expect = expect[0] as S.List // } // return false // stop scanner // } // } // }, undefined, ScanMode.ScanComments) // return [code, expect] // }
the_stack
import { define } from 'elements-sk/define'; import 'elements-sk/checkbox-sk'; import 'elements-sk/error-toast-sk'; import 'elements-sk/icon/alarm-off-icon-sk'; import 'elements-sk/icon/comment-icon-sk'; import 'elements-sk/icon/notifications-icon-sk'; import 'elements-sk/icon/person-icon-sk'; import 'elements-sk/spinner-sk'; import 'elements-sk/styles/buttons'; import 'elements-sk/tabs-panel-sk'; import 'elements-sk/tabs-sk'; import 'elements-sk/toast-sk'; import '../incident-sk'; import '../bot-chooser-sk'; import '../email-chooser-sk'; import '../silence-sk'; import dialogPolyfill from 'dialog-polyfill'; import { diffDate } from 'common-sk/modules/human'; import { CheckOrRadio } from 'elements-sk/checkbox-sk/checkbox-sk'; import { HintableObject } from 'common-sk/modules/hintable'; import { $, $$ } from 'common-sk/modules/dom'; import { errorMessage } from 'elements-sk/errorMessage'; import { html, render, TemplateResult } from 'lit-html'; import { jsonOrThrow } from 'common-sk/modules/jsonOrThrow'; import { stateReflector } from 'common-sk/modules/stateReflector'; import { SpinnerSk } from 'elements-sk/spinner-sk/spinner-sk'; import { Login } from '../../../infra-sk/modules/login'; import { BotChooserSk } from '../bot-chooser-sk/bot-chooser-sk'; import { EmailChooserSk } from '../email-chooser-sk/email-chooser-sk'; import '../../../infra-sk/modules/theme-chooser-sk'; import * as paramset from '../paramset'; import { displaySilence, expiresIn, getSilenceFullName } from '../am'; import { Silence, Incident, StatsRequest, Stat, IncidentsResponse, ParamSet, Params, IncidentsInRangeRequest, AuditLog, } from '../json'; // Legal states. const START = 'start'; const INCIDENT = 'incident'; const EDIT_SILENCE = 'edit_silence'; const VIEW_STATS = 'view_stats'; const VIEW_AUDITLOG = 'view_auditlog'; const MAX_SILENCES_TO_DISPLAY_IN_TAB = 50; const BOT_CENTRIC_PARAMS = ['alertname', 'bot']; class State { tab: number = 0; // The selected tab. alert_id: string = ''; // The selected alert (if any). } // This response structure comes from chrome-ops-rotation-proxy.appspot.com. // We do not have access to the structure to generate TS. interface RotationResp { emails: string[]; } export class AlertManagerSk extends HTMLElement { private incidents: Incident[] = []; // All active incidents. private filterSilencesVal: string = ''; private filterAuditLogsVal: string = ''; private silences: Silence[] = []; // All active silences. private stats: Stat[] = []; // Last requested stats. private audit_logs: AuditLog[] = []; private stats_range = '1w'; private incident_stats: Incident[] = []; // The incidents for a given stat. private rhs_state = START; // One of START, INCIDENT, or EDIT_SILENCE. private selected: Incident|Silence|null = null; // The selected incident, i.e. you clicked on the name. private checked = new Set(); // Checked incidents, i.e. you clicked the checkbox. private bots_to_incidents: Record<string, Incident[]> = {}; // Bot names to their incidents. Used in bot-centric view. private isBotCentricView = false; // Determines if bot-centric view is displayed on incidents tab. private current_silence: Silence|null = null; // A silence under construction. // Params to ignore when constructing silences. private ignored = ['__silence_state', 'description', 'id', 'swarming', 'assigned_to', 'kubernetes_pod_name', 'instance', 'pod_template_hash', 'abbr_owner_regex', 'controller_revision_hash']; private shift_pressed_during_click = false; // If the shift key was held down during the mouse click. private last_checked_incident: string|null = null; // Keeps track of the last checked incident. Used for multi-selecting incidents with shift. private incidents_notified: Record<string, boolean> = {}; // Keeps track of all incidents that were notified via desktop notifications. private incidentsToRecentlyExpired: Record<string, boolean> = {}; // Map of incident IDs to whether their silences recently expired. private user = 'barney@example.org'; private infra_gardener = ''; // State is reflected to the URL via stateReflector. private state: State = { tab: 0, alert_id: '', }; private favicon: HTMLAnchorElement | null = null; private spinner: SpinnerSk | null = null; private emails: string[] = []; private helpDialog: HTMLDialogElement | null = null; constructor() { super(); fetch('https://chrome-ops-rotation-proxy.appspot.com/current/grotation:skia-infra-gardener', { mode: 'cors' }).then(jsonOrThrow).then((json: RotationResp) => { this.infra_gardener = json.emails[0]; this._render(); }); Login.then((loginstatus) => { this.user = loginstatus.Email; this._render(); }); } private static template = (ele: AlertManagerSk) => html` <header> ${ele.infraGardener()} <theme-chooser-sk></theme-chooser-sk> </header> <dialog id=help> <h2>Keyboard Controls</h2> <table> <tr><td class=mono>'ArrowDown'</td><td>Move down the list of incidents.</td></tr> <tr><td class=mono>'ArrowUp'</td><td>Move up the list of incidents.</td></tr> <tr><td class=mono>'Space'</td><td>Check the incident to create a silence or to assign.</td></tr> <tr><td class=mono>'Shift+ArrowDown'</td><td>Check the below incident to create a silence (only if the current incident is checked).</td></tr> <tr><td class=mono>'Shift+ArrowUp'</td><td>Check the above incident to create a silence (only if the current incident is checked).</td></tr> <tr><td class=mono>'ArrowRight'</td><td>Move to the first textarea in RHS.</td></tr> <tr><td class=mono>'a'</td><td>Assign selected alert(s).</td></tr> <tr><td class=mono>'b'</td><td>Switches view from normal to bot-centric view.</td></tr> <tr><td class=mono>'1'</td><td>Switches to the "Mine" tab.</td></tr> <tr><td class=mono>'2'</td><td>Switches to the "Alerts" tab.</td></tr> <tr><td class=mono>'?'</td><td>Show help.</td></tr> <tr><td class=mono>'Esc'</td><td>Stop showing help.</td></tr> </table> <div class=footnote> Note: Keyboard controls only work in the 'Mine' and 'Alerts' tabs. 'Bot-centric view' is also not supported. </div> </dialog> <section class=nav> <tabs-sk @tab-selected-sk=${ele.tabSwitch} selected=${ele.state.tab}> <button>Mine</button> <button>Alerts</button> <button>Silences</button> <button>Stats</button> <button>Audit</button> </tabs-sk> <tabs-panel-sk> <section class=mine> <span class=selection-buttons> ${ele.displayAssignMultiple()} ${ele.displayClearSelections()} </span> ${ele.incidentList(ele.getMyIncidents(), false)} </section> <section class=incidents> ${ele.botCentricBtn()} <span class=selection-buttons> ${ele.displayAssignMultiple()} ${ele.displayClearSelections()} </span> ${ele.incidentList(ele.incidents, ele.isBotCentricView)} </section> <section class=silences> <input class=silences-filter placeholder="Filter silences" .value="${ele.filterSilencesVal}" @input=${(e: Event) => ele.filterSilencesEvent(e)}></input> <br/><br/> ${ele.silences.filter((silence: Silence) => getSilenceFullName(silence.param_set).includes(ele.filterSilencesVal)).slice(0, MAX_SILENCES_TO_DISPLAY_IN_TAB).map((i: Silence) => html` <h2 class=${ele.classOfSilenceH2(i)} @click=${() => ele.silenceClick(i)}> <span> ${displaySilence(i.param_set)} </span> <span> <span title='Expires in'>${expiresIn(i.active, i.created, i.duration)}</span> <comment-icon-sk title='This silence has notes.' class=${ele.hasNotes(i)}></comment-icon-sk> <span title='The number of active alerts that match this silence.'>${ele.numMatchSilence(i)}</span> </span> </h2>`)} </section> <section class=stats> ${ele.statsList()} </section> <section class=auditlogs> <input class=auditlogs-filter placeholder="Filter audit logs" .value="${ele.filterAuditLogsVal}" @input=${(e: Event) => ele.filterAuditLogsEvent(e)}></input> </section> </tabs-panel-sk> </section> <section class=edit> ${ele.rightHandSide()} </section> <footer> <spinner-sk id=busy></spinner-sk> <bot-chooser-sk id=bot-chooser></bot-chooser-sk> <email-chooser-sk id=email-chooser></email-chooser-sk> <error-toast-sk></error-toast-sk> </footer> `; connectedCallback(): void { this.requestDesktopNotificationPermission(); this.addEventListener('save-silence', (e) => this.saveSilence((e as CustomEvent).detail.silence)); this.addEventListener('archive-silence', (e) => this.archiveSilence((e as CustomEvent).detail.silence)); this.addEventListener('reactivate-silence', (e) => this.reactivateSilence((e as CustomEvent).detail.silence)); this.addEventListener('delete-silence', (e) => this.deleteSilence((e as CustomEvent).detail.silence)); this.addEventListener('add-silence-note', (e) => this.addSilenceNote(e as CustomEvent)); this.addEventListener('del-silence-note', (e) => this.delSilenceNote(e as CustomEvent)); this.addEventListener('add-silence-param', (e) => this.addSilenceParam((e as CustomEvent).detail.silence)); this.addEventListener('delete-silence-param', (e) => this.deleteSilenceParam((e as CustomEvent).detail.silence)); this.addEventListener('modify-silence-param', (e) => this.modifySilenceParam((e as CustomEvent).detail.silence)); this.addEventListener('add-note', (e) => this.addNote(e as CustomEvent)); this.addEventListener('del-note', (e) => this.delNote(e as CustomEvent)); this.addEventListener('take', (e) => this.take(e as CustomEvent)); this.addEventListener('bot-chooser', () => this.botChooser()); this.addEventListener('assign', (e) => this.assign(e as CustomEvent)); this.addEventListener('assign-to-owner', (e) => this.assignToOwner(e as CustomEvent)); // For keyboard navigation. document.addEventListener('keydown', (e) => this.keyDown(e)); this.stateHasChanged = stateReflector( /* getState */ () => (this.state as unknown) as HintableObject, /* setState */ (newState) => { this.state = (newState as unknown) as State; // Set rhs_side to AUDIT_LOG if tab is on Audit. if (this.state.tab === 4) { this.getAuditLogs(); this.rhs_state = VIEW_AUDITLOG; } this._render(); }, ); this._render(); this.helpDialog = $$('#help', this); dialogPolyfill.registerDialog(this.helpDialog!); this.spinner = $$('#busy', this) as SpinnerSk; this.favicon = $$('#favicon'); this.spinner.active = true; this.poll(true); } private getMyIncidents(): Incident[] { return this.incidents.filter((i: Incident) => i.active && i.params.__silence_state !== 'silenced' && (this.user === this.infra_gardener || i.params.assigned_to === this.user || (i.params.owner === this.user && !i.params.assigned_to))); } private keyDown(e: KeyboardEvent) { // Ignore all tabs other than the mine and incident tabs. if (this.state.tab !== 0 && this.state.tab !== 1) { return; } // Too complicated to navigate through issues in bot centric view // because the layout of incidents is completely different than // the standard view. if (this.isBotCentricView) { return; } // Ignore IME composition events. if (e.isComposing || e.keyCode === 229) { return; } // Do not perform keyboard navigation if input/textarea/select are // selected. const focusedElem: Element | null = document.activeElement; const ignoreKeyboardNavigationInTags = ['input', 'textarea', 'select']; if (focusedElem && ignoreKeyboardNavigationInTags.includes(focusedElem.tagName.toLowerCase())) { return; } switch (e.key) { case '?': (this.helpDialog! as any).showModal(); break; case 'ArrowUp': this.keyboardNavigateIncidents(e, true); break; case 'ArrowDown': this.keyboardNavigateIncidents(e, false); break; case 'ArrowRight': // Put focus on the 1st textarea on the page (if one exists). if ($('textarea') && $('textarea').length > 0) { ($('textarea')[0] as HTMLElement).focus(); } break; case ' ': if (this.selected) { ($$(`#${this.selected!.key}`)! as HTMLElement).click(); } else if (this.checked.size > 0) { // No incident was selected. Clear all the checked incidents and // start from the first incident. this.checked.clear(); this.last_checked_incident = null; if (this.incidents.length > 0) { this.selected = this.incidents[0]; } this._render(); } e.preventDefault(); break; case 'b': this.flipBotCentricView(); break; case 'a': // If an alert is selected and nothing is checked then // check the selected alert before assigning it. if (this.selected && this.checked.size === 0) { ($$(`#${this.selected!.key}`)! as HTMLElement).click(); } this.assignMultiple(); break; case '1': this.keyboardNavigateTabs(0); break; case '2': this.keyboardNavigateTabs(1); break; default: break; } } private keyboardNavigateTabs(tabIndex: number) { this.state.tab = tabIndex; this.state.alert_id = ''; this.selected = null; this.checked.clear(); this.rhs_state = START; this.stateHasChanged(); this._render(); } private keyboardNavigateIncidents(e: KeyboardEvent, reverseDirection: boolean) { // If an alert is not selected or checked then the first incident in the // incidents array can be starting point. let foundStartingPoint = (this.selected === null) && (this.checked.size === 0); // Figure out which incidents we are looking at. let incidentsArray = this.incidents; if (this.state.tab === 0) { // Use "my" incidents if we are on the "Mine" tab. incidentsArray = this.getMyIncidents(); } if (reverseDirection && !foundStartingPoint) { // We only want to reverse incidents if we have not yet // found a starting point else we will start with the // last alert. incidentsArray = incidentsArray.reverse(); } for (const incident of incidentsArray) { if (foundStartingPoint) { const k = incident.key; // If shift key is pressed then check the incident if it is not already // checked. if (e.shiftKey && this.last_checked_incident) { if (this.checked.has(k)) { // This incident is already checked. Set it as the // last_checked_incident so we can proceed from here the next time. this.last_checked_incident = k; } else { // Check the incident. ($$(`#${k}`)! as HTMLElement).click(); } } else { ($$(`#container-${k}`)! as HTMLElement).click(); } break; } if (this.selected && this.selected.key === incident.key) { // We found the selected incident, the next incident in the iteration // is the one we need to process. foundStartingPoint = true; } else if (this.checked.size > 0 && this.last_checked_incident === incident.key) { // We found the last checked incident, the next incident in the // iteration is the one we need to process. foundStartingPoint = true; } } } // Call this anytime something in private state is changed. Will be replaced // with the real function once stateReflector has been setup. // eslint-disable-next-line @typescript-eslint/no-empty-function private stateHasChanged = () => {}; private classOfH2(incident: Incident): string { const ret = []; if (!incident.active) { ret.push('inactive'); } else if (incident.params.__silence_state === 'silenced') { ret.push('silenced'); } else if (incident.params.assigned_to) { ret.push('assigned'); } if (this.selected && this.selected.key === incident.key) { ret.push('selected'); } return ret.join(' '); } private classOfSilenceH2(silence: Silence): string { const ret = []; if (!silence.active) { ret.push('inactive'); } if (this.selected && this.selected.key === silence.key) { ret.push('selected'); } return ret.join(' '); } private editIncident(): TemplateResult { if (this.selected) { return html`<incident-sk .incident_silences=${this.silences} .incident_state=${this.selected} ></incident-sk>`; } return html``; } private editSilence(): TemplateResult { return html`<silence-sk .silence_state=${this.current_silence} .silence_incidents=${this.incidents} ></silence-sk>`; } private viewStats(): TemplateResult[] { return this.incident_stats.map((i, index) => html`<incident-sk .incident_state=${i} ?minimized params=${index === 0}></incident-sk>`); } private rightHandSide(): TemplateResult|TemplateResult[] { switch (this.rhs_state) { case START: return []; case INCIDENT: return this.editIncident(); case EDIT_SILENCE: return this.editSilence(); case VIEW_STATS: return this.viewStats(); case VIEW_AUDITLOG: return this.viewAuditLogsTable(); default: return []; } } private hasNotes(o: Incident| Silence): string { return (o.notes && o.notes.length > 0) ? '' : 'invisible'; } private hasRecentlyExpiredSilence(incident: Incident): string { return (this.incidentsToRecentlyExpired[incident.id]) ? '' : 'invisible'; } private displayIncident(incident: Incident): TemplateResult { const ret = [incident.params.alertname]; const abbr = incident.params.abbr; if (abbr) { ret.push(` - ${abbr}`); } const fullIncident = ret.join(' '); let displayIncident = fullIncident; if (displayIncident.length > 33) { displayIncident = `${displayIncident.slice(0, 30)}...`; } return html`<span title="${fullIncident}">${displayIncident}</span>`; } private infraGardener(): TemplateResult { if (this.infra_gardener === this.user) { return html`<notifications-icon-sk title='You are the Infra Gardener, awesome!'></notifications-icon-sk>`; } return html``; } private assignedTo(incident: Incident): TemplateResult { if (incident.params.assigned_to === this.user) { return html`<person-icon-sk title='This item is assigned to you.'></person-icon-sk>`; } if (incident.params.assigned_to) { return html`<span class='assigned-circle' title='This item is assigned to ${incident.params.assigned_to}.'>${incident.params.assigned_to[0].toUpperCase()}</span>`; } return html``; } private populateBotsToIncidents(incidents: Incident[]): void { // Reset bots_to_incidents and populate it from scratch. this.bots_to_incidents = {}; for (let i = 0; i < incidents.length; i++) { const incident = incidents[i]; if (incident.params && incident.params.bot) { // Only consider active bot incidents that are not assigned or silenced. if (!incident.active || incident.params.__silence_state === 'silenced' || incident.params.assigned_to) { continue; } const botName = incident.params.bot; if (this.bots_to_incidents[botName]) { this.bots_to_incidents[botName].push(incident); } else { this.bots_to_incidents[botName] = [incident]; } } } } private botCentricView(): TemplateResult[] { this.populateBotsToIncidents(this.incidents); const botsHTML: TemplateResult[] = []; Object.keys(this.bots_to_incidents).forEach((botName) => { botsHTML.push(html` <h2 class="bot-centric"> <span class=noselect> <checkbox-sk class=bot-alert-checkbox ?checked=${this.isBotChecked(this.bots_to_incidents[botName])} @change=${this.check_selected} @click=${this.clickHandler} id=${botName}></checkbox-sk> <span class=bot-alert> ${botName} <span class=bot-incident-list> ${this.incidentListForBot(this.bots_to_incidents[botName])} </span> </span> </span> </h2> `); }); return botsHTML; } // Checks to see if all the incidents for the bot are checked. private isBotChecked(incidents: Incident[]): boolean { for (let i = 0; i < incidents.length; i++) { if (!this.checked.has(incidents[i].key)) { return false; } } return true; } private incidentListForBot(incidents: Incident[]): TemplateResult { const incidentsHTML = incidents.map((i) => html`<li @click=${() => this.select(i)}>${i.params.alertname}</li>`); return html`<ul class=bot-incident-elem>${incidentsHTML}</ul>`; } private incidentList(incidents: Incident[], isBotCentricView: boolean): TemplateResult[] { if (isBotCentricView) { return this.botCentricView(); } return incidents.map((i) => html` <h2 class=${this.classOfH2(i)} @click=${() => this.select(i)} id=container-${i.key}> <span class=noselect> <checkbox-sk ?checked=${this.checked.has(i.key)} @change=${this.check_selected} @click=${this.clickHandler} id=${i.key}></checkbox-sk> ${this.assignedTo(i)} ${this.displayIncident(i)} </span> <span> <alarm-off-icon-sk title='This incident has a recently expired silence' class=${this.hasRecentlyExpiredSilence(i)}></alarm-off-icon-sk> <comment-icon-sk title='This incident has notes.' class=${this.hasNotes(i)}></comment-icon-sk> </span> </h2> `); } private statsList(): TemplateResult[] { return this.stats.map((stat: Stat) => html`<h2 @click=${() => this.statsClick(stat.incident)}>${this.displayIncident(stat.incident)} <span>${stat.num}</span></h2>`); } private viewAuditLogsTable(): TemplateResult { return html` <table id=audit-logs-table> ${this.getAuditLogsRows()} </table> `; } private getAuditLogsRows(): TemplateResult[] { const filtered_audit_logs = this.audit_logs.filter((a) => a.body.includes(this.filterAuditLogsVal)); return filtered_audit_logs.map((a) => html` <tr> <td> ${diffDate(a.timestamp * 1000)} ago </td> <td> ${a.action} </td> <td> ${a.user} </td> <td> ${a.body} </td> </tr> `); } private numMatchSilence(s: Silence): number { if (!this.incidents) { return 0; } return this.incidents.filter( (incident: Incident) => paramset.match(s.param_set, incident.params) && incident.active, ).length; } private displayClearSelections(): TemplateResult { return html`<button class=selection ?disabled=${this.checked.size === 0} @click=${this.clearSelections}>Clear selections</button>`; } private filterSilencesEvent(e: Event): void { this.filterSilencesVal = (e.target as HTMLInputElement).value; this._render(); } private filterAuditLogsEvent(e: Event): void { this.filterAuditLogsVal = (e.target as HTMLInputElement).value; this._render(); } private clearSelections(): void { this.checked = new Set(); this._render(); } private displayAssignMultiple(): TemplateResult { return html`<button class=selection ?disabled=${this.checked.size === 0} @click=${this.assignMultiple}>Assign ${this.checked.size} alerts</button>`; } private botCentricBtn(): TemplateResult { let buttonText; if (this.isBotCentricView) { buttonText = 'Switch to Normal view'; } else { buttonText = 'Switch to Bot-centric view'; } return html`<button @click=${this.flipBotCentricView}>${buttonText}</button>`; } private findParent(ele: HTMLElement|null, tagName: string): HTMLElement|null { while (ele && (ele.tagName !== tagName)) { ele = ele.parentElement; } return ele; } private poll(stopSpinner: boolean): void { const incidents = fetch('/_/incidents', { credentials: 'include', }).then(jsonOrThrow).then((json: IncidentsResponse) => { this.incidents = json.incidents || []; // If alert_id is specified and it is in supported rhs_states then display // an incident. if ((this.rhs_state === START || this.rhs_state === INCIDENT) && this.state.alert_id) { for (let i = 0; i < this.incidents.length; i++) { if (this.incidents[i].id === this.state.alert_id) { this.select(this.incidents[i]); break; } } } this.incidents = json.incidents || []; this.incidentsToRecentlyExpired = json.ids_to_recently_expired_silences || {}; }); const silences = fetch('/_/silences', { credentials: 'include', }).then(jsonOrThrow).then((json: Silence[]) => { this.silences = json; }); const emails = fetch('/_/emails', { credentials: 'include', }).then(jsonOrThrow).then((json: string[]) => { this.emails = json; }); Promise.all([incidents, silences, emails]).then(() => { this._render(); }).catch((msg) => { if (msg.resp) { msg.resp.text().then(errorMessage); } else { errorMessage(msg); } }).finally(() => { if (stopSpinner) { this.spinner!.active = false; } window.setTimeout(() => this.poll(false), 10000); }); } private tabSwitch(e: CustomEvent): void { this.state.tab = e.detail.index; // Unset alert_id when switching tabs. this.state.alert_id = ''; this.stateHasChanged(); // Unset filters when switching tabs. this.filterSilencesVal = ''; this.filterAuditLogsVal = ''; // If tab is stats then load stats. if (e.detail.index === 3) { this.getStats(); } // If tab is silences then display empty silence to populate from scratch. // This will go away if any existing silence is clicked on. if (e.detail.index === 2) { fetch('/_/new_silence', { credentials: 'include', }).then(jsonOrThrow).then((json: Silence) => { this.selected = null; this.current_silence = json; this.rhs_state = EDIT_SILENCE; this._render(); }).catch(errorMessage); } else if (e.detail.index === 4) { // If tab is audit logs then load them. this.getAuditLogs(); this.rhs_state = VIEW_AUDITLOG; this._render(); } else { this.rhs_state = START; this._render(); } } private clickHandler(e: KeyboardEvent): void { this.shift_pressed_during_click = e.shiftKey; e.stopPropagation(); } private silenceClick(silence: Silence): void { this.current_silence = JSON.parse(JSON.stringify(silence)) as Silence; this.selected = silence; this.rhs_state = EDIT_SILENCE; this._render(); } private statsClick(incident: Incident): void { this.selected = incident; this.incidentStats(); this.rhs_state = VIEW_STATS; } // Update the paramset for a silence as Incidents are checked and unchecked. // TODO(jcgregorio) Remove this once checkbox-sk is fixed. private check_selected_impl(key: string, isChecked: boolean): void { if (isChecked) { this.last_checked_incident = key; this.checked.add(key); this.incidents.forEach((i) => { if (i.key === key) { paramset.add(this.current_silence!.param_set, i.params, this.ignored); } }); } else { this.last_checked_incident = null; this.checked.delete(key); this.current_silence!.param_set = {}; this.incidents.forEach((i) => { if (this.checked.has(i.key)) { paramset.add(this.current_silence!.param_set, i.params, this.ignored); } }); } if (this.isBotCentricView) { this.make_bot_centric_param_set(this.current_silence!.param_set); } this.rhs_state = EDIT_SILENCE; this._render(); } // Goes through the paramset and leaves only silence keys that are useful // in bot-centric view like 'alertname' and 'bot'. private make_bot_centric_param_set(target_paramset: ParamSet): void { Object.keys(target_paramset).forEach((key) => { if (BOT_CENTRIC_PARAMS.indexOf(key) === -1) { delete target_paramset[key]; } }); } private check_selected(e: Event): void { const checkbox = this.findParent(e.target as HTMLElement, 'CHECKBOX-SK') as CheckOrRadio; const incidents_to_check: string[] = []; if (this.isBotCentricView && this.bots_to_incidents && this.bots_to_incidents[checkbox.id]) { this.bots_to_incidents[checkbox.id].forEach((i) => { incidents_to_check.push(i.key); }); } else { incidents_to_check.push(checkbox.id); } const checkSelectedImplFunc = () => { incidents_to_check.forEach((id) => { this.check_selected_impl(id, checkbox.checked); }); }; if (!this.checked.size) { // Request a new silence. fetch('/_/new_silence', { credentials: 'include', }).then(jsonOrThrow).then((json) => { this.selected = null; this.current_silence = json; checkSelectedImplFunc(); }).catch(errorMessage); } else if (this.shift_pressed_during_click && this.last_checked_incident) { let foundStart = false; let foundEnd = false; // Find all incidents included in the range during shift click. const incidents_included_in_range: string[] = []; // The incidents we go through for shift click selections will be // different for bot-centric vs normal view. const incidents = this.isBotCentricView ? ([] as Incident[]).concat(...Object.values(this.bots_to_incidents)) : this.incidents; incidents.some((i) => { if (i.key === this.last_checked_incident || incidents_to_check.includes(i.key)) { if (!foundStart) { // This is the 1st time we have entered this block. This means we // found the first incident. foundStart = true; } else { // This is the 2nd time we have entered this block. This means we // found the last incident. foundEnd = true; } } if (foundStart) { incidents_included_in_range.push(i.key); } return foundEnd; }); if (foundStart && foundEnd) { incidents_included_in_range.forEach((key) => { this.check_selected_impl(key, true); }); } else { // Could not find start and/or end incident. Only check the last // clicked. checkSelectedImplFunc(); } } else { checkSelectedImplFunc(); } } private select(incident: Incident): void { this.state.alert_id = incident.id; this.stateHasChanged(); this.rhs_state = INCIDENT; this.checked = new Set(); this.selected = incident; this.current_silence = null; this._render(); } private addNote(e: CustomEvent): void { this.doImpl('/_/add_note', e.detail); } private delNote(e: CustomEvent): void { this.doImpl('/_/del_note', e.detail); } private addSilenceParam(silence: Silence): void { // Don't save silences that are just being created when you add a param. if (!silence.key) { this.current_silence = silence; this._render(); return; } this.checked = new Set(); this.doImpl('/_/save_silence', silence, (json: Silence) => this.silenceAction(json, false)); } private deleteSilenceParam(silence: Silence): void { // Don't save silences that are just being created when you delete a param. if (!silence.key) { this.current_silence = silence; this._render(); return; } this.checked = new Set(); this.doImpl('/_/save_silence', silence, (json: Silence) => this.silenceAction(json, false)); } private modifySilenceParam(silence: Silence): void { // Don't save silences that are just being created when you modify a param. if (!silence.key) { this.current_silence = silence; this._render(); return; } this.checked = new Set(); this.doImpl('/_/save_silence', silence, (json: Silence) => this.silenceAction(json, false)); } private saveSilence(silence: Silence): void { this.checked = new Set(); this.doImpl('/_/save_silence', silence, (json: Silence) => this.silenceAction(json, true)); } private archiveSilence(silence: Silence): void { this.doImpl('/_/archive_silence', silence, (json: Silence) => this.silenceAction(json, true)); } private reactivateSilence(silence: Silence): void { this.doImpl('/_/reactivate_silence', silence, (json: Silence) => this.silenceAction(json, false)); } private deleteSilence(silence: Silence): void { this.doImpl('/_/del_silence', silence, (json: Silence) => { for (let i = 0; i < this.silences.length; i++) { if (this.silences[i].key === json.key) { this.silences.splice(i, 1); this.rhs_state = START; break; } } }); } private addSilenceNote(e: CustomEvent): void { this.doImpl('/_/add_silence_note', e.detail, (json: Silence) => this.silenceAction(json, false)); } private delSilenceNote(e: CustomEvent): void { this.doImpl('/_/del_silence_note', e.detail, (json: Silence) => this.silenceAction(json, false)); } private botChooser(): void { this.populateBotsToIncidents(this.incidents); ($$('#bot-chooser', this) as BotChooserSk).open(this.bots_to_incidents, this.current_silence!.param_set.bot!).then((bot) => { if (!bot) { return; } const bot_incidents = this.bots_to_incidents[bot]; bot_incidents.forEach((i) => { const bot_centric_params: Params = {}; BOT_CENTRIC_PARAMS.forEach((p) => { bot_centric_params[p] = i.params[p]; }); paramset.add(this.current_silence!.param_set, bot_centric_params, this.ignored); }); this.modifySilenceParam(this.current_silence!); }); } private assign(e: CustomEvent): void { const owner = this.selected && (this.selected as Incident).params.owner; ($$('#email-chooser', this) as EmailChooserSk).open(this.emails, owner!).then((email) => { const detail = { key: e.detail.key, email: email, }; this.doImpl('/_/assign', detail); }); } private flipBotCentricView(): void { this.isBotCentricView = !this.isBotCentricView; this._render(); } private assignMultiple(): void { // See if the selected incidents have a common owner. let commonOwner = ''; for (let i = 0; i < this.incidents.length; i++) { if (!this.checked.has(this.incidents[i].key)) { // This incident has not been selected. continue; } const incidentOwner = this.incidents[i].params.owner; if (incidentOwner) { if (commonOwner === '') { commonOwner = incidentOwner; } else if (commonOwner !== incidentOwner) { // The incident owner is different than the common owner found so far. // This means there is no common owner; commonOwner = ''; break; } } else { // This incident has no owner so there can be no common owner. commonOwner = ''; break; } } ($$('#email-chooser', this) as EmailChooserSk).open(this.emails, commonOwner).then((email) => { const detail = { keys: Array.from(this.checked), email: email, }; this.doImpl('/_/assign_multiple', detail, (json) => { this.incidents = json; this.checked = new Set(); this._render(); }); }); } private assignToOwner(e: CustomEvent): void { const owner = this.selected && (this.selected as Incident).params.owner; const detail = { key: e.detail.key, email: owner, }; this.doImpl('/_/assign', detail); } private take(e: CustomEvent): void { this.doImpl('/_/take', e.detail); // Do not do desktop notification on takes, it is redundant. this.incidents_notified[e.detail.key] = true; } private getStats(): void { const detail: StatsRequest = { range: this.stats_range, }; this.doImpl('/_/stats', detail, (json: Stat[]) => this.statsAction(json)); } private getAuditLogs(): void { this.doImpl('/_/audit_logs', {}, (json: AuditLog[]) => this.auditLogsAction(json)); } private incidentStats(): void { const detail: IncidentsInRangeRequest = { incident: this.selected as Incident, range: this.stats_range, }; this.doImpl('/_/incidents_in_range', detail, (json: Incident[]) => this.incidentStatsAction(json)); } // Actions to take after updating incident stats. private incidentStatsAction(json: Incident[]): void { this.incident_stats = json; } // Actions to take after updating Stats. private statsAction(json: Stat[]): void { this.stats = json; } // Actions to take after updating Audit Logs. private auditLogsAction(json: AuditLog[]): void { this.audit_logs = json; } // Actions to take after updating an Incident. private incidentAction(json: Incident): void { const incidents = this.incidents; for (let i = 0; i < incidents.length; i++) { if (incidents[i].key === json.key) { incidents[i] = json; break; } } this.selected = json; } // Actions to take after updating a Silence. private silenceAction(json: Silence, clear: boolean): void { let found = false; this.current_silence = json; for (let i = 0; i < this.silences.length; i++) { if (this.silences[i].key === json.key) { this.silences[i] = json; found = true; break; } } if (!found) { this.silences.push(json); } if (clear) { this.rhs_state = START; } } // Common work done for all fetch requests. private doImpl(url: string, detail: any, action = (json: any) => this.incidentAction(json)): void { this.spinner!.active = true; fetch(url, { body: JSON.stringify(detail), headers: { 'content-type': 'application/json', }, credentials: 'include', method: 'POST', }).then(jsonOrThrow).then((json) => { action(json); this._render(); this.spinner!.active = false; }).catch((msg) => { this.spinner!.active = false; msg.resp.text().then(errorMessage); }); } // Fix-up all the incidents and silences, including re-sorting them. private rationalize(): void { this.incidents.forEach((incident) => { const silenced = this.silences.reduce((isSilenced, silence) => isSilenced || (silence.active && paramset.match(silence.param_set, incident.params)), false); incident.params.__silence_state = silenced ? 'silenced' : 'active'; }); // Sort the incidents, using the following 'sortby' list as tiebreakers. const sortby = ['__silence_state', 'assigned_to', 'alertname', 'abbr', 'id']; this.incidents.sort((a, b) => { // Sort active before inactive. if (a.active !== b.active) { return a.active ? -1 : 1; } // Inactive incidents are then sorted by 'lastseen' timestamp. if (!a.active) { const delta = b.last_seen - a.last_seen; if (delta) { return delta; } } for (let i = 0; i < sortby.length; i++) { const key = sortby[i]; const left = a.params[key] || ''; const right = b.params[key] || ''; const cmp = left.localeCompare(right); if (cmp) { return cmp; } } return 0; }); this.silences.sort((a, b) => { // Sort active before inactive. if (a.active !== b.active) { return a.active ? -1 : 1; } return b.updated - a.updated; }); } private needsTriaging(incident: Incident, isInfraGardener: boolean): boolean { if (incident.active && (incident.params.__silence_state !== 'silenced') && ( (isInfraGardener && !incident.params.assigned_to) || (incident.params.assigned_to === this.user) || (incident.params.owner === this.user && !incident.params.assigned_to) ) ) { return true; } return false; } private requestDesktopNotificationPermission(): void { if (Notification && Notification.permission === 'default') { Notification.requestPermission(); } } private sendDesktopNotification(unNotifiedIncidents: Incident[]): void { if (unNotifiedIncidents.length === 0) { // Do nothing. return; } let text = ''; if (unNotifiedIncidents.length === 1) { text = `${unNotifiedIncidents[0].params.alertname}\n\n${unNotifiedIncidents[0].params.description}`; } else { text = `There are ${unNotifiedIncidents.length} alerts assigned to you`; } const notification = new Notification('am.skia.org notification', { icon: '/dist/icon-active.png', body: text, // 'tag' handles multi-tab scenarios. When multiple tabs are open then // only one notification is sent for the same alert. tag: `alertManagerNotification${text}`, }); // onclick move focus to the am.skia.org tab and close the notification. notification.onclick = () => { window.parent.focus(); window.focus(); // Supports older browsers. this.select(unNotifiedIncidents[0]); // Display the 1st incident. notification.close(); }; setTimeout(notification.close.bind(notification), 10000); } private _render(): void { this.rationalize(); render(AlertManagerSk.template(this), this, { eventContext: this }); // Update the icon. const isInfraGardener = this.user === this.infra_gardener; const numActive = this.incidents.reduce((n, incident) => n += this.needsTriaging(incident, isInfraGardener) ? 1 : 0, 0); // Show desktop notifications only if permission was granted and only if // silences have been successfully fetched. If silences have not been // fetched yet then we might end up notifying on silenced incidents. if (Notification.permission === 'granted' && this.silences.length !== 0) { const unNotifiedIncidents = this.incidents.filter((i) => !this.incidents_notified[i.key] && this.needsTriaging(i, isInfraGardener)); this.sendDesktopNotification(unNotifiedIncidents); unNotifiedIncidents.forEach((i) => this.incidents_notified[i.key] = true); } document.title = `${numActive} - AlertManager`; if (!this.favicon) { return; } if (numActive > 0) { this.favicon.href = '/dist/icon-active.png'; } else { this.favicon.href = '/dist/icon.png'; } } } define('alert-manager-sk', AlertManagerSk);
the_stack
* Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ import { FtrProviderContext } from '../../ftr_provider_context'; import { WebElementWrapper } from '../lib/web_element_wrapper'; const REMOVE_PANEL_DATA_TEST_SUBJ = 'embeddablePanelAction-deletePanel'; const EDIT_PANEL_DATA_TEST_SUBJ = 'embeddablePanelAction-editPanel'; const REPLACE_PANEL_DATA_TEST_SUBJ = 'embeddablePanelAction-replacePanel'; const CLONE_PANEL_DATA_TEST_SUBJ = 'embeddablePanelAction-clonePanel'; const TOGGLE_EXPAND_PANEL_DATA_TEST_SUBJ = 'embeddablePanelAction-togglePanel'; const CUSTOMIZE_PANEL_DATA_TEST_SUBJ = 'embeddablePanelAction-ACTION_CUSTOMIZE_PANEL'; const OPEN_CONTEXT_MENU_ICON_DATA_TEST_SUBJ = 'embeddablePanelToggleMenuIcon'; const OPEN_INSPECTOR_TEST_SUBJ = 'embeddablePanelAction-openInspector'; export function DashboardPanelActionsProvider({ getService, getPageObjects }: FtrProviderContext) { const log = getService('log'); const testSubjects = getService('testSubjects'); const PageObjects = getPageObjects(['header', 'common']); return new (class DashboardPanelActions { async findContextMenu(parent?: WebElementWrapper) { return parent ? await testSubjects.findDescendant(OPEN_CONTEXT_MENU_ICON_DATA_TEST_SUBJ, parent) : await testSubjects.find(OPEN_CONTEXT_MENU_ICON_DATA_TEST_SUBJ); } async isContextMenuIconVisible() { log.debug('isContextMenuIconVisible'); return await testSubjects.exists(OPEN_CONTEXT_MENU_ICON_DATA_TEST_SUBJ); } async toggleContextMenu(parent?: WebElementWrapper) { log.debug('toggleContextMenu'); await (parent ? parent.moveMouseTo() : testSubjects.moveMouseTo('dashboardPanelTitle')); const toggleMenuItem = await this.findContextMenu(parent); await toggleMenuItem.click(); } async expectContextMenuToBeOpen() { await testSubjects.existOrFail('embeddablePanelContextMenuOpen'); } async openContextMenu(parent?: WebElementWrapper) { log.debug(`openContextMenu(${parent}`); if (await testSubjects.exists('embeddablePanelContextMenuOpen')) return; await this.toggleContextMenu(parent); await this.expectContextMenuToBeOpen(); } async hasContextMenuMoreItem() { return await testSubjects.exists('embeddablePanelMore-mainMenu'); } async clickContextMenuMoreItem() { const hasMoreSubPanel = await testSubjects.exists('embeddablePanelMore-mainMenu'); if (hasMoreSubPanel) { await testSubjects.click('embeddablePanelMore-mainMenu'); } } async openContextMenuMorePanel(parent?: WebElementWrapper) { await this.openContextMenu(parent); await this.clickContextMenuMoreItem(); } async clickEdit() { log.debug('clickEdit'); await this.openContextMenu(); const isActionVisible = await testSubjects.exists(EDIT_PANEL_DATA_TEST_SUBJ); if (!isActionVisible) await this.clickContextMenuMoreItem(); await testSubjects.clickWhenNotDisabled(EDIT_PANEL_DATA_TEST_SUBJ); await PageObjects.header.waitUntilLoadingHasFinished(); await PageObjects.common.waitForTopNavToBeVisible(); } async editPanelByTitle(title?: string) { log.debug(`editPanelByTitle(${title})`); if (title) { const panelOptions = await this.getPanelHeading(title); await this.openContextMenu(panelOptions); } else { await this.openContextMenu(); } await testSubjects.clickWhenNotDisabled(EDIT_PANEL_DATA_TEST_SUBJ); } async clickExpandPanelToggle() { log.debug(`clickExpandPanelToggle`); this.openContextMenu(); const isActionVisible = await testSubjects.exists(TOGGLE_EXPAND_PANEL_DATA_TEST_SUBJ); if (!isActionVisible) await this.clickContextMenuMoreItem(); await testSubjects.click(TOGGLE_EXPAND_PANEL_DATA_TEST_SUBJ); } async removePanel() { log.debug('removePanel'); await this.openContextMenu(); const isActionVisible = await testSubjects.exists(REMOVE_PANEL_DATA_TEST_SUBJ); if (!isActionVisible) await this.clickContextMenuMoreItem(); const isPanelActionVisible = await testSubjects.exists(REMOVE_PANEL_DATA_TEST_SUBJ); if (!isPanelActionVisible) await this.clickContextMenuMoreItem(); await testSubjects.click(REMOVE_PANEL_DATA_TEST_SUBJ); } async removePanelByTitle(title: string) { const header = await this.getPanelHeading(title); await this.openContextMenu(header); const isActionVisible = await testSubjects.exists(REMOVE_PANEL_DATA_TEST_SUBJ); if (!isActionVisible) await this.clickContextMenuMoreItem(); await testSubjects.click(REMOVE_PANEL_DATA_TEST_SUBJ); } async customizePanel(parent?: WebElementWrapper) { await this.openContextMenu(parent); await testSubjects.click(CUSTOMIZE_PANEL_DATA_TEST_SUBJ); } async replacePanelByTitle(title?: string) { log.debug(`replacePanel(${title})`); if (title) { const panelOptions = await this.getPanelHeading(title); await this.openContextMenu(panelOptions); } else { await this.openContextMenu(); } const actionExists = await testSubjects.exists(REPLACE_PANEL_DATA_TEST_SUBJ); if (!actionExists) { await this.clickContextMenuMoreItem(); } await testSubjects.click(REPLACE_PANEL_DATA_TEST_SUBJ); } async clonePanelByTitle(title?: string) { log.debug(`clonePanel(${title})`); if (title) { const panelOptions = await this.getPanelHeading(title); await this.openContextMenu(panelOptions); } else { await this.openContextMenu(); } await testSubjects.click(CLONE_PANEL_DATA_TEST_SUBJ); } async openInspectorByTitle(title: string) { const header = await this.getPanelHeading(title); await this.openInspector(header); } async openInspector(parent: WebElementWrapper) { await this.openContextMenu(parent); const exists = await testSubjects.exists(OPEN_INSPECTOR_TEST_SUBJ); if (!exists) { await this.clickContextMenuMoreItem(); } await testSubjects.click(OPEN_INSPECTOR_TEST_SUBJ); } async expectExistsRemovePanelAction() { log.debug('expectExistsRemovePanelAction'); await this.expectExistsPanelAction(REMOVE_PANEL_DATA_TEST_SUBJ); } async expectExistsPanelAction(testSubject: string) { log.debug('expectExistsPanelAction', testSubject); await this.openContextMenu(); if (await testSubjects.exists(CLONE_PANEL_DATA_TEST_SUBJ)) return; if (await this.hasContextMenuMoreItem()) { await this.clickContextMenuMoreItem(); } await testSubjects.existOrFail(CLONE_PANEL_DATA_TEST_SUBJ); await this.toggleContextMenu(); } async expectMissingPanelAction(testSubject: string) { log.debug('expectMissingPanelAction', testSubject); await this.openContextMenu(); await testSubjects.missingOrFail(testSubject); if (await this.hasContextMenuMoreItem()) { await this.clickContextMenuMoreItem(); await testSubjects.missingOrFail(testSubject); } await this.toggleContextMenu(); } async expectExistsEditPanelAction() { log.debug('expectExistsEditPanelAction'); await this.expectExistsPanelAction(EDIT_PANEL_DATA_TEST_SUBJ); } async expectExistsReplacePanelAction() { log.debug('expectExistsReplacePanelAction'); await this.expectExistsPanelAction(REPLACE_PANEL_DATA_TEST_SUBJ); } async expectExistsClonePanelAction() { log.debug('expectExistsClonePanelAction'); await this.expectExistsPanelAction(CLONE_PANEL_DATA_TEST_SUBJ); } async expectMissingEditPanelAction() { log.debug('expectMissingEditPanelAction'); await this.expectMissingPanelAction(EDIT_PANEL_DATA_TEST_SUBJ); } async expectMissingReplacePanelAction() { log.debug('expectMissingReplacePanelAction'); await this.expectMissingPanelAction(REPLACE_PANEL_DATA_TEST_SUBJ); } async expectMissingDuplicatePanelAction() { log.debug('expectMissingDuplicatePanelAction'); await this.expectMissingPanelAction(CLONE_PANEL_DATA_TEST_SUBJ); } async expectMissingRemovePanelAction() { log.debug('expectMissingRemovePanelAction'); await this.expectMissingPanelAction(REMOVE_PANEL_DATA_TEST_SUBJ); } async expectExistsToggleExpandAction() { log.debug('expectExistsToggleExpandAction'); await this.expectExistsPanelAction(TOGGLE_EXPAND_PANEL_DATA_TEST_SUBJ); } async getPanelHeading(title: string) { return await testSubjects.find(`embeddablePanelHeading-${title.replace(/\s/g, '')}`); } async clickHidePanelTitleToggle() { await testSubjects.click('customizePanelHideTitle'); } async toggleHidePanelTitle(originalTitle: string) { log.debug(`hidePanelTitle(${originalTitle})`); if (originalTitle) { const panelOptions = await this.getPanelHeading(originalTitle); await this.customizePanel(panelOptions); } else { await this.customizePanel(); } await this.clickHidePanelTitleToggle(); await testSubjects.click('saveNewTitleButton'); } /** * * @param customTitle * @param originalTitle - optional to specify which panel to change the title on. * @return {Promise<void>} */ async setCustomPanelTitle(customTitle: string, originalTitle?: string) { log.debug(`setCustomPanelTitle(${customTitle}, ${originalTitle})`); if (originalTitle) { const panelOptions = await this.getPanelHeading(originalTitle); await this.customizePanel(panelOptions); } else { await this.customizePanel(); } await testSubjects.setValue('customEmbeddablePanelTitleInput', customTitle); await testSubjects.click('saveNewTitleButton'); } async resetCustomPanelTitle(panel: WebElementWrapper) { log.debug('resetCustomPanelTitle'); await this.customizePanel(panel); await testSubjects.click('resetCustomEmbeddablePanelTitle'); await testSubjects.click('saveNewTitleButton'); await this.toggleContextMenu(panel); } async getActionWebElementByText(text: string): Promise<WebElementWrapper> { log.debug(`getActionWebElement: "${text}"`); const menu = await testSubjects.find('multipleActionsContextMenu'); const items = await menu.findAllByCssSelector('[data-test-subj*="embeddablePanelAction-"]'); for (const item of items) { const currentText = await item.getVisibleText(); if (currentText === text) { return item; } } throw new Error(`No action matching text "${text}"`); } })(); }
the_stack
import { createHash } from "crypto"; import fs from "fs"; import pathlib from "path"; import * as executor from "./executor"; import { createConverter } from "./converter"; import { runInTmpAsync, WaitFileEventFunc, createConverterWithFileWatcher, sleep, } from "./testutil"; import ts from "@tslab/typescript-for-tslab"; import { normalizeJoin } from "./tspath"; let ex: executor.Executor; let waitFileEvent: WaitFileEventFunc; let consoleLogCalls = []; let consoleErrorCalls = []; beforeAll(() => { let node = createConverterWithFileWatcher(); waitFileEvent = node.waitFileEvent; let browserConv = createConverter({ isBrowser: true }); let close = () => { node.converter.close(); browserConv.close(); }; let exconsole = { log: function (...args) { consoleLogCalls.push(args); }, error: function (...args) { consoleErrorCalls.push(args); }, }; const convs = { node: node.converter, browser: browserConv, close }; ex = executor.createExecutor(process.cwd(), convs, exconsole); }); afterAll(() => { if (ex) { ex.close(); } }); afterEach(() => { ex.reset(); consoleLogCalls = []; consoleErrorCalls = []; }); describe("execute", () => { it("immediate", () => { // Show code is executed immediately with execute. // See a docstring of execute for details. const promise = ex.execute("let x = 10; x + 4;"); expect(consoleLogCalls).toEqual([[14]]); }); it("calculate numbers", async () => { expect(await ex.execute(`let x = 3, y = 4;`)).toBe(true); expect(await ex.execute(`let z = x * y; z -= 2;`)).toBe(true); expect(await ex.execute(`y = x * z;`)).toBe(true); expect(ex.locals).toEqual({ x: 3, y: 30, z: 10 }); expect(await ex.execute(`x = Math.max(z, y)`)); expect(ex.locals).toEqual({ x: 30, y: 30, z: 10 }); expect(consoleLogCalls).toEqual([[10], [30], [30]]); }); it("recursion", async () => { let ok = await ex.execute( ` function naiveFib(n: number) { if (n > 1) { return naiveFib(n - 1) + naiveFib(n - 2); } return 1; } let fib20 = naiveFib(20);` ); expect(ok).toBe(true); expect(ex.locals.fib20).toEqual(10946); }); it("node globals", async () => { let ok = await ex.execute(`let ver = process.version;`); expect(ok).toBe(true); expect(ex.locals.ver).toEqual(process.version); }); it("redeclare const", async () => { expect(await ex.execute(`const x = 3;`)).toBe(true); expect(await ex.execute(`const x = 4;`)).toBe(true); expect(ex.locals).toEqual({ x: 4 }); }); it("class", async () => { let ok = await ex.execute(` class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } toString(): string { return 'Person(' + this.name + ', ' + this.age + ')'; } } let alice = (new Person('alice', 123)).toString(); `); expect(ok).toBe(true); expect(ex.locals.alice).toEqual("Person(alice, 123)"); }); for (const tc of [ { name: "import start", import: 'import * as crypto from "crypto";' }, { name: "import default", import: 'import crypto from "crypto";' }, { name: "dynamic import", import: 'const crypto = await import("crypto")' }, ]) { // Note: For some reason, dynamic import is way slower than others. it(tc.name, async () => { let ok = await ex.execute( [ tc.import, 'const message = "Hello TypeScript!";', 'const hash = crypto.createHash("sha256").update(message).digest("hex");', ].join("\n") ); expect(ok).toBe(true); const hash = createHash("sha256") .update("Hello TypeScript!") .digest("hex"); expect(ex.locals.hash).toEqual(hash); }); } it("enum", async () => { expect( await ex.execute(` enum Direction { Up = 1, Down, Left, Right, } `) ).toBe(true); expect(await ex.execute(`const x = Direction.Down`)).toBe(true); expect(await ex.execute(`const y = Direction[2]`)).toBe(true); expect(await ex.execute(`let Direction = null;`)).toBe(true); expect(ex.locals).toEqual({ x: 2, y: "Down", Direction: null }); }); it("exports defineProperty", async () => { // Check defineProperty is hooked and we can redefine properties in tslab. expect( await ex.execute( [ 'Object.defineProperty(exports, "myprop", {value: "p0"});', "let prop0 = exports.myprop", 'Object.defineProperty(exports, "myprop", {value: "p1"});', "let prop1 = exports.myprop", ].join("\n") ) ).toBe(true); expect(ex.locals).toEqual({ myprop: "p1", prop0: "p0", prop1: "p1", }); }); it("syntax error", async () => { expect(await ex.execute(`let x + y;`)).toBe(false); expect(consoleErrorCalls).toEqual([ ["%s%d:%d - %s", "", 1, 7, "',' expected."], ["%s%d:%d - %s", "", 1, 9, "Cannot find name 'y'."], ]); }); it("exception", async () => { let ok = await ex.execute(`throw new Error('my error');`); expect(ok).toBe(false); expect(consoleErrorCalls).toEqual([[new Error("my error")]]); }); it("await promise resolved", async () => { let promise = ex.execute(` await new Promise(resolve => { resolve('Hello Promise'); }); `); // The promise is not resolved yet. expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([]); expect(await promise).toBe(true); expect(consoleLogCalls).toEqual([["Hello Promise"]]); expect(consoleErrorCalls).toEqual([]); }); it("await promise rejected", async () => { let promise = ex.execute(` await new Promise((_, reject) => { reject('Good Bye Promise'); }); `); // The promise is not resolved yet. expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([]); expect(await promise).toBe(false); expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([["Good Bye Promise"]]); }); it("await async resolved", async () => { let promise = ex.execute(` async function fn(msg: string) { return 'Hello ' + msg; } await fn('async'); `); // The promise is not resolved yet. expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([]); expect(await promise).toBe(true); expect(consoleLogCalls).toEqual([["Hello async"]]); expect(consoleErrorCalls).toEqual([]); }); it("await async rejected", async () => { let promise = ex.execute(` async function fn(msg: string) { throw 'Good Bye async'; } await fn('async'); `); // The promise is not resolved yet. expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([]); expect(await promise).toBe(false); expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([["Good Bye async"]]); }); it("assign top-level await", async () => { let promise = ex.execute(` async function asyncHello() { return "Hello, World!"; } let msg = await asyncHello();`); expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([]); expect(await promise).toBe(true); expect(ex.locals.msg).toEqual("Hello, World!"); }); it("promise rejected immediately", async () => { let promise = ex.execute(` new Promise(() => { throw new Error('rejected immediately'); }); `); expect(await promise).toBe(true); expect(consoleErrorCalls).toEqual([]); expect(consoleLogCalls.length).toEqual(1); expect(consoleLogCalls[0].length).toEqual(1); // If we don't catch this, another test with Promise fails for some reason. // TODO: Investigate what happens internally. try { await consoleLogCalls[0][0]; fail("await above must fail."); } catch (e) { expect(e).toEqual(new Error("rejected immediately")); } }); it("import star", async () => { expect( await ex.execute(` import * as crypto from "crypto"; let h0 = crypto.createHash("sha256").update("Hello TypeScript!").digest("hex"); `) ).toBe(true); expect( await ex.execute(` let h1 = crypto.createHash("sha256").update("Hello TypeScript!").digest("hex"); `) ).toBe(true); expect(await ex.execute(`let crypto = 'crypto';`)).toBe(true); const hash = createHash("sha256").update("Hello TypeScript!").digest("hex"); expect(ex.locals).toEqual({ crypto: "crypto", h0: hash, h1: hash }); }); it("import star", async () => { expect( await ex.execute(` import * as crypto from "crypto"; let h0 = crypto.createHash("sha256").update("Hello TypeScript!").digest("hex"); `) ).toBe(true); expect( await ex.execute(` let h1 = crypto.createHash("sha256").update("Hello TypeScript!").digest("hex"); `) ).toBe(true); expect(await ex.execute(`let crypto = 'crypto';`)).toBe(true); const hash = createHash("sha256").update("Hello TypeScript!").digest("hex"); expect(ex.locals).toEqual({ crypto: "crypto", h0: hash, h1: hash }); }); it("import default", async () => { expect( await ex.execute(` import crypto from "crypto"; let h0 = crypto.createHash("sha256").update("Hello TypeScript!").digest("hex"); `) ).toBe(true); expect( await ex.execute(` let h1 = crypto.createHash("sha256").update("Hello TypeScript!").digest("hex"); `) ).toBe(true); expect(await ex.execute(`let crypto = 'crypto';`)).toBe(true); const hash = createHash("sha256").update("Hello TypeScript!").digest("hex"); expect(ex.locals).toEqual({ crypto: "crypto", h0: hash, h1: hash }); }); it("named import", async () => { expect( await ex.execute(` import {createHash} from "crypto"; let h0 = createHash("sha256").update("Hello TypeScript!").digest("hex"); `) ).toBe(true); expect( await ex.execute(` let h1 = createHash("sha256").update("Hello TypeScript!").digest("hex"); `) ).toBe(true); expect(await ex.execute(`let createHash = 'createHash';`)).toBe(true); const hash = createHash("sha256").update("Hello TypeScript!").digest("hex"); expect(ex.locals).toEqual({ createHash: "createHash", h0: hash, h1: hash, }); }); it("package tslab", async () => { expect( await ex.execute(` import * as tslab from "tslab"; let png = tslab.display.png; `) ).toBe(true); expect(typeof ex.locals.png).toEqual("function"); }); it("performance", async () => { function naiveFib(n: number): number { if (n > 1) { return naiveFib(n - 1) + naiveFib(n - 2); } return 1; } let start = Date.now(); let want = naiveFib(35); let end = Date.now(); let t0 = end - start; start = Date.now(); expect( await ex.execute(` function naiveFib(n: number): number { if (n > 1) { return naiveFib(n - 1) + naiveFib(n - 2); } return 1; } let got = naiveFib(35); `) ).toBe(true); end = Date.now(); let t1 = end - start; expect(ex.locals.got).toBe(want); expect(t1 / t0).toBeGreaterThan(0.5); expect(t0 / t1).toBeGreaterThan(0.5); }); it("fixed bug#32", async () => { // https://github.com/yunabe/tslab/issues/32 is reproducible. expect(await ex.execute(`let b = {}.constructor === Object`)).toBe(true); expect(ex.locals.b).toEqual(true); }); }); describe("interrupt", () => { it("interrupt without execute", () => { // Confirm it does not cause any problem like "UnhandledPromiseRejection". ex.interrupt(); }); it("interrupt", async () => { // Confirm it does not cause any problem like "UnhandledPromiseRejection". let src = "await new Promise(resolve => setTimeout(() => resolve('done'), 10));"; let promise = ex.execute(src); expect(await promise).toBe(true); expect(consoleLogCalls).toEqual([["done"]]); consoleLogCalls = []; promise = ex.execute(src); ex.interrupt(); expect(await promise).toBe(false); expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([ [new Error("Interrupted asynchronously")], ]); }); }); describe("modules", () => { it("updated", async () => { expect( await ex.execute(` /** * @module mylib */ export const a = 'AAA';`) ).toBe(true); expect( await ex.execute( 'import * as mylib from "./mylib";\nconst b = mylib.a + "BBB";' ) ).toBe(true); expect(ex.locals.b).toEqual("AAABBB"); expect( await ex.execute(` /** * @module mylib */ export let a = 'XXX';`) ).toBe(true); expect( await ex.execute( 'import * as mylib from "./mylib";\nconst b = mylib.a + "BBB";' ) ).toBe(true); expect(ex.locals.b).toEqual("XXXBBB"); expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([]); }); it("jsx", async () => { expect( await ex.execute( `/** @jsx @module mylib */ let React: any; let x = <div></div>` ) ); expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([]); }); }); describe("externalFiles", () => { it("dependencies", async () => { await runInTmpAsync("pkg", async (dir) => { fs.writeFileSync( pathlib.join(dir, "a.ts"), 'export const aVal: string = "AAA";' ); fs.mkdirSync(pathlib.join(dir, "b")); fs.writeFileSync( pathlib.join(dir, "b/c.ts"), 'import {aVal} from "../a";\nexport const bVal = "BBB" + aVal;' ); let promise = ex.execute( [`import {bVal} from "./${dir}/b/c";`].join("\n") ); expect(await promise).toBe(true); expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([]); expect(ex.locals).toEqual({ bVal: "BBBAAA" }); }); }); it("errors", async () => { await runInTmpAsync("pkg", async (dir) => { fs.writeFileSync( pathlib.join(dir, "a.ts"), 'export const aVal: number = "AAA";' ); let promise = ex.execute(`import {aVal} from "./${dir}/a";`); expect(await promise).toBe(false); expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([ [ "%s%d:%d - %s", pathlib.normalize(`${dir}/a.ts `), 1, 14, "Type 'string' is not assignable to type 'number'.", ], ]); }); }); it("cache module", async () => { await runInTmpAsync("pkg", async (dir) => { fs.writeFileSync( pathlib.join(dir, "rand.ts"), [ 'import { randomBytes } from "crypto";', 'export const uid = randomBytes(8).toString("hex");', ].join("\n") ); let promise = ex.execute(`import {uid} from "./${dir}/rand";`); expect(await promise).toBe(true); const uid = ex.locals.uid; expect(typeof uid).toBe("string"); promise = ex.execute(`import {uid} from "./${dir}/rand";`); expect(await promise).toBe(true); const uid2 = ex.locals.uid; expect(uid2).toEqual(uid); }); }); it("changed", async () => { await runInTmpAsync("pkg", async (dir) => { const srcPath = normalizeJoin(process.cwd(), dir, "a.ts"); fs.writeFileSync(srcPath, 'export const aVal = "ABC";'); let promise = ex.execute(`import {aVal} from "./${dir}/a";`); expect(await promise).toBe(true); expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([]); expect(ex.locals.aVal).toEqual("ABC"); fs.writeFileSync(srcPath, 'export const aVal = "XYZ";'); await waitFileEvent(srcPath, ts.FileWatcherEventKind.Changed); // yield to TyeScript compiler just for safety. await sleep(0); promise = ex.execute(`import {aVal} from "./${dir}/a";`); expect(await promise).toBe(true); expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([]); expect(ex.locals.aVal).toEqual("XYZ"); }); }); }); describe("browswer", () => { it("module", async () => { expect( await ex.execute( `/** @browser @module mylib */ const div = document.createElement('div');` ) ).toBe(true); expect(consoleLogCalls).toEqual([]); expect(consoleErrorCalls).toEqual([]); }); it("complete", async () => { const src = `/** @browser @module mylib */ const div = document.querySe[cur]`; const info = ex.complete(src.replace("[cur]", ""), src.indexOf("[cur]")); expect(info.candidates).toEqual(["querySelector", "querySelectorAll"]); }); it("inspect", async () => { const src = `/** @browser @module mylib */ const div = document.createElement('div');`; const info = ex.inspect(src, src.indexOf("document.")); expect(info).toEqual({ displayParts: [ { kind: "keyword", text: "var" }, { kind: "space", text: " " }, { kind: "localName", text: "document" }, { kind: "punctuation", text: ":" }, { kind: "space", text: " " }, { kind: "localName", text: "Document" }, ], documentation: [], kind: "var", kindModifiers: "declare", tags: undefined, textSpan: { length: 8, start: 43 }, }); }); });
the_stack
import { Injectable } from '@angular/core'; import { CoreApp } from '@services/app'; import { CoreSites } from '@services/sites'; import { CoreFilterDelegate } from './filter-delegate'; import { CoreFilter, CoreFilterFilter, CoreFilterFormatTextOptions, CoreFilterClassifiedFilters, CoreFiltersGetAvailableInContextWSParamContext, } from './filter'; import { CoreCourse } from '@features/course/services/course'; import { CoreCourses } from '@features/courses/services/courses'; import { makeSingleton } from '@singletons'; import { CoreEvents, CoreEventSiteData } from '@singletons/events'; import { CoreLogger } from '@singletons/logger'; import { CoreSite } from '@classes/site'; import { CoreCourseHelper } from '@features/course/services/course-helper'; /** * Helper service to provide filter functionalities. */ @Injectable({ providedIn: 'root' }) export class CoreFilterHelperProvider { protected logger: CoreLogger; /** * When a module context is requested, we request all the modules in a course to decrease WS calls. If there are a lot of * modules, checking the cache of all contexts can be really slow, so we use this memory cache to speed up the process. */ protected moduleContextsCache: { [siteId: string]: { [courseId: number]: { [contextLevel: string]: { contexts: CoreFilterClassifiedFilters; time: number; }; }; }; } = {}; constructor() { this.logger = CoreLogger.getInstance('CoreFilterHelperProvider'); CoreEvents.on(CoreEvents.WS_CACHE_INVALIDATED, (data: CoreEventSiteData) => { delete this.moduleContextsCache[data.siteId || '']; }); CoreEvents.on(CoreEvents.SITE_STORAGE_DELETED, (data: CoreEventSiteData) => { delete this.moduleContextsCache[data.siteId || '']; }); } /** * Get the contexts of all blocks in a course. * * @param courseId Course ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the contexts. */ async getBlocksContexts(courseId: number, siteId?: string): Promise<CoreFiltersGetAvailableInContextWSParamContext[]> { const blocks = await CoreCourse.getCourseBlocks(courseId, siteId); const contexts: CoreFiltersGetAvailableInContextWSParamContext[] = []; blocks.forEach((block) => { contexts.push({ contextlevel: 'block', instanceid: block.instanceid, }); }); return contexts; } /** * Get some filters from memory cache. If not in cache, get them and store them in cache. * * @param contextLevel The context level. * @param instanceId Instance ID related to the context. * @param options Options for format text. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the filters. */ protected async getCacheableFilters( contextLevel: string, instanceId: number, getFilters: () => Promise<CoreFiltersGetAvailableInContextWSParamContext[]>, options: CoreFilterFormatTextOptions, site: CoreSite, ): Promise<CoreFilterFilter[]> { // Check the memory cache first. const result = this.getFromMemoryCache(options.courseId ?? -1, contextLevel, instanceId, site); if (result) { return result; } const siteId = site.getId(); const contexts = await getFilters(); const filters = await CoreFilter.getAvailableInContexts(contexts, siteId); this.storeInMemoryCache(options.courseId ?? -1, contextLevel, filters, siteId); return filters[contextLevel][instanceId] || []; } /** * If user is enrolled in the course, return contexts of all enrolled courses to decrease number of WS requests. * * @param courseId Course ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the contexts. */ async getCourseContexts(courseId: number, siteId?: string): Promise<CoreFiltersGetAvailableInContextWSParamContext[]> { const courseIds = await CoreCourses.getCourseIdsIfEnrolled(courseId, siteId); const contexts: CoreFiltersGetAvailableInContextWSParamContext[] = []; courseIds.forEach((courseId) => { contexts.push({ contextlevel: 'course', instanceid: courseId, }); }); return contexts; } /** * Get the contexts of all course modules in a course. * * @param courseId Course ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the contexts. */ async getCourseModulesContexts(courseId: number, siteId?: string): Promise<CoreFiltersGetAvailableInContextWSParamContext[]> { const sections = await CoreCourse.getSections(courseId, false, true, undefined, siteId); const contexts: CoreFiltersGetAvailableInContextWSParamContext[] = []; sections.forEach((section) => { if (section.modules) { section.modules.forEach((module) => { if (CoreCourseHelper.canUserViewModule(module, section)) { contexts.push({ contextlevel: 'module', instanceid: module.id, }); } }); } }); return contexts; } /** * Get the filters in a certain context, performing some checks like the site version. * It's recommended to use this function instead of canGetFilters + getEnabledFilters because this function will check if * it's really needed to call the WS. * * @param contextLevel The context level. * @param instanceId Instance ID related to the context. * @param options Options for format text. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the filters. */ async getFilters( contextLevel: string, instanceId: number, options?: CoreFilterFormatTextOptions, siteId?: string, ): Promise<CoreFilterFilter[]> { options = options || {}; options.contextLevel = contextLevel; options.instanceId = instanceId; options.filter = false; try { const site = await CoreSites.getSite(siteId); siteId = site.getId(); const canGet = await CoreFilter.canGetFilters(siteId); if (!canGet) { options.filter = true; // We cannot check which filters are available, apply them all. return CoreFilterDelegate.getEnabledFilters(contextLevel, instanceId); } let hasFilters = true; if (contextLevel == 'system' || (contextLevel == 'course' && instanceId == site.getSiteHomeId())) { // No need to check the site filters because we're requesting the same context, so we'd do the same twice. } else { // Check if site has any filter to treat. hasFilters = await this.siteHasFiltersToTreat(options, siteId); } if (!hasFilters) { return []; } options.filter = true; if (contextLevel == 'module' && options.courseId) { // Get all the modules filters with a single call to decrease the number of WS calls. const getFilters = this.getCourseModulesContexts.bind(this, options.courseId, siteId); return this.getCacheableFilters(contextLevel, instanceId, getFilters, options, site); } else if (contextLevel == 'course') { // If enrolled, get all enrolled courses filters with a single call to decrease number of WS calls. const getFilters = this.getCourseContexts.bind(this, instanceId, siteId); return this.getCacheableFilters(contextLevel, instanceId, getFilters, options, site); } else if (contextLevel == 'block' && options.courseId && CoreCourse.canGetCourseBlocks(site)) { // Get all the course blocks filters with a single call to decrease number of WS calls. const getFilters = this.getBlocksContexts.bind(this, options.courseId, siteId); return this.getCacheableFilters(contextLevel, instanceId, getFilters, options, site); } return CoreFilter.getAvailableInContext(contextLevel, instanceId, siteId); } catch (error) { this.logger.error('Error getting filters, return an empty array', error, contextLevel, instanceId); return []; } } /** * Get filters and format text. * * @param text Text to filter. * @param contextLevel The context level. * @param instanceId Instance ID related to the context. * @param options Options for format text. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the formatted text and the filters. */ async getFiltersAndFormatText( text: string, contextLevel: string, instanceId: number, options?: CoreFilterFormatTextOptions, siteId?: string, ): Promise<{text: string; filters: CoreFilterFilter[]}> { const filters = await this.getFilters(contextLevel, instanceId, options, siteId); text = await CoreFilter.formatText(text, options, filters, siteId); return { text, filters: filters }; } /** * Get module context filters from the memory cache. * * @param courseId Course the module belongs to. * @param contextLevel Context level. * @param instanceId Instance ID. * @param site Site. * @return The filters, undefined if not found. */ protected getFromMemoryCache( courseId: number, contextLevel: string, instanceId: number, site: CoreSite, ): CoreFilterFilter[] | undefined { const siteId = site.getId(); // Check if we have the context in the memory cache. if (!this.moduleContextsCache[siteId]?.[courseId]?.[contextLevel]) { return; } const cachedData = this.moduleContextsCache[siteId][courseId][contextLevel]; if (!CoreApp.isOnline() || Date.now() <= cachedData.time + site.getExpirationDelay(CoreSite.FREQUENCY_RARELY)) { // We can use cache, return the filters if found. return cachedData.contexts[contextLevel] && cachedData.contexts[contextLevel][instanceId]; } } /** * Check if site has available any filter that should be treated by the app. * * @param options Options passed to the filters. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with boolean: whether it has filters to treat. */ async siteHasFiltersToTreat(options?: CoreFilterFormatTextOptions, siteId?: string): Promise<boolean> { options = options || {}; const site = await CoreSites.getSite(siteId); // Get filters at site level. const filters = await CoreFilter.getAvailableInContext('system', 0, site.getId()); return CoreFilterDelegate.shouldBeApplied(filters, options, site); } /** * Store filters in the memory cache. * * @param contexts Filters to store, classified by contextlevel and instanceid * @param siteId Site ID. */ protected storeInMemoryCache( courseId: number, contextLevel: string, contexts: CoreFilterClassifiedFilters, siteId: string, ): void { this.moduleContextsCache[siteId] = this.moduleContextsCache[siteId] || {}; this.moduleContextsCache[siteId][courseId] = this.moduleContextsCache[siteId][courseId] || {}; this.moduleContextsCache[siteId][courseId][contextLevel] = { contexts: contexts, time: Date.now(), }; } } export const CoreFilterHelper = makeSingleton(CoreFilterHelperProvider);
the_stack
import { Address, BigInt, Bytes, dataSource } from "@graphprotocol/graph-ts"; import { TransactionManager, LiquidityAdded, LiquidityRemoved, TransactionCancelled, TransactionFulfilled, TransactionPrepared, } from "../../generated/TransactionManager/TransactionManager"; import { AssetBalance, Router, DayMetric } from "../../generated/schema"; /** * Updates the subgraph records when LiquidityAdded events are emitted. Will create a Router record if it does not exist * * @param event - The contract event to update the subgraph record with */ export function handleLiquidityAdded(event: LiquidityAdded): void { let router = Router.load(event.params.router.toHex()); if (router == null) { router = new Router(event.params.router.toHex()); router.save(); } // ID is of the format ROUTER_ADDRESS-ASSET_ID const assetBalance = getOrCreateAssetBalance(event.params.assetId, event.params.router); // add new amount assetBalance.amount = assetBalance.amount.plus(event.params.amount); // add supplied amount assetBalance.supplied = assetBalance.supplied.plus(event.params.amount); // save assetBalance.save(); } /** * Updates the subgraph records when LiquidityRemoved events are emitted. Will create a Router record if it does not exist * * @param event - The contract event to update the subgraph record with */ export function handleLiquidityRemoved(event: LiquidityRemoved): void { let router = Router.load(event.params.router.toHex()); if (router == null) { router = new Router(event.params.router.toHex()); router.save(); } // ID is of the format ROUTER_ADDRESS-ASSET_ID const assetBalance = getOrCreateAssetBalance(event.params.assetId, event.params.router); // update amount assetBalance.amount = assetBalance.amount.minus(event.params.amount); // update removed assetBalance.removed = assetBalance.removed.plus(event.params.amount); // save assetBalance.save(); } /** * Creates subgraph records when TransactionPrepared events are emitted. * * @param event - The contract event used to create the subgraph record */ export function handleTransactionPrepared(event: TransactionPrepared): void { // load user and router // router should have liquidity but it may not let router = Router.load(event.params.txData.router.toHex()); if (router == null) { router = new Router(event.params.txData.router.toHex()); router.save(); } const chainId = getChainId(event.address); const routerAddress = event.params.router; const sendingChainId = event.params.txData.sendingChainId; const sendingAssetId = event.params.txData.sendingAssetId; const receivingChainId = event.params.txData.receivingChainId; const receivingAssetId = event.params.txData.receivingAssetId; const amount = event.params.txData.amount; // Get receiving asset balance (update amount and locked) // router is providing liquidity on receiver prepare if (chainId == receivingChainId) { const receivingAssetBalance = getOrCreateAssetBalance(receivingAssetId, routerAddress); receivingAssetBalance.amount = receivingAssetBalance.amount.minus(amount); receivingAssetBalance.locked = receivingAssetBalance.locked.plus(amount); receivingAssetBalance.receivingPrepareTxCount = receivingAssetBalance.receivingPrepareTxCount.plus( BigInt.fromI32(1), ); receivingAssetBalance.save(); } else if (chainId == sendingChainId) { const sendingAssetBalance = getOrCreateAssetBalance(sendingAssetId, routerAddress); sendingAssetBalance.lockedIn = sendingAssetBalance.lockedIn.plus(amount); sendingAssetBalance.sendingPrepareTxCount = sendingAssetBalance.sendingPrepareTxCount.plus(BigInt.fromI32(1)); sendingAssetBalance.save(); } } /** * Updates subgraph records when TransactionFulfilled events are emitted * * @param event - The contract event used to update the subgraph */ export function handleTransactionFulfilled(event: TransactionFulfilled): void { const chainId = getChainId(event.address); const timestamp = event.block.timestamp; const router = event.params.router; const receivingChainId = event.params.args.txData.receivingChainId; const sendingChainId = event.params.args.txData.sendingChainId; const sendingAssetId = event.params.args.txData.sendingAssetId; const receivingAssetId = event.params.args.txData.receivingAssetId; const amount = event.params.args.txData.amount; const relayerFee = event.params.args.relayerFee; // receiving chain if (chainId == receivingChainId) { // Get asset balance const receivingAssetBalance = getOrCreateAssetBalance(receivingAssetId, router); // load metrics const dayMetricReceiving = getOrCreateDayMetric(timestamp, receivingAssetId); // router releases locked liquidity on receiver fulfill receivingAssetBalance.locked = receivingAssetBalance.locked.minus(amount); receivingAssetBalance.volume = receivingAssetBalance.volume.plus(amount); receivingAssetBalance.receivingFulfillTxCount = receivingAssetBalance.receivingFulfillTxCount.plus( BigInt.fromI32(1), ); // Update metrics dayMetricReceiving.volume = dayMetricReceiving.volume.plus(amount); dayMetricReceiving.receivingTxCount = dayMetricReceiving.receivingTxCount.plus(BigInt.fromI32(1)); dayMetricReceiving.relayerFee = dayMetricReceiving.relayerFee.plus(relayerFee); // Save receivingAssetBalance.save(); dayMetricReceiving.save(); } else if (chainId == sendingChainId) { // Get asset balance const sendingAssetBalance = getOrCreateAssetBalance(sendingAssetId, router); // load metrics const dayMetricsSending = getOrCreateDayMetric(timestamp, sendingAssetId); // router receives liquidity back on sender fulfill sendingAssetBalance.amount = sendingAssetBalance.amount.plus(amount); sendingAssetBalance.lockedIn = sendingAssetBalance.lockedIn.minus(amount); sendingAssetBalance.volumeIn = sendingAssetBalance.volumeIn.plus(amount); sendingAssetBalance.sendingFulfillTxCount = sendingAssetBalance.sendingFulfillTxCount.plus(BigInt.fromI32(1)); dayMetricsSending.volumeIn = dayMetricsSending.volumeIn.plus(amount); dayMetricsSending.sendingTxCount = dayMetricsSending.sendingTxCount.plus(BigInt.fromI32(1)); // Save sendingAssetBalance.save(); dayMetricsSending.save(); } } /** * Updates subgraph records when TransactionCancelled events are emitted * * @param event - The contract event used to update the subgraph */ export function handleTransactionCancelled(event: TransactionCancelled): void { const chainId = getChainId(event.address); const timestamp = event.block.timestamp; const router = event.params.router; const sendingChainId = event.params.args.txData.sendingChainId; const sendingAssetId = event.params.args.txData.sendingAssetId; const receivingChainId = event.params.args.txData.receivingChainId; const receivingAssetId = event.params.args.txData.receivingAssetId; const amount = event.params.args.txData.amount; // router receives liquidity back on receiver cancel if (chainId == receivingChainId) { const receivingAssetBalance = getOrCreateAssetBalance(receivingAssetId, router); const dayMetricReceiving = getOrCreateDayMetric(timestamp, receivingAssetId); // preparation for the receiving chain receivingAssetBalance.amount = receivingAssetBalance.amount.plus(amount); receivingAssetBalance.locked = receivingAssetBalance.locked.minus(amount); receivingAssetBalance.receivingCancelTxCount = receivingAssetBalance.receivingCancelTxCount.plus(BigInt.fromI32(1)); // update metrics dayMetricReceiving.cancelTxCount = dayMetricReceiving.cancelTxCount.plus(BigInt.fromI32(1)); // save receivingAssetBalance.save(); dayMetricReceiving.save(); } else if (chainId == sendingChainId) { const sendingAssetBalance = getOrCreateAssetBalance(sendingAssetId, router); sendingAssetBalance.lockedIn = sendingAssetBalance.lockedIn.minus(amount); sendingAssetBalance.sendingCancelTxCount = sendingAssetBalance.sendingCancelTxCount.plus(BigInt.fromI32(1)); // save sendingAssetBalance.save(); } } function getChainId(transactionManagerAddress: Address): BigInt { // try to get chainId from the mapping let network = dataSource.network(); let chainId: BigInt; if (network == "mainnet") { chainId = BigInt.fromI32(1); } else if (network == "ropsten") { chainId = BigInt.fromI32(3); } else if (network == "rinkeby") { chainId = BigInt.fromI32(4); } else if (network == "goerli") { chainId = BigInt.fromI32(5); } else if (network == "kovan") { chainId = BigInt.fromI32(42); } else if (network == "bsc") { chainId = BigInt.fromI32(56); } else if (network == "chapel") { chainId = BigInt.fromI32(97); } else if (network == "xdai") { chainId = BigInt.fromI32(100); } else if (network == "matic") { chainId = BigInt.fromI32(137); } else if (network == "fantom") { chainId = BigInt.fromI32(250); } else if (network == "mbase") { chainId = BigInt.fromI32(1287); } else if (network == "arbitrum-one") { chainId = BigInt.fromI32(42161); } else if (network == "fuji") { chainId = BigInt.fromI32(43113); } else if (network == "avalanche") { chainId = BigInt.fromI32(43114); } else if (network == "mumbai") { chainId = BigInt.fromI32(80001); } else if (network == "arbitrum-rinkeby") { chainId = BigInt.fromI32(421611); } else { // instantiate contract to get the chainId as a fallback chainId = TransactionManager.bind(transactionManagerAddress).getChainId(); } return chainId; } function getOrCreateAssetBalance(assetId: Bytes, router: Address): AssetBalance { let assetBalanceId = assetId.toHex() + "-" + router.toHex(); let assetBalance = AssetBalance.load(assetBalanceId); if (assetBalance == null) { assetBalance = new AssetBalance(assetBalanceId); assetBalance.assetId = assetId; assetBalance.router = router.toHex(); assetBalance.amount = new BigInt(0); assetBalance.supplied = new BigInt(0); assetBalance.locked = new BigInt(0); assetBalance.removed = new BigInt(0); assetBalance.volume = new BigInt(0); assetBalance.volumeIn = new BigInt(0); } return assetBalance; } function getOrCreateDayMetric(timestamp: BigInt, assetId: Bytes): DayMetric { let day = timestamp.toI32() / 86400; // rounded let dayStartTimestamp = day * 86400; let dayIDPerAsset = day.toString() + "-" + assetId.toHex(); let dayMetric = DayMetric.load(dayIDPerAsset); if (dayMetric === null) { dayMetric = new DayMetric(dayIDPerAsset); dayMetric.dayStartTimestamp = BigInt.fromI32(dayStartTimestamp); dayMetric.assetId = assetId.toHex(); dayMetric.volume = BigInt.fromI32(0); dayMetric.sendingTxCount = BigInt.fromI32(0); dayMetric.receivingTxCount = BigInt.fromI32(0); dayMetric.cancelTxCount = BigInt.fromI32(0); dayMetric.volumeIn = BigInt.fromI32(0); } return dayMetric; }
the_stack
import { UserDataWrapper } from "../models/userDataWrapper"; import { Org } from "../models/org"; import { Config } from "../models/config"; import { Controller } from "./controller"; import { SOURCE_TYPE, CONSTANTS, OPERATION, DATA_MEDIA_TYPE, MIGRATION_DIRECTION } from "./statics"; import { SObjectDescribe } from "../models/sobjectDescribe"; import { AppUtils } from "./appUtils"; import { ScriptObject } from "../models/scriptObject"; import { ScriptObjectField } from "../models/ScriptObjectField"; import { IAngularScope, IAppSettings, IPackageJson } from "./helper_interfaces"; import { Form } from "../models/form"; import { RESOURCES } from "./resources"; import { FieldItem } from "../models/fieldItem"; import { ObjectEditData, SelectItem } from "./helper_classes"; const path = require('path') const platformFolders = require('platform-folders'); /** * Class to hold all UI data */ export class AppUIState { controller: Controller; ///////////////////////////////////// // Common /////////////////////////// ///////////////////////////////////// constructor(controller: Controller) { this.controller = controller; // Common **************************** this.state.switchStateHandler = this.controller.switchStateHandler.bind(this.controller); this.state.openBasePathInExplorerHandler = this.controller.openBasePathInExplorerHandler.bind(this.controller); this.state.openConfigInExplorerHandler = this.controller.openConfigInExplorerHandler.bind(this.controller); // Login page ************************* this.loginPage.loginHandler = this.controller.loginHandler.bind(this.controller); this.indexPage.logOffHandler = this.controller.logOffHandler.bind(this.controller); // Register page ************************* this.registerPage.registerHandler = this.controller.registerHandler.bind(this.controller); this.homePage.refreshOrgsListHandler = this.controller.refreshOrgsListHandler.bind(this.controller); // Profile page ************************* this.profilePage.saveEmailAndPasswordHandler = this.controller.saveEmailAndPasswordHandler.bind(this.controller); this.profilePage.saveApplicationSettingsHandler = this.controller.saveApplicationSettingsHandler.bind(this.controller); this.profilePage.openChangeBasePathDialogHandler = this.controller.openChangeBasePathDialogHandler.bind(this.controller); // Home page ************************* this.homePage.goNext = this.controller.homeGoNext.bind(this.controller); this.homePage.executeForceOrgListHandler = this.controller.executeForceOrgListHandler.bind(this.controller); this.homePage.executeForceOrgDisplayHandler = this.controller.executeForceOrgDisplayHandler.bind(this.controller); this.homePage.downloadCLICommadOutputHandler = this.controller.downloadCLICommadOutputHandler.bind(this.controller); // Config page ************************* this.configPage.goNext = this.controller.configGoNext.bind(this.controller); this.configPage.addConfigClickHandler = this.controller.addConfigClickHandler.bind(this.controller); this.configPage.editConfigClickHandler = this.controller.editConfigClickHandler.bind(this.controller); this.configPage.cloneConfigClickHandler = this.controller.cloneConfigClickHandler.bind(this.controller); this.controller.$scope["uploadConfigChangeHandler"] = this.configPage.uploadConfigChangeHandler = this.controller.uploadConfigChangeHandler.bind(this.controller); this.configPage.downloadConfigClickHandler = this.controller.downloadConfigClickHandler.bind(this.controller); this.configPage.removeConfigClickHandler = this.controller.removeConfigClickHandler.bind(this.controller); this.configPage.addObjectsClickHandler = this.controller.addObjectsClickHandler.bind(this.controller); this.configPage.selectObjectClickHandler = this.controller.selectObjectClickHandler.bind(this.controller); this.configPage.switchOrgsHandler = this.controller.switchOrgsHandler.bind(this.controller); this.configPage.removeUnusedConfigFoldersHandler = this.controller.removeUnusedConfigFoldersHandler.bind(this.controller); this.configPage.updateSObjectQueryHandler = this.controller.updateSObjectQueryHandler.bind(this.controller); this.configPage.executeTestQueryHandler = this.controller.executeTestQueryHandler.bind(this.controller); this.configPage.saveConfigParameterHandler = this.controller.saveConfigParameterHandler.bind(this.controller); this.configPage.saveConfigParameterDelayedHandler = this.controller.saveConfigParameterDelayedHandler.bind(this.controller); this.configPage.polymorphicFieldChangedHandler = this.controller.polymorphicFieldChangedHandler.bind(this.controller); this.configPage.externalIdEnterModeChangeHandler = this.controller.externalIdEnterModeChangeHandler.bind(this.controller); this.configPage.upDownObjectHandler = this.controller.upDownObjectHandler.bind(this.controller); this.configPage.removeObjectHandler = this.controller.removeObjectHandler.bind(this.controller); this.configPage.saveConfigHandler = this.controller.saveConfigHandler.bind(this.controller); this.configPage.saveConfigDelayedHandler = this.controller.saveConfigDelayedHandler.bind(this.controller); this.configPage.addFieldMappingHandler = this.controller.addFieldMappingHandler.bind(this.controller); this.configPage.removeFieldMappingHandler = this.controller.removeFieldMappingHandler.bind(this.controller); this.configPage.fieldMappingChangedHandler = this.controller.fieldMappingChangedHandler.bind(this.controller); this.configPage.fieldMappingInitializeHandler = this.controller.fieldMappingInitializeHandler.bind(this.controller); this.configPage.validateConfigurationHandler = this.controller.validateConfigurationHandler.bind(this.controller); this.configPage.reconnectOrgsHandler = this.controller.reconnectOrgsHandler.bind(this.controller); this.configPage.addMockingItemHandler = this.controller.addMockingItemHandler.bind(this.controller); this.configPage.removeMockingItemHandler = this.controller.removeMockingItemHandler.bind(this.controller); // Preview page ************************* this.previewPage.generateExportJsonHandler = this.controller.generateExportJsonHandler.bind(this.controller); this.previewPage.copyCLICommandStringToClipboardHandler = this.controller.copyCLICommandStringToClipboardHandler.bind(this.controller); this.previewPage.goNext = this.controller.previewGoNext.bind(this.controller); // Execute page ************************* this.state.abortExecutionHandler = this.controller.abortExecutionHandler.bind(this.controller); }; /** * The global static settings * (available across whole application) */ private static _appSettings: IAppSettings; public static get appSettings(): IAppSettings { if (!this._appSettings) { const packageJson = AppUtils.readPackageJson(); const userJson = AppUtils.readUserJson(); AppUIState._appSettings = AppUtils.objectAssignSafeDefined({}, // Basic default app settings ************* CONSTANTS.DEFAULT_APP_SETTINGS, // Extended default app settings ************* <IAppSettings>{ db_basePath: platformFolders.getDocumentsFolder(), isDebug: process.env.DEBUG == "true", app_title: packageJson.description + ' (v' + packageJson.version + ')', version: packageJson.version, repoUrl: packageJson.repository, packageJsonUrl: packageJson.package_json }, // User settings override the defaults ********** <IAppSettings>{ db_name: userJson.db_name, db_path: userJson.db_path, db_basePath: userJson.db_basePath || platformFolders.getDocumentsFolder() }); } return this._appSettings; } /** * Make app settings accessible via $scope within the Controller ... */ get settings(): IAppSettings { return AppUIState.appSettings; } ////////////////////////////////////////////// // Pages & state //////////////////////////// ////////////////////////////////////////////// state = { // Fields ******************************** userData: <UserDataWrapper>null, scriptIsExecuting: false, newVersionMessage: <string>null, // Methods / Properties ******************************** isLoggedIn: () => this.state.userData != null, orgs: (): Org[] => this.state.isLoggedIn() ? this.state.userData.orgs : [], configs: ($new?: Array<Config>): Config[] => { if (!$new) { return this.state.isLoggedIn() ? this.state.userData.configs : []; } else { this.state.userData.configs = $new; return $new; } }, pageName: (): string => this.controller.$state["$current"].name, sourceOrg: (): Org => this.state.userData.orgs.filter(org => org.sourceType == SOURCE_TYPE.Source)[0] || new Org(), targetOrg: (): Org => this.state.userData.orgs.filter(org => org.sourceType == SOURCE_TYPE.Target)[0] || new Org(), config: (): Config => { return this.state.configs().filter(config => config.id == this.configPage.allConfigIds[0])[0] || new Config(); }, sobject: (): ScriptObject => { return this.state.config().objects.filter(object => object.name == this.configPage.currentSObjectId)[0] || new ScriptObject(); }, availableSObjects: (): SObjectDescribe[] => { let self = this; return ___getObject().filter(object => { return !CONSTANTS.NOT_SUPPORTED_OBJECTS.some(name => object.name == name); }); // ------------ Local function --------------- // function ___getObject(): SObjectDescribe[] { if (self.state.sourceOrg().isFile()) { return self.state.targetOrg().objects; } if (self.state.targetOrg().isFile()) { return self.state.sourceOrg().objects; } return AppUtils.intersect(self.state.sourceOrg().objects, self.state.targetOrg().objects, "name"); } }, orgDataSourcesAmount: (): number => { return this.state.orgs().filter(org => org.isOrg()).length; }, hasFileSource: (): boolean => { return this.state.sourceOrg().isFile() || this.state.targetOrg().isFile(); }, // Event Handlers ******************************** switchStateHandler: <Function>null, openBasePathInExplorerHandler: <Function>null, openConfigInExplorerHandler: <Function>null, setSourceTargetOrgs: () => { this.state.orgs().forEach(org => { org.sourceType = this.homePage.currentSourceOrgIds[0] == org.id ? SOURCE_TYPE.Source : this.homePage.currentTargetOrgIds[0] == org.id ? SOURCE_TYPE.Target : SOURCE_TYPE.Unknown; }); }, abortExecutionHandler: <Function>null, setNewVersionMessage: async () => { const packageJsonRemote: IPackageJson = await AppUtils.readRemoveJsonAsync(this.settings.packageJsonUrl); if (packageJsonRemote.version != this.settings.version) { this.state.newVersionMessage = RESOURCES.NewVersionAvailable.format(packageJsonRemote.version, this.settings.version, this.settings.repoUrl); } else { this.state.newVersionMessage = ""; } } }; indexPage = { // Methods / Properties ******************************** viewPlaceholderClass: () => this.state.isLoggedIn() ? "bg-main" : "", menuActiveClasses: () => { return { home: ['home', 'config', 'preview', 'execute'].indexOf(this.state.pageName()) >= 0 ? ' active ' : '', register: this.state.pageName() == 'register' ? ' active ' : '', login: this.state.pageName() == 'login' ? ' active ' : '', profile: this.state.pageName() == 'profile' ? ' active ' : '' }; }, // Event Handlers ******************************** logOffHandler: <Function>null }; loginPage = { // Fields ******************************** form: new Form(), // Event Handlers ******************************** loginHandler: <Function>null }; registerPage = { // Fields ******************************** form: new Form(), // Event Handlers ******************************** registerHandler: <Function>null }; profilePage = { // Fields ******************************** form: new Form(), settingsForm: <IAppSettings>{}, // Event Handlers ******************************** saveEmailAndPasswordHandler: <Function>null, saveApplicationSettingsHandler: <Function>null, openChangeBasePathDialogHandler: <Function>null }; homePage = { // Fields ******************************** currentSourceOrgIds: new Array<string>(), currentTargetOrgIds: new Array<string>(), cliOutput: RESOURCES.Home_ExecuteSFDXCommandDescription, cliOutputPlain: <string>null, // Methods / Properties ******************************** isValid: () => !(this.homePage.currentSourceOrgIds[0] == this.homePage.currentTargetOrgIds[0] || !this.homePage.currentSourceOrgIds[0] || !this.homePage.currentTargetOrgIds[0]), isShown: () => this.state.isLoggedIn(), // Event Handlers ******************************** refreshOrgsListHandler: <Function>null, goNext: <Function>null, executeForceOrgListHandler: <Function>null, executeForceOrgDisplayHandler: <Function>null, downloadCLICommadOutputHandler: <Function>null }; configPage = { // Fields ******************************** allConfigIds: new Array<string>(), allSObjectIds: new Array<string>(), currentSObjectId: <string>null, objectEditData: new ObjectEditData(), isComplexExternalIdEditMode: false, availableTargetSObjectNamesForFieldMapping: new Array<FieldItem>(), availableTargetSFieldsNamesForFieldMapping: new Array<FieldItem>(), selectedFieldNameForMock: "", // Methods / Properties ******************************** isValid: () => { return this.state.config().isValid(); }, isShown: () => this.state.sourceOrg().sourceType != SOURCE_TYPE.Unknown && this.state.targetOrg().sourceType != SOURCE_TYPE.Unknown, availableSObjects: (): SObjectDescribe[] => { if (!this.state.config()) return new Array<SObjectDescribe>(); return AppUtils.exclude(this.state.availableSObjects(), this.state.config().objects, "name"); }, showRemoveUnusedConfigFildersButton: (): boolean => { let folders = AppUtils.getListOfDirs(this.state.userData.basePath); let toDelete = folders.filter(folder => { if (!folder.name.startsWith('_')) { if (!this.state.configs().map(c => c.name).some(x => folder.name == x)) { return true; } } }).map(folder => folder.fullPath); return toDelete.length > 0; }, _operationList: <Array<SelectItem>>null, operationList: (): SelectItem[] => { if (!this.configPage._operationList) { this.configPage._operationList = AppUtils.listEnum(OPERATION) .filter(item => item != OPERATION[OPERATION.Unknown]) .map(item => new SelectItem({ value: item, text: item })); } return this.configPage._operationList; }, getObjectQuickInfoString: (objectIndex: number): string => { let scriptObject = this.state.config().objects[objectIndex]; return `${scriptObject.master ? RESOURCES.Config_MasterTag + ' | ' : ''}${scriptObject.operation} | ${scriptObject.externalId}${scriptObject.deleteOldData ? ' | ' + RESOURCES.Config_DeleteOldDataTag : ''}`; }, disableAddNewFieldMappingItemButton: () => { return this.state.sobject().fieldMapping.length > 0 && (!this.state.sobject().targetSobjectNameForFieldMapping || this.state.sobject().fieldMapping.some(fieldMapping => (!fieldMapping.sourceField || !fieldMapping.targetField) && !fieldMapping.targetObject)); }, // Event Handlers ******************************** goNext: <Function>null, switchOrgsHandler: <Function>null, addConfigClickHandler: <Function>null, editConfigClickHandler: <Function>null, cloneConfigClickHandler: <Function>null, uploadConfigChangeHandler: <Function>null, downloadConfigClickHandler: <Function>null, removeConfigClickHandler: <Function>null, addObjectsClickHandler: <Function>null, selectObjectClickHandler: <Function>null, addRemoveObjectFieldsHandler: ($scope: IAngularScope, $new: Array<ScriptObjectField>, $element: JQuery) => { let list1 = $new.map(field => { return { name: field.name }; }); let list2 = this.state.sobject().fields.map(field => { return { name: field.name }; }); if (!AppUtils.isEquals(list1, list2)) { this.controller.addRemoveObjectFieldsHandler($scope, $new.map(field => new ScriptObjectField(field)), $element); } }, addRemoveObjectExcludedFieldsHandler: ($scope: IAngularScope, $new: Array<FieldItem>, $element: JQuery) => { let list1 = $new.map(field => field.name); let list2 = this.state.sobject().excludedFields; if (!AppUtils.isEquals(list1, list2)) { this.controller.addRemoveObjectExcludedFieldsHandler($scope, $new, $element); } }, removeUnusedConfigFoldersHandler: <Function>null, updateSObjectQueryHandler: <Function>null, executeTestQueryHandler: <Function>null, saveConfigParameterHandler: <Function>null, saveConfigParameterDelayedHandler: <Function>null, polymorphicFieldChangedHandler: <Function>null, externalIdEnterModeChangeHandler: <Function>null, upDownObjectHandler: <Function>null, removeObjectHandler: <Function>null, saveConfigHandler: <Function>null, saveConfigDelayedHandler: <Function>null, addFieldMappingHandler: <Function>null, removeFieldMappingHandler: <Function>null, fieldMappingChangedHandler: <Function>null, fieldMappingInitializeHandler: <Function>null, validateConfigurationHandler: <Function>null, reconnectOrgsHandler: <Function>null, addMockingItemHandler: <Function>null, removeMockingItemHandler: <Function>null, updateFieldItems: () => { // availableTargetSObjectNamesForFieldMapping -------------- // this.configPage.availableTargetSObjectNamesForFieldMapping = AppUtils.uniqueArray( this.state.orgs() .filter(org => org.media == DATA_MEDIA_TYPE.Org) .reduce((acc, org) => { if (org.isDescribed) { acc = acc.concat(org.objects.map(object => object.name)); } return acc; }, [])) .sort() .map(value => new FieldItem({ name: value })); // availableTargetSFieldsNamesForFieldMapping --------------- // let targetObject = this.state.sobject().targetSobjectNameForFieldMapping; if (targetObject) { this.configPage.availableTargetSFieldsNamesForFieldMapping = AppUtils.uniqueArray( this.state.orgs() .filter(org => org.media == DATA_MEDIA_TYPE.Org) .reduce((acc, org) => { if (org.isDescribed) { let fields = org.objectsMap.get(targetObject) && org.objectsMap.get(targetObject).fields.map(field => field.name); if (fields) { acc = acc.concat(fields); } } return acc; }, [])) .sort() .map(value => new FieldItem({ name: value })); } } }; previewPage = { // Fields ******************************** selectedMigrationDirection: "", isFullExportJson: false, exportJson: "", allowShowing: false, // Methods / Properties ******************************** isValid: () => { return true; }, isShown: () => { return this.configPage.isValid() && (this.previewPage.allowShowing || this.state.scriptIsExecuting); }, migrationDirections: () => { return this.state.hasFileSource() ? CONSTANTS.MIGRATION_DIRECTIONS.filter(item => item.value != MIGRATION_DIRECTION[MIGRATION_DIRECTION.Orgs]) : CONSTANTS.MIGRATION_DIRECTIONS; }, migrationDirectionSelectorIsDisabled: (): boolean => { return this.state.hasFileSource(); }, getSelectedMigrationDirectionEnum: (): MIGRATION_DIRECTION => { return MIGRATION_DIRECTION[this.previewPage.selectedMigrationDirection] }, getCLICommandString: (): string => { if (!this.state.config().isInitialized()) { return ""; } let useFileSource = this.previewPage.getSelectedMigrationDirectionEnum() == MIGRATION_DIRECTION.File2Org; let useFileTarget = this.previewPage.getSelectedMigrationDirectionEnum() == MIGRATION_DIRECTION.Org2File; return `sfdx sfdmu:run --sourceusername ${useFileSource ? "csvfile" : this.state.sourceOrg().aliasOrName} --targetusername ${useFileTarget ? "csvfile" : this.state.targetOrg().aliasOrName} --path ${this.state.config().exportJsonFilepath} --verbose`; }, // Event Handlers ******************************** generateExportJsonHandler: <Function>null, copyCLICommandStringToClipboardHandler: <Function>null, goNext: <Function>null }; executePage = { // Fields ******************************** allowShowing: false, executeLogHtml: <string>null, // Methods / Properties ******************************** isShown: () => { return this.previewPage.isShown() && (this.executePage.allowShowing || this.state.scriptIsExecuting); }, // Event Handlers ******************************** getCLICommandString: this.previewPage.getCLICommandString, }; ///////////////////////////////////// // Other //////////////////////////// ///////////////////////////////////// get externalId(): string[] { return [this.state.sobject().externalId]; } set externalId(value: string[]) { this.state.sobject().externalId = value[0]; } }
the_stack
import BigNumber from 'bignumber.js' function setupWallet (): void { cy.createEmptyWallet(true) cy.getByTestID('bottom_tab_dex').click() cy.getByTestID('close_dex_guidelines').click() cy.sendDFItoWallet() .sendDFITokentoWallet() .sendTokenToWallet(['BTC']).wait(3000) cy.getByTestID('bottom_tab_dex').click() cy.getByTestID('pool_pair_add_dBTC-DFI').click() cy.wait(100) cy.getByTestID('token_balance_primary').contains('10') cy.getByTestID('token_balance_secondary').contains('19.9') } function setupWalletForConversion (): void { cy.createEmptyWallet(true) cy.getByTestID('bottom_tab_dex').click() cy.getByTestID('close_dex_guidelines').click() cy.sendDFItoWallet() .sendDFITokentoWallet() .sendTokenToWallet(['BTC']).wait(3000) .sendTokenToWallet(['BTC']).wait(3000) cy.getByTestID('bottom_tab_dex').click() cy.getByTestID('pool_pair_add_dBTC-DFI').click() cy.wait(100) cy.getByTestID('token_balance_primary').contains('20') cy.getByTestID('token_balance_secondary').contains('19.9') } context('Wallet - DEX - Add Liquidity', () => { before(function () { setupWallet() }) it('should update both token and build summary when click on max amount button', function () { cy.getByTestID('MAX_amount_button').first().click() cy.getByTestID('token_input_primary').should('have.value', '10.00000000') cy.getByTestID('token_input_secondary').should('have.value', '10.00000000') cy.getByTestID('a_per_b_price').contains('1.00000000') cy.getByTestID('a_per_b_price_label').contains('dBTC price per DFI') cy.getByTestID('b_per_a_price').contains('1.00000000') cy.getByTestID('b_per_a_price_label').contains('DFI price per dBTC') cy.getByTestID('share_of_pool').contains('1.00000000') cy.getByTestID('share_of_pool_suffix').contains('%') }) it('should update both token and build summary when click on half amount button', function () { cy.getByTestID('token_input_primary_clear_button').click() cy.getByTestID('50%_amount_button').first().click() cy.getByTestID('token_input_primary').should('have.value', '5.00000000') cy.getByTestID('token_input_secondary').should('have.value', '5.00000000') cy.getByTestID('a_per_b_price').contains('1.00000000') cy.getByTestID('a_per_b_price_label').contains('dBTC price per DFI') cy.getByTestID('b_per_a_price').contains('1.00000000') cy.getByTestID('b_per_a_price_label').contains('DFI price per dBTC') cy.getByTestID('share_of_pool').contains('0.50000000') cy.getByTestID('share_of_pool_suffix').contains('%') }) it('should update both token and build summary base on primary token input', function () { cy.getByTestID('token_input_primary_clear_button').click() cy.getByTestID('token_input_primary').invoke('val').should(text => expect(text).to.contain('')) cy.getByTestID('token_input_secondary').invoke('val').should(text => expect(text).to.contain('0')) cy.getByTestID('token_input_primary').type('3') cy.getByTestID('token_input_secondary').should('have.value', '3.00000000') cy.getByTestID('a_per_b_price').contains('1.00000000') cy.getByTestID('a_per_b_price_label').contains('dBTC price per DFI') cy.getByTestID('b_per_a_price').contains('1.00000000') cy.getByTestID('b_per_a_price_label').contains('DFI price per dBTC') cy.getByTestID('share_of_pool').contains('0.30000000') cy.getByTestID('share_of_pool_suffix').contains('%') }) it('should update both token and build summary base on secondary token input', function () { cy.getByTestID('token_input_secondary_clear_button').click() cy.getByTestID('token_input_secondary').type('2') cy.getByTestID('token_input_primary').should('have.value', '2.00000000') cy.getByTestID('a_per_b_price').contains('1.00000000') cy.getByTestID('a_per_b_price_label').contains('dBTC price per DFI') cy.getByTestID('b_per_a_price').contains('1.00000000') cy.getByTestID('b_per_a_price_label').contains('DFI price per dBTC') cy.getByTestID('share_of_pool').contains('0.20000000') cy.getByTestID('share_of_pool_suffix').contains('%') cy.getByTestID('button_continue_add_liq').click() }) it('should have correct confirm info', function () { cy.getByTestID('text_add_amount').contains('2.00000000') cy.getByTestID('text_add_amount_suffix_dBTC').should('exist') cy.getByTestID('text_add_amount_suffix_DFI').should('exist') cy.getByTestID('a_amount_label').contains('dBTC') cy.getByTestID('a_amount').contains('2.00000000') cy.getByTestID('b_amount_label').contains('DFI') cy.getByTestID('b_amount').contains('2.00000000') cy.getByTestID('percentage_pool').contains('0.20000000') cy.getByTestID('percentage_pool_suffix').contains('%') cy.getByTestID('button_cancel_add').click() }) }) context('Wallet - DEX - Combine Add and Confirm Liquidity Spec', () => { before(function () { setupWallet() }) it('should get disabled submit button when value is zero', function () { cy.getByTestID('token_input_primary').type('0') cy.getByTestID('button_continue_add_liq').should('have.attr', 'aria-disabled') cy.getByTestID('token_input_secondary_clear_button').click() cy.getByTestID('token_input_secondary').type('0') cy.getByTestID('button_continue_add_liq').should('have.attr', 'aria-disabled') }) it('should get disabled submit button when value is nan', function () { cy.getByTestID('token_input_primary_clear_button').click() cy.getByTestID('token_input_primary').type('test value') cy.getByTestID('button_continue_add_liq').should('have.attr', 'aria-disabled') cy.getByTestID('token_input_secondary_clear_button').click() cy.getByTestID('token_input_secondary').type('test value') cy.getByTestID('button_continue_add_liq').should('have.attr', 'aria-disabled') }) it('should get disabled submit button when value is more than input token A and token B', function () { cy.getByTestID('token_input_primary_clear_button').click() cy.getByTestID('token_input_primary').type('20.00000000') cy.getByTestID('button_continue_add_liq').should('have.attr', 'aria-disabled') cy.getByTestID('token_input_secondary_clear_button').click() cy.getByTestID('token_input_secondary').type('15.00000000') cy.getByTestID('button_continue_add_liq').should('have.attr', 'aria-disabled') }) it('should get disabled submit button when max for token A, while token B doesn\'t have enough balanceB', function () { cy.sendTokenToWallet(['BTC']).wait(3000) cy.getByTestID('MAX_amount_button').first().click() cy.getByTestID('button_continue_add_liq').should('have.attr', 'aria-disabled') }) it('should get disabled submit button when max for token B, while token A doesn\'t have enough balanceB', function () { cy.sendDFITokentoWallet().sendDFITokentoWallet().wait(3000) cy.getByTestID('MAX_amount_button').eq(1).click() cy.getByTestID('button_continue_add_liq').should('have.attr', 'aria-disabled') }) it('should get redirect to confirm page after clicking on continue', function () { cy.getByTestID('MAX_amount_button').first().click() cy.getByTestID('button_continue_add_liq').should('not.have.attr', 'disabled') cy.getByTestID('button_continue_add_liq').click() cy.url().should('include', 'DEX/ConfirmAddLiquidity') }) }) context('Wallet - DEX - Add Liquidity Confirm Txn', () => { beforeEach(function () { setupWallet() }) afterEach(function () { cy.getByTestID('dex_tabs_YOUR_POOL_PAIRS').click() cy.getByTestID('your_dBTC-DFI').contains('10.00000000') cy.getByTestID('your_dBTC').contains('9.99999999') cy.getByTestID('your_DFI').contains('9.99999999') cy.getByTestID('bottom_tab_balances').click() cy.getByTestID('balances_row_15').should('exist') cy.getByTestID('balances_row_15_symbol').contains('dBTC-DFI') // Remove added liquidity cy.getByTestID('bottom_tab_dex').click() cy.getByTestID('dex_tabs_YOUR_POOL_PAIRS').click() cy.getByTestID('pool_pair_remove_dBTC-DFI').click() cy.getByTestID('button_slider_max').click().wait(1000) cy.getByTestID('button_continue_remove_liq').click() cy.getByTestID('button_confirm_remove').click().wait(2000) cy.closeOceanInterface() }) it('should have updated confirm info', function () { cy.getByTestID('token_input_primary').type('10') cy.getByTestID('button_continue_add_liq').click() cy.getByTestID('text_add_amount').contains('10.00000000') cy.getByTestID('text_add_amount_suffix_dBTC').should('exist') cy.getByTestID('text_add_amount_suffix_DFI').should('exist') cy.getByTestID('a_amount_label').contains('dBTC') cy.getByTestID('a_amount').contains('10.00000000') cy.getByTestID('b_amount_label').contains('DFI') cy.getByTestID('b_amount').contains('10.00000000') cy.getByTestID('percentage_pool').contains('1.00000000') cy.getByTestID('percentage_pool_suffix').contains('%') cy.getByTestID('button_confirm_add').click().wait(3000) cy.closeOceanInterface() }) it('should be able to add correct liquidity when user cancel a tx and updated some inputs', function () { const oldAmount = '5.00000000' const newAmount = '10.00000000' cy.getByTestID('token_input_primary').type(oldAmount) cy.getByTestID('button_continue_add_liq').click() cy.getByTestID('text_add_amount').contains(`${oldAmount}`) cy.getByTestID('text_add_amount_suffix_dBTC').should('exist') cy.getByTestID('text_add_amount_suffix_DFI').should('exist') cy.getByTestID('a_amount_label').contains('dBTC') cy.getByTestID('a_amount').contains(oldAmount) cy.getByTestID('b_amount_label').contains('DFI') cy.getByTestID('b_amount').contains(oldAmount) cy.getByTestID('percentage_pool').contains('0.50000000') cy.getByTestID('percentage_pool_suffix').contains('%') cy.getByTestID('text_fee').should('exist') cy.getByTestID('button_confirm_add').click().wait(3000) // Check for authorization page description cy.getByTestID('txn_authorization_description') .contains(`Adding ${new BigNumber(oldAmount).toFixed(8)} dBTC - ${new BigNumber(oldAmount).toFixed(8)} DFI`) // Cancel send on authorisation page cy.getByTestID('cancel_authorization').click() cy.getByTestID('button_cancel_add').click() // Update the input amount cy.getByTestID('token_input_primary_clear_button').click() cy.getByTestID('token_input_primary').type(newAmount) cy.getByTestID('button_continue_add_liq').click() cy.getByTestID('text_add_amount').contains(`${newAmount}`) cy.getByTestID('text_add_amount_suffix_dBTC').should('exist') cy.getByTestID('text_add_amount_suffix_DFI').should('exist') cy.getByTestID('a_amount_label').contains('dBTC') cy.getByTestID('a_amount').contains(newAmount) cy.getByTestID('b_amount_label').contains('DFI') cy.getByTestID('b_amount').contains(newAmount) cy.getByTestID('percentage_pool').contains('1.00000000') cy.getByTestID('percentage_pool_suffix').contains('%') cy.getByTestID('text_fee').should('exist') cy.getByTestID('button_confirm_add').click().wait(3000) // Check for authorization page description cy.getByTestID('txn_authorization_description') .contains(`Adding ${new BigNumber(newAmount).toFixed(8)} dBTC - ${new BigNumber(newAmount).toFixed(8)} DFI`) cy.closeOceanInterface() }) }) context('Wallet - DEX - Add Liquidity with Conversion', () => { beforeEach(function () { setupWalletForConversion() }) it('should be able to display conversion info', function () { cy.getByTestID('token_input_secondary').type('11') cy.getByTestID('conversion_info_text').should('exist') cy.getByTestID('conversion_info_text').should('contain', 'Conversion will be required. Your passcode will be asked to authorize both transactions.') cy.getByTestID('text_amount_to_convert_label').contains('UTXO to be converted') cy.getByTestID('text_amount_to_convert').contains('1.00000000') cy.getByTestID('transaction_details_hint_text').contains('Authorize transaction in the next screen to convert') }) it('should trigger convert and add liquidity', function () { cy.getByTestID('token_input_primary').type('11') cy.getByTestID('button_continue_add_liq').click() cy.getByTestID('txn_authorization_description') .contains(`Converting ${new BigNumber('1').toFixed(8)} UTXO to Token`) cy.closeOceanInterface().wait(3000) cy.getByTestID('conversion_tag').should('exist') cy.getByTestID('text_add_amount').should('contain', '11.00000000') cy.getByTestID('button_confirm_add').click().wait(3000) cy.closeOceanInterface() }) })
the_stack
import { ErrorConstant } from '@remirror/core-constants'; import { assertGet, invariant, isNumber, isString, object } from '@remirror/core-helpers'; import type { AttributesProps, CommandFunction, CommandFunctionProps, FromToProps, MakeNullable, MarkType, MarkTypeProps, NodeType, NodeTypeProps, PrimitiveSelection, ProsemirrorAttributes, RangeProps, Selection, Transaction, } from '@remirror/core-types'; import { ResolvedPos } from '@remirror/core-types'; import { TextSelection } from '@remirror/pm/state'; import { findWrapping, liftTarget } from '@remirror/pm/transform'; import { getDefaultBlockNode, getMarkRange, getTextSelection, isMarkType, isNodeType, } from './core-utils'; import { getActiveNode } from './prosemirror-utils'; export interface UpdateMarkProps extends Partial<RangeProps>, Partial<AttributesProps> { /** * The text to append. * * @default ''' */ appendText?: string; /** * The type of the */ type: MarkType; } /** * Update the selection with the provided MarkType. * * @param props - see [[`UpdateMarkProps`]] for options */ export function updateMark(props: UpdateMarkProps): CommandFunction { return ({ dispatch, tr }) => { const { type, attrs = object(), appendText, range } = props; const selection = range ? TextSelection.create(tr.doc, range.from, range.to) : tr.selection; const { $from, from, to } = selection; let applicable = $from.depth === 0 ? tr.doc.type.allowsMarkType(type) : false; tr.doc.nodesBetween(from, to, (node) => { if (applicable) { return false; } if (node.inlineContent && node.type.allowsMarkType(type)) { applicable = true; return; } return; }); if (!applicable) { return false; } dispatch?.( tr.addMark(from, to, type.create(attrs)) && appendText ? tr.insertText(appendText) : tr, ); return true; }; } /** * Lift the selected block, or the closest ancestor block of the selection that * can be lifted, out of its parent node. * * Adapted from * https://github.com/ProseMirror/prosemirror-commands/blob/3126d5c625953ba590c5d3a0db7f1009f46f1571/src/commands.js#L212-L221 */ export function lift({ tr, dispatch }: Pick<CommandFunctionProps, 'tr' | 'dispatch'>): boolean { const { $from, $to } = tr.selection; const range = $from.blockRange($to); const target = range && liftTarget(range); if (!isNumber(target) || !range) { return false; } dispatch?.(tr.lift(range, target).scrollIntoView()); return true; } /** * Wrap the selection or the provided text in a node of the given type with the * given attributes. */ export function wrapIn( type: string | NodeType, attrs: ProsemirrorAttributes = {}, selection?: PrimitiveSelection, ): CommandFunction { return function (props) { const { tr, dispatch, state } = props; const nodeType = isString(type) ? assertGet(state.schema.nodes, type) : type; const { from, to } = getTextSelection(selection ?? tr.selection, tr.doc); const $from = tr.doc.resolve(from); const $to = tr.doc.resolve(to); const blockRange = $from.blockRange($to); const wrapping = blockRange && findWrapping(blockRange, nodeType, attrs); if (!wrapping || !blockRange) { return false; } dispatch?.(tr.wrap(blockRange, wrapping).scrollIntoView()); return true; }; } /** * Toggle between wrapping an inactive node with the provided node type, and * lifting it up into it's parent. * * @param nodeType - the node type to toggle * @param attrs - the attrs to use for the node */ export function toggleWrap( nodeType: string | NodeType, attrs: ProsemirrorAttributes = {}, selection?: PrimitiveSelection, ): CommandFunction { return (props) => { const { tr, state } = props; const type = isString(nodeType) ? assertGet(state.schema.nodes, nodeType) : nodeType; const activeNode = getActiveNode({ state: tr, type, attrs }); if (activeNode) { return lift(props); } return wrapIn(nodeType, attrs, selection)(props); }; } /** * Returns a command that tries to set the selected textblocks to the * given node type with the given attributes. * * @param nodeType - the name of the node or the [[`NodeType`]]. */ export function setBlockType( nodeType: string | NodeType, attrs?: ProsemirrorAttributes, selection?: PrimitiveSelection, preserveAttrs = true, ): CommandFunction { return function (props) { const { tr, dispatch, state } = props; const type = isString(nodeType) ? assertGet(state.schema.nodes, nodeType) : nodeType; const { from, to } = getTextSelection(selection ?? tr.selection, tr.doc); let applicable = false; let activeAttrs: ProsemirrorAttributes | undefined; tr.doc.nodesBetween(from, to, (node, pos) => { if (applicable) { // Exit early and don't descend. return false; } if (!node.isTextblock || node.hasMarkup(type, attrs)) { return; } if (node.type === type) { applicable = true; activeAttrs = node.attrs; return; } const $pos = tr.doc.resolve(pos); const index = $pos.index(); applicable = $pos.parent.canReplaceWith(index, index + 1, type); if (applicable) { activeAttrs = $pos.parent.attrs; } return; }); if (!applicable) { return false; } dispatch?.( tr .setBlockType(from, to, type, { ...(preserveAttrs ? activeAttrs : {}), ...attrs }) .scrollIntoView(), ); return true; }; } export interface ToggleBlockItemProps extends NodeTypeProps, Partial<AttributesProps> { /** * The type to toggle back to. Usually this is the `paragraph` node type. * * @default 'paragraph' */ toggleType?: NodeType | string; /** * Whether to preserve the attrs when toggling a block item. This means that * extra attributes that are shared between nodes will be maintained. * * @default true */ preserveAttrs?: boolean; } /** * Toggle a block between the provided type and toggleType. * * @param toggleProps - see [[`ToggleBlockItemProps`]] for available options */ export function toggleBlockItem(toggleProps: ToggleBlockItemProps): CommandFunction { return (props) => { const { tr, state } = props; const { type, attrs, preserveAttrs = true } = toggleProps; const activeNode = getActiveNode({ state: tr, type, attrs }); const toggleType = toggleProps.toggleType ?? getDefaultBlockNode(state.schema); if (activeNode) { return setBlockType(toggleType, { ...(preserveAttrs ? activeNode.node.attrs : {}), ...attrs, })(props); } const toggleNode = getActiveNode({ state: tr, type: toggleType, attrs }); return setBlockType(type, { ...(preserveAttrs ? toggleNode?.node.attrs : {}), ...attrs })( props, ); }; } export interface ReplaceTextProps extends Partial<AttributesProps> { /** * The text to append. * * @default ''' */ appendText?: string; /** * Optional text content to include. */ content?: string; /** * The content type to be inserted in place of the range / selection. */ type?: NodeType | MarkType | string; /** * Whether to keep the original selection after the replacement. */ keepSelection?: boolean; /** * @deprecated - use `selection` instead. */ range?: FromToProps; /** * The selected part of the document to replace. */ selection?: PrimitiveSelection; } /** * Taken from https://stackoverflow.com/a/4900484 * * Check that the browser is chrome. Supports passing a minimum version to check * that it is a greater than or equal to this version. */ export function isChrome(minVersion = 0): boolean { const parsedAgent = navigator.userAgent.match(/Chrom(e|ium)\/(\d+)\./); return parsedAgent ? Number.parseInt(assertGet(parsedAgent, 2), 10) >= minVersion : false; } /** * Checks the selection for the current state and updates the active transaction * to a selection that is consistent with the initial selection. * * @param state - the editor state before any updates * @param tr - the transaction which has been updated and may have impacted the * selection. */ export function preserveSelection(selection: Selection, tr: Transaction): void { // Get the previous movable part of the cursor selection. let { head, empty, anchor } = selection; // Map this movable cursor selection through each of the steps that have happened in // the transaction. for (const step of tr.steps) { const map = step.getMap(); head = map.map(head); } if (empty) { // Update the transaction with the new text selection. tr.setSelection(TextSelection.create(tr.doc, head)); } else { tr.setSelection(TextSelection.create(tr.doc, anchor, head)); } } /** * Replaces text with an optional appended string at the end. * * @param props - see [[`ReplaceTextProps`]] */ export function replaceText(props: ReplaceTextProps): CommandFunction { const { attrs = {}, appendText = '', content = '', keepSelection = false, range } = props; return ({ state, tr, dispatch }) => { const schema = state.schema; const selection = getTextSelection(props.selection ?? range ?? tr.selection, tr.doc); const index = selection.$from.index(); const { from, to, $from } = selection; const type = isString(props.type) ? schema.nodes[props.type] ?? schema.marks[props.type] : props.type; invariant(isString(props.type) ? type : true, { code: ErrorConstant.SCHEMA, message: `Schema contains no marks or nodes with name ${type}`, }); if (isNodeType(type)) { if (!$from.parent.canReplaceWith(index, index, type)) { return false; } tr.replaceWith(from, to, type.create(attrs, content ? schema.text(content) : undefined)); } else { invariant(content, { message: '`replaceText` cannot be called without content when using a mark type', }); tr.replaceWith( from, to, schema.text(content, isMarkType(type) ? [type.create(attrs)] : undefined), ); } // Only append the text if text is provided (ignore the empty string). if (appendText) { tr.insertText(appendText); } if (keepSelection) { preserveSelection(state.selection, tr); } if (dispatch) { // A workaround for a chrome bug // https://github.com/ProseMirror/prosemirror/issues/710#issuecomment-338047650 if (isChrome(60)) { document.getSelection()?.empty(); } dispatch(tr); } return true; }; } /** * Retrieve the first mark at a given resolved position `$pos` or range * * @remarks * * If multiple marks are present, the returned mark will be the mark with highest priority. * * @param $pos - the resolved ProseMirror position * @param $end - the end position to search until. When this is provided * it will search for a mark until the `$end`. The first mark within * the range will be returned. */ function getFirstMark($pos: ResolvedPos, $end?: ResolvedPos): MarkType | undefined { // Get the start position of the current node that the `$pos` value was // calculated for. const start = $pos.parent.childAfter($pos.parentOffset); // If the position provided was incorrect and no node exists for this start // position exit early. if (!start.node) { return; } const { marks, nodeSize } = start.node; if (marks[0]) { return marks[0].type; } const startPos = $pos.start() + start.offset; const endPos = startPos + nodeSize; return getFirstMark($pos.doc.resolve(endPos + 1), $end); } export interface RemoveMarkProps extends MakeNullable<MarkTypeProps, 'type'> { /** * Whether to expand empty selections to the current mark range. * * @default true */ expand?: boolean; /** * @deprecated use `selection` property instead. */ range?: FromToProps; /** * The selection to apply to the command. */ selection?: PrimitiveSelection; } /** * Removes a mark from the current selection or provided range. * * @param props - see [[`RemoveMarkProps`]] for options */ export function removeMark(props: RemoveMarkProps): CommandFunction { return ({ dispatch, tr, state }) => { const { type, expand = true, range } = props; const selection = getTextSelection(props.selection ?? range ?? tr.selection, tr.doc); let { from, to, $from, $to } = selection; const markType = isString(type) ? state.schema.marks[type] : type; if (markType !== null) { invariant(markType, { code: ErrorConstant.SCHEMA, message: `Mark type: ${type} does not exist on the current schema.`, }); } // If no mark type was supplied, get the first mark present on this node to determine a mark range const rangeMark = markType ?? getFirstMark($from); if (!rangeMark) { return false; } const markRange = getMarkRange($from, rangeMark, $to); if (expand && markRange) { // Expand the from position to the mark range (if it is smaller) - keep bound within doc from = Math.max(0, Math.min(from, markRange.from)); // Expand the to position to the mark range (if it is larger) - keep bound within doc to = Math.min(Math.max(to, markRange.to), tr.doc.nodeSize - 2); } dispatch?.( tr.removeMark(from, isNumber(to) ? to : from, isMarkType(markType) ? markType : undefined), ); return true; }; }
the_stack
export type Direction = 'fwd' | 'back'; type Callback = (err?: Error, result?: any) => void; export interface PinDefinitionObject { /** * Pin number of the PWM output */ PWM: number; /** * Pin number of the first coil output */ IN1: number; /** * Pin number of the second coil output */ IN2: number; } export type PinDefinition = PinDefinitionObject | number[]; export interface DCOptions { /** * PWM Interface Object */ pwm: object; /** * Pin definition for the motor */ pins: PinDefinition; speed?: number | undefined; frequency?: number | undefined; } /** * DC Controller Object */ export interface DC { /** * Initialize the DC controller instance. * Synchronous overload. */ init(): this; /** * Initialize the DC controller instance. * Asynchronous overload. * * @param cb Node style callback for asynch initialization */ init(cb: Callback): void; /** * Starts the motor in the desired direction. * * @param dir Direction of movement. * @param cb Node style callback. Gets called with cb(err, result) after completion. */ run(dir: Direction, cb: Callback): void; /** * Starts the motor in the desired direction. * * @param dir Direction of movement. */ runSync(dir: Direction): void; /** * Stops the motor. * Doesn't actually brake the motor, just stops applying voltage to it. * * @param cb Node style callback. Gets called with cb(err, result) after completion. */ stop(cb: Callback): void; /** * Stops the motor. * Doesn't actually brake the motor, just stops applying voltage to it. */ stopSync(): void; /** * Sets DC motor speed. * The speed can be set as a percentage, from 0% to 100%. To change the actual top speed, * the actual voltage supplied to the motor needs to be controlled by hardware (get a higher * voltage source). * * @param speed Relative speed. 0% to 100%. * @param cb Node style callback. Gets called with cb(err, result) after completion. */ setSpeed(speed: number, cb: Callback): void; /** * Sets DC motor speed. * The speed can be set as a percentage, from 0% to 100%. To change the actual top speed, * the actual voltage supplied to the motor needs to be controlled by hardware (get a higher * voltage source). * * @param speed Relative speed. 0% to 100%. */ setSpeedSync(speed: number): void; /** * Sets the PWM frequency for the DC motor. * This setting affects the frequency at which the PWM chip will work to command the DC motor. * * @param freq PWM Frequency in Hz. * @param cb Node style callback. Gets called with cb(err, result) after completion. */ setFrequency(freq: number, cb: Callback): void; /** * Sets the PWM frequency for the DC motor. * This setting affects the frequency at which the PWM chip will work to command the DC motor. * * @param freq PWM Frequency in Hz. */ setFrequencySync(freq: number): void; } /** * Servo controller initialization options */ export interface ServoOptions { /** * PWM Interface Object */ pwm: object; /** * Servo controller pin. Which pin (0 to 15) is the servo connected to? */ pin: number; /** * Duration in ms of pulse at position 0 */ min?: number | undefined; /** * Duration in ms of pulse at position 100 */ max?: number | undefined; /** * PWM Controller frequency for the servo */ freq?: number | undefined; } /** * Servo Controller Object */ export interface Servo { /** * Move Servo to desired position. * * @param pos Relative position (0% to 100%). */ moveTo(pos: number): void; /** * Calibrate the limits for the servolib * * @param freq The update freq in Hz * @param min The min. pulse in ms * @param max The max. pulse in ms */ calibrate(freq: number, min: number, max: number): void; } /** * Stepper controller initialization options */ export interface StepperOptions { /** * PWM Interface Object */ pwm: object; /** * Pin definition for the motor */ pins: { /** * Pin definition for winding 1 of the stepper */ W1: PinDefinition; /** * Pin definition for winding 2 of the stepper */ W2: PinDefinition; }; /** * Steps per revolution of the stepper motor */ steps?: number | undefined; /** * number of microsteps per step */ microsteps?: 8 | 16 | undefined; /** * PWM Controller frequency for the stepper */ frequency?: number | undefined; /** * Stepping style */ style?: 'single' | 'double' | 'interleaved' | 'microstep' | undefined; current?: number | undefined; /** * Pulses per second */ pps?: number | undefined; /** * Revolutions per minute */ rpm?: number | undefined; /** * Steps per second */ sps?: number | undefined; } export interface StepResult { /** * Performed steps */ steps: number; /** * Direction of steps performed */ dir: Direction; /** * Time in ms taken to perform the steps */ duration: number; /** * Number of steps retried */ retried: number; } export interface StepSyncResult { /** * Performed steps */ steps: number; /** * Direction of steps performed */ dir: Direction; /** * Time in ms taken to perform the steps */ duration: number; } /** * Stepper motor speed for step(). */ export interface StepperSpeed { /** * Speed in steps per second */ sps?: number | undefined; /** * Speed in pulses per second (pulses can be steps, microsteps, etc) */ pps?: number | undefined; /** * Speed in revolutions per minute */ rpm?: number | undefined; } /** * Stepper motor controller */ export interface Stepper { readonly options: StepperOptions; /** * Initialize the Stepeper controller instance. * Synchronous overload. * * @returns Returns init'd Stepper controller object (self) */ init(): this; /** * Initialize the Stepeper controller instance. * Synchronous overload. * * @param cb Node style callback for asynch initialization */ init(cb: (err: null, self: Stepper) => void): void; /** * Perform arbitrary number of steps asynchronously. * Configuration as stepping style, speed, etc should have been set previously. * * @param dir Direction of movement * @param steps Number of steps. * @param cb Node style callback. cb(err, result). */ step( dir: Direction, steps: number, cb: (err?: Error, result?: StepResult) => void ): void; /** * Perform arbitrary number of steps synchronously. * Configuration as stepping style, speed, etc should have been set previously. * * @param dir Direction of movement * @param steps Number of steps. * @returns The result of the action. */ stepSync(dir: Direction, steps: number): StepSyncResult; /** * Perform one step asynchronously. * Configuration as stepping style, speed, etc should have been set previously. * * @param dir Direction of movement * @param cb Node style callback. cb(err, result). */ oneStep(dir: Direction, cb: (err?: Error, result?: any) => void): void; /** * Perform one step synchronously. * Configuration as stepping style, speed, etc should have been set previously. * * @param dir Direction of movement */ oneStepSync(dir: Direction): void; /** * Release the stepper motor asynchronously. * * Stops applying current to the motor coils. * * @param cb Node style callback */ release(cb: (err?: Error, result?: any) => void): void; /** * Release the stepper motor synchronously. * Stops applying current to the motor coils. */ releaseSync(): void; /** * Set the current rate at which to supply the steps. * Provide a number from 0 to 1 and the current will be reduced proportionally * * @param current Current rate, from 0 to 1. */ setCurrent(current: number): void; /** * Set stepping style. * * @param style Stepping style. */ setStyle(style: 'single' | 'double' | 'interleaved' | 'microstep'): void; /** * Set PWM Controller working frequency asynchronously. * * @param freq PWM frequency. * @param cb Node style callback. cb(err, result). */ setFrequency(freq: number, cb: (err?: Error, result?: any) => void): void; /** * Set PWM Controller working frequency synchronously. * * @param freq PWM frequency. */ setFrequencySync(freq: number): void; /** * Set desired number of microsteps per step. * (Used for microstepping) * * @param ms Microsteps per step */ setMicrosteps(ms: 8 | 16): void; /** * Set number of steps per revolution for motor. * * @param steps Number of steps per revolution for stepper motor. */ setSteps(steps: number): void; /** * Set motor speed for step(). */ setSpeed(speed: StepperSpeed): void; } export interface MotorPins { readonly PWM: number; readonly IN2: number; readonly IN1: number; } /** * motorHat controller * * Needs to be initialized with init(). */ export interface MotorHat { readonly pins: { M1: MotorPins; M2: MotorPins; M3: MotorPins; M4: MotorPins; }; /** * Array of initialized Servo controllers */ readonly servos: ReadonlyArray<Servo>; /** * Array of initialized Stepper controllers */ readonly steppers: ReadonlyArray<Stepper>; /** * Array of initialized DC controllers */ readonly dcs: ReadonlyArray<DC>; /** * Creates a servo motor controller. * Pass in an options object to generate an uninitialized ServoLib object. */ servo(opts: ServoOptions): Servo; /** * Creates a stepper motor controller. * Pass in an options object to generate an uninitialized StepperLib object. */ stepper(opts: StepperOptions): Stepper; /** * Creates a new DC motor controller * Pass in an options object to generate an uninitialized DCLib object */ dc(opts: DCOptions): DC; /** * Initialize the motorHat library instance. * Synchronous overload. * * Instantiates the individual Motor/Servo/Stepper controllers and initializes them. * * @returns Returns initialized motorHat object (self) */ init(): MotorHat; /** * Initialize the motorHat library instance. * Asynchronous overload. * * Instantiates the individual Motor/Servo/Stepper controllers and initializes them. * Returns initialized motorHat object (self) in second parameter to callback if callback * provided, to enable chaining. * * @param cb Node style callback for asynch initialization */ init(cb: Callback): void; } export type Motor = 'M1' | 'M2' | 'M3' | 'M4'; export interface MotorHatOptions { /** * i2c address of the PWM chip on the MotorHat. * * * 0x6F for knockoff HATs. * * * 0x60 for official AdaFruit HATs?? */ address?: number | undefined; /** * i2c driver devfile number. Varies by RaspBerry version. * Should be automatically detected. */ busnum?: number | undefined; /** * Definition of the stepper motors connected to the HAT. * At most 2 steppers, each motor is represented by either an object of the form * { W1: winding, W2: winding }. Each winding should be one of following: 'M1', 'M2', 'M3', * 'M4' depending on the port the stepper is connected to. Correct example: { W1: 'M3', W2: 'M1' } */ steppers?: ReadonlyArray<{ W1: Motor; W2: Motor }> | undefined; /** * Definition of the DC motors connected to the HAT. * At most 4 DCs, each should be one of following: 'M1', 'M2', 'M3', 'M4' depending on * port the motor is connected to. */ dcs?: ReadonlyArray<Motor> | undefined; /** * Definition of the servos connected to the HAT. * List of the channels that have servos connected to them. 0 to 15. */ servos?: ReadonlyArray<number> | undefined; } /** * Creates a new MotorHat controller * * Pass in an options object to generate an uninitialized MotorHat object. */ declare function motorhat(options: MotorHatOptions): MotorHat; export default motorhat;
the_stack
import {ClipMode} from "../../scripts/clipperUI/clipMode"; import { MainController, MainControllerClass, MainControllerProps, PanelType } from "../../scripts/clipperUI/mainController"; import {Status} from "../../scripts/clipperUI/status"; import {SmartValue} from "../../scripts/communicator/smartValue"; import {Constants} from "../../scripts/constants"; import {Assert} from "../assert"; import {MithrilUtils} from "../mithrilUtils"; import {MockProps} from "../mockProps"; import {TestModule} from "../testModule"; declare function require(name: string); module TestConstants { export module Ids { // Dynamically generated, hence not in constants module export var fullPageButton = "fullPageButton"; export var regionButton = "regionButton"; export var augmentationButton = "augmentationButton"; export var sectionLocationContainer = "sectionLocationContainer"; } } // Currently we set a 100ms delay before the initial render, which breaks our tests MainControllerClass.prototype.getInitialState = function () { return { currentPanel: this.getPanelTypeToShow() }; }; export class MainControllerTests extends TestModule { private mockMainControllerProps: MainControllerProps; private defaultComponent; protected module() { return "mainController"; } protected beforeEach() { this.mockMainControllerProps = MockProps.getMockMainControllerProps(); this.defaultComponent = <MainController clipperState={this.mockMainControllerProps.clipperState} onSignInInvoked={this.mockMainControllerProps.onSignInInvoked} onSignOutInvoked={this.mockMainControllerProps.onSignOutInvoked} updateFrameHeight={this.mockMainControllerProps.updateFrameHeight} onStartClip={this.mockMainControllerProps.onStartClip}/>; } protected tests() { test("On the sign in panel, the tab order is correct", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = PanelType.SignInNeeded; }); Assert.tabOrderIsIncremental([Constants.Ids.signInButtonMsa, Constants.Ids.signInButtonOrgId, Constants.Ids.closeButton]); }); test("On the clip options panel, the tab order is correct", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = PanelType.ClipOptions; }); Assert.tabOrderIsIncremental([Constants.Ids.clipButton, Constants.Ids.feedbackButton, Constants.Ids.currentUserControl, Constants.Ids.closeButton]); }); test("On the pdf clip options panel, tab order should flow linearly between pdf options with the page range radio button appearing only when selected", () => { this.mockMainControllerProps.clipperState.currentMode.set(ClipMode.Pdf); let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = PanelType.ClipOptions; document.getElementById(Constants.Ids.radioAllPagesLabel).click(); }); Assert.tabOrderIsIncremental([Constants.Ids.clipButton, Constants.Ids.radioAllPagesLabel, TestConstants.Ids.sectionLocationContainer, Constants.Ids.feedbackButton, Constants.Ids.currentUserControl, Constants.Ids.closeButton]); MithrilUtils.simulateAction(() => { document.getElementById(Constants.Ids.radioPageRangeLabel).click(); }); Assert.tabOrderIsIncremental([Constants.Ids.clipButton, Constants.Ids.radioPageRangeLabel, TestConstants.Ids.sectionLocationContainer, Constants.Ids.feedbackButton, Constants.Ids.currentUserControl, Constants.Ids.closeButton]); }); test("On the pdf clip options panel, after clicking 'More' the tab order is correct", () => { this.mockMainControllerProps.clipperState.currentMode.set(ClipMode.Pdf); let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = PanelType.ClipOptions; }); MithrilUtils.simulateAction(() => { document.getElementById(Constants.Ids.moreClipOptions).click(); }); Assert.tabOrderIsIncremental([Constants.Ids.clipButton, Constants.Ids.radioAllPagesLabel, Constants.Ids.checkboxToDistributePages, Constants.Ids.checkboxToAttachPdf, Constants.Ids.feedbackButton, Constants.Ids.currentUserControl, Constants.Ids.closeButton]); MithrilUtils.simulateAction(() => { document.getElementById(Constants.Ids.radioPageRangeLabel).click(); }); Assert.tabOrderIsIncremental([Constants.Ids.clipButton, Constants.Ids.radioPageRangeLabel, Constants.Ids.checkboxToDistributePages, Constants.Ids.checkboxToAttachPdf, Constants.Ids.feedbackButton, Constants.Ids.currentUserControl, Constants.Ids.closeButton]); }); test("On the region instructions panel, the tab order is correct", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = PanelType.RegionInstructions; }); Assert.tabOrderIsIncremental([Constants.Ids.regionClipCancelButton, Constants.Ids.closeButton]); }); test("On the clip success panel, the tab order is correct", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = PanelType.ClippingSuccess; }); Assert.tabOrderIsIncremental([Constants.Ids.launchOneNoteButton, Constants.Ids.closeButton]); }); test("On the clip failure panel, the tab order is correct", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.props.clipperState.oneNoteApiResult.data = this.getMockRequestError(); controllerInstance.state.currentPanel = PanelType.ClippingFailure; }); Assert.tabOrderIsIncremental([Constants.Ids.currentUserControl, Constants.Ids.closeButton]); let dialogButtonContainers = document.getElementsByClassName("dialogButton"); const dialogButtons = []; for (let i = 0; i < dialogButtonContainers.length; i++) { const dialogButtonContainer = dialogButtonContainers[i] as HTMLElement; dialogButtons.push(dialogButtonContainer.firstChild); } Assert.equalTabIndexes(dialogButtons); }); test("On the clip failure panel, the right message is displayed for a particular API error code", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.props.clipperState.oneNoteApiResult.data = this.getMockRequestError(); controllerInstance.state.currentPanel = PanelType.ClippingFailure; }); let stringsJson = require("../../strings.json"); strictEqual(document.getElementById(Constants.Ids.dialogMessage).innerText, stringsJson["WebClipper.Error.PasswordProtected"], "The correct message is displayed for the given status code"); }); test("If the close button is clicked, the uiExpanded prop should be set to false, and getPanelTypeToShow() should return the None panel", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = PanelType.ClipOptions; }); MithrilUtils.simulateAction(() => { document.getElementById(Constants.Ids.closeButton).click(); }); ok(!controllerInstance.state.uiExpanded, "If the close button is clicked, the uiExpanded prop should be false"); strictEqual(controllerInstance.getPanelTypeToShow(), PanelType.None, "If the close button is clicked, getPanelTypeToShow() should return the None panel"); }); test("If the uiExpanded prop is set to false, getPanelTypeToShow() should return the None panel", () => { let props = MockProps.getMockMainControllerProps(); props.clipperState.uiExpanded = false; let controllerInstance = MithrilUtils.mountToFixture( <MainController clipperState={props.clipperState} onSignInInvoked={this.mockMainControllerProps.onSignInInvoked} onSignOutInvoked={this.mockMainControllerProps.onSignOutInvoked} updateFrameHeight={this.mockMainControllerProps.updateFrameHeight} onStartClip={this.mockMainControllerProps.onStartClip}/>); strictEqual(controllerInstance.getPanelTypeToShow(), PanelType.None, "If the clipper state is set to not show the UI, getPanelTypeToShow() should return the None panel"); }); test("If loc strings have not been fetched, the Loading panel should be displayed", () => { let props = MockProps.getMockMainControllerProps(); props.clipperState.fetchLocStringStatus = Status.InProgress; let controllerInstance = MithrilUtils.mountToFixture( <MainController clipperState={props.clipperState} onSignInInvoked={this.mockMainControllerProps.onSignInInvoked} onSignOutInvoked={this.mockMainControllerProps.onSignOutInvoked} updateFrameHeight={this.mockMainControllerProps.updateFrameHeight} onStartClip={this.mockMainControllerProps.onStartClip}/>); ok(document.getElementById(Constants.Ids.clipperLoadingContainer), "The Loading panel should be shown in the UI"); strictEqual(controllerInstance.getPanelTypeToShow(), PanelType.Loading, "The Loading panel should be returned by getPanelTypeToShow()"); }); test("If user info is being fetched, the Loading panel should be displayed", () => { let props = MockProps.getMockMainControllerProps(); props.clipperState.userResult.status = Status.InProgress; let controllerInstance = MithrilUtils.mountToFixture( <MainController clipperState={props.clipperState} onSignInInvoked={this.mockMainControllerProps.onSignInInvoked} onSignOutInvoked={this.mockMainControllerProps.onSignOutInvoked} updateFrameHeight={this.mockMainControllerProps.updateFrameHeight} onStartClip={this.mockMainControllerProps.onStartClip}/>); ok(document.getElementById(Constants.Ids.clipperLoadingContainer), "The Loading panel should be shown in the UI"); strictEqual(controllerInstance.getPanelTypeToShow(), PanelType.Loading, "The Loading panel should be returned by getPanelTypeToShow()"); }); test("If invoke options is being fetched, the Loading panel should be displayed", () => { let props = MockProps.getMockMainControllerProps(); props.clipperState.invokeOptions = undefined; let controllerInstance = MithrilUtils.mountToFixture( <MainController clipperState={props.clipperState} onSignInInvoked={this.mockMainControllerProps.onSignInInvoked} onSignOutInvoked={this.mockMainControllerProps.onSignOutInvoked} updateFrameHeight={this.mockMainControllerProps.updateFrameHeight} onStartClip={this.mockMainControllerProps.onStartClip}/>); ok(document.getElementById(Constants.Ids.clipperLoadingContainer), "The Loading panel should be shown in the UI"); strictEqual(controllerInstance.getPanelTypeToShow(), PanelType.Loading, "The Loading panel should be returned by getPanelTypeToShow()"); }); test("If loc strings and user info have been fetched, getPanelTypeToShow() should not return the Loading panel", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); notStrictEqual(controllerInstance.getPanelTypeToShow(), PanelType.Loading, "The Loading panel should be not shown when the loc strings and user info have been fetched"); }); test("If the user's info is not available, the SignInNeeded panel should be displayed", () => { let props = MockProps.getMockMainControllerProps(); props.clipperState.userResult = {status: Status.Failed}; let controllerInstance = MithrilUtils.mountToFixture( <MainController clipperState={props.clipperState} onSignInInvoked={this.mockMainControllerProps.onSignInInvoked} onSignOutInvoked={this.mockMainControllerProps.onSignOutInvoked} updateFrameHeight={this.mockMainControllerProps.updateFrameHeight} onStartClip={this.mockMainControllerProps.onStartClip}/>); ok(document.getElementById(Constants.Ids.signInContainer), "The SignInNeeded panel should be shown in the UI"); strictEqual(controllerInstance.getPanelTypeToShow(), PanelType.SignInNeeded, "The SignInNeeded panel should be returned by getPanelTypeToShow()"); }); test("If the region mode is selected and region selection is progress, the Loading panel should be displayed", () => { let props = MockProps.getMockMainControllerProps(); props.clipperState.currentMode = new SmartValue<ClipMode>(ClipMode.Region); props.clipperState.regionResult.status = Status.InProgress; let controllerInstance = MithrilUtils.mountToFixture( <MainController clipperState={props.clipperState} onSignInInvoked={this.mockMainControllerProps.onSignInInvoked} onSignOutInvoked={this.mockMainControllerProps.onSignOutInvoked} updateFrameHeight={this.mockMainControllerProps.updateFrameHeight} onStartClip={this.mockMainControllerProps.onStartClip}/>); ok(document.getElementById(Constants.Ids.clipperLoadingContainer), "The Loading panel should be shown in the UI"); strictEqual(controllerInstance.getPanelTypeToShow(), PanelType.Loading, "The Loading panel should be returned by getPanelTypeToShow()"); }); test("If the region mode is selected and region selection has not started, the RegionInstructions panel should be displayed", () => { let props = MockProps.getMockMainControllerProps(); props.clipperState.currentMode = new SmartValue<ClipMode>(ClipMode.Region); props.clipperState.regionResult.status = Status.NotStarted; let controllerInstance = MithrilUtils.mountToFixture( <MainController clipperState={props.clipperState} onSignInInvoked={this.mockMainControllerProps.onSignInInvoked} onSignOutInvoked={this.mockMainControllerProps.onSignOutInvoked} updateFrameHeight={this.mockMainControllerProps.updateFrameHeight} onStartClip={this.mockMainControllerProps.onStartClip}/>); ok(document.getElementById(Constants.Ids.regionInstructionsContainer), "The RegionInstructions panel should be shown in the UI"); strictEqual(controllerInstance.getPanelTypeToShow(), PanelType.RegionInstructions, "The RegionInstructions panel should be returned by getPanelTypeToShow()"); }); test("If currently clipping to OneNote, the ClippingToApi panel should be displayed", () => { let props = MockProps.getMockMainControllerProps(); props.clipperState.oneNoteApiResult.status = Status.InProgress; let controllerInstance = MithrilUtils.mountToFixture( <MainController clipperState={props.clipperState} onSignInInvoked={this.mockMainControllerProps.onSignInInvoked} onSignOutInvoked={this.mockMainControllerProps.onSignOutInvoked} updateFrameHeight={this.mockMainControllerProps.updateFrameHeight} onStartClip={this.mockMainControllerProps.onStartClip}/>); ok(document.getElementById(Constants.Ids.clipperApiProgressContainer), "The ClippingToApi panel should be shown in the UI"); strictEqual(controllerInstance.getPanelTypeToShow(), PanelType.ClippingToApi, "The ClippingToApi panel should be returned by getPanelTypeToShow()"); }); test("If clipping to OneNote failed, the dialog panel should be displayed", () => { let props = MockProps.getMockMainControllerProps(); props.clipperState.oneNoteApiResult.data = this.getMockRequestError(); props.clipperState.oneNoteApiResult.status = Status.Failed; let controllerInstance = MithrilUtils.mountToFixture( <MainController clipperState={props.clipperState} onSignInInvoked={this.mockMainControllerProps.onSignInInvoked} onSignOutInvoked={this.mockMainControllerProps.onSignOutInvoked} updateFrameHeight={this.mockMainControllerProps.updateFrameHeight} onStartClip={this.mockMainControllerProps.onStartClip}/>); ok(document.getElementById(Constants.Ids.dialogMessageContainer), "The ClippingFailure panel should be shown in the UI in the form of the dialog panel"); strictEqual(controllerInstance.getPanelTypeToShow(), PanelType.ClippingFailure, "The ClippingFailure panel should be returned by getPanelTypeToShow()"); }); test("If clipping to OneNote succeeded, the ClippingSuccess panel should be displayed", () => { let props = MockProps.getMockMainControllerProps(); props.clipperState.oneNoteApiResult.status = Status.Succeeded; let controllerInstance = MithrilUtils.mountToFixture( <MainController clipperState={props.clipperState} onSignInInvoked={this.mockMainControllerProps.onSignInInvoked} onSignOutInvoked={this.mockMainControllerProps.onSignOutInvoked} updateFrameHeight={this.mockMainControllerProps.updateFrameHeight} onStartClip={this.mockMainControllerProps.onStartClip}/>); ok(document.getElementById(Constants.Ids.clipperSuccessContainer), "The ClippingSuccess panel should be shown in the UI"); strictEqual(controllerInstance.getPanelTypeToShow(), PanelType.ClippingSuccess, "The ClippingSuccess panel should be returned by getPanelTypeToShow()"); }); test("The footer should not be rendered when the Loading panel is shown", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = PanelType.Loading; }); ok(!document.getElementById(Constants.Ids.clipperFooterContainer), "The footer container should not render when the clipper is loading"); }); test("The footer should be rendered when the SignIn panel is shown", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = PanelType.SignInNeeded; }); ok(document.getElementById(Constants.Ids.clipperFooterContainer), "The footer container should not render when the clipper is showing the sign in panel"); }); test("The footer should be rendered when the ClipOptions panel is shown", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = PanelType.ClipOptions; }); ok(document.getElementById(Constants.Ids.clipperFooterContainer), "The footer container should render when the clipper is showing the clip options panel"); }); test("The footer should not be rendered when the RegionInstructions panel is shown", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = PanelType.RegionInstructions; }); ok(!document.getElementById(Constants.Ids.clipperFooterContainer), "The footer container should not render when the clipper is showing the region instructions panel"); }); test("The footer should not be rendered when the ClippingToApi panel is shown", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = PanelType.ClippingToApi; }); ok(!document.getElementById(Constants.Ids.clipperFooterContainer), "The footer container should not render when the clipper is clipping to OneNote API"); }); test("The footer should be rendered when the ClippingFailure panel is shown", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.props.clipperState.oneNoteApiResult.data = this.getMockRequestError(); controllerInstance.state.currentPanel = PanelType.ClippingFailure; }); ok(document.getElementById(Constants.Ids.clipperFooterContainer), "The footer container should render when the clipper is showing the clip failure panel"); }); test("The footer should be not be rendered when the ClippingSuccess panel is shown", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = PanelType.ClippingSuccess; }); ok(!document.getElementById(Constants.Ids.clipperFooterContainer), "The footer container should not be rendered when the clipper is showing the clip success panel"); }); test("The close button should not be rendered when the ClippingToApi panel is shown", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = PanelType.ClippingToApi; }); ok(!document.getElementById(Constants.Ids.closeButton), "The close button should not render when the clipper is clipping to OneNote API"); }); test("The close button should be rendered when the panel shown is not ClippingToApi", () => { let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); let panels = [ PanelType.Loading, PanelType.SignInNeeded, PanelType.ClipOptions, PanelType.RegionInstructions, PanelType.ClippingFailure, PanelType.ClippingSuccess ]; // We have to write it this (ugly) way as the sensible way is only supported by ES6, which we're not using for (let i = 0; i < panels.length; i++) { let panel = panels[i]; MithrilUtils.simulateAction(() => { controllerInstance.state.currentPanel = panel; }); ok(document.getElementById(Constants.Ids.closeButton), "The close button should render when the clipper is not clipping to OneNote API"); } }); } private getMockRequestError(): OneNoteApi.RequestError { return { error: "Unexpected response status" as {}, statusCode: 403, response: '{"error":{"code":"10004","message":"Unable to create a page in this section because it is password protected.","@api.url":"http://aka.ms/onenote-errors#C10004"}}' } as OneNoteApi.RequestError; } } (new MainControllerTests()).runTests();
the_stack
import { Component, ViewChild } from '@angular/core'; import { IgxBottomNavComponent } from '../tabs/bottom-nav/public_api'; @Component({ template: ` <div #wrapperDiv> <igx-bottom-nav> <igx-bottom-nav-item> <igx-bottom-nav-header> <igx-icon igxTabHeaderIcon>library_music</igx-icon> <span igxTabHeaderLabel>Tab 1</span> </igx-bottom-nav-header> <igx-bottom-nav-content> <h1>Tab 1 Content</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </igx-bottom-nav-content> </igx-bottom-nav-item> <igx-bottom-nav-item> <igx-bottom-nav-header> <igx-icon igxTabHeaderIcon>video_library</igx-icon> <span igxTabHeaderLabel>Tab 2</span> </igx-bottom-nav-header> <igx-bottom-nav-content> <h1>Tab 2 Content</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </igx-bottom-nav-content> </igx-bottom-nav-item> <igx-bottom-nav-item> <igx-bottom-nav-header> <igx-icon igxTabHeaderIcon>library_books</igx-icon> <span igxTabHeaderLabel>Tab 3</span> </igx-bottom-nav-header> <igx-bottom-nav-content> <h1>Tab 3 Content</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vitae malesuada odio. Praesent ante lectus, porta a eleifend vel, sodales eu nisl. Vivamus sit amet purus eu lectus cursus rhoncus quis non ex. Cras ac nulla sed arcu finibus volutpat. Vivamus risus ipsum, pharetra a augue nec, euismod fringilla odio. Integer id velit rutrum, accumsan ante a, semper nunc. Phasellus ultrices tincidunt imperdiet. Nullam vulputate mauris diam. Nullam elementum, libero vel varius fermentum, lorem ex bibendum nulla, pretium lacinia erat nibh vel massa. In hendrerit, sapien ac mollis iaculis, dolor tellus malesuada sem, a accumsan lectus nisl facilisis leo. Curabitur consequat sit amet nulla at consequat. Duis volutpat tristique luctus. </p> </igx-bottom-nav-content> </igx-bottom-nav-item> </igx-bottom-nav> </div>` }) export class TabBarTestComponent { @ViewChild(IgxBottomNavComponent, { static: true }) public bottomNav: IgxBottomNavComponent; @ViewChild('wrapperDiv', { static: true }) public wrapperDiv: any; } @Component({ template: ` <div #wrapperDiv> <igx-bottom-nav alignment="bottom"> <igx-bottom-nav-item> <igx-bottom-nav-header> <igx-icon igxTabHeaderIcon>library_music</igx-icon> <span igxTabHeaderLabel>Tab 1</span> </igx-bottom-nav-header> <igx-bottom-nav-content> <h1>Tab 1 Content</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </igx-bottom-nav-content> </igx-bottom-nav-item> <igx-bottom-nav-item> <igx-bottom-nav-header> <igx-icon igxTabHeaderIcon>video_library</igx-icon> <span igxTabHeaderLabel>Tab 2</span> </igx-bottom-nav-header> <igx-bottom-nav-content> <h1>Tab 2 Content</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </igx-bottom-nav-content> </igx-bottom-nav-item> <igx-bottom-nav-item> <igx-bottom-nav-header> <igx-icon igxTabHeaderIcon>library_books</igx-icon> <span igxTabHeaderLabel>Tab 3</span> </igx-bottom-nav-header> <igx-bottom-nav-content> <h1>Tab 3 Content</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vitae malesuada odio. Praesent ante lectus, porta a eleifend vel, sodales eu nisl. Vivamus sit amet purus eu lectus cursus rhoncus quis non ex. Cras ac nulla sed arcu finibus volutpat. Vivamus risus ipsum, pharetra a augue nec, euismod fringilla odio. Integer id velit rutrum, accumsan ante a, semper nunc. Phasellus ultrices tincidunt imperdiet. Nullam vulputate mauris diam. Nullam elementum, libero vel varius fermentum, lorem ex bibendum nulla, pretium lacinia erat nibh vel massa. In hendrerit, sapien ac mollis iaculis, dolor tellus malesuada sem, a accumsan lectus nisl facilisis leo. Curabitur consequat sit amet nulla at consequat. Duis volutpat tristique luctus. </p> </igx-bottom-nav-content> </igx-bottom-nav-item> </igx-bottom-nav> </div>` }) export class BottomTabBarTestComponent { @ViewChild(IgxBottomNavComponent, { static: true }) public bottomNav: IgxBottomNavComponent; @ViewChild('wrapperDiv', { static: true }) public wrapperDiv: any; } // @Component({ // template: ` // <div #wrapperDiv> // <igx-bottom-nav> // <igx-bottom-nav-content label="dede"> // <ng-template igxTab> // <div>T1</div> // </ng-template> // <h1>Tab 1 Content</h1> // </igx-bottom-nav-content> // <igx-bottom-nav-content label="Tab 2"> // <ng-template igxTab> // <div>T2</div> // </ng-template> // <h1>Tab 2 Content</h1> // </igx-bottom-nav-content> // <igx-bottom-nav-content label="Tab 3"> // <ng-template igxTab> // <div>T3</div> // </ng-template> // <h1>Tab 3 Content</h1> // </igx-bottom-nav-content> // </igx-bottom-nav> // </div>` // }) // export class TemplatedTabBarTestComponent { // @ViewChild(IgxBottomNavComponent, { static: true }) public bottomNav: IgxBottomNavComponent; // @ViewChild('wrapperDiv', { static: true }) public wrapperDiv: any; // } @Component({ template: ` <div #wrapperDiv> <div> <router-outlet></router-outlet> </div> <igx-bottom-nav> <igx-bottom-nav-item routerLinkActive #rla1="routerLinkActive" [selected]="rla1.isActive"> <igx-bottom-nav-header routerLink="/view1"> <igx-icon igxTabHeaderIcon>library_music</igx-icon> <span igxTabHeaderLabel>Tab 1</span> </igx-bottom-nav-header> </igx-bottom-nav-item> <igx-bottom-nav-item routerLinkActive #rla2="routerLinkActive" [selected]="rla2.isActive"> <igx-bottom-nav-header routerLink="/view2"> <igx-icon igxTabHeaderIcon>video_library</igx-icon> <span igxTabHeaderLabel>Tab 2</span> </igx-bottom-nav-header> </igx-bottom-nav-item> <igx-bottom-nav-item routerLinkActive #rla3="routerLinkActive" [selected]="rla3.isActive"> <igx-bottom-nav-header routerLink="/view3"> <igx-icon igxTabHeaderIcon>library_books</igx-icon> <span igxTabHeaderLabel>Tab 3</span> </igx-bottom-nav-header> </igx-bottom-nav-item> </igx-bottom-nav> </div> ` }) export class TabBarRoutingTestComponent { @ViewChild(IgxBottomNavComponent, { static: true }) public bottomNav: IgxBottomNavComponent; } @Component({ template: ` <div #wrapperDiv> <igx-bottom-nav> <igx-bottom-nav-item> <igx-bottom-nav-header> <igx-icon igxTabHeaderIcon>library_music</igx-icon> <span igxTabHeaderLabel>Tab 1</span> </igx-bottom-nav-header> <igx-bottom-nav-content></igx-bottom-nav-content> </igx-bottom-nav-item> <igx-bottom-nav-item [selected]="true"> <igx-bottom-nav-header> <igx-icon igxTabHeaderIcon>video_library</igx-icon> <span igxTabHeaderLabel>Tab 2</span> </igx-bottom-nav-header> <igx-bottom-nav-content></igx-bottom-nav-content> </igx-bottom-nav-item> <igx-bottom-nav-item> <igx-bottom-nav-header> <igx-icon igxTabHeaderIcon>library_books</igx-icon> <span igxTabHeaderLabel>Tab 3</span> </igx-bottom-nav-header> <igx-bottom-nav-content></igx-bottom-nav-content> </igx-bottom-nav-item> </igx-bottom-nav> </div> ` }) export class TabBarTabsOnlyModeTestComponent { @ViewChild(IgxBottomNavComponent, { static: true }) public bottomNav: IgxBottomNavComponent; } @Component({ template: ` <div #wrapperDiv> <div> <router-outlet></router-outlet> </div> <igx-bottom-nav> <igx-bottom-nav-item routerLinkActive #rla1="routerLinkActive" [selected]="rla1.isActive"> <igx-bottom-nav-header routerLink="/view1"> <igx-icon igxTabHeaderIcon>library_music</igx-icon> <span igxTabHeaderLabel>Tab 1</span> </igx-bottom-nav-header> </igx-bottom-nav-item> <igx-bottom-nav-item routerLinkActive #rlaX="routerLinkActive" [selected]="rlaX.isActive"> <igx-bottom-nav-header routerLink="/view5"> <igx-icon igxTabHeaderIcon>library_books</igx-icon> <span igxTabHeaderLabel>Tab 5</span> </igx-bottom-nav-header> </igx-bottom-nav-item> </igx-bottom-nav> </div> ` }) export class BottomNavRoutingGuardTestComponent { @ViewChild(IgxBottomNavComponent, { static: true }) public bottomNav: IgxBottomNavComponent; } @Component({ template: ` <div> <div> <igx-bottom-nav> <igx-bottom-nav-item> <igx-bottom-nav-header> <span igxTabHeaderLabel>Tab 1</span> </igx-bottom-nav-header> <igx-bottom-nav-content> <div>Content 1</div> </igx-bottom-nav-content> </igx-bottom-nav-item> <igx-bottom-nav-item> <igx-bottom-nav-header> <span igxTabHeaderLabel>Tab 2</span> </igx-bottom-nav-header> <igx-bottom-nav-content> <div>Content 2</div> </igx-bottom-nav-content> </igx-bottom-nav-item> <igx-bottom-nav-item> <igx-bottom-nav-header> <span igxTabHeaderLabel>Tab 3</span> </igx-bottom-nav-header> <igx-bottom-nav-content> <div>Content 3</div> </igx-bottom-nav-content> </igx-bottom-nav-item> </igx-bottom-nav> </div> <div> <igx-bottom-nav> <igx-bottom-nav-item> <igx-bottom-nav-header> <span igxTabHeaderLabel>Tab 4</span> </igx-bottom-nav-header> <igx-bottom-nav-content> <div>Content 4</div> </igx-bottom-nav-content> </igx-bottom-nav-item> <igx-bottom-nav-item> <igx-bottom-nav-header> <span igxTabHeaderLabel>Tab 5</span> </igx-bottom-nav-header> <igx-bottom-nav-content> <div>Content 5</div> </igx-bottom-nav-content> </igx-bottom-nav-item> <igx-bottom-nav-item> <igx-bottom-nav-header> <span igxTabHeaderLabel>Tab 6</span> </igx-bottom-nav-header> <igx-bottom-nav-content> <div>Content 6</div> </igx-bottom-nav-content> </igx-bottom-nav-item> </igx-bottom-nav> </div> </div> ` }) export class BottomNavTestHtmlAttributesComponent { @ViewChild(IgxBottomNavComponent, { static: true }) public bottomNav: IgxBottomNavComponent; }
the_stack