text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { parseDOM } from 'htmlparser2'; import cheerio from '.'; import * as utils from './utils'; import { fruits, food, noscript } from './__fixtures__/fixtures'; import { Cheerio } from './cheerio'; import type { Element } from 'domhandler'; import type { CheerioOptions } from './options'; declare module '.' { interface Cheerio<T> { myPlugin(...args: unknown[]): { context: Cheerio<T>; args: unknown[]; }; foo(): void; } } // HTML const script = '<script src="script.js" type="text/javascript"></script>'; const multiclass = '<p><a class="btn primary" href="#">Save</a></p>'; describe('cheerio', () => { it('cheerio(null) should be empty', () => { expect(cheerio(null as any)).toHaveLength(0); }); it('cheerio(undefined) should be empty', () => { expect(cheerio(undefined)).toHaveLength(0); }); it("cheerio('') should be empty", () => { expect(cheerio('')).toHaveLength(0); }); it('cheerio(selector) with no context or root should be empty', () => { expect(cheerio('.h2')).toHaveLength(0); expect(cheerio('#fruits')).toHaveLength(0); }); it('cheerio(node) : should override previously-loaded nodes', () => { const $ = cheerio.load('<div><span></span></div>'); const spanNode = $('span')[0]; const $span = $(spanNode); expect($span[0]).toBe(spanNode); }); it('should be able to create html without a root or context', () => { const $h2 = cheerio('<h2>'); expect($h2).not.toHaveLength(0); expect($h2).toHaveLength(1); expect($h2[0]).toHaveProperty('tagName', 'h2'); }); it('should be able to create complicated html', () => { const $script = cheerio(script) as Cheerio<Element>; expect($script).not.toHaveLength(0); expect($script).toHaveLength(1); expect($script[0].attribs.src).toBe('script.js'); expect($script[0].attribs).toHaveProperty('type', 'text/javascript'); expect($script[0].childNodes).toHaveLength(0); }); function testAppleSelect($apple: ArrayLike<Element>) { expect($apple).toHaveLength(1); const apple = $apple[0]; expect(apple.parentNode).toHaveProperty('tagName', 'ul'); expect(apple.prev).toBe(null); expect((apple.next as Element).attribs.class).toBe('orange'); expect(apple.childNodes).toHaveLength(1); expect(apple.childNodes[0]).toHaveProperty('data', 'Apple'); } // eslint-disable-next-line jest/expect-expect it('should be able to select .apple with only a context', () => { const $apple = cheerio('.apple', fruits); testAppleSelect($apple); }); // eslint-disable-next-line jest/expect-expect it('should be able to select .apple with a node as context', () => { const $apple = cheerio('.apple', cheerio(fruits)[0]); testAppleSelect($apple); }); // eslint-disable-next-line jest/expect-expect it('should be able to select .apple with only a root', () => { const $apple = cheerio('.apple', null, fruits); testAppleSelect($apple); }); it('should be able to select an id', () => { const $fruits = cheerio('#fruits', null, fruits); expect($fruits).toHaveLength(1); expect($fruits[0].attribs.id).toBe('fruits'); }); it('should be able to select a tag', () => { const $ul = cheerio('ul', fruits); expect($ul).toHaveLength(1); expect($ul[0].tagName).toBe('ul'); }); it('should accept a node reference as a context', () => { const $elems = cheerio('<div><span></span></div>'); expect(cheerio('span', $elems[0])).toHaveLength(1); }); it('should accept an array of node references as a context', () => { const $elems = cheerio('<div><span></span></div>'); expect(cheerio('span', $elems.toArray())).toHaveLength(1); }); it('should select only elements inside given context (Issue #193)', () => { const $ = cheerio.load(food); const $fruits = $('#fruits'); const fruitElements = $('li', $fruits); expect(fruitElements).toHaveLength(3); }); it('should be able to select multiple tags', () => { const $fruits = cheerio('li', null, fruits); expect($fruits).toHaveLength(3); const classes = ['apple', 'orange', 'pear']; $fruits.each((idx, $fruit) => { expect($fruit.attribs.class).toBe(classes[idx]); }); }); // eslint-disable-next-line jest/expect-expect it('should be able to do: cheerio("#fruits .apple")', () => { const $apple = cheerio('#fruits .apple', fruits); testAppleSelect($apple); }); // eslint-disable-next-line jest/expect-expect it('should be able to do: cheerio("li.apple")', () => { const $apple = cheerio('li.apple', fruits); testAppleSelect($apple); }); // eslint-disable-next-line jest/expect-expect it('should be able to select by attributes', () => { const $apple = cheerio('li[class=apple]', fruits); testAppleSelect($apple); }); it('should be able to select multiple classes: cheerio(".btn.primary")', () => { const $a = cheerio('.btn.primary', multiclass); expect($a).toHaveLength(1); expect($a[0].childNodes[0]).toHaveProperty('data', 'Save'); }); it('should not create a top-level node', () => { const $elem = cheerio('* div', '<div>'); expect($elem).toHaveLength(0); }); it('should be able to select multiple elements: cheerio(".apple, #fruits")', () => { const $elems = cheerio('.apple, #fruits', fruits); expect($elems).toHaveLength(2); const $apple = $elems .toArray() .filter((elem) => elem.attribs.class === 'apple'); const $fruits = $elems .toArray() .filter((elem) => elem.attribs.id === 'fruits'); testAppleSelect($apple); expect($fruits[0].attribs.id).toBe('fruits'); }); it('should select first element cheerio(:first)', () => { const $elem = cheerio('li:first', fruits); expect($elem.attr('class')).toBe('apple'); const $filtered = cheerio('li', fruits).filter(':even'); expect($filtered).toHaveLength(2); }); it('should be able to select immediate children: cheerio("#fruits > .pear")', () => { const $food = cheerio(food); cheerio('.pear', $food).append('<li class="pear">Another Pear!</li>'); expect(cheerio('#fruits .pear', $food)).toHaveLength(2); const $elem = cheerio('#fruits > .pear', $food); expect($elem).toHaveLength(1); expect($elem.attr('class')).toBe('pear'); }); it('should be able to select immediate children: cheerio(".apple + .pear")', () => { let $elem = cheerio('.apple + li', fruits); expect($elem).toHaveLength(1); $elem = cheerio('.apple + .pear', fruits); expect($elem).toHaveLength(0); $elem = cheerio('.apple + .orange', fruits); expect($elem).toHaveLength(1); expect($elem.attr('class')).toBe('orange'); }); it('should be able to select immediate children: cheerio(".apple ~ .pear")', () => { let $elem = cheerio('.apple ~ li', fruits); expect($elem).toHaveLength(2); $elem = cheerio('.apple ~ .pear', fruits); expect($elem.attr('class')).toBe('pear'); }); it('should handle wildcards on attributes: cheerio("li[class*=r]")', () => { const $elem = cheerio('li[class*=r]', fruits); expect($elem).toHaveLength(2); expect($elem.eq(0).attr('class')).toBe('orange'); expect($elem.eq(1).attr('class')).toBe('pear'); }); it('should handle beginning of attr selectors: cheerio("li[class^=o]")', () => { const $elem = cheerio('li[class^=o]', fruits); expect($elem).toHaveLength(1); expect($elem.eq(0).attr('class')).toBe('orange'); }); it('should handle beginning of attr selectors: cheerio("li[class$=e]")', () => { const $elem = cheerio('li[class$=e]', fruits); expect($elem).toHaveLength(2); expect($elem.eq(0).attr('class')).toBe('apple'); expect($elem.eq(1).attr('class')).toBe('orange'); }); it('(extended Array) should not interfere with prototype methods (issue #119)', () => { const extended: any = []; extended.find = extended.children = extended.each = function () { /* Ignore */ }; const $empty = cheerio(extended); expect($empty.find).toBe(cheerio.prototype.find); expect($empty.children).toBe(cheerio.prototype.children); expect($empty.each).toBe(cheerio.prototype.each); }); it('cheerio.html(null) should return a "" string', () => { expect(cheerio.html(null as any)).toBe(''); }); it('should set html(number) as a string', () => { const $elem = cheerio('<div>'); // @ts-expect-error Passing a number $elem.html(123); expect(typeof $elem.text()).toBe('string'); }); it('should set text(number) as a string', () => { const $elem = cheerio('<div>'); // @ts-expect-error Passing a number $elem.text(123); expect(typeof $elem.text()).toBe('string'); }); describe('.load', () => { it('should generate selections as proper instances', () => { const $ = cheerio.load(fruits); expect($('.apple')).toBeInstanceOf($); }); // Issue #1092 it('should handle a character `)` in `:contains` selector', () => { const result = cheerio.load('<p>)aaa</p>')(":contains('\\)aaa')"); expect(result).toHaveLength(3); expect(result.first().prop('tagName')).toBe('HTML'); expect(result.eq(1).prop('tagName')).toBe('BODY'); expect(result.last().prop('tagName')).toBe('P'); }); it('should be able to filter down using the context', () => { const $ = cheerio.load(fruits); const apple = $('.apple', 'ul'); const lis = $('li', 'ul'); expect(apple).toHaveLength(1); expect(lis).toHaveLength(3); }); it('should preserve root content', () => { const $ = cheerio.load(fruits); // Root should not be overwritten const el = $('<div></div>'); expect(Object.is(el, el._root)).toBe(false); // Query has to have results expect($('li', 'ul')).toHaveLength(3); }); it('should allow loading a pre-parsed DOM', () => { const dom = parseDOM(food); const $ = cheerio.load(dom); expect($('ul')).toHaveLength(3); }); it('should allow loading a single element', () => { const el = parseDOM(food)[0]; const $ = cheerio.load(el); expect($('ul')).toHaveLength(3); }); it('should render xml in html() when options.xml = true', () => { const str = '<MixedCaseTag UPPERCASEATTRIBUTE=""></MixedCaseTag>'; const expected = '<MixedCaseTag UPPERCASEATTRIBUTE=""/>'; const $ = cheerio.load(str, { xml: true }); expect($('MixedCaseTag').get(0)).toHaveProperty( 'tagName', 'MixedCaseTag' ); expect($.html()).toBe(expected); }); it('should render xml in html() when options.xml = true passed to html()', () => { const str = '<MixedCaseTag UPPERCASEATTRIBUTE=""></MixedCaseTag>'; // Since parsing done without xml flag, all tags converted to lowercase const expectedXml = '<html><head/><body><mixedcasetag uppercaseattribute=""/></body></html>'; const expectedNoXml = '<html><head></head><body><mixedcasetag uppercaseattribute=""></mixedcasetag></body></html>'; const $ = cheerio.load(str); expect($('MixedCaseTag').get(0)).toHaveProperty( 'tagName', 'mixedcasetag' ); expect($.html()).toBe(expectedNoXml); expect($.html({ xml: true })).toBe(expectedXml); }); it('should respect options on the element level', () => { const str = '<!doctype html><html><head><title>Some test</title></head><body><footer><p>Copyright &copy; 2003-2014</p></footer></body></html>'; const expectedHtml = '<p>Copyright &copy; 2003-2014</p>'; const expectedXml = '<p>Copyright © 2003-2014</p>'; const domNotEncoded = cheerio.load(str, { xml: { decodeEntities: false }, }); const domEncoded = cheerio.load(str); expect(domNotEncoded('footer').html()).toBe(expectedHtml); expect(domEncoded('footer').html()).toBe(expectedXml); }); it('should use htmlparser2 if xml option is used', () => { const str = '<div></div>'; const dom = cheerio.load(str, null, false); expect(dom.html()).toBe(str); }); it('should return a fully-qualified Function', () => { const $ = cheerio.load('<div>'); expect($).toBeInstanceOf(Function); }); describe('prototype extensions', () => { it('should honor extensions defined on `prototype` property', () => { const $ = cheerio.load('<div>'); $.prototype.myPlugin = function (...args: unknown[]) { return { context: this, args, }; }; const $div = $('div'); expect(typeof $div.myPlugin).toBe('function'); expect($div.myPlugin().context).toBe($div); expect($div.myPlugin(1, 2, 3).args).toStrictEqual([1, 2, 3]); }); it('should honor extensions defined on `fn` property', () => { const $ = cheerio.load('<div>'); $.fn.myPlugin = function (...args: unknown[]) { return { context: this, args, }; }; const $div = $('div'); expect(typeof $div.myPlugin).toBe('function'); expect($div.myPlugin().context).toBe($div); expect($div.myPlugin(1, 2, 3).args).toStrictEqual([1, 2, 3]); }); it('should isolate extensions between loaded functions', () => { const $a = cheerio.load('<div>'); const $b = cheerio.load('<div>'); $a.prototype.foo = function () { /* Ignore */ }; expect($b('div').foo).toBeUndefined(); }); }); }); describe('util functions', () => { it('camelCase function test', () => { expect(utils.camelCase('cheerio.js')).toBe('cheerioJs'); expect(utils.camelCase('camel-case-')).toBe('camelCase'); expect(utils.camelCase('__directory__')).toBe('_directory_'); expect(utils.camelCase('_one-two.three')).toBe('OneTwoThree'); }); it('cssCase function test', () => { expect(utils.cssCase('camelCase')).toBe('camel-case'); expect(utils.cssCase('jQuery')).toBe('j-query'); expect(utils.cssCase('neverSayNever')).toBe('never-say-never'); expect(utils.cssCase('CSSCase')).toBe('-c-s-s-case'); }); it('cloneDom : should be able clone single Elements', () => { const main = cheerio('<p>Cheerio</p>') as Cheerio<Element>; let result: Element[] = []; utils.domEach<Element>(main, (el) => { result = [...result, ...utils.cloneDom(el)]; }); expect(result).toHaveLength(1); expect(result[0]).not.toBe(main[0]); expect(main[0].children.length).toBe(result[0].children.length); expect(cheerio(result).text()).toBe(main.text()); }); it('isHtml function test', () => { expect(utils.isHtml('<html>')).toBe(true); expect(utils.isHtml('\n<html>\n')).toBe(true); expect(utils.isHtml('#main')).toBe(false); expect(utils.isHtml('\n<p>foo<p>bar\n')).toBe(true); expect(utils.isHtml('dog<p>fox<p>cat')).toBe(true); expect(utils.isHtml('<p>fox<p>cat')).toBe(true); expect(utils.isHtml('\n<p>fox<p>cat\n')).toBe(true); expect(utils.isHtml('#<p>fox<p>cat#')).toBe(true); expect(utils.isHtml('<123>')).toBe(false); }); }); describe('parse5 options', () => { // Should parse noscript tags only with false option value test('{scriptingEnabled: ???}', () => { const opt = 'scriptingEnabled'; const options: CheerioOptions = {}; let result; // [default] scriptingEnabled: true - tag contains one text element result = cheerio.load(noscript)('noscript'); expect(result).toHaveLength(1); expect(result[0].children).toHaveLength(1); expect(result[0].children[0].type).toBe('text'); // ScriptingEnabled: false - content of noscript will parsed options[opt] = false; result = cheerio.load(noscript, options)('noscript'); expect(result).toHaveLength(1); expect(result[0].children).toHaveLength(2); expect(result[0].children[0].type).toBe('comment'); expect(result[0].children[1].type).toBe('tag'); expect(result[0].children[1]).toHaveProperty('name', 'a'); // ScriptingEnabled: ??? - should acts as true const values = [undefined, null, 0, '']; for (const val of values) { options[opt] = val as any; result = cheerio.load(noscript, options)('noscript'); expect(result).toHaveLength(1); expect(result[0].children).toHaveLength(1); expect(result[0].children[0].type).toBe('text'); } }); // Should contain location data only with truthful option value test('{sourceCodeLocationInfo: ???}', () => { const prop = 'sourceCodeLocation'; const opt = 'sourceCodeLocationInfo'; const options: CheerioOptions = {}; let result; let i; // Location data should not be present let values = [undefined, null, 0, false, '']; for (i = 0; i < values.length; i++) { options[opt] = values[i] as any; result = cheerio.load(noscript, options)('noscript'); expect(result).toHaveLength(1); expect(result[0]).not.toHaveProperty(prop); } // Location data should be present values = [true, 1, 'test']; for (i = 0; i < values.length; i++) { options[opt] = values[i] as any; result = cheerio.load(noscript, options)('noscript'); expect(result).toHaveLength(1); expect(result[0]).toHaveProperty(prop); expect(typeof (result[0] as any)[prop]).toBe('object'); } }); }); });
the_stack
const SYMBOLS = { /* 0x00: 'GOWARM', 0x03: 'GOSTROUT', 0x0A: 'USR', 0x0D: 'CHARAC', 0x0E: 'ENDCHR', 0x0F: 'TKN.CNTR', 0x0F: 'EOL.PNTR', 0x0F: 'NUMDIM', 0x10: 'DIMFLG', 0x11: 'VALTYP', 0x13: 'DATAFLG', 0x13: 'GARFLG', 0x14: 'SUBFLG', 0x15: 'INPUTFLG', 0x16: 'CPRMASK', 0x16: 'SIGNFLG', 0x1A: 'HGR.SHAPE', 0x1C: 'HGR.BITS', 0x1D: 'HGR.COUNT', 0x24: 'MON.CH', 0x26: 'MON.GBASL', 0x27: 'MON.GBASH', 0x2C: 'MON.H2', 0x2D: 'MON.V2', 0x30: 'MON.HMASK', 0x32: 'MON.INVFLG', 0x33: 'MON.PROMPT', 0x3C: 'MON.A1L', 0x3D: 'MON.A1H', 0x3E: 'MON.A2L', 0x3F: 'MON.A2H', 0x50: 'LINNUM', 0x52: 'TEMPPT', 0x53: 'LASTPT', 0x55: 'TEMPST', 0x5E: 'INDEX', 0x60: 'DEST', 0x62: 'RESULT', 0x67: 'TXTTAB', 0x69: 'VARTAB', 0x6B: 'ARYTAB', 0x6D: 'STREND', 0x6F: 'FRETOP', 0x71: 'FRESPC', 0x73: 'MEMSIZ', 0x75: 'CURLIN', 0x77: 'OLDLIN', 0x79: 'OLDTEXT', 0x7B: 'DATLIN', 0x7D: 'DATPTR', 0x7F: 'INPTR', 0x81: 'VARNAM', 0x83: 'VARPNT', 0x85: 'FORPNT', 0x87: 'TXPSV', 0x87: 'LASTOP', 0x89: 'CPRTYP', 0x8A: 'TEMP3', 0x8A: 'FNCNAM', 0x8C: 'DSCPTR', 0x8F: 'DSCLEN', 0x90: 'JMPADRS', 0x91: 'LENGTH', 0x92: 'ARG.EXTENSION', 0x93: 'TEMP1', 0x94: 'ARYPNT', 0x94: 'HIGHDS', 0x96: 'HIGHTR', 0x98: 'TEMP2', 0x99: 'TMPEXP', 0x99: 'INDX', 0x9A: 'EXPON', 0x9B: 'DPFLG', 0x9B: 'LOWTR', 0x9C: 'EXPSGN', 0x9D: 'FAC', 0x9D: 'DSCTMP', 0xA0: 'VPNT', 0xA2: 'FAC.SIGN', 0xA3: 'SERLEN', 0xA4: 'SHIFT.SIGN.EXT', 0xA5: 'ARG', 0xAA: 'ARG.SIGN', 0xAB: 'SGNCPR', 0xAC: 'FAC.EXTENSION', 0xAD: 'SERPNT', 0xAB: 'STRNG1', 0xAD: 'STRNG2', 0xAF: 'PRGEND', 0xB1: 'CHRGET', 0xB7: 'CHRGOT', 0xB8: 'TXTPTR', 0xC9: 'RNDSEED', 0xD0: 'HGR.DX', 0xD2: 'HGR.DY', 0xD3: 'HGR.QUADRANT', 0xD4: 'HGR.E', 0xD6: 'LOCK', 0xD8: 'ERRFLG', 0xDA: 'ERRLIN', 0xDC: 'ERRPOS', 0xDE: 'ERRNUM', 0xDF: 'ERRSTK', 0xE0: 'HGR.X', 0xE2: 'HGR.Y', 0xE4: 'HGR.COLOR', 0xE5: 'HGR.HORIZ', 0xE6: 'HGR.PAGE', 0xE7: 'HGR.SCALE', 0xE8: 'HGR.SHAPE.PNTR', 0xEA: 'HGR.COLLISIONS', 0xF0: 'FIRST', 0xF1: 'SPEEDZ', 0xF2: 'TRCFLG', 0xF3: 'FLASH.BIT', 0xF4: 'TXTPSV', 0xF6: 'CURLSV', 0xF8: 'REMSTK', 0xF9: 'HGR.ROTATION', 0x0100: 'STACK', 0x0200: 'INPUT.BUFFER', 0x03F5: 'AMPERSAND.VECTOR', */ 0xC000: 'KEYBOARD', 0xC001: '80STOREON', 0xC002: 'RAMRDOFF', 0xC003: 'RAMRDON', 0xC004: 'RAMWROFF', 0xC005: 'RAMWRON', 0xC006: 'INTCXOFF', 0xC007: 'INTCXON', 0xC008: 'ALTZPOFF', 0xC009: 'ALTZPON', 0xC00A: 'SLOT3OFF', 0xC00B: 'SLOT3ON', 0xC00C: 'CLR80VID', 0xC00D: 'SET80VID', 0xC00E: 'CLRALTCH', 0xC00F: 'SETALTCH', 0xC010: 'STROBE', 0xC011: 'BSRBANK2', 0xC012: 'BSRREAD', 0xC013: 'RAMRD', 0xC014: 'RAMWRT', 0xC015: 'INTCXROM', 0xC016: 'ALTZP', 0xC017: 'SLOT3ROM', 0xC018: '80STRORE', 0xC019: 'VERTBLANK', 0xC01A: 'RDTEXT', 0xC01B: 'RDMIXED', 0xC01C: 'RDPAGE2', 0xC01D: 'RDHIRES', 0xC01E: 'RDALTCH', 0xC01F: 'RD80VID', 0xC020: 'TAPEOUT', 0xC030: 'SPEAKER', 0xC050: 'CLRTEXT', 0xC051: 'SETTEXT', 0xC052: 'CLRMIXED', 0xC053: 'SETMIXED', 0xC054: 'PAGE1', 0xC055: 'PAGE2', 0xC056: 'CLRHIRS', 0xC057: 'SETHIRES', 0xC058: 'CLRAN0', 0xC059: 'SETAN0', 0xC05A: 'CLRAN1', 0xC05B: 'SETAN1', 0xC05C: 'CLRAN2', 0xC05D: 'SETAN2', 0xC05E: 'CLRAN3', 0xC05F: 'SETAN3', 0xC060: 'TAPEIN', 0xC061: 'PB0', 0xC062: 'PB1', 0xC063: 'PB2', 0xC064: 'PADDLE0', 0xC065: 'PADDLE1', 0xC066: 'PADDLE2', 0xC067: 'PADDLE3', 0xC070: 'PDLTRIG', 0xC07E: 'SETIOUDIS', 0xC07F: 'CLRIOUDIS', 0xC080: 'RDBSR2', 0xC081: 'WRBSR2', 0xC082: 'OFFBSR2', 0xC083: 'RWBSR2', 0xC084: 'RDBSR2', 0xC085: 'WRBSR2', 0xC086: 'OFFBSR2', 0xC087: 'RWBSR2', 0xC088: 'RDBSR1', 0xC089: 'WRBSR1', 0xC08A: 'OFFBSR1', 0xC08B: 'RWBSR1', 0xC08C: 'RDBSR1', 0xC08D: 'WRBSR1', 0xC08E: 'OFFBSR1', 0xC08F: 'RWBSR1', 0xD000: 'TOKEN.ADDRESS.TABLE', 0xD080: 'UNFNC', 0xD0B2: 'MATHTBL', 0xD0C7: 'M.NEG', 0xD0CA: 'M.EQU', 0xD0CD: 'M.REL', 0xD0D0: 'TOKEN.NAME.TABLE', 0xD260: 'ERROR.MESSAGES', 0xD350: 'QT.ERROR', 0xD358: 'QT.IN', 0xD35D: 'QT.BREAK', 0xD365: 'GTFORPNT', 0xD393: 'BLTU', 0xD39A: 'BLTU2', 0xD3D6: 'CHKMEM', 0xD3E3: 'REASON', 0xD410: 'MEMERR', 0xD412: 'ERROR', 0xD431: 'PRINT.ERROR.LINNUM', 0xD43C: 'RESTART', 0xD45C: 'NUMBERED.LINE', 0xD4B5: 'PUT.NEW.LINE', 0xD4F2: 'FIX.LINKS', 0xD52C: 'INLIN', 0xD52E: 'INLIN2', 0xD553: 'INCHR', 0xD559: 'PARSE.INPUT.LINE', 0xD56C: 'PARSE', 0xD61A: 'FNDLIN', 0xD61E: 'FL1', 0xD648: 'RTS.1', 0xD649: 'NEW', 0xD64B: 'SCRTCH', 0xD665: 'SETPTRS', 0xD66A: 'CLEAR', 0xD66C: 'CLEARC', 0xD683: 'STKINI', 0xD696: 'RTS.2', 0xD697: 'STXTPT', 0xD6A5: 'LIST', 0xD6DA: 'LIST.0', 0xD6FE: 'LIST.1', 0xD702: 'LIST.2', 0xD724: 'LIST.3', 0xD72C: 'GETCHR', 0xD734: 'LIST.4', 0xD766: 'FOR', 0xD7AF: 'STEP', 0xD7D2: 'NEWSTT', 0xD805: 'TRACE.', 0xD826: 'GOEND', 0xD828: 'EXECUTE.STATEMENT', 0xD82A: 'EXECUTE.STATEMENT.1', 0xD842: 'COLON.', 0xD846: 'SYNERR.1', 0xD849: 'RESTORE', 0xD853: 'SETDA', 0xD857: 'RTS.3', 0xD858: 'ISCNTC', 0xD863: 'CONTROL.C.TYPED', 0xD86E: 'STOP', 0xD870: 'END', 0xD871: 'END2', 0xD88A: 'END4', 0xD896: 'CONT', 0xD8AF: 'RTS.4', 0xD8B0: 'SAVE', 0xD8C9: 'LOAD', 0xD8F0: 'VARTIO', 0xD901: 'PROGIO', 0xD912: 'RUN', 0xD921: 'GOSUB', 0xD935: 'GO.TO.LINE', 0xD93E: 'GOTO', 0xD96A: 'RTS.5', 0xD96B: 'POP', 0xD97C: 'UNDERR', 0xD981: 'SYNERR.2', 0xD984: 'RETURN', 0xD995: 'DATA', 0xD998: 'ADDON', 0xD9A2: 'RTS.6', 0xD9A3: 'DATAN', 0xD9A6: 'REMN', 0xD9C5: 'PULL3', 0xD9C9: 'IF', 0xD9DC: 'REM', 0xD9E1: 'IF.TRUE', 0xD9EC: 'ONGOTO', 0xD9F4: 'ON.1', 0xD9F8: 'ON.2', 0xDA0B: 'RTS.7', 0xDA0C: 'LINGET', 0xDA46: 'LET', 0xDA63: 'LET2', 0xDA7A: 'LET.STRING', 0xDA7B: 'PUTSTR', 0xDACF: 'PR.STRING', 0xDAD5: 'PRINT', 0xDAD7: 'PRINT2', 0xDAFB: 'CRDO', 0xDB00: 'NEGATE', 0xDB02: 'RTS.8', 0xDB03: 'PR.COMMA', 0xDB16: 'PR.TAB.OR.SPC', 0xDB2C: 'NXSPC', 0xDB2F: 'PR.NEXT.CHAR', 0xDB35: 'DOSPC', 0xDB3A: 'STROUT', 0xDB3D: 'STRPRT', 0xDB57: 'OUTSP', 0xDB5A: 'OUTQUES', 0xDB5C: 'OUTDO', 0xDB71: 'INPUTERR', 0xDB7B: 'READERR', 0xDB7F: 'ERLIN', 0xDB86: 'INPERR', 0xDB87: 'RESPERR', 0xDBA0: 'GET', 0xDBB2: 'INPUT', 0xDBDC: 'NXIN', 0xDBE2: 'READ', 0xDBE9: 'INPUT.FLAG.ZERO', 0xDBEB: 'PROCESS.INPUT.LIST', 0xDBF1: 'PROCESS.INPUT.ITEM', 0xDC2B: 'INSTART', 0xDC69: 'INPUT.DATA', 0xDC72: 'INPUT.MORE', 0xDC99: 'INPFIN', 0xDCA0: 'FINDATA', 0xDCC6: 'INPDONE', 0xDCDF: 'ERR.EXTRA', 0xDCEF: 'ERR.REENTRY', 0xDCF9: 'NEXT', 0xDCFF: 'NEXT.1', 0xDD02: 'NEXT.2', 0xDD0D: 'GERR', 0xDD0F: 'NEXT.3', 0xDD67: 'FRMNUM', 0xDD6A: 'CHKNUM', 0xDD6C: 'CHKSTR', 0xDD6D: 'CHKVAL', 0xDD78: 'JERROR', 0xDD7B: 'FRMEVL', 0xDD86: 'FRMEVL.1', 0xDD95: 'FRMEVL.2', 0xDDCD: 'FRM.PRECEDENCE.TEST', 0xDDD6: 'NXOP', 0xDDD7: 'SAVOP', 0xDDE4: 'FRM.RELATIONAL', 0xDDF6: 'PREFNC', 0xDDFD: 'FRM.RECURSE', 0xDE0D: 'SNTXERR', 0xDE10: 'FRM.STACK.1', 0xDE15: 'FRM.STACK.2', 0xDE20: 'FRM.STACK.3', 0xDE35: 'NOTMATH', 0xDE38: 'GOEX', 0xDE3A: 'FRM.PERFORM.1', 0xDE43: 'FRM.PERFORM.2', 0xDE5D: 'EXIT', 0xDE60: 'FRM.ELEMENT', 0xDE81: 'STRTXT', 0xDE90: 'NOT.', 0xDE98: 'EQUOP', 0xDEA4: 'FN.', 0xDEAB: 'SGN.', 0xDEB2: 'PARCHK', 0xDEB8: 'CHKCLS', 0xDEBB: 'CHKOPN', 0xDEBE: 'CHKCOM', 0xDEC0: 'SYNCHR', 0xDEC9: 'SYNERR', 0xDECE: 'MIN', 0xDED0: 'EQUL', 0xDED5: 'FRM.VARIABLE', 0xDED7: 'FRM.VARIABLE.CALL', 0xDEF9: 'SCREEN', 0xDF0C: 'UNARY', 0xDF4F: 'OR', 0xDF55: 'AND', 0xDF5D: 'FALSE', 0xDF60: 'TRUE', 0xDF65: 'RELOPS', 0xDF7D: 'STRCMP', 0xDFAA: 'STRCMP.1', 0xDFB0: 'NUMCMP', 0xDFB5: 'STRCMP.2', 0xDFC1: 'CMPDONE', 0xDFCD: 'PDL', 0xDFD6: 'NXDIM', 0xDFD9: 'DIM', 0xDFE3: 'PTRGET', 0xDFE8: 'PTRGET2', 0xDFEA: 'PTRGET3', 0xDFF4: 'BADNAM', 0xDFF7: 'NAMOK', 0xE007: 'PTRGET4', 0xE07D: 'ISLETC', 0xE087: 'NAME.NOT.FOUND', 0xE09A: 'C.ZERO', 0xE09C: 'MAKE.NEW.VARIABLE', 0xE0DE: 'SET.VARPNT.AND.YA', 0xE0ED: 'GETARY', 0xE0EF: 'GETARY2', 0xE0FE: 'NEG32768', 0xE102: 'MAKINT', 0xE108: 'MKINT', 0xE10C: 'AYINT', 0xE119: 'MI1', 0xE11B: 'MI2', 0xE11E: 'ARRAY', 0xE196: 'SUBERR', 0xE199: 'IQERR', 0xE19B: 'JER', 0xE19E: 'USE.OLD.ARRAY', 0xE1B8: 'MAKE.NEW.ARRAY', 0xE24B: 'FIND.ARRAY.ELEMENT', 0xE253: 'FAE.1', 0xE269: 'GSE', 0xE26C: 'GME', 0xE26F: 'FAE.2', 0xE270: 'FAE.3', 0xE2AC: 'RTS.9', 0xE2AD: 'MULTIPLY.SUBSCRIPT', 0xE2B6: 'MULTIPLY.SUBS.1', 0xE2DE: 'FRE', 0xE2F2: 'GIVAYF', 0xE2FF: 'POS', 0xE301: 'SNGFLT', 0xE306: 'ERRDIR', 0xE30E: 'UNDFNC', 0xE313: 'DEF', 0xE341: 'FNC.', 0xE354: 'FUNCT', 0xE3AF: 'FNCDATA', 0xE3C5: 'STR', 0xE3D5: 'STRINI', 0xE3DD: 'STRSPA', 0xE3E7: 'STRLIT', 0xE3ED: 'STRLT2', 0xE42A: 'PUTNEW', 0xE432: 'JERR', 0xE435: 'PUTEMP', 0xE452: 'GETSPA', 0xE484: 'GARBAG', 0xE488: 'FIND.HIGHEST.STRING', 0xE519: 'CHECK.SIMPLE.VARIABLE', 0xE523: 'CHECK.VARIABLE', 0xE552: 'CHECK.BUMP', 0xE55D: 'CHECK.EXIT', 0xE562: 'MOVE.HIGHEST.STRING.TO.TOP', 0xE597: 'CAT', 0xE5D4: 'MOVINS', 0xE5E2: 'MOVSTR', 0xE5E6: 'MOVSTR.1', 0xE5FD: 'FRESTR', 0xE600: 'FREFAC', 0xE604: 'FRETMP', 0xE635: 'FRETMS', 0xE646: 'CHRSTR', 0xE65A: 'LEFTSTR', 0xE660: 'SUBSTRING.1', 0xE667: 'SUBSTRING.2', 0xE668: 'SUBSTRING.3', 0xE686: 'RIGHTSTR', 0xE691: 'MIDSTR', 0xE6B9: 'SUBSTRING.SETUP', 0xE6D6: 'LEN', 0xE6DC: 'GETSTR', 0xE6E5: 'ASC', 0xE6F2: 'GOIQ', 0xE6F5: 'GTBYTC', 0xE6F8: 'GETBYT', 0xE6FB: 'CONINT', 0xE707: 'VAL', 0xE73D: 'POINT', 0xE746: 'GTNUM', 0xE74C: 'COMBYTE', 0xE752: 'GETADR', 0xE764: 'PEEK', 0xE77B: 'POKE', 0xE784: 'WAIT', 0xE79F: 'RTS.10', 0xE7A0: 'FADDH', 0xE7A7: 'FSUB', 0xE7AA: 'FSUBT', 0xE7B9: 'FADD.1', 0xE7BE: 'FADD', 0xE7C1: 'FADDT', 0xE7CE: 'FADD.2', 0xE7FA: 'FADD.3', 0xE829: 'NORMALIZE.FAC.1', 0xE82E: 'NORMALIZE.FAC.2', 0xE84E: 'ZERO.FAC', 0xE850: 'STA.IN.FAC.SIGN.AND.EXP', 0xE852: 'STA.IN.FAC.SIGN', 0xE855: 'FADD.4', 0xE874: 'NORMALIZE.FAC.3', 0xE880: 'NORMALIZE.FAC.4', 0xE88D: 'NORMALIZE.FAC.5', 0xE88F: 'NORMALIZE.FAC.6', 0xE89D: 'RTS.11', 0xE89E: 'COMPLEMENT.FAC', 0xE8A4: 'COMPLEMENT.FAC.MANTISSA', 0xE8C6: 'INCREMENT.FAC.MANTISSA', 0xE8D4: 'RTS.12', 0xE8D5: 'OVERFLOW', 0xE8DA: 'SHIFT.RIGHT.1', 0xE8DC: 'SHIFT.RIGHT.2', 0xE8F0: 'SHIFT.RIGHT', 0xE8FD: 'L', // 0xE8FD: 'SHIFT.RIGHT.3', 0xE907: 'SHIFT.RIGHT.4', 0xE911: 'SHIFT.RIGHT.5', 0xE913: 'CON.ONE', 0xE918: 'POLY.LOG', 0xE92D: 'CON.SQR.HALF', 0xE932: 'CON.SQR.TWO', 0xE937: 'CON.NEG.HALF', 0xE93C: 'CON.LOG.TWO', 0xE941: 'LOG', 0xE948: 'GIQ', 0xE94B: 'LOG.2', 0xE97F: 'FMULT', 0xE982: 'FMULTT', 0xE9B0: 'MULTIPLY.1', 0xE9B5: 'MULTIPLY.2', 0xE9E2: 'RTS.13', 0xE9E3: 'LOAD.ARG.FROM.YA', 0xEA0E: 'ADD.EXPONENTS', 0xEA10: 'ADD.EXPONENTS.1', 0xEA2B: 'OUTOFRNG', 0xEA31: 'ZERO', 0xEA36: 'JOV', 0xEA39: 'MUL10', 0xEA50: 'CON.TEN', 0xEA55: 'DIV10', 0xEA5E: 'DIV', 0xEA66: 'FDIV', 0xEA69: 'FDIVT', 0xEAE6: 'COPY.RESULT.INTO.FAC', 0xEAF9: 'LOAD.FAC.FROM.YA', 0xEB1E: 'STORE.FAC.IN.TEMP2.ROUNDED', 0xEB21: 'STORE.FAC.IN.TEMP1.ROUNDED', 0xEB27: 'SETFOR', 0xEB2B: 'STORE.FAC.AT.YX.ROUNDED', 0xEB53: 'COPY.ARG.TO.FAC', 0xEB55: 'MFA', 0xEB63: 'COPY.FAC.TO.ARG.ROUNDED', 0xEB66: 'MAF', 0xEB71: 'RTS.14', 0xEB72: 'ROUND.FAC', 0xEB7A: 'INCREMENT.MANTISSA', 0xEB82: 'SIGN', 0xEB86: 'SIGN1', 0xEB88: 'SIGN2', 0xEB8F: 'RTS.15', 0xEB90: 'SGN', 0xEB93: 'FLOAT', 0xEB9B: 'FLOAT.1', 0xEBA0: 'FLOAT.2', 0xEBAF: 'ABS', 0xEBB2: 'FCOMP', 0xEBB4: 'FCOMP2', 0xEBF2: 'QINT', 0xEC11: 'RTS.16', 0xEC12: 'QINT.2', 0xEC23: 'INT', 0xEC40: 'QINT.3', 0xEC49: 'RTS.17', 0xEC4A: 'FIN', 0xEC61: 'FIN.1', 0xEC64: 'FIN.2', 0xEC66: 'FIN.3', 0xEC87: 'FIN.4', 0xEC8A: 'FIN.5', 0xEC8C: 'FIN.6', 0xEC98: 'FIN.10', 0xEC9E: 'FIN.7', 0xECA0: 'FIN.8', 0xECC1: 'FIN.9', 0xECD5: 'ADDACC', 0xECE8: 'GETEXP', 0xED0A: 'CON.99999999.9', 0xED0F: 'CON.999999999', 0xED14: 'CON.BILLION', 0xED19: 'INPRT', 0xED24: 'LINPRT', 0xED2E: 'PRINT.FAC', 0xED31: 'GO.STROUT', 0xED34: 'FOUT', 0xED36: 'FOUT.1', 0xED8C: 'FOUT.2', 0xEE17: 'FOUT.3', 0xEE57: 'FOUT.4', 0xEE5A: 'FOUT.5', 0xEE5F: 'FOUT.6', 0xEE64: 'CON.HALF', 0xEE69: 'DECTBL', // 0xEE8D: 'DECTBL.END', 0xEE8D: 'SQR', 0xEE97: 'FPWRT', 0xEED0: 'NEGOP', 0xEEDA: 'RTS.18', 0xEEDB: 'CON.LOG.E', 0xEEE0: 'POLY.EXP', 0xEF09: 'EXP', 0xEF5C: 'POLYNOMIAL.ODD', 0xEF72: 'POLYNOMIAL', 0xEF76: 'SERMAIN', 0xEFA5: 'RTS.19', 0xEFA6: 'CON.RND.1', 0xEFAA: 'CON.RND.2', 0xEFAE: 'RND', 0xEFE7: 'GO.MOVMF', 0xEFEA: 'COS', 0xEFF1: 'SIN', 0xF023: 'SIN.1', 0xF026: 'SIN.2', 0xF03A: 'TAN', 0xF062: 'TAN.1', 0xF066: 'CON.PI.HALF', 0xF06B: 'CON.PI.DOUB', 0xF070: 'QUARTER', 0xF075: 'POLY.SIN', 0xF09E: 'ATN', 0xF0CD: 'RTS.20', 0xF0CE: 'POLY.ATN', 0xF10B: 'GENERIC.CHRGET', 0xF128: 'COLD.START', // 0xF128: 'GENERIC.END', 0xF1D5: 'CALL', 0xF1DE: 'IN.NUMBER', 0xF1E5: 'PR.NUMBER', 0xF1EC: 'PLOTFNS', 0xF206: 'GOERR', 0xF209: 'LINCOOR', 0xF225: 'PLOT', 0xF232: 'HLIN', 0xF241: 'VLIN', 0xF24F: 'COLOR', 0xF256: 'VTAB', 0xF262: 'SPEED', 0xF26D: 'TRACE', 0xF26F: 'NOTRACE', 0xF273: 'NORMAL', 0xF277: 'INVERSE', 0xF279: 'N.I.', 0xF27B: 'N.I.F.', 0xF280: 'FLASH', 0xF286: 'HIMEM', 0xF296: 'JMM', 0xF299: 'SETHI', 0xF2A6: 'LOMEM', 0xF2CB: 'ONERR', 0xF2E9: 'HANDLERR', 0xF318: 'RESUME', 0xF32E: 'JSYN', 0xF331: 'DEL', 0xF390: 'GR', 0xF399: 'TEXT', 0xF39F: 'STORE', 0xF3BC: 'RECALL', 0xF3D8: 'HGR2', 0xF3E2: 'HGR', 0xF3EA: 'SETHPG', 0xF3F2: 'HCLR', 0xF3F6: 'BKGND', 0xF411: 'HPOSN', 0xF457: 'HPLOT0', 0xF465: 'MOVE.LEFT.OR.RIGHT', 0xF46E: 'LR.1', 0xF471: 'LR.2', 0xF476: 'LR.3', 0xF478: 'LR.4', 0xF47E: 'COLOR.SHIFT', 0xF48A: 'MOVE.RIGHT', 0xF49C: 'LRUDX1', 0xF49D: 'LRUDX2', 0xF4B3: 'LRUD1', 0xF4B4: 'LRUD2', 0xF4C4: 'LRUD3', 0xF4C8: 'LRUD4', 0xF4CD: 'CON.03', 0xF4D3: 'MOVE.UP.OR.DOWN', 0xF501: 'UD.1', 0xF505: 'MOVE.DOWN', 0xF508: 'CON.04', 0xF530: 'HLINRL', 0xF53A: 'HGLIN', 0xF57C: 'MOVEX', 0xF581: 'MOVEX2', 0xF5B2: 'MSKTBL', 0xF5B9: 'CON.1C', 0xF5BA: 'COSINE.TABLE', 0xF5CB: 'HFIND', 0xF600: 'RTS.22', 0xF601: 'DRAW0', 0xF605: 'DRAW1', 0xF65D: 'XDRAW0', 0xF661: 'XDRAW1', 0xF6B9: 'HFNS', 0xF6E6: 'GGERR', 0xF6E9: 'HCOLOR', 0xF6F5: 'RTS.23', 0xF6F6: 'COLORTBL', 0xF6FE: 'HPLOT', 0xF721: 'ROT', 0xF727: 'SCALE', 0xF72D: 'DRWPNT', 0xF769: 'DRAW', 0xF76F: 'XDRAW', 0xF775: 'SHLOAD', 0xF7BC: 'TAPEPNT', 0xF7D9: 'GETARYPT', 0xF7E7: 'HTAB', 0xF800: 'MON.PLOT', 0xF819: 'MON.HLINE', 0xF828: 'MON.VLINE', 0xF864: 'MON.SETCOL', 0xF871: 'MON.SCRN', 0xFB1E: 'MON.PREAD', 0xFB39: 'MON.SETTXT', 0xFB40: 'MON.SETGR', 0xFB5B: 'MON.TABV', 0xFC58: 'MON.HOME', 0xFCA8: 'MON.WAIT', 0xFCFA: 'MON.RD2BIT', 0xFD0C: 'MON.RDKEY', 0xFD6A: 'MON.GETLN', 0xFDED: 'MON.COUT', 0xFE8B: 'MON.INPORT', 0xFE95: 'MON.OUTPORT', 0xFECD: 'MON.WRITE', 0xFEFD: 'MON.READ', 0xFF02: 'MON.READ2' }; export default SYMBOLS;
the_stack
import {Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core'; import {ActivatedRoute} from '@angular/router'; import {ProviderService} from '../../../services/provider.service'; import moment from 'moment'; import { filter } from 'lodash'; import { BotDetectionService } from 'app/services/bot-detection.service'; @Component({ selector: 'app-account-settings', templateUrl: './account-settings.component.html', styleUrls: ['./account-settings.component.scss'] }) export class AccountSettingsComponent implements OnInit, OnChanges { @Output() onSavedAccountSettings = new EventEmitter<any>(); @Input() accountSettings: any; @Input() inheritMode = false; @Input() readonly = false; @ViewChild('accountForm', { static: true }) form: any; formChanged = false; userProviders: any[]; botDetectionPlugins: any[]; private domainId: string; private defaultMaxAttempts = 10; private defaultLoginAttemptsResetTime = 12; private defaultLoginAttemptsResetTimeUnit = 'hours'; private defaultAccountBlockedDuration = 2; private defaultAccountBlockedDurationUnit = 'hours'; availableFields = [ {"key" : "email", "label" : "Email", "type" : "email"}, {"key" : "username", "label" : "Username", "type" : "text"}, ]; newField = {}; selectedFields = []; constructor(private route: ActivatedRoute, private providerService: ProviderService, private botDetectionService: BotDetectionService) {} ngOnInit(): void { this.domainId = this.route.snapshot.data['domain']?.id; this.initDateValues(); this.initSelectedFields(); this.providerService.findUserProvidersByDomain(this.domainId).subscribe(response => { this.userProviders = response; }); this.botDetectionService.findByDomain(this.domainId).subscribe(response => { this.botDetectionPlugins = response; }) } ngOnChanges(changes: SimpleChanges): void { if (changes.accountSettings.previousValue && changes.accountSettings.currentValue) { this.accountSettings = changes.accountSettings.currentValue; this.initDateValues(); this.initSelectedFields(); } } save() { let accountSettings = Object.assign({}, this.accountSettings); if (accountSettings.inherited) { accountSettings = { 'inherited' : true }; } else { // set duration values accountSettings.loginAttemptsResetTime = this.getDuration(accountSettings.loginAttemptsResetTime, accountSettings.loginAttemptsResetTimeUnitTime); accountSettings.accountBlockedDuration = this.getDuration(accountSettings.accountBlockedDuration, accountSettings.accountBlockedDurationUnitTime); delete accountSettings.loginAttemptsResetTimeUnitTime; delete accountSettings.accountBlockedDurationUnitTime; // set list of fields that will be used by the ForgotPassword Form if (accountSettings.resetPasswordCustomForm) { accountSettings['resetPasswordCustomFormFields'] = this.selectedFields; } else { delete accountSettings.resetPasswordCustomFormFields; delete accountSettings.resetPasswordConfirmIdentity; } if (!accountSettings.useBotDetection) { delete accountSettings.botDetectionPlugin; } } this.onSavedAccountSettings.emit(accountSettings); this.formChanged = false; } onFieldSelected(event) { this.newField = {...this.availableFields.filter(f=> f.key === event.value)[0]}; } addField() { this.selectedFields.push({...this.newField}); this.selectedFields = [...this.selectedFields]; this.newField = {}; this.formChanged = true; } removeField(key) { let idx = this.selectedFields.findIndex(item => item.key === key); if (idx >= 0) { this.selectedFields.splice(idx, 1); this.selectedFields = [...this.selectedFields]; this.formChanged = true; } } isFieldSelected(key) { return this.selectedFields.findIndex(item => item.key === key) >= 0; } enableInheritMode(event) { this.accountSettings.inherited = event.checked; this.formChanged = true; } isInherited() { return this.accountSettings && this.accountSettings.inherited; } enableBrutForceAuthenticationDetection(event) { this.accountSettings.loginAttemptsDetectionEnabled = event.checked; this.formChanged = true; // apply default values this.accountSettings.maxLoginAttempts = this.accountSettings.maxLoginAttempts || this.defaultMaxAttempts; this.accountSettings.loginAttemptsResetTime = this.accountSettings.loginAttemptsResetTime || this.defaultLoginAttemptsResetTime; this.accountSettings.loginAttemptsResetTimeUnitTime = this.accountSettings.loginAttemptsResetTimeUnitTime || this.defaultLoginAttemptsResetTimeUnit; this.accountSettings.accountBlockedDuration = this.accountSettings.accountBlockedDuration || this.defaultAccountBlockedDuration; this.accountSettings.accountBlockedDurationUnitTime = this.accountSettings.accountBlockedDurationUnitTime || this.defaultAccountBlockedDurationUnit; } isBrutForceAuthenticationEnabled() { return this.accountSettings && this.accountSettings.loginAttemptsDetectionEnabled; } enableDynamicUserRegistration(event) { this.accountSettings.dynamicUserRegistration = event.checked; this.formChanged = true; } isDynamicUserRegistrationEnabled() { return this.accountSettings && this.accountSettings.dynamicUserRegistration; } enableCompleteRegistration(event) { this.accountSettings.completeRegistrationWhenResetPassword = event.checked; this.formChanged = true; } isCompleteRegistrationEnabled() { return this.accountSettings && this.accountSettings.completeRegistrationWhenResetPassword; } enableAutoLoginAfterRegistration(event) { this.accountSettings.autoLoginAfterRegistration = event.checked; this.formChanged = true; } isAutoLoginAfterRegistrationEnabled() { return this.accountSettings && this.accountSettings.autoLoginAfterRegistration; } enableAutoLoginAfterResetPassword(event) { this.accountSettings.autoLoginAfterResetPassword = event.checked; this.formChanged = true; } isAutoLoginAfterResetPasswordEnabled() { return this.accountSettings && this.accountSettings.autoLoginAfterResetPassword; } enableSendRecoverAccountEmail(event) { this.accountSettings.sendRecoverAccountEmail = event.checked; this.formChanged = true; } isSendRecoverAccountEmailEnabled() { return this.accountSettings && this.accountSettings.sendRecoverAccountEmail; } enableDeletePasswordlessDevicesAfterResetPassword(event) { this.accountSettings.deletePasswordlessDevicesAfterResetPassword = event.checked; this.formChanged = true; } isDeletePasswordlessDevicesAfterResetPasswordEnabled() { return this.accountSettings && this.accountSettings.deletePasswordlessDevicesAfterResetPassword; } enableBotDetection(event) { this.accountSettings.useBotDetection = event.checked; this.formChanged = true; } isBotDetectionEnabled() { return this.accountSettings && this.accountSettings.useBotDetection; } hasBotDetectionPlugins() { return this.botDetectionPlugins && this.botDetectionPlugins.length > 0; } enableResetPasswordCustomForm(event) { this.accountSettings.resetPasswordCustomForm = event.checked; this.formChanged = true; } isResetPasswordCustomFormEnabled() { return this.accountSettings && this.accountSettings.resetPasswordCustomForm; } enableResetPasswordConfirmIdentity(event) { this.accountSettings.resetPasswordConfirmIdentity = event.checked; this.formChanged = true; } isResetPasswordConfirmIdentityEnabled() { return this.accountSettings && this.accountSettings.resetPasswordConfirmIdentity; } updateModel() { this.formChanged = true; } formIsValid() { if (this.accountSettings.loginAttemptsDetectionEnabled) { if (this.accountSettings.maxLoginAttempts < 1) { return false; } if (this.accountSettings.loginAttemptsResetTime < 1) { return false; } else if (!this.accountSettings.loginAttemptsResetTimeUnitTime) { return false; } if (this.accountSettings.accountBlockedDuration < 1) { return false; } else if (!this.accountSettings.accountBlockedDurationUnitTime) { return false; } } if (this.accountSettings.resetPasswordCustomForm) { return this.selectedFields && this.selectedFields.length > 0; } return true; } private initDateValues() { if (this.accountSettings.loginAttemptsResetTime > 0) { const loginAttemptsResetTime = this.getHumanizeDuration(this.accountSettings.loginAttemptsResetTime); this.accountSettings.loginAttemptsResetTime = loginAttemptsResetTime[0]; this.accountSettings.loginAttemptsResetTimeUnitTime = loginAttemptsResetTime[1]; } if (this.accountSettings.accountBlockedDuration > 0) { const accountBlockedDuration = this.getHumanizeDuration(this.accountSettings.accountBlockedDuration); this.accountSettings.accountBlockedDuration = accountBlockedDuration[0]; this.accountSettings.accountBlockedDurationUnitTime = accountBlockedDuration[1]; } } private initSelectedFields() { if (this.accountSettings.resetPasswordCustomForm) { this.selectedFields = this.accountSettings.resetPasswordCustomFormFields || []; } } private getHumanizeDuration(value) { const humanizeDate = moment.duration(value, 'seconds').humanize().split(' '); const humanizeDateValue = (humanizeDate.length === 2) ? (humanizeDate[0] === 'a' || humanizeDate[0] === 'an') ? 1 : humanizeDate[0] : value; const humanizeDateUnit = (humanizeDate.length === 2) ? humanizeDate[1].endsWith('s') ? humanizeDate[1] : humanizeDate[1] + 's' : humanizeDate[2].endsWith('s') ? humanizeDate[2] : humanizeDate[2] + 's'; return new Array(humanizeDateValue, humanizeDateUnit); } private getDuration(value, unit) { return moment.duration(parseInt(value), unit).asSeconds(); } }
the_stack
import { aws_events, aws_events_targets, Stack } from "aws-cdk-lib"; import { Construct } from "constructs"; import { ASL } from "../asl"; import { CallExpr, Expr, Identifier, ObjectLiteralExpr, PropAssignExpr, StringLiteralExpr, } from "../expression"; import { Function, NativePreWarmContext, PrewarmClients } from "../function"; import { isArrayLiteralExpr, isComputedPropertyNameExpr, isIdentifier, isObjectLiteralExpr, isSpreadAssignExpr, } from "../guards"; import { Integration, IntegrationCall, IntegrationImpl, isIntegration, makeIntegration, } from "../integration"; import type { AnyFunction } from "../util"; import { RulePredicateFunction, Rule, PredicateRuleBase, ImportedRule, ScheduledEvent, IRule, } from "./rule"; import type { Event } from "./types"; export const isEventBus = <EvntBus extends IEventBus<any>>( v: any ): v is EvntBus => { return ( "functionlessKind" in v && v.functionlessKind === EventBusBase.FunctionlessType ); }; /** * Returns the {@link Event} type on the {@link EventBus}. */ export type EventBusEvent<B extends IEventBus<any>> = [B] extends [ IEventBus<infer E> ] ? E : never; export interface IEventBusFilterable<in Evnt extends Event> { /** * EventBus Rules can filter events using Functionless predicate functions. * * Equals * * ```ts * when(this, 'rule', (event) => event.source === "lambda") * ``` * * Starts With (Prefix) * * ```ts * when(this, 'rule', (event) => event.id.startsWith("2022")) * ``` * * Not * * ```ts * when(this, 'rule', (event) => event.source !== "dynamo") * ``` * * Numeric Ranges * * ```ts * when(this, 'rule', (event) => event.detail.num >= 10 || event.detail.num > 100 && event.detail.num < 1000) * ``` * * Presence * * ```ts * when(this, 'rule', (event) => !event.detail.optional) * ``` * * Multiple Fields * * ```ts * when(this, 'rule', (event) => event.source === "lambda" && event['detail-type'] === "SUCCESS") * ``` * * Array Includes * * ```ts * when(this, 'rule', (event) => event.detail.list.includes("someValue")) * ``` * * Omitting the scope will use the bus as the scope. * * ```ts * when('rule', ...) * ``` * * Unsupported by Event Bridge * * OR Logic between multiple fields * * AND logic between most logic on a single field (except for numeric ranges.) * * Multiple `!field.startsWith(...)` on a single field * * Any operation on an Array other than `includes` and presence (`event.detail.list === undefined`). * * Any string operation other than `===/==`, `!==/!=`, `startsWith`, and presence (`!==/=== undefined`). * * Math (`event.detail.num + 1 < 10`) * * Comparisons between fields (`event.detail.previous !== event.id`) * * Unsupported by Functionless: * * Variables from outside of the function scope * * @typeParam InEvnt - The type the {@link Rule} matches. Covariant of output {@link OutEvnt}. * @typeParam NewEvnt - The type the predicate narrows to, a sub-type of {@link InEvnt}. */ when<InEvnt extends Evnt, NewEvnt extends InEvnt>( id: string, predicate: RulePredicateFunction<InEvnt, NewEvnt> ): Rule<InEvnt, NewEvnt>; when<InEvnt extends Evnt, NewEvnt extends InEvnt>( scope: Construct, id: string, predicate: RulePredicateFunction<InEvnt, NewEvnt> ): Rule<InEvnt, NewEvnt>; } /** * @typeParam Evnt - the union type of events that this EventBus can accept. * `Evnt` is the contravariant version of `OutEvnt` in that * the bus will accept any of `Evnt` while the EventBus can * emit any of `OutEvnt`. */ export interface IEventBus<in Evnt extends Event = Event> extends IEventBusFilterable<Evnt>, Integration< "EventBus", (event: PutEventInput<Evnt>, ...events: PutEventInput<Evnt>[]) => void, EventBusTargetIntegration< PutEventInput<Evnt>, aws_events_targets.EventBusProps | undefined > > { readonly resource: aws_events.IEventBus; readonly eventBusArn: string; readonly eventBusName: string; // @ts-ignore - value does not exist, is only available at compile time readonly __functionBrand: ( event: PutEventInput<Evnt>, ...events: PutEventInput<Evnt>[] ) => void; /** * This static property identifies this class as an EventBus to the TypeScript plugin. */ readonly functionlessKind: typeof EventBusBase.FunctionlessType; /** * Put one or more events on an Event Bus. */ putEvents(event: PutEventInput<Evnt>, ...events: PutEventInput<Evnt>[]): void; /** * Creates a rule that matches all events on the bus. * * When no scope or id are given, the bus is used as the scope and the id will be `all`. * The rule created will be a singleton. * * When scope and id are given, a new rule will be created each time. * * Like all functionless, a rule is only created when the rule is used with `.pipe` or the rule is retrieved using `.rule`. * * ```ts * const bus = new EventBus(scope, 'bus'); * const func = new Function(scope, 'func', async (payload: {id: string}) => console.log(payload.id)); * * bus * .all() * .map(event => ({id: event.id})) * .pipe(func); * ``` */ all<OutEnvt extends Evnt>(): PredicateRuleBase<Evnt, OutEnvt>; all<OutEnvt extends Evnt>( scope: Construct, id: string ): PredicateRuleBase<Evnt, OutEnvt>; } /** * @typeParam Evnt - the union type of events that this EventBus can accept. * `Evnt` is the contravariant version of `OutEvnt` in that * the bus will accept any of `Evnt` while the EventBus can * emit any of `OutEvnt`. * @typeParam OutEvnt - the union type of events that this EventBus will emit through rules. * `OutEvnt` is the covariant version of `Evnt` in that * the bus will emit any of `OutEvnt` while the EventBus can * can accept any of `Evnt`. This type parameter should be left * empty to be inferred. ex: `EventBus<Event<Detail1> | Event<Detail2>>`. */ abstract class EventBusBase<in Evnt extends Event, OutEvnt extends Evnt = Evnt> implements IEventBus<Evnt> { /** * This static properties identifies this class as an EventBus to the TypeScript plugin. */ public static readonly FunctionlessType = "EventBus"; readonly functionlessKind = "EventBus"; readonly kind = "EventBus"; readonly eventBusName: string; readonly eventBusArn: string; protected static singletonDefaultNode = "__DefaultBus"; private allRule: PredicateRuleBase<Evnt, OutEvnt> | undefined; public readonly putEvents: IntegrationCall< "EventBus.putEvents", IEventBus<Evnt>["putEvents"] >; // @ts-ignore - value does not exist, is only available at compile time readonly __functionBrand: ( event: PutEventInput<Evnt>, ...events: PutEventInput<Evnt>[] ) => void; constructor(readonly resource: aws_events.IEventBus) { this.eventBusName = resource.eventBusName; this.eventBusArn = resource.eventBusArn; // Closure event bus base const eventBusName = this.eventBusName; this.putEvents = makeIntegration< "EventBus.putEvents", IEventBus<Evnt>["putEvents"] >({ kind: "EventBus.putEvents", asl: (call: CallExpr, context: ASL) => { this.resource.grantPutEventsTo(context.role); // Validate that the events are object literals. // Then normalize nested arrays of events into a single list of events. // TODO Relax these restrictions: https://github.com/functionless/functionless/issues/101 const eventObjs = call.args.reduce( (events: ObjectLiteralExpr[], arg) => { if (isArrayLiteralExpr(arg.expr)) { if (!arg.expr.items.every(isObjectLiteralExpr)) { throw Error( "Event Bus put events must use inline object parameters. Variable references are not supported currently." ); } return [...events, ...arg.expr.items]; } else if (isObjectLiteralExpr(arg.expr)) { return [...events, arg.expr]; } throw Error( "Event Bus put events must use inline object parameters. Variable references are not supported currently." ); }, [] ); // The interface should prevent this. if (eventObjs.length === 0) { throw Error("Must provide at least one event."); } const propertyMap: Record<keyof Event, string> = { "detail-type": "DetailType", account: "Account", detail: "Detail", id: "Id", region: "Region", resources: "Resources", source: "Source", time: "Time", version: "Version", }; const events = eventObjs.map((event) => { const props = event.properties.filter( ( e ): e is PropAssignExpr & { name: StringLiteralExpr | Identifier; } => !(isSpreadAssignExpr(e) || isComputedPropertyNameExpr(e.name)) ); if (props.length < event.properties.length) { throw Error( "Event Bus put events must use inline objects instantiated without computed or spread keys." ); } return ( props .map( (prop) => [ isIdentifier(prop.name) ? prop.name.name : prop.name.value, prop.expr, ] as const ) .filter( (x): x is [keyof typeof propertyMap, Expr] => x[0] in propertyMap && !!x[1] ) /** * Build the parameter payload for an event entry. * All members must be in Pascal case. */ .reduce( (acc: Record<string, string>, [name, expr]) => ({ ...acc, [propertyMap[name]]: ASL.toJson(expr), }), { EventBusName: this.resource.eventBusArn } ) ); }); return { Resource: "arn:aws:states:::events:putEvents", Type: "Task" as const, Parameters: { Entries: events, }, }; }, native: { bind: (context: Function<any, any>) => { this.resource.grantPutEventsTo(context.resource); }, preWarm: (prewarmContext: NativePreWarmContext) => { prewarmContext.getOrInit(PrewarmClients.EVENT_BRIDGE); }, call: async (args, preWarmContext) => { const eventBridge = preWarmContext.getOrInit( PrewarmClients.EVENT_BRIDGE ); await eventBridge .putEvents({ Entries: args.map((event) => ({ Detail: JSON.stringify(event.detail), EventBusName: eventBusName, DetailType: event["detail-type"], Resources: event.resources, Source: event.source, Time: typeof event.time === "number" ? new Date(event.time) : undefined, })), }) .promise(); }, }, }); } public readonly eventBus = makeEventBusIntegration< PutEventInput<Evnt>, aws_events_targets.EventBusProps | undefined >({ target: (props, targetInput?) => { if (targetInput) { throw new Error("Event bus rule target does not support target input."); } return new aws_events_targets.EventBus(this.resource, props); }, }); /** * @inheritDoc * * @typeParam InEvnt - The type the {@link Rule} matches. Covariant of output {@link OutEvnt}. * @typeParam NewEvnt - The type the predicate narrows to, a sub-type of {@link InEvnt}. */ public when<InEvnt extends OutEvnt, NewEvnt extends InEvnt>( id: string, predicate: RulePredicateFunction<InEvnt, NewEvnt> ): Rule<InEvnt, NewEvnt>; public when<InEvnt extends OutEvnt, NewEvnt extends InEvnt>( scope: Construct, id: string, predicate: RulePredicateFunction<InEvnt, NewEvnt> ): Rule<InEvnt, NewEvnt>; public when<InEvnt extends OutEvnt, NewEvnt extends InEvnt>( scope: Construct | string, id?: string | RulePredicateFunction<InEvnt, NewEvnt>, predicate?: RulePredicateFunction<InEvnt, NewEvnt> ): Rule<InEvnt, NewEvnt> { if (predicate) { return new Rule<InEvnt, NewEvnt>( scope as Construct, id as string, this as any, predicate ); } else { return new Rule<InEvnt, NewEvnt>( this.resource, scope as string, this as any, id as RulePredicateFunction<InEvnt, NewEvnt> ); } } public all(): PredicateRuleBase<Evnt, OutEvnt>; public all(scope: Construct, id: string): PredicateRuleBase<Evnt, OutEvnt>; public all(scope?: Construct, id?: string): PredicateRuleBase<Evnt, OutEvnt> { if (!scope || !id) { if (!this.allRule) { this.allRule = new PredicateRuleBase<Evnt, OutEvnt>( this.resource, "all", this as IEventBus<Evnt>, // an empty doc will be converted to `{ source: [{ prefix: "" }]}` { doc: {} } ); } return this.allRule; } return new PredicateRuleBase<Evnt, OutEvnt>( scope, id, this as IEventBus<Evnt>, { doc: {}, } ); } } export type PutEventInput<Evnt extends Event> = Partial<Evnt> & Pick<Evnt, "detail" | "source" | "detail-type">; /** * A Functionless wrapper for a AWS CDK {@link aws_events.EventBus}. * * Wrap your {@link aws_events.EventBus} instance with this class, * specify a type to represent the events passing through the EventBus, * and then use the .when, .map and .pipe functions to express * EventBus Event Patterns and Targets Inputs with native TypeScript syntax. * * Filtering events and sending them to Lambda. * * ```ts * interface Payload { * value: string; * } * * // An event with the payload * interface myEvent extends Event<Payload> {} * * // A function that expects the payload. * const myLambdaFunction = new functionless.Function<Payload, void>(this, 'myFunction', ...); * * // instantiate an aws_events.EventBus Construct * const awsBus = new aws_events.EventBus(this, "mybus"); * * // Wrap the aws_events.EventBus with the functionless.EventBus * new functionless.EventBus<myEvent>(awsBus) * // when the payload is equal to some value * .when(this, 'rule1', event => event.detail.value === "some value") * // grab the payload * .map(event => event.detail) * // send to the function * .pipe(myLambdaFunction); * ``` * * Forwarding to another Event Bus based on some predicate: * * ```ts * // Using an imported event bus * const anotherEventBus = aws_event.EventBus.fromEventBusArn(...); * * new functionless.EventBus<myEvent>(awsBus) * // when the payload is equal to some value * .when(this, 'rule2', event => event.detail.value === "some value") * // send verbatim to the other event bus * .pipe(anotherEventBus); * ``` * * @typeParam Evnt - the union type of events that this EventBus can accept. * `Evnt` is the contravariant version of `OutEvnt` in that * the bus will accept any of `Evnt` while the EventBus can * emit any of `OutEvnt`. * @typeParam OutEvnt - the union type of events that this EventBus will emit through rules. * `OutEvnt` is the covariant version of `Evnt` in that * the bus will emit any of `OutEvnt` while the EventBus can * can accept any of `Evnt`. This type parameter should be left * empty to be inferred. ex: `EventBus<Event<Detail1> | Event<Detail2>>`. */ export class EventBus< in Evnt extends Event, out OutEvnt extends Evnt = Evnt > extends EventBusBase<Evnt, OutEvnt> { constructor(scope: Construct, id: string, props?: aws_events.EventBusProps) { super(new aws_events.EventBus(scope, id, props)); } /** * Import an {@link aws_events.IEventBus} wrapped with Functionless abilities. * * @typeParam Evnt - the union of types which are expected on the default {@link EventBus}. */ public static fromBus<Evnt extends Event>( bus: aws_events.IEventBus ): IEventBus<Evnt> { return new ImportedEventBus<Evnt>(bus); } /** * Retrieves the default event bus as a singleton on the given stack or the stack of the given construct. * * Equivalent to doing * ```ts * const awsBus = aws_events.EventBus.fromEventBusName(Stack.of(scope), id, "default"); * new functionless.EventBus.fromBus(awsBus); * ``` * * @typeParam Evnt - the union of types which are expected on the default {@link EventBus}. */ public static default<Evnt extends Event>( stack: Stack ): DefaultEventBus<Evnt>; public static default<Evnt extends Event>( scope: Construct ): DefaultEventBus<Evnt>; public static default<Evnt extends Event>( scope: Construct | Stack ): DefaultEventBus<Evnt> { return new DefaultEventBus<Evnt>(scope); } /** * Creates a schedule based event bus rule on the default bus. * * Always sends the {@link ScheduledEvent} event. * * ```ts * // every hour * const everyHour = EventBus.schedule(scope, 'cron', aws_events.Schedule.rate(Duration.hours(1))); * * const func = new Function(scope, 'func', async (payload: {id: string}) => console.log(payload.id)); * * everyHour * .map(event => ({id: event.id})) * .pipe(func); * ``` */ public static schedule( scope: Construct, id: string, schedule: aws_events.Schedule, props?: Omit< aws_events.RuleProps, "schedule" | "eventBus" | "eventPattern" | "targets" > ): ImportedRule<ScheduledEvent> { return EventBus.default(scope).schedule(scope, id, schedule, props); } } /** * @typeParam Evnt - the union type of events that this EventBus can accept. * `Evnt` is the contravariant version of `OutEvnt` in that * the bus will accept any of `Evnt` while the EventBus can * emit any of `OutEvnt`. * @typeParam OutEvnt - the union type of events that this EventBus will emit through rules. * `OutEvnt` is the covariant version of `Evnt` in that * the bus will emit any of `OutEvnt` while the EventBus can * can accept any of `Evnt`. This type parameter should be left * empty to be inferred. ex: `EventBus<Event<Detail1> | Event<Detail2>>`. */ export class DefaultEventBus< in Evnt extends Event, out OutEvnt extends Evnt = Evnt > extends EventBusBase<Evnt, OutEvnt> { constructor(scope: Construct) { const stack = scope instanceof Stack ? scope : Stack.of(scope); const bus = (stack.node.tryFindChild( EventBusBase.singletonDefaultNode ) as aws_events.IEventBus) ?? aws_events.EventBus.fromEventBusName( stack, EventBusBase.singletonDefaultNode, "default" ); super(bus); } /** * Creates a schedule based event bus rule on the default bus. * * Always sends the {@link ScheduledEvent} event. * * ```ts * const bus = EventBus.default(scope); * // every hour * const everyHour = bus.schedule(scope, 'cron', aws_events.Schedule.rate(Duration.hours(1))); * * const func = new Function(scope, 'func', async (payload: {id: string}) => console.log(payload.id)); * * everyHour * .map(event => ({id: event.id})) * .pipe(func); * ``` */ public schedule( scope: Construct, id: string, schedule: aws_events.Schedule, props?: Omit< aws_events.RuleProps, "schedule" | "eventBus" | "eventPattern" | "targets" > ): ImportedRule<ScheduledEvent> { return new ImportedRule<ScheduledEvent>( new aws_events.Rule(scope, id, { ...props, schedule, }) ); } } /** * @typeParam Evnt - the union type of events that this EventBus can accept. * `Evnt` is the contravariant version of `OutEvnt` in that * the bus will accept any of `Evnt` while the EventBus can * emit any of `OutEvnt`. * @typeParam OutEvnt - the union type of events that this EventBus will emit through rules. * `OutEvnt` is the covariant version of `Evnt` in that * the bus will emit any of `OutEvnt` while the EventBus can * can accept any of `Evnt`. This type parameter should be left * empty to be inferred. ex: `EventBus<Event<Detail1> | Event<Detail2>>`. */ class ImportedEventBus< in Evnt extends Event, out OutEvnt extends Evnt = Evnt > extends EventBusBase<Evnt, OutEvnt> { constructor(bus: aws_events.IEventBus) { super(bus); } } /** * Defines an integration that can be used in the `pipe` function of an {@link EventBus} (Rule or Transform). * * ```ts * const myEbIntegration = { // an Integration * kind: 'myEbIntegration', * eventBus: { * target: (props, targetInput) => { * // return a RuleTarget * } * } * } * * new EventBus().when("rule", () => true).pipe(myEbIntegration); * ``` * * @typeParam - Payload - the type which the {@link Integration} expects as an input from {@link EventBus}. * @typeParam - Props - the optional properties the {@link Integration} accepts. Leave undefined to require no properties. */ export interface EventBusTargetIntegration< // the payload type we expect to be transformed into before making this call. in Payload, in Props extends object | undefined = undefined > { /** * {@link EventBusTargetIntegration} does not make direct use of `P`. Typescript will ignore P when * doing type checking. By making the interface look like there is a property which is of type P, * typescript will consider P when type checking. * * This is useful for cases like {@link IRule.pipe} and {@link IEventTransform.pipe} which need to validate that * an integration implements the right EventBus integration. * * We use a function interface in order to satisfy the covariant relationship that we expect the super-P in as opposed to * returning sub-P. */ __payloadBrand: (p: Payload) => void; /** * Method called when an integration is passed to EventBus's `.pipe` function. * * @returns a IRuleTarget that makes use of the props and optional target input. * @internal */ target: ( props: Props, targetInput?: aws_events.RuleTargetInput ) => aws_events.IRuleTarget; } export type IntegrationWithEventBus< Payload, Props extends object | undefined = undefined > = Integration<string, AnyFunction, EventBusTargetIntegration<Payload, Props>>; /** * @typeParam - Payload - the type which the {@link Integration} expects as an input from {@link EventBus}. * @typeParam - Props - the optional properties the {@link Integration} accepts. Leave undefined to require no properties. */ export function makeEventBusIntegration< Payload, Props extends object | undefined = undefined >( integration: Omit<EventBusTargetIntegration<Payload, Props>, "__payloadBrand"> ) { return integration as EventBusTargetIntegration<Payload, Props>; } export type DynamicProps<Props extends object | undefined> = Props extends object ? (props: Props) => void : (props?: Props) => void; /** * Add a target to the run based on the configuration given. */ export function pipe< Evnt extends Event, Payload, Props extends object | undefined = undefined, Target extends aws_events.RuleTargetInput | undefined = | aws_events.RuleTargetInput | undefined >( rule: IRule<Evnt>, integration: | IntegrationWithEventBus<Payload, Props> | ((targetInput: Target) => aws_events.IRuleTarget), props: Props, targetInput: Target ) { if (isIntegration<IntegrationWithEventBus<Payload, Props>>(integration)) { const target = new IntegrationImpl(integration).eventBus.target( props, targetInput ); return rule.resource.addTarget(target); } else { return rule.resource.addTarget(integration(targetInput)); } }
the_stack
import { BarcodeGenerator } from "../../../src/barcode/barcode"; import { createElement } from "@syncfusion/ej2-base"; let barcode: BarcodeGenerator; let ele: HTMLElement; describe('Code128 - Barcode', () => { describe('checking Code128 barcode rendering all lines check', () => { //let barcode: BarcodeGenerator; //let barcode: BarcodeGenerator; beforeAll((): void => { ele = createElement('div', { id: 'barcode128' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '414px', height: '150px', type: 'Code128', value: '1122abcdEFGH11223344', mode: 'SVG' }); barcode.appendTo('#barcode128'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); var output1 = { 0: { width: "3.73", height: "116.50", x: 10, y: 10 }, 1: { width: "1.87", height: "116.50", x: 16, y: 10 }, 2: { width: "5.60", height: "116.50", x: 21, y: 10 }, 3: { width: "3.73", height: "116.50", x: 31, y: 10 }, 4: { width: "1.87", height: "116.50", x: 40, y: 10 }, 5: { width: "1.87", height: "116.50", x: 45, y: 10 }, 6: { width: "3.73", height: "116.50", x: 51, y: 10 }, 7: { width: "5.60", height: "116.50", x: 59, y: 10 }, 8: { width: "1.87", height: "116.50", x: 66, y: 10 }, 9: { width: "1.87", height: "116.50", x: 72, y: 10 }, 10: { width: "7.47", height: "116.50", x: 75, y: 10 }, 11: { width: "5.60", height: "116.50", x: 85, y: 10 }, 12: { width: "1.87", height: "116.50", x: 92, y: 10 }, 13: { width: "1.87", height: "116.50", x: 98, y: 10 }, 14: { width: "3.73", height: "116.50", x: 101, y: 10 }, 15: { width: "1.87", height: "116.50", x: 113, y: 10 }, 16: { width: "1.87", height: "116.50", x: 118, y: 10 }, 17: { width: "3.73", height: "116.50", x: 128, y: 10 }, 18: { width: "1.87", height: "116.50", x: 133, y: 10 }, 19: { width: "1.87", height: "116.50", x: 143, y: 10 }, 20: { width: "3.73", height: "116.50", x: 146, y: 10 }, 21: { width: "1.87", height: "116.50", x: 154, y: 10 }, 22: { width: "1.87", height: "116.50", x: 163, y: 10 }, 23: { width: "3.73", height: "116.50", x: 169, y: 10 }, 24: { width: "1.87", height: "116.50", x: 174, y: 10 }, 25: { width: "3.73", height: "116.50", x: 182, y: 10 }, 26: { width: "1.87", height: "116.50", x: 187, y: 10 }, 27: { width: "1.87", height: "116.50", x: 195, y: 10 }, 28: { width: "3.73", height: "116.50", x: 202, y: 10 }, 29: { width: "1.87", height: "116.50", x: 212, y: 10 }, 30: { width: "3.73", height: "116.50", x: 215, y: 10 }, 31: { width: "1.87", height: "116.50", x: 221, y: 10 }, 32: { width: "1.87", height: "116.50", x: 228, y: 10 }, 33: { width: "3.73", height: "116.50", x: 236, y: 10 }, 34: { width: "1.87", height: "116.50", x: 245, y: 10 }, 35: { width: "1.87", height: "116.50", x: 249, y: 10 }, 36: { width: "1.87", height: "116.50", x: 256, y: 10 }, 37: { width: "5.60", height: "116.50", x: 260, y: 10 }, 38: { width: "7.47", height: "116.50", x: 268, y: 10 }, 39: { width: "3.73", height: "116.50", x: 277, y: 10 }, 40: { width: "1.87", height: "116.50", x: 286, y: 10 }, 41: { width: "1.87", height: "116.50", x: 292, y: 10 }, 42: { width: "3.73", height: "116.50", x: 298, y: 10 }, 43: { width: "5.60", height: "116.50", x: 305, y: 10 }, 44: { width: "1.87", height: "116.50", x: 313, y: 10 }, 45: { width: "1.87", height: "116.50", x: 318, y: 10 }, 46: { width: "1.87", height: "116.50", x: 322, y: 10 }, 47: { width: "3.73", height: "116.50", x: 329, y: 10 }, 48: { width: "1.87", height: "116.50", x: 339, y: 10 }, 49: { width: "3.73", height: "116.50", x: 346, y: 10 }, 50: { width: "5.60", height: "116.50", x: 352, y: 10 }, 51: { width: "5.60", height: "116.50", x: 359, y: 10 }, 52: { width: "1.87", height: "116.50", x: 367, y: 10 }, 53: { width: "3.73", height: "116.50", x: 370, y: 10 }, 54: { width: "3.73", height: "116.50", x: 380, y: 10 }, 55: { width: "5.60", height: "116.50", x: 389, y: 10 }, 56: { width: "1.87", height: "116.50", x: 397, y: 10 }, 57: { width: "3.73", height: "116.50", x: 400, y: 10 }, }; it('checking Code128 barcode rendering with display text margin and barcode margin', (done: Function) => { let barcode = document.getElementById('barcode128') let children: HTMLElement = barcode.children[0] as HTMLElement expect((Math.round(Number(children.children[0].getAttribute('x'))) === 87) && (children.children[0] as HTMLElement).style.fontSize === '20px').toBe(true); for (let j: number = 1; j < children.children.length - 1; j++) { expect(Math.round(Number(children.children[j + 1].getAttribute('x'))) === output1[j].x && Math.round(Number(children.children[j + 1].getAttribute('y'))) === output1[j].y && parseFloat((children.children[j + 1].getAttribute('width'))).toFixed(2) === output1[j].width && parseFloat((children.children[j + 1].getAttribute('height'))).toFixed(2) === output1[j].height).toBe(true); } done(); }); }); describe('checking Code128 barcode rendering all lines check', () => { //let barcode: BarcodeGenerator; //let barcode: BarcodeGenerator; beforeAll((): void => { ele = createElement('div', { id: 'barcode128' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '414px', height: '150px', type: 'Code128', value: '!@#$%^&*()aa1122BBcC', mode: 'SVG' }); barcode.appendTo('#barcode128'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); var output1 = { 0: { width: "3.09", height: "116.50", x: 10, y: 10 }, 1: { width: "1.55", height: "116.50", x: 15, y: 10 }, 2: { width: "1.55", height: "116.50", x: 19, y: 10 }, 3: { width: "3.09", height: "116.50", x: 27, y: 10 }, 4: { width: "3.09", height: "116.50", x: 33, y: 10 }, 5: { width: "3.09", height: "116.50", x: 38, y: 10 }, 6: { width: "3.09", height: "116.50", x: 44, y: 10 }, 7: { width: "3.09", height: "116.50", x: 52, y: 10 }, 8: { width: "3.09", height: "116.50", x: 56, y: 10 }, 9: { width: "1.55", height: "116.50", x: 61, y: 10 }, 10: { width: "1.55", height: "116.50", x: 66, y: 10 }, 11: { width: "3.09", height: "116.50", x: 70, y: 10 }, 12: { width: "1.55", height: "116.50", x: 78, y: 10 }, 13: { width: "1.55", height: "116.50", x: 83, y: 10 }, 14: { width: "3.09", height: "116.50", x: 89, y: 10 }, 15: { width: "1.55", height: "116.50", x: 95, y: 10 }, 16: { width: "1.55", height: "116.50", x: 101, y: 10 }, 17: { width: "3.09", height: "116.50", x: 106, y: 10 }, 18: { width: "6.18", height: "116.50", x: 112, y: 10 }, 19: { width: "1.55", height: "116.50", x: 123, y: 10 }, 20: { width: "1.55", height: "116.50", x: 126, y: 10 }, 21: { width: "1.55", height: "116.50", x: 129, y: 10 }, 22: { width: "3.09", height: "116.50", x: 134, y: 10 }, 23: { width: "1.55", height: "116.50", x: 140, y: 10 }, 24: { width: "3.09", height: "116.50", x: 146, y: 10 }, 25: { width: "1.55", height: "116.50", x: 152, y: 10 }, 26: { width: "1.55", height: "116.50", x: 158, y: 10 }, 27: { width: "1.55", height: "116.50", x: 163, y: 10 }, 28: { width: "3.09", height: "116.50", x: 169, y: 10 }, 29: { width: "1.55", height: "116.50", x: 175, y: 10 }, 30: { width: "3.09", height: "116.50", x: 180, y: 10 }, 31: { width: "1.55", height: "116.50", x: 186, y: 10 }, 32: { width: "1.55", height: "116.50", x: 191, y: 10 }, 33: { width: "1.55", height: "116.50", x: 197, y: 10 }, 34: { width: "1.55", height: "116.50", x: 202, y: 10 }, 35: { width: "3.09", height: "116.50", x: 205, y: 10 }, 36: { width: "1.55", height: "116.50", x: 214, y: 10 }, 37: { width: "1.55", height: "116.50", x: 219, y: 10 }, 38: { width: "3.09", height: "116.50", x: 222, y: 10 }, 39: { width: "1.55", height: "116.50", x: 231, y: 10 }, 40: { width: "4.64", height: "116.50", x: 234, y: 10 }, 41: { width: "6.18", height: "116.50", x: 240, y: 10 }, 42: { width: "3.09", height: "116.50", x: 248, y: 10 }, 43: { width: "1.55", height: "116.50", x: 256, y: 10 }, 44: { width: "1.55", height: "116.50", x: 260, y: 10 }, 45: { width: "3.09", height: "116.50", x: 265, y: 10 }, 46: { width: "4.64", height: "116.50", x: 271, y: 10 }, 47: { width: "1.55", height: "116.50", x: 277, y: 10 }, 48: { width: "1.55", height: "116.50", x: 282, y: 10 }, 49: { width: "6.18", height: "116.50", x: 285, y: 10 }, 50: { width: "4.64", height: "116.50", x: 293, y: 10 }, 51: { width: "1.55", height: "116.50", x: 299, y: 10 }, 52: { width: "1.55", height: "116.50", x: 305, y: 10 }, 53: { width: "3.09", height: "116.50", x: 308, y: 10 }, 54: { width: "1.55", height: "116.50", x: 316, y: 10 }, 55: { width: "1.55", height: "116.50", x: 322, y: 10 }, 56: { width: "3.09", height: "116.50", x: 325, y: 10 }, 57: { width: "1.55", height: "116.50", x: 333, y: 10 }, 58: { width: "1.55", height: "116.50", x: 341, y: 10 }, 59: { width: "3.09", height: "116.50", x: 344, y: 10 }, 60: { width: "1.55", height: "116.50", x: 350, y: 10 }, 61: { width: "1.55", height: "116.50", x: 356, y: 10 }, 62: { width: "3.09", height: "116.50", x: 362, y: 10 }, 63: { width: "1.55", height: "116.50", x: 367, y: 10 }, 64: { width: "4.64", height: "116.50", x: 370, y: 10 }, 65: { width: "3.09", height: "116.50", x: 379, y: 10 }, 66: { width: "3.09", height: "116.50", x: 384, y: 10 }, 67: { width: "4.64", height: "116.50", x: 392, y: 10 }, 68: { width: "1.55", height: "116.50", x: 398, y: 10 }, 69: { width: "3.09", height: "116.50", x: 401, y: 10 }, }; it('checking Code128 barcode rendering with display text margin and barcode margin', (done: Function) => { let barcode = document.getElementById('barcode128') let children: HTMLElement = barcode.children[0] as HTMLElement expect((Math.round(Number(children.children[0].getAttribute('x'))) === 87) && (children.children[0] as HTMLElement).style.fontSize === '20px').toBe(true); for (let j: number = 1; j < children.children.length - 1; j++) { expect(Math.round(Number(children.children[j + 1].getAttribute('x'))) === output1[j].x && Math.round(Number(children.children[j + 1].getAttribute('y'))) === output1[j].y && parseFloat((children.children[j + 1].getAttribute('width'))).toFixed(2) === output1[j].width && parseFloat((children.children[j + 1].getAttribute('height'))).toFixed(2) === output1[j].height).toBe(true); } done(); }); }); describe('checking Code128 barcode rendering all lines check', () => { //let barcode: BarcodeGenerator; //let barcode: BarcodeGenerator; beforeAll((): void => { ele = createElement('div', { id: 'barcode1283' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '414px', height: '150px', type: 'Code128', value: '!@#$%^&*()aa1122BBcC', mode: 'SVG' }); barcode.appendTo('#barcode1283'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); var output1 = { 0: {width: "3.09", height: "116.50", x: 10, y: 10}, 1: {width: "1.55", height: "116.50", x: 15, y: 10}, 2: {width: "1.55", height: "116.50", x: 19, y: 10}, 3: {width: "3.09", height: "116.50", x: 27, y: 10}, 4: {width: "3.09", height: "116.50", x: 33, y: 10}, 5: {width: "3.09", height: "116.50", x: 38, y: 10}, 6: {width: "3.09", height: "116.50", x: 44, y: 10}, 7: {width: "3.09", height: "116.50", x: 52, y: 10}, 8: {width: "3.09", height: "116.50", x: 56, y: 10}, 9: {width: "1.55", height: "116.50", x: 61, y: 10}, 10: {width: "1.55", height: "116.50", x: 66, y: 10}, 11: {width: "3.09", height: "116.50", x: 70, y: 10}, 12: {width: "1.55", height: "116.50", x: 78, y: 10}, 13: {width: "1.55", height: "116.50", x: 83, y: 10}, 14: {width: "3.09", height: "116.50", x: 89, y: 10}, 15: {width: "1.55", height: "116.50", x: 95, y: 10}, 16: {width: "1.55", height: "116.50", x: 101, y: 10}, 17: {width: "3.09", height: "116.50", x: 106, y: 10}, 18: {width: "6.18", height: "116.50", x: 112, y: 10}, 19: {width: "1.55", height: "116.50", x: 123, y: 10}, 20: {width: "1.55", height: "116.50", x: 126, y: 10}, 21: {width: "1.55", height: "116.50", x: 129, y: 10}, 22: {width: "3.09", height: "116.50", x: 134, y: 10}, 23: {width: "1.55", height: "116.50", x: 140, y: 10}, 24: {width: "3.09", height: "116.50", x: 146, y: 10}, 25: {width: "1.55", height: "116.50", x: 152, y: 10}, 26: {width: "1.55", height: "116.50", x: 158, y: 10}, 27: {width: "1.55", height: "116.50", x: 163, y: 10}, 28: {width: "3.09", height: "116.50", x: 169, y: 10}, 29: {width: "1.55", height: "116.50", x: 175, y: 10}, 30: {width: "3.09", height: "116.50", x: 180, y: 10}, 31: {width: "1.55", height: "116.50", x: 186, y: 10}, 32: {width: "1.55", height: "116.50", x: 191, y: 10}, 33: {width: "1.55", height: "116.50", x: 197, y: 10}, 34: {width: "1.55", height: "116.50", x: 202, y: 10}, 35: {width: "3.09", height: "116.50", x: 205, y: 10}, 36: {width: "1.55", height: "116.50", x: 214, y: 10}, 37: {width: "1.55", height: "116.50", x: 219, y: 10}, 38: {width: "3.09", height: "116.50", x: 222, y: 10}, 39: {width: "1.55", height: "116.50", x: 231, y: 10}, 40: {width: "4.64", height: "116.50", x: 234, y: 10}, 41: {width: "6.18", height: "116.50", x: 240, y: 10}, 42: {width: "3.09", height: "116.50", x: 248, y: 10}, 43: {width: "1.55", height: "116.50", x: 256, y: 10}, 44: {width: "1.55", height: "116.50", x: 260, y: 10}, 45: {width: "3.09", height: "116.50", x: 265, y: 10}, 46: {width: "4.64", height: "116.50", x: 271, y: 10}, 47: {width: "1.55", height: "116.50", x: 277, y: 10}, 48: {width: "1.55", height: "116.50", x: 282, y: 10}, 49: {width: "6.18", height: "116.50", x: 285, y: 10}, 50: {width: "4.64", height: "116.50", x: 293, y: 10}, 51: {width: "1.55", height: "116.50", x: 299, y: 10}, 52: {width: "1.55", height: "116.50", x: 305, y: 10}, 53: {width: "3.09", height: "116.50", x: 308, y: 10}, 54: {width: "1.55", height: "116.50", x: 316, y: 10}, 55: {width: "1.55", height: "116.50", x: 322, y: 10}, 56: {width: "3.09", height: "116.50", x: 325, y: 10}, 57: {width: "1.55", height: "116.50", x: 333, y: 10}, 58: {width: "1.55", height: "116.50", x: 341, y: 10}, 59: {width: "3.09", height: "116.50", x: 344, y: 10}, 60: {width: "1.55", height: "116.50", x: 350, y: 10}, 61: {width: "1.55", height: "116.50", x: 356, y: 10}, 62: {width: "3.09", height: "116.50", x: 362, y: 10}, 63: {width: "1.55", height: "116.50", x: 367, y: 10}, 64: {width: "4.64", height: "116.50", x: 370, y: 10}, 65: {width: "3.09", height: "116.50", x: 379, y: 10}, 66: {width: "3.09", height: "116.50", x: 384, y: 10}, 67: {width: "4.64", height: "116.50", x: 392, y: 10}, 68: {width: "1.55", height: "116.50", x: 398, y: 10}, 69: {width: "3.09", height: "116.50", x: 401, y: 10}, }; it('checking Code128 barcode rendering with display text margin and barcode margin', (done: Function) => { let barcode = document.getElementById('barcode1283') let children: HTMLElement = barcode.children[0] as HTMLElement expect((Math.round(Number(children.children[0].getAttribute('x'))) === 87) && (children.children[0] as HTMLElement).style.fontSize === '20px').toBe(true); for (let j: number = 1; j < children.children.length - 1; j++) { expect(Math.round(Number(children.children[j + 1].getAttribute('x'))) === output1[j].x && Math.round(Number(children.children[j + 1].getAttribute('y'))) === output1[j].y && parseFloat((children.children[j + 1].getAttribute('width'))).toFixed(2) === output1[j].width && parseFloat((children.children[j + 1].getAttribute('height'))).toFixed(2) === output1[j].height).toBe(true); } done(); }); }); describe('checking Code128 barcode rendering invalid character', () => { //let barcode: BarcodeGenerator; //let barcode: BarcodeGenerator; beforeAll((): void => { ele = createElement('div', { id: 'barcode1283' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '414px', height: '150px', type: 'Code128', value: 'ÃÃ', mode: 'SVG' }); barcode.appendTo('#barcode1283'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('checking Code128 barcode rendering with display text margin and barcode margin', (done: Function) => { done(); }); }); });
the_stack
import { expect } from 'chai'; import debug from 'debug'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: No types available import TCP from 'libp2p-tcp'; import { makeLogFileName, NimWaku, NOISE_KEY_1, NOISE_KEY_2, } from '../../test_utils'; import { delay } from '../delay'; import { Waku } from '../waku'; import { WakuMessage } from '../waku_message'; import { generatePrivateKey, generateSymmetricKey, getPublicKey, } from '../waku_message/version_1'; import { PageDirection } from './history_rpc'; const dbg = debug('waku:test:store'); const TestContentTopic = '/test/1/waku-store/utf8'; describe('Waku Store', () => { let waku: Waku; let nimWaku: NimWaku; afterEach(async function () { nimWaku ? nimWaku.stop() : null; waku ? await waku.stop() : null; }); it('Retrieves history', async function () { this.timeout(5_000); nimWaku = new NimWaku(makeLogFileName(this)); await nimWaku.start({ persistMessages: true }); for (let i = 0; i < 2; i++) { expect( await nimWaku.sendMessage( await WakuMessage.fromUtf8String(`Message ${i}`, TestContentTopic) ) ).to.be.true; } waku = await Waku.create({ staticNoiseKey: NOISE_KEY_1, libp2p: { modules: { transport: [TCP] } }, }); await waku.dial(await nimWaku.getMultiaddrWithId()); // Wait for identify protocol to finish await new Promise((resolve) => { waku.libp2p.peerStore.once('change:protocols', resolve); }); const messages = await waku.store.queryHistory([]); expect(messages?.length).eq(2); const result = messages?.findIndex((msg) => { return msg.payloadAsUtf8 === 'Message 0'; }); expect(result).to.not.eq(-1); }); it('Retrieves history using callback', async function () { this.timeout(5_000); nimWaku = new NimWaku(makeLogFileName(this)); await nimWaku.start({ persistMessages: true }); const totalMsgs = 20; for (let i = 0; i < totalMsgs; i++) { expect( await nimWaku.sendMessage( await WakuMessage.fromUtf8String(`Message ${i}`, TestContentTopic) ) ).to.be.true; } waku = await Waku.create({ staticNoiseKey: NOISE_KEY_1, libp2p: { modules: { transport: [TCP] } }, }); await waku.dial(await nimWaku.getMultiaddrWithId()); // Wait for identify protocol to finish await new Promise((resolve) => { waku.libp2p.peerStore.once('change:protocols', resolve); }); let messages: WakuMessage[] = []; await waku.store.queryHistory([], { callback: (_msgs) => { messages = messages.concat(_msgs); }, }); expect(messages?.length).eq(totalMsgs); const result = messages?.findIndex((msg) => { return msg.payloadAsUtf8 === 'Message 0'; }); expect(result).to.not.eq(-1); }); it('Retrieval aborts when callback returns true', async function () { this.timeout(5_000); nimWaku = new NimWaku(makeLogFileName(this)); await nimWaku.start({ persistMessages: true }); const availMsgs = 20; for (let i = 0; i < availMsgs; i++) { expect( await nimWaku.sendMessage( await WakuMessage.fromUtf8String(`Message ${i}`, TestContentTopic) ) ).to.be.true; } waku = await Waku.create({ staticNoiseKey: NOISE_KEY_1, libp2p: { modules: { transport: [TCP] } }, }); await waku.dial(await nimWaku.getMultiaddrWithId()); // Wait for identify protocol to finish await new Promise((resolve) => { waku.libp2p.peerStore.once('change:protocols', resolve); }); let messages: WakuMessage[] = []; const desiredMsgs = 14; await waku.store.queryHistory([], { pageSize: 7, callback: (_msgs) => { messages = messages.concat(_msgs); return messages.length >= desiredMsgs; }, }); expect(messages?.length).eq(desiredMsgs); }); it('Retrieves all historical elements in chronological order through paging', async function () { this.timeout(5_000); nimWaku = new NimWaku(makeLogFileName(this)); await nimWaku.start({ persistMessages: true }); for (let i = 0; i < 15; i++) { expect( await nimWaku.sendMessage( await WakuMessage.fromUtf8String(`Message ${i}`, TestContentTopic) ) ).to.be.true; } waku = await Waku.create({ staticNoiseKey: NOISE_KEY_1, libp2p: { modules: { transport: [TCP] } }, }); await waku.dial(await nimWaku.getMultiaddrWithId()); // Wait for identify protocol to finish await new Promise((resolve) => { waku.libp2p.peerStore.once('change:protocols', resolve); }); const messages = await waku.store.queryHistory([], { pageDirection: PageDirection.FORWARD, }); expect(messages?.length).eq(15); for (let index = 0; index < 2; index++) { expect( messages?.findIndex((msg) => { return msg.payloadAsUtf8 === `Message ${index}`; }) ).to.eq(index); } }); it('Retrieves history using custom pubsub topic', async function () { this.timeout(5_000); const customPubSubTopic = '/waku/2/custom-dapp/proto'; nimWaku = new NimWaku(makeLogFileName(this)); await nimWaku.start({ persistMessages: true, topics: customPubSubTopic }); for (let i = 0; i < 2; i++) { expect( await nimWaku.sendMessage( await WakuMessage.fromUtf8String(`Message ${i}`, TestContentTopic), customPubSubTopic ) ).to.be.true; } waku = await Waku.create({ pubSubTopic: customPubSubTopic, staticNoiseKey: NOISE_KEY_1, libp2p: { modules: { transport: [TCP] } }, }); await waku.dial(await nimWaku.getMultiaddrWithId()); // Wait for identify protocol to finish await new Promise((resolve) => { waku.libp2p.peerStore.once('change:protocols', resolve); }); const nimPeerId = await nimWaku.getPeerId(); const messages = await waku.store.queryHistory([], { peerId: nimPeerId, }); expect(messages?.length).eq(2); const result = messages?.findIndex((msg) => { return msg.payloadAsUtf8 === 'Message 0'; }); expect(result).to.not.eq(-1); }); it('Retrieves history with asymmetric & symmetric encrypted messages', async function () { this.timeout(10_000); nimWaku = new NimWaku(makeLogFileName(this)); await nimWaku.start({ persistMessages: true, lightpush: true }); const encryptedAsymmetricMessageText = 'This message is encrypted for me using asymmetric'; const encryptedSymmetricMessageText = 'This message is encrypted for me using symmetric encryption'; const clearMessageText = 'This is a clear text message for everyone to read'; const otherEncMessageText = 'This message is not for and I must not be able to read it'; const privateKey = generatePrivateKey(); const symKey = generateSymmetricKey(); const publicKey = getPublicKey(privateKey); const [ encryptedAsymmetricMessage, encryptedSymmetricMessage, clearMessage, otherEncMessage, ] = await Promise.all([ WakuMessage.fromUtf8String( encryptedAsymmetricMessageText, TestContentTopic, { encPublicKey: publicKey, } ), WakuMessage.fromUtf8String( encryptedSymmetricMessageText, TestContentTopic, { symKey: symKey, } ), WakuMessage.fromUtf8String(clearMessageText, TestContentTopic), WakuMessage.fromUtf8String(otherEncMessageText, TestContentTopic, { encPublicKey: getPublicKey(generatePrivateKey()), }), ]); dbg('Messages have been encrypted'); const [waku1, waku2, nimWakuMultiaddr] = await Promise.all([ Waku.create({ staticNoiseKey: NOISE_KEY_1, libp2p: { modules: { transport: [TCP] } }, }), Waku.create({ staticNoiseKey: NOISE_KEY_2, libp2p: { modules: { transport: [TCP] } }, }), nimWaku.getMultiaddrWithId(), ]); dbg('Waku nodes created'); await Promise.all([ waku1.dial(nimWakuMultiaddr), waku2.dial(nimWakuMultiaddr), ]); dbg('Waku nodes connected to nim Waku'); let lightPushPeers = waku1.lightPush.peers; while (lightPushPeers.length == 0) { await delay(100); lightPushPeers = waku1.lightPush.peers; } dbg('Sending messages using light push'); await Promise.all([ waku1.lightPush.push(encryptedAsymmetricMessage), waku1.lightPush.push(encryptedSymmetricMessage), waku1.lightPush.push(otherEncMessage), waku1.lightPush.push(clearMessage), ]); let storePeers = waku2.store.peers; while (storePeers.length == 0) { await delay(100); storePeers = waku2.store.peers; } waku2.store.addDecryptionKey(symKey); dbg('Retrieve messages from store'); const messages = await waku2.store.queryHistory([], { decryptionKeys: [privateKey], }); expect(messages?.length).eq(3); if (!messages) throw 'Length was tested'; expect(messages[0].payloadAsUtf8).to.eq(clearMessageText); expect(messages[1].payloadAsUtf8).to.eq(encryptedSymmetricMessageText); expect(messages[2].payloadAsUtf8).to.eq(encryptedAsymmetricMessageText); await Promise.all([waku1.stop(), waku2.stop()]); }); it('Retrieves history using start and end time', async function () { this.timeout(5_000); nimWaku = new NimWaku(makeLogFileName(this)); await nimWaku.start({ persistMessages: true }); const startTime = new Date(); const message1Timestamp = new Date(); message1Timestamp.setTime(startTime.getTime() + 60 * 1000); const message2Timestamp = new Date(); message2Timestamp.setTime(startTime.getTime() + 2 * 60 * 1000); const messageTimestamps = [message1Timestamp, message2Timestamp]; const endTime = new Date(); endTime.setTime(startTime.getTime() + 3 * 60 * 1000); let firstMessageTime; for (let i = 0; i < 2; i++) { expect( await nimWaku.sendMessage( await WakuMessage.fromUtf8String(`Message ${i}`, TestContentTopic, { timestamp: messageTimestamps[i], }) ) ).to.be.true; if (!firstMessageTime) firstMessageTime = Date.now() / 1000; } waku = await Waku.create({ staticNoiseKey: NOISE_KEY_1, libp2p: { modules: { transport: [TCP] } }, }); await waku.dial(await nimWaku.getMultiaddrWithId()); // Wait for identify protocol to finish await new Promise((resolve) => { waku.libp2p.peerStore.once('change:protocols', resolve); }); const nimPeerId = await nimWaku.getPeerId(); const firstMessage = await waku.store.queryHistory([], { peerId: nimPeerId, timeFilter: { startTime, endTime: message1Timestamp }, }); const bothMessages = await waku.store.queryHistory([], { peerId: nimPeerId, timeFilter: { startTime, endTime, }, }); expect(firstMessage?.length).eq(1); expect(firstMessage[0]?.payloadAsUtf8).eq('Message 0'); expect(bothMessages?.length).eq(2); }); });
the_stack
import * as fs from 'fs'; import * as path from 'path'; import { Transforms, RunTestcaseOptions, InlineLists, BrowserOptions, Browser, emptyOpts } from '../types'; import * as Visit from './visit'; import * as Transform from '../transform'; import { compileToStringSync } from 'node-elm-compiler'; import * as Post from '../postprocess'; export interface Stat { name: string; bytes: number; } // Asset Sizes export const assetSizeStats = (dir: string): Stat[] => { const stats: Stat[] = []; const files = fs.readdirSync(dir); for (let i in files) { const file = files[i]; const stat = fs.statSync(path.join(dir, file)); stats.push({ name: path.basename(file), bytes: stat.size, }); } return stats; }; type Results = { assets: { [key: string]: Stat[] }; benchmarks: any; }; type BenchRunFormatted = { [key: string]: {[key: string]: { browser: Browser , tag: string | null , benchTags: string[] , status: {runsPerSecond: number, goodnessOfFit: number} , v8: V8FormattedData } } } export function reformat(results: Visit.BenchRun[]): any { let project: string = 'Unknown'; let reformed: any = {}; results.forEach((item: any) => { project = item.name; item.results.forEach((result: any) => { const newItem = { browser: item.browser, tag: item.tag, benchTags: result.tags, status: result.status, v8: reformatV8(item.v8) }; if (project in reformed) { if (result.name in reformed[project]) { reformed[project][result.name].push(newItem); } else { reformed[project][result.name] = [newItem]; } } else { reformed[project] = {}; reformed[project][result.name] = [newItem]; } }); for (const [key, value] of Object.entries(reformed[project])) { reformed[project][key].sort(sortResults); } }); return reformed; } type V8FormattedData = { uncalled: string[], optimized: string[], interpreted: string[], other: {status: string, name: string}[] memory: {name: string, representation: string[]}[] } function reformatV8(val: Visit.V8Data | null): V8FormattedData { let gathered: V8FormattedData = {uncalled: [], optimized: [], interpreted: [], other: [], memory: []} if (val == null) { return gathered } for (const key in val.fns){ if (key.startsWith("$elm_explorations$benchmark$Benchmark$") || key == "_Benchmark_operation"){ continue } const status: string = val.fns[key].status switch(status) { case 'uncalled': { gathered.uncalled.push(key) break; } case 'optimized': { gathered.optimized.push(key) break; } case 'interpreted': { gathered.interpreted.push(key) break; } default: { gathered.other.push( {status: status, name: key} ) break; } } } for (const key in val.memory){ gathered.memory.push({name: key, representation: v8MemoryDescription(val.memory[key]) }) } return gathered } function v8MemoryDescription(representation: Visit.Memory): string[] { let descriptors = [] for (const key in representation){ if (representation[key]) { descriptors.push(key) } } return descriptors } function sortResults(a: any, b: any) { if (a.browser == b.browser) { if (a.tag == null) { return -1; } else if (b.tag == null) { return 1; } else if (a.tag == 'final') { return -1; } else if (b.tag == 'final') { return 1; } else { return a.tag > b.tag ? 1 : -1; } } else { return a.browser < b.browser ? 1 : -1; } } // adds commas to the number so its easier to read. function humanizeNumber(x: number): string { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } function roundToDecimal(level: number, num: number): number { let factor: number = Math.pow(10, level); return Math.round(num * factor) / factor; } type Testcase = { name: string; dir: string; elmFile: string; }; // Run a list of testcases export const run = async function ( options: RunTestcaseOptions, runnable: Testcase[] ) { let results: any[] = []; let assets: any = {}; for (let instance of runnable) { const source: string = compileToStringSync([instance.elmFile], { output: 'output/elm.opt.js', cwd: instance.dir, optimize: true, // processOpts: // // ignore stdout // { // stdio: ['pipe', 'pipe', 'pipe'], // }, }); const transformed = await Transform.transform( instance.dir, source, path.join(instance.dir, instance.elmFile), options.verbose, options.transforms ); removeFilesFromDir(path.join(instance.dir, 'output')) fs.writeFileSync( path.join(instance.dir, 'output', '.keep'), "" ); fs.writeFileSync(path.join(instance.dir, 'output', 'elm.opt.js'), source); fs.writeFileSync( path.join(instance.dir, 'output', 'elm.opt.transformed.js'), transformed ); await Post.process( path.join(instance.dir, 'output', 'elm.opt.js'), { minify: options.minify , gzip: options.gzip } ) await Post.process( path.join(instance.dir, 'output', 'elm.opt.transformed.js'), { minify: options.minify , gzip: options.gzip } ) if (options.assetSizes) { assets[instance.name] = assetSizeStats(path.join(instance.dir, 'output')); } for (let browser of options.runBenchmark) { results.push( await prepare_boilerplate( browser, instance.name, null, instance.dir, source ) ); results.push( await prepare_boilerplate( browser, instance.name, 'final', instance.dir, transformed ) ); } } return { assets: assets, benchmarks: reformat(results) }; }; const breakdown = function ( options: Transforms ): { name: string; options: Transforms }[] { let transforms: { name: string; options: Transforms }[] = []; let full: { name: string; include: boolean; options: Transforms }[] = [ { include: options.variantShapes, name: 'variant shapes', options: Object.assign({}, emptyOpts, { variantShapes: true }), }, { include: options.replaceVDomNode, name: 'virtualDom corrections', options: Object.assign({}, emptyOpts, { replaceVDomNode: true }), }, { include: options.inlineFunctions, name: 'inline functions', options: Object.assign({}, emptyOpts, { inlineFunctions: true }), }, { include: options.passUnwrappedFunctions, name: 'pass unwrapped functions', options: Object.assign({}, emptyOpts, { passUnwrappedFunctions: true }), }, { include: options.listLiterals == InlineLists.AsObjects, name: 'inline list literals as Objects', options: Object.assign({}, emptyOpts, { listLiterals: options.listLiterals, }), }, { include: options.listLiterals == InlineLists.AsCons, name: 'inline list literals as Cons', options: Object.assign({}, emptyOpts, { listLiterals: options.listLiterals, }), }, { include: options.inlineEquality, name: 'inline equality', options: Object.assign({}, emptyOpts, { inlineEquality: true }), }, { include: options.inlineNumberToString, name: 'inline number-to-string', options: Object.assign({}, emptyOpts, { inlineNumberToString: true }), }, { include: options.arrowFns, name: 'arrowize functions', options: Object.assign({}, emptyOpts, { arrowFns: true }), }, { include: options.objectUpdate != false, name: 'object update', options: Object.assign({}, emptyOpts, { objectUpdate: options.objectUpdate, }), }, { include: options.unusedValues, name: 'Thorough removal of unused values', options: Object.assign({}, emptyOpts, { unusedValues: options.unusedValues, }), }, ]; for (let i in full) { if (full[i].include) { transforms.push(full[i]); } } return transforms; }; // Run a list of test cases // But we'll run each transformation individually to see what the breakdown is. // We'll also run a final case with all the requested transformations export const runWithBreakdown = async function ( options: RunTestcaseOptions, runnable: Testcase[] ) { let results: any[] = []; let assets: any = {}; for (let instance of runnable) { const source: string = compileToStringSync([instance.elmFile], { output: 'output/elm.opt.js', cwd: instance.dir, optimize: true, processOpts: // ignore stdout { stdio: ['pipe', 'ignore', 'pipe'], }, }); fs.writeFileSync(path.join(instance.dir, 'output', 'elm.opt.js'), source); await Post.process( path.join(instance.dir, 'output', 'elm.opt.js'), { minify: options.minify , gzip: options.gzip } ) const transformed = await Transform.transform( instance.dir, source, path.join(instance.dir, instance.elmFile), options.verbose, options.transforms ); fs.writeFileSync( path.join(instance.dir, 'output', 'elm.opt.transformed.js'), transformed ); await Post.process( path.join(instance.dir, 'output', 'elm.opt.transformed.js'), { minify: options.minify , gzip: options.gzip } ) for (let browser of options.runBenchmark) { results.push( await prepare_boilerplate( browser, instance.name, null, instance.dir, source ) ); results.push( await prepare_boilerplate( browser, instance.name, 'final', instance.dir, transformed ) ); } let steps = breakdown(options.transforms); for (let i in steps) { const intermediate = await Transform.transform( instance.dir, source, path.join(instance.dir, instance.elmFile), options.verbose, steps[i].options ); const dashedLabel = steps[i].name.replace(unallowedChars, '-'); fs.writeFileSync( path.join(instance.dir, 'output', `elm.opt.${dashedLabel}.js`), intermediate ); await Post.process( path.join(instance.dir, 'output', `elm.opt.${dashedLabel}.js`), { minify: options.minify , gzip: options.gzip } ) for (let browser of options.runBenchmark) { results.push( await prepare_boilerplate( browser, instance.name, steps[i].name, instance.dir, intermediate ) ); } } if (options.assetSizes) { assets[instance.name] = assetSizeStats(path.join(instance.dir, 'output')); } } return { assets: assets, benchmarks: reformat(results) }; }; const unallowedChars = /[^A-Za-z0-9]/g; // Run a list of test cases // But we'll knock out each transformation individually to see if that has an effect // We'll also run a final case with all the requested transformations export const runWithKnockout = async function ( options: RunTestcaseOptions, runnable: Testcase[] ) { let results: any[] = []; let assets: any = {}; for (let instance of runnable) { const source: string = compileToStringSync([instance.elmFile], { output: 'output/elm.opt.js', cwd: instance.dir, optimize: true, processOpts: // ignore stdout { stdio: ['pipe', 'ignore', 'pipe'], }, }); fs.writeFileSync(path.join(instance.dir, 'output', 'elm.opt.js'), source); const transformed = await Transform.transform( instance.dir, source, path.join(instance.dir, instance.elmFile), options.verbose, options.transforms ); removeFilesFromDir(path.join(instance.dir, 'output')) fs.writeFileSync( path.join(instance.dir, 'output', '.keep'), "" ); fs.writeFileSync( path.join(instance.dir, 'output', 'elm.opt.transformed.js'), transformed ); await Post.process( path.join(instance.dir, 'output', 'elm.opt.transformed.js'), { minify: options.minify , gzip: options.gzip } ) for (let browser of options.runBenchmark) { results.push( await prepare_boilerplate( browser, instance.name, null, instance.dir, source ) ); results.push( await prepare_boilerplate( browser, instance.name, 'final', instance.dir, transformed ) ); } let steps = knockout(options.transforms); for (let i in steps) { const intermediate = await Transform.transform( instance.dir, source, path.join(instance.dir, instance.elmFile), options.verbose, steps[i].options ); const dashedLabel = steps[i].name.replace(unallowedChars, '-'); fs.writeFileSync( path.join(instance.dir, 'output', `elm.opt.minus-${dashedLabel}.js`), intermediate ); await Post.process( path.join(instance.dir, 'output', `elm.opt.minus-${dashedLabel}.js`), { minify: options.minify , gzip: options.gzip } ) for (let browser of options.runBenchmark) { results.push( await prepare_boilerplate( browser, instance.name, steps[i].name, instance.dir, intermediate ) ); } } assets[instance.name] = assetSizeStats(path.join(instance.dir, 'output')); } return { assets: assets, benchmarks: reformat(results) }; }; const knockout = function ( options: Transforms ): { name: string; options: Transforms }[] { let transforms: { name: string; options: Transforms }[] = []; let full: { name: string; include: boolean; options: Transforms }[] = [ { include: options.variantShapes, name: 'without variant shapes', options: Object.assign({}, options, { variantShapes: false }), }, { include: options.replaceVDomNode, name: 'without virtualDom corrections', options: Object.assign({}, options, { replaceVDomNode: false }), }, { include: options.inlineFunctions, name: 'without inline functions', options: Object.assign({}, options, { inlineFunctions: false }), }, { include: options.passUnwrappedFunctions, name: 'without passing unwrapped functions', options: Object.assign({}, options, { passUnwrappedFunctions: false }), }, { include: options.listLiterals != false, name: 'without inline list literals', options: Object.assign({}, options, { listLiterals: false, }), }, { include: options.inlineEquality, name: 'without inline equality', options: Object.assign({}, options, { inlineEquality: false }), }, { include: options.inlineNumberToString, name: 'without inline number-to-string', options: Object.assign({}, options, { inlineNumberToString: false }), }, { include: options.arrowFns, name: 'without arrowize functions', options: Object.assign({}, options, { arrowFns: false }), }, { include: options.objectUpdate != false, name: 'without object update', options: Object.assign({}, options, { objectUpdate: false, }), }, { include: options.unusedValues, name: 'without thorough removal of unused values', options: Object.assign({}, options, { unusedValues: false, }), }, ]; for (let i in full) { if (full[i].include) { transforms.push(full[i]); } } return transforms; }; // BOILERPLATE MANAGEMENT const htmlTemplate = ` <html> <head> <meta charset="UTF-8" /> <title>V8 Benchmark</title> <script src="elm.opt.transformed.js"></script> </head> <body> <div id="myapp"></div> <script> window.memoryCheckReady = false window.memory = {} function start() { var app = Elm.V8.Benchmark.init({ node: document.getElementById('myapp'), }); window.results = []; app.ports.reportResults.subscribe(function (message) { window.results = message; document.title = 'done'; }); } </script> <script src="v8-browser.js" onload="waitForV8(start)"></script> </body> </html> ` const jsTemplate = `const { Elm } = require("./elm.opt.transformed.js") globalThis["v8"] = require('./v8-node.js'); globalThis["window"] = {memoryCheckReady: false, memory: {}} const main = () => new Promise((resolve, reject) => { const app = Elm.V8.Benchmark.init({ flags: { } }) app.ports.reportResults.subscribe(resolve) }) .then((report) => { console.log(JSON.stringify(report)) }) main()` /* elmFile -> the elm file that has the harness for running the benchmark Steps 1. compile elmFile into js in elm-stuff/elm-optimize-level-2 2. copy htmlTemplate into elm-stuff if it doesn't exist. (names are hardcoded) 3. Visit.benchmark */ function removeFilesFromDir(dir: string){ const files = fs.readdirSync(dir) for (const file of files) { fs.unlinkSync(path.join(dir, file)); } } async function prepare_boilerplate( browser: BrowserOptions, name:string, tag: string | null, dir: string, js: string ) { const base = path.join(dir, 'elm-stuff', 'elm-optimize-level-2') const htmlPath = path.join(base, 'run.html') const jsPath = path.join(base, 'run.js') const nonNulltag = tag ? '.' + tag.replace(unallowedChars, '-') : '' const jitLogPath = path.join(dir, 'output', `elm.opt${nonNulltag}.jitlog`) fs.mkdirSync(base, {recursive: true}) fs.writeFileSync(htmlPath, htmlTemplate) fs.writeFileSync(jsPath, jsTemplate) fs.writeFileSync(path.join(base, 'elm.opt.transformed.js'), js) await Post.includeV8Helpers(path.join(base)) return await Visit.benchmark( browser, name, tag, htmlPath, jsPath, jitLogPath ) }
the_stack
import { each, IIterable, IIterator, iterItems, map, StringExt, toArray, toObject } from '@phosphor/algorithm'; import { BPlusTree, LinkedList } from '@phosphor/collections'; import { DisposableDelegate, IDisposable } from '@phosphor/disposable'; import { IMessageHandler, Message, MessageLoop, ConflatableMessage } from '@phosphor/messaging'; import { ISignal, Signal } from '@phosphor/signaling'; import { Record } from './record'; import { Schema, validateSchema } from './schema'; import { IServerAdapter } from './serveradapter'; import { Table } from './table'; import { createDuplexId } from './utilities'; /** * A multi-user collaborative datastore. * * #### Notes * A store is structured in a maximally flat way using a hierarchy * of tables, records, and fields. Internally, the object graph is * synchronized among all users via CRDT algorithms. * * https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type * https://hal.inria.fr/file/index/docid/555588/filename/techreport.pdf */ export class Datastore implements IDisposable, IIterable<Table<Schema>>, IMessageHandler { /** * Create a new datastore. * * @param options - The options for creating the datastore * * @returns A new datastore table. * * @throws An exception if any of the schema definitions are invalid. */ static create(options: Datastore.IOptions): Datastore { let {schemas} = options; // Throws an error for invalid schemas: Private.validateSchemas(schemas); let context = { inTransaction: false, transactionId: '', version: 0, storeId: options.id, change: {}, patch: {}, }; let tables = new BPlusTree<Table<Schema>>(Private.recordCmp); if (options.restoreState) { // If passed state to restore, pass the intital state to recreate each // table let state = JSON.parse(options.restoreState); tables.assign(map(schemas, s => { return Table.recreate(s, context, state[s.id] || []); })); } else { // Otherwise, simply create a new, empty table tables.assign(map(schemas, s => { return Table.create(s, context); })); } return new Datastore(context, tables, options.adapter); } /** * Dispose of the resources held by the datastore. */ dispose(): void { // Bail if already disposed. if (this._disposed) { return; } this._disposed = true; Signal.clearData(this); this._adapter = null; } /** * Whether the datastore has been disposed. */ get isDisposed(): boolean { return this._disposed; } /** * A signal emitted when changes are made to the store. * * #### Notes * This signal is emitted either at the end of a local mutation, * or after a remote mutation has been applied. The storeId can * be used to determine its source. * * The payload represents the set of local changes that were made * to bring the store to its current state. * * #### Complexity * `O(1)` */ get changed(): ISignal<Datastore, Datastore.IChangedArgs> { return this._changed; } /** * The unique id of the store. * * #### Notes * The id is unique among all other collaborating peers. * * #### Complexity * `O(1)` */ get id(): number { return this._context.storeId; } /** * Whether a transaction is currently in progress. * * #### Complexity * `O(1)` */ get inTransaction(): boolean { return this._context.inTransaction; } /** * The current version of the datastore. * * #### Notes * This version is automatically increased for each transaction * to the store. However, it might not increase linearly (i.e. * it might make jumps). * * #### Complexity * `O(1)` */ get version(): number { return this._context.version; } /** * Create an iterator over all the tables of the datastore. * * @returns An iterator. */ iter(): IIterator<Table<Schema>> { return this._tables.iter(); } /** * Get the table for a particular schema. * * @param schema - The schema of interest. * * @returns The table for the specified schema. * * @throws An exception if no table exists for the given schema. * * #### Complexity * `O(log32 n)` */ get<S extends Schema>(schema: S): Table<S> { let t = this._tables.get(schema.id, Private.recordIdCmp); if (t === undefined) { throw new Error(`No table found for schema with id: ${schema.id}`); } return t as Table<S>; } /** * Begin a new transaction in the store. * * @returns The id of the new transaction * * @throws An exception if a transaction is already in progress. * * #### Notes * This will allow the state of the store to be mutated * thorugh the `update` method on the individual tables. * * After the updates are completed, `endTransaction` should * be called. */ beginTransaction(): string { let newVersion = this._context.version + 1; let id = this._transactionIdFactory(newVersion, this.id); this._initTransaction(id, newVersion); MessageLoop.postMessage(this, new ConflatableMessage('transaction-begun')); return id; } /** * Completes a transaction. * * #### Notes * This completes a transaction previously started with * `beginTransaction`. If a change has occurred, the * `changed` signal will be emitted. */ endTransaction(): void { this._finalizeTransaction(); let {patch, change, storeId, transactionId, version} = this._context; // Possibly broadcast the transaction to collaborators. if (this._adapter && !Private.isPatchEmpty(patch)) { this._adapter.broadcast({ id: transactionId, storeId, patch, version }); } // Add the transation to the cemetery to indicate it is visible. this._cemetery[transactionId] = 1; // Emit a change signal if (!Private.isChangeEmpty(this._context.change)) { this._changed.emit({ storeId, transactionId, type: 'transaction', change, }); } } /** * Handle a message. */ processMessage(msg: Message): void { switch(msg.type) { case 'transaction-begun': if (this._context.inTransaction) { console.warn( `Automatically ending transaction (did you forget to end it?): ${ this._context.transactionId }` ); this.endTransaction(); } break; case 'queued-transaction': this._processQueue(); break; default: break; } } /** * Undo a patch that was previously applied. * * @param transactionId - The transaction to undo. * * @returns A promise which resolves when the action is complete. * * @throws An exception if `undo` is called during a mutation, or if no * server adapter has been set for the datastore. * * #### Notes * If changes are made, the `changed` signal will be emitted before * the promise resolves. */ undo(transactionId: string): Promise<void> { if (!this._adapter) { throw Error('No server adapter has been set for the datastore'); } if (this.inTransaction) { throw Error('Cannot undo during a transaction'); } return this._adapter.undo(transactionId); } /** * Redo a patch that was previously undone. * * @param transactionId - The transaction to redo. * * @returns A promise which resolves when the action is complete. * * @throws An exception if `redo` is called during a mutation, or if no * server adapter has been set for the datastore. * * #### Notes * If changes are made, the `changed` signal will be emitted before * the promise resolves. */ redo(transactionId: string): Promise<void> { if (!this._adapter) { throw Error('No server adapter has been set for the datastore'); } if (this.inTransaction) { throw Error('Cannot redo during a transaction'); } return this._adapter.redo(transactionId); } /** * The handler for broadcasting transactions to peers. */ get adapter(): IServerAdapter | null { return this._adapter; } /** * Serialize the state of the datastore to a string. * * @returns The serialized state. */ toString(): string { return JSON.stringify(toObject( map(this, (table): [string, Record<Schema>[]] => { return [table.schema.id, toArray(table)]; }) )); } /** * Create a new datastore. * * @param id - The unique id of the datastore. * @param tables - The tables of the datastore. */ private constructor( context: Datastore.Context, tables: BPlusTree<Table<Schema>>, adapter?: IServerAdapter, transactionIdFactory?: Datastore.TransactionIdFactory ) { this._context = context; this._tables = tables; this._adapter = adapter || null; this._transactionIdFactory = transactionIdFactory || createDuplexId; if (this._adapter) { this._adapter.onRemoteTransaction = this._onRemoteTransaction.bind(this); this._adapter.onUndo = this._onUndo.bind(this); this._adapter.onRedo = this._onRedo.bind(this); } } /** * Handle a transaction from the server adapter. */ private _onRemoteTransaction(transaction: Datastore.Transaction): void { this._processTransaction(transaction, 'transaction'); } /** * Handle an undo from the server adapter. */ private _onUndo(transaction: Datastore.Transaction): void { this._processTransaction(transaction, 'undo'); } /** * Handle a redo from the server adapter. */ private _onRedo(transaction: Datastore.Transaction): void { this._processTransaction(transaction, 'redo'); } /** * Apply a transaction to the datastore. * * @param transactionApplication - The data of the transaction. * * @throws An exception if `processTransaction` is called during a mutation. * * #### Notes * If changes are made, the `changed` signal will be emitted. */ private _processTransaction(transaction: Datastore.Transaction, type: Datastore.TransactionType): void { let {storeId, patch} = transaction; try { this._initTransaction( transaction.id, Math.max(this._context.version, transaction.version) ); } catch (e) { // Already in a transaction. Put the transaction in the queue to apply // later. this._queueTransaction(transaction, type); return; } let change: Datastore.MutableChange = {}; try { each(iterItems(patch), ([schemaId, tablePatch]) => { let table = this._tables.get(schemaId, Private.recordIdCmp); if (table === undefined) { console.warn( `Missing table for schema id '${ schemaId }' in transaction '${transaction.id}'`); this._finalizeTransaction(); return; } if ( type === 'transaction' || type === 'redo') { let count = this._cemetery[transaction.id]; if (count === undefined) { this._cemetery[transaction.id] = 1; change[schemaId] = Table.patch(table, tablePatch); return; } this._cemetery[transaction.id] = count + 1; // If the transaction is just now positive, apply it to the store. if (this._cemetery[transaction.id] === 1) { change[schemaId] = Table.patch(table, tablePatch); return; } } else { let count = this._cemetery[transaction.id]; if (count === undefined) { this._cemetery[transaction.id] = -1; return; } this._cemetery[transaction.id] = count - 1; // If the transaction hasn't already been unapplied, do so. if (this._cemetery[transaction.id] === 0) { change[schemaId] = Table.unpatch(table, tablePatch); } } }); } finally { this._finalizeTransaction(); } if (!Private.isChangeEmpty(change)) { this._changed.emit({ storeId, transactionId: transaction.id, type, change, }); } } /** * Queue a transaction for later application. * * @param transaction - the transaction to queue. */ private _queueTransaction(transaction: Datastore.Transaction, type: Datastore.TransactionType): void { this._transactionQueue.addLast([transaction, type]); MessageLoop.postMessage(this, new ConflatableMessage('queued-transaction')); } /** * Process all transactions currently queued. */ private _processQueue(): void { let queue = this._transactionQueue; // If the transaction queue is empty, bail. if (queue.isEmpty) { return; } // Add a sentinel value to the end of the queue. The queue will // only be processed up to the sentinel. Transactions added during // this cycle will execute on the next cycle. let sentinel = {}; queue.addLast(sentinel as any); // Enter the processing loop. while (true) { // Remove the first transaction in the queue. let [transaction, type] = queue.removeFirst()!; // If the value is the sentinel, exit the loop. if (transaction === sentinel) { return; } // Apply the transaction. this._processTransaction(transaction, type); } } /** * Reset the context state for a new transaction. * * @param id - The id of the new transaction. * @param newVersion - The version of the datastore after the transaction. * * @throws An exception if a transaction is already in progress. */ private _initTransaction(id: string, newVersion: number): void { let context = this._context as Private.MutableContext; if (context.inTransaction) { throw new Error(`Already in a transaction: ${this._context.transactionId}`); } context.inTransaction = true; context.change = {}; context.patch = {}; context.transactionId = id; context.version = newVersion; } /** * Finalize the context state for a transaction in progress. * * @throws An exception if no transaction is in progress. */ private _finalizeTransaction(): void { let context = this._context as Private.MutableContext; if (!context.inTransaction) { throw new Error('No transaction in progress.'); } context.inTransaction = false; } private _adapter: IServerAdapter | null; private _cemetery: { [id: string]: number } = {}; private _disposed = false; private _tables: BPlusTree<Table<Schema>>; private _context: Datastore.Context; private _changed = new Signal<Datastore, Datastore.IChangedArgs>(this); private _transactionIdFactory: Datastore.TransactionIdFactory; private _transactionQueue = new LinkedList<[ Datastore.Transaction, Datastore.TransactionType ]>(); } /** * The namespace for the `Datastore` class statics. */ export namespace Datastore { /** * A type alias for kinds of transactions. */ export type TransactionType = 'transaction' | 'undo' | 'redo'; /** * An options object for initializing a datastore. */ export interface IOptions { /** * The unique id of the datastore. */ id: number; /** * The table schemas of the datastore. */ schemas: ReadonlyArray<Schema>; /** * An optional handler for broadcasting transactions to peers. */ adapter?: IServerAdapter; /** * An optional transaction id factory to override the default. */ transactionIdFactory?: TransactionIdFactory; /** * Initialize the state to a previously serialized one. */ restoreState?: string; } /** * The arguments object for the store `changed` signal. */ export interface IChangedArgs { /** * Whether the change was generated by transaction, undo, or redo. */ readonly type: TransactionType; /** * The transaction id associated with the change. */ readonly transactionId: string; /** * The id of the store responsible for the change. */ readonly storeId: number; /** * A mapping of schema id to table change set. */ readonly change: Change; } /** * A type alias for a store change. */ export type Change = { readonly [schemaId: string]: Table.Change<Schema>; }; /** * A type alias for a store patch. */ export type Patch = { readonly [schemaId: string]: Table.Patch<Schema>; }; /** * @internal */ export type MutableChange = { [schemaId: string]: Table.MutableChange<Schema>; }; /** * @internal */ export type MutablePatch = { [schemaId: string]: Table.MutablePatch<Schema>; }; /** * An object representing a datastore transaction. */ export type Transaction = { /** * The id of the transaction. */ readonly id: string; /** * The id of the store responsible for the transaction. */ readonly storeId: number; /** * The patch data of the transaction. */ readonly patch: Patch; /** * The version of the source datastore. */ readonly version: number; } /** * @internal */ export type Context = Readonly<Private.MutableContext>; /** * A factory function for generating a unique transaction id. */ export type TransactionIdFactory = (version: number, storeId: number) => string; /** * A helper function to wrap an update to the datastore in calls to * `beginTransaction` and `endTransaction`. * * @param datastore: the datastore to which to apply the update. * * @param update: A function that performs the update on the datastore. * The function is called with a transaction id string, in case the * user wishes to store the transaction ID for later use. * * @returns the transaction ID. * * #### Notes * If the datastore is already in a transaction, this does not attempt * to start a new one, and returns an empty string for the transaction * id. This allows for transactions to be composed a bit more easily. */ export function withTransaction( datastore: Datastore, update: (id: string) => void ): string { let id = ''; if (!datastore.inTransaction) { id = datastore.beginTransaction(); } try { update(id); } finally { if (id) { datastore.endTransaction(); } } return id; } /** * A base type for describing the location of data in a datastore, * to be consumed by some object. The only requirement is that it * has a datastore object. Objects extending from this will, in general, * have some combination of table, record, and field locations. */ export type DataLocation = { /** * The datastore in which the data is contained. */ datastore: Datastore; }; /** * An interface for referring to a specific table in a datastore. */ export type TableLocation<S extends Schema> = { /** * The schema in question. This schema must exist in the datastore, * or an error may result in its usage. */ schema: S; }; /** * An interface for referring to a specific record in a datastore. */ export type RecordLocation<S extends Schema> = TableLocation<S> & { /** * The record in question. */ record: string; }; /** * An interface for referring to a specific field in a datastore. * * #### Notes * The field must exist in the schema. */ export type FieldLocation< S extends Schema, F extends keyof S['fields'] > = RecordLocation<S> & { /** * The field in question. */ field: F; }; /** * Get a given table by its location. * * @param datastore: the datastore in which the table resides. * * @param loc: The table location. * * @returns the table. */ export function getTable<S extends Schema>( datastore: Datastore, loc: TableLocation<S> ): Table<S> { return datastore.get(loc.schema); } /** * Get a given record by its location. * * @param datastore: the datastore in which the record resides. * * @param loc: The record location. * * @returns the record, or undefined if it does not exist. */ export function getRecord<S extends Schema>( datastore: Datastore, loc: RecordLocation<S> ): Record.Value<S> | undefined { return datastore.get(loc.schema).get(loc.record); } /** * Get a given field by its location. * * @param datastore: the datastore in which the field resides. * * @param loc: the field location. * * @returns the field in question. * * #### Notes * This will throw an error if the record does not exist in the given table. */ export function getField<S extends Schema, F extends keyof S['fields']>( datastore: Datastore, loc: FieldLocation<S, F> ): S['fields'][F]['ValueType'] { const record = datastore.get(loc.schema).get(loc.record); if (!record) { throw Error(`The record ${loc.record} could not be found`); } return record[loc.field]; } /** * Update a table. * * @param datastore: the datastore in which the table resides. * * @param loc: the table location. * * @param update: the update to the table. * * #### Notes * This does not begin a transaction, so usage of this function should be * combined with `beginTransaction`/`endTransaction`, or `withTransaction`. */ export function updateTable<S extends Schema>( datastore: Datastore, loc: TableLocation<S>, update: Table.Update<S> ): void { let table = datastore.get(loc.schema); table.update(update); } /** * Update a record in a table. * * @param datastore: the datastore in which the record resides. * * @param loc: the record location. * * @param update: the update to the record. * * #### Notes * This does not begin a transaction, so usage of this function should be * combined with `beginTransaction`/`endTransaction`, or `withTransaction`. */ export function updateRecord<S extends Schema>( datastore: Datastore, loc: RecordLocation<S>, update: Record.Update<S> ): void { let table = datastore.get(loc.schema); table.update({ [loc.record]: update }); } /** * Update a field in a table. * * @param datastore: the datastore in which the field resides. * * @param loc: the field location. * * @param update: the update to the field. * * #### Notes * This does not begin a transaction, so usage of this function should be * combined with `beginTransaction`/`endTransaction`, or `withTransaction`. */ export function updateField<S extends Schema, F extends keyof S['fields']>( datastore: Datastore, loc: FieldLocation<S, F>, update: S['fields'][F]['UpdateType'] ): void { let table = datastore.get(loc.schema); // TODO: this cast may be made unnecessary once microsoft/TypeScript#13573 // is fixed, possibly by microsoft/TypeScript#26797 lands. table.update({ [loc.record]: { [loc.field]: update } as Record.Update<S> }); } /** * Listen to changes in a table. Changes to other tables are ignored. * * @param datastore: the datastore in which the table resides. * * @param loc: the table location. * * @param slot: a callback function to invoke when the table changes. * * @returns an `IDisposable` that can be disposed to remove the listener. */ export function listenTable<S extends Schema>( datastore: Datastore, loc: TableLocation<S>, slot: (source: Datastore, args: Table.Change<S>) => void, thisArg?: any ): IDisposable { // A wrapper change signal connection function. const wrapper = (source: Datastore, args: Datastore.IChangedArgs) => { // Ignore changes that don't match the requested record. if (!args.change[loc.schema.id]) { return; } // Otherwise, call the slot. const tc = args.change[loc.schema.id]! as Table.Change<S>; slot.bind(thisArg)(source, tc); }; datastore.changed.connect(wrapper); return new DisposableDelegate(() => { datastore.changed.disconnect(wrapper); }); } /** * Listen to changes in a record in a table. Changes to other tables and * other records in the same table are ignored. * * @param datastore: the datastore in which the record resides. * * @param loc: the record location. * * @param slot: a callback function to invoke when the record changes. * * @returns an `IDisposable` that can be disposed to remove the listener. */ export function listenRecord<S extends Schema>( datastore: Datastore, loc: RecordLocation<S>, slot: (source: Datastore, args: Record.Change<S>) => void, thisArg?: any ): IDisposable { // A wrapper change signal connection function. const wrapper = (source: Datastore, args: Datastore.IChangedArgs) => { // Ignore changes that don't match the requested record. if ( !args.change[loc.schema.id] || !args.change[loc.schema.id][loc.record] ) { return; } // Otherwise, call the slot. const tc = args.change[loc.schema.id]! as Table.Change<S>; slot.bind(thisArg)(source, tc[loc.record]); }; datastore.changed.connect(wrapper); return new DisposableDelegate(() => { datastore.changed.disconnect(wrapper); }); } /** * Listen to changes in a fields in a table. Changes to other tables, other * records in the same table, and other fields in the same record are ignored. * * @param datastore: the datastore in which the field resides. * * @param loc: the field location. * * @param slot: a callback function to invoke when the field changes. * * @returns an `IDisposable` that can be disposed to remove the listener. */ export function listenField<S extends Schema, F extends keyof S['fields']>( datastore: Datastore, loc: FieldLocation<S, F>, slot: (source: Datastore, args: S['fields'][F]['ChangeType']) => void, thisArg?: any ): IDisposable { const wrapper = (source: Datastore, args: Datastore.IChangedArgs) => { // Ignore changes that don't match the requested field. if ( !args.change[loc.schema.id] || !args.change[loc.schema.id][loc.record] || !args.change[loc.schema.id][loc.record][loc.field as string] ) { return; } // Otherwise, call the slot. const tc = args.change[loc.schema.id]! as Table.Change<S>; slot.bind(thisArg)(source, tc[loc.record][loc.field]); }; datastore.changed.connect(wrapper); return new DisposableDelegate(() => { datastore.changed.disconnect(wrapper); }); } } namespace Private { /** * Validates all schemas, and throws an error if any are invalid. */ export function validateSchemas(schemas: ReadonlyArray<Schema>) { let errors = []; for (let s of schemas) { let err = validateSchema(s); if (err.length) { errors.push(`Schema '${s.id}' validation failed: \n${err.join('\n')}`); } } if (errors.length) { throw new Error(errors.join('\n\n')); } } /** * A three-way record comparison function. */ export function recordCmp<S extends Schema>(a: Table<S>, b: Table<S>): number { return StringExt.cmp(a.schema.id, b.schema.id); } /** * A three-way record id comparison function. */ export function recordIdCmp<S extends Schema>(table: Table<S>, id: string): number { return StringExt.cmp(table.schema.id, id); } export type MutableContext = { /** * Whether the datastore currently in a transaction. */ inTransaction: boolean; /** * The id of the current transaction. */ transactionId: string; /** * The current version of the datastore. */ version: number; /** * The unique id of the datastore. */ storeId: number; /** * The current change object of the transaction. */ change: Datastore.MutableChange; /** * The current patch object of the transaction. */ patch: Datastore.MutablePatch; } /** * Checks if a patch is empty. */ export function isPatchEmpty(patch: Datastore.Patch): boolean { return Object.keys(patch).length === 0; } /** * Checks if a change is empty. */ export function isChangeEmpty(change: Datastore.Change): boolean { return Object.keys(change).length === 0; } }
the_stack
import test from 'tape-promise/tape'; import {webgl1TestDevice, webgl2TestDevice, getTestDevices} from '@luma.gl/test-utils'; import {Device, Texture, TextureFormat, cast} from '@luma.gl/api'; import GL from '@luma.gl/constants'; import {Buffer, getKey, isWebGL2, readPixelsToArray} from '@luma.gl/gltools'; import {TEXTURE_FORMATS} from '@luma.gl/webgl/adapter/converters/texture-formats'; import {SAMPLER_PARAMETERS} from './webgl-sampler.spec'; import WEBGLTexture from '@luma.gl/webgl/adapter/resources/webgl-texture'; // import {convertToSamplerProps} from '@luma.gl/webgl/adapter/converters/sampler-parameters'; test('WebGL#Texture construct/delete', async (t) => { for (const device of await getTestDevices()) { const texture = device.createTexture({}); t.ok(texture instanceof Texture, 'Texture construction successful'); texture.destroy(); t.ok(texture instanceof Texture, 'Texture delete successful'); texture.destroy(); t.ok(texture instanceof Texture, 'Texture repeated delete successful'); } t.end(); }); test('WebGLDevice#isTextureFormatSupported()', async (t) => { const FORMATS: Record<string, TextureFormat[]> = { 'webgl': ['rgba8unorm'], 'webgl2': ['r32float', 'rg32float', 'rgb32float-webgl', 'rgba32float'] } for (const device of await getTestDevices()) { const unSupportedFormats = []; FORMATS[device.info.type].forEach((format) => { if (!device.isTextureFormatSupported(format)) { unSupportedFormats.push(format); } }); t.deepEqual(unSupportedFormats, [], `All ${device.info.type} formats are supported`); } t.end(); }); const DEFAULT_TEXTURE_DATA = new Uint8Array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]); const DATA = [1, 0.5, 0.25, 0.125]; const UINT8_DATA = new Uint8Array(DATA); const UINT16_DATA = new Uint16Array(DATA); const FLOAT_DATA = new Float32Array(DATA); const TEXTURE_DATA = { [GL.UNSIGNED_BYTE]: UINT8_DATA, // RGB_TO[GL.UNSIGNED_BYTE](DATA)), [GL.UNSIGNED_SHORT_5_6_5]: UINT16_DATA, // RGB_TO[GL.UNSIGNED_SHORT_5_6_5](DATA)) [GL.UNSIGNED_SHORT_4_4_4_4]: UINT16_DATA, // RGB_TO[GL.UNSIGNED_SHORT_5_6_5](DATA)) [GL.UNSIGNED_SHORT_5_5_5_1]: UINT16_DATA, // RGB_TO[GL.UNSIGNED_SHORT_5_6_5](DATA)) [GL.FLOAT]: FLOAT_DATA }; // const RGB_TO = { // [GL.UNSIGNED_BYTE]: (r, g, b) => [r * 256, g * 256, b * 256], // [GL.UNSIGNED_SHORT_5_6_5]: (r, g, b) => r * 32 << 11 + g * 64 << 6 + b * 32 // }; // const RGB_FROM = { // [GL.UNSIGNED_BYTE]: v => [v[0] / 256, v[1] / 256, v[2] / 256], // [GL.UNSIGNED_SHORT_5_6_5]: v => [v >> 11 / 32, v >> 6 % 64 / 64, v % 32 * 32] // }; function testFormatCreation(t, device: Device, withData: boolean = false) { for (const [format, formatInfo] of Object.entries(TEXTURE_FORMATS)) { if (device.isTextureFormatSupported(format)) { try { const data = withData ? TEXTURE_DATA[type] || DEFAULT_TEXTURE_DATA : null; // TODO: for some reason mipmap generation failing for RGB32F format const mipmaps = device.isTextureFormatRenderable(format) && device.isTextureFormatFilterable(format); const sampler = mipmaps ? { magFilter: 'linear', minFilter: 'linear', addressModeU: 'clamp-to-edge', addressModeW: 'clamp-to-edge' } : {}; const texture = device.createTexture({ data, format, width: 1, height: 1, mipmaps, sampler }); t.equals(texture.props.format, format, `Texture(${format}) created with mipmaps=${mipmaps}`); texture.destroy(); } catch (error) { t.comment(`Texture(${format}) creation FAILED ${error}`); } } else { t.comment(`Texture(${format}) not supported in ${device.info.type}`) } } } function testFormatDeduction(t, device: Device) { for (const [formatName, formatInfo] of Object.entries(TEXTURE_FORMATS)) { const expectedType = formatInfo.types[0]; const expectedDataFormat = formatInfo.dataFormat; const options = { format: Number(format), height: 1, width: 1 }; if (device.isTextureFormatSupported({format})) { const texture = device.createTexture(options); const msg = `Texture({format: ${getKey(GL, format)}}) created`; t.equals(texture.format, Number(format), msg); t.equals(texture.type, expectedType, msg); t.equals(texture.dataFormat, expectedDataFormat, msg); texture.destroy(); } } } test.skip('WebGL#Texture format deduction', (t) => { if (webgl2TestDevice) { testFormatDeduction(t, webgl2TestDevice); } testFormatDeduction(t, webgl1TestDevice); t.end(); }); test.skip('WebGL#Texture format creation', (t) => { if (webgl2TestDevice) { testFormatCreation(t, webgl2TestDevice); } testFormatCreation(t, webgl1TestDevice); t.end(); }); test.skip('WebGL#Texture format creation with data', (t) => { if (webgl2TestDevice) { testFormatCreation(t, webgl2TestDevice, true); } testFormatCreation(t, webgl1TestDevice, true); t.end(); }); /* test.skip('WebGL#Texture WebGL1 extension format creation', t => { for (const format of TEXTURE_FORMATS) { } let texture = webgl1TestDevice.createTexture({}); t.ok(texture instanceof Texture, 'Texture construction successful'); texture = texture.destroy(); t.ok(texture instanceof Texture, 'Texture delete successful'); t.end(); }); test.skip('WebGL#Texture WebGL2 format creation', t => { for (const format in TEXTURE_FORMATS) { if (!WEBGL1_FORMATS.indexOf(format)) { } } let texture = webgl1TestDevice.createTexture({}); t.ok(texture instanceof Texture, 'Texture construction successful'); texture = texture.destroy(); t.ok(texture instanceof Texture, 'Texture delete successful'); t.end(); }); */ test.skip('WebGL#Texture setParameters', (t) => { let texture = webgl1TestDevice.createTexture({}); t.ok(texture instanceof Texture, 'Texture construction successful'); testSamplerParameters({t, texture, parameters: SAMPLER_PARAMETERS}); /* // Bad tests const parameter = GL.TEXTURE_MAG_FILTER; const value = GL.LINEAR_MIPMAP_LINEAR; texture.setParameters({ [parameter]: value }); const newValue = getParameter(texture, GL.TEXTURE_MAG_FILTER); t.equals(newValue, value, `Texture.setParameters({[${getKey(GL, parameter)}]: ${getKey(GL, value)}})`); */ texture.destroy(); t.ok(texture instanceof Texture, 'Texture delete successful'); t.end(); }); test.skip('WebGL2#Texture setParameters', (t) => { if (!webgl2TestDevice) { t.comment('WebGL2 not available, skipping tests'); t.end(); return; } let texture = webgl2TestDevice.createTexture({}); t.ok(texture instanceof Texture, 'Texture construction successful'); testSamplerParameters({t, texture, parameters: SAMPLER_PARAMETERS_WEBGL2}); texture.destroy(); t.ok(texture instanceof Texture, 'Texture delete successful'); t.end(); }); test.skip('WebGL#Texture NPOT Workaround: texture creation', (t) => { // Create NPOT texture with no parameters let texture = webgl1TestDevice.createTexture({data: null, width: 500, height: 512}); t.ok(texture instanceof Texture, 'Texture construction successful'); // Default parameters should be changed to supported NPOT parameters. let minFilter = getParameter(texture, 'minFilter'); t.equals(minFilter, GL.LINEAR, 'NPOT texture min filter is set to LINEAR'); let wrapS = getParameter(texture, 'addressModeU'); t.equals(wrapS, 'clamp-to-edge', 'NPOT texture wrap_s is set to CLAMP_TO_EDGE'); let wrapT = getParameter(texture, 'addressModeV'); t.equals(wrapT, 'clamp-to-edge', 'NPOT texture wrap_t is set to CLAMP_TO_EDGE'); const parameters = { ['minFilter']: 'nearest', ['addressModeU']: 'repeat', ['addressModeV']: 'mirrored-repeat' }; // Create NPOT texture with parameters texture = webgl1TestDevice.createTexture({ data: null, width: 512, height: 600, parameters }); t.ok(texture instanceof Texture, 'Texture construction successful'); // Above parameters should be changed to supported NPOT parameters. minFilter = getParameter(texture, 'minFilter'); t.equals(minFilter, 'nearest', 'NPOT texture min filter is set to NEAREST'); wrapS = getParameter(texture, 'addressModeU'); t.equals(wrapS, 'clamp-to-edge', 'NPOT texture wrap_s is set to CLAMP_TO_EDGE'); wrapT = getParameter(texture, 'addressModeV'); t.equals(wrapT, 'clamp-to-edge', 'NPOT texture wrap_t is set to CLAMP_TO_EDGE'); t.end(); }); test.skip('WebGL#Texture NPOT Workaround: setParameters', (t) => { // Create NPOT texture const texture = webgl1TestDevice.createTexture({data: null, width: 100, height: 100}); t.ok(texture instanceof Texture, 'Texture construction successful'); const invalidNPOTParameters = { ['minFilter']: 'linear', ['mipmapFilter']: 'nearest', ['addressModeU']: 'mirrored-repeat', ['addressModeV']: 'repeat' }; texture.setParameters(invalidNPOTParameters); // Above parameters should be changed to supported NPOT parameters. const minFilter = getParameter(texture, 'minFilter'); t.equals(minFilter,'linear', 'NPOT texture min filter is set to LINEAR'); const wrapS = getParameter(texture, 'addressModeU'); t.equals(wrapS, 'clamp-to-edge', 'NPOT texture wrap_s is set to CLAMP_TO_EDGE'); const wrapT = getParameter(texture, 'addressModeV'); t.equals(wrapT, 'clamp-to-edge', 'NPOT texture wrap_t is set to CLAMP_TO_EDGE'); t.end(); }); test.skip('WebGL2#Texture NPOT Workaround: texture creation', (t) => { // WebGL2 supports NPOT texture hence, texture parameters should not be changed. if (!webgl2TestDevice) { t.comment('WebGL2 not available, skipping tests'); t.end(); return; } // Create NPOT texture with no parameters let texture = webgl2TestDevice.createTexture({data: null, width: 500, height: 512}); t.ok(texture instanceof Texture, 'Texture construction successful'); // Default values are un-changed. let minFilter = getParameter(texture, 'minFilter'); t.equals( minFilter, 'nearest', 'NPOT texture min filter is set to NEAREST_MIPMAP_LINEAR' ); // mipmapFilter, 'LINEAR', let wrapS = getParameter(texture, 'addressModeU'); t.equals(wrapS, 'repeat', 'NPOT texture wrap_s is set to REPEAT'); let wrapT = getParameter(texture, 'addressModeV'); t.equals(wrapT, 'repeat', 'NPOT texture wrap_t is set to REPEAT'); const parameters = { ['minFilter']: 'nearest', ['addressModeU']: 'repeat', ['addressModeV']: 'mirrored-repeat' }; // Create NPOT texture with parameters texture = webgl2TestDevice.createTexture({ data: null, width: 512, height: 600, parameters }); t.ok(texture instanceof Texture, 'Texture construction successful'); minFilter = getParameter(texture, 'minFilter'); t.equals(minFilter, 'nearest', 'NPOT texture min filter is set to NEAREST'); wrapS = getParameter(texture, 'addressModeU'); t.equals(wrapS, 'repeat', 'NPOT texture wrap_s is set to REPEAT'); wrapT = getParameter(texture, 'addressModeV'); t.equals(wrapT, 'mirrored-repeat', 'NPOT texture wrap_t is set to MIRRORED_REPEAT'); t.end(); }); test.skip('WebGL2#Texture NPOT Workaround: setParameters', (t) => { if (!webgl2TestDevice) { t.comment('WebGL2 not available, skipping tests'); t.end(); return; } // Create NPOT texture const texture = webgl2TestDevice.createTexture({data: null, width: 100, height: 100}); t.ok(texture instanceof Texture, 'Texture construction successful'); const invalidNPOTParameters = { ['minFilter']: 'linear', ['mipmapFilter']: 'nearest', ['addressModeU']: 'mirrored-repeat', ['addressModeV']: 'repeat' }; texture.setParameters(invalidNPOTParameters); // Above parameters are not changed for NPOT texture when using WebGL2 context. const minFilter = getParameter(texture, 'minFilter'); t.equals( minFilter, GL.LINEAR_MIPMAP_NEAREST, 'NPOT texture min filter is set to LINEAR_MIPMAP_NEAREST' ); const wrapS = getParameter(texture, 'addressModeU'); t.equals(wrapS, 'mirrored-repeat', 'NPOT texture wrap_s is set to MIRRORED_REPEAT'); const wrapT = getParameter(texture, 'addressModeV'); t.equals(wrapT, 'repeat', 'NPOT texture wrap_t is set to REPEAT'); t.end(); }); test.skip('WebGL1#Texture setImageData', (t) => { // data: null const texture = webgl1TestDevice.createTexture({data: null, width: 2, height: 1, mipmaps: false}); t.deepEquals(readPixelsToArray(texture), new Float32Array(8), 'Pixels are empty'); // data: typed array const data = new Uint8Array([0, 1, 2, 3, 128, 201, 255, 255]); texture.setImageData({data}); t.deepEquals(readPixelsToArray(texture), data, 'Pixels are set correctly'); // data: canvas if (typeof document !== 'undefined') { const canvas = document.createElement('canvas'); canvas.width = 2; canvas.height = 1; const ctx = canvas.getContext('2d'); const imageData = ctx.getImageData(0, 0, 2, 1); imageData.data[2] = 128; imageData.data[3] = 255; imageData.data[7] = 1; ctx.putImageData(imageData, 0, 0); texture.setImageData({data: canvas}); t.deepEquals( readPixelsToArray(texture), new Uint8Array([0, 0, 128, 255, 0, 0, 0, 1]), 'Pixels are set correctly' ); } t.end(); }); test.skip('WebGL2#Texture setImageData', (t) => { if (!webgl2TestDevice) { t.comment('WebGL2 not available, skipping tests'); t.end(); return; } let data; // data: null const texture = webgl2TestDevice.createTexture({ data: null, width: 2, height: 1, format: GL.RGBA32F, type: GL.FLOAT, mipmaps: false }); t.deepEquals(readPixelsToArray(texture), new Float32Array(8), 'Pixels are empty'); // data: typed array data = new Float32Array([0.1, 0.2, -3, -2, 0, 0.5, 128, 255]); texture.setImageData({data}); t.deepEquals(readPixelsToArray(texture), data, 'Pixels are set correctly'); // data: buffer data = new Float32Array([21, 0.82, 0, 1, 0, 255, 128, 3.333]); const buffer = new Buffer(gl2, {data, accessor: {size: 4, type: GL.FLOAT}}); texture.setImageData({data: buffer}); t.deepEquals(readPixelsToArray(texture), data, 'Pixels are set correctly'); // data: canvas if (typeof document !== 'undefined') { const canvas = document.createElement('canvas'); canvas.width = 2; canvas.height = 1; const ctx = canvas.getContext('2d'); ctx.fillRect(0, 0, 2, 1); texture.setImageData({data: canvas}); t.deepEquals( readPixelsToArray(texture), new Float32Array([0, 0, 0, 1, 0, 0, 0, 1]), 'Pixels are set correctly' ); } t.end(); }); test.skip('WebGL1#Texture setSubImageData', (t) => { // data: null const texture = webgl1TestDevice.createTexture({data: null, width: 2, height: 1, mipmaps: false}); t.deepEquals(readPixelsToArray(texture), new Uint8Array(8), 'Pixels are empty'); // data: typed array const data = new Uint8Array([1, 2, 3, 4]); texture.setSubImageData({data, x: 0, y: 0, width: 1, height: 1}); t.deepEquals( readPixelsToArray(texture), new Uint8Array([1, 2, 3, 4, 0, 0, 0, 0]), 'Pixels are set correctly' ); // data: canvas if (typeof document !== 'undefined') { const canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = 1; const ctx = canvas.getContext('2d'); ctx.fillRect(0, 0, 1, 1); texture.setSubImageData({data: canvas, x: 1, y: 0, width: 1, height: 1}); t.deepEquals( readPixelsToArray(texture), new Uint8Array([1, 2, 3, 4, 0, 0, 0, 255]), 'Pixels are set correctly' ); } t.end(); }); test.skip('WebGL2#Texture setSubImageData', (t) => { if (!webgl2TestDevice) { t.comment('WebGL2 not available, skipping tests'); t.end(); return; } let data; // data: null const texture = webgl2TestDevice.createTexture({ data: null, width: 2, height: 1, format: GL.RGBA32F, type: GL.FLOAT, mipmaps: false }); t.deepEquals(readPixelsToArray(texture), new Float32Array(8), 'Pixels are empty'); // data: typed array data = new Float32Array([0.1, 0.2, -3, -2]); texture.setSubImageData({data, x: 0, y: 0, width: 1, height: 1}); t.deepEquals( readPixelsToArray(texture), new Float32Array([0.1, 0.2, -3, -2, 0, 0, 0, 0]), 'Pixels are set correctly' ); // data: buffer data = new Float32Array([-3, 255, 128, 3.333]); const buffer = new Buffer(gl2, {data, accessor: {size: 4, type: GL.FLOAT}}); texture.setSubImageData({data: buffer, x: 1, y: 0, width: 1, height: 1}); t.deepEquals( readPixelsToArray(texture), new Float32Array([0.1, 0.2, -3, -2, -3, 255, 128, 3.333]), 'Pixels are set correctly' ); // data: canvas if (typeof document !== 'undefined') { const canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = 1; const ctx = canvas.getContext('2d'); ctx.fillRect(0, 0, 1, 1); texture.setSubImageData({data: canvas, x: 1, y: 0, width: 1, height: 1}); t.deepEquals( readPixelsToArray(texture), new Float32Array([0.1, 0.2, -3, -2, 0, 0, 0, 1]), 'Pixels are set correctly' ); } t.end(); }); /* test.skip('WebGL2#Texture resize', (t) => { let texture = webgl1TestDevice.createTexture({ data: null, width: 2, height: 2, mipmaps: true }); texture.resize({ width: 4, height: 4, mipmaps: true }); t.ok(texture.mipmaps, 'mipmaps should set to true for POT.'); texture.resize({ width: 3, height: 3, mipmaps: true }); t.notOk(texture.mipmaps, 'mipmaps should set to false when resizing to NPOT.'); texture = webgl1TestDevice.createTexture({ data: null, width: 2, height: 2, mipmaps: true }); texture.resize({ width: 4, height: 4 }); t.notOk(texture.mipmaps, 'mipmaps should set to false when resizing.'); t.end(); }); */ test.skip('WebGL2#Texture generateMipmap', (t) => { let texture = webgl1TestDevice.createTexture({ data: null, width: 3, height: 3, mipmaps: false }); texture.generateMipmap(); t.notOk(texture.mipmaps, 'Should not turn on mipmaps for NPOT.'); texture = webgl1TestDevice.createTexture({ data: null, width: 2, height: 2, mipmaps: false }); texture.generateMipmap(); t.ok(texture.mipmaps, 'Should turn on mipmaps for POT.'); t.end(); }); // Shared with texture*.spec.js export function testSamplerParameters({t, texture, parameters}) { for (const parameterName in parameters) { const values = parameters[parameterName]; const parameter = Number(parameterName); for (const valueName in values) { const value = Number(valueName); texture.setParameters({ [parameter]: value }); const name = texture.constructor.name; const newValue = getParameter(texture, parameter); t.equals( newValue, value, `${name}.setParameters({[${getKey(GL, parameter)}]: ${getKey(GL, value)}}) read back OK` ); } } } // 2D TEXTURES test.skip('WebGL#Texture construct/delete', (t) => { t.throws( // @ts-expect-error () => new Texture(), /.*WebGLRenderingContext.*/, 'Texture throws on missing gl context' ); const texture = webgl1TestDevice.createTexture(); t.ok(texture instanceof Texture, 'Texture construction successful'); t.comment(JSON.stringify(texture.getParameters({keys: true}))); texture.destroy(); t.ok(texture instanceof Texture, 'Texture delete successful'); texture.destroy(); t.ok(texture instanceof Texture, 'Texture repeated delete successful'); t.end(); }); test.skip('WebGL#Texture async constructor', (t) => { let texture = webgl1TestDevice.createTexture(); t.ok(texture instanceof Texture, 'Synchronous Texture construction successful'); t.equal(texture.loaded, true, 'Sync Texture marked as loaded'); texture.destroy(); let loadCompleted; const loadPromise = new Promise((resolve) => { loadCompleted = resolve; // eslint-disable-line }); texture = new Texture(gl, loadPromise); t.ok(texture instanceof Texture, 'Asynchronous Texture construction successful'); t.equal(texture.loaded, false, 'Async Texture initially marked as not loaded'); loadPromise.then(() => { t.equal(texture.loaded, true, 'Async Texture marked as loaded on promise completion'); t.end(); }); // @ts-expect-error loadCompleted(null); }); test.skip('WebGL#Texture buffer update', (t) => { let texture = webgl1TestDevice.createTexture(); t.ok(texture instanceof Texture, 'Texture construction successful'); texture = texture.destroy(); t.ok(texture instanceof Texture, 'Texture delete successful'); t.end(); }); // CUBE TEXTURES test.skip('WebGL#TextureCube construct/delete', (t) => { t.throws( // @ts-expect-error () => new TextureCube(), /.*WebGLRenderingContext.*/, 'TextureCube throws on missing gl context' ); const texture = webgl1TestDevice.createTexture({dimension: 'cube'}); t.ok(texture instanceof Texture, 'TextureCube construction successful'); // t.comment(JSON.stringify(texture.getParameters({keys: true}))); texture.destroy(); t.ok(texture instanceof Texture, 'TextureCube delete successful'); texture.destroy(); t.ok(texture instanceof Texture, 'TextureCube repeated delete successful'); t.end(); }); test.skip('WebGL#TextureCube buffer update', (t) => { let texture = webgl1TestDevice.createTexture({dimension: 'cube'}); t.ok(texture instanceof Texture, 'TextureCube construction successful'); texture.destroy(); t.ok(texture instanceof Texture, 'TextureCube delete successful'); t.end(); }); test.skip('WebGL#TextureCube multiple LODs', (t) => { const texture = webgl1TestDevice.createTexture({dimension: 'cube'}, { pixels: { [GL.TEXTURE_CUBE_MAP_POSITIVE_X]: [], [GL.TEXTURE_CUBE_MAP_NEGATIVE_X]: [], [GL.TEXTURE_CUBE_MAP_POSITIVE_Y]: [], [GL.TEXTURE_CUBE_MAP_NEGATIVE_Y]: [], [GL.TEXTURE_CUBE_MAP_POSITIVE_Z]: [], [GL.TEXTURE_CUBE_MAP_NEGATIVE_Z]: [] } }); t.ok(texture instanceof Texture, 'TextureCube construction successful'); t.end(); }); // 3D TEXTURES test.skip('WebGL#Texture3D construct/delete', (t) => { if (!webgl2TestDevice) { t.comment('WebGL2 not available, skipping tests'); t.end(); return; } t.throws(() => webgl2TestDevice.createTexture({dimension: '3d'}), 'Texture3D throws on missing gl context'); // TODO(Tarek): generating mipmaps on an empty 3D texture seems to trigger an INVALID_OPERATION // error. See if this is expected behaviour. /* let texture = new Texture3D(gl); t.ok(texture instanceof Texture3D, 'Texture3D construction successful'); texture.destroy(); gl.getError(); // Reset error texture = new Texture3D(gl, { width: 4, height: 4, depth: 4, data: new Uint8Array(4 * 4 * 4), format: gl.RED, dataFormat: gl.R8 }); t.ok(gl.getError() === gl.NO_ERROR, 'Texture3D construction with array produces no errors'); texture.destroy(); t.ok(!gl.isTexture(texture.handle), `Texture GL object was deleted`); t.ok(texture instanceof Texture3D, 'Texture3D delete successful'); const buffer = new Buffer(gl, new Uint8Array(4 * 4 * 4)); texture = new Texture3D(gl, { width: 4, height: 4, depth: 4, data: buffer, format: gl.RED, dataFormat: gl.R8 }); t.ok(gl.getError() === gl.NO_ERROR, 'Texture3D construction with buffer produces no errors'); texture.destroy(); buffer.destroy(); */ t.end(); }); // HELPERS function getParameter(texture: Texture, pname: number): any { const webglTexture = cast<WEBGLTexture>(texture); this.gl.bindTexture(webglTexture.target, webglTexture.handle); const value = webglTexture.gl.getTexParameter(webglTexture.target, pname); webglTexture.gl.bindTexture(webglTexture.target, null); return value; } function isFormatSupported(format, glContext) { format = Number(format); const opts = Object.assign({format}, TEXTURE_FORMATS[format]); if (!device.isTextureFormatSupported({format}) || (!isWebGL2(glContext) && opts.compressed)) { return false; } return true; }
the_stack
import { Address, Algorithm, isBlockInfoPending, PubkeyBundle, PubkeyBytes, TokenTicker } from "@iov/bcp"; import { ActionKind, bnsCodec, BnsConnection, VoteOption } from "@iov/bns"; import { Random } from "@iov/crypto"; import { Bech32, toHex } from "@iov/encoding"; import { Ed25519HdWallet, HdPaths, UserProfile } from "@iov/keycontrol"; import { sleep } from "@iov/utils"; import { ReadonlyDate } from "readonly-date"; import { Governor, GovernorOptions } from "./governor"; import { CommitteeId, ProposalType } from "./proposals"; function pendingWithoutBnsd(): void { if (!process.env.BNSD_ENABLED) { pending("Set BNSD_ENABLED to enable bnsd-based tests"); } } function randomBnsAddress(): Address { return Bech32.encode("tiov", Random.getBytes(20)) as Address; } function randomBnsPubkey(): PubkeyBundle { return { algo: Algorithm.Ed25519, data: Random.getBytes(32) as PubkeyBytes, }; } // Dev admin // path: m/44'/234'/0' // pubkey: 418f88ff4876d33a3d6e2a17d0fe0e78dc3cb5e4b42c6c156ed1b8bfce5d46d1 // IOV address: tiov15nuhg3l8ma2mdmcdvgy7hme20v3xy5mkxcezea // This account has money in the genesis file (see scripts/bnsd/README.md). const adminMnemonic = "degree tackle suggest window test behind mesh extra cover prepare oak script"; const adminPath = HdPaths.iov(0); const bnsdUrl = "ws://localhost:23456"; const guaranteeFundEscrowId = 6; const rewardFundAddress = "tiov15nuhg3l8ma2mdmcdvgy7hme20v3xy5mkxcezea" as Address; async function getGovernorOptions( path = adminPath, ): Promise<GovernorOptions & { readonly profile: UserProfile }> { const connection = await BnsConnection.establish(bnsdUrl); const chainId = connection.chainId; const profile = new UserProfile(); const wallet = profile.addWallet(Ed25519HdWallet.fromMnemonic(adminMnemonic)); const identity = await profile.createIdentity(wallet.id, chainId, path); return { connection: connection, identity: identity, guaranteeFundEscrowId: guaranteeFundEscrowId, rewardFundAddress: rewardFundAddress, profile: profile, }; } describe("Governor", () => { it("can be constructed", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); expect(governor).toBeTruthy(); options.connection.disconnect(); }); describe("address", () => { it("returns correct address", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); expect(governor.address).toEqual("tiov15nuhg3l8ma2mdmcdvgy7hme20v3xy5mkxcezea"); options.connection.disconnect(); }); }); describe("getElectorates", () => { it("can get electorates", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const electorates = await governor.getElectorates(); expect(electorates.length).toEqual(2); expect(electorates[0].id).toEqual(1); expect(electorates[1].id).toEqual(2); options.connection.disconnect(); }); it("only lists electorates that contain the governor by default", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const electorates = await governor.getElectorates(); expect(electorates.length).toBeGreaterThanOrEqual(1); for (const electorate of electorates) { const electorAddresses = Object.keys(electorate.electors); expect(electorAddresses).toContain(governor.address); } options.connection.disconnect(); }); it("can get empty list of electorates", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(HdPaths.iov(100)); const governor = new Governor(options); const electorates = await governor.getElectorates(); expect(electorates.length).toEqual(0); options.connection.disconnect(); }); it("can get all electorates when filtering is skipped", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const electorates = await governor.getElectorates(true); expect(electorates.length).toBeGreaterThanOrEqual(3); expect(electorates[0].id).toEqual(1); expect(electorates[1].id).toEqual(2); expect(electorates[2].id).toEqual(3); options.connection.disconnect(); }); it("lists each ID only once", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const electorates = await governor.getElectorates(true); const uniqueIds = new Set(electorates.map((electorate) => electorate.id)); expect(uniqueIds.size).toEqual(electorates.length); options.connection.disconnect(); }); }); describe("getElectionRules", () => { it("returns an empty array for non-existent electorateId", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const electorateId = 100; const electionRules = await governor.getElectionRules(electorateId); expect(electionRules.length).toEqual(0); options.connection.disconnect(); }); it("returns the latest versions of election rules for an electorate", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const electorateId = 1; const electionRules = (await governor.getElectionRules(electorateId)).filter( ({ version }) => version === 1, ); expect(electionRules.length).toEqual(1); expect(electionRules[0].id).toEqual(1); expect(electionRules[0].version).toEqual(1); options.connection.disconnect(); }); }); describe("getProposals", () => { it("can get an empty list of proposals", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(HdPaths.iov(100)); const governor = new Governor(options); const proposals = await governor.getProposals(); expect(proposals.length).toEqual(0); options.connection.disconnect(); }); }); describe("buildCreateProposalTx", () => { it("works for AmendProtocol", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const tx = await governor.buildCreateProposalTx({ type: ProposalType.AmendProtocol, title: "Switch to Proof-of-Work", description: "Proposal to change consensus algorithm to POW", startTime: new ReadonlyDate(1562164525898), electionRuleId: 1, text: "Switch to Proof-of-Work", }); expect(tx).toEqual({ kind: "bns/create_proposal", chainId: options.identity.chainId, title: "Switch to Proof-of-Work", action: { kind: ActionKind.CreateTextResolution, resolution: "Switch to Proof-of-Work", }, description: "Proposal to change consensus algorithm to POW", electionRuleId: 1, startTime: 1562164525, author: governor.address, fee: { tokens: { quantity: "10000000", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, payer: governor.address, }, }); options.connection.disconnect(); }); it("works for AddCommitteeMember", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const address = randomBnsAddress(); const tx = await governor.buildCreateProposalTx({ type: ProposalType.AddCommitteeMember, title: `Add ${address} to committee 5`, description: `Proposal to add ${address} to committee 5`, startTime: new ReadonlyDate(1562164525898), electionRuleId: 1, committee: 5 as CommitteeId, address: address, weight: 4, }); expect(tx).toEqual({ kind: "bns/create_proposal", chainId: options.identity.chainId, title: `Add ${address} to committee 5`, action: { kind: ActionKind.UpdateElectorate, electorateId: 5, diffElectors: { [address]: { weight: 4 }, }, }, description: `Proposal to add ${address} to committee 5`, electionRuleId: 1, startTime: 1562164525, author: governor.address, fee: { tokens: { quantity: "10000000", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, payer: governor.address, }, }); options.connection.disconnect(); }); it("works for RemoveCommitteeMember", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const address = randomBnsAddress(); const tx = await governor.buildCreateProposalTx({ type: ProposalType.RemoveCommitteeMember, title: `Remove ${address} from committee 5`, description: `Proposal to remove ${address} from committee 5`, startTime: new ReadonlyDate(1562164525898), electionRuleId: 1, committee: 5 as CommitteeId, address: address, }); expect(tx).toEqual({ kind: "bns/create_proposal", chainId: options.identity.chainId, title: `Remove ${address} from committee 5`, action: { kind: ActionKind.UpdateElectorate, electorateId: 5, diffElectors: { [address]: { weight: 0 }, }, }, description: `Proposal to remove ${address} from committee 5`, electionRuleId: 1, startTime: 1562164525, author: governor.address, fee: { tokens: { quantity: "10000000", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, payer: governor.address, }, }); options.connection.disconnect(); }); it("works for AmendElectionRuleThreshold", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const tx = await governor.buildCreateProposalTx({ type: ProposalType.AmendElectionRuleThreshold, title: "Amend threshold for committee 5", description: "Proposal to amend threshold to 2/7", startTime: new ReadonlyDate(1562164525898), electionRuleId: 1, targetElectionRuleId: 2, threshold: { numerator: 2, denominator: 7, }, }); expect(tx).toEqual({ kind: "bns/create_proposal", chainId: options.identity.chainId, title: "Amend threshold for committee 5", action: { kind: ActionKind.UpdateElectionRule, electionRuleId: 2, threshold: { numerator: 2, denominator: 7, }, quorum: { numerator: 2, denominator: 3, }, votingPeriod: 10, }, description: "Proposal to amend threshold to 2/7", electionRuleId: 1, startTime: 1562164525, author: governor.address, fee: { tokens: { quantity: "10000000", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, payer: governor.address, }, }); options.connection.disconnect(); }); it("works for AmendElectionRuleQuorum", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const tx = await governor.buildCreateProposalTx({ type: ProposalType.AmendElectionRuleQuorum, title: "Amend quorum for committee 5", description: "Proposal to amend quorum to 2/7", startTime: new ReadonlyDate(1562164525898), electionRuleId: 1, targetElectionRuleId: 2, quorum: { numerator: 2, denominator: 7, }, }); expect(tx).toEqual({ kind: "bns/create_proposal", chainId: options.identity.chainId, title: "Amend quorum for committee 5", action: { kind: ActionKind.UpdateElectionRule, electionRuleId: 2, threshold: { numerator: 1, denominator: 2, }, quorum: { numerator: 2, denominator: 7, }, votingPeriod: 10, }, description: "Proposal to amend quorum to 2/7", electionRuleId: 1, startTime: 1562164525, author: governor.address, fee: { tokens: { quantity: "10000000", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, payer: governor.address, }, }); options.connection.disconnect(); }); it("works for AddValidator", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const pubkey = randomBnsPubkey(); const pubkeyHex = toHex(pubkey.data); const tx = await governor.buildCreateProposalTx({ type: ProposalType.AddValidator, title: `Add ${pubkeyHex} as validator`, description: `Proposal to add ${pubkeyHex} as validator`, startTime: new ReadonlyDate(1562164525898), electionRuleId: 1, pubkey: pubkey, power: 12, }); expect(tx).toEqual({ kind: "bns/create_proposal", chainId: options.identity.chainId, title: `Add ${pubkeyHex} as validator`, action: { kind: ActionKind.SetValidators, validatorUpdates: { [`ed25519_${pubkeyHex}`]: { power: 12 }, }, }, description: `Proposal to add ${pubkeyHex} as validator`, electionRuleId: 1, startTime: 1562164525, author: governor.address, fee: { tokens: { quantity: "10000000", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, payer: governor.address, }, }); options.connection.disconnect(); }); it("works for RemoveValidator", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const pubkey = randomBnsPubkey(); const pubkeyHex = toHex(pubkey.data); const tx = await governor.buildCreateProposalTx({ type: ProposalType.RemoveValidator, title: `Remove validator ${pubkeyHex}`, description: `Proposal to remove validator ${pubkeyHex}`, startTime: new ReadonlyDate(1562164525898), electionRuleId: 1, pubkey: pubkey, }); expect(tx).toEqual({ kind: "bns/create_proposal", chainId: options.identity.chainId, title: `Remove validator ${pubkeyHex}`, action: { kind: ActionKind.SetValidators, validatorUpdates: { [`ed25519_${pubkeyHex}`]: { power: 0 }, }, }, description: `Proposal to remove validator ${pubkeyHex}`, electionRuleId: 1, startTime: 1562164525, author: governor.address, fee: { tokens: { quantity: "10000000", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, payer: governor.address, }, }); options.connection.disconnect(); }); it("works for ReleaseGuaranteeFunds", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const tx = await governor.buildCreateProposalTx({ type: ProposalType.ReleaseGuaranteeFunds, title: "Release guarantee funds", description: "Proposal to release guarantee funds", startTime: new ReadonlyDate(1562164525898), electionRuleId: 1, amount: { quantity: "2000000002", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, }); expect(tx).toEqual({ kind: "bns/create_proposal", chainId: options.identity.chainId, title: "Release guarantee funds", action: { kind: ActionKind.ReleaseEscrow, escrowId: guaranteeFundEscrowId, amount: { quantity: "2000000002", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, }, description: "Proposal to release guarantee funds", electionRuleId: 1, startTime: 1562164525, author: governor.address, fee: { tokens: { quantity: "10000000", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, payer: governor.address, }, }); options.connection.disconnect(); }); it("works for DistributeFunds", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const { connection, identity, profile } = options; const address = connection.codec.identityToAddress(identity); const cleanRewardFundAddress = Bech32.encode("tiov", Random.getBytes(20)) as Address; const governor = new Governor({ ...options, rewardFundAddress: cleanRewardFundAddress, }); const sendTx = await connection.withDefaultFee( { kind: "bcp/send", chainId: identity.chainId, sender: address, recipient: cleanRewardFundAddress, amount: { quantity: "999000000000", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, }, address, ); const nonce = await connection.getNonce({ pubkey: identity.pubkey }); const signed = await profile.signTransaction(identity, sendTx, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); const recipient1 = randomBnsAddress(); const recipient2 = randomBnsAddress(); const tx = await governor.buildCreateProposalTx({ type: ProposalType.DistributeFunds, title: "Distribute funds", description: "Proposal to distribute funds", startTime: new ReadonlyDate(1562164525898), electionRuleId: 1, recipients: [ { address: recipient1, weight: 2, }, { address: recipient2, weight: 5, }, ], }); expect(tx).toEqual({ kind: "bns/create_proposal", chainId: identity.chainId, title: "Distribute funds", action: { kind: ActionKind.ExecuteProposalBatch, messages: [ { kind: ActionKind.Send, sender: cleanRewardFundAddress, recipient: recipient1, amount: { quantity: "285428571428", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, }, { kind: ActionKind.Send, sender: cleanRewardFundAddress, recipient: recipient2, amount: { quantity: "713571428571", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, }, ], }, description: "Proposal to distribute funds", electionRuleId: 1, startTime: 1562164525, author: address, fee: { tokens: { quantity: "10000000", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, payer: address, }, }); connection.disconnect(); }); it("works for ExecuteMigration", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const { connection, identity } = options; const governor = new Governor({ ...options }); const tx = await governor.buildCreateProposalTx({ type: ProposalType.ExecuteMigration, title: "Execute this migration", description: "for some good reason", startTime: new ReadonlyDate(1562164525898), electionRuleId: 1, id: "foobar", }); expect(tx).toEqual({ kind: "bns/create_proposal", chainId: identity.chainId, title: "Execute this migration", description: "for some good reason", action: { kind: ActionKind.ExecuteMigration, id: "foobar", }, electionRuleId: 1, startTime: 1562164525, author: governor.address, fee: { tokens: { quantity: "10000000", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, payer: governor.address, }, }); connection.disconnect(); }); }); describe("createVoteTx", () => { it("can build a Vote transaction", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const tx = await governor.buildVoteTx(5, VoteOption.Yes); expect(tx).toEqual({ kind: "bns/vote", chainId: options.identity.chainId, proposalId: 5, selection: VoteOption.Yes, voter: governor.address, fee: { tokens: { quantity: "10000000", fractionalDigits: 9, tokenTicker: "CASH" as TokenTicker, }, payer: governor.address, }, }); options.connection.disconnect(); }); }); describe("getVotes", () => { it("can get all votes cast by a governor", async () => { pendingWithoutBnsd(); const options = await getGovernorOptions(); const governor = new Governor(options); const { connection, identity, profile } = options; const createProposalTx = await governor.buildCreateProposalTx({ type: ProposalType.AmendProtocol, title: "Test getVote", description: "Proposal to test getVote", startTime: new ReadonlyDate(Date.now() + 1000), electionRuleId: 1, text: "Get a vote", }); const nonce1 = await connection.getNonce({ pubkey: identity.pubkey }); const signed1 = await profile.signTransaction(identity, createProposalTx, bnsCodec, nonce1); const response1 = await connection.postTx(bnsCodec.bytesToPost(signed1)); await response1.blockInfo.waitFor((info) => !isBlockInfoPending(info)); await sleep(7000); const votesPre = await governor.getVotes(); const proposals = await governor.getProposals(); const proposalId = proposals[proposals.length - 1].id; const voteTx = await governor.buildVoteTx(proposalId, VoteOption.Yes); const nonce2 = await connection.getNonce({ pubkey: identity.pubkey }); const signed2 = await profile.signTransaction(identity, voteTx, bnsCodec, nonce2); const response2 = await connection.postTx(bnsCodec.bytesToPost(signed2)); await response2.blockInfo.waitFor((info) => !isBlockInfoPending(info)); const votesPost = await governor.getVotes(); expect(votesPost.length).toEqual(votesPre.length + 1); expect(votesPost[votesPost.length - 1].proposalId).toEqual(proposalId); expect(votesPost[votesPost.length - 1].selection).toEqual(VoteOption.Yes); connection.disconnect(); }); }); });
the_stack
import {CdkDragDrop} from '@angular/cdk/drag-drop'; import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import {FormsModule} from '@angular/forms'; import {MatFormFieldModule} from '@angular/material/form-field'; import {MatIconModule} from '@angular/material/icon'; import {MatInputModule} from '@angular/material/input'; import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from '@angular/platform-browser-dynamic/testing'; import {BehaviorSubject} from 'rxjs'; import {CollectionParameters, CpuIdleWaitLayer, CpuRunningLayer, CpuWaitQueueLayer, Layer} from '../../models'; import {Viewport} from '../../util'; import {SettingsMenu} from './settings_menu'; import {SettingsMenuModule} from './settings_menu_module'; try { TestBed.initTestEnvironment( BrowserDynamicTestingModule, platformBrowserDynamicTesting()); } catch { // Ignore exceptions when calling it multiple times. } const RED_HEX = '#ff0000'; const GREEN_HEX = '#00ff00'; // Delay time which will guarantee flush of time input const TIME_INPUT_DEBOUNCE_MS = 1000; function setupSettingsMenu(component: SettingsMenu) { component.parameters = new BehaviorSubject<CollectionParameters|undefined>( new CollectionParameters('collection_params', [], 0, 2e9)); component.viewport = new BehaviorSubject<Viewport>(new Viewport()); component.layers = new BehaviorSubject<Array<BehaviorSubject<Layer>>>([]); component.showMigrations = new BehaviorSubject<boolean>(true); component.showSleeping = new BehaviorSubject<boolean>(true); component.maxIntervalCount = new BehaviorSubject<number>(0); } function mockLayers(): Array<BehaviorSubject<Layer>> { const layers: Array<BehaviorSubject<Layer>> = []; const layerCount = 10; for (let i = 0; i < layerCount; i++) { // Use arbitrary colors spread evenly across the color space const maxHexColor = 0xFFFFFF; const colorVal = Math.floor(i * (maxHexColor - layerCount) / layerCount); const color = `#${colorVal.toString(16)}`; const layer = new Layer(`Mock Layer ${i}`, '', undefined, color); layers.push(new BehaviorSubject(layer)); } return layers; } async function createSettingsMenuWithMockData( layers: Array<BehaviorSubject<Layer>>): Promise<ComponentFixture<SettingsMenu>> { const fixture = TestBed.createComponent(SettingsMenu); const component = fixture.componentInstance; setupSettingsMenu(component); component.layers.next(layers); await fixture.whenStable(); fixture.detectChanges(); return fixture; } function getLayerColorInput( root: Element, layerIndex: number): HTMLInputElement { const layerList = root.querySelector('.layer-list'); expect(layerList).toBeTruthy(); const colorInputs = layerList!.querySelectorAll('.color-input'); expect(colorInputs.length).toBeGreaterThan(layerIndex); const colorInput = colorInputs[layerIndex]; expect(colorInput instanceof HTMLInputElement).toBe(true); return colorInput as HTMLInputElement; } function isLayerVisible(root: Element, layerIndex: number): boolean { const layerList = root.querySelector('.layer-list'); expect(layerList).toBeTruthy(); const layerContainers = layerList!.querySelectorAll('.layer-box'); expect(layerContainers.length).toBeGreaterThan(layerIndex); const layerContainer = layerContainers[layerIndex]; return !layerContainer.classList.contains('hidden'); } describe('SettingsMenu', () => { beforeEach(async () => { document.body.style.width = '500px'; document.body.style.height = '500px'; await TestBed .configureTestingModule({ imports: [ FormsModule, MatFormFieldModule, MatInputModule, MatIconModule, SettingsMenuModule ], }) .compileComponents(); }); it('should create', async () => { const layers = mockLayers(); const fixture = await createSettingsMenuWithMockData(layers); expect(fixture.componentInstance).toBeTruthy(); }); it('should respond to layer change', async () => { // Set up menu with initial layer data const expectedInitialColor = RED_HEX; const expectedInitialVisibility = true; const initialLayer = new Layer( 'Layer to Change', '', undefined, expectedInitialColor, undefined, expectedInitialVisibility); const layerSubject = new BehaviorSubject<Layer>(initialLayer); const layers = mockLayers(); const layerIndex = 4; layers.splice(layerIndex, 0, layerSubject); const fixture = await createSettingsMenuWithMockData(layers); // Verify initial layer data const actualInitialColor = getLayerColorInput(fixture.nativeElement, layerIndex).value; expect(actualInitialColor).toEqual(expectedInitialColor); const actualInitialVisibility = isLayerVisible(fixture.nativeElement, layerIndex); expect(actualInitialVisibility).toBe(expectedInitialVisibility); // Modify layer const expectedNewVisibility = false; const expectedNewColor = GREEN_HEX; const newLayer = new Layer( initialLayer.name, '', undefined, expectedNewColor, undefined, expectedNewVisibility); layerSubject.next(newLayer); await fixture.whenStable(); fixture.detectChanges(); // Verify layer was modified const actualNewColor = getLayerColorInput(fixture.nativeElement, layerIndex).value; expect(actualNewColor).toEqual(expectedNewColor); const actualNewVisibility = isLayerVisible(fixture.nativeElement, layerIndex); expect(actualNewVisibility).toBe(expectedNewVisibility); }); it('should allow drag drop of layers', async () => { // Set up menu const layers = mockLayers(); const fixture = await createSettingsMenuWithMockData(layers); // Simulate drag-drop of layer into a new index const initialIndex = 5; const newIndex = 2; const initialLayer = layers[initialIndex]; const dropEvent = {previousIndex: initialIndex, currentIndex: newIndex} as CdkDragDrop<string[]>; fixture.componentInstance.drop(dropEvent); fixture.detectChanges(); // Verify that the layer was moved const layerSpy = jasmine.createSpy('layerSpy'); fixture.componentInstance.layers.subscribe(layerSpy); expect(layerSpy.calls.mostRecent().args[0][newIndex]).toBe(initialLayer); }); it('should propagate layer changes', async () => { // Set up menu with initial layer data const initialColor = RED_HEX; const initialVisibility = true; const initialLayer = new Layer( 'Layer to Change', '', undefined, initialColor, undefined, initialVisibility); const layerSubject = new BehaviorSubject<Layer>(initialLayer); const layers = mockLayers(); const layerIndex = 2; layers.splice(layerIndex, 0, layerSubject); const fixture = await createSettingsMenuWithMockData(layers); const layerSubjectSpy = jasmine.createSpy('layerSubjectSpy'); layerSubject.subscribe(layerSubjectSpy); expect(layerSubjectSpy).toHaveBeenCalledTimes(1); // Change the layer color const colorInput = getLayerColorInput(fixture.nativeElement, layerIndex); const expectedNewColor = GREEN_HEX; colorInput.value = expectedNewColor; colorInput.dispatchEvent(new Event('input')); await fixture.whenStable(); fixture.detectChanges(); // Verify that the layer was changed expect(layerSubjectSpy).toHaveBeenCalledTimes(2); const newLayer = layerSubjectSpy.calls.mostRecent().args[0] as Layer; expect(newLayer.color).toEqual(expectedNewColor); }); it('should update viewport on valid time input change', fakeAsync(() => { const fixture = TestBed.createComponent(SettingsMenu); const component = fixture.componentInstance; setupSettingsMenu(component); fixture.detectChanges(); const inputs = fixture.nativeElement.querySelectorAll('.viewport-input'); inputs[0].value = '50 ms'; inputs[0].dispatchEvent(new Event('input')); tick(TIME_INPUT_DEBOUNCE_MS); expect(component.viewport.value.left).toBe(0.025); expect(component.viewport.value.right).toBe(1.0); })); it('should not update viewport on invalid time input change', fakeAsync(() => { const fixture = TestBed.createComponent(SettingsMenu); const component = fixture.componentInstance; setupSettingsMenu(component); fixture.detectChanges(); const inputs = fixture.nativeElement.querySelectorAll('.viewport-input'); // Don't update if invalid inputs[0].value = '50 ms'; inputs[0].dispatchEvent(new Event('input')); inputs[1].value = '5 ms'; inputs[1].dispatchEvent(new Event('input')); tick(TIME_INPUT_DEBOUNCE_MS); expect(component.viewport.value.left).toBe(0.025); expect(component.viewport.value.right).toBe(1.0); // Update when valid inputs[1].value = '55 ms'; inputs[1].dispatchEvent(new Event('input')); tick(TIME_INPUT_DEBOUNCE_MS); expect(component.viewport.value.left).toBe(0.025); expect(component.viewport.value.right).toBe(0.0275); })); it('should clip out of range time inputs', fakeAsync(() => { const fixture = TestBed.createComponent(SettingsMenu); const component = fixture.componentInstance; setupSettingsMenu(component); fixture.detectChanges(); const inputs = fixture.nativeElement.querySelectorAll('.viewport-input'); // Correct bad inputs inputs[0].value = '50 ms'; inputs[0].dispatchEvent(new Event('input')); inputs[1].value = '3000 ms'; inputs[1].dispatchEvent(new Event('input')); tick(TIME_INPUT_DEBOUNCE_MS); expect(component.viewport.value.left).toBe(0.025); expect(component.viewport.value.right).toBe(1.0); })); it('should show fixed layers separately', async () => { // Set up menu const layers = [ new BehaviorSubject(new CpuRunningLayer() as unknown as Layer), new BehaviorSubject(new CpuIdleWaitLayer() as unknown as Layer), new BehaviorSubject(new CpuWaitQueueLayer() as unknown as Layer), ].concat(mockLayers()); const fixture = await createSettingsMenuWithMockData(layers); const component = fixture.componentInstance; expect(component.fixedLayers).toEqual(layers.slice(0, 3)); expect(component.adjustableLayers).toEqual(layers.slice(3)); }); });
the_stack
import { builderContentToJsxLiteComponent, componentToBuilder, componentToJsxLite, parseJsx, } from "@jsx-lite/core"; import * as vscode from "vscode"; import { BuilderJSXLiteEditorProvider } from "./builder-jsx-lite-editor"; import { useBeta, useDev } from "./config"; export function activate(context: vscode.ExtensionContext) { context.subscriptions.push( vscode.commands.registerCommand("builder.start", () => { BuilderPanel.createOrShow(context.extensionUri); }) ); function openPreviewToTheSide(uri?: vscode.Uri) { let resource = uri; if (!(resource instanceof vscode.Uri)) { if (vscode.window.activeTextEditor) { // we are relaxed and don't check for markdown files resource = vscode.window.activeTextEditor.document.uri; } } BuilderPanel.openEditor(resource!, vscode.window.activeTextEditor!, { viewColumn: vscode.ViewColumn.Two, preserveFocus: true, }); } context.subscriptions.push( vscode.commands.registerCommand( "builder.openJsxLiteEditorToTheSide", openPreviewToTheSide ) ); context.subscriptions.push(BuilderJSXLiteEditorProvider.register(context)); if (vscode.window.registerWebviewPanelSerializer) { // Make sure we register a serializer in activation event vscode.window.registerWebviewPanelSerializer(BuilderPanel.viewType, { async deserializeWebviewPanel( webviewPanel: vscode.WebviewPanel, state: any ) { BuilderPanel.revive(webviewPanel, context.extensionUri); }, }); } } class BuilderPanel { /** * Track the currently panel. Only allow a single panel to exist at a time. */ public static currentPanel: BuilderPanel | undefined; public static readonly viewType = "catCoding"; private readonly _panel: vscode.WebviewPanel; private readonly _extensionUri: vscode.Uri; private _disposables: vscode.Disposable[] = []; public static openEditor( sourceUri: vscode.Uri, editor: vscode.TextEditor, viewOptions: { viewColumn: vscode.ViewColumn; preserveFocus?: boolean } ) { // Otherwise, create a new panel. const panel = vscode.window.createWebviewPanel( BuilderPanel.viewType, "Builder.io", viewOptions, { // Enable javascript in the webview enableScripts: true, // And restrict the webview to only loading content from our extension's `media` directory. localResourceRoots: [vscode.Uri.joinPath(sourceUri, "media")], } ); BuilderPanel.currentPanel = new BuilderPanel(panel, sourceUri, editor); } public static createOrShow(extensionUri: vscode.Uri) { const column = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : undefined; // If we already have a panel, show it. if (BuilderPanel.currentPanel) { BuilderPanel.currentPanel._panel.reveal(column); return; } // Otherwise, create a new panel. const panel = vscode.window.createWebviewPanel( BuilderPanel.viewType, "Builder.io", column || vscode.ViewColumn.One, { // Enable javascript in the webview enableScripts: true, // And restrict the webview to only loading content from our extension's `media` directory. localResourceRoots: [vscode.Uri.joinPath(extensionUri, "media")], } ); BuilderPanel.currentPanel = new BuilderPanel(panel, extensionUri); } public static revive(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) { BuilderPanel.currentPanel = new BuilderPanel(panel, extensionUri); } private constructor( panel: vscode.WebviewPanel, extensionUri: vscode.Uri, private editor?: vscode.TextEditor ) { this._panel = panel; this._extensionUri = extensionUri; // Set the webview's initial html content this._update(); // Listen for when the panel is disposed // This happens when the user closes the panel or when the panel is closed programatically this._panel.onDidDispose(() => this.dispose(), null, this._disposables); // Handle messages from the webview this._panel.webview.onDidReceiveMessage( (message) => { switch (message.type) { case "builder.editorLoaded": { const text = this.editor!.document.getText(); const parsed = parseJsx(text); const builderContent = componentToBuilder(parsed); this._panel.webview.postMessage({ type: "builder.textChanged", data: { builderJson: builderContent, }, }); return; } case "builder.openWindow": { const url = message.data.url; vscode.env.openExternal(vscode.Uri.parse(url)); return; } case "builder.saveContent": { const content = message.data.content; if (typeof content?.data?.blocksString === "string") { content.data.blocks = JSON.parse(content.data.blocksString); delete content.data.blocksString; } const jsxLiteJson = builderContentToJsxLiteComponent(content); const jsxLite = componentToJsxLite(jsxLiteJson); const edit = new vscode.WorkspaceEdit(); const document = this.editor!.document; edit.replace( document.uri, new vscode.Range(0, 0, document.lineCount, 0), jsxLite ); vscode.workspace.applyEdit(edit); document.save(); return; } } }, null, this._disposables ); if (this.editor) { this._disposables.push( vscode.workspace.onDidChangeTextDocument((event) => { // const text = event.document.getText(); // const parsed = parseJsx(text); // const builderContent = componentToBuilder(parsed); // this._panel.webview.postMessage({ // type: "builder.textChanged", // data: { // builderJson: builderContent, // }, // }); }) ); this._disposables.push( vscode.workspace.onDidSaveTextDocument((document) => { const text = document.getText(); const parsed = parseJsx(text); const builderContent = componentToBuilder(parsed); this._panel.webview.postMessage({ type: "builder.textChanged", data: { builderJson: builderContent, }, }); console.info("save"); }) ); this._disposables.push( vscode.window.onDidChangeTextEditorSelection((event) => { // TODO: sync text cursor/selection with builder scroll/selection console.info("selection change", event); }) ); this._disposables.push( vscode.window.onDidChangeActiveTextEditor((event) => { console.info("active editor change", event); }) ); } } public doRefactor() { // Send a message to the webview webview. // You can send any JSON serializable data. this._panel.webview.postMessage({ command: "refactor" }); } public dispose() { BuilderPanel.currentPanel = undefined; // Clean up our resources this._panel.dispose(); while (this._disposables.length) { const x = this._disposables.pop(); if (x) { x.dispose(); } } } private _update() { const webview = this._panel.webview; this._updateWebview(webview); } private _updateWebview(webview: vscode.Webview) { this._panel.webview.html = this._getHtmlForWebview(webview); } private _getHtmlForWebview(webview: vscode.Webview) { // Local path to main script run in the webview const scriptPathOnDisk = vscode.Uri.joinPath( this._extensionUri, "media", "main.js" ); // And the uri we use to load this script in the webview const scriptUri = webview.asWebviewUri(scriptPathOnDisk); // Local path to css styles const styleResetPath = vscode.Uri.joinPath( this._extensionUri, "media", "reset.css" ); const stylesPathMainPath = vscode.Uri.joinPath( this._extensionUri, "media", "vscode.css" ); // Uri to load styles into webview const stylesResetUri = webview.asWebviewUri(styleResetPath); const stylesMainUri = webview.asWebviewUri(stylesPathMainPath); // Use a nonce to only allow specific scripts to be run const nonce = getNonce(); return `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!-- Use a content security policy to only allow loading images from https or from our extension directory, and only allow scripts that have a specific nonce. --> <meta http-equiv="Content-Security-Policy" content="default-src 'none'; frame-src ${ useDev ? "*" : "https://*" }; style-src https://* ${webview.cspSource} 'nonce-${nonce}'; img-src ${ webview.cspSource } https:; script-src 'nonce-${nonce}';"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="${stylesResetUri}" rel="stylesheet"> <link href="${stylesMainUri}" rel="stylesheet"> <title>Builder.io</title> </head> <body> <style nonce="${nonce}"> .fiddle-frame { border: none; position: absolute; top: -10%; left: -10%; right: -10%; bottom: -10%; width: 120%; height: 120%; transform: scale(0.8333); } </style> <iframe class="fiddle-frame" src="${ useDev ? "http://localhost:1234" : useBeta ? "https://beta.builder.io" : "https://builder.io" }/fiddle"></iframe> <script nonce="${nonce}"> /* eslint-disable no-undef */ const vscode = acquireVsCodeApi(); // This script will be run within the webview itself // It cannot access the main VS Code APIs directly. (function () { /** @type {HTMLIFrameElement} */ const frame = document.querySelector(".fiddle-frame"); window.addEventListener("message", (e) => { const data = e.data; if (data) { if (data.type === "builder.textChanged") { frame.contentWindow.postMessage({ type: "builder.updateEditorData", data: { data: data.data.builderJson } }, '*'); } if (data.type === "builder.editorLoaded") { // Loaded - message down the data vscode.postMessage({ type: "builder.editorLoaded" }); } if (data.type === "builder.openWindow") { // Loaded - message down the data vscode.postMessage(data); } if (data.type === "builder.saveContent") { // Loaded - data updated vscode.postMessage({ type: "builder.saveContent", data: data.data }); } } }); })(); </script> </body> </html>`; } } function getNonce() { let text = ""; const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (let i = 0; i < 32; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; }
the_stack
import { eventChannel } from 'redux-saga' import { all, takeEvery, call, put, take, select } from 'redux-saga/effects' import { ActionType, getType } from 'typesafe-actions' import RNPushNotification from 'react-native-push-notification' import Textile, { EventSubscription, FeedItemType } from '@textile/react-native-sdk' import Long from 'long' import { toTypedNotification } from '../Services/Notifications' import { logNewEvent } from './DeviceLogs' import { pendingInvitesTask, cameraRollThreadCreateTask } from './ThreadsSagas' import { PreferencesSelectors } from '../Redux/PreferencesRedux' import { RootAction } from '../Redux/Types' import TextileEventsActions, { TextileEventsAction } from '../Redux/TextileEventsRedux' import GroupsActions, { GroupsAction } from '../Redux/GroupsRedux' import { contactsActions, ContactsAction } from '../features/contacts' import { updatesActions, UpdatesAction } from '../features/updates' import DeviceLogsActions, { DeviceLogsAction } from '../Redux/DeviceLogsRedux' import { groupActions, GroupAction } from '../features/group' import AppConfig from '../Config/app-config' function displayNotification(message: string, title?: string) { RNPushNotification.localNotification({ title, message, playSound: false, vibrate: false }) } function nodeEvents() { return eventChannel< | GroupAction | GroupsAction | ContactsAction | DeviceLogsAction | UpdatesAction | TextileEventsAction >(emitter => { const subscriptions: EventSubscription[] = [] subscriptions.push( Textile.events.addThreadUpdateReceivedListener( (threadId, feedItemData) => { if ( feedItemData.type === FeedItemType.Text || feedItemData.type === FeedItemType.Comment || feedItemData.type === FeedItemType.Like || feedItemData.type === FeedItemType.Files || feedItemData.type === FeedItemType.Ignore || feedItemData.type === FeedItemType.Join || feedItemData.type === FeedItemType.Leave ) { emitter(groupActions.feed.refreshFeed.request({ id: threadId })) } // TODO: remove this if needed if ( feedItemData.type === FeedItemType.Comment || feedItemData.type === FeedItemType.Like || feedItemData.type === FeedItemType.Files || feedItemData.type === FeedItemType.Ignore || feedItemData.type === FeedItemType.Join ) { emitter(GroupsActions.refreshThreadRequest(threadId)) } if ( feedItemData.type === FeedItemType.Join || feedItemData.type === FeedItemType.Leave ) { // Every time the a JOIN or LEAVE block is detected, we should refresh our in-mem contact list // Enhancement: compare the joiner id with known ids and skip the refresh if known. emitter(contactsActions.getContactsRequest()) // Temporary: to ensure that our UI udpates after a self-join or a self-leave emitter(GroupsActions.refreshThreadRequest(threadId)) } // create a local log line for the threadUpdate event const message = `BlockType ${feedItemData.type} on ${threadId}` emitter( DeviceLogsActions.logNewEvent( new Date().getTime(), 'onThreadUpdate', message, false ) ) } ) ) subscriptions.push( Textile.events.addThreadAddedListener(threadId => { emitter(GroupsActions.threadAddedNotification(threadId)) }) ) subscriptions.push( Textile.events.addThreadRemovedListener(threadId => { emitter(GroupsActions.threadRemoved(threadId)) }) ) subscriptions.push( Textile.events.addNotificationReceivedListener(notification => { emitter( updatesActions.newNotificationRequest( toTypedNotification(notification) ) ) }) ) subscriptions.push( Textile.events.addNodeStartedListener(() => { emitter(TextileEventsActions.nodeStarted()) }) ) subscriptions.push( Textile.events.addNodeStoppedListener(() => { emitter(TextileEventsActions.nodeStopped()) }) ) subscriptions.push( Textile.events.addNodeOnlineListener(() => { emitter(TextileEventsActions.nodeOnline()) }) ) subscriptions.push( Textile.events.addNodeFailedToStartListener(error => { emitter(TextileEventsActions.nodeFailedToStart(error)) }) ) subscriptions.push( Textile.events.addNodeFailedToStopListener(error => { emitter(TextileEventsActions.nodeFailedToStop(error)) }) ) subscriptions.push( Textile.events.addWillStopNodeInBackgroundAfterDelayListener(delay => { emitter(TextileEventsActions.stopNodeAfterDelayStarting(delay)) }) ) subscriptions.push( Textile.events.addCanceledPendingNodeStopListener(() => { emitter(TextileEventsActions.stopNodeAfterDelayCancelled()) }) ) subscriptions.push( Textile.events.addSyncUpdateListener(status => { const sizeComplete = Long.fromValue(status.sizeComplete).toNumber() const sizeTotal = Long.fromValue(status.sizeTotal).toNumber() const groupSizeComplete = Long.fromValue( status.groupsSizeComplete ).toNumber() const groupSizeTotal = Long.fromValue(status.groupsSizeTotal).toNumber() const total = Math.max(sizeTotal, groupSizeTotal) const { id, numComplete, numTotal } = status emitter( groupActions.fileSync.syncUpdate( id, numComplete, numTotal, groupSizeComplete, total ) ) }) ) subscriptions.push( Textile.events.addSyncCompleteListener(status => { emitter(groupActions.fileSync.syncComplete(status.id)) }) ) subscriptions.push( Textile.events.addSyncFailedListener(status => { const { id, errorId, error } = status emitter(groupActions.fileSync.syncFailed(id, errorId, error)) }) ) return () => { for (const subscription of subscriptions) { subscription.cancel() } } }) } function* handleNodeEvents() { const chan = yield call(nodeEvents) try { while (true) { // take(END) will cause the saga to terminate by jumping to the finally block const action = yield take(chan) yield put(action) } } finally { // should never terminate } } export function* refreshMessages() { while (true) { try { // Block until we get an active or background app state const action: ActionType< typeof TextileEventsActions.refreshMessagesRequest > = yield take( (action: RootAction) => action.type === getType(TextileEventsActions.refreshMessagesRequest) ) yield call(Textile.cafes.checkMessages) yield call(logNewEvent, 'refreshMessages', action.type) } catch (error) { yield call(logNewEvent, 'refreshMessages', error.message, true) } } } export function* ignoreFileRequest() { while (true) { try { // Block until we get an active or background app state const action: ActionType< typeof TextileEventsActions.ignoreFileRequest > = yield take( (action: RootAction) => action.type === getType(TextileEventsActions.ignoreFileRequest) ) yield call(Textile.ignores.add, action.payload.blockId) yield call(logNewEvent, 'ignoreFile', action.type) } catch (error) { yield call(logNewEvent, 'ignoreFileRequest', error.message, true) } } } export function* nodeOnline() { while (yield take(getType(TextileEventsActions.nodeOnline))) { yield call(logNewEvent, 'Node is:', 'online') } } export function* startNodeFinished() { while (true) { try { // Block until we get an active or background app state const action: ActionType< typeof TextileEventsActions.nodeStarted > = yield take( (action: RootAction) => action.type === getType(TextileEventsActions.nodeStarted) ) // Handle any pending invites now that we are finished yield call(pendingInvitesTask) yield call(cameraRollThreadCreateTask) } catch (error) { yield call(logNewEvent, 'startNodeFinished', error.message, true) } } } export function* stopNodeAfterDelayStarting() { while (true) { try { // Block until we get an active or background app state const action: ActionType< typeof TextileEventsActions.stopNodeAfterDelayStarting > = yield take( (action: RootAction) => action.type === getType(TextileEventsActions.stopNodeAfterDelayStarting) ) if (yield select(PreferencesSelectors.showNodeStateNotification)) { yield call( displayNotification, `Running the node for ${action.payload.delay} sec. in the background` ) } } catch (error) { yield call(logNewEvent, 'stopNodeAfterDelayStarting', error.message, true) } } } export function* stopNodeAfterDelayCancelled() { while (true) { try { // Block until we get an active or background app state const action: ActionType< typeof TextileEventsActions.stopNodeAfterDelayCancelled > = yield take( (action: RootAction) => action.type === getType(TextileEventsActions.stopNodeAfterDelayCancelled) ) // Let it keep running if (yield select(PreferencesSelectors.showNodeStateNotification)) { yield call( displayNotification, 'Delayed stop of node canceled because of foreground event' ) } } catch (error) { yield call( logNewEvent, 'stopNodeAfterDelayCancelled', error.message, true ) } } } export function* stopNodeAfterDelayComplete() { while (true) { try { // Block until we get an active or background app state const action: ActionType< typeof TextileEventsActions.nodeStopped > = yield take( (action: RootAction) => action.type === getType(TextileEventsActions.nodeStopped) ) if (yield select(PreferencesSelectors.showNodeStateNotification)) { yield call(displayNotification, 'Node stopped') } } catch (error) { yield call(logNewEvent, 'stopNodeAfterDelayComplete', error.message, true) } } } export function* newError() { while (true) { try { // Block until we get an active or background app state const action: ActionType< typeof TextileEventsActions.newErrorMessage > = yield take( (action: RootAction) => action.type === getType(TextileEventsActions.newErrorMessage) ) if (yield select(PreferencesSelectors.showNodeErrorNotification)) { yield call( displayNotification, action.payload.type, action.payload.message ) } yield call(logNewEvent, action.payload.type, action.payload.message, true) } catch (error) { yield call(logNewEvent, 'newError error', error.message, true) } } } export function* startSagas() { yield all([ call(handleNodeEvents), call(startNodeFinished), call(stopNodeAfterDelayStarting), call(stopNodeAfterDelayCancelled), call(stopNodeAfterDelayComplete), call(refreshMessages), call(ignoreFileRequest), call(nodeOnline), call(newError) ]) }
the_stack
import { PivotFieldList } from '../../src/pivotfieldlist/base/field-list'; import { createElement, remove, EmitType, closest, getInstance } from '@syncfusion/ej2-base'; import { pivot_dataset } from '../base/datasource.spec'; import { IDataSet } from '../../src/base/engine'; import { MaskedTextBox } from '@syncfusion/ej2-inputs'; import { TreeView } from '@syncfusion/ej2-navigations'; import { LoadEventArgs, FieldDragStartEventArgs, FieldDropEventArgs, FieldDroppedEventArgs, FieldRemoveEventArgs, CalculatedFieldCreateEventArgs } from '../../src/common/base/interface'; import { CalculatedField } from '../../src/common/calculatedfield/calculated-field'; import * as util from '../utils.spec'; import { profile, inMB, getMemoryProfile } from '../common.spec'; describe('Field List rendering on mobile device', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe('Static rendering', () => { let originalTimeout: number; let fieldListObj: PivotFieldList; let elem: HTMLElement = createElement('div', { id: 'PivotFieldList', styles: 'height:400px;width:100%' }); afterAll(() => { if (fieldListObj) { fieldListObj.destroy(); } remove(elem); }); beforeAll((done: Function) => { originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; if (document.getElementById(elem.id)) { remove(document.getElementById(elem.id)); } document.body.appendChild(elem); let dataBound: EmitType<Object> = () => { done(); }; fieldListObj = new PivotFieldList({ dataSourceSettings: { dataSource: pivot_dataset as IDataSet[], expandAll: false, enableSorting: true, sortSettings: [{ name: 'company', order: 'Descending' }], filterSettings: [{ name: 'name', type: 'Include', items: ['Knight Wooten'] }, { name: 'company', type: 'Exclude', items: ['NIPAZ'] }, { name: 'gender', type: 'Include', items: ['male'] }], rows: [{ name: 'company' }, { name: 'state' }], columns: [{ name: 'name' }], values: [{ name: 'balance' }, { name: 'quantity' }], filters: [{ name: 'gender' }] }, allowCalculatedField: true, dataBound: dataBound, renderMode: 'Fixed', load: (args: LoadEventArgs) => { fieldListObj.isAdaptive = true; }, fieldDragStart: (args: FieldDragStartEventArgs) => { expect(args.fieldItem).toBeTruthy; expect(args.cancel).toBe(false); console.log('fieldDragName: ' + args.fieldItem.name); }, fieldDrop: (args: FieldDropEventArgs) => { expect(args.dropField).toBeTruthy; expect(args.cancel).toBe(false); console.log('fieldDropName: ' + args.dropField.name); }, onFieldDropped: (args: FieldDroppedEventArgs) => { expect(args.droppedField).toBeTruthy; console.log('fieldDroppedName: ' + args.droppedField.name); }, fieldRemove: (args: FieldRemoveEventArgs) => { expect(args.fieldItem).toBeTruthy; expect(args.cancel).toBe(false); console.log('fieldRemoveName: ' + args.fieldItem.name); }, calculatedFieldCreate: (args: CalculatedFieldCreateEventArgs) => { expect(args.calculatedField).toBeTruthy; expect(args.cancel).toBe(false); console.log('CreateCalcaltedFieldName: ' + args.calculatedField.name); } }); fieldListObj.appendTo('#PivotFieldList'); fieldListObj.calculatedFieldModule = new CalculatedField(fieldListObj); }); let persistdata: string; it('control class testing for mobile device', () => { expect(fieldListObj.element.classList.contains('e-pivotfieldlist')).toEqual(true); expect(fieldListObj.element.classList.contains('e-device')).toEqual(true); }); it('get component name testing', () => { expect(fieldListObj.getModuleName()).toEqual('pivotfieldlist'); }); it('check on axis view change', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); expect([].slice.call(element.querySelectorAll('.e-toolbar-item')).length).toEqual(5); let headerElement: HTMLElement[] = [].slice.call(element.querySelectorAll('.e-toolbar-item')); expect(headerElement[0].classList.contains('e-active')).toBeTruthy; headerElement[1].click(); setTimeout(() => { expect(headerElement[1].textContent).toBe('Columns'); expect(headerElement[1].classList.contains('e-active')).toBeTruthy; let addButton: HTMLElement = element.querySelector('.e-field-list-footer').querySelector('.e-field-list-btn'); expect(addButton.classList.contains('e-disable')).not.toBeTruthy; done(); }, 1000); }); it('check on axis view change to calculated field', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); expect([].slice.call(element.querySelectorAll('.e-toolbar-item')).length).toEqual(5); let headerElement: HTMLElement[] = [].slice.call(element.querySelectorAll('.e-toolbar-item')); expect(headerElement[1].classList.contains('e-active')).toBeTruthy; headerElement[4].click(); setTimeout(() => { expect(headerElement[4].textContent).toBe('Create Calculated Field'); expect(headerElement[4].classList.contains('e-active')).toBeTruthy; let addButton: HTMLElement = element.querySelector('.e-field-list-footer').querySelector('.e-calculated-field-btn'); expect(addButton.classList.contains('e-disable')).not.toBeTruthy; done(); }, 100); }); it('check on change calculated field to axis view', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); expect([].slice.call(element.querySelectorAll('.e-toolbar-item')).length).toEqual(5); let headerElement: HTMLElement[] = [].slice.call(element.querySelectorAll('.e-toolbar-item')); expect(headerElement[4].classList.contains('e-active')).toBeTruthy; headerElement[1].click(); setTimeout(() => { expect(headerElement[1].textContent).toBe('Columns'); expect(headerElement[1].classList.contains('e-active')).toBeTruthy; let addButton: HTMLElement = element.querySelector('.e-field-list-footer').querySelector('.e-field-list-btn'); expect(addButton.classList.contains('e-disable')).not.toBeTruthy; done(); }, 100); }); it('check sorting pivotbutton', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); expect(element.querySelector('.e-content').querySelector('.e-item.e-active')).not.toBeUndefined; let contentElement: HTMLElement = element.querySelector('.e-content').querySelector('.e-item.e-active'); let pivotButtons: HTMLElement[] = [].slice.call(contentElement.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); ((pivotButtons[0]).querySelector('.e-sort') as HTMLElement).click(); setTimeout(() => { expect((pivotButtons[0]).querySelector('.e-descend')).toBeTruthy; done(); }, 1000); }); it('open filter popup', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); let contentElement: HTMLElement = element.querySelector('.e-content').querySelector('.e-item.e-active'); let pivotButtons: HTMLElement[] = [].slice.call(contentElement.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); ((pivotButtons[0]).querySelector('.e-btn-filter') as HTMLElement).click(); setTimeout(() => { expect(fieldListObj.pivotCommon.filterDialog.dialogPopUp.element.classList.contains('e-popup-open')).toBe(true); done(); }, 1000); }); it('close filter popup by cancel', (done: Function) => { (fieldListObj.pivotCommon.filterDialog.dialogPopUp.element.querySelector('.e-cancel-btn') as HTMLElement).click(); setTimeout(() => { expect(fieldListObj.pivotCommon.filterDialog.dialogPopUp.element).toBeUndefined; done(); }); }); it('check remove pivot button', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); let contentElement: HTMLElement = element.querySelector('.e-content').querySelector('.e-item.e-active'); let pivotButtons: HTMLElement[] = [].slice.call(contentElement.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); expect(pivotButtons[0].id).toBe('name'); (pivotButtons[0].querySelector('.e-remove') as HTMLElement).click(); setTimeout(() => { pivotButtons = [].slice.call(contentElement.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toEqual(0); done(); }, 1000); }); it('Open fields dialog', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); let contentElement: HTMLElement = element.querySelector('.e-content').querySelector('.e-item.e-active'); let pivotButtons: HTMLElement[] = [].slice.call(contentElement.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toEqual(0); let addButton: HTMLElement = element.querySelector('.e-field-list-footer').querySelector('.e-field-list-btn'); expect(addButton.classList.contains('e-disable')).not.toBeTruthy; addButton.click(); setTimeout(() => { expect(element.parentElement .querySelector('.e-adaptive-field-list-dialog').classList.contains('e-popup-open')).toBe(true); done(); }, 1000); }); it('check on field node', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); let treeObj: TreeView = fieldListObj.treeViewModule.fieldTable; let checkEle: Element[] = <Element[] & NodeListOf<Element>>treeObj.element.querySelectorAll('.e-checkbox-wrapper'); expect(checkEle.length).toBeGreaterThan(0); util.checkTreeNode(treeObj, closest(checkEle[0], 'li')); setTimeout(() => { expect(checkEle[0].querySelector('.e-check')).toBeTruthy; done(); }, 1000); }); it('un-check on field node', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); let treeObj: TreeView = fieldListObj.treeViewModule.fieldTable; let checkEle: Element[] = <Element[] & NodeListOf<Element>>treeObj.element.querySelectorAll('.e-checkbox-wrapper'); expect(checkEle.length).toBeGreaterThan(0); util.checkTreeNode(treeObj, closest(checkEle[0], 'li')); setTimeout(() => { expect(checkEle[0].querySelector('.e-check')).toBeUndefined; done(); }, 1000); }); it('check add fields to current axis', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); let treeObj: TreeView = fieldListObj.treeViewModule.fieldTable; let checkEle: Element[] = <Element[] & NodeListOf<Element>>treeObj.element.querySelectorAll('.e-checkbox-wrapper'); expect(checkEle.length).toBeGreaterThan(0); util.checkTreeNode(treeObj, closest(checkEle[0], 'li')); expect(checkEle[0].querySelector('.e-check')).toBeTruthy; (element.parentElement .querySelector('.e-adaptive-field-list-dialog').querySelector('.e-ok-btn') as HTMLElement).click(); setTimeout(() => { expect(element.parentElement .querySelector('.e-adaptive-field-list-dialog')).toBeUndefined; let contentElement: HTMLElement = element.querySelector('.e-content').querySelector('.e-item.e-active'); let pivotButtons: HTMLElement[] = [].slice.call(contentElement.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toEqual(1); expect(pivotButtons[0].id).toBe('_id'); let addButton: HTMLElement = element.querySelector('.e-field-list-footer').querySelector('.e-field-list-btn'); addButton.click(); done(); }, 1000); }); it('check add fields on search option', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); expect(element.parentElement.querySelector('.e-adaptive-field-list-dialog')).toBeTruthy; expect(element.parentElement .querySelector('.e-adaptive-field-list-dialog').classList.contains('e-popup-open')).toBe(true); let searchOption: MaskedTextBox = (fieldListObj.treeViewModule as any).editorSearch; expect(searchOption).not.toBeUndefined; searchOption.setProperties({ value: 'gender' }); searchOption.change({ value: searchOption.value }); let treeObj: TreeView = fieldListObj.treeViewModule.fieldTable; let checkEle: Element[] = <Element[] & NodeListOf<Element>>treeObj.element.querySelectorAll('.e-checkbox-wrapper'); expect(checkEle.length).toBeGreaterThan(0); expect(treeObj.element.querySelector('.e-checkbox-wrapper').classList.contains('e-small')).toBe(false); setTimeout(() => { expect(checkEle[0].querySelector('.e-check')).toBeTruthy; (element.parentElement .querySelector('.e-adaptive-field-list-dialog').querySelector('.e-ok-btn') as HTMLElement).click(); done(); }, 1000); }); it('set rtl property', (done: Function) => { fieldListObj.enableRtl = true; setTimeout(() => { expect(fieldListObj.element.classList.contains('e-rtl')).toBeTruthy; done(); }, 1000); }); it('remove rtl property', (done: Function) => { fieldListObj.enableRtl = false; setTimeout(() => { expect(fieldListObj.element.classList.contains('e-rtl')).not.toBeTruthy; done(); }, 1000); }); it('check on axis view change to calculated field', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); expect([].slice.call(element.querySelectorAll('.e-toolbar-item')).length).toEqual(5); let headerElement: HTMLElement[] = [].slice.call(element.querySelectorAll('.e-toolbar-item')); headerElement[4].click(); setTimeout(() => { expect(headerElement[4].textContent).toBe('Create Calculated Field'); expect(headerElement[4].classList.contains('e-active')).toBeTruthy; let addButton: HTMLElement = element.querySelector('.e-field-list-footer').querySelector('.e-calculated-field-btn'); expect(addButton.classList.contains('e-disable')).not.toBeTruthy; done(); }, 100); }); // it('check field list icon', (done: Function) => { // (fieldListObj.element.querySelector('.e-toggle-field-list') as HTMLElement).click(); // jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; // setTimeout(() => { // expect(fieldListObj.dialogRenderer.fieldListDialog.element.classList.contains('e-popup-open')).toBe(true); // let dialogElement: HTMLElement = fieldListObj.dialogRenderer.fieldListDialog.element; // let element: HTMLElement = dialogElement.querySelector('.e-adaptive-container'); // expect([].slice.call(element.querySelectorAll('.e-toolbar-item')).length).toEqual(5); // let headerElement: HTMLElement[] = [].slice.call(element.querySelectorAll('.e-toolbar-item')); // expect(headerElement[4].classList.contains('e-active')).toBeTruthy; // headerElement[4].click(); // done(); // }, 1000); // }); it('check on calculated field apply button', (done: Function) => { (document.querySelector('.e-pivot-ok-button') as any).click(); setTimeout(() => { expect(document.querySelectorAll('.e-dialog').length === 0).toBeTruthy; // (document.querySelector('.e-control.e-btn.e-ok-btn') as any).click(); // document.querySelector('.e-pivot-error-dialog').remove(); done(); }, 1000); }); it('check on calculated field add button', (done: Function) => { (document.querySelector('.e-calculated-field-btn') as any).click(); setTimeout(() => { expect(document.querySelectorAll('.e-pivot-accord').length > 0).toBeTruthy; (document.querySelector('.e-pivot-cancel-button') as any).click(); done(); }, 1000); }); it('check on calculated field apply button', (done: Function) => { (document.querySelector('.e-pivot-calc-input') as any).value = 'ss'; (document.querySelector('.e-pivot-formula') as any).value = '11'; let calc: any = fieldListObj.calculatedFieldModule; calc.inputObj.value = 'ss'; let formatString: MaskedTextBox = getInstance(document.querySelector('#' + fieldListObj.element.id + 'Custom_Format_Element') as HTMLElement, MaskedTextBox) as MaskedTextBox; expect(formatString).toBeTruthy; formatString.setProperties({ value: 'C0' }); formatString.refresh(); (document.querySelector('.e-pivot-ok-button') as any).click(); setTimeout(() => { expect((document.querySelector('.e-pivot-calc-input') as any).value === '').toBeTruthy; (document.querySelector('.e-calculated-field-btn') as any).click(); done(); }, 1000); }); it('check on calculated field add field', (done: Function) => { (document.querySelector('.e-icons.e-frame') as any).click(); (document.querySelectorAll('.e-tgl-collapse-icon') as any)[11].click(); (document.querySelectorAll('.e-pivot-calc-radio')[1] as any).click(); (document.querySelectorAll('.e-icons.e-frame')[12] as any).click(); (document.querySelector('.e-pivot-add-button') as any).click(); setTimeout(() => { expect((document.querySelector('.e-pivot-formula') as any). value === '"DistinctCount(pno)""Sum(advance)"').toBeTruthy(); (document.querySelector('.e-pivot-calc-input') as any).value = 'New'; let calc: any = fieldListObj.calculatedFieldModule; calc.inputObj.value = 'New'; (document.querySelector('.e-pivot-ok-button') as any).click(); done(); }, 1000); }); it('check on calculated field change existing formula', (done: Function) => { (document.querySelector('.e-pivot-calc-input') as any).value = 'New'; (document.querySelector('.e-pivot-formula') as any).value = '100/100'; let calc: any = fieldListObj.calculatedFieldModule; calc.inputObj.value = 'New'; let formatString: MaskedTextBox = getInstance(document.querySelector('#' + fieldListObj.element.id + 'Custom_Format_Element') as HTMLElement, MaskedTextBox) as MaskedTextBox; expect(formatString).toBeTruthy; formatString.value = 'P1'; formatString.change({ value: formatString.value }); (document.querySelector('.e-pivot-ok-button') as any).click(); setTimeout(() => { expect((document.querySelector('.e-pivot-calc-input') as any).value === '').toBeTruthy; (document.querySelector('.e-control.e-btn.e-ok-btn') as any).click(); done(); }, 1000); }); it('check on calculated field change existing formula', (done: Function) => { (document.querySelector('.e-pivot-calc-input') as any).value = 'balance'; (document.querySelector('.e-pivot-formula') as any).value = '100'; let calc: any = fieldListObj.calculatedFieldModule; calc.inputObj.value = 'balance'; (document.querySelector('.e-pivot-ok-button') as any).click(); setTimeout(() => { expect((document.querySelector('.e-pivot-calc-input') as any).value === '').toBeTruthy; expect(document.querySelectorAll('.e-pivot-error-dialog').length > 0).toBeTruthy; (document.querySelector('.e-control.e-btn.e-ok-btn') as any).click(); // document.querySelector('.e-pivot-error-dialog').remove(); done(); }, 1000); }); it('check on calculated field change existing formula', (done: Function) => { (document.querySelector('.e-pivot-calc-input') as any).value = 'Sales'; (document.querySelector('.e-pivot-formula') as any).value = '100/+/'; let calc: any = fieldListObj.calculatedFieldModule; calc.inputObj.value = 'Sales'; (document.querySelector('.e-pivot-ok-button') as any).click(); setTimeout(() => { expect(document.querySelectorAll('.e-pivot-error-dialog').length > 0).toBeTruthy; (document.querySelector('.e-control.e-btn.e-ok-btn') as any).click(); //document.querySelector('.e-pivot-error-dialog').remove(); done(); }, 1000); }); it('check on calculated field edit icon', (done: Function) => { (document.querySelector('.e-calculated-field-btn') as any).click(); setTimeout(() => { expect(document.querySelectorAll('.e-pivot-accord').length > 0).toBeTruthy; let accordions: HTMLElement[] = [].slice.call(document.querySelectorAll('.e-pivot-accord .e-acrdn-item')); expect(accordions.length).toBe(20); let calcElement: HTMLElement = accordions[accordions.length - 1] as HTMLElement; expect(calcElement).toBeTruthy; expect(calcElement.textContent).toBe('New (Calculated Field)'); (calcElement.querySelector('div.e-acrdn-header-icon > span') as HTMLElement).click(); done(); }, 1000); }); it('check on edited calculated field info', (done: Function) => { expect((document.querySelector('.e-pivot-calc-input') as any).value).toBe('New'); expect((document.querySelector('.e-pivot-formula') as any).value).toBe('100/100'); expect((document.querySelector('.e-custom-format-input') as any).value).toBe('P1'); (document.querySelector('.e-pivot-formula') as any).value = '(100/10)+5'; let calc: any = fieldListObj.calculatedFieldModule; calc.inputObj.value = 'New -1'; calc.inputObj.change({ value: calc.inputObj.value }); let formatString: MaskedTextBox = getInstance(document.querySelector('#' + fieldListObj.element.id + 'Custom_Format_Element') as HTMLElement, MaskedTextBox) as MaskedTextBox; expect(formatString).toBeTruthy; formatString.value = 'C1'; formatString.change({ value: formatString.value }); setTimeout(() => { expect((document.querySelector('.e-pivot-calc-input') as any).value).toBe('New -1'); expect((document.querySelector('.e-pivot-formula') as any).value).toBe('(100/10)+5'); expect((document.querySelector('.e-custom-format-input') as any).value).toBe('C1'); done(); }, 1000); }); it('check on change calculated field to axis view', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); expect([].slice.call(element.querySelectorAll('.e-toolbar-item')).length).toEqual(5); let headerElement: HTMLElement[] = [].slice.call(element.querySelectorAll('.e-toolbar-item')); expect(headerElement[4].classList.contains('e-active')).toBeTruthy; headerElement[3].click(); setTimeout(() => { expect(headerElement[3].textContent).toBe('Values'); expect(headerElement[3].classList.contains('e-active')).toBeTruthy; let addButton: HTMLElement = element.querySelector('.e-field-list-footer').querySelector('.e-field-list-btn'); expect(addButton.classList.contains('e-disable')).not.toBeTruthy; done(); }, 100); }); it('check on axis view change to calculated field', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); expect([].slice.call(element.querySelectorAll('.e-toolbar-item')).length).toEqual(5); let headerElement: HTMLElement[] = [].slice.call(element.querySelectorAll('.e-toolbar-item')); expect(headerElement[3].classList.contains('e-active')).toBeTruthy; headerElement[4].click(); setTimeout(() => { expect(headerElement[4].textContent).toBe('Create Calculated Field'); expect(headerElement[4].classList.contains('e-active')).toBeTruthy; let addButton: HTMLElement = element.querySelector('.e-field-list-footer').querySelector('.e-calculated-field-btn'); expect(addButton.classList.contains('e-disable')).not.toBeTruthy; done(); }, 100); }); it('check on edited calculated field info matained after axis changes', (done: Function) => { expect((document.querySelector('.e-pivot-calc-input') as any).value).toBe('New -1'); expect((document.querySelector('.e-pivot-formula') as any).value).toBe('(100/10)+5'); expect((document.querySelector('.e-custom-format-input') as any).value).toBe('C1'); setTimeout(() => { (document.querySelector('.e-pivot-ok-button') as any).click(); done(); }, 1000); }); it('check on calculated field info reset after changes applied', () => { expect((document.querySelector('.e-pivot-calc-input') as any).value).toBe(''); expect((document.querySelector('.e-pivot-formula') as any).value).toBe(''); expect((document.querySelector('.e-custom-format-input') as any).value).toBe(''); }); it('check on calculated field button edit option', (done: Function) => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); expect([].slice.call(element.querySelectorAll('.e-toolbar-item')).length).toEqual(5); let headerElement: HTMLElement[] = [].slice.call(element.querySelectorAll('.e-toolbar-item')); expect(headerElement[4].classList.contains('e-active')).toBeTruthy; headerElement[3].click(); setTimeout(() => { expect(headerElement[3].textContent).toBe('Values'); expect(headerElement[3].classList.contains('e-active')).toBeTruthy; let addButton: HTMLElement = element.querySelector('.e-field-list-footer').querySelector('.e-field-list-btn'); expect(addButton.classList.contains('e-disable')).not.toBeTruthy; let contentElement: HTMLElement = element.querySelector('.e-field-list-values'); let pivotButtons: HTMLElement[] = [].slice.call(contentElement.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); expect(pivotButtons[pivotButtons.length - 1].id).toBe('New'); expect(pivotButtons[pivotButtons.length - 1].textContent).toBe('New -1'); expect(pivotButtons[pivotButtons.length - 1].querySelector('.e-edit')).toBeTruthy; (pivotButtons[pivotButtons.length - 1].querySelector('.e-edit') as HTMLElement).click(); done(); }, 100); }); it('check -> edited calculated field info', () => { let element: HTMLElement = fieldListObj.element.querySelector('.e-adaptive-container'); let headerElement: HTMLElement[] = [].slice.call(element.querySelectorAll('.e-toolbar-item')); expect(headerElement[4].textContent).toBe('Create Calculated Field'); expect(headerElement[4].classList.contains('e-active')).toBeTruthy; expect((document.querySelector('.e-pivot-calc-input') as any).value).toBe('New -1'); expect((document.querySelector('.e-pivot-formula') as any).value).toBe('(100/10)+5'); expect((document.querySelector('.e-custom-format-input') as any).value).toBe('C1'); }); }); describe('Dynamic rendering', () => { let fieldListObj: PivotFieldList; let elem: HTMLElement = createElement('div', { id: 'PivotFieldList', styles: 'height:400px;width:100%' }); afterAll(() => { if (fieldListObj) { fieldListObj.destroy(); } remove(elem); }); beforeAll((done: Function) => { if (document.getElementById(elem.id)) { remove(document.getElementById(elem.id)); } document.body.appendChild(elem); let dataBound: EmitType<Object> = () => { done(); }; fieldListObj = new PivotFieldList({ dataSourceSettings: { dataSource: pivot_dataset as IDataSet[], expandAll: false, enableSorting: true, sortSettings: [{ name: 'company', order: 'Descending' }], filterSettings: [{ name: 'name', type: 'Include', items: ['Knight Wooten'] }, { name: 'company', type: 'Exclude', items: ['NIPAZ'] }, { name: 'gender', type: 'Include', items: ['male'] }], rows: [{ name: 'company' }, { name: 'state' }], columns: [{ name: 'name' }], values: [{ name: 'balance' }, { name: 'quantity' }], filters: [{ name: 'gender' }] }, allowCalculatedField: true, dataBound: dataBound, fieldDragStart: (args: FieldDragStartEventArgs) => { expect(args.fieldItem).toBeTruthy; expect(args.cancel).toBe(false); console.log('fieldDragName: ' + args.fieldItem.name); }, fieldDrop: (args: FieldDropEventArgs) => { expect(args.dropField).toBeTruthy; expect(args.cancel).toBe(false); console.log('fieldDropName: ' + args.dropField.name); }, onFieldDropped: (args: FieldDroppedEventArgs) => { expect(args.droppedField).toBeTruthy; console.log('fieldDroppedName: ' + args.droppedField.name); }, fieldRemove: (args: FieldRemoveEventArgs) => { expect(args.fieldItem).toBeTruthy; expect(args.cancel).toBe(false); console.log('fieldRemoveName: ' + args.fieldItem.name); }, calculatedFieldCreate: (args: CalculatedFieldCreateEventArgs) => { expect(args.calculatedField).toBeTruthy; expect(args.cancel).toBe(false); console.log('CreateCalcaltedFieldName: ' + args.calculatedField.name); }, load: (args: LoadEventArgs) => { fieldListObj.isAdaptive = true; } }); fieldListObj.appendTo('#PivotFieldList'); util.disableDialogAnimation(fieldListObj.dialogRenderer.fieldListDialog); fieldListObj.calculatedFieldModule = new CalculatedField(fieldListObj); }); let persistdata: string; it('control class testing for mobile device', () => { expect(document.getElementById('PivotFieldList').classList.contains('e-pivotfieldlist')).toEqual(true); expect(document.getElementById('PivotFieldList').classList.contains('e-device')).toEqual(true); }); it('get component name testing', () => { expect(fieldListObj.getModuleName()).toEqual('pivotfieldlist'); }); it('check field list icon', (done: Function) => { (fieldListObj.element.querySelector('.e-toggle-field-list') as HTMLElement).click(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(fieldListObj.dialogRenderer.fieldListDialog.element.classList.contains('e-popup-open')).toBe(true); done(); }, 1000); }); it('check on axis view change', (done: Function) => { let dialogElement: HTMLElement = fieldListObj.dialogRenderer.fieldListDialog.element; let element: HTMLElement = dialogElement.querySelector('.e-adaptive-container'); expect([].slice.call(element.querySelectorAll('.e-toolbar-item')).length).toEqual(5); let headerElement: HTMLElement[] = [].slice.call(element.querySelectorAll('.e-toolbar-item')); expect(headerElement[0].classList.contains('e-active')).toBeTruthy; headerElement[1].click(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(headerElement[1].textContent).toBe('Columns'); expect(headerElement[1].classList.contains('e-active')).toBeTruthy; let addButton: HTMLElement = dialogElement.querySelector('.e-field-list-footer').querySelector('.e-field-list-btn'); expect(addButton.classList.contains('e-disable')).not.toBeTruthy; done(); }, 1000); }); it('check on axis view change to calculated field', (done: Function) => { let dialogElement: HTMLElement = fieldListObj.dialogRenderer.fieldListDialog.element; let element: HTMLElement = dialogElement.querySelector('.e-adaptive-container'); expect([].slice.call(element.querySelectorAll('.e-toolbar-item')).length).toEqual(5); let headerElement: HTMLElement[] = [].slice.call(element.querySelectorAll('.e-toolbar-item')); expect(headerElement[1].classList.contains('e-active')).toBeTruthy; headerElement[4].click(); setTimeout(() => { expect(headerElement[4].textContent).toBe('Create Calculated Field'); expect(headerElement[4].classList.contains('e-active')).toBeTruthy; let addButton: HTMLElement = dialogElement. querySelector('.e-field-list-footer').querySelector('.e-calculated-field-btn'); expect(addButton.classList.contains('e-disable')).not.toBeTruthy; done(); }, 100); }); it('check on change calculated field to axis view', (done: Function) => { let dialogElement: HTMLElement = fieldListObj.dialogRenderer.fieldListDialog.element; let element: HTMLElement = dialogElement.querySelector('.e-adaptive-container'); expect([].slice.call(element.querySelectorAll('.e-toolbar-item')).length).toEqual(5); let headerElement: HTMLElement[] = [].slice.call(element.querySelectorAll('.e-toolbar-item')); expect(headerElement[4].classList.contains('e-active')).toBeTruthy; headerElement[1].click(); setTimeout(() => { expect(headerElement[1].textContent).toBe('Columns'); expect(headerElement[1].classList.contains('e-active')).toBeTruthy; let addButton: HTMLElement = dialogElement.querySelector('.e-field-list-footer').querySelector('.e-field-list-btn'); expect(addButton.classList.contains('e-disable')).not.toBeTruthy; done(); }, 100); }); it('check sorting pivotbutton', (done: Function) => { let dialogElement: HTMLElement = fieldListObj.dialogRenderer.fieldListDialog.element; let element: HTMLElement = dialogElement.querySelector('.e-adaptive-container'); expect(element.querySelector('.e-content').querySelector('.e-item.e-active')).not.toBeUndefined; let contentElement: HTMLElement = element.querySelector('.e-content').querySelector('.e-item.e-active'); let pivotButtons: HTMLElement[] = [].slice.call(contentElement.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); ((pivotButtons[0]).querySelector('.e-sort') as HTMLElement).click(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((pivotButtons[0]).querySelector('.e-descend')).toBeTruthy; done(); }, 1000); }); it('open filter popup', (done: Function) => { let dialogElement: HTMLElement = fieldListObj.dialogRenderer.fieldListDialog.element; let element: HTMLElement = dialogElement.querySelector('.e-adaptive-container'); let contentElement: HTMLElement = element.querySelector('.e-content').querySelector('.e-item.e-active'); let pivotButtons: HTMLElement[] = [].slice.call(contentElement.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); ((pivotButtons[0]).querySelector('.e-btn-filter') as HTMLElement).click(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(fieldListObj.pivotCommon.filterDialog.dialogPopUp.element.classList.contains('e-popup-open')).toBe(true); done(); }, 1000); }); it('close filter popup by cancel', (done: Function) => { (fieldListObj.pivotCommon.filterDialog.dialogPopUp.element.querySelector('.e-cancel-btn') as HTMLElement).click(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(fieldListObj.pivotCommon.filterDialog.dialogPopUp.element).toBeUndefined; done(); }, 1000); }); it('check remove pivot button', (done: Function) => { let dialogElement: HTMLElement = fieldListObj.dialogRenderer.fieldListDialog.element; let element: HTMLElement = dialogElement.querySelector('.e-adaptive-container'); let contentElement: HTMLElement = element.querySelector('.e-content').querySelector('.e-item.e-active'); let pivotButtons: HTMLElement[] = [].slice.call(contentElement.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toBeGreaterThan(0); expect(pivotButtons[0].id).toBe('name'); (pivotButtons[0].querySelector('.e-remove') as HTMLElement).click(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { pivotButtons = [].slice.call(contentElement.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toEqual(0); done(); }, 1000); }); it('Open fields dialog', (done: Function) => { let dialogElement: HTMLElement = fieldListObj.dialogRenderer.fieldListDialog.element; let element: HTMLElement = dialogElement.querySelector('.e-adaptive-container'); let contentElement: HTMLElement = element.querySelector('.e-content').querySelector('.e-item.e-active'); let pivotButtons: HTMLElement[] = [].slice.call(contentElement.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toEqual(0); let addButton: HTMLElement = dialogElement.querySelector('.e-field-list-footer').querySelector('.e-field-list-btn'); expect(addButton.classList.contains('e-disable')).not.toBeTruthy; addButton.click(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(dialogElement.querySelector('.e-adaptive-field-list-dialog').classList.contains('e-popup-open')).toBe(true); done(); }, 1000); }); it('check on field node', () => { let dialogElement: HTMLElement = fieldListObj.dialogRenderer.fieldListDialog.element; let element: HTMLElement = dialogElement.querySelector('.e-adaptive-container'); let treeObj: TreeView = fieldListObj.treeViewModule.fieldTable; let checkEle: Element[] = <Element[] & NodeListOf<Element>>treeObj.element.querySelectorAll('.e-checkbox-wrapper'); expect(checkEle.length).toBeGreaterThan(0); util.checkTreeNode(treeObj, closest(checkEle[0], 'li')); expect(checkEle[0].querySelector('.e-check')).toBeTruthy; }); it('un-check on field node', () => { let dialogElement: HTMLElement = fieldListObj.dialogRenderer.fieldListDialog.element; let element: HTMLElement = dialogElement.querySelector('.e-adaptive-container'); let treeObj: TreeView = fieldListObj.treeViewModule.fieldTable; let checkEle: Element[] = <Element[] & NodeListOf<Element>>treeObj.element.querySelectorAll('.e-checkbox-wrapper'); expect(checkEle.length).toBeGreaterThan(0); util.checkTreeNode(treeObj, closest(checkEle[0], 'li')); expect(checkEle[0].querySelector('.e-check')).toBeUndefined; }); it('check add fields to current axis', (done: Function) => { let dialogElement: HTMLElement = fieldListObj.dialogRenderer.fieldListDialog.element; let element: HTMLElement = dialogElement.querySelector('.e-adaptive-container'); let treeObj: TreeView = fieldListObj.treeViewModule.fieldTable; let checkEle: Element[] = <Element[] & NodeListOf<Element>>treeObj.element.querySelectorAll('.e-checkbox-wrapper'); expect(checkEle.length).toBeGreaterThan(0); expect(treeObj.element.querySelector('.e-checkbox-wrapper').classList.contains('e-small')).toBe(false); util.checkTreeNode(treeObj, closest(checkEle[0], 'li')); expect(checkEle[0].querySelector('.e-check')).toBeTruthy; (dialogElement.querySelector('.e-adaptive-field-list-dialog').querySelector('.e-ok-btn') as HTMLElement).click(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(dialogElement.querySelector('.e-adaptive-field-list-dialog')).toBeUndefined; let contentElement: HTMLElement = element.querySelector('.e-content').querySelector('.e-item.e-active'); let pivotButtons: HTMLElement[] = [].slice.call(contentElement.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toEqual(1); expect(pivotButtons[0].id).toBe('_id'); let addButton: HTMLElement = dialogElement.querySelector('.e-field-list-footer').querySelector('.e-field-list-btn'); addButton.click(); done(); }, 1000); }); it('set rtl property', (done: Function) => { fieldListObj.enableRtl = true; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.getElementById('PivotFieldList').classList.contains('e-rtl')).toBeTruthy; done(); }, 1000); }); it('remove rtl property', (done: Function) => { fieldListObj.enableRtl = false; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.getElementById('PivotFieldList').classList.contains('e-rtl')).not.toBeTruthy; done(); }, 1000); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange); //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()); //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); });
the_stack
import { sha256 } from "js-sha256"; import { serialize, deserialize } from "serializer.ts/Serializer"; import BigNumber from "bignumber.js"; import * as fs from "fs"; import * as path from "path"; import deepEqual = require("deep-equal"); import * as uuidv4 from "uuid/v4"; import * as express from "express"; import * as bodyParser from "body-parser"; import { URL } from "url"; import axios from "axios"; import { Set } from "typescript-collections"; import * as parseArgs from "minimist"; export type Address = string; export class Transaction { public senderAddress: Address; public recipientAddress: Address; public value: number; constructor(senderAddress: Address, recipientAddress: Address, value: number) { this.senderAddress = senderAddress; this.recipientAddress = recipientAddress; this.value = value; } } export class Block { public blockNumber: number; public transactions: Array<Transaction>; public timestamp: number; public nonce: number; public prevBlock: string; constructor(blockNumber: number, transactions: Array<Transaction>, timestamp: number, nonce: number, prevBlock: string) { this.blockNumber = blockNumber; this.transactions = transactions; this.timestamp = timestamp; this.nonce = nonce; this.prevBlock = prevBlock; } // Calculates the SHA256 of the entire block, including its transactions. public sha256(): string { return sha256(JSON.stringify(serialize<Block>(this))); } } export class Node { public id: string; public url: URL; constructor(id: string, url: URL) { this.id = id; this.url = url; } public toString(): string { return `${this.id}:${this.url}`; } } export class Blockchain { // Let's define that our "genesis" block as an empty block, starting from the January 1, 1970 (midnight "UTC"). public static readonly GENESIS_BLOCK = new Block(0, [], 0, 0, "fiat lux"); public static readonly DIFFICULTY = 4; public static readonly TARGET = 2 ** (256 - Blockchain.DIFFICULTY); public static readonly MINING_SENDER = "<COINBASE>"; public static readonly MINING_REWARD = 50; public nodeId: string; public nodes: Set<Node>; public blocks: Array<Block>; public transactionPool: Array<Transaction>; private storagePath: string; constructor(nodeId: string) { this.nodeId = nodeId; this.nodes = new Set<Node>(); this.transactionPool = []; this.storagePath = path.resolve(__dirname, "../", `${this.nodeId}.blockchain`); // Load the blockchain from the storage. this.load(); } // Registers new node. public register(node: Node): boolean { return this.nodes.add(node); } // Saves the blockchain to the disk. private save() { fs.writeFileSync(this.storagePath, JSON.stringify(serialize(this.blocks), undefined, 2), "utf8"); } // Loads the blockchain from the disk. private load() { try { this.blocks = deserialize<Block[]>(Block, JSON.parse(fs.readFileSync(this.storagePath, "utf8"))); } catch (err) { if (err.code !== "ENOENT") { throw err; } this.blocks = [Blockchain.GENESIS_BLOCK]; } finally { this.verify(); } } // Verifies the blockchain. public static verify(blocks: Array<Block>): boolean { try { // The blockchain can't be empty. It should always contain at least the genesis block. if (blocks.length === 0) { throw new Error("Blockchain can't be empty!"); } // The first block has to be the genesis block. if (!deepEqual(blocks[0], Blockchain.GENESIS_BLOCK)) { throw new Error("Invalid first block!"); } // Verify the chain itself. for (let i = 1; i < blocks.length; ++i) { const current = blocks[i]; // Verify block number. if (current.blockNumber !== i) { throw new Error(`Invalid block number ${current.blockNumber} for block #${i}!`); } // Verify that the current blocks properly points to the previous block. const previous = blocks[i - 1]; if (current.prevBlock !== previous.sha256()) { throw new Error(`Invalid previous block hash for block #${i}!`); } // Verify the difficutly of the PoW. // // TODO: what if the diffuclty was adjusted? if (!this.isPoWValid(current.sha256())) { throw new Error(`Invalid previous block hash's difficutly for block #${i}!`); } } return true; } catch (err) { console.error(err); return false; } } // Verifies the blockchain. private verify() { // The blockchain can't be empty. It should always contain at least the genesis block. if (!Blockchain.verify(this.blocks)) { throw new Error("Invalid blockchain!"); } } // Receives candidate blockchains, verifies them, and if a longer and valid alternative is found - uses it to replace // our own. public consensus(blockchains: Array<Array<Block>>): boolean { // Iterate over the proposed candidates and find the longest, valid, candidate. let maxLength: number = 0; let bestCandidateIndex: number = -1; for (let i = 0; i < blockchains.length; ++i) { const candidate = blockchains[i]; // Don't bother validating blockchains shorther than the best candidate so far. if (candidate.length <= maxLength) { continue; } // Found a good candidate? if (Blockchain.verify(candidate)) { maxLength = candidate.length; bestCandidateIndex = i; } } // Compare the candidate and consider to use it. if (bestCandidateIndex !== -1 && (maxLength > this.blocks.length || !Blockchain.verify(this.blocks))) { this.blocks = blockchains[bestCandidateIndex]; this.save(); return true; } return false; } // Validates PoW. public static isPoWValid(pow: string): boolean { try { if (!pow.startsWith("0x")) { pow = `0x${pow}`; } return new BigNumber(pow).lessThanOrEqualTo(Blockchain.TARGET.toString()); } catch { return false; } } // Mines for block. private mineBlock(transactions: Array<Transaction>): Block { // Create a new block which will "point" to the last block. const lastBlock = this.getLastBlock(); const newBlock = new Block(lastBlock.blockNumber + 1, transactions, Blockchain.now(), 0, lastBlock.sha256()); while (true) { const pow = newBlock.sha256(); console.log(`Mining #${newBlock.blockNumber}: nonce: ${newBlock.nonce}, pow: ${pow}`); if (Blockchain.isPoWValid(pow)) { console.log(`Found valid POW: ${pow}!`); break; } newBlock.nonce++; } return newBlock; } // Submits new transaction public submitTransaction(senderAddress: Address, recipientAddress: Address, value: number) { this.transactionPool.push(new Transaction(senderAddress, recipientAddress, value)); } // Creates new block on the blockchain. public createBlock(): Block { // Add a "coinbase" transaction granting us the mining reward! const transactions = [new Transaction(Blockchain.MINING_SENDER, this.nodeId, Blockchain.MINING_REWARD), ...this.transactionPool]; // Mine the transactions in a new block. const newBlock = this.mineBlock(transactions); // Append the new block to the blockchain. this.blocks.push(newBlock); // Remove the mined transactions. this.transactionPool = []; // Save the blockchain to the storage. this.save(); return newBlock; } public getLastBlock(): Block { return this.blocks[this.blocks.length - 1]; } public static now(): number { return Math.round(new Date().getTime() / 1000); } } // Web server: const ARGS = parseArgs(process.argv.slice(2)); const PORT = ARGS.port || 3000; const app = express(); const nodeId = ARGS.id || uuidv4(); const blockchain = new Blockchain(nodeId); // Set up bodyParser: app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => { console.error(err.stack); res.status(500); }); // Show all the blocks. app.get("/blocks", (req: express.Request, res: express.Response) => { res.json(serialize(blockchain.blocks)); }); // Show specific block. app.get("/blocks/:id", (req: express.Request, res: express.Response) => { const id = Number(req.params.id); if (isNaN(id)) { res.json("Invalid parameter!"); res.status(500); return; } if (id >= blockchain.blocks.length) { res.json(`Block #${id} wasn't found!`); res.status(404); return; } res.json(serialize(blockchain.blocks[id])); }); app.post("/blocks/mine", (req: express.Request, res: express.Response) => { // Mine the new block. const newBlock = blockchain.createBlock(); res.json(`Mined new block #${newBlock.blockNumber}`); }); // Show all transactions in the transaction pool. app.get("/transactions", (req: express.Request, res: express.Response) => { res.json(serialize(blockchain.transactionPool)); }); app.post("/transactions", (req: express.Request, res: express.Response) => { const senderAddress = req.body.senderAddress; const recipientAddress = req.body.recipientAddress; const value = Number(req.body.value); if (!senderAddress || !recipientAddress || !value) { res.json("Invalid parameters!"); res.status(500); return; } blockchain.submitTransaction(senderAddress, recipientAddress, value); res.json(`Transaction from ${senderAddress} to ${recipientAddress} was added successfully`); }); app.get("/nodes", (req: express.Request, res: express.Response) => { res.json(serialize(blockchain.nodes.toArray())); }); app.post("/nodes", (req: express.Request, res: express.Response) => { const id = req.body.id; const url = new URL(req.body.url); if (!id || !url) { res.json("Invalid parameters!"); res.status(500); return; } const node = new Node(id, url); if (blockchain.register(node)) { res.json(`Registered node: ${node}`); } else { res.json(`Node ${node} already exists!`); res.status(500); } }); app.put("/nodes/consensus", (req: express.Request, res: express.Response) => { // Fetch the state of the other nodes. const requests = blockchain.nodes.toArray().map(node => axios.get(`${node.url}blocks`)); if (requests.length === 0) { res.json("There are nodes to sync with!"); res.status(404); return; } axios.all(requests).then(axios.spread((...blockchains) => { if (blockchain.consensus(blockchains.map(res => deserialize<Block[]>(Block, res.data)))) { res.json(`Node ${nodeId} has reached a consensus on a new state.`); } else { res.json(`Node ${nodeId} hasn't reached a consensus on the existing state.`); } res.status(200); return; })).catch(err => { console.log(err); res.status(500); res.json(err); return; }); res.status(500); }); if (!module.parent) { app.listen(PORT); console.log(`Web server started on port ${PORT}. Node ID is: ${nodeId}`); }
the_stack
import {ATN} from "antlr4ts/atn/ATN"; import {ATNDeserializer} from "antlr4ts/atn/ATNDeserializer"; import {FailedPredicateException} from "antlr4ts/FailedPredicateException"; import {NotNull, Override} from "antlr4ts/Decorators"; import {NoViableAltException} from "antlr4ts/NoViableAltException"; import {Parser} from "antlr4ts/Parser"; import {ParserRuleContext} from "antlr4ts/ParserRuleContext"; import {ParserATNSimulator} from "antlr4ts/atn/ParserATNSimulator"; import {ParseTreeListener} from "antlr4ts/tree/ParseTreeListener"; import {ParseTreeVisitor} from "antlr4ts/tree/ParseTreeVisitor"; import {RecognitionException} from "antlr4ts/RecognitionException"; import {RuleContext} from "antlr4ts/RuleContext"; //import { RuleVersion } from "antlr4ts/RuleVersion"; import {TerminalNode} from "antlr4ts/tree/TerminalNode"; import {Token} from "antlr4ts/Token"; import {TokenStream} from "antlr4ts/TokenStream"; import {Vocabulary} from "antlr4ts/Vocabulary"; import {VocabularyImpl} from "antlr4ts/VocabularyImpl"; import * as Utils from "antlr4ts/misc/Utils"; import {ReactiveListener} from "./ReactiveListener"; import {ReactiveVisitor} from "./ReactiveVisitor"; export class ReactiveParser extends Parser { public static readonly T__0 = 1; public static readonly T__1 = 2; public static readonly T__2 = 3; public static readonly Identifier = 4; public static readonly NonzeroDigit = 5; public static readonly DigitSequence = 6; public static readonly FractionalConstant = 7; public static readonly ExponentPart = 8; public static readonly PLUS = 9; public static readonly MINUS = 10; public static readonly MULTIPLY = 11; public static readonly DIVIDE = 12; public static readonly NOT = 13; public static readonly GT = 14; public static readonly GTE = 15; public static readonly LT = 16; public static readonly LTE = 17; public static readonly EQUALS = 18; public static readonly NOT_EQUALS = 19; public static readonly AND = 20; public static readonly OR = 21; public static readonly DOT = 22; public static readonly OPEN_BRACKET = 23; public static readonly CLOSED_BRACKET = 24; public static readonly Whitespace = 25; public static readonly RULE_expression = 0; public static readonly RULE_reference = 1; public static readonly RULE_atomicExpression = 2; public static readonly RULE_literal = 3; public static readonly RULE_integerLiteral = 4; public static readonly RULE_floatingLiteral = 5; public static readonly RULE_booleanLiteral = 6; // tslint:disable:no-trailing-whitespace public static readonly ruleNames: string[] = [ "expression", "reference", "atomicExpression", "literal", "integerLiteral", "floatingLiteral", "booleanLiteral", ]; private static readonly _LITERAL_NAMES: Array<string | undefined> = [ undefined, "'0'", "'true'", "'false'", undefined, undefined, undefined, undefined, undefined, "'+'", "'-'", "'*'", "'/'", "'!'", "'>'", "'>='", "'<'", "'<='", "'=='", "'!='", "'&&'", "'||'", "'.'", "'('", "')'", ]; private static readonly _SYMBOLIC_NAMES: Array<string | undefined> = [ undefined, undefined, undefined, undefined, "Identifier", "NonzeroDigit", "DigitSequence", "FractionalConstant", "ExponentPart", "PLUS", "MINUS", "MULTIPLY", "DIVIDE", "NOT", "GT", "GTE", "LT", "LTE", "EQUALS", "NOT_EQUALS", "AND", "OR", "DOT", "OPEN_BRACKET", "CLOSED_BRACKET", "Whitespace", ]; public static readonly VOCABULARY: Vocabulary = new VocabularyImpl(ReactiveParser._LITERAL_NAMES, ReactiveParser._SYMBOLIC_NAMES, []); // @Override // @NotNull public get vocabulary(): Vocabulary { return ReactiveParser.VOCABULARY; } // tslint:enable:no-trailing-whitespace // @Override public get grammarFileName(): string { return "Reactive.g4"; } // @Override public get ruleNames(): string[] { return ReactiveParser.ruleNames; } // @Override public get serializedATN(): string { return ReactiveParser._serializedATN; } constructor(input: TokenStream) { super(input); this._interp = new ParserATNSimulator(ReactiveParser._ATN, this); } public expression(): ExpressionContext; public expression(_p: number): ExpressionContext; // @RuleVersion(0) public expression(_p?: number): ExpressionContext { if (_p === undefined) { _p = 0; } let _parentctx: ParserRuleContext = this._ctx; let _parentState: number = this.state; let _localctx: ExpressionContext = new ExpressionContext(this._ctx, _parentState); let _prevctx: ExpressionContext = _localctx; let _startState: number = 0; this.enterRecursionRule(_localctx, 0, ReactiveParser.RULE_expression, _p); try { let _alt: number; this.enterOuterAlt(_localctx, 1); { this.state = 24; this._errHandler.sync(this); switch (this._input.LA(1)) { case ReactiveParser.T__0: case ReactiveParser.T__1: case ReactiveParser.T__2: case ReactiveParser.Identifier: case ReactiveParser.NonzeroDigit: case ReactiveParser.DigitSequence: case ReactiveParser.FractionalConstant: { _localctx = new AtomicContext(_localctx); this._ctx = _localctx; _prevctx = _localctx; this.state = 15; this.atomicExpression(); } break; case ReactiveParser.OPEN_BRACKET: { _localctx = new GroupExpressionContext(_localctx); this._ctx = _localctx; _prevctx = _localctx; this.state = 16; this.match(ReactiveParser.OPEN_BRACKET); this.state = 17; (_localctx as GroupExpressionContext)._exp = this.expression(0); this.state = 18; this.match(ReactiveParser.CLOSED_BRACKET); } break; case ReactiveParser.NOT: { _localctx = new UnaryExpressionNotContext(_localctx); this._ctx = _localctx; _prevctx = _localctx; this.state = 20; this.match(ReactiveParser.NOT); this.state = 21; (_localctx as UnaryExpressionNotContext)._exp = this.expression(14); } break; case ReactiveParser.MINUS: { _localctx = new UnaryExpressionNegateContext(_localctx); this._ctx = _localctx; _prevctx = _localctx; this.state = 22; this.match(ReactiveParser.MINUS); this.state = 23; (_localctx as UnaryExpressionNegateContext)._exp = this.expression(13); } break; default: throw new NoViableAltException(this); } this._ctx._stop = this._input.tryLT(-1); this.state = 64; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 2, this._ctx); while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { if (_alt === 1) { if (this._parseListeners != null) { this.triggerExitRuleEvent(); } _prevctx = _localctx; { this.state = 62; this._errHandler.sync(this); switch (this.interpreter.adaptivePredict(this._input, 1, this._ctx)) { case 1: { _localctx = new BinaryExpressionMultiplyContext(new ExpressionContext(_parentctx, _parentState)); (_localctx as BinaryExpressionMultiplyContext)._left = _prevctx; this.pushNewRecursionContext(_localctx, _startState, ReactiveParser.RULE_expression); this.state = 26; if (!(this.precpred(this._ctx, 12))) { throw new FailedPredicateException(this, "this.precpred(this._ctx, 12)"); } this.state = 27; this.match(ReactiveParser.MULTIPLY); this.state = 28; (_localctx as BinaryExpressionMultiplyContext)._right = this.expression(13); } break; case 2: { _localctx = new BinaryExpressionDivideContext(new ExpressionContext(_parentctx, _parentState)); (_localctx as BinaryExpressionDivideContext)._left = _prevctx; this.pushNewRecursionContext(_localctx, _startState, ReactiveParser.RULE_expression); this.state = 29; if (!(this.precpred(this._ctx, 11))) { throw new FailedPredicateException(this, "this.precpred(this._ctx, 11)"); } this.state = 30; this.match(ReactiveParser.DIVIDE); this.state = 31; (_localctx as BinaryExpressionDivideContext)._right = this.expression(12); } break; case 3: { _localctx = new BinaryExpressionAddContext(new ExpressionContext(_parentctx, _parentState)); (_localctx as BinaryExpressionAddContext)._left = _prevctx; this.pushNewRecursionContext(_localctx, _startState, ReactiveParser.RULE_expression); this.state = 32; if (!(this.precpred(this._ctx, 10))) { throw new FailedPredicateException(this, "this.precpred(this._ctx, 10)"); } this.state = 33; this.match(ReactiveParser.PLUS); this.state = 34; (_localctx as BinaryExpressionAddContext)._right = this.expression(11); } break; case 4: { _localctx = new BinaryExpressionSubtractContext(new ExpressionContext(_parentctx, _parentState)); (_localctx as BinaryExpressionSubtractContext)._left = _prevctx; this.pushNewRecursionContext(_localctx, _startState, ReactiveParser.RULE_expression); this.state = 35; if (!(this.precpred(this._ctx, 9))) { throw new FailedPredicateException(this, "this.precpred(this._ctx, 9)"); } this.state = 36; this.match(ReactiveParser.MINUS); this.state = 37; (_localctx as BinaryExpressionSubtractContext)._right = this.expression(10); } break; case 5: { _localctx = new BinaryExpressionGreaterThanContext(new ExpressionContext(_parentctx, _parentState)); (_localctx as BinaryExpressionGreaterThanContext)._left = _prevctx; this.pushNewRecursionContext(_localctx, _startState, ReactiveParser.RULE_expression); this.state = 38; if (!(this.precpred(this._ctx, 8))) { throw new FailedPredicateException(this, "this.precpred(this._ctx, 8)"); } this.state = 39; this.match(ReactiveParser.GT); this.state = 40; (_localctx as BinaryExpressionGreaterThanContext)._right = this.expression(9); } break; case 6: { _localctx = new BinaryExpressionLessThanContext(new ExpressionContext(_parentctx, _parentState)); (_localctx as BinaryExpressionLessThanContext)._left = _prevctx; this.pushNewRecursionContext(_localctx, _startState, ReactiveParser.RULE_expression); this.state = 41; if (!(this.precpred(this._ctx, 7))) { throw new FailedPredicateException(this, "this.precpred(this._ctx, 7)"); } this.state = 42; this.match(ReactiveParser.LT); this.state = 43; (_localctx as BinaryExpressionLessThanContext)._right = this.expression(8); } break; case 7: { _localctx = new BinaryExpressionGreaterThanOrEqualContext(new ExpressionContext(_parentctx, _parentState)); (_localctx as BinaryExpressionGreaterThanOrEqualContext)._left = _prevctx; this.pushNewRecursionContext(_localctx, _startState, ReactiveParser.RULE_expression); this.state = 44; if (!(this.precpred(this._ctx, 6))) { throw new FailedPredicateException(this, "this.precpred(this._ctx, 6)"); } this.state = 45; this.match(ReactiveParser.GTE); this.state = 46; (_localctx as BinaryExpressionGreaterThanOrEqualContext)._right = this.expression(7); } break; case 8: { _localctx = new BinaryExpressionLessThanOrEqualContext(new ExpressionContext(_parentctx, _parentState)); (_localctx as BinaryExpressionLessThanOrEqualContext)._left = _prevctx; this.pushNewRecursionContext(_localctx, _startState, ReactiveParser.RULE_expression); this.state = 47; if (!(this.precpred(this._ctx, 5))) { throw new FailedPredicateException(this, "this.precpred(this._ctx, 5)"); } this.state = 48; this.match(ReactiveParser.LTE); this.state = 49; (_localctx as BinaryExpressionLessThanOrEqualContext)._right = this.expression(6); } break; case 9: { _localctx = new BinaryExpressionEqualContext(new ExpressionContext(_parentctx, _parentState)); (_localctx as BinaryExpressionEqualContext)._left = _prevctx; this.pushNewRecursionContext(_localctx, _startState, ReactiveParser.RULE_expression); this.state = 50; if (!(this.precpred(this._ctx, 4))) { throw new FailedPredicateException(this, "this.precpred(this._ctx, 4)"); } this.state = 51; this.match(ReactiveParser.EQUALS); this.state = 52; (_localctx as BinaryExpressionEqualContext)._right = this.expression(5); } break; case 10: { _localctx = new BinaryExpressionNotEqualContext(new ExpressionContext(_parentctx, _parentState)); (_localctx as BinaryExpressionNotEqualContext)._left = _prevctx; this.pushNewRecursionContext(_localctx, _startState, ReactiveParser.RULE_expression); this.state = 53; if (!(this.precpred(this._ctx, 3))) { throw new FailedPredicateException(this, "this.precpred(this._ctx, 3)"); } this.state = 54; this.match(ReactiveParser.NOT_EQUALS); this.state = 55; (_localctx as BinaryExpressionNotEqualContext)._right = this.expression(4); } break; case 11: { _localctx = new BinaryExpressionAndContext(new ExpressionContext(_parentctx, _parentState)); (_localctx as BinaryExpressionAndContext)._left = _prevctx; this.pushNewRecursionContext(_localctx, _startState, ReactiveParser.RULE_expression); this.state = 56; if (!(this.precpred(this._ctx, 2))) { throw new FailedPredicateException(this, "this.precpred(this._ctx, 2)"); } this.state = 57; this.match(ReactiveParser.AND); this.state = 58; (_localctx as BinaryExpressionAndContext)._right = this.expression(3); } break; case 12: { _localctx = new BinaryExpressionOrContext(new ExpressionContext(_parentctx, _parentState)); (_localctx as BinaryExpressionOrContext)._left = _prevctx; this.pushNewRecursionContext(_localctx, _startState, ReactiveParser.RULE_expression); this.state = 59; if (!(this.precpred(this._ctx, 1))) { throw new FailedPredicateException(this, "this.precpred(this._ctx, 1)"); } this.state = 60; this.match(ReactiveParser.OR); this.state = 61; (_localctx as BinaryExpressionOrContext)._right = this.expression(2); } break; } } } this.state = 66; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 2, this._ctx); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.unrollRecursionContexts(_parentctx); } return _localctx; } // @RuleVersion(0) public reference(): ReferenceContext { let _localctx: ReferenceContext = new ReferenceContext(this._ctx, this.state); this.enterRule(_localctx, 2, ReactiveParser.RULE_reference); try { let _alt: number; this.enterOuterAlt(_localctx, 1); { this.state = 67; this.match(ReactiveParser.Identifier); this.state = 72; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 3, this._ctx); while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { if (_alt === 1) { { { this.state = 68; this.match(ReactiveParser.DOT); this.state = 69; this.match(ReactiveParser.Identifier); } } } this.state = 74; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 3, this._ctx); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public atomicExpression(): AtomicExpressionContext { let _localctx: AtomicExpressionContext = new AtomicExpressionContext(this._ctx, this.state); this.enterRule(_localctx, 4, ReactiveParser.RULE_atomicExpression); try { this.state = 77; this._errHandler.sync(this); switch (this._input.LA(1)) { case ReactiveParser.T__0: case ReactiveParser.T__1: case ReactiveParser.T__2: case ReactiveParser.NonzeroDigit: case ReactiveParser.DigitSequence: case ReactiveParser.FractionalConstant: this.enterOuterAlt(_localctx, 1); { this.state = 75; this.literal(); } break; case ReactiveParser.Identifier: this.enterOuterAlt(_localctx, 2); { this.state = 76; this.reference(); } break; default: throw new NoViableAltException(this); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public literal(): LiteralContext { let _localctx: LiteralContext = new LiteralContext(this._ctx, this.state); this.enterRule(_localctx, 6, ReactiveParser.RULE_literal); try { this.state = 82; this._errHandler.sync(this); switch (this._input.LA(1)) { case ReactiveParser.T__0: case ReactiveParser.NonzeroDigit: this.enterOuterAlt(_localctx, 1); { this.state = 79; this.integerLiteral(); } break; case ReactiveParser.DigitSequence: case ReactiveParser.FractionalConstant: this.enterOuterAlt(_localctx, 2); { this.state = 80; this.floatingLiteral(); } break; case ReactiveParser.T__1: case ReactiveParser.T__2: this.enterOuterAlt(_localctx, 3); { this.state = 81; this.booleanLiteral(); } break; default: throw new NoViableAltException(this); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public integerLiteral(): IntegerLiteralContext { let _localctx: IntegerLiteralContext = new IntegerLiteralContext(this._ctx, this.state); this.enterRule(_localctx, 8, ReactiveParser.RULE_integerLiteral); try { this.state = 89; this._errHandler.sync(this); switch (this._input.LA(1)) { case ReactiveParser.T__0: this.enterOuterAlt(_localctx, 1); { this.state = 84; this.match(ReactiveParser.T__0); } break; case ReactiveParser.NonzeroDigit: this.enterOuterAlt(_localctx, 2); { { this.state = 85; this.match(ReactiveParser.NonzeroDigit); this.state = 87; this._errHandler.sync(this); switch (this.interpreter.adaptivePredict(this._input, 6, this._ctx)) { case 1: { this.state = 86; this.match(ReactiveParser.DigitSequence); } break; } } } break; default: throw new NoViableAltException(this); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public floatingLiteral(): FloatingLiteralContext { let _localctx: FloatingLiteralContext = new FloatingLiteralContext(this._ctx, this.state); this.enterRule(_localctx, 10, ReactiveParser.RULE_floatingLiteral); try { this.state = 97; this._errHandler.sync(this); switch (this._input.LA(1)) { case ReactiveParser.FractionalConstant: this.enterOuterAlt(_localctx, 1); { this.state = 91; this.match(ReactiveParser.FractionalConstant); this.state = 93; this._errHandler.sync(this); switch (this.interpreter.adaptivePredict(this._input, 8, this._ctx)) { case 1: { this.state = 92; this.match(ReactiveParser.ExponentPart); } break; } } break; case ReactiveParser.DigitSequence: this.enterOuterAlt(_localctx, 2); { this.state = 95; this.match(ReactiveParser.DigitSequence); this.state = 96; this.match(ReactiveParser.ExponentPart); } break; default: throw new NoViableAltException(this); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public booleanLiteral(): BooleanLiteralContext { let _localctx: BooleanLiteralContext = new BooleanLiteralContext(this._ctx, this.state); this.enterRule(_localctx, 12, ReactiveParser.RULE_booleanLiteral); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 99; _la = this._input.LA(1); if (!(_la === ReactiveParser.T__1 || _la === ReactiveParser.T__2)) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } public sempred(_localctx: RuleContext, ruleIndex: number, predIndex: number): boolean { switch (ruleIndex) { case 0: return this.expression_sempred(_localctx as ExpressionContext, predIndex); } return true; } private expression_sempred(_localctx: ExpressionContext, predIndex: number): boolean { switch (predIndex) { case 0: return this.precpred(this._ctx, 12); case 1: return this.precpred(this._ctx, 11); case 2: return this.precpred(this._ctx, 10); case 3: return this.precpred(this._ctx, 9); case 4: return this.precpred(this._ctx, 8); case 5: return this.precpred(this._ctx, 7); case 6: return this.precpred(this._ctx, 6); case 7: return this.precpred(this._ctx, 5); case 8: return this.precpred(this._ctx, 4); case 9: return this.precpred(this._ctx, 3); case 10: return this.precpred(this._ctx, 2); case 11: return this.precpred(this._ctx, 1); } return true; } public static readonly _serializedATN: string = "\x03\uAF6F\u8320\u479D\uB75C\u4880\u1605\u191C\uAB37\x03\x1Bh\x04\x02" + "\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04\x07" + "\t\x07\x04\b\t\b\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02" + "\x03\x02\x03\x02\x03\x02\x05\x02\x1B\n\x02\x03\x02\x03\x02\x03\x02\x03" + "\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03" + "\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03" + "\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03" + "\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x07\x02A\n\x02\f\x02\x0E" + "\x02D\v\x02\x03\x03\x03\x03\x03\x03\x07\x03I\n\x03\f\x03\x0E\x03L\v\x03" + "\x03\x04\x03\x04\x05\x04P\n\x04\x03\x05\x03\x05\x03\x05\x05\x05U\n\x05" + "\x03\x06\x03\x06\x03\x06\x05\x06Z\n\x06\x05\x06\\\n\x06\x03\x07\x03\x07" + "\x05\x07`\n\x07\x03\x07\x03\x07\x05\x07d\n\x07\x03\b\x03\b\x03\b\x02\x02" + "\x03\x02\t\x02\x02\x04\x02\x06\x02\b\x02\n\x02\f\x02\x0E\x02\x02\x03\x03" + "\x02\x04\x05w\x02\x1A\x03\x02\x02\x02\x04E\x03\x02\x02\x02\x06O\x03\x02" + "\x02\x02\bT\x03\x02\x02\x02\n[\x03\x02\x02\x02\fc\x03\x02\x02\x02\x0E" + "e\x03\x02\x02\x02\x10\x11\b\x02\x01\x02\x11\x1B\x05\x06\x04\x02\x12\x13" + "\x07\x19\x02\x02\x13\x14\x05\x02\x02\x02\x14\x15\x07\x1A\x02\x02\x15\x1B" + "\x03\x02\x02\x02\x16\x17\x07\x0F\x02\x02\x17\x1B\x05\x02\x02\x10\x18\x19" + "\x07\f\x02\x02\x19\x1B\x05\x02\x02\x0F\x1A\x10\x03\x02\x02\x02\x1A\x12" + "\x03\x02\x02\x02\x1A\x16\x03\x02\x02\x02\x1A\x18\x03\x02\x02\x02\x1BB" + "\x03\x02\x02\x02\x1C\x1D\f\x0E\x02\x02\x1D\x1E\x07\r\x02\x02\x1EA\x05" + "\x02\x02\x0F\x1F \f\r\x02\x02 !\x07\x0E\x02\x02!A\x05\x02\x02\x0E\"#\f" + "\f\x02\x02#$\x07\v\x02\x02$A\x05\x02\x02\r%&\f\v\x02\x02&\'\x07\f\x02" + "\x02\'A\x05\x02\x02\f()\f\n\x02\x02)*\x07\x10\x02\x02*A\x05\x02\x02\v" + "+,\f\t\x02\x02,-\x07\x12\x02\x02-A\x05\x02\x02\n./\f\b\x02\x02/0\x07\x11" + "\x02\x020A\x05\x02\x02\t12\f\x07\x02\x0223\x07\x13\x02\x023A\x05\x02\x02" + "\b45\f\x06\x02\x0256\x07\x14\x02\x026A\x05\x02\x02\x0778\f\x05\x02\x02" + "89\x07\x15\x02\x029A\x05\x02\x02\x06:;\f\x04\x02\x02;<\x07\x16\x02\x02" + "<A\x05\x02\x02\x05=>\f\x03\x02\x02>?\x07\x17\x02\x02?A\x05\x02\x02\x04" + "@\x1C\x03\x02\x02\x02@\x1F\x03\x02\x02\x02@\"\x03\x02\x02\x02@%\x03\x02" + "\x02\x02@(\x03\x02\x02\x02@+\x03\x02\x02\x02@.\x03\x02\x02\x02@1\x03\x02" + "\x02\x02@4\x03\x02\x02\x02@7\x03\x02\x02\x02@:\x03\x02\x02\x02@=\x03\x02" + "\x02\x02AD\x03\x02\x02\x02B@\x03\x02\x02\x02BC\x03\x02\x02\x02C\x03\x03" + "\x02\x02\x02DB\x03\x02\x02\x02EJ\x07\x06\x02\x02FG\x07\x18\x02\x02GI\x07" + "\x06\x02\x02HF\x03\x02\x02\x02IL\x03\x02\x02\x02JH\x03\x02\x02\x02JK\x03" + "\x02\x02\x02K\x05\x03\x02\x02\x02LJ\x03\x02\x02\x02MP\x05\b\x05\x02NP" + "\x05\x04\x03\x02OM\x03\x02\x02\x02ON\x03\x02\x02\x02P\x07\x03\x02\x02" + "\x02QU\x05\n\x06\x02RU\x05\f\x07\x02SU\x05\x0E\b\x02TQ\x03\x02\x02\x02" + "TR\x03\x02\x02\x02TS\x03\x02\x02\x02U\t\x03\x02\x02\x02V\\\x07\x03\x02" + "\x02WY\x07\x07\x02\x02XZ\x07\b\x02\x02YX\x03\x02\x02\x02YZ\x03\x02\x02" + "\x02Z\\\x03\x02\x02\x02[V\x03\x02\x02\x02[W\x03\x02\x02\x02\\\v\x03\x02" + "\x02\x02]_\x07\t\x02\x02^`\x07\n\x02\x02_^\x03\x02\x02\x02_`\x03\x02\x02" + "\x02`d\x03\x02\x02\x02ab\x07\b\x02\x02bd\x07\n\x02\x02c]\x03\x02\x02\x02" + "ca\x03\x02\x02\x02d\r\x03\x02\x02\x02ef\t\x02\x02\x02f\x0F\x03\x02\x02" + "\x02\f\x1A@BJOTY[_c"; public static __ATN: ATN; public static get _ATN(): ATN { if (!ReactiveParser.__ATN) { ReactiveParser.__ATN = new ATNDeserializer().deserialize(Utils.toCharArray(ReactiveParser._serializedATN)); } return ReactiveParser.__ATN; } } export class ExpressionContext extends ParserRuleContext { constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return ReactiveParser.RULE_expression; } public copyFrom(ctx: ExpressionContext): void { super.copyFrom(ctx); } } export class BinaryExpressionDivideContext extends ExpressionContext { public _left: ExpressionContext; public _right: ExpressionContext; public DIVIDE(): TerminalNode { return this.getToken(ReactiveParser.DIVIDE, 0); } public expression(): ExpressionContext[]; public expression(i: number): ExpressionContext; public expression(i?: number): ExpressionContext | ExpressionContext[] { if (i === undefined) { return this.getRuleContexts(ExpressionContext); } else { return this.getRuleContext(i, ExpressionContext); } } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterBinaryExpressionDivide) { listener.enterBinaryExpressionDivide(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitBinaryExpressionDivide) { listener.exitBinaryExpressionDivide(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitBinaryExpressionDivide) { return visitor.visitBinaryExpressionDivide(this); } else { return visitor.visitChildren(this); } } } export class UnaryExpressionNotContext extends ExpressionContext { public _exp: ExpressionContext; public NOT(): TerminalNode { return this.getToken(ReactiveParser.NOT, 0); } public expression(): ExpressionContext { return this.getRuleContext(0, ExpressionContext); } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterUnaryExpressionNot) { listener.enterUnaryExpressionNot(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitUnaryExpressionNot) { listener.exitUnaryExpressionNot(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitUnaryExpressionNot) { return visitor.visitUnaryExpressionNot(this); } else { return visitor.visitChildren(this); } } } export class BinaryExpressionLessThanContext extends ExpressionContext { public _left: ExpressionContext; public _right: ExpressionContext; public LT(): TerminalNode { return this.getToken(ReactiveParser.LT, 0); } public expression(): ExpressionContext[]; public expression(i: number): ExpressionContext; public expression(i?: number): ExpressionContext | ExpressionContext[] { if (i === undefined) { return this.getRuleContexts(ExpressionContext); } else { return this.getRuleContext(i, ExpressionContext); } } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterBinaryExpressionLessThan) { listener.enterBinaryExpressionLessThan(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitBinaryExpressionLessThan) { listener.exitBinaryExpressionLessThan(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitBinaryExpressionLessThan) { return visitor.visitBinaryExpressionLessThan(this); } else { return visitor.visitChildren(this); } } } export class BinaryExpressionAndContext extends ExpressionContext { public _left: ExpressionContext; public _right: ExpressionContext; public AND(): TerminalNode { return this.getToken(ReactiveParser.AND, 0); } public expression(): ExpressionContext[]; public expression(i: number): ExpressionContext; public expression(i?: number): ExpressionContext | ExpressionContext[] { if (i === undefined) { return this.getRuleContexts(ExpressionContext); } else { return this.getRuleContext(i, ExpressionContext); } } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterBinaryExpressionAnd) { listener.enterBinaryExpressionAnd(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitBinaryExpressionAnd) { listener.exitBinaryExpressionAnd(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitBinaryExpressionAnd) { return visitor.visitBinaryExpressionAnd(this); } else { return visitor.visitChildren(this); } } } export class AtomicContext extends ExpressionContext { public atomicExpression(): AtomicExpressionContext { return this.getRuleContext(0, AtomicExpressionContext); } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterAtomic) { listener.enterAtomic(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitAtomic) { listener.exitAtomic(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitAtomic) { return visitor.visitAtomic(this); } else { return visitor.visitChildren(this); } } } export class BinaryExpressionGreaterThanOrEqualContext extends ExpressionContext { public _left: ExpressionContext; public _right: ExpressionContext; public GTE(): TerminalNode { return this.getToken(ReactiveParser.GTE, 0); } public expression(): ExpressionContext[]; public expression(i: number): ExpressionContext; public expression(i?: number): ExpressionContext | ExpressionContext[] { if (i === undefined) { return this.getRuleContexts(ExpressionContext); } else { return this.getRuleContext(i, ExpressionContext); } } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterBinaryExpressionGreaterThanOrEqual) { listener.enterBinaryExpressionGreaterThanOrEqual(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitBinaryExpressionGreaterThanOrEqual) { listener.exitBinaryExpressionGreaterThanOrEqual(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitBinaryExpressionGreaterThanOrEqual) { return visitor.visitBinaryExpressionGreaterThanOrEqual(this); } else { return visitor.visitChildren(this); } } } export class BinaryExpressionOrContext extends ExpressionContext { public _left: ExpressionContext; public _right: ExpressionContext; public OR(): TerminalNode { return this.getToken(ReactiveParser.OR, 0); } public expression(): ExpressionContext[]; public expression(i: number): ExpressionContext; public expression(i?: number): ExpressionContext | ExpressionContext[] { if (i === undefined) { return this.getRuleContexts(ExpressionContext); } else { return this.getRuleContext(i, ExpressionContext); } } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterBinaryExpressionOr) { listener.enterBinaryExpressionOr(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitBinaryExpressionOr) { listener.exitBinaryExpressionOr(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitBinaryExpressionOr) { return visitor.visitBinaryExpressionOr(this); } else { return visitor.visitChildren(this); } } } export class GroupExpressionContext extends ExpressionContext { public _exp: ExpressionContext; public OPEN_BRACKET(): TerminalNode { return this.getToken(ReactiveParser.OPEN_BRACKET, 0); } public CLOSED_BRACKET(): TerminalNode { return this.getToken(ReactiveParser.CLOSED_BRACKET, 0); } public expression(): ExpressionContext { return this.getRuleContext(0, ExpressionContext); } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterGroupExpression) { listener.enterGroupExpression(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitGroupExpression) { listener.exitGroupExpression(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitGroupExpression) { return visitor.visitGroupExpression(this); } else { return visitor.visitChildren(this); } } } export class BinaryExpressionSubtractContext extends ExpressionContext { public _left: ExpressionContext; public _right: ExpressionContext; public MINUS(): TerminalNode { return this.getToken(ReactiveParser.MINUS, 0); } public expression(): ExpressionContext[]; public expression(i: number): ExpressionContext; public expression(i?: number): ExpressionContext | ExpressionContext[] { if (i === undefined) { return this.getRuleContexts(ExpressionContext); } else { return this.getRuleContext(i, ExpressionContext); } } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterBinaryExpressionSubtract) { listener.enterBinaryExpressionSubtract(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitBinaryExpressionSubtract) { listener.exitBinaryExpressionSubtract(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitBinaryExpressionSubtract) { return visitor.visitBinaryExpressionSubtract(this); } else { return visitor.visitChildren(this); } } } export class BinaryExpressionGreaterThanContext extends ExpressionContext { public _left: ExpressionContext; public _right: ExpressionContext; public GT(): TerminalNode { return this.getToken(ReactiveParser.GT, 0); } public expression(): ExpressionContext[]; public expression(i: number): ExpressionContext; public expression(i?: number): ExpressionContext | ExpressionContext[] { if (i === undefined) { return this.getRuleContexts(ExpressionContext); } else { return this.getRuleContext(i, ExpressionContext); } } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterBinaryExpressionGreaterThan) { listener.enterBinaryExpressionGreaterThan(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitBinaryExpressionGreaterThan) { listener.exitBinaryExpressionGreaterThan(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitBinaryExpressionGreaterThan) { return visitor.visitBinaryExpressionGreaterThan(this); } else { return visitor.visitChildren(this); } } } export class BinaryExpressionNotEqualContext extends ExpressionContext { public _left: ExpressionContext; public _right: ExpressionContext; public NOT_EQUALS(): TerminalNode { return this.getToken(ReactiveParser.NOT_EQUALS, 0); } public expression(): ExpressionContext[]; public expression(i: number): ExpressionContext; public expression(i?: number): ExpressionContext | ExpressionContext[] { if (i === undefined) { return this.getRuleContexts(ExpressionContext); } else { return this.getRuleContext(i, ExpressionContext); } } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterBinaryExpressionNotEqual) { listener.enterBinaryExpressionNotEqual(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitBinaryExpressionNotEqual) { listener.exitBinaryExpressionNotEqual(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitBinaryExpressionNotEqual) { return visitor.visitBinaryExpressionNotEqual(this); } else { return visitor.visitChildren(this); } } } export class UnaryExpressionNegateContext extends ExpressionContext { public _exp: ExpressionContext; public MINUS(): TerminalNode { return this.getToken(ReactiveParser.MINUS, 0); } public expression(): ExpressionContext { return this.getRuleContext(0, ExpressionContext); } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterUnaryExpressionNegate) { listener.enterUnaryExpressionNegate(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitUnaryExpressionNegate) { listener.exitUnaryExpressionNegate(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitUnaryExpressionNegate) { return visitor.visitUnaryExpressionNegate(this); } else { return visitor.visitChildren(this); } } } export class BinaryExpressionEqualContext extends ExpressionContext { public _left: ExpressionContext; public _right: ExpressionContext; public EQUALS(): TerminalNode { return this.getToken(ReactiveParser.EQUALS, 0); } public expression(): ExpressionContext[]; public expression(i: number): ExpressionContext; public expression(i?: number): ExpressionContext | ExpressionContext[] { if (i === undefined) { return this.getRuleContexts(ExpressionContext); } else { return this.getRuleContext(i, ExpressionContext); } } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterBinaryExpressionEqual) { listener.enterBinaryExpressionEqual(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitBinaryExpressionEqual) { listener.exitBinaryExpressionEqual(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitBinaryExpressionEqual) { return visitor.visitBinaryExpressionEqual(this); } else { return visitor.visitChildren(this); } } } export class BinaryExpressionMultiplyContext extends ExpressionContext { public _left: ExpressionContext; public _right: ExpressionContext; public MULTIPLY(): TerminalNode { return this.getToken(ReactiveParser.MULTIPLY, 0); } public expression(): ExpressionContext[]; public expression(i: number): ExpressionContext; public expression(i?: number): ExpressionContext | ExpressionContext[] { if (i === undefined) { return this.getRuleContexts(ExpressionContext); } else { return this.getRuleContext(i, ExpressionContext); } } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterBinaryExpressionMultiply) { listener.enterBinaryExpressionMultiply(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitBinaryExpressionMultiply) { listener.exitBinaryExpressionMultiply(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitBinaryExpressionMultiply) { return visitor.visitBinaryExpressionMultiply(this); } else { return visitor.visitChildren(this); } } } export class BinaryExpressionLessThanOrEqualContext extends ExpressionContext { public _left: ExpressionContext; public _right: ExpressionContext; public LTE(): TerminalNode { return this.getToken(ReactiveParser.LTE, 0); } public expression(): ExpressionContext[]; public expression(i: number): ExpressionContext; public expression(i?: number): ExpressionContext | ExpressionContext[] { if (i === undefined) { return this.getRuleContexts(ExpressionContext); } else { return this.getRuleContext(i, ExpressionContext); } } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterBinaryExpressionLessThanOrEqual) { listener.enterBinaryExpressionLessThanOrEqual(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitBinaryExpressionLessThanOrEqual) { listener.exitBinaryExpressionLessThanOrEqual(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitBinaryExpressionLessThanOrEqual) { return visitor.visitBinaryExpressionLessThanOrEqual(this); } else { return visitor.visitChildren(this); } } } export class BinaryExpressionAddContext extends ExpressionContext { public _left: ExpressionContext; public _right: ExpressionContext; public PLUS(): TerminalNode { return this.getToken(ReactiveParser.PLUS, 0); } public expression(): ExpressionContext[]; public expression(i: number): ExpressionContext; public expression(i?: number): ExpressionContext | ExpressionContext[] { if (i === undefined) { return this.getRuleContexts(ExpressionContext); } else { return this.getRuleContext(i, ExpressionContext); } } constructor(ctx: ExpressionContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterBinaryExpressionAdd) { listener.enterBinaryExpressionAdd(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitBinaryExpressionAdd) { listener.exitBinaryExpressionAdd(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitBinaryExpressionAdd) { return visitor.visitBinaryExpressionAdd(this); } else { return visitor.visitChildren(this); } } } export class ReferenceContext extends ParserRuleContext { public Identifier(): TerminalNode[]; public Identifier(i: number): TerminalNode; public Identifier(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(ReactiveParser.Identifier); } else { return this.getToken(ReactiveParser.Identifier, i); } } public DOT(): TerminalNode[]; public DOT(i: number): TerminalNode; public DOT(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(ReactiveParser.DOT); } else { return this.getToken(ReactiveParser.DOT, i); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return ReactiveParser.RULE_reference; } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterReference) { listener.enterReference(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitReference) { listener.exitReference(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitReference) { return visitor.visitReference(this); } else { return visitor.visitChildren(this); } } } export class AtomicExpressionContext extends ParserRuleContext { public literal(): LiteralContext | undefined { return this.tryGetRuleContext(0, LiteralContext); } public reference(): ReferenceContext | undefined { return this.tryGetRuleContext(0, ReferenceContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return ReactiveParser.RULE_atomicExpression; } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterAtomicExpression) { listener.enterAtomicExpression(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitAtomicExpression) { listener.exitAtomicExpression(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitAtomicExpression) { return visitor.visitAtomicExpression(this); } else { return visitor.visitChildren(this); } } } export class LiteralContext extends ParserRuleContext { public integerLiteral(): IntegerLiteralContext | undefined { return this.tryGetRuleContext(0, IntegerLiteralContext); } public floatingLiteral(): FloatingLiteralContext | undefined { return this.tryGetRuleContext(0, FloatingLiteralContext); } public booleanLiteral(): BooleanLiteralContext | undefined { return this.tryGetRuleContext(0, BooleanLiteralContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return ReactiveParser.RULE_literal; } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterLiteral) { listener.enterLiteral(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitLiteral) { listener.exitLiteral(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitLiteral) { return visitor.visitLiteral(this); } else { return visitor.visitChildren(this); } } } export class IntegerLiteralContext extends ParserRuleContext { public NonzeroDigit(): TerminalNode | undefined { return this.tryGetToken(ReactiveParser.NonzeroDigit, 0); } public DigitSequence(): TerminalNode | undefined { return this.tryGetToken(ReactiveParser.DigitSequence, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return ReactiveParser.RULE_integerLiteral; } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterIntegerLiteral) { listener.enterIntegerLiteral(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitIntegerLiteral) { listener.exitIntegerLiteral(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitIntegerLiteral) { return visitor.visitIntegerLiteral(this); } else { return visitor.visitChildren(this); } } } export class FloatingLiteralContext extends ParserRuleContext { public FractionalConstant(): TerminalNode | undefined { return this.tryGetToken(ReactiveParser.FractionalConstant, 0); } public ExponentPart(): TerminalNode | undefined { return this.tryGetToken(ReactiveParser.ExponentPart, 0); } public DigitSequence(): TerminalNode | undefined { return this.tryGetToken(ReactiveParser.DigitSequence, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return ReactiveParser.RULE_floatingLiteral; } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterFloatingLiteral) { listener.enterFloatingLiteral(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitFloatingLiteral) { listener.exitFloatingLiteral(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitFloatingLiteral) { return visitor.visitFloatingLiteral(this); } else { return visitor.visitChildren(this); } } } export class BooleanLiteralContext extends ParserRuleContext { constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return ReactiveParser.RULE_booleanLiteral; } // @Override public enterRule(listener: ReactiveListener): void { if (listener.enterBooleanLiteral) { listener.enterBooleanLiteral(this); } } // @Override public exitRule(listener: ReactiveListener): void { if (listener.exitBooleanLiteral) { listener.exitBooleanLiteral(this); } } // @Override public accept<Result>(visitor: ReactiveVisitor<Result>): Result { if (visitor.visitBooleanLiteral) { return visitor.visitBooleanLiteral(this); } else { return visitor.visitChildren(this); } } }
the_stack
import { AppSync } from 'aws-sdk'; import * as setup from './hotswap-test-setup'; let hotswapMockSdkProvider: setup.HotswapMockSdkProvider; let mockUpdateResolver: (params: AppSync.UpdateResolverRequest) => AppSync.UpdateResolverResponse; let mockUpdateFunction: (params: AppSync.UpdateFunctionRequest) => AppSync.UpdateFunctionResponse; beforeEach(() => { hotswapMockSdkProvider = setup.setupHotswapTests(); mockUpdateResolver = jest.fn(); mockUpdateFunction = jest.fn(); hotswapMockSdkProvider.stubAppSync({ updateResolver: mockUpdateResolver, updateFunction: mockUpdateFunction }); }); test('returns undefined when a new Resolver is added to the Stack', async () => { // GIVEN const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { AppSyncResolver: { Type: 'AWS::AppSync::Resolver', }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); }); test('calls the updateResolver() API when it receives only a mapping template difference in a Unit Resolver', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { AppSyncResolver: { Type: 'AWS::AppSync::Resolver', Properties: { ApiId: 'apiId', FieldName: 'myField', TypeName: 'Query', DataSourceName: 'my-datasource', Kind: 'UNIT', RequestMappingTemplate: '## original request template', ResponseMappingTemplate: '## original response template', }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); setup.pushStackResourceSummaries( setup.stackSummaryOf( 'AppSyncResolver', 'AWS::AppSync::Resolver', 'arn:aws:appsync:us-east-1:111111111111:apis/apiId/types/Query/resolvers/myField', ), ); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { AppSyncResolver: { Type: 'AWS::AppSync::Resolver', Properties: { ApiId: 'apiId', FieldName: 'myField', TypeName: 'Query', DataSourceName: 'my-datasource', Kind: 'UNIT', RequestMappingTemplate: '## new request template', ResponseMappingTemplate: '## original response template', }, Metadata: { 'aws:asset:path': 'new-path', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).not.toBeUndefined(); expect(mockUpdateResolver).toHaveBeenCalledWith({ apiId: 'apiId', dataSourceName: 'my-datasource', typeName: 'Query', fieldName: 'myField', kind: 'UNIT', requestMappingTemplate: '## new request template', responseMappingTemplate: '## original response template', }); }); test('does not call the updateResolver() API when it receives only a mapping template difference in a Pipeline Resolver', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { AppSyncResolver: { Type: 'AWS::AppSync::Resolver', Properties: { ApiId: 'apiId', FieldName: 'myField', TypeName: 'Query', DataSourceName: 'my-datasource', Kind: 'PIPELINE', PipelineConfig: ['function1'], RequestMappingTemplate: '## original request template', ResponseMappingTemplate: '## original response template', }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { AppSyncResolver: { Type: 'AWS::AppSync::Resolver', Properties: { ApiId: 'apiId', FieldName: 'myField', TypeName: 'Query', DataSourceName: 'my-datasource', Kind: 'PIPELINE', PipelineConfig: ['function1'], RequestMappingTemplate: '## new request template', ResponseMappingTemplate: '## original response template', }, Metadata: { 'aws:asset:path': 'new-path', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); expect(mockUpdateResolver).not.toHaveBeenCalled(); }); test('does not call the updateResolver() API when it receives a change that is not a mapping template difference in a Resolver', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { AppSyncResolver: { Type: 'AWS::AppSync::Resolver', Properties: { RequestMappingTemplate: '## original template', FieldName: 'oldField', }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { AppSyncResolver: { Type: 'AWS::AppSync::Resolver', Properties: { RequestMappingTemplate: '## new template', FieldName: 'newField', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); expect(mockUpdateResolver).not.toHaveBeenCalled(); }); test('does not call the updateResolver() API when a resource with type that is not AWS::AppSync::Resolver but has the same properties is changed', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { AppSyncResolver: { Type: 'AWS::AppSync::NotAResolver', Properties: { RequestMappingTemplate: '## original template', FieldName: 'oldField', }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { AppSyncResolver: { Type: 'AWS::AppSync::NotAResolver', Properties: { RequestMappingTemplate: '## new template', FieldName: 'newField', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); expect(mockUpdateResolver).not.toHaveBeenCalled(); }); test('calls the updateFunction() API when it receives only a mapping template difference in a Function', async () => { // GIVEN const mockListFunctions = jest.fn().mockReturnValue({ functions: [{ name: 'my-function', functionId: 'functionId' }] }); hotswapMockSdkProvider.stubAppSync({ listFunctions: mockListFunctions, updateFunction: mockUpdateFunction }); setup.setCurrentCfnStackTemplate({ Resources: { AppSyncFunction: { Type: 'AWS::AppSync::FunctionConfiguration', Properties: { Name: 'my-function', ApiId: 'apiId', DataSourceName: 'my-datasource', FunctionVersion: '2018-05-29', RequestMappingTemplate: '## original request template', ResponseMappingTemplate: '## original response template', }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { AppSyncFunction: { Type: 'AWS::AppSync::FunctionConfiguration', Properties: { Name: 'my-function', ApiId: 'apiId', DataSourceName: 'my-datasource', FunctionVersion: '2018-05-29', RequestMappingTemplate: '## original request template', ResponseMappingTemplate: '## new response template', }, Metadata: { 'aws:asset:path': 'new-path', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).not.toBeUndefined(); expect(mockUpdateFunction).toHaveBeenCalledWith({ apiId: 'apiId', dataSourceName: 'my-datasource', functionId: 'functionId', functionVersion: '2018-05-29', name: 'my-function', requestMappingTemplate: '## original request template', responseMappingTemplate: '## new response template', }); }); test('does not call the updateFunction() API when it receives a change that is not a mapping template difference in a Function', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { AppSyncFunction: { Type: 'AWS::AppSync::FunctionConfiguration', Properties: { RequestMappingTemplate: '## original template', Name: 'my-function', DataSourceName: 'my-datasource', }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { AppSyncFunction: { Type: 'AWS::AppSync::FunctionConfiguration', Properties: { RequestMappingTemplate: '## new template', Name: 'my-function', DataSourceName: 'new-datasource', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); expect(mockUpdateFunction).not.toHaveBeenCalled(); }); test('does not call the updateFunction() API when a resource with type that is not AWS::AppSync::FunctionConfiguration but has the same properties is changed', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { AppSyncFunction: { Type: 'AWS::AppSync::NotAFunctionConfiguration', Properties: { RequestMappingTemplate: '## original template', Name: 'my-function', DataSourceName: 'my-datasource', }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { AppSyncFunction: { Type: 'AWS::AppSync::NotAFunctionConfiguration', Properties: { RequestMappingTemplate: '## new template', Name: 'my-resolver', DataSourceName: 'my-datasource', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); expect(mockUpdateFunction).not.toHaveBeenCalled(); });
the_stack
import { EventEmitter } from 'events'; import * as fs from 'fs'; import * as path from 'path'; import * as sshConfig from 'ssh-config'; import app from '../app'; import logger from '../logger'; import { getUserSetting } from '../host'; import { replaceHomePath, resolvePath } from '../helper'; import { SETTING_KEY_REMOTE } from '../constants'; import upath from './upath'; import Ignore from './ignore'; import { FileSystem } from './fs'; import Scheduler from './scheduler'; import { createRemoteIfNoneExist, removeRemoteFs } from './remoteFs'; import TransferTask from './transferTask'; import localFs from './localFs'; type Omit<T, U> = Pick<T, Exclude<keyof T, U>>; interface Root { name: string; context: string; watcher: WatcherConfig; defaultProfile: string; } interface Host { host: string; port: number; username: string; password: string; remotePath: string; connectTimeout: number; } interface ServiceOption { protocol: string; remote?: string; uploadOnSave: boolean; downloadOnOpen: boolean | 'confirm'; syncOption: { delete: boolean; skipCreate: boolean; ignoreExisting: boolean; update: boolean; }; ignore: string[]; ignoreFile: string; remoteExplorer?: { filesExclude?: string[]; }; remoteTimeOffsetInHours: number; limitOpenFilesOnRemote: number | true; } interface WatcherConfig { files: false | string; autoUpload: boolean; autoDelete: boolean; } interface SftpOption { // sftp agent?: string; privateKeyPath?: string; passphrase: string | true; interactiveAuth: boolean; algorithms: any; sshConfigPath?: string; concurrency: number; sshCustomParams?: string; hop: (Host & SftpOption)[] | (Host & SftpOption); } interface FtpOption { secure: boolean | 'control' | 'implicit'; secureOptions: any; } export interface FileServiceConfig extends Root, Host, ServiceOption, SftpOption, FtpOption { profiles?: { [x: string]: FileServiceConfig; }; } export interface ServiceConfig extends Root, Host, Omit<ServiceOption, 'ignore'>, SftpOption, FtpOption { ignore?: ((fsPath: string) => boolean) | null; } export interface WatcherService { create(watcherBase: string, watcherConfig: WatcherConfig): any; dispose(watcherBase: string): void; } interface TransferScheduler { // readonly _scheduler: Scheduler; size: number; add(x: TransferTask): void; run(): Promise<void>; stop(): void; } type ConfigValidator = (x: any) => { message: string }; const DEFAULT_SSHCONFIG_FILE = '~/.ssh/config'; function filesIgnoredFromConfig(config: FileServiceConfig): string[] { const cache = app.fsCache; const ignore: string[] = config.ignore && config.ignore.length ? config.ignore : []; const ignoreFile = config.ignoreFile; if (!ignoreFile) { return ignore; } let ignoreFromFile; if (cache.has(ignoreFile)) { ignoreFromFile = cache.get(ignoreFile); } else if (fs.existsSync(ignoreFile)) { ignoreFromFile = fs.readFileSync(ignoreFile).toString(); cache.set(ignoreFile, ignoreFromFile); } else { throw new Error( `File ${ignoreFile} not found. Check your config of "ignoreFile"` ); } return ignore.concat(ignoreFromFile.split(/\r?\n/g)); } function getHostInfo(config) { const ignoreOptions = [ 'name', 'remotePath', 'uploadOnSave', 'downloadOnOpen', 'ignore', 'ignoreFile', 'watcher', 'concurrency', 'syncOption', 'sshConfigPath', ]; return Object.keys(config).reduce((obj, key) => { if (ignoreOptions.indexOf(key) === -1) { obj[key] = config[key]; } return obj; }, {}); } function chooseDefaultPort(protocol) { return protocol === 'ftp' ? 21 : 22; } function setConfigValue(config, key, value) { if (config[key] === undefined) { if (key === 'port') { config[key] = parseInt(value, 10); } else { config[key] = value; } } } function mergeConfigWithExternalRefer( config: FileServiceConfig ): FileServiceConfig { const copyed = Object.assign({}, config); if (config.remote) { const remoteMap = getUserSetting(SETTING_KEY_REMOTE); const remote = remoteMap.get<Record<string, any>>(config.remote); if (!remote) { throw new Error(`Can\'t not find remote "${config.remote}"`); } const remoteKeyMapping = new Map([['scheme', 'protocol']]); const remoteKeyIgnored = new Map([['rootPath', 1]]); Object.keys(remote).forEach(key => { if (remoteKeyIgnored.has(key)) { return; } const targetKey = remoteKeyMapping.has(key) ? remoteKeyMapping.get(key) : key; setConfigValue(copyed, targetKey, remote[key]); }); } if (config.protocol !== 'sftp') { return copyed; } const sshConfigPath = replaceHomePath( config.sshConfigPath || DEFAULT_SSHCONFIG_FILE ); const cache = app.fsCache; let sshConfigContent; if (cache.has(sshConfigPath)) { sshConfigContent = cache.get(sshConfigPath); } else { try { sshConfigContent = fs.readFileSync(sshConfigPath, 'utf8'); } catch (error) { logger.warn(error.message, `load ${sshConfigPath} failed`); sshConfigContent = ''; } cache.set(sshConfigPath, sshConfigContent); } if (!sshConfigContent) { return copyed; } const parsedSSHConfig = sshConfig.parse(sshConfigContent); const section = parsedSSHConfig.find({ Host: copyed.host, }); if (section === null) { return copyed; } const mapping = new Map([ ['hostname', 'host'], ['port', 'port'], ['user', 'username'], ['identityfile', 'privateKeyPath'], ['serveraliveinterval', 'keepalive'], ['connecttimeout', 'connTimeout'], ]); section.config.forEach(line => { if (!line.param) { return; } const key = mapping.get(line.param.toLowerCase()); if (key !== undefined) { // don't need consider config priority, always set to the resolve host. if (key === 'host') { copyed[key] = line.value; } else { setConfigValue(copyed, key, line.value); } } }); return copyed; } function getCompleteConfig( config: FileServiceConfig, workspace: string ): FileServiceConfig { const mergedConfig = mergeConfigWithExternalRefer(config); if (mergedConfig.agent && mergedConfig.privateKeyPath) { logger.warn( 'Config Option Conflicted. You are specifing "agent" and "privateKey" at the same time, ' + 'the later will be ignored.' ); } // remove the './' part from a relative path mergedConfig.remotePath = upath.normalize(mergedConfig.remotePath); if (mergedConfig.privateKeyPath) { mergedConfig.privateKeyPath = resolvePath( workspace, mergedConfig.privateKeyPath ); } if (mergedConfig.ignoreFile) { mergedConfig.ignoreFile = resolvePath(workspace, mergedConfig.ignoreFile); } // convert ingore config to ignore function if (mergedConfig.agent && mergedConfig.agent.startsWith('$')) { const evnVarName = mergedConfig.agent.slice(1); const val = process.env[evnVarName]; if (!val) { throw new Error(`Environment variable "${evnVarName}" not found`); } mergedConfig.agent = val; } return mergedConfig; } function mergeProfile( target: FileServiceConfig, source: FileServiceConfig ): FileServiceConfig { const res = Object.assign({}, target); delete res.profiles; const keys = Object.keys(source); for (const key of keys) { if (key === 'ignore') { res.ignore = res.ignore.concat(source.ignore); } else { res[key] = source[key]; } } return res; } enum Event { BEFORE_TRANSFER = 'BEFORE_TRANSFER', AFTER_TRANSFER = 'AFTER_TRANSFER', } let id = 0; export default class FileService { private _eventEmitter: EventEmitter = new EventEmitter(); private _name: string; private _watcherConfig: WatcherConfig; private _profiles: string[]; private _pendingTransferTasks: Set<TransferTask> = new Set(); private _transferSchedulers: TransferScheduler[] = []; private _config: FileServiceConfig; private _configValidator: ConfigValidator; private _watcherService: WatcherService = { create() { /* do nothing */ }, dispose() { /* do nothing */ }, }; id: number; baseDir: string; workspace: string; constructor(baseDir: string, workspace: string, config: FileServiceConfig) { this.id = ++id; this.workspace = workspace; this.baseDir = baseDir; this._watcherConfig = config.watcher; this._config = config; if (config.profiles) { this._profiles = Object.keys(config.profiles); } } get name(): string { return this._name ? this._name : ''; } set name(name: string) { this._name = name; } setConfigValidator(configValidator: ConfigValidator) { this._configValidator = configValidator; } setWatcherService(watcherService: WatcherService) { if (this._watcherService) { this._disposeWatcher(); } this._watcherService = watcherService; this._createWatcher(); } getAvaliableProfiles(): string[] { return this._profiles || []; } getPendingTransferTasks(): TransferTask[] { return Array.from(this._pendingTransferTasks); } isTransferring() { return this._transferSchedulers.length > 0; } cancelTransferTasks() { // keep the order // 1, remove tasks not start this._transferSchedulers.forEach(transfer => transfer.stop()); this._transferSchedulers.length = 0; // 2. cancel running task this._pendingTransferTasks.forEach(t => t.cancel()); this._pendingTransferTasks.clear(); } beforeTransfer(listener: (task: TransferTask) => void) { this._eventEmitter.on(Event.BEFORE_TRANSFER, listener); } afterTransfer(listener: (err: Error | null, task: TransferTask) => void) { this._eventEmitter.on(Event.AFTER_TRANSFER, listener); } createTransferScheduler(concurrency): TransferScheduler { const fileService = this; const scheduler = new Scheduler({ autoStart: false, concurrency, }); scheduler.onTaskStart(task => { this._pendingTransferTasks.add(task as TransferTask); this._eventEmitter.emit(Event.BEFORE_TRANSFER, task); }); scheduler.onTaskDone((err, task) => { this._pendingTransferTasks.delete(task as TransferTask); this._eventEmitter.emit(Event.AFTER_TRANSFER, err, task); }); let runningPromise: Promise<void> | null = null; let isStopped: boolean = false; const transferScheduler: TransferScheduler = { get size() { return scheduler.size; }, stop() { isStopped = true; scheduler.empty(); }, add(task: TransferTask) { if (isStopped) { return; } scheduler.add(task); }, run() { if (isStopped) { return Promise.resolve(); } if (scheduler.size <= 0) { fileService._removeScheduler(transferScheduler); return Promise.resolve(); } if (!runningPromise) { runningPromise = new Promise(resolve => { scheduler.onIdle(() => { runningPromise = null; fileService._removeScheduler(transferScheduler); resolve(); }); scheduler.start(); }); } return runningPromise; }, }; fileService._storeScheduler(transferScheduler); return transferScheduler; } getLocalFileSystem(): FileSystem { return localFs; } getRemoteFileSystem(config: ServiceConfig): Promise<FileSystem> { return createRemoteIfNoneExist(getHostInfo(config)); } getConfig(): ServiceConfig { let config = this._config; const hasProfile = config.profiles && Object.keys(config.profiles).length > 0; if (hasProfile && app.state.profile) { logger.info(`Using profile: ${app.state.profile}`); const profile = config.profiles![app.state.profile]; if (!profile) { throw new Error( `Unkown Profile "${app.state.profile}".` + ' Please check your profile setting.' + ' You can set a profile by running command `SFTP: Set Profile`.' ); } config = mergeProfile(config, profile); } const completeConfig = getCompleteConfig(config, this.workspace); const error = this._configValidator && this._configValidator(completeConfig); if (error) { let errorMsg = `Config validation fail: ${error.message}.`; // tslint:disable-next-line triple-equals if (hasProfile && app.state.profile == null) { errorMsg += ' You might want to set a profile first.'; } throw new Error(errorMsg); } return this._resolveServiceConfig(completeConfig); } dispose() { this._disposeWatcher(); this._disposeFileSystem(); } private _resolveServiceConfig( fileServiceConfig: FileServiceConfig ): ServiceConfig { const serviceConfig: ServiceConfig = fileServiceConfig as any; if (serviceConfig.port === undefined) { serviceConfig.port = chooseDefaultPort(serviceConfig.protocol); } if (serviceConfig.protocol === 'ftp') { serviceConfig.concurrency = 1; } serviceConfig.ignore = this._createIgnoreFn(fileServiceConfig); return serviceConfig; } private _storeScheduler(scheduler: TransferScheduler) { this._transferSchedulers.push(scheduler); } private _removeScheduler(scheduler: TransferScheduler) { const index = this._transferSchedulers.findIndex(s => s === scheduler); if (index !== -1) { this._transferSchedulers.splice(index, 1); } } private _createIgnoreFn(config: FileServiceConfig): ServiceConfig['ignore'] { const localContext = this.baseDir; const remoteContext = config.remotePath; const ignoreConfig = filesIgnoredFromConfig(config); if (ignoreConfig.length <= 0) { return null; } const ignore = Ignore.from(ignoreConfig); const ignoreFunc = fsPath => { // vscode will always return path with / as separator const normalizedPath = path.normalize(fsPath); let relativePath; if (normalizedPath.indexOf(localContext) === 0) { // local path relativePath = path.relative(localContext, fsPath); } else { // remote path relativePath = upath.relative(remoteContext, fsPath); } // skip root return relativePath !== '' && ignore.ignores(relativePath); }; return ignoreFunc; } private _createWatcher() { this._watcherService.create(this.baseDir, this._watcherConfig); } private _disposeWatcher() { this._watcherService.dispose(this.baseDir); } // fixme: remote all profiles private _disposeFileSystem() { return removeRemoteFs(getHostInfo(this.getConfig())); } }
the_stack
import huffman from "n-ary-huffman"; import iconsChecksum from "../icons/checksum"; import { elementKey, ElementRender, ElementReport, ElementTypes, ElementWithHint, ExtendedElementReport, HintMeasurements, HintUpdate, } from "../shared/hints"; import { HintsMode, KeyboardAction, KeyboardMapping, KeyboardModeBackground, KeyboardModeWorker, NormalizedKeypress, PREVENT_OVERTYPING_ALLOWED_KEYBOARD_ACTIONS, } from "../shared/keyboard"; import { addListener, CONTAINER_ID, decode, fireAndForget, isMixedCase, log, makeRandomToken, partition, Resets, splitEnteredText, } from "../shared/main"; import type { FromBackground, FromOptions, FromPopup, FromRenderer, FromWorker, ToBackground, ToOptions, ToPopup, ToRenderer, ToWorker, } from "../shared/messages"; import { diffOptions, flattenOptions, getDefaults, getRawOptions, makeOptionsDecoder, OptionsData, PartialOptions, unflattenOptions, } from "../shared/options"; import { MAX_PERF_ENTRIES, Perf, Stats, TabsPerf, TimeTracker, } from "../shared/perf"; import { tweakable, unsignedInt } from "../shared/tweakable"; type MessageInfo = { tabId: number; frameId: number; url: string | undefined; }; type TabState = { hintsState: HintsState; keyboardMode: KeyboardModeBackground; perf: Perf; isOptionsPage: boolean; isPinned: boolean; }; type HintsState = | { type: "Collecting"; mode: HintsMode; pendingElements: PendingElements; startTime: number; time: TimeTracker; stats: Array<Stats>; refreshing: boolean; highlighted: Highlighted; } | { type: "Hinting"; mode: HintsMode; startTime: number; time: TimeTracker; stats: Array<Stats>; enteredChars: string; enteredText: string; elementsWithHints: Array<ElementWithHint>; highlighted: Highlighted; updateState: UpdateState; peeking: boolean; } | { type: "Idle"; highlighted: Highlighted; }; // All HintsState types store the highlighted hints (highlighted due to being // matched, not due to filtering by text), so that they can stay highlighted for // `t.MATCH_HIGHLIGHT_DURATION` ms. type Highlighted = Array<HighlightedItem>; type HighlightedItem = { sinceTimestamp: number; element: ElementWithHint; }; type PendingElements = { pendingFrames: { answering: number; collecting: number; lastStartWaitTimestamp: number; }; elements: Array<ExtendedElementReport>; }; type UpdateState = | { type: "WaitingForResponse"; lastUpdateStartTimestamp: number; } | { type: "WaitingForTimeout"; lastUpdateStartTimestamp: number; }; type HintInput = | { type: "ActivateHint"; alt: boolean; } | { type: "Backspace"; } | { type: "Input"; keypress: NormalizedKeypress; }; // As far as I can tell, the top frameId is always 0. This is also mentioned here: // https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/Tabs/executeScript // “frameId: Optional integer. The frame where the code should be injected. // Defaults to 0 (the top-level frame).” const TOP_FRAME_ID = 0; export const t = { // Some onscreen frames may never respond (if the frame 404s or hasn't loaded // yet), but the parent can't now that. If a frame hasn't reported that it is // alive after this timeout, ignore it. FRAME_REPORT_TIMEOUT: unsignedInt(100), // ms // Only show the badge “spinner” if the hints are slow. BADGE_COLLECTING_DELAY: unsignedInt(300), // ms // Roughly how often to update the hints in hints mode. While a lower number // might yield updates faster, that feels very stuttery. Having a somewhat // longer interval feels better. UPDATE_INTERVAL: unsignedInt(500), // ms UPDATE_MIN_TIMEOUT: unsignedInt(100), // ms // How long a matched/activated hint should show as highlighted. MATCH_HIGHLIGHT_DURATION: unsignedInt(200), // ms }; export const tMeta = tweakable("Background", t); export default class BackgroundProgram { options: OptionsData; tabState = new Map<number, TabState>(); restoredTabsPerf: TabsPerf = {}; oneTimeWindowMessageToken: string = makeRandomToken(); resets = new Resets(); constructor() { const mac = false; const defaults = getDefaults({ mac }); this.options = { defaults, values: defaults, raw: {}, errors: [], mac, }; } async start(): Promise<void> { log("log", "BackgroundProgram#start", BROWSER, PROD); try { await this.updateOptions({ isInitial: true }); } catch (errorAny) { const error = errorAny as Error; this.options.errors = [error.message]; } if (!PROD) { await this.restoreTabsPerf(); } const tabs = await browser.tabs.query({}); this.resets.add( addListener( browser.runtime.onMessage, this.onMessage.bind(this), "BackgroundProgram#onMessage" ), addListener( browser.runtime.onConnect, this.onConnect.bind(this), "BackgroundProgram#onConnect" ), addListener( browser.tabs.onActivated, this.onTabActivated.bind(this), "BackgroundProgram#onTabActivated" ), addListener( browser.tabs.onCreated, this.onTabCreated.bind(this), "BackgroundProgram#onTabCreated" ), addListener( browser.tabs.onUpdated, this.onTabUpdated.bind(this), "BackgroundProgram#onTabUpdated", // Chrome doesn’t support filters. BROWSER === "firefox" ? { properties: ["status", "pinned"] } : undefined ), addListener( browser.tabs.onRemoved, this.onTabRemoved.bind(this), "BackgroundProgram#onTabRemoved" ) ); for (const tab of tabs) { if (tab.id !== undefined) { fireAndForget( this.updateIcon(tab.id), "BackgroundProgram#start->updateIcon", tab ); } } fireAndForget( browser.browserAction.setBadgeBackgroundColor({ color: COLOR_BADGE }), "BackgroundProgram#start->setBadgeBackgroundColor" ); fireAndForget( this.maybeOpenTutorial(), "BackgroundProgram#start->maybeOpenTutorial" ); fireAndForget( this.maybeReopenOptions(), "BackgroundProgram#start->maybeReopenOptions" ); // Firefox automatically loads content scripts into existing tabs, while // Chrome only automatically loads content scripts into _new_ tabs. // Firefox requires a workaround (see renderer/Program.ts), while we // manually load the content scripts into existing tabs in Chrome. if (BROWSER === "firefox") { firefoxWorkaround(tabs); } else { await runContentScripts(tabs); } } stop(): void { log("log", "BackgroundProgram#stop"); this.resets.reset(); } sendWorkerMessage( message: ToWorker, recipient: { tabId: number; frameId: number | "all_frames" } ): void { log("log", "BackgroundProgram#sendWorkerMessage", message, recipient); fireAndForget( this.sendContentMessage({ type: "ToWorker", message }, recipient), "BackgroundProgram#sendWorkerMessage", message, recipient ); } sendRendererMessage(message: ToRenderer, { tabId }: { tabId: number }): void { const recipient = { tabId, frameId: TOP_FRAME_ID }; log("log", "BackgroundProgram#sendRendererMessage", message, recipient); fireAndForget( this.sendContentMessage({ type: "ToRenderer", message }, recipient), "BackgroundProgram#sendRendererMessage", message, recipient ); } sendPopupMessage(message: ToPopup): void { log("log", "BackgroundProgram#sendPopupMessage", message); fireAndForget( this.sendBackgroundMessage({ type: "ToPopup", message }), "BackgroundProgram#sendPopupMessage", message ); } sendOptionsMessage(message: ToOptions): void { const optionsTabOpen = Array.from(this.tabState).some( ([, tabState]) => tabState.isOptionsPage ); // Trying to send a message to Options when no Options tab is open results // in "errors" being logged to the console. if (optionsTabOpen) { log("log", "BackgroundProgram#sendOptionsMessage", message); fireAndForget( this.sendBackgroundMessage({ type: "ToOptions", message }), "BackgroundProgram#sendOptionsMessage", message ); } } // This might seem like sending a message to oneself, but // `browser.runtime.sendMessage` seems to only send messages to *other* // background scripts, such as the popup script. async sendBackgroundMessage(message: FromBackground): Promise<void> { await browser.runtime.sendMessage(message); } async sendContentMessage( message: FromBackground, { tabId, frameId }: { tabId: number; frameId: number | "all_frames" } ): Promise<void> { await (frameId === "all_frames" ? browser.tabs.sendMessage(tabId, message) : browser.tabs.sendMessage(tabId, message, { frameId })); } // Warning: Don’t make this method async! If a new tab gets for example 3 // events in a short time just after being opened, those three events might // overwrite each other. Expected execution: // // 1. Process event1. // 2. Process event2. // 3. Process event3. // // Async execution (for very close events): // // 1. Start processing event1 until the first `await`. // 2. Start processing event2 until the first `await`. // 3. Start processing event3 until the first `await`. // 4. Finish processing event1 (assuming no more `await`s). // 5. Finish processing event2 (assuming no more `await`s). // 6. Finish processing event3 (assuming no more `await`s). // // In the async case, all of the events might try to do `this.tabState.set()`. // // This happens when opening the Options page: WorkerScriptAdded, // OptionsScriptAdded and RendererScriptAdded are all triggered very close to // each other. An overwrite can cause us to lose `tabState.isOptionsPage`, // breaking shortcuts customization. onMessage( message: ToBackground, sender: browser.runtime.MessageSender ): void { // `info` can be missing when the message comes from for example the popup // (which isn’t associated with a tab). The worker script can even load in // an `about:blank` frame somewhere when hovering the browserAction! const info = makeMessageInfo(sender); const tabStateRaw = info === undefined ? undefined : this.tabState.get(info.tabId); const tabState = tabStateRaw === undefined ? makeEmptyTabState(info?.tabId) : tabStateRaw; if (info !== undefined && tabStateRaw === undefined) { const { [info.tabId.toString()]: perf = [] } = this.restoredTabsPerf; tabState.perf = perf; this.tabState.set(info.tabId, tabState); } switch (message.type) { case "FromWorker": if (info !== undefined) { try { this.onWorkerMessage(message.message, info, tabState); } catch (error) { log( "error", "BackgroundProgram#onWorkerMessage", error, message.message, info ); } } break; case "FromRenderer": if (info !== undefined) { try { this.onRendererMessage(message.message, info, tabState); } catch (error) { log( "error", "BackgroundProgram#onRendererMessage", error, message.message, info ); } } break; case "FromPopup": fireAndForget( this.onPopupMessage(message.message), "BackgroundProgram#onPopupMessage", message.message, info ); break; case "FromOptions": if (info !== undefined) { fireAndForget( this.onOptionsMessage(message.message, info, tabState), "BackgroundProgram#onOptionsMessage", message.message, info ); } break; } } onConnect(port: browser.runtime.Port): void { port.onDisconnect.addListener(({ sender }) => { const info = sender === undefined ? undefined : makeMessageInfo(sender); if (info !== undefined) { // A frame was removed. If in hints mode, hide all hints for elements in // that frame. this.hideElements(info); } }); } onWorkerMessage( message: FromWorker, info: MessageInfo, tabState: TabState ): void { log("log", "BackgroundProgram#onWorkerMessage", message, info); switch (message.type) { case "WorkerScriptAdded": this.sendWorkerMessage( // Make sure that the added worker script gets the same token as all // other frames in the page. Otherwise the first hints mode won't // reach into any frames. this.makeWorkerState(tabState, { refreshToken: false }), { tabId: info.tabId, frameId: info.frameId, } ); break; case "KeyboardShortcutMatched": this.onKeyboardShortcut(message.action, info, message.timestamp); break; case "NonKeyboardShortcutKeypress": this.handleHintInput(info.tabId, message.timestamp, { type: "Input", keypress: message.keypress, }); break; case "KeypressCaptured": this.sendOptionsMessage({ type: "KeypressCaptured", keypress: message.keypress, }); break; case "ReportVisibleFrame": { const { hintsState } = tabState; if (hintsState.type !== "Collecting") { return; } const { pendingFrames } = hintsState.pendingElements; pendingFrames.answering = Math.max(0, pendingFrames.answering - 1); pendingFrames.collecting += 1; break; } case "ReportVisibleElements": { const { hintsState } = tabState; if (hintsState.type !== "Collecting") { return; } const elements: Array<ExtendedElementReport> = message.elements.map( (element) => ({ ...element, // Move the element index into the `.frame` property. `.index` is set // later (in `this.maybeStartHinting`) and used to map elements in // BackgroundProgram to DOM elements in RendererProgram. index: -1, frame: { id: info.frameId, index: element.index }, hidden: false, }) ); hintsState.pendingElements.elements.push(...elements); const { pendingFrames } = hintsState.pendingElements; pendingFrames.answering += message.numFrames; pendingFrames.collecting = Math.max(0, pendingFrames.collecting - 1); hintsState.stats.push(message.stats); if (message.numFrames === 0) { this.maybeStartHinting(info.tabId); } else { pendingFrames.lastStartWaitTimestamp = Date.now(); this.setTimeout(info.tabId, t.FRAME_REPORT_TIMEOUT.value); } break; } case "ReportUpdatedElements": { const { hintsState } = tabState; if (hintsState.type !== "Hinting") { return; } const updatedElementsWithHints = mergeElements( hintsState.elementsWithHints, message.elements, info.frameId ); const { enteredChars, enteredText } = hintsState; const { allElementsWithHints, updates } = updateHints({ mode: hintsState.mode, enteredChars, enteredText, elementsWithHints: updatedElementsWithHints, highlighted: hintsState.highlighted, chars: this.options.values.chars, autoActivate: this.options.values.autoActivate, matchHighlighted: false, updateMeasurements: true, }); hintsState.elementsWithHints = allElementsWithHints; this.sendRendererMessage( { type: "UpdateHints", updates, enteredText, }, { tabId: info.tabId } ); this.sendRendererMessage( { type: "RenderTextRects", rects: message.rects, frameId: info.frameId, }, { tabId: info.tabId } ); this.updateBadge(info.tabId); if (info.frameId === TOP_FRAME_ID) { const { updateState } = hintsState; const now = Date.now(); const elapsedTime = now - updateState.lastUpdateStartTimestamp; const timeout = Math.max( t.UPDATE_MIN_TIMEOUT.value, t.UPDATE_INTERVAL.value - elapsedTime ); log("log", "Scheduling next elements update", { elapsedTime, timeout, UPDATE_INTERVAL: t.UPDATE_INTERVAL.value, UPDATE_MIN_TIMEOUT: t.UPDATE_MIN_TIMEOUT.value, }); hintsState.updateState = { type: "WaitingForTimeout", lastUpdateStartTimestamp: updateState.lastUpdateStartTimestamp, }; this.setTimeout(info.tabId, timeout); } break; } case "ReportTextRects": this.sendRendererMessage( { type: "RenderTextRects", rects: message.rects, frameId: info.frameId, }, { tabId: info.tabId } ); break; // When clicking a link using the extension that causes a page load (no // `.preventDefault()`, no internal fragment identifier, no `javascript:` // protocol, etc), exit hints mode. This is especially nice for the // "ManyClick" mode since it makes the hints go away immediately when // clicking the link rather than after a little while when the "pagehide" // event has fired. case "ClickedLinkNavigatingToOtherPage": { const { hintsState } = tabState; if (hintsState.type !== "Idle") { // Exit in “Delayed” mode so that the matched hints still show as // highlighted. this.exitHintsMode({ tabId: info.tabId, delayed: true }); } break; } // If the user clicks a link while hints mode is active, exit it. // Otherwise you’ll end up in hints mode on the new page (it is still the // same tab, after all) but with no hints. If changing the address bar of // the tab to for example `about:preferences` it is too late to send // message to the content scripts (“Error: Receiving end does not exist”). // Instead, syncing `WorkerProgram`s and unrendering is taken care of // if/when returning to the page via the back button. (See below.) case "TopPageHide": { const { hintsState } = tabState; if (hintsState.type !== "Idle") { this.exitHintsMode({ tabId: info.tabId, sendMessages: false }); } break; } // When clicking the back button In Firefox, the content scripts of the // previous page aren’t re-run but instead pick up from where they were // when leaving the page. If the user clicked a link while in hints mode // and then pressed the back button, the `tabState` for the tab won’t be // in hints mode, but the content scripts of the page might be out of // sync. They never got any messages saying that hints mode was exited, // and now they pick up from where they were. So after returning to a page // via the back/forward buttons, make sure that the content scripts are in // sync. case "PersistedPageShow": this.sendWorkerMessage(this.makeWorkerState(tabState), { tabId: info.tabId, frameId: "all_frames", }); break; case "OpenNewTabs": if (BROWSER === "firefox") { fireAndForget( openNewTabs(info.tabId, message.urls), "BackgroundProgram#onWorkerMessage->openNewTabs", message, info ); } break; } } // Instead of doing `setTimeout(doSomething, duration)`, call // `this.setTimeout(tabId, duration)` instead and add // `this.doSomething(tabId)` to `onTimeout` below. Every method called from // `onTimeout` is responsible for checking that everything is in the correct // state and that the correct amount of time has passed. No matter when or // from where or in which state `onTimeout` is called, it should always do the // correct thing. This means that we never have to clear any timeouts, which // is very tricky to keep track of. setTimeout(tabId: number, duration: number): void { setTimeout(() => { try { this.onTimeout(tabId); } catch (error) { log("error", "BackgroundProgram#onTimeout", error, tabId); } }, duration); } onTimeout(tabId: number): void { this.updateBadge(tabId); this.maybeStartHinting(tabId); this.updateElements(tabId); this.unhighlightHints(tabId); this.stopPreventOvertyping(tabId); } getTextRects({ enteredChars, allElementsWithHints, words, tabId, }: { enteredChars: string; allElementsWithHints: Array<ElementWithHint>; words: Array<string>; tabId: number; }): void { const indexesByFrame = new Map<number, Array<number>>(); for (const { text, hint, frame } of allElementsWithHints) { const previous = indexesByFrame.get(frame.id) ?? []; indexesByFrame.set(frame.id, previous); if (matchesText(text, words) && hint.startsWith(enteredChars)) { previous.push(frame.index); } } for (const [frameId, indexes] of indexesByFrame) { this.sendWorkerMessage( { type: "GetTextRects", indexes, words, }, { tabId, frameId } ); } } handleHintInput(tabId: number, timestamp: number, input: HintInput): void { const tabState = this.tabState.get(tabId); if (tabState === undefined) { return; } const { hintsState } = tabState; if (hintsState.type !== "Hinting") { return; } // Ignore unknown/non-text keys. if (input.type === "Input" && input.keypress.printableKey === undefined) { return; } const isHintKey = (input.type === "Input" && input.keypress.printableKey !== undefined && this.options.values.chars.includes(input.keypress.printableKey)) || (input.type === "Backspace" && hintsState.enteredChars !== ""); // Disallow filtering by text after having started entering hint chars. if ( !isHintKey && input.type !== "ActivateHint" && hintsState.enteredChars !== "" ) { return; } // Update entered chars (either text chars or hint chars). const updated = updateChars( isHintKey ? hintsState.enteredChars : hintsState.enteredText, input ); const enteredChars = isHintKey ? updated : hintsState.enteredChars; const enteredText = isHintKey ? hintsState.enteredText : updated .toLowerCase() // Trim leading whitespace and allow only one trailing space. .replace(/^\s+/, "") .replace(/\s+$/, " "); const { allElementsWithHints, match: actualMatch, updates, words, } = updateHints({ mode: hintsState.mode, enteredChars, enteredText, elementsWithHints: hintsState.elementsWithHints, highlighted: hintsState.highlighted, chars: this.options.values.chars, autoActivate: this.options.values.autoActivate, matchHighlighted: input.type === "ActivateHint", updateMeasurements: false, }); // Disallow matching hints (by text) by backspacing away chars. This can // happen if your entered text matches two links and then the link you // were after is removed. const [match, preventOverTyping] = input.type === "Backspace" || actualMatch === undefined ? [undefined, false] : [actualMatch.elementWithHint, actualMatch.autoActivated]; // If pressing a hint char that is currently unused, ignore it. if (enteredChars !== "" && updates.every((update) => update.hidden)) { return; } const now = Date.now(); const highlighted = match !== undefined ? allElementsWithHints .filter((element) => element.hint === match.hint) .map((element) => ({ sinceTimestamp: now, element })) : []; hintsState.enteredChars = enteredChars; hintsState.enteredText = enteredText; hintsState.elementsWithHints = allElementsWithHints; hintsState.highlighted = hintsState.highlighted.concat(highlighted); this.getTextRects({ enteredChars, allElementsWithHints, words, tabId, }); const shouldContinue = match === undefined ? true : this.handleHintMatch({ tabId, match, updates, preventOverTyping, alt: // By holding a modifier while typing the last character to // activate a hint forces opening links in new tabs. On Windows // and Linux, alt is used (since it is the only safe modifier). On // mac, ctrl is used since alt/option types special characters and // cmd is not safe. (input.type === "Input" && (this.options.mac ? input.keypress.ctrl : input.keypress.alt)) || (input.type === "ActivateHint" && input.alt), timestamp, }); // Some hint modes handle updating hintsState and sending messages // themselves. The rest share the same implementation below. if (!shouldContinue) { return; } this.sendRendererMessage( { type: "UpdateHints", updates, enteredText, }, { tabId } ); if (match !== undefined) { tabState.hintsState = { type: "Idle", highlighted: hintsState.highlighted, }; this.setTimeout(tabId, t.MATCH_HIGHLIGHT_DURATION.value); this.updateWorkerStateAfterHintActivation({ tabId, preventOverTyping, }); } this.updateBadge(tabId); } // Executes some action on the element of the matched hint. Returns whether // the "NonKeyboardShortcutKeypress" handler should continue with its default // implementation for updating hintsState and sending messages or not. Some // hint modes handle that themselves. handleHintMatch({ tabId, match, updates, preventOverTyping, alt, timestamp, }: { tabId: number; match: ElementWithHint; updates: Array<HintUpdate>; preventOverTyping: boolean; alt: boolean; timestamp: number; }): boolean { const tabState = this.tabState.get(tabId); if (tabState === undefined) { return true; } const { hintsState } = tabState; if (hintsState.type !== "Hinting") { return true; } const { url } = match; const mode: HintsMode = url !== undefined && alt && hintsState.mode !== "Select" ? "ForegroundTab" : hintsState.mode; switch (mode) { case "Click": this.sendWorkerMessage( { type: "ClickElement", index: match.frame.index, }, { tabId, frameId: match.frame.id, } ); return true; case "ManyClick": { if (match.isTextInput) { this.sendWorkerMessage( { type: "ClickElement", index: match.frame.index, }, { tabId, frameId: match.frame.id, } ); return true; } this.sendWorkerMessage( { type: "ClickElement", index: match.frame.index, }, { tabId, frameId: match.frame.id, } ); // Highlight the matched hints immediately, but hide others when the // highlight duration is over. Likely, the same hints will appear again // when the “next” hints mode is started. This reduces flicker. this.sendRendererMessage( { type: "UpdateHints", updates: updates.filter((update) => update.type !== "Hide"), enteredText: hintsState.enteredText, }, { tabId } ); // In case the “next” hints mode takes longer than the highlight // duration, remove the shruggie. It might flicker by otherwise, and we // don’t need it, just like we don’t show it when entering hints mode // initially. this.sendRendererMessage({ type: "RemoveShruggie" }, { tabId }); this.updateWorkerStateAfterHintActivation({ tabId, preventOverTyping, }); this.enterHintsMode({ tabId, timestamp, mode: hintsState.mode, }); this.setTimeout(tabId, t.MATCH_HIGHLIGHT_DURATION.value); return false; } case "ManyTab": { if (url === undefined) { log( "error", "Cannot open background tab (many) due to missing URL", match ); return true; } const matchedIndexes = new Set( hintsState.elementsWithHints .filter((element) => element.hint === match.hint) .map((element) => element.index) ); const highlightedKeys = new Set( hintsState.highlighted.map(({ element }) => elementKey(element)) ); hintsState.enteredChars = ""; hintsState.enteredText = ""; this.openNewTab({ url, elementIndex: match.frame.index, tabId, frameId: match.frame.id, foreground: false, }); this.sendRendererMessage( { type: "UpdateHints", updates: assignHints(hintsState.elementsWithHints, { mode: "ManyTab", chars: this.options.values.chars, hasEnteredText: false, }).map((element, index) => ({ type: "UpdateContent", index: element.index, order: index, matchedChars: "", restChars: element.hint, highlighted: matchedIndexes.has(element.index) || highlightedKeys.has(elementKey(element)), hidden: element.hidden, })), enteredText: "", }, { tabId } ); this.updateWorkerStateAfterHintActivation({ tabId, preventOverTyping, }); this.updateBadge(tabId); this.setTimeout(tabId, t.MATCH_HIGHLIGHT_DURATION.value); return false; } case "BackgroundTab": if (url === undefined) { log("error", "Cannot open background tab due to missing URL", match); return true; } this.openNewTab({ url, elementIndex: match.frame.index, tabId, frameId: match.frame.id, foreground: false, }); return true; case "ForegroundTab": if (url === undefined) { log("error", "Cannot open foreground tab due to missing URL", match); return true; } this.openNewTab({ url, elementIndex: match.frame.index, tabId, frameId: match.frame.id, foreground: true, }); return true; case "Select": this.sendWorkerMessage( alt ? { type: "CopyElement", index: match.frame.index, } : { type: "SelectElement", index: match.frame.index, }, { tabId, frameId: match.frame.id, } ); return true; } } refreshHintsRendering(tabId: number): void { const tabState = this.tabState.get(tabId); if (tabState === undefined) { return; } const { hintsState } = tabState; if (hintsState.type !== "Hinting") { return; } const { enteredChars, enteredText } = hintsState; const { allElementsWithHints, updates, words } = updateHints({ mode: hintsState.mode, enteredChars, enteredText, elementsWithHints: hintsState.elementsWithHints, highlighted: hintsState.highlighted, chars: this.options.values.chars, autoActivate: this.options.values.autoActivate, matchHighlighted: false, updateMeasurements: false, }); this.getTextRects({ enteredChars, allElementsWithHints, words, tabId }); this.sendRendererMessage( { type: "UpdateHints", updates, enteredText, }, { tabId } ); this.updateBadge(tabId); } openNewTab({ url, elementIndex, tabId, frameId, foreground, }: { url: string; elementIndex: number; tabId: number; frameId: number; foreground: boolean; }): void { this.sendWorkerMessage( { type: "FocusElement", index: elementIndex, }, { tabId, frameId } ); // In Firefox, creating a tab with `openerTabId` works just like // right-clicking a link and choosing "Open Link in New Tab" (basically, // it's opened to the right of the current tab). In Chrome, created tabs are // always opened at the end of the tab strip. However, dispatching a // ctrl-click on an `<a>` element opens a tab just like ctrl-clicking it for // real. I considered keeping track of where to open tabs manually for // Chrome, but the logic for where to open tabs turned out to be too // complicated to replicate in a good way, and there does not seem to be a // downside of using the fake ctrl-click method in Chrome. In fact, there’s // even an upside to the ctrl-click method: The HTTP Referer header is sent, // just as if you had clicked the link for real. See: <bugzil.la/1615860>. if (BROWSER === "chrome") { this.sendWorkerMessage( { type: "OpenNewTab", url, foreground, }, { tabId, frameId: TOP_FRAME_ID } ); } else { fireAndForget( browser.tabs .create({ active: foreground, url, openerTabId: tabId, }) .then(() => undefined), "BackgroundProgram#openNewTab", url ); } } maybeStartHinting(tabId: number): void { const tabState = this.tabState.get(tabId); if (tabState === undefined) { return; } const { hintsState } = tabState; if (hintsState.type !== "Collecting") { return; } const { pendingFrames } = hintsState.pendingElements; const frameWaitDuration = Date.now() - pendingFrames.lastStartWaitTimestamp; if ( pendingFrames.collecting > 0 || (pendingFrames.answering > 0 && frameWaitDuration < t.FRAME_REPORT_TIMEOUT.value) ) { return; } const { time } = hintsState; time.start("assign hints"); const elementsWithHints: Array<ElementWithHint> = assignHints( hintsState.pendingElements.elements.map((element, index) => ({ ...element, // These are filled in by `assignHints` but need to be set here for type // checking reasons. weight: 0, hint: "", // This is set for real in the next couple of lines, but set here also // to be extra sure that the sorting really is stable. index, })), { mode: hintsState.mode, chars: this.options.values.chars, hasEnteredText: false, } // `.index` was set to `-1` in "ReportVisibleElements" (and to a temporary // index above). Now set it for real to map these elements to DOM elements // in RendererProgram. ).map((element, index) => ({ ...element, index })); const elementKeys = new Set( elementsWithHints.map((element) => elementKey(element)) ); const highlightedKeys = new Set( hintsState.highlighted.map(({ element }) => elementKey(element)) ); const [alreadyHighlighted, extraHighlighted] = partition( hintsState.highlighted, ({ element }) => elementKeys.has(elementKey(element)) ); const updateIndex = ( { element, sinceTimestamp }: HighlightedItem, index: number ): HighlightedItem => ({ element: { ...element, index }, sinceTimestamp, }); const numElements = elementsWithHints.length; const highlighted = extraHighlighted // Add indexes to the highlighted hints that get extra DOM nodes. .map((item, index) => updateIndex(item, numElements + index)) // Other highlighted hints don’t get extra DOM nodes – they instead // highlight new hints with the same characters and position. Mark them // with an index of -1 for `unhighlightHints`’s sakes. .concat(alreadyHighlighted.map((item) => updateIndex(item, -1))); const elementRenders: Array<ElementRender> = elementsWithHints .map((element, index) => ({ hintMeasurements: element.hintMeasurements, hint: element.hint, // Hints at the same position and with the same hint characters as a // previously matched hint are marked as highlighted. highlighted: highlightedKeys.has(elementKey(element)), invertedZIndex: index + 1, })) // Other previously matched hints are rendered (but not stored in // `hintsState.elementsWithHints`). .concat( extraHighlighted.map(({ element }) => ({ hintMeasurements: element.hintMeasurements, hint: element.hint, highlighted: true, // Previously matched hints are always shown on top over regular hints. invertedZIndex: 0, })) ); tabState.hintsState = { type: "Hinting", mode: hintsState.mode, startTime: hintsState.startTime, time, stats: hintsState.stats, enteredChars: "", enteredText: "", elementsWithHints, highlighted, updateState: { type: "WaitingForTimeout", lastUpdateStartTimestamp: hintsState.startTime, }, peeking: false, }; this.sendWorkerMessage(this.makeWorkerState(tabState), { tabId, frameId: "all_frames", }); this.setTimeout(tabId, t.UPDATE_INTERVAL.value); time.start("render"); this.sendRendererMessage( { type: "Render", elements: elementRenders, mixedCase: isMixedCase(this.options.values.chars), }, { tabId } ); this.updateBadge(tabId); } updateElements(tabId: number): void { const tabState = this.tabState.get(tabId); if (tabState === undefined) { return; } const { hintsState } = tabState; if (hintsState.type !== "Hinting") { return; } const { updateState } = hintsState; if (updateState.type !== "WaitingForTimeout") { return; } if ( Date.now() - updateState.lastUpdateStartTimestamp >= t.UPDATE_INTERVAL.value ) { if (hintsState.elementsWithHints.every((element) => element.hidden)) { this.enterHintsMode({ tabId, timestamp: Date.now(), mode: hintsState.mode, }); } else { hintsState.updateState = { type: "WaitingForResponse", lastUpdateStartTimestamp: Date.now(), }; // Refresh `oneTimeWindowMessageToken`. this.sendWorkerMessage(this.makeWorkerState(tabState), { tabId, frameId: "all_frames", }); this.sendWorkerMessage( { type: "UpdateElements" }, { tabId, frameId: TOP_FRAME_ID, } ); } } } hideElements(info: MessageInfo): void { const tabState = this.tabState.get(info.tabId); if (tabState === undefined) { return; } const { hintsState } = tabState; if (hintsState.type !== "Hinting") { return; } if (info.frameId === TOP_FRAME_ID) { log( "log", "BackgroundProgram#hideElements", "Skipping because this should not happen for the top frame.", info ); return; } log("log", "BackgroundProgram#hideElements", info); for (const element of hintsState.elementsWithHints) { if (element.frame.id === info.frameId) { element.hidden = true; } } const { enteredChars, enteredText } = hintsState; const { allElementsWithHints, updates } = updateHints({ mode: hintsState.mode, enteredChars, enteredText, elementsWithHints: hintsState.elementsWithHints, highlighted: hintsState.highlighted, chars: this.options.values.chars, autoActivate: this.options.values.autoActivate, matchHighlighted: false, updateMeasurements: false, }); hintsState.elementsWithHints = allElementsWithHints; this.sendRendererMessage( { type: "RenderTextRects", rects: [], frameId: info.frameId, }, { tabId: info.tabId } ); this.sendRendererMessage( { type: "UpdateHints", updates, enteredText, }, { tabId: info.tabId } ); this.updateBadge(info.tabId); } onRendererMessage( message: FromRenderer, info: MessageInfo, tabState: TabState ): void { log("log", "BackgroundProgram#onRendererMessage", message, info); switch (message.type) { case "RendererScriptAdded": this.sendRendererMessage( { type: "StateSync", css: this.options.values.css, logLevel: log.level, }, { tabId: info.tabId } ); // Both uBlock Origin and Adblock Plus use `browser.tabs.insertCSS` with // `{ display: none !important; }` and `cssOrigin: "user"` to hide // elements. I’ve seen LinkHint’s container to be hidden by a // `[style*="animation:"]` filter. This makes sure that the container // cannot be hidden by adblockers. // In Chrome, 255 ids have the same specificity as >=256 (for Firefox, // it’s 1023). One can increase the specificity even more by adding // classes, but I don’t think it’s worth the trouble. fireAndForget( browser.tabs.insertCSS(info.tabId, { code: `${`#${CONTAINER_ID}`.repeat( 255 )} { display: block !important; }`, cssOrigin: "user", runAt: "document_start", }), "BackgroundProgram#onRendererMessage", "Failed to insert adblock workaround CSS", message, info ); break; case "Rendered": { const { hintsState } = tabState; if (hintsState.type !== "Hinting") { return; } const { startTime, time, stats: collectStats } = hintsState; time.stop(); const { durations, firstPaintTimestamp, lastPaintTimestamp } = message; const timeToFirstPaint = firstPaintTimestamp - startTime; const timeToLastPaint = lastPaintTimestamp - startTime; tabState.perf = [ { timeToFirstPaint, timeToLastPaint, topDurations: time.export(), collectStats, renderDurations: durations, }, ...tabState.perf, ].slice(0, MAX_PERF_ENTRIES); this.sendOptionsMessage({ type: "PerfUpdate", perf: { [info.tabId]: tabState.perf }, }); break; } } } async onPopupMessage(message: FromPopup): Promise<void> { log("log", "BackgroundProgram#log", message); switch (message.type) { case "PopupScriptAdded": { const tab = await getCurrentTab(); const tabState = tab.id === undefined ? undefined : this.tabState.get(tab.id); this.sendPopupMessage({ type: "Init", logLevel: log.level, isEnabled: tabState !== undefined, }); break; } } } async onOptionsMessage( message: FromOptions, info: MessageInfo, tabState: TabState ): Promise<void> { log("log", "BackgroundProgram#onOptionsMessage", message, info); switch (message.type) { case "OptionsScriptAdded": { tabState.isOptionsPage = true; this.updateOptionsPageData(); this.sendOptionsMessage({ type: "StateSync", logLevel: log.level, options: this.options, }); const perf = Object.fromEntries( Array.from(this.tabState, ([tabId, tabState2]) => [ tabId.toString(), tabState2.perf, ]) ); this.sendOptionsMessage({ type: "PerfUpdate", perf }); break; } case "SaveOptions": await this.saveOptions(message.partialOptions); this.updateTabsAfterOptionsChange(); break; case "ResetOptions": await this.resetOptions(); this.updateTabsAfterOptionsChange(); break; case "ResetPerf": for (const tabState2 of this.tabState.values()) { tabState2.perf = []; } if (!PROD) { await browser.storage.local.remove("perf"); } break; case "ToggleKeyboardCapture": tabState.keyboardMode = message.capture ? { type: "Capture" } : { type: "FromHintsState" }; this.sendWorkerMessage(this.makeWorkerState(tabState), { tabId: info.tabId, frameId: "all_frames", }); break; } } onKeyboardShortcut( action: KeyboardAction, info: MessageInfo, timestamp: number ): void { const enterHintsMode = (mode: HintsMode): void => { this.enterHintsMode({ tabId: info.tabId, timestamp, mode, }); }; switch (action) { case "EnterHintsMode_Click": enterHintsMode("Click"); break; case "EnterHintsMode_BackgroundTab": enterHintsMode("BackgroundTab"); break; case "EnterHintsMode_ForegroundTab": enterHintsMode("ForegroundTab"); break; case "EnterHintsMode_ManyClick": enterHintsMode("ManyClick"); break; case "EnterHintsMode_ManyTab": enterHintsMode("ManyTab"); break; case "EnterHintsMode_Select": enterHintsMode("Select"); break; case "ExitHintsMode": this.exitHintsMode({ tabId: info.tabId }); break; case "RotateHintsForward": this.sendRendererMessage( { type: "RotateHints", forward: true, }, { tabId: info.tabId } ); break; case "RotateHintsBackward": this.sendRendererMessage( { type: "RotateHints", forward: false, }, { tabId: info.tabId } ); break; case "RefreshHints": { const tabState = this.tabState.get(info.tabId); if (tabState === undefined) { return; } const { hintsState } = tabState; if (hintsState.type !== "Hinting") { return; } // Refresh `oneTimeWindowMessageToken`. this.sendWorkerMessage(this.makeWorkerState(tabState), { tabId: info.tabId, frameId: "all_frames", }); enterHintsMode(hintsState.mode); break; } case "TogglePeek": { const tabState = this.tabState.get(info.tabId); if (tabState === undefined) { return; } const { hintsState } = tabState; if (hintsState.type !== "Hinting") { return; } this.sendRendererMessage( hintsState.peeking ? { type: "Unpeek" } : { type: "Peek" }, { tabId: info.tabId } ); hintsState.peeking = !hintsState.peeking; break; } case "Escape": this.exitHintsMode({ tabId: info.tabId }); this.sendWorkerMessage( { type: "Escape" }, { tabId: info.tabId, frameId: "all_frames" } ); break; case "ActivateHint": this.handleHintInput(info.tabId, timestamp, { type: "ActivateHint", alt: false, }); break; case "ActivateHintAlt": this.handleHintInput(info.tabId, timestamp, { type: "ActivateHint", alt: true, }); break; case "Backspace": this.handleHintInput(info.tabId, timestamp, { type: "Backspace" }); break; case "ReverseSelection": this.sendWorkerMessage( { type: "ReverseSelection" }, { tabId: info.tabId, frameId: "all_frames" } ); break; } } enterHintsMode({ tabId, timestamp, mode, }: { tabId: number; timestamp: number; mode: HintsMode; }): void { const tabState = this.tabState.get(tabId); if (tabState === undefined) { return; } const time = new TimeTracker(); time.start("collect"); this.sendWorkerMessage( { type: "StartFindElements", types: getElementTypes(mode), }, { tabId, frameId: TOP_FRAME_ID, } ); const refreshing = tabState.hintsState.type !== "Idle"; tabState.hintsState = { type: "Collecting", mode, pendingElements: { pendingFrames: { answering: 0, collecting: 1, // The top frame is collecting. lastStartWaitTimestamp: Date.now(), }, elements: [], }, startTime: timestamp, time, stats: [], refreshing, highlighted: tabState.hintsState.highlighted, }; this.updateBadge(tabId); this.setTimeout(tabId, t.BADGE_COLLECTING_DELAY.value); } exitHintsMode({ tabId, delayed = false, sendMessages = true, }: { tabId: number; delayed?: boolean; sendMessages?: boolean; }): void { const tabState = this.tabState.get(tabId); if (tabState === undefined) { return; } if (sendMessages) { if (delayed) { this.setTimeout(tabId, t.MATCH_HIGHLIGHT_DURATION.value); } else { this.sendRendererMessage({ type: "Unrender" }, { tabId }); } } tabState.hintsState = { type: "Idle", highlighted: tabState.hintsState.highlighted, }; if (sendMessages) { this.sendWorkerMessage(this.makeWorkerState(tabState), { tabId, frameId: "all_frames", }); } this.updateBadge(tabId); } unhighlightHints(tabId: number): void { const tabState = this.tabState.get(tabId); if (tabState === undefined) { return; } const { hintsState } = tabState; if (hintsState.highlighted.length === 0) { return; } const now = Date.now(); const [doneWaiting, stillWaiting] = partition( hintsState.highlighted, ({ sinceTimestamp }) => now - sinceTimestamp >= t.MATCH_HIGHLIGHT_DURATION.value ); const hideDoneWaiting = ({ refresh = false, }: { refresh?: boolean } = {}): void => { if (doneWaiting.length > 0) { this.sendRendererMessage( { type: "UpdateHints", updates: doneWaiting // Highlighted elements with -1 as index don’t have their own DOM // nodes – instead, they have highlighted a new hint with the same // characters and position. They unhighlighted using // `this.refreshHintsRendering` below. .filter(({ element }) => element.index !== -1) .map(({ element }) => ({ type: "Hide", index: element.index, hidden: true, })), enteredText: "", }, { tabId } ); if (refresh) { this.refreshHintsRendering(tabId); } } }; hintsState.highlighted = stillWaiting; switch (hintsState.type) { case "Idle": case "Collecting": if (stillWaiting.length === 0) { this.sendRendererMessage({ type: "Unrender" }, { tabId }); } else { hideDoneWaiting(); } break; case "Hinting": { hideDoneWaiting({ refresh: true }); break; } } } stopPreventOvertyping(tabId: number): void { const tabState = this.tabState.get(tabId); if (tabState === undefined) { return; } const { keyboardMode } = tabState; if ( keyboardMode.type === "PreventOverTyping" && Date.now() - keyboardMode.sinceTimestamp >= this.options.values.overTypingDuration ) { tabState.keyboardMode = { type: "FromHintsState" }; this.sendWorkerMessage(this.makeWorkerState(tabState), { tabId, frameId: "all_frames", }); } } onTabCreated(tab: browser.tabs.Tab): void { if (tab.id !== undefined) { fireAndForget( this.updateIcon(tab.id), "BackgroundProgram#onTabCreated->updateIcon", tab ); } } onTabActivated(): void { this.updateOptionsPageData(); } onTabUpdated( tabId: number, changeInfo: browser.tabs._OnUpdatedChangeInfo ): void { if (changeInfo.status !== undefined) { fireAndForget( this.updateIcon(tabId), "BackgroundProgram#onTabUpdated->updateIcon", tabId ); } const tabState = this.tabState.get(tabId); if (tabState !== undefined && changeInfo.status === "loading") { tabState.isOptionsPage = false; this.updateOptionsPageData(); } if (tabState !== undefined && changeInfo.pinned !== undefined) { tabState.isPinned = changeInfo.pinned; this.sendWorkerMessage(this.makeWorkerState(tabState), { tabId, frameId: "all_frames", }); } } onTabRemoved(tabId: number): void { this.deleteTabState(tabId); } deleteTabState(tabId: number): void { const tabState = this.tabState.get(tabId); if (tabState === undefined) { return; } this.tabState.delete(tabId); if (!tabState.isOptionsPage) { this.sendOptionsMessage({ type: "PerfUpdate", perf: { [tabId]: [] }, }); } this.updateOptionsPageData(); } async updateIcon(tabId: number): Promise<void> { // In Chrome the below check fails for the extension options page, so check // for the options page explicitly. const tabState = this.tabState.get(tabId); let enabled = tabState !== undefined ? tabState.isOptionsPage : false; // Check if we’re allowed to execute content scripts on this page. if (!enabled) { try { await browser.tabs.executeScript(tabId, { code: "", runAt: "document_start", }); enabled = true; } catch { enabled = false; } } const type: IconType = enabled ? "normal" : "disabled"; const icons = getIcons(type); log("log", "BackgroundProgram#updateIcon", tabId, type); await browser.browserAction.setIcon({ path: icons, tabId }); } updateBadge(tabId: number): void { const tabState = this.tabState.get(tabId); if (tabState === undefined) { return; } const { hintsState } = tabState; fireAndForget( browser.browserAction.setBadgeText({ text: getBadgeText(hintsState), tabId, }), "BackgroundProgram#updateBadge->setBadgeText" ); } async updateOptions({ isInitial = false, }: { isInitial?: boolean } = {}): Promise<void> { if (!PROD) { if (isInitial) { const defaultStorageSync = DEFAULT_STORAGE_SYNC; if ( typeof defaultStorageSync === "object" && defaultStorageSync !== null ) { await browser.storage.sync.clear(); await browser.storage.sync.set(defaultStorageSync); } } } const info = await browser.runtime.getPlatformInfo(); const mac = info.os === "mac"; const defaults = getDefaults({ mac }); const rawOptions = await getRawOptions(); const defaulted = { ...flattenOptions(defaults), ...rawOptions }; const [unflattened, map] = unflattenOptions(defaulted); const decodeErrors: Array<string> = []; const options = decode( makeOptionsDecoder(defaults), unflattened, decodeErrors, map ); log("log", "BackgroundProgram#updateOptions", { defaults, rawOptions, defaulted, unflattened, options, decodeErrors, }); this.options = { values: options, defaults, raw: rawOptions, errors: decodeErrors, mac, }; log.level = options.logLevel; } async saveOptions(partialOptions: PartialOptions): Promise<void> { // The options are stored flattened to increase the chance of the browser // sync not overwriting things when options has changed from multiple // places. This means we have to retrieve the whole storage, unflatten it, // merge in the `partialOptions`, flatten that and finally store it. Just // flattening `partialOptions` and storing that would mean that you couldn't // remove any `options.keys`, for example. try { const rawOptions = await getRawOptions(); const { keysToRemove, optionsToSet } = diffOptions( flattenOptions(this.options.defaults), flattenOptions({ ...this.options.values, ...partialOptions }), rawOptions ); log("log", "BackgroundProgram#saveOptions", { partialOptions, keysToRemove, optionsToSet, }); await browser.storage.sync.remove(keysToRemove); await browser.storage.sync.set(optionsToSet); await this.updateOptions(); } catch (errorAny) { const error = errorAny as Error; this.options.errors = [error.message]; } } async resetOptions(): Promise<void> { try { await browser.storage.sync.clear(); await this.updateOptions(); } catch (errorAny) { const error = errorAny as Error; this.options.errors = [error.message]; } } updateTabsAfterOptionsChange(): void { this.sendOptionsMessage({ type: "StateSync", logLevel: log.level, options: this.options, }); for (const tabId of this.tabState.keys()) { // This also does a "StateSync" for all workers. this.exitHintsMode({ tabId }); this.sendRendererMessage( { type: "StateSync", css: this.options.values.css, logLevel: log.level, }, { tabId } ); } } makeWorkerState( tabState: TabState, { refreshToken = true }: { refreshToken?: boolean } = {} ): ToWorker { const { hintsState } = tabState; if (refreshToken) { this.oneTimeWindowMessageToken = makeRandomToken(); } const common = { logLevel: log.level, keyTranslations: this.options.values.useKeyTranslations ? this.options.values.keyTranslations : {}, oneTimeWindowMessageToken: this.oneTimeWindowMessageToken, mac: this.options.mac, isPinned: tabState.isPinned, }; const getKeyboardShortcuts = ( shortcuts: Array<KeyboardMapping> ): Array<KeyboardMapping> => tabState.keyboardMode.type === "PreventOverTyping" ? shortcuts.filter((shortcut) => PREVENT_OVERTYPING_ALLOWED_KEYBOARD_ACTIONS.has(shortcut.action) ) : shortcuts; const getKeyboardMode = (mode: KeyboardModeWorker): KeyboardModeWorker => tabState.keyboardMode.type === "FromHintsState" ? mode : tabState.keyboardMode.type; return hintsState.type === "Hinting" ? { type: "StateSync", clearElements: false, keyboardShortcuts: getKeyboardShortcuts( this.options.values.hintsKeyboardShortcuts ), keyboardMode: getKeyboardMode("Hints"), ...common, } : { type: "StateSync", clearElements: hintsState.type === "Idle", keyboardShortcuts: getKeyboardShortcuts( this.options.values.normalKeyboardShortcuts ), keyboardMode: getKeyboardMode("Normal"), ...common, }; } // Send a "StateSync" message to WorkerProgram. If a hint was auto-activated // by text filtering, prevent “over-typing” (continued typing after the hint // got matched, before realizing it got matched) by temporarily removing all // keyboard shortcuts and suppressing all key presses for a short time. updateWorkerStateAfterHintActivation({ tabId, preventOverTyping, }: { tabId: number; preventOverTyping: boolean; }): void { const tabState = this.tabState.get(tabId); if (tabState === undefined) { return; } if (preventOverTyping) { tabState.keyboardMode = { type: "PreventOverTyping", sinceTimestamp: Date.now(), }; this.setTimeout(tabId, this.options.values.overTypingDuration); } this.sendWorkerMessage(this.makeWorkerState(tabState), { tabId, frameId: "all_frames", }); } updateOptionsPageData(): void { if (!PROD) { const run = async (): Promise<void> => { const optionsTabState = Array.from(this.tabState).filter( ([, tabState]) => tabState.isOptionsPage ); let isActive = false; for (const [tabId] of optionsTabState) { try { const tab = await browser.tabs.get(tabId); if (tab.active) { isActive = true; break; } } catch { // Tab was not found. Try the next one. } } if (optionsTabState.length > 0) { await browser.storage.local.set({ optionsPage: isActive }); } else { await browser.storage.local.remove("optionsPage"); } }; fireAndForget(run(), "BackgroundProgram#updateOptionsPageData"); } } async maybeOpenTutorial(): Promise<void> { const { tutorialShown } = await browser.storage.local.get("tutorialShown"); if (tutorialShown !== true) { await browser.tabs.create({ active: true, url: META_TUTORIAL, }); await browser.storage.local.set({ tutorialShown: true }); } } async maybeReopenOptions(): Promise<void> { if (!PROD) { const { optionsPage } = await browser.storage.local.get("optionsPage"); if (typeof optionsPage === "boolean") { const isActive = optionsPage; const activeTab = await getCurrentTab(); await browser.runtime.openOptionsPage(); if (!isActive && activeTab.id !== undefined) { await browser.tabs.update(activeTab.id, { active: true }); } } } } async restoreTabsPerf(): Promise<void> { if (!PROD) { try { const { perf } = await browser.storage.local.get("perf"); if (perf !== undefined) { this.restoredTabsPerf = decode(TabsPerf, perf); log( "log", "BackgroundProgram#restoreTabsPerf", this.restoredTabsPerf ); } } catch (error) { log( "error", "BackgroundProgram#restoreTabsPerf", "Failed to restore.", error ); } } } } function makeEmptyTabState(tabId: number | undefined): TabState { const tabState: TabState = { hintsState: { type: "Idle", highlighted: [], }, keyboardMode: { type: "FromHintsState" }, perf: [], isOptionsPage: false, isPinned: false, }; if (tabId !== undefined) { // This is a really ugly hack. `makeEmptyTabState` is used within // `BackgroundProgram#onMessage`. As mentioned over there, that method must // _not_ be async. So instead of waiting for `browser.tabs.get` (returning a // Promise), we just mutate the tab state as soon as possible. This means // that code trying to access `tabState.isPinned` right after // `makeEmptyTabState` might get the wrong value. At the time of this // writing, no code does that so the hack holds. browser.tabs.get(tabId).then( (tab) => { tabState.isPinned = tab.pinned; }, (error) => { log("error", "makeEmptyTabState", `Failed to get tab ${tabId}.`, error); } ); } return tabState; } const CLICK_TYPES: ElementTypes = [ "clickable", "clickable-event", "label", "link", "scrollable", "textarea", ]; const TAB_TYPES: ElementTypes = ["link"]; function getElementTypes(mode: HintsMode): ElementTypes { switch (mode) { case "Click": return CLICK_TYPES; case "BackgroundTab": return TAB_TYPES; case "ForegroundTab": return TAB_TYPES; case "ManyClick": return CLICK_TYPES; case "ManyTab": return TAB_TYPES; case "Select": return "selectable"; } } function getCombiningUrl( mode: HintsMode, element: ElementWithHint ): string | undefined { switch (mode) { case "Click": return shouldCombineHintsForClick(element) ? element.urlWithTarget : undefined; case "BackgroundTab": return element.url; case "ForegroundTab": return element.url; case "ManyClick": return shouldCombineHintsForClick(element) ? element.urlWithTarget : undefined; case "ManyTab": return element.url; case "Select": return undefined; } } function shouldCombineHintsForClick(element: ElementWithHint): boolean { const { url, hasClickListener } = element; // The diff expander buttons on GitHub are links to the same fragment // identifier. So are Bootstrap carousel next/previous “buttons”. So it’s not // safe to combine links with fragment identifiers at all. (They may be // powered by delegated event listeners.) I guess they aren’t as common // anyway. Also don’t combine if the elements themselves have click listeners. // Some sites use `<a>` as buttons with click listeners but still include an // href for some reason. return url !== undefined && !url.includes("#") && !hasClickListener; } async function runContentScripts( tabs: Array<browser.tabs.Tab> ): Promise<Array<Array<unknown>>> { const manifest = browser.runtime.getManifest(); const detailsList = manifest.content_scripts === undefined ? [] : manifest.content_scripts .filter((script) => script.matches.includes("<all_urls>")) .flatMap((script) => script.js === undefined ? [] : script.js.map((file) => ({ file, allFrames: script.all_frames, matchAboutBlank: script.match_about_blank, runAt: script.run_at, })) ); return Promise.all( tabs.flatMap((tab) => detailsList.map(async (details) => { if (tab.id === undefined) { return []; } try { return (await browser.tabs.executeScript( tab.id, details )) as Array<unknown>; } catch { // If `executeScript` fails it means that the extension is not // allowed to run content scripts in the tab. Example: most // `chrome://*` pages. We don’t need to do anything in that case. return []; } }) ) ); } function firefoxWorkaround(tabs: Array<browser.tabs.Tab>): void { for (const tab of tabs) { if (tab.id !== undefined) { const message: FromBackground = { type: "FirefoxWorkaround" }; browser.tabs.sendMessage(tab.id, message).catch(() => { // If `sendMessage` fails it means that there’s no content script // listening in that tab. Example: `about:` pages (where extensions // are not allowed to run content scripts). We don’t need to do // anything in that case. }); } } } async function getCurrentTab(): Promise<browser.tabs.Tab> { const tabs = await browser.tabs.query({ active: true, windowId: browser.windows.WINDOW_ID_CURRENT, }); if (tabs.length !== 1) { throw new Error( `getCurrentTab: Got an unexpected amount of tabs: ${tabs.length}` ); } return tabs[0]; } // Open a bunch of tabs, and then focus the first of them. async function openNewTabs(tabId: number, urls: Array<string>): Promise<void> { const newTabs = await Promise.all( urls.map((url) => browser.tabs.create({ active: urls.length === 1, url, openerTabId: tabId, }) ) ); if (newTabs.length >= 2 && newTabs[0].id !== undefined) { await browser.tabs.update(newTabs[0].id, { active: true }); } } type IconType = "disabled" | "normal"; function getIcons(type: IconType): Record<string, string> { const manifest = browser.runtime.getManifest(); return Object.fromEntries( Object.entries(manifest.browser_action?.default_icon ?? {}).flatMap( ([key, value]) => { if (typeof value === "string") { const newValue = value.replace(/(\$)\w+/, `$1${type}`); // Default icons are always PNG in development to support Chrome. Switch // to SVG in Firefox during development to make it easier to work on the // SVG icon source (automatic reloading). This also requires a // cache-bust. const finalValue = !PROD && BROWSER === "firefox" ? `${newValue.replace(/png/g, "svg")}?${iconsChecksum}` : newValue; return [[key, finalValue]]; } return []; } ) ); } // Left to right, top to bottom. function comparePositions(a: HintMeasurements, b: HintMeasurements): number { // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions return a.x - b.x || a.y - b.y; } function getBadgeText(hintsState: HintsState): string { switch (hintsState.type) { case "Idle": return ""; case "Collecting": // Only show the badge “spinner” if the hints are slow. But show it // immediately when refreshing so that one can see it flash in case you // get exactly the same hints after refreshing, so that you understand // that something happened. It’s also nice to show in "ManyClick" mode. return Date.now() - hintsState.startTime > t.BADGE_COLLECTING_DELAY.value || hintsState.refreshing ? "…" : ""; case "Hinting": { const { enteredChars, enteredText } = hintsState; const words = splitEnteredText(enteredText); return hintsState.elementsWithHints .filter( (element) => // "Hidden" elements have been removed from the DOM or moved off-screen. !element.hidden && matchesText(element.text, words) && element.hint.startsWith(enteredChars) ) .length.toString(); } } } class Combined { children: Array<ElementWithHint>; weight: number; constructor(children: Array<ElementWithHint>) { this.children = children; this.weight = Math.max(...children.map((child) => child.weight)); } } function combineByHref( elements: Array<ElementWithHint>, mode: HintsMode ): Array<Combined | ElementWithHint> { const map = new Map<string, Array<ElementWithHint>>(); const rest: Array<ElementWithHint> = []; for (const element of elements) { const url = getCombiningUrl(mode, element); if (url !== undefined) { const previous = map.get(url); if (previous !== undefined) { previous.push(element); } else { map.set(url, [element]); } } else { rest.push(element); } } return Array.from(map.values()) .map((children): Combined | ElementWithHint => new Combined(children)) .concat(rest); } function assignHints( passedElements: Array<ElementWithHint>, { mode, chars, hasEnteredText, }: { mode: HintsMode; chars: string; hasEnteredText: boolean } ): Array<ElementWithHint> { const largestTextWeight = hasEnteredText ? Math.max(1, ...passedElements.map((element) => element.textWeight)) : 0; // Sort the elements so elements with more weight get higher z-index. const elements: Array<ElementWithHint> = passedElements .map((element) => ({ ...element, // When filtering by text, give better hints to elements with shorter // text. The more of the text that is matched, the more likely to be what // the user is looking for. weight: hasEnteredText ? largestTextWeight - element.textWeight + 1 : element.hintMeasurements.weight, // This is set to the real thing below. hint: "", })) .sort( (a, b) => // Higher weights first. // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions b.weight - a.weight || // If the weights are the same, sort by on-screen position, left to // right and then top to bottom (reading order in LTR languages). If you // scroll _down_ to a list of same-weight links they usually end up in // the order naturally, but if you scroll _up_ to the same list the // IntersectionObserver fires in a different order, so it’s important // not to rely on that to get consistent hints. comparePositions(a.hintMeasurements, b.hintMeasurements) || // `hintsState.elementsWithHints` changes order as // `hintsState.enteredText` come and go. Sort on `.index` if all other // things are equal, so that elements don’t unexpectedly swap hints after // erasing some text chars. a.index - b.index ); const combined = combineByHref(elements, mode); const tree = huffman.createTree(combined, chars.length, { // Even though we sorted `elements` above, `combined` might not be sorted. sorted: false, }); tree.assignCodeWords(chars, (item, codeWord) => { if (item instanceof Combined) { for (const child of item.children) { child.hint = codeWord; } } else { item.hint = codeWord; } }); return elements; } function makeMessageInfo( sender: browser.runtime.MessageSender ): MessageInfo | undefined { return sender.tab?.id !== undefined && sender.frameId !== undefined ? { tabId: sender.tab.id, frameId: sender.frameId, url: sender.url } : undefined; } function updateChars(chars: string, input: HintInput): string { switch (input.type) { case "Input": { const key = input.keypress.printableKey; return key !== undefined ? `${chars}${key}` : chars; } case "ActivateHint": return chars; case "Backspace": return chars.slice(0, -1); } } function updateHints({ mode, enteredChars, enteredText, elementsWithHints: passedElementsWithHints, highlighted, chars, autoActivate: autoActivateOption, matchHighlighted, updateMeasurements, }: { mode: HintsMode; enteredChars: string; enteredText: string; elementsWithHints: Array<ElementWithHint>; highlighted: Highlighted; chars: string; autoActivate: boolean; matchHighlighted: boolean; updateMeasurements: boolean; }): { elementsWithHints: Array<ElementWithHint>; allElementsWithHints: Array<ElementWithHint>; match: | { elementWithHint: ElementWithHint; autoActivated: boolean } | undefined; updates: Array<HintUpdate>; words: Array<string>; } { const hasEnteredText = enteredText !== ""; const hasEnteredTextOnly = hasEnteredText && enteredChars === ""; const words = splitEnteredText(enteredText); // Filter away elements/hints not matching by text. const [matching, nonMatching] = partition( passedElementsWithHints, (element) => matchesText(element.text, words) ); // Update the hints after the above filtering. const elementsWithHintsAndMaybeHidden = assignHints(matching, { mode, chars, hasEnteredText, }); // Filter away elements that have become hidden _after_ assigning hints, so // that the hints stay the same. const elementsWithHints = elementsWithHintsAndMaybeHidden.filter( (element) => !element.hidden ); // Find which hints to highlight (if any), and which to activate (if // any). This depends on whether only text chars have been entered, if // auto activation is enabled, if the Enter key is pressed and if hint // chars have been entered. const allHints = elementsWithHints .map((element) => element.hint) .filter((hint) => hint.startsWith(enteredChars)); const matchingHints = allHints.filter((hint) => hint === enteredChars); const autoActivate = hasEnteredTextOnly && autoActivateOption; const matchingHintsSet = autoActivate ? new Set(allHints) : new Set(matchingHints); const matchedHint = matchingHintsSet.size === 1 ? Array.from(matchingHintsSet)[0] : undefined; const highlightedHint = hasEnteredText ? allHints[0] : undefined; const match = elementsWithHints.find( (element) => element.hint === matchedHint || (matchHighlighted && element.hint === highlightedHint) ); const highlightedKeys = new Set( highlighted.map(({ element }) => elementKey(element)) ); const updates: Array<HintUpdate> = elementsWithHintsAndMaybeHidden .map((element, index): HintUpdate => { const matches = element.hint.startsWith(enteredChars); const isHighlighted = (match !== undefined && element.hint === match.hint) || element.hint === highlightedHint || highlightedKeys.has(elementKey(element)); return updateMeasurements ? { // Update the position of the hint. type: "UpdatePosition", index: element.index, order: index, hint: element.hint, hintMeasurements: element.hintMeasurements, highlighted: isHighlighted, hidden: element.hidden || !matches, } : matches && (match === undefined || isHighlighted) ? { // Update the hint (which can change based on text filtering), // which part of the hint has been matched and whether it // should be marked as highlighted/matched. type: "UpdateContent", index: element.index, order: index, matchedChars: enteredChars, restChars: element.hint.slice(enteredChars.length), highlighted: isHighlighted, hidden: element.hidden, } : { // Hide hints that don’t match the entered hint chars. type: "Hide", index: element.index, hidden: true, }; }) .concat( nonMatching.map((element) => ({ // Hide hints for elements filtered by text. type: "Hide", index: element.index, hidden: true, })) ); const allElementsWithHints = elementsWithHintsAndMaybeHidden.concat(nonMatching); return { elementsWithHints, allElementsWithHints, match: match === undefined ? undefined : { elementWithHint: match, autoActivated: autoActivate, }, updates, words, }; } function mergeElements( elementsWithHints: Array<ElementWithHint>, updates: Array<ElementReport>, frameId: number ): Array<ElementWithHint> { const updateMap = new Map<number, ElementReport>( updates.map((update) => [update.index, update]) ); return elementsWithHints.map((element) => { if (element.frame.id !== frameId) { return element; } const update = updateMap.get(element.frame.index); if (update === undefined) { return { ...element, hidden: true }; } return { type: update.type, index: element.index, hintMeasurements: { ...update.hintMeasurements, // Keep the original weight so that hints don't change. weight: element.hintMeasurements.weight, }, url: update.url, urlWithTarget: update.urlWithTarget, text: update.text, textContent: update.textContent, // Keep the original text weight so that hints don't change. textWeight: element.textWeight, isTextInput: update.isTextInput, hasClickListener: update.hasClickListener, frame: element.frame, hidden: false, weight: element.weight, hint: element.hint, }; }); } function matchesText(passedText: string, words: Array<string>): boolean { const text = passedText.toLowerCase(); return words.every((word) => text.includes(word)); }
the_stack
import { extname } from '../../../common/path'; import Sequence from '../../../parsers/mdlx/sequence'; import Texture from '../../../parsers/mdlx/texture'; import Material from '../../../parsers/mdlx/material'; import Layer, { FilterMode as LayerFilterMode } from '../../../parsers/mdlx/layer'; import Geoset from '../../../parsers/mdlx/geoset'; import GeosetAnimation from '../../../parsers/mdlx/geosetanimation'; import Bone from '../../../parsers/mdlx/bone'; import Light from '../../../parsers/mdlx/light'; import ParticleEmitter from '../../../parsers/mdlx/particleemitter'; import ParticleEmitter2, { FilterMode as Particle2FilterMode, Flags as Particle2Flags } from '../../../parsers/mdlx/particleemitter2'; import ParticleEmitterPopcorn from '../../../parsers/mdlx/particleemitterpopcorn'; import RibbonEmitter from '../../../parsers/mdlx/ribbonemitter'; import EventObject from '../../../parsers/mdlx/eventobject'; import Camera from '../../../parsers/mdlx/camera'; import FaceEffect from '../../../parsers/mdlx/faceeffect'; import SanityTestData from './data'; import { sequenceNames, replaceableIds, testObjects, testReference, getTextureIds, testGeosetSkinning, hasAnimation, getAnimation, testExtent, testAndGetReference } from './utils'; import testTracks from './tracks'; export function testHeader(data: SanityTestData): void { const version = data.model.version; if (version !== 800 && version !== 900 && version !== 1000) { data.addWarning(`Unknown version: ${version}`); } if (version === 900) { data.addError('Version 900 is not supported by Warcrft 3'); } if (data.model.animationFile !== '') { data.addWarning(`The animation file should probably be empty, currently set to: "${data.model.animationFile}"`); } testExtent(data, data.model.extent); } export function testSequences(data: SanityTestData): void { const sequences = data.model.sequences; if (sequences.length) { testObjects(data, sequences, testSequence); data.assertSevere(data.foundStand, 'Missing "Stand" sequence'); data.assertSevere(data.foundDeath, 'Missing "Death" sequence'); } else { data.addWarning('No sequences'); } } function testSequence(data: SanityTestData, sequence: Sequence, index: number): void { const name = sequence.name; const tokens = name.toLowerCase().trim().split('-')[0].split(/\s+/); let token = tokens[0]; const interval = sequence.interval; const length = interval[1] - interval[0]; const sequences = data.model.sequences; for (let i = 0; i < index; i++) { const otherSequence = sequences[i]; const otherInterval = otherSequence.interval; // Reforged fixed these weird issues with sequence ordering. if (data.model.version === 800) { if (interval[0] === otherInterval[0]) { data.addSevere(`This sequence starts at the same frame as sequence ${i} "${otherSequence.name}"`); } else if (interval[0] < otherInterval[1]) { data.addSevere(`This sequence starts before sequence ${i} "${otherSequence.name}" ends`); } } } if (token === 'alternate') { token = tokens[1]; } if (token === 'stand') { data.foundStand = true; } if (token === 'death') { data.foundDeath = true; } data.addImplicitReference(); data.assertWarning(sequenceNames.has(token), `"${token}" is not a standard name`); data.assertWarning(length !== 0, 'Zero length'); data.assertWarning(length > -1, `Negative length: ${length}`); testExtent(data, sequence.extent); } export function testGlobalSequence(data: SanityTestData, sequence: number): void { data.assertWarning(sequence !== 0, 'Zero length'); data.assertWarning(sequence >= 0, `Negative length: ${sequence}`); } export function testTextures(data: SanityTestData): void { const textures = data.model.textures; if (textures.length) { testObjects(data, textures, testTexture); } else { data.addWarning('No textures'); } } function testTexture(data: SanityTestData, texture: Texture): void { const replaceableId = texture.replaceableId; const path = texture.path.toLowerCase(); const ext = extname(path); data.assertError(path === '' || ext === '.blp' || ext === '.tga' || ext === '.tif' || ext === '.dds', `Corrupted path: "${path}"`); data.assertError(replaceableId === 0 || replaceableIds.has(replaceableId), `Unknown replaceable ID: ${replaceableId}`); data.assertWarning(path === '' || replaceableId === 0, `Path "${path}" and replaceable ID ${replaceableId} used together`); } export function testMaterial(data: SanityTestData, material: Material): void { const layers = material.layers; const shader = material.shader; if (data.model.version > 800) { data.assertWarning(shader === '' || shader === 'Shader_SD_FixedFunction' || shader === 'Shader_HD_DefaultUnit', `Unknown shader: "${shader}"`); } if (layers.length) { testObjects(data, layers, testLayer); } else { data.addWarning('No layers'); } } function testLayer(data: SanityTestData, layer: Layer): void { const textures = data.model.textures; const textureAnimations = data.model.textureAnimations; for (const textureId of getTextureIds(layer)) { testReference(data, textures, textureId, 'texture'); } const textureAnimationId = layer.textureAnimationId; if (textureAnimationId !== -1) { testReference(data, textureAnimations, textureAnimationId, 'texture animation'); } const filterMode = layer.filterMode; data.assertWarning(filterMode >= LayerFilterMode.None && filterMode <= LayerFilterMode.Modulate2x, `Invalid filter mode: ${layer.filterMode}`); } export function testGeoset(data: SanityTestData, geoset: Geoset, index: number): void { const geosetAnimations = data.model.geosetAnimations; const material = testAndGetReference(data, data.model.materials, geoset.materialId, 'material'); let isHd = false; if (material && material.shader === 'Shader_HD_DefaultUnit') { isHd = true; } if (!isHd) { // When a geoset has too many vertices (or faces? or both?) it will render completely bugged in WC3. // I don't know the exact number, but here are numbers that I tested: // // Verts Faces Result // ---------------------- // 7433 16386 Bugged // 7394 16290 Good // const GUESSED_MAX_VERTICES = 7433 * 3; data.assertSevere(geoset.vertices.length < GUESSED_MAX_VERTICES, `Too many vertices in one geoset: ${geoset.vertices.length / 3}`); } testGeosetSkinning(data, geoset); if (geosetAnimations.length) { const references = []; for (let j = 0, k = geosetAnimations.length; j < k; j++) { if (geosetAnimations[j].geosetId === index) { references.push(j); } } data.assertWarning(references.length <= 1, `Referenced by ${references.length} geoset animations: ${references.join(', ')}`); } if (geoset.faces.length) { data.addImplicitReference(); } else { // The game and my code have no issue with geosets containing no faces, but Magos crashes, so add a warning in addition to it being useless. data.addWarning('Zero faces'); } // The game and my code have no issue with geosets having any number of sequence extents, but Magos fails to parse, so add a warning. // Either way this is only relevant to version 800, because there seem to always be 0 extents in >800 models. if (geoset.sequenceExtents.length !== data.model.sequences.length && data.model.version === 800) { data.addWarning(`Number of sequence extents (${geoset.sequenceExtents.length}) does not match the number of sequences (${data.model.sequences.length})`); } testExtent(data, geoset.extent); for (const extent of geoset.sequenceExtents) { testExtent(data, extent); } } export function testGeosetAnimation(data: SanityTestData, geosetAnimation: GeosetAnimation): void { const geosets = data.model.geosets; const geosetId = geosetAnimation.geosetId; data.addImplicitReference(); testReference(data, geosets, geosetId, 'geoset'); } const SUPPOSED_ALPHA_THRESHOLD = 0.1; export function testBone(data: SanityTestData, bone: Bone, index: number): void { const geosets = data.model.geosets; const geosetAnimations = data.model.geosetAnimations; const geosetId = bone.geosetId; const geosetAnimationId = bone.geosetAnimationId; if (geosetId !== -1) { testReference(data, geosets, geosetId, 'geoset'); } if (geosetAnimationId !== -1 && testReference(data, geosetAnimations, geosetAnimationId, 'geoset animation')) { const geosetAnimation = geosetAnimations[geosetAnimationId]; if (geosetId !== -1 && geosetAnimation.alpha < SUPPOSED_ALPHA_THRESHOLD && !hasAnimation(geosetAnimation, 'KGAO')) { data.addSevere(`Referencing geoset ${geosetId} and geoset animation ${geosetAnimationId} with a 0 alpha, the geoset may be invisible`); } } data.assertWarning(data.boneUsageMap.get(index) > 0, `There are no vertices attached to this bone`); } export function testLight(data: SanityTestData, light: Light): void { const attenuation = light.attenuation; data.assertWarning(attenuation[0] >= 80, `Minimum attenuation should probably be bigger than or equal to 80, but is ${attenuation[0]}`); data.assertWarning(attenuation[1] <= 200, `Maximum attenuation should probably be smaller than or equal to 200, but is ${attenuation[1]}`); data.assertWarning(attenuation[1] - attenuation[0] > 0, `The maximum attenuation should be bigger than the minimum, but isn't`); } export function testAttachments(data: SanityTestData): void { const attachments = data.model.attachments; let foundOrigin = false; for (const attachment of attachments) { const path = attachment.path; if (path.length) { const lowerCase = path.toLowerCase(); data.assertError(lowerCase.endsWith('.mdl') || lowerCase.endsWith('.mdx'), `Invalid path "${path}"`); } if (attachment.name.startsWith('Origin Ref')) { foundOrigin = true; } } if (!foundOrigin) { data.addWarning('Missing the Origin attachment point'); } } export function testPivotPoints(data: SanityTestData): void { const pivotPoints = data.model.pivotPoints; const objects = data.objects; data.assertWarning(pivotPoints.length === objects.length, `Expected ${objects.length} pivot points, got ${pivotPoints.length}`); } export function testParticleEmitter(data: SanityTestData, emitter: ParticleEmitter): void { const path = emitter.path.toLowerCase(); data.assertError(path.endsWith('.mdl') || path.endsWith('.mdx'), 'Invalid path'); } export function testParticleEmitter2(data: SanityTestData, emitter: ParticleEmitter2): void { const replaceableId = emitter.replaceableId; testReference(data, data.model.textures, emitter.textureId, 'texture'); const filterMode = emitter.filterMode; data.assertWarning(filterMode >= Particle2FilterMode.Blend && filterMode <= Particle2FilterMode.AlphaKey, `Invalid filter mode: ${emitter.filterMode}`); data.assertError(replaceableId === 0 || replaceableIds.has(replaceableId), `Invalid replaceable ID: ${replaceableId}`); if (emitter.flags & Particle2Flags.XYQuad) { data.assertSevere(emitter.speed !== 0 && emitter.latitude !== 0, 'XY Quad emitters must have a non-zero speed and latitude'); } data.assertSevere(emitter.timeMiddle >= 0 && emitter.timeMiddle <= 1, `Expected time middle to be between 0 and 1, got ${emitter.timeMiddle}`); if (emitter.squirt && !getAnimation(emitter, 'KP2E')) { data.addSevere('Using squirt without animating the emission rate'); } } export function testParticleEmitterPopcorn(data: SanityTestData, emitter: ParticleEmitterPopcorn): void { const path = emitter.path; if (path.length) { data.assertError(path.endsWith('.pkfx'), `Corrupted path: "${path}"`); } } export function testRibbonEmitter(data: SanityTestData, emitter: RibbonEmitter): void { testReference(data, data.model.materials, emitter.materialId, 'material'); } export function testEventObject(data: SanityTestData, eventObject: EventObject): void { testTracks(data, eventObject); } export function testCamera(data: SanityTestData, _camera: Camera): void { // I don't know what the rules are as to when cameras are used for portraits. // Therefore, for now never report them as not used. data.addImplicitReference(); } export function testFaceEffect(data: SanityTestData, faceEffect: FaceEffect): void { const path = faceEffect.path; if (path.length) { data.assertError(path.endsWith('.facefx') || path.endsWith('.facefx_ingame'), `Corrupted face effect path: "${path}"`); } data.addImplicitReference(); } export function testBindPose(data: SanityTestData): void { const matrices = data.model.bindPose; const objects = data.objects; if (matrices.length && objects.length) { // There's always an extra matrix for some reason. // Face effects? but also models with no face effects have it. data.assertWarning(matrices.length === objects.length + 1, `Expected ${objects.length + 1} matrices, got ${matrices.length}`); } }
the_stack
import { BrowserWindow, Event as ElectronEvent, IpcMainEvent, MessagePortMain } from 'electron'; import { validatedIpcMain } from 'vs/base/parts/ipc/electron-main/ipcMain'; import { Barrier } from 'vs/base/common/async'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { FileAccess } from 'vs/base/common/network'; import { IProcessEnvironment } from 'vs/base/common/platform'; import { assertIsDefined } from 'vs/base/common/types'; import { connect as connectMessagePort } from 'vs/base/parts/ipc/electron-main/ipc.mp'; import { IEnvironmentMainService } from 'vs/platform/environment/electron-main/environmentMainService'; import { ILifecycleMainService } from 'vs/platform/lifecycle/electron-main/lifecycleMainService'; import { ILogService } from 'vs/platform/log/common/log'; import product from 'vs/platform/product/common/product'; import { IProtocolMainService } from 'vs/platform/protocol/electron-main/protocol'; import { ISharedProcess, ISharedProcessConfiguration } from 'vs/platform/sharedProcess/node/sharedProcess'; import { ISharedProcessWorkerConfiguration } from 'vs/platform/sharedProcess/common/sharedProcessWorkerService'; import { IThemeMainService } from 'vs/platform/theme/electron-main/themeMainService'; import { WindowError } from 'vs/platform/window/electron-main/window'; import { toErrorMessage } from 'vs/base/common/errorMessage'; export class SharedProcess extends Disposable implements ISharedProcess { private readonly firstWindowConnectionBarrier = new Barrier(); private window: BrowserWindow | undefined = undefined; private windowCloseListener: ((event: ElectronEvent) => void) | undefined = undefined; private readonly _onDidError = this._register(new Emitter<{ type: WindowError; details?: { reason: string; exitCode: number } }>()); readonly onDidError = Event.buffer(this._onDidError.event); // buffer until we have a listener! constructor( private readonly machineId: string, private userEnv: IProcessEnvironment, @IEnvironmentMainService private readonly environmentMainService: IEnvironmentMainService, @ILifecycleMainService private readonly lifecycleMainService: ILifecycleMainService, @ILogService private readonly logService: ILogService, @IThemeMainService private readonly themeMainService: IThemeMainService, @IProtocolMainService private readonly protocolMainService: IProtocolMainService ) { super(); this.registerListeners(); } private registerListeners(): void { // Shared process connections from workbench windows validatedIpcMain.on('vscode:createSharedProcessMessageChannel', (e, nonce: string) => this.onWindowConnection(e, nonce)); // Shared process worker relay validatedIpcMain.on('vscode:relaySharedProcessWorkerMessageChannel', (e, configuration: ISharedProcessWorkerConfiguration) => this.onWorkerConnection(e, configuration)); // Lifecycle this._register(this.lifecycleMainService.onWillShutdown(() => this.onWillShutdown())); } private async onWindowConnection(e: IpcMainEvent, nonce: string): Promise<void> { this.logService.trace('SharedProcess: on vscode:createSharedProcessMessageChannel'); // release barrier if this is the first window connection if (!this.firstWindowConnectionBarrier.isOpen()) { this.firstWindowConnectionBarrier.open(); } // await the shared process to be overall ready // we do not just wait for IPC ready because the // workbench window will communicate directly await this.whenReady(); // connect to the shared process window const port = await this.connect(); // Check back if the requesting window meanwhile closed // Since shared process is delayed on startup there is // a chance that the window close before the shared process // was ready for a connection. if (e.sender.isDestroyed()) { return port.close(); } // send the port back to the requesting window e.sender.postMessage('vscode:createSharedProcessMessageChannelResult', nonce, [port]); } private onWorkerConnection(e: IpcMainEvent, configuration: ISharedProcessWorkerConfiguration): void { this.logService.trace('SharedProcess: onWorkerConnection', configuration); const disposables = new DisposableStore(); const disposeWorker = (reason: string) => { if (!this.isAlive()) { return; // the shared process is already gone, no need to dispose anything } this.logService.trace(`SharedProcess: disposing worker (reason: '${reason}')`, configuration); // Only once! disposables.dispose(); // Send this into the shared process who owns workers this.send('vscode:electron-main->shared-process=disposeWorker', configuration); }; // Ensure the sender is a valid target to send to const receiverWindow = BrowserWindow.fromId(configuration.reply.windowId); if (!receiverWindow || receiverWindow.isDestroyed() || receiverWindow.webContents.isDestroyed() || !configuration.reply.channel) { disposeWorker('unavailable'); return; } // Attach to lifecycle of receiver to manage worker lifecycle disposables.add(Event.filter(this.lifecycleMainService.onWillLoadWindow, e => e.window.win === receiverWindow)(() => disposeWorker('load'))); disposables.add(Event.fromNodeEventEmitter(receiverWindow, 'closed')(() => disposeWorker('closed'))); // The shared process window asks us to relay a `MessagePort` // from a shared process worker to the target window. It needs // to be send via `postMessage` to transfer the port. receiverWindow.webContents.postMessage(configuration.reply.channel, configuration.reply.nonce, e.ports); } private onWillShutdown(): void { const window = this.window; if (!window) { return; // possibly too early before created } // Signal exit to shared process when shutting down this.send('vscode:electron-main->shared-process=exit'); // Shut the shared process down when we are quitting // // Note: because we veto the window close, we must first remove our veto. // Otherwise the application would never quit because the shared process // window is refusing to close! // if (this.windowCloseListener) { window.removeListener('close', this.windowCloseListener); this.windowCloseListener = undefined; } // Electron seems to crash on Windows without this setTimeout :| setTimeout(() => { try { window.close(); } catch (err) { // ignore, as electron is already shutting down } this.window = undefined; }, 0); } private send(channel: string, ...args: any[]): void { if (!this.isAlive()) { this.logService.warn(`Sending IPC message to channel '${channel}' for shared process window that is destroyed`); return; } try { this.window?.webContents.send(channel, ...args); } catch (error) { this.logService.warn(`Error sending IPC message to channel '${channel}' of shared process: ${toErrorMessage(error)}`); } } private _whenReady: Promise<void> | undefined = undefined; whenReady(): Promise<void> { if (!this._whenReady) { // Overall signal that the shared process window was loaded and // all services within have been created. this._whenReady = new Promise<void>(resolve => validatedIpcMain.once('vscode:shared-process->electron-main=init-done', () => { this.logService.trace('SharedProcess: Overall ready'); resolve(); })); } return this._whenReady; } private _whenIpcReady: Promise<void> | undefined = undefined; private get whenIpcReady() { if (!this._whenIpcReady) { this._whenIpcReady = (async () => { // Always wait for first window asking for connection await this.firstWindowConnectionBarrier.wait(); // Create window for shared process this.createWindow(); // Listeners this.registerWindowListeners(); // Wait for window indicating that IPC connections are accepted await new Promise<void>(resolve => validatedIpcMain.once('vscode:shared-process->electron-main=ipc-ready', () => { this.logService.trace('SharedProcess: IPC ready'); resolve(); })); })(); } return this._whenIpcReady; } private createWindow(): void { const configObjectUrl = this._register(this.protocolMainService.createIPCObjectUrl<ISharedProcessConfiguration>()); // shared process is a hidden window by default this.window = new BrowserWindow({ show: false, backgroundColor: this.themeMainService.getBackgroundColor(), webPreferences: { preload: FileAccess.asFileUri('vs/base/parts/sandbox/electron-browser/preload.js', require).fsPath, additionalArguments: [`--vscode-window-config=${configObjectUrl.resource.toString()}`, '--vscode-window-kind=shared-process'], v8CacheOptions: this.environmentMainService.useCodeCache ? 'bypassHeatCheck' : 'none', nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false, enableWebSQL: false, spellcheck: false, nativeWindowOpen: true, images: false, webgl: false } }); // Store into config object URL configObjectUrl.update({ machineId: this.machineId, windowId: this.window.id, appRoot: this.environmentMainService.appRoot, codeCachePath: this.environmentMainService.codeCachePath, backupWorkspacesPath: this.environmentMainService.backupWorkspacesPath, userEnv: this.userEnv, args: this.environmentMainService.args, logLevel: this.logService.getLevel(), product }); // Load with config this.window.loadURL(FileAccess.asBrowserUri('vs/code/electron-browser/sharedProcess/sharedProcess.html', require).toString(true)); } private registerWindowListeners(): void { if (!this.window) { return; } // Prevent the window from closing this.windowCloseListener = (e: ElectronEvent) => { this.logService.trace('SharedProcess#close prevented'); // We never allow to close the shared process unless we get explicitly disposed() e.preventDefault(); // Still hide the window though if visible if (this.window?.isVisible()) { this.window.hide(); } }; this.window.on('close', this.windowCloseListener); // Crashes & Unresponsive & Failed to load // We use `onUnexpectedError` explicitly because the error handler // will send the error to the active window to log in devtools too this.window.webContents.on('render-process-gone', (event, details) => this._onDidError.fire({ type: WindowError.CRASHED, details })); this.window.on('unresponsive', () => this._onDidError.fire({ type: WindowError.UNRESPONSIVE })); this.window.webContents.on('did-fail-load', (event, exitCode, reason) => this._onDidError.fire({ type: WindowError.LOAD, details: { reason, exitCode } })); } async connect(): Promise<MessagePortMain> { // Wait for shared process being ready to accept connection await this.whenIpcReady; // Connect and return message port const window = assertIsDefined(this.window); return connectMessagePort(window); } async toggle(): Promise<void> { // wait for window to be created await this.whenIpcReady; if (!this.window) { return; // possibly disposed already } if (this.window.isVisible()) { this.window.webContents.closeDevTools(); this.window.hide(); } else { this.window.show(); this.window.webContents.openDevTools(); } } isVisible(): boolean { return this.window?.isVisible() ?? false; } private isAlive(): boolean { const window = this.window; if (!window) { return false; } return !window.isDestroyed() && !window.webContents.isDestroyed(); } }
the_stack
import { AST_NODE_TYPES, AST_TOKEN_TYPES, STORAGE_CLASS, } from '../ast/glsl-ast-node-types'; import { ArrayExpression, AssignmentExpression, BaseNode, BinaryExpression, BlockStatement, CallExpression, ConditionalExpression, DataType, DoWhileStatement, Expression, ExpressionStatement, ForStatement, FunctionDeclaration, FunctionExpression, Identifier, IfStatement, MemberExpression, NumThreadStatement, Program, ReturnStatement, Scalar, Scope, Statement, UnaryExpression, UpdateExpression, VariableDeclaration, VariableDeclarator, WhileStatement, } from '../ast/glsl-tree'; import { DefineValuePlaceholder, GLSLContext } from '../Compiler'; import { builtinFunctions, componentWiseFunctions, importFunctions, } from '../utils/builtin-functions'; import { compareDataTypePriority, getComponentDataTypeFromVector, getComponentSize, isArray, isLeft, isMatrix, isScalar, isVector, } from '../utils/data-type'; import { getIdentifierFromScope, traverseUpwards } from '../utils/node'; import { ICodeGenerator, Target } from './ICodeGenerator'; const dataTypeMap: Record<DataType, string> = { [AST_TOKEN_TYPES.Void]: 'void', [AST_TOKEN_TYPES.Boolean]: 'bool', [AST_TOKEN_TYPES.Int32]: 'int', [AST_TOKEN_TYPES.Uint32]: 'uint', [AST_TOKEN_TYPES.Float]: 'float', [AST_TOKEN_TYPES.Vector2Float]: 'vec2', [AST_TOKEN_TYPES.Vector3Float]: 'vec3', [AST_TOKEN_TYPES.Vector4Float]: 'vec4', [AST_TOKEN_TYPES.Vector2Int]: 'ivec2', [AST_TOKEN_TYPES.Vector3Int]: 'ivec3', [AST_TOKEN_TYPES.Vector4Int]: 'ivec4', [AST_TOKEN_TYPES.Vector2Uint]: 'uvec2', [AST_TOKEN_TYPES.Vector3Uint]: 'uvec3', [AST_TOKEN_TYPES.Vector4Uint]: 'uvec4', [AST_TOKEN_TYPES.Vector2Boolean]: 'bvec2', [AST_TOKEN_TYPES.Vector3Boolean]: 'bvec3', [AST_TOKEN_TYPES.Vector4Boolean]: 'bvec4', [AST_TOKEN_TYPES.Matrix3x3Float]: 'mat3', [AST_TOKEN_TYPES.Matrix4x4Float]: 'mat4', [AST_TOKEN_TYPES.FloatArray]: 'sampler2D', [AST_TOKEN_TYPES.Vector4FloatArray]: 'sampler2D', }; export class CodeGeneratorGLSL450 implements ICodeGenerator { public static GWEBGPU_UNIFORM_PARAMS = 'gWebGPUUniformParams'; public static GWEBGPU_BUFFER = 'gWebGPUBuffer'; private context: GLSLContext; private bufferBindingIndex = -1; public clear() { this.bufferBindingIndex = -1; } public generate(program: Program, context?: GLSLContext): string { if (context) { this.context = context; } const [ workGroupSizeX, workGroupSizeY, workGroupSizeZ, ] = context?.threadGroupSize || [1, 1, 1]; const body = program.body .map((stmt) => this.generateStatement(stmt)) .join('\n'); return ` ${importFunctions[Target.GLSL450]} bool gWebGPUDebug = false; vec4 gWebGPUDebugOutput = vec4(0.0); ivec3 globalInvocationID = ivec3(gl_GlobalInvocationID); ivec3 workGroupSize = ivec3(${workGroupSizeX},${workGroupSizeY},${workGroupSizeZ}); ivec3 workGroupID = ivec3(gl_WorkGroupID); ivec3 localInvocationID = ivec3(gl_LocalInvocationID); ivec3 numWorkGroups = ivec3(gl_NumWorkGroups); int localInvocationIndex = int(gl_LocalInvocationIndex); ${this.generateUniforms()} ${this.generateBuffers()} ${this.generateGlobalVariableDeclarations()} ${body} `; } public generateStatement(stmt: Statement): string { if (stmt.type === AST_NODE_TYPES.VariableDeclaration) { return this.generateVariableDeclaration(stmt); } else if (stmt.type === AST_NODE_TYPES.FunctionDeclaration) { return this.generateFunctionExpression(stmt); } else if (stmt.type === AST_NODE_TYPES.BlockStatement) { return this.generateBlockStatement(stmt); } else if (stmt.type === AST_NODE_TYPES.NumThreadStatement) { return this.generateNumThreadStatement(stmt); } else if (stmt.type === AST_NODE_TYPES.ImportedFunctionStatement) { return stmt.content; } else { // tslint:disable-next-line:no-console console.warn(`[GLSL450 compiler]: unknown statement: ${stmt.type}`); } return ''; } public generateNumThreadStatement(stmt: NumThreadStatement): string { const [x, y, z] = stmt.threadGroupSize; return `layout ( local_size_x = ${x}, local_size_y = ${y}, local_size_z = ${z} ) in;`; } public generateVariableDeclaration(stmt: VariableDeclaration): string { return stmt.declarations .map((declarator) => { if (declarator.storageClass === STORAGE_CLASS.UniformConstant) { const define = this.context?.defines.find( (d) => d.name === declarator.id.name, ); const placeHolder = `${DefineValuePlaceholder}${define?.name}`; // #define CONST 10 return `#define ${declarator.id.name} ${ define?.runtime ? placeHolder : this.generateExpression(declarator.init) }`; } else if ( declarator.storageClass === STORAGE_CLASS.Uniform || declarator.storageClass === STORAGE_CLASS.StorageBuffer ) { // const name = declarator.id.name; // const componentDataType = getComponentDataTypeFromVector( // declarator.id.dataType, // ); // const componentDataTypeStr = this.generateDataType(componentDataType); // const dataType = this.generateDataType(declarator.id.dataType); // 不在这里生成 } else if (declarator.storageClass === STORAGE_CLASS.Private) { if (declarator.init) { // float a = 1.0; // float b = vec3(1.0); return `${this.generateDataType(declarator.id.dataType)} ${ declarator.id.name } = ${this.generateExpression( declarator.init, declarator.id.dataType, )};`; } else { // float a; // Root Scope 中不允许声明变量但不赋值 if ( stmt.parent && (stmt.parent as Program).type === AST_NODE_TYPES.Program ) { return ''; } return `${this.generateDataType(declarator.id.dataType)} ${ declarator.id.name };`; } } return ''; }) .join('\n'); } public generateBlockStatement(stmt: BlockStatement): string { return stmt.body .map((s) => { if (s.type === AST_NODE_TYPES.VariableDeclaration) { return this.generateVariableDeclaration(s); } else if (s.type === AST_NODE_TYPES.ExpressionStatement) { return this.generateExpression(s.expression) + ';'; } else if (s.type === AST_NODE_TYPES.ReturnStatement) { return this.generateReturnStatement(s); } else if (s.type === AST_NODE_TYPES.IfStatement) { return this.generateIfStatement(s); } else if (s.type === AST_NODE_TYPES.ForStatement) { return this.generateForStatement(s); } else if (s.type === AST_NODE_TYPES.BreakStatement) { return 'break;'; } else if (s.type === AST_NODE_TYPES.ContinueStatement) { return 'continue;'; } else if (s.type === AST_NODE_TYPES.WhileStatement) { return this.generateWhileStatement(s); } else if (s.type === AST_NODE_TYPES.DoWhileStatement) { return this.generateDoWhileStatement(s); } else { // tslint:disable-next-line:no-console console.warn(`[GLSL450 compiler]: unknown statement: ${stmt}`); } return ''; }) .join('\n'); } public generateReturnStatement(stmt: ReturnStatement): string { // 必须匹配函数返回值类型,需要向上查找最近的的 FunctionDeclaration const returnType = traverseUpwards<DataType>(stmt, (currentNode) => { if ( (currentNode as FunctionDeclaration).type === AST_NODE_TYPES.FunctionDeclaration && (currentNode as FunctionDeclaration).returnType ) { return (currentNode as FunctionDeclaration).returnType; } }); return `return ${(stmt.argument && this.generateExpression(stmt.argument, returnType)) || ''};`; } public generateWhileStatement(stmt: WhileStatement): string { return `while(${this.generateExpression(stmt.test)}) { ${this.generateStatement(stmt.body)} }`; } public generateDoWhileStatement(stmt: DoWhileStatement): string { return `do { ${this.generateStatement(stmt.body)} } while(${this.generateExpression(stmt.test)});`; } public generateForStatement(node: ForStatement): string { let init = ''; if (node.init?.type === AST_NODE_TYPES.VariableDeclaration) { // 修改 init 类型例如 int i = 0; node.init.declarations.forEach((d) => { d.id.dataType = AST_TOKEN_TYPES.Int32; }); init = this.generateVariableDeclaration(node.init); } else if (node.init?.type === AST_NODE_TYPES.AssignmentExpression) { init = this.generateExpression(node.init); } return `for (${init} ${node.test && this.generateExpression(node.test)}; ${node.update && this.generateExpression(node.update)}) {${this.generateBlockStatement( node.body as BlockStatement, )}}`; } public generateIfStatement(node: IfStatement): string { let consequent = ''; if (node.consequent.type === AST_NODE_TYPES.ExpressionStatement) { consequent = this.generateExpression(node.consequent.expression); } else if (node.consequent.type === AST_NODE_TYPES.BlockStatement) { consequent = this.generateBlockStatement(node.consequent); } else if (node.consequent.type === AST_NODE_TYPES.ReturnStatement) { consequent = this.generateReturnStatement(node.consequent); } else if (node.consequent.type === AST_NODE_TYPES.BreakStatement) { consequent = 'break;'; } let alternate = ''; if (node.alternate) { if (node.alternate.type === AST_NODE_TYPES.ExpressionStatement) { alternate = this.generateExpression(node.alternate.expression); } else if (node.alternate.type === AST_NODE_TYPES.BlockStatement) { alternate = this.generateBlockStatement(node.alternate); } else if (node.alternate.type === AST_NODE_TYPES.ReturnStatement) { alternate = this.generateReturnStatement(node.alternate); } else if (node.alternate.type === AST_NODE_TYPES.BreakStatement) { alternate = 'break;'; } } return `if (${this.generateExpression(node.test)}) {${consequent}}${ alternate ? `else {${alternate}}` : '' }`; } public generateFunctionExpression( stmt: FunctionDeclaration | FunctionExpression, ): string { if (stmt.body) { return `${this.generateDataType( stmt.returnType || AST_TOKEN_TYPES.Void, )} ${stmt.id?.name}(${(stmt.params || []) .map( (p) => p.type === AST_NODE_TYPES.Identifier && `${this.generateDataType(p.dataType)} ${p.name}`, ) .join(', ')}) {${this.generateBlockStatement(stmt.body)}}`; } return ''; } public generateExpression( expression: Expression | null, dataType?: DataType, ): string { // @ts-ignore if (isScalar(expression?.type)) { return this.generateScalar( // @ts-ignore dataType || expression?.type, // @ts-ignore expression.value, ); // @ts-ignore } else if (isVector(expression?.type)) { // @ts-ignore return this.generateVector( // @ts-ignore dataType || expression?.type, // @ts-ignore expression.value, ); // @ts-ignore } else if (isMatrix(expression?.type)) { return this.generateMatrix( // @ts-ignore dataType || expression?.type, // @ts-ignore expression.value, ); } else if (expression?.type === AST_NODE_TYPES.ArrayExpression) { return this.generateArrayExpression(expression, dataType); } else if (expression?.type === AST_NODE_TYPES.Identifier) { const id = getIdentifierFromScope(expression, expression.name); const storageClass = (id?.parent as VariableDeclarator)?.storageClass; // 需要改变引用方式 if (id && storageClass) { if (storageClass === STORAGE_CLASS.StorageBuffer) { const bufferIndex = this.context.uniforms .filter((u) => u.storageClass === STORAGE_CLASS.StorageBuffer) .findIndex((u) => u.name === id.name); if (bufferIndex > -1) { return `${CodeGeneratorGLSL450.GWEBGPU_BUFFER}${bufferIndex}.${expression.name}`; } } else if (storageClass === STORAGE_CLASS.Uniform) { const uniform = this.context.uniforms .filter((u) => u.storageClass === STORAGE_CLASS.Uniform) .find((u) => u.name === id.name); if (uniform) { return `${CodeGeneratorGLSL450.GWEBGPU_UNIFORM_PARAMS}.${expression.name}`; } } } return this.castingDataType( dataType, expression.dataType, expression.name, ); } else if (expression?.type === AST_NODE_TYPES.BinaryExpression) { return this.generateBinaryExpression(expression, dataType); } else if (expression?.type === AST_NODE_TYPES.CallExpression) { return this.generateCallExpression(expression, dataType); } else if (expression?.type === AST_NODE_TYPES.AssignmentExpression) { return this.generateAssignmentExpression(expression, dataType); } else if (expression?.type === AST_NODE_TYPES.UpdateExpression) { return this.generateUpdateExpression(expression); } else if (expression?.type === AST_NODE_TYPES.MemberExpression) { return this.generateMemberExpression(expression); } else if (expression?.type === AST_NODE_TYPES.ConditionalExpression) { return this.generateConditionalExpression(expression); } else if (expression?.type === AST_NODE_TYPES.UnaryExpression) { return this.generateUnaryExpression(expression, dataType); } else { // tslint:disable-next-line:no-console console.warn( `[GLSL450 compiler]: unknown expression: ${expression}`, dataType, ); } return ''; } public generateUnaryExpression( expression: UnaryExpression, dataType?: DataType, ): string { return `${expression.operator}${this.generateExpression( expression.argument, dataType, )}`; } public generateConditionalExpression( expression: ConditionalExpression, ): string { // 条件判断也应该丢弃掉之前推断的类型 return `(${this.generateExpression( expression.test, )}) ? (${this.generateExpression( expression.consequent, )}) : (${this.generateExpression(expression.alternate)})`; } public generateMemberExpression(expression: MemberExpression): string { const objectStr = this.generateExpression(expression.object); if (expression.property.type === AST_NODE_TYPES.Identifier) { if (!expression.computed) { // swizzling & struct uniform eg. params.u_k / vec.rgba return `${objectStr}.${(expression.property as Identifier).name}`; } else { return `${objectStr}[${(expression.property as Identifier).name}]`; } } else if ( (expression.property.type === AST_TOKEN_TYPES.Float || expression.property.type === AST_TOKEN_TYPES.Int32 || expression.property.type === AST_TOKEN_TYPES.Uint32) && isFinite(Number(expression.property.value)) ) { const index = Number(expression.property.value); if ( expression.object.type === AST_NODE_TYPES.Identifier && isArray(expression.object.dataType) ) { // shared[0] 此时不能写成 shared.x return `${objectStr}[${index}]`; } else { let swizzlingComponent = 'x'; switch (index) { case 0: swizzlingComponent = 'x'; break; case 1: swizzlingComponent = 'y'; break; case 2: swizzlingComponent = 'z'; break; case 3: swizzlingComponent = 'w'; break; } // vec[0] // 考虑 getData()[0] 的情况,转译成 getData().x return `${objectStr}.${swizzlingComponent}`; } } else { // data[a + b] return `${objectStr}[${this.generateExpression(expression.property)}]`; } } public generateUpdateExpression(expression: UpdateExpression): string { // i++ ++i return expression.prefix ? `${expression.operator}${(expression.argument as Identifier).name}` : `${(expression.argument as Identifier).name}${expression.operator}`; } public generateAssignmentExpression( expression: AssignmentExpression, dataType?: DataType, ): string { if (expression.operator === '<<=') { console.log(expression, dataType); } const left = this.generateExpression(expression.left, dataType); const right = this.generateExpression(expression.right, dataType); return `${left} ${expression.operator} ${right}`; } public generateArrayExpression( expression: ArrayExpression, dataType?: DataType, ): string { const dt = expression.dataType || dataType || AST_TOKEN_TYPES.Vector4Float; // vec3(1.0, 2.0, 3.0) return `${this.generateDataType(dt)}(${expression.elements .map((e) => this.generateExpression(e, getComponentDataTypeFromVector(dt)), ) .join(', ')})`; } public generateBinaryExpression( expression: BinaryExpression, dataType?: DataType, ): string { const needBracket = // @ts-ignore expression.parent?.type === AST_NODE_TYPES.BinaryExpression; return `${needBracket ? '(' : ''}${this.generateExpression( expression.left, dataType, )} ${expression.operator} ${this.generateExpression( expression.right, dataType, )}${needBracket ? ')' : ''}`; } // TODO: 替换 Math.sin() -> sin() public generateCallExpression( expression: CallExpression, dataType?: DataType, ): string { const isComponentWise = expression.callee.type === AST_NODE_TYPES.Identifier && componentWiseFunctions.indexOf(expression.callee.name) > -1; let params: Identifier[] = []; if (expression.callee.type === AST_NODE_TYPES.Identifier) { // 获取函数声明时的参数类型 const functionId = getIdentifierFromScope( expression, expression.callee.name, true, ); if ( functionId && functionId.parent && (functionId.parent as FunctionDeclaration).type === AST_NODE_TYPES.FunctionDeclaration ) { params = (functionId.parent as FunctionDeclaration).params; } } return `${this.generateExpression(expression.callee)}(${expression.arguments .map((e, i) => { // if (e.type === AST_NODE_TYPES.CallExpression) { // // int(floor(v.x + 0.5)) // // 考虑函数嵌套的情况,需要丢弃掉外层推断的类型 // return this.generateExpression(e); // } return this.generateExpression( e, isComponentWise ? dataType : params[i] && params[i].dataType, ); }) .join(', ')})`; } public generateDataType(dt: DataType): string { return dataTypeMap[dt]; } public generateScalar(dt: DataType, scalar: number | boolean): string { if (dt === AST_TOKEN_TYPES.Boolean) { return `${!!scalar}`; } else if (dt === AST_TOKEN_TYPES.Float) { return this.wrapFloat(`${Number(scalar)}`); } else if (dt === AST_TOKEN_TYPES.Int32 || dt === AST_TOKEN_TYPES.Uint32) { return parseInt(`${Number(scalar)}`, 10).toString(); } return `${scalar}`; } public generateVector(dt: DataType, vector: number | boolean): string { const componentDataType = getComponentDataTypeFromVector(dt); return this.castingDataType( dt, componentDataType, this.generateScalar(componentDataType, vector), ); } public generateMatrix(dt: DataType, vector: number | boolean): string { const componentDataType = getComponentDataTypeFromVector(dt); return this.castingDataType( dt, componentDataType, this.generateScalar(componentDataType, vector), ); } private wrapFloat(float: string): string { return float.indexOf('.') === -1 ? `${float}.0` : float; } private castingDataType( dt1: DataType | undefined, dt2: DataType, content: string, ): string { // 需要强制类型转换 if (dt1 && dt1 !== dt2) { const castDataType = compareDataTypePriority(dt1, dt2); if (castDataType !== dt2) { return `${this.generateDataType(castDataType)}(${content})`; } } return content; } private generateSwizzling(dt: DataType): string { const size = getComponentSize(dt); if (size === 3) { return '.rgb'; } else if (size === 2) { return '.rg'; } else if (size === 4) { return '.rgba'; } else { return '.r'; } } private generateGlobalVariableDeclarations() { if (!this.context) { return ''; } return `${this.context.globalDeclarations .map( (gd) => `${(gd.shared && 'shared') || ''} ${this.generateDataType( getComponentDataTypeFromVector(gd.type), ).replace('[]', '')} ${gd.name}[${gd.value}];`, ) .join('\n')} `; } private generateUniforms(): string { if (!this.context) { return ''; } const uniformDeclarations = this.context.uniforms .map((uniform) => { if ( uniform.storageClass === STORAGE_CLASS.Uniform // WebGPU Compute Shader 使用 buffer 而非 uniform ) { return `${this.generateDataType(uniform.type)} ${uniform.name};`; } return ''; }) .join('\n ') // 缩进 .trim(); return ( uniformDeclarations && `layout(std140, set = 0, binding = ${++this .bufferBindingIndex}) uniform GWebGPUParams { ${uniformDeclarations} } ${CodeGeneratorGLSL450.GWEBGPU_UNIFORM_PARAMS};` ); } private generateBuffers() { if (!this.context) { return ''; } let bufferIndex = -1; return this.context.uniforms .map((u) => { if (u.storageClass === STORAGE_CLASS.StorageBuffer) { bufferIndex++; return `layout(std430, set = 0, binding = ${++this .bufferBindingIndex}) buffer ${(u.readonly && 'readonly') || ''} ${(u.writeonly && 'writeonly') || ''} GWebGPUBuffer${bufferIndex} { ${this.generateDataType(getComponentDataTypeFromVector(u.type))} ${u.name}[]; } ${CodeGeneratorGLSL450.GWEBGPU_BUFFER}${bufferIndex}; `; // } else if (u.type === 'image2D') { // return `layout(set = 0, binding = ${++this // .bufferBindingIndex}) uniform texture2D ${u.name}; // layout(set = 0, binding = ${++this.bufferBindingIndex}) uniform sampler ${ // u.name // }Sampler; // `; } return ''; }) .filter((line) => line) .join('\n') .trim(); } }
the_stack
import React from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import { lucidClassNames } from '../../util/style-helpers'; import { findTypes, getFirst, StandardProps } from '../../util/component-types'; import { buildModernHybridComponent } from '../../util/state-management'; import * as reducers from './SingleSelect.reducers'; import { IDropMenuProps, IDropMenuState, IDropMenuOptionProps, IDropMenuOptionGroupProps, DropMenuDumb as DropMenu, IOptionsData, } from '../DropMenu/DropMenu'; import ChevronIcon from '../Icon/ChevronIcon/ChevronIcon'; const cx = lucidClassNames.bind('&-SingleSelect'); const { any, bool, func, node, number, object, shape, string, oneOfType } = PropTypes; /** Placeholder Child Component */ export interface ISingleSelectPlaceholderProps extends StandardProps { description?: string; } const Placeholder = (_props: ISingleSelectPlaceholderProps): null => null; Placeholder.displayName = 'SingleSelect.Placeholder'; Placeholder.peek = { description: `Content this is displayed when nothing is selected.`, }; Placeholder.propName = 'Placeholder'; /** Option Child Component */ export interface ISingleSelectOptionProps extends IDropMenuOptionProps { description?: string; name?: string; /** Custom Option component (alias for `SingleSelect.Option.Selected`) */ Selected?: React.ReactNode; } const Selected = (_props: { children?: React.ReactNode }): null => null; Selected.displayName = 'SingleSelect.Option.Selected'; Selected.peek = { description: `Customizes the rendering of the Option when it is selected and is displayed instead of the Placeholder.`, }; Selected.propName = 'Selected'; Selected.propTypes = {}; const Option = (_props: ISingleSelectOptionProps): null => null; Option.displayName = 'SingleSelect.Option'; Option.peek = { description: ` A selectable option in the list. `, }; Option.Selected = Selected; Option.propName = 'Option'; Option.propTypes = { /** Customizes the rendering of the Option when it is selected and is displayed instead of the Placeholder. */ Selected: any, ...DropMenu.Option.propTypes, }; Option.defaultProps = DropMenu.Option.defaultProps; const OptionGroup = (_props: IDropMenuOptionGroupProps): null => null; OptionGroup.displayName = 'SingleSelect.OptionGroup'; OptionGroup.peek = { description: ` Groups \`Option\`s together with a non-selectable heading. `, }; OptionGroup.propName = 'OptionGroup'; OptionGroup.propTypes = DropMenu.OptionGroup.propTypes; OptionGroup.defaultProps = DropMenu.OptionGroup.defaultProps; type ISingleSelectDropMenuProps = Partial<IDropMenuProps>; /** Single Select Component */ export interface ISingleSelectProps extends StandardProps { /** Custom Placeholder component (alias for `SingleSelect.Placeholder`) */ Placeholder?: React.ReactNode; /** Custom Option component (alias for `SingleSelect.Option`) */ Option?: React.ReactNode; //TODO: Remove? Seems like this belongs on OptionProps not SingleSelectProps /** Custom Option component (alias for `SingleSelect.Option.Selected`) */ Selected?: React.ReactNode; /** Custom OptionGroup component (alias for `SingleSelect.OptionGroup`) */ OptionGroup?: IDropMenuOptionGroupProps; hasReset: boolean; isSelectionHighlighted: boolean; isDisabled: boolean; isInvisible: boolean; selectedIndex: number | null; DropMenu: ISingleSelectDropMenuProps; maxMenuHeight?: number | string; showIcon?: boolean; onSelect?: ( optionIndex: number | null, { props, event, }: { props: ISingleSelectOptionProps | undefined; event: React.MouseEvent | React.KeyboardEvent; } ) => void; } export interface ISingleSelectState { selectedIndex: number | null; optionGroups: IDropMenuOptionGroupProps[]; flattenedOptionsData: IOptionsData[]; ungroupedOptionData: IOptionsData[]; optionGroupDataLookup: { [key: number]: IOptionsData[] }; DropMenu: IDropMenuState; } const defaultProps = { hasReset: true, isSelectionHighlighted: true, isDisabled: false, isInvisible: false, selectedIndex: null, showIcon: true, DropMenu: DropMenu.defaultProps, }; class SingleSelect extends React.Component< ISingleSelectProps, ISingleSelectState > { static displayName = 'SingleSelect'; static peek = { description: `\`SingleSelect\` is a dropdown list.`, notes: { overview: ` A dropdown list. When you click on the trigger a dropdown menu appears, allows you to choose one option, and execute relevant actions. `, intendedUse: ` Allow users to select one option from a list of 3-10 options. **Styling notes** - Use the default style in forms. The blue outline helps users clearly see that a selection has been made. - Use \`isSelectedHighlighted='false'\` if the default selection is All or a null state. See the \`no selection highlighting\` example. - Use \`isInvisible\` for filters within a full page table header. See the \`invisible\` example. `, technicalRecommendations: ` `, }, categories: ['controls', 'selectors'], madeFrom: ['DropMenu'], }; static defaultProps = defaultProps; static reducers = reducers; static Placeholder = Placeholder; static Option = Option; static Selected = Selected; static OptionGroup = OptionGroup; static NullOption = DropMenu.NullOption; static FixedOption = DropMenu.FixedOption; static propTypes = { /** Should be instances of: \`SingleSelect.Placeholder\`, \`SingleSelect.Option\`, \`SingleSelect.OptionGroup\`. Other direct child elements will not render. */ children: node, className: string /** Appended to the component-specific class names set on the root elements. Applies to *both* the control and the flyout menu. */, /** Styles that are passed through to root element. */ style: object, /** Applies primary color styling to the control when an item is selected. */ isSelectionHighlighted: bool, /** Allows user to reset the \`optionIndex\` to \`null\` if they select the placeholder at the top of the options list. If \`false\`, it will not render the placeholder in the menu. */ hasReset: bool, /** Disables the \`SingleSelect\` from being clicked or focused. */ isDisabled: bool, /** Gives the effect of an 'invisible button'. Essentially, there is no grey border, but there is still a blue border on a selection. */ isInvisible: bool, /** The currently selected \`SingleSelect.Option\` index or \`null\` if nothing is selected. */ selectedIndex: number, /** The max height of the fly-out menu. */ maxMenuHeight: oneOfType([number, string]), /** Show or hide the dropndown icon */ showIcon: bool, /** Object of \`DropMenu\` props which are passed thru to the underlying \`DropMenu\` component. */ DropMenu: shape(DropMenu.propTypes), /** Called when an option is selected. Has the signature \`(optionIndex, {props, event}) => {}\` where \`optionIndex\` is the new \`selectedIndex\` or \`null\` and \`props\` are the \`props\` for the selected \`Option\`. */ onSelect: func, Placeholder: any /** *Child Element* - The content rendered in the control when there is no option is selected. Also rendered in the option list to remove current selection. */, Option: any /** *Child Element* - A drop menu option. The \`optionIndex\` is in-order of rendering regardless of group nesting, starting with index \`0\`. Each \`Option\` may be passed a prop called \`isDisabled\` to disable selection of that \`Option\`. Any other props pass to Option will be available from the \`onSelect\` handler. */, OptionGroup: any /** *Child Element* - Used to group \`Option\`s within the menu. Any non-\`Option\`s passed in will be rendered as a label for the group. */, }; UNSAFE_componentWillMount() { // preprocess the options data before rendering const { optionGroups, flattenedOptionsData, ungroupedOptionData, optionGroupDataLookup, } = DropMenu.preprocessOptionData(this.props, SingleSelect); this.setState({ optionGroups, flattenedOptionsData, ungroupedOptionData, optionGroupDataLookup, }); } UNSAFE_componentWillReceiveProps(nextProps: ISingleSelectProps): void { // only preprocess options data when it changes (via new props) - better performance than doing this each render const { optionGroups, flattenedOptionsData, ungroupedOptionData, optionGroupDataLookup, } = DropMenu.preprocessOptionData(nextProps, SingleSelect); this.setState({ optionGroups, flattenedOptionsData, ungroupedOptionData, optionGroupDataLookup, }); } render(): React.ReactNode { const { style, className, hasReset, isDisabled, isInvisible, isSelectionHighlighted, selectedIndex, maxMenuHeight, onSelect, showIcon, DropMenu: dropMenuProps, } = this.props; const { direction, isExpanded, flyOutStyle } = dropMenuProps; const { optionGroups, optionGroupDataLookup, ungroupedOptionData, flattenedOptionsData, } = this.state; const placeholderProps = _.first( _.map(findTypes(this.props, SingleSelect.Placeholder), 'props') ); const placeholder = _.get(placeholderProps, 'children', 'Select'); const isItemSelected = _.isNumber(selectedIndex); const isHighlighted = (!isDisabled && isItemSelected && isSelectionHighlighted) || (isExpanded && isSelectionHighlighted); const isNullOptionSelected = selectedIndex === null; return ( <DropMenu {...dropMenuProps} isDisabled={isDisabled} selectedIndices={_.isNumber(selectedIndex) ? [selectedIndex] : []} className={cx('&', className)} onSelect={onSelect} style={style} flyOutStyle={_.assign( {}, flyOutStyle, !_.isNil(maxMenuHeight) ? { maxHeight: maxMenuHeight } : null )} ContextMenu={{ directonOffset: isNullOptionSelected ? -1 : 0 }} > <DropMenu.Control> <div tabIndex={0} className={cx('&-Control', { '&-Control-is-highlighted': isHighlighted, '&-Control-is-selected': isHighlighted, '&-Control-is-expanded': isExpanded, '&-Control-is-disabled': isDisabled, '&-Control-is-invisible': isInvisible, '&-Control-is-null-option': isNullOptionSelected, })} > <span {...(!isItemSelected ? placeholderProps : null)} className={cx( '&-Control-content', !isItemSelected ? _.get(placeholderProps, 'className') : null )} > {isItemSelected ? _.get( getFirst( flattenedOptionsData[selectedIndex as number].optionProps, SingleSelect.Option.Selected ), 'props.children' ) || flattenedOptionsData[selectedIndex as number].optionProps .children : placeholder} </span> {showIcon && ( <ChevronIcon size={12} direction={isExpanded ? direction : 'down'} /> )} </div> </DropMenu.Control> {hasReset && isItemSelected ? ( <DropMenu.NullOption {...placeholderProps}> {placeholder} </DropMenu.NullOption> ) : null} {_.map(optionGroups, (optionGroupProps, optionGroupIndex) => ( <DropMenu.OptionGroup key={'SingleSelectOptionGroup' + optionGroupIndex} {...optionGroupProps} > {optionGroupProps.children} {_.map( _.get(optionGroupDataLookup, optionGroupIndex), ({ optionProps, optionIndex }) => ( <DropMenu.Option key={'SingleSelectOption' + optionIndex} {..._.omit(optionProps, 'Selected')} /> ) )} </DropMenu.OptionGroup> )).concat( // then render all the ungrouped options at the end _.map(ungroupedOptionData, ({ optionProps, optionIndex }) => ( <DropMenu.Option key={'SingleSelectOption' + optionIndex} {..._.omit(optionProps, 'Selected')} /> )) )} </DropMenu> ); } } export default buildModernHybridComponent< ISingleSelectProps, ISingleSelectState, typeof SingleSelect >(SingleSelect as any, { reducers }); export { SingleSelect as SingleSelectDumb };
the_stack
import { Endpoints } from "@octokit/types"; export interface PaginatingEndpoints { /** * @see https://developer.github.com/v3/apps/#list-installations-for-the-authenticated-app */ "GET /app/installations": { parameters: Endpoints["GET /app/installations"]["parameters"]; response: Endpoints["GET /app/installations"]["response"]; }; /** * @see https://developer.github.com/v3/oauth_authorizations/#list-your-grants */ "GET /applications/grants": { parameters: Endpoints["GET /applications/grants"]["parameters"]; response: Endpoints["GET /applications/grants"]["response"]; }; /** * @see https://developer.github.com/v3/oauth_authorizations/#list-your-authorizations */ "GET /authorizations": { parameters: Endpoints["GET /authorizations"]["parameters"]; response: Endpoints["GET /authorizations"]["response"]; }; /** * @see https://developer.github.com/v3/enterprise-admin/actions/#list-self-hosted-runner-groups-for-an-enterprise */ "GET /enterprises/:enterprise/actions/runner-groups": { parameters: Endpoints["GET /enterprises/:enterprise/actions/runner-groups"]["parameters"]; response: Endpoints["GET /enterprises/:enterprise/actions/runner-groups"]["response"] & { data: Endpoints["GET /enterprises/:enterprise/actions/runner-groups"]["response"]["data"]["runner_groups"]; }; }; /** * @see https://developer.github.com/v3/enterprise-admin/actions/#list-organization-access-to-a-self-hosted-runner-group-in-a-enterprise */ "GET /enterprises/:enterprise/actions/runner-groups/:runner_group_id/organizations": { parameters: Endpoints["GET /enterprises/:enterprise/actions/runner-groups/:runner_group_id/organizations"]["parameters"]; response: Endpoints["GET /enterprises/:enterprise/actions/runner-groups/:runner_group_id/organizations"]["response"] & { data: Endpoints["GET /enterprises/:enterprise/actions/runner-groups/:runner_group_id/organizations"]["response"]["data"]["organizations"]; }; }; /** * @see https://developer.github.com/v3/enterprise-admin/actions/#list-self-hosted-runners-in-a-group-for-an-enterprise */ "GET /enterprises/:enterprise/actions/runner-groups/:runner_group_id/runners": { parameters: Endpoints["GET /enterprises/:enterprise/actions/runner-groups/:runner_group_id/runners"]["parameters"]; response: Endpoints["GET /enterprises/:enterprise/actions/runner-groups/:runner_group_id/runners"]["response"] & { data: Endpoints["GET /enterprises/:enterprise/actions/runner-groups/:runner_group_id/runners"]["response"]["data"]["runners"]; }; }; /** * @see https://developer.github.com/v3/enterprise-admin/actions/#list-self-hosted-runners-for-an-enterprise */ "GET /enterprises/:enterprise/actions/runners": { parameters: Endpoints["GET /enterprises/:enterprise/actions/runners"]["parameters"]; response: Endpoints["GET /enterprises/:enterprise/actions/runners"]["response"] & { data: Endpoints["GET /enterprises/:enterprise/actions/runners"]["response"]["data"]["runners"]; }; }; /** * @see https://developer.github.com/v3/enterprise-admin/actions/#list-runner-applications-for-an-enterprise */ "GET /enterprises/:enterprise/actions/runners/downloads": { parameters: Endpoints["GET /enterprises/:enterprise/actions/runners/downloads"]["parameters"]; response: Endpoints["GET /enterprises/:enterprise/actions/runners/downloads"]["response"]; }; /** * @see https://developer.github.com/v3/gists/#list-gists-for-the-authenticated-user */ "GET /gists": { parameters: Endpoints["GET /gists"]["parameters"]; response: Endpoints["GET /gists"]["response"]; }; /** * @see https://developer.github.com/v3/gists/comments/#list-gist-comments */ "GET /gists/:gist_id/comments": { parameters: Endpoints["GET /gists/:gist_id/comments"]["parameters"]; response: Endpoints["GET /gists/:gist_id/comments"]["response"]; }; /** * @see https://developer.github.com/v3/gists/#list-gist-commits */ "GET /gists/:gist_id/commits": { parameters: Endpoints["GET /gists/:gist_id/commits"]["parameters"]; response: Endpoints["GET /gists/:gist_id/commits"]["response"]; }; /** * @see https://developer.github.com/v3/gists/#list-gist-forks */ "GET /gists/:gist_id/forks": { parameters: Endpoints["GET /gists/:gist_id/forks"]["parameters"]; response: Endpoints["GET /gists/:gist_id/forks"]["response"]; }; /** * @see https://developer.github.com/v3/gists/#list-public-gists */ "GET /gists/public": { parameters: Endpoints["GET /gists/public"]["parameters"]; response: Endpoints["GET /gists/public"]["response"]; }; /** * @see https://developer.github.com/v3/gists/#list-starred-gists */ "GET /gists/starred": { parameters: Endpoints["GET /gists/starred"]["parameters"]; response: Endpoints["GET /gists/starred"]["response"]; }; /** * @see https://developer.github.com/v3/apps/installations/#list-repositories-accessible-to-the-app-installation */ "GET /installation/repositories": { parameters: Endpoints["GET /installation/repositories"]["parameters"]; response: Endpoints["GET /installation/repositories"]["response"] & { data: Endpoints["GET /installation/repositories"]["response"]["data"]["repositories"]; }; }; /** * @see https://developer.github.com/v3/issues/#list-issues-assigned-to-the-authenticated-user */ "GET /issues": { parameters: Endpoints["GET /issues"]["parameters"]; response: Endpoints["GET /issues"]["response"]; }; /** * @see https://developer.github.com/v3/apps/marketplace/#list-plans */ "GET /marketplace_listing/plans": { parameters: Endpoints["GET /marketplace_listing/plans"]["parameters"]; response: Endpoints["GET /marketplace_listing/plans"]["response"]; }; /** * @see https://developer.github.com/v3/apps/marketplace/#list-accounts-for-a-plan */ "GET /marketplace_listing/plans/:plan_id/accounts": { parameters: Endpoints["GET /marketplace_listing/plans/:plan_id/accounts"]["parameters"]; response: Endpoints["GET /marketplace_listing/plans/:plan_id/accounts"]["response"]; }; /** * @see https://developer.github.com/v3/apps/marketplace/#list-plans-stubbed */ "GET /marketplace_listing/stubbed/plans": { parameters: Endpoints["GET /marketplace_listing/stubbed/plans"]["parameters"]; response: Endpoints["GET /marketplace_listing/stubbed/plans"]["response"]; }; /** * @see https://developer.github.com/v3/apps/marketplace/#list-accounts-for-a-plan-stubbed */ "GET /marketplace_listing/stubbed/plans/:plan_id/accounts": { parameters: Endpoints["GET /marketplace_listing/stubbed/plans/:plan_id/accounts"]["parameters"]; response: Endpoints["GET /marketplace_listing/stubbed/plans/:plan_id/accounts"]["response"]; }; /** * @see https://developer.github.com/v3/activity/notifications/#list-notifications-for-the-authenticated-user */ "GET /notifications": { parameters: Endpoints["GET /notifications"]["parameters"]; response: Endpoints["GET /notifications"]["response"]; }; /** * @see https://developer.github.com/v3/orgs/#list-organizations */ "GET /organizations": { parameters: Endpoints["GET /organizations"]["parameters"]; response: Endpoints["GET /organizations"]["response"]; }; /** * @see https://developer.github.com/v3/actions/self-hosted-runner-groups/#list-self-hosted-runner-groups-for-an-organization */ "GET /orgs/:org/actions/runner-groups": { parameters: Endpoints["GET /orgs/:org/actions/runner-groups"]["parameters"]; response: Endpoints["GET /orgs/:org/actions/runner-groups"]["response"] & { data: Endpoints["GET /orgs/:org/actions/runner-groups"]["response"]["data"]["runner_groups"]; }; }; /** * @see https://developer.github.com/v3/actions/self-hosted-runner-groups/#list-repository-access-to-a-self-hosted-runner-group-in-an-organization */ "GET /orgs/:org/actions/runner-groups/:runner_group_id/repositories": { parameters: Endpoints["GET /orgs/:org/actions/runner-groups/:runner_group_id/repositories"]["parameters"]; response: Endpoints["GET /orgs/:org/actions/runner-groups/:runner_group_id/repositories"]["response"] & { data: Endpoints["GET /orgs/:org/actions/runner-groups/:runner_group_id/repositories"]["response"]["data"]["repositories"]; }; }; /** * @see https://developer.github.com/v3/actions/self-hosted-runner-groups/#list-self-hosted-runners-in-a-group-for-an-organization */ "GET /orgs/:org/actions/runner-groups/:runner_group_id/runners": { parameters: Endpoints["GET /orgs/:org/actions/runner-groups/:runner_group_id/runners"]["parameters"]; response: Endpoints["GET /orgs/:org/actions/runner-groups/:runner_group_id/runners"]["response"] & { data: Endpoints["GET /orgs/:org/actions/runner-groups/:runner_group_id/runners"]["response"]["data"]["runners"]; }; }; /** * @see https://developer.github.com/v3/actions/self-hosted-runners/#list-self-hosted-runners-for-an-organization */ "GET /orgs/:org/actions/runners": { parameters: Endpoints["GET /orgs/:org/actions/runners"]["parameters"]; response: Endpoints["GET /orgs/:org/actions/runners"]["response"] & { data: Endpoints["GET /orgs/:org/actions/runners"]["response"]["data"]["runners"]; }; }; /** * @see https://developer.github.com/v3/actions/self-hosted-runners/#list-runner-applications-for-an-organization */ "GET /orgs/:org/actions/runners/downloads": { parameters: Endpoints["GET /orgs/:org/actions/runners/downloads"]["parameters"]; response: Endpoints["GET /orgs/:org/actions/runners/downloads"]["response"]; }; /** * @see https://developer.github.com/v3/actions/secrets/#list-organization-secrets */ "GET /orgs/:org/actions/secrets": { parameters: Endpoints["GET /orgs/:org/actions/secrets"]["parameters"]; response: Endpoints["GET /orgs/:org/actions/secrets"]["response"] & { data: Endpoints["GET /orgs/:org/actions/secrets"]["response"]["data"]["secrets"]; }; }; /** * @see https://developer.github.com/v3/actions/secrets/#list-selected-repositories-for-an-organization-secret */ "GET /orgs/:org/actions/secrets/:secret_name/repositories": { parameters: Endpoints["GET /orgs/:org/actions/secrets/:secret_name/repositories"]["parameters"]; response: Endpoints["GET /orgs/:org/actions/secrets/:secret_name/repositories"]["response"] & { data: Endpoints["GET /orgs/:org/actions/secrets/:secret_name/repositories"]["response"]["data"]["repositories"]; }; }; /** * @see https://developer.github.com/v3/orgs/blocking/#list-users-blocked-by-an-organization */ "GET /orgs/:org/blocks": { parameters: Endpoints["GET /orgs/:org/blocks"]["parameters"]; response: Endpoints["GET /orgs/:org/blocks"]["response"]; }; /** * @see https://developer.github.com/v3/orgs/#list-saml-sso-authorizations-for-an-organization */ "GET /orgs/:org/credential-authorizations": { parameters: Endpoints["GET /orgs/:org/credential-authorizations"]["parameters"]; response: Endpoints["GET /orgs/:org/credential-authorizations"]["response"]; }; /** * @see https://developer.github.com/v3/orgs/hooks/#list-organization-webhooks */ "GET /orgs/:org/hooks": { parameters: Endpoints["GET /orgs/:org/hooks"]["parameters"]; response: Endpoints["GET /orgs/:org/hooks"]["response"]; }; /** * @see https://developer.github.com/v3/orgs/#list-app-installations-for-an-organization */ "GET /orgs/:org/installations": { parameters: Endpoints["GET /orgs/:org/installations"]["parameters"]; response: Endpoints["GET /orgs/:org/installations"]["response"] & { data: Endpoints["GET /orgs/:org/installations"]["response"]["data"]["installations"]; }; }; /** * @see https://developer.github.com/v3/orgs/members/#list-pending-organization-invitations */ "GET /orgs/:org/invitations": { parameters: Endpoints["GET /orgs/:org/invitations"]["parameters"]; response: Endpoints["GET /orgs/:org/invitations"]["response"]; }; /** * @see https://developer.github.com/v3/orgs/members/#list-organization-invitation-teams */ "GET /orgs/:org/invitations/:invitation_id/teams": { parameters: Endpoints["GET /orgs/:org/invitations/:invitation_id/teams"]["parameters"]; response: Endpoints["GET /orgs/:org/invitations/:invitation_id/teams"]["response"]; }; /** * @see https://developer.github.com/v3/issues/#list-organization-issues-assigned-to-the-authenticated-user */ "GET /orgs/:org/issues": { parameters: Endpoints["GET /orgs/:org/issues"]["parameters"]; response: Endpoints["GET /orgs/:org/issues"]["response"]; }; /** * @see https://developer.github.com/v3/orgs/members/#list-organization-members */ "GET /orgs/:org/members": { parameters: Endpoints["GET /orgs/:org/members"]["parameters"]; response: Endpoints["GET /orgs/:org/members"]["response"]; }; /** * @see https://developer.github.com/v3/migrations/orgs/#list-organization-migrations */ "GET /orgs/:org/migrations": { parameters: Endpoints["GET /orgs/:org/migrations"]["parameters"]; response: Endpoints["GET /orgs/:org/migrations"]["response"]; }; /** * @see https://developer.github.com/v3/migrations/orgs/#list-repositories-in-an-organization-migration */ "GET /orgs/:org/migrations/:migration_id/repositories": { parameters: Endpoints["GET /orgs/:org/migrations/:migration_id/repositories"]["parameters"]; response: Endpoints["GET /orgs/:org/migrations/:migration_id/repositories"]["response"]; }; /** * @see https://developer.github.com/v3/orgs/outside_collaborators/#list-outside-collaborators-for-an-organization */ "GET /orgs/:org/outside_collaborators": { parameters: Endpoints["GET /orgs/:org/outside_collaborators"]["parameters"]; response: Endpoints["GET /orgs/:org/outside_collaborators"]["response"]; }; /** * @see https://developer.github.com/v3/projects/#list-organization-projects */ "GET /orgs/:org/projects": { parameters: Endpoints["GET /orgs/:org/projects"]["parameters"]; response: Endpoints["GET /orgs/:org/projects"]["response"]; }; /** * @see https://developer.github.com/v3/orgs/members/#list-public-organization-members */ "GET /orgs/:org/public_members": { parameters: Endpoints["GET /orgs/:org/public_members"]["parameters"]; response: Endpoints["GET /orgs/:org/public_members"]["response"]; }; /** * @see https://developer.github.com/v3/repos/#list-organization-repositories */ "GET /orgs/:org/repos": { parameters: Endpoints["GET /orgs/:org/repos"]["parameters"]; response: Endpoints["GET /orgs/:org/repos"]["response"]; }; /** * @see https://developer.github.com/v3/teams/team_sync/#list-idp-groups-for-an-organization */ "GET /orgs/:org/team-sync/groups": { parameters: Endpoints["GET /orgs/:org/team-sync/groups"]["parameters"]; response: Endpoints["GET /orgs/:org/team-sync/groups"]["response"] & { data: Endpoints["GET /orgs/:org/team-sync/groups"]["response"]["data"]["groups"]; }; }; /** * @see https://developer.github.com/v3/teams/#list-teams */ "GET /orgs/:org/teams": { parameters: Endpoints["GET /orgs/:org/teams"]["parameters"]; response: Endpoints["GET /orgs/:org/teams"]["response"]; }; /** * @see https://developer.github.com/v3/teams/discussions/#list-discussions */ "GET /orgs/:org/teams/:team_slug/discussions": { parameters: Endpoints["GET /orgs/:org/teams/:team_slug/discussions"]["parameters"]; response: Endpoints["GET /orgs/:org/teams/:team_slug/discussions"]["response"]; }; /** * @see https://developer.github.com/v3/teams/discussion_comments/#list-discussion-comments */ "GET /orgs/:org/teams/:team_slug/discussions/:discussion_number/comments": { parameters: Endpoints["GET /orgs/:org/teams/:team_slug/discussions/:discussion_number/comments"]["parameters"]; response: Endpoints["GET /orgs/:org/teams/:team_slug/discussions/:discussion_number/comments"]["response"]; }; /** * @see https://developer.github.com/v3/reactions/#list-reactions-for-a-team-discussion-comment */ "GET /orgs/:org/teams/:team_slug/discussions/:discussion_number/comments/:comment_number/reactions": { parameters: Endpoints["GET /orgs/:org/teams/:team_slug/discussions/:discussion_number/comments/:comment_number/reactions"]["parameters"]; response: Endpoints["GET /orgs/:org/teams/:team_slug/discussions/:discussion_number/comments/:comment_number/reactions"]["response"]; }; /** * @see https://developer.github.com/v3/reactions/#list-reactions-for-a-team-discussion */ "GET /orgs/:org/teams/:team_slug/discussions/:discussion_number/reactions": { parameters: Endpoints["GET /orgs/:org/teams/:team_slug/discussions/:discussion_number/reactions"]["parameters"]; response: Endpoints["GET /orgs/:org/teams/:team_slug/discussions/:discussion_number/reactions"]["response"]; }; /** * @see https://developer.github.com/v3/teams/members/#list-pending-team-invitations */ "GET /orgs/:org/teams/:team_slug/invitations": { parameters: Endpoints["GET /orgs/:org/teams/:team_slug/invitations"]["parameters"]; response: Endpoints["GET /orgs/:org/teams/:team_slug/invitations"]["response"]; }; /** * @see https://developer.github.com/v3/teams/members/#list-team-members */ "GET /orgs/:org/teams/:team_slug/members": { parameters: Endpoints["GET /orgs/:org/teams/:team_slug/members"]["parameters"]; response: Endpoints["GET /orgs/:org/teams/:team_slug/members"]["response"]; }; /** * @see https://developer.github.com/v3/teams/#list-team-projects */ "GET /orgs/:org/teams/:team_slug/projects": { parameters: Endpoints["GET /orgs/:org/teams/:team_slug/projects"]["parameters"]; response: Endpoints["GET /orgs/:org/teams/:team_slug/projects"]["response"]; }; /** * @see https://developer.github.com/v3/teams/#list-team-repositories */ "GET /orgs/:org/teams/:team_slug/repos": { parameters: Endpoints["GET /orgs/:org/teams/:team_slug/repos"]["parameters"]; response: Endpoints["GET /orgs/:org/teams/:team_slug/repos"]["response"]; }; /** * @see https://developer.github.com/v3/teams/team_sync/#list-idp-groups-for-a-team */ "GET /orgs/:org/teams/:team_slug/team-sync/group-mappings": { parameters: Endpoints["GET /orgs/:org/teams/:team_slug/team-sync/group-mappings"]["parameters"]; response: Endpoints["GET /orgs/:org/teams/:team_slug/team-sync/group-mappings"]["response"] & { data: Endpoints["GET /orgs/:org/teams/:team_slug/team-sync/group-mappings"]["response"]["data"]["groups"]; }; }; /** * @see https://developer.github.com/v3/teams/#list-child-teams */ "GET /orgs/:org/teams/:team_slug/teams": { parameters: Endpoints["GET /orgs/:org/teams/:team_slug/teams"]["parameters"]; response: Endpoints["GET /orgs/:org/teams/:team_slug/teams"]["response"]; }; /** * @see https://developer.github.com/v3/projects/collaborators/#list-project-collaborators */ "GET /projects/:project_id/collaborators": { parameters: Endpoints["GET /projects/:project_id/collaborators"]["parameters"]; response: Endpoints["GET /projects/:project_id/collaborators"]["response"]; }; /** * @see https://developer.github.com/v3/projects/columns/#list-project-columns */ "GET /projects/:project_id/columns": { parameters: Endpoints["GET /projects/:project_id/columns"]["parameters"]; response: Endpoints["GET /projects/:project_id/columns"]["response"]; }; /** * @see https://developer.github.com/v3/projects/cards/#list-project-cards */ "GET /projects/columns/:column_id/cards": { parameters: Endpoints["GET /projects/columns/:column_id/cards"]["parameters"]; response: Endpoints["GET /projects/columns/:column_id/cards"]["response"]; }; /** * @see https://developer.github.com/v3/actions/artifacts/#list-artifacts-for-a-repository */ "GET /repos/:owner/:repo/actions/artifacts": { parameters: Endpoints["GET /repos/:owner/:repo/actions/artifacts"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/actions/artifacts"]["response"] & { data: Endpoints["GET /repos/:owner/:repo/actions/artifacts"]["response"]["data"]["artifacts"]; }; }; /** * @see https://developer.github.com/v3/actions/self-hosted-runners/#list-self-hosted-runners-for-a-repository */ "GET /repos/:owner/:repo/actions/runners": { parameters: Endpoints["GET /repos/:owner/:repo/actions/runners"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/actions/runners"]["response"] & { data: Endpoints["GET /repos/:owner/:repo/actions/runners"]["response"]["data"]["runners"]; }; }; /** * @see https://developer.github.com/v3/actions/self-hosted-runners/#list-runner-applications-for-a-repository */ "GET /repos/:owner/:repo/actions/runners/downloads": { parameters: Endpoints["GET /repos/:owner/:repo/actions/runners/downloads"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/actions/runners/downloads"]["response"]; }; /** * @see https://developer.github.com/v3/actions/workflow-runs/#list-workflow-runs-for-a-repository */ "GET /repos/:owner/:repo/actions/runs": { parameters: Endpoints["GET /repos/:owner/:repo/actions/runs"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/actions/runs"]["response"] & { data: Endpoints["GET /repos/:owner/:repo/actions/runs"]["response"]["data"]["workflow_runs"]; }; }; /** * @see https://developer.github.com/v3/actions/artifacts/#list-workflow-run-artifacts */ "GET /repos/:owner/:repo/actions/runs/:run_id/artifacts": { parameters: Endpoints["GET /repos/:owner/:repo/actions/runs/:run_id/artifacts"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/actions/runs/:run_id/artifacts"]["response"] & { data: Endpoints["GET /repos/:owner/:repo/actions/runs/:run_id/artifacts"]["response"]["data"]["artifacts"]; }; }; /** * @see https://developer.github.com/v3/actions/workflow-jobs/#list-jobs-for-a-workflow-run */ "GET /repos/:owner/:repo/actions/runs/:run_id/jobs": { parameters: Endpoints["GET /repos/:owner/:repo/actions/runs/:run_id/jobs"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/actions/runs/:run_id/jobs"]["response"] & { data: Endpoints["GET /repos/:owner/:repo/actions/runs/:run_id/jobs"]["response"]["data"]["jobs"]; }; }; /** * @see https://developer.github.com/v3/actions/secrets/#list-repository-secrets */ "GET /repos/:owner/:repo/actions/secrets": { parameters: Endpoints["GET /repos/:owner/:repo/actions/secrets"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/actions/secrets"]["response"] & { data: Endpoints["GET /repos/:owner/:repo/actions/secrets"]["response"]["data"]["secrets"]; }; }; /** * @see https://developer.github.com/v3/actions/workflows/#list-repository-workflows */ "GET /repos/:owner/:repo/actions/workflows": { parameters: Endpoints["GET /repos/:owner/:repo/actions/workflows"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/actions/workflows"]["response"] & { data: Endpoints["GET /repos/:owner/:repo/actions/workflows"]["response"]["data"]["workflows"]; }; }; /** * @see https://developer.github.com/v3/actions/workflow-runs/#list-workflow-runs */ "GET /repos/:owner/:repo/actions/workflows/:workflow_id/runs": { parameters: Endpoints["GET /repos/:owner/:repo/actions/workflows/:workflow_id/runs"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/actions/workflows/:workflow_id/runs"]["response"] & { data: Endpoints["GET /repos/:owner/:repo/actions/workflows/:workflow_id/runs"]["response"]["data"]["workflow_runs"]; }; }; /** * @see https://developer.github.com/v3/issues/assignees/#list-assignees */ "GET /repos/:owner/:repo/assignees": { parameters: Endpoints["GET /repos/:owner/:repo/assignees"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/assignees"]["response"]; }; /** * @see https://developer.github.com/v3/repos/branches/#list-branches */ "GET /repos/:owner/:repo/branches": { parameters: Endpoints["GET /repos/:owner/:repo/branches"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/branches"]["response"]; }; /** * @see https://developer.github.com/v3/checks/runs/#list-check-run-annotations */ "GET /repos/:owner/:repo/check-runs/:check_run_id/annotations": { parameters: Endpoints["GET /repos/:owner/:repo/check-runs/:check_run_id/annotations"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/check-runs/:check_run_id/annotations"]["response"]; }; /** * @see https://developer.github.com/v3/checks/runs/#list-check-runs-in-a-check-suite */ "GET /repos/:owner/:repo/check-suites/:check_suite_id/check-runs": { parameters: Endpoints["GET /repos/:owner/:repo/check-suites/:check_suite_id/check-runs"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/check-suites/:check_suite_id/check-runs"]["response"] & { data: Endpoints["GET /repos/:owner/:repo/check-suites/:check_suite_id/check-runs"]["response"]["data"]["check_runs"]; }; }; /** * @see https://developer.github.com/v3/code-scanning/#list-code-scanning-alerts-for-a-repository */ "GET /repos/:owner/:repo/code-scanning/alerts": { parameters: Endpoints["GET /repos/:owner/:repo/code-scanning/alerts"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/code-scanning/alerts"]["response"]; }; /** * @see https://developer.github.com/v3/repos/collaborators/#list-repository-collaborators */ "GET /repos/:owner/:repo/collaborators": { parameters: Endpoints["GET /repos/:owner/:repo/collaborators"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/collaborators"]["response"]; }; /** * @see https://developer.github.com/v3/repos/comments/#list-commit-comments-for-a-repository */ "GET /repos/:owner/:repo/comments": { parameters: Endpoints["GET /repos/:owner/:repo/comments"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/comments"]["response"]; }; /** * @see https://developer.github.com/v3/reactions/#list-reactions-for-a-commit-comment */ "GET /repos/:owner/:repo/comments/:comment_id/reactions": { parameters: Endpoints["GET /repos/:owner/:repo/comments/:comment_id/reactions"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/comments/:comment_id/reactions"]["response"]; }; /** * @see https://developer.github.com/v3/repos/commits/#list-commits */ "GET /repos/:owner/:repo/commits": { parameters: Endpoints["GET /repos/:owner/:repo/commits"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/commits"]["response"]; }; /** * @see https://developer.github.com/v3/repos/commits/#list-branches-for-head-commit */ "GET /repos/:owner/:repo/commits/:commit_sha/branches-where-head": { parameters: Endpoints["GET /repos/:owner/:repo/commits/:commit_sha/branches-where-head"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/commits/:commit_sha/branches-where-head"]["response"]; }; /** * @see https://developer.github.com/v3/repos/comments/#list-commit-comments */ "GET /repos/:owner/:repo/commits/:commit_sha/comments": { parameters: Endpoints["GET /repos/:owner/:repo/commits/:commit_sha/comments"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/commits/:commit_sha/comments"]["response"]; }; /** * @see https://developer.github.com/v3/repos/commits/#list-pull-requests-associated-with-a-commit */ "GET /repos/:owner/:repo/commits/:commit_sha/pulls": { parameters: Endpoints["GET /repos/:owner/:repo/commits/:commit_sha/pulls"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/commits/:commit_sha/pulls"]["response"]; }; /** * @see https://developer.github.com/v3/checks/runs/#list-check-runs-for-a-git-reference */ "GET /repos/:owner/:repo/commits/:ref/check-runs": { parameters: Endpoints["GET /repos/:owner/:repo/commits/:ref/check-runs"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/commits/:ref/check-runs"]["response"] & { data: Endpoints["GET /repos/:owner/:repo/commits/:ref/check-runs"]["response"]["data"]["check_runs"]; }; }; /** * @see https://developer.github.com/v3/checks/suites/#list-check-suites-for-a-git-reference */ "GET /repos/:owner/:repo/commits/:ref/check-suites": { parameters: Endpoints["GET /repos/:owner/:repo/commits/:ref/check-suites"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/commits/:ref/check-suites"]["response"] & { data: Endpoints["GET /repos/:owner/:repo/commits/:ref/check-suites"]["response"]["data"]["check_suites"]; }; }; /** * @see https://developer.github.com/v3/repos/statuses/#list-commit-statuses-for-a-reference */ "GET /repos/:owner/:repo/commits/:ref/statuses": { parameters: Endpoints["GET /repos/:owner/:repo/commits/:ref/statuses"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/commits/:ref/statuses"]["response"]; }; /** * @see https://developer.github.com/v3/repos/#list-repository-contributors */ "GET /repos/:owner/:repo/contributors": { parameters: Endpoints["GET /repos/:owner/:repo/contributors"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/contributors"]["response"]; }; /** * @see https://developer.github.com/v3/repos/deployments/#list-deployments */ "GET /repos/:owner/:repo/deployments": { parameters: Endpoints["GET /repos/:owner/:repo/deployments"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/deployments"]["response"]; }; /** * @see https://developer.github.com/v3/repos/deployments/#list-deployment-statuses */ "GET /repos/:owner/:repo/deployments/:deployment_id/statuses": { parameters: Endpoints["GET /repos/:owner/:repo/deployments/:deployment_id/statuses"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/deployments/:deployment_id/statuses"]["response"]; }; /** * @see https://developer.github.com/v3/repos/forks/#list-forks */ "GET /repos/:owner/:repo/forks": { parameters: Endpoints["GET /repos/:owner/:repo/forks"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/forks"]["response"]; }; /** * @see https://developer.github.com/v3/git/refs/#list-matching-references */ "GET /repos/:owner/:repo/git/matching-refs/:ref": { parameters: Endpoints["GET /repos/:owner/:repo/git/matching-refs/:ref"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/git/matching-refs/:ref"]["response"]; }; /** * @see https://developer.github.com/v3/repos/hooks/#list-repository-webhooks */ "GET /repos/:owner/:repo/hooks": { parameters: Endpoints["GET /repos/:owner/:repo/hooks"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/hooks"]["response"]; }; /** * @see https://developer.github.com/v3/repos/invitations/#list-repository-invitations */ "GET /repos/:owner/:repo/invitations": { parameters: Endpoints["GET /repos/:owner/:repo/invitations"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/invitations"]["response"]; }; /** * @see https://developer.github.com/v3/issues/#list-repository-issues */ "GET /repos/:owner/:repo/issues": { parameters: Endpoints["GET /repos/:owner/:repo/issues"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/issues"]["response"]; }; /** * @see https://developer.github.com/v3/issues/comments/#list-issue-comments */ "GET /repos/:owner/:repo/issues/:issue_number/comments": { parameters: Endpoints["GET /repos/:owner/:repo/issues/:issue_number/comments"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/issues/:issue_number/comments"]["response"]; }; /** * @see https://developer.github.com/v3/issues/events/#list-issue-events */ "GET /repos/:owner/:repo/issues/:issue_number/events": { parameters: Endpoints["GET /repos/:owner/:repo/issues/:issue_number/events"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/issues/:issue_number/events"]["response"]; }; /** * @see https://developer.github.com/v3/issues/labels/#list-labels-for-an-issue */ "GET /repos/:owner/:repo/issues/:issue_number/labels": { parameters: Endpoints["GET /repos/:owner/:repo/issues/:issue_number/labels"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/issues/:issue_number/labels"]["response"]; }; /** * @see https://developer.github.com/v3/reactions/#list-reactions-for-an-issue */ "GET /repos/:owner/:repo/issues/:issue_number/reactions": { parameters: Endpoints["GET /repos/:owner/:repo/issues/:issue_number/reactions"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/issues/:issue_number/reactions"]["response"]; }; /** * @see https://developer.github.com/v3/issues/timeline/#list-timeline-events-for-an-issue */ "GET /repos/:owner/:repo/issues/:issue_number/timeline": { parameters: Endpoints["GET /repos/:owner/:repo/issues/:issue_number/timeline"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/issues/:issue_number/timeline"]["response"]; }; /** * @see https://developer.github.com/v3/issues/comments/#list-issue-comments-for-a-repository */ "GET /repos/:owner/:repo/issues/comments": { parameters: Endpoints["GET /repos/:owner/:repo/issues/comments"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/issues/comments"]["response"]; }; /** * @see https://developer.github.com/v3/reactions/#list-reactions-for-an-issue-comment */ "GET /repos/:owner/:repo/issues/comments/:comment_id/reactions": { parameters: Endpoints["GET /repos/:owner/:repo/issues/comments/:comment_id/reactions"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/issues/comments/:comment_id/reactions"]["response"]; }; /** * @see https://developer.github.com/v3/issues/events/#list-issue-events-for-a-repository */ "GET /repos/:owner/:repo/issues/events": { parameters: Endpoints["GET /repos/:owner/:repo/issues/events"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/issues/events"]["response"]; }; /** * @see https://developer.github.com/v3/repos/keys/#list-deploy-keys */ "GET /repos/:owner/:repo/keys": { parameters: Endpoints["GET /repos/:owner/:repo/keys"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/keys"]["response"]; }; /** * @see https://developer.github.com/v3/issues/labels/#list-labels-for-a-repository */ "GET /repos/:owner/:repo/labels": { parameters: Endpoints["GET /repos/:owner/:repo/labels"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/labels"]["response"]; }; /** * @see https://developer.github.com/v3/repos/#list-repository-languages */ "GET /repos/:owner/:repo/languages": { parameters: Endpoints["GET /repos/:owner/:repo/languages"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/languages"]["response"]; }; /** * @see https://developer.github.com/v3/issues/milestones/#list-milestones */ "GET /repos/:owner/:repo/milestones": { parameters: Endpoints["GET /repos/:owner/:repo/milestones"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/milestones"]["response"]; }; /** * @see https://developer.github.com/v3/issues/labels/#list-labels-for-issues-in-a-milestone */ "GET /repos/:owner/:repo/milestones/:milestone_number/labels": { parameters: Endpoints["GET /repos/:owner/:repo/milestones/:milestone_number/labels"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/milestones/:milestone_number/labels"]["response"]; }; /** * @see https://developer.github.com/v3/activity/notifications/#list-repository-notifications-for-the-authenticated-user */ "GET /repos/:owner/:repo/notifications": { parameters: Endpoints["GET /repos/:owner/:repo/notifications"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/notifications"]["response"]; }; /** * @see https://developer.github.com/v3/repos/pages/#list-github-pages-builds */ "GET /repos/:owner/:repo/pages/builds": { parameters: Endpoints["GET /repos/:owner/:repo/pages/builds"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/pages/builds"]["response"]; }; /** * @see https://developer.github.com/v3/projects/#list-repository-projects */ "GET /repos/:owner/:repo/projects": { parameters: Endpoints["GET /repos/:owner/:repo/projects"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/projects"]["response"]; }; /** * @see https://developer.github.com/v3/pulls/#list-pull-requests */ "GET /repos/:owner/:repo/pulls": { parameters: Endpoints["GET /repos/:owner/:repo/pulls"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/pulls"]["response"]; }; /** * @see https://developer.github.com/v3/pulls/comments/#list-review-comments-on-a-pull-request */ "GET /repos/:owner/:repo/pulls/:pull_number/comments": { parameters: Endpoints["GET /repos/:owner/:repo/pulls/:pull_number/comments"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/pulls/:pull_number/comments"]["response"]; }; /** * @see https://developer.github.com/v3/pulls/#list-commits-on-a-pull-request */ "GET /repos/:owner/:repo/pulls/:pull_number/commits": { parameters: Endpoints["GET /repos/:owner/:repo/pulls/:pull_number/commits"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/pulls/:pull_number/commits"]["response"]; }; /** * @see https://developer.github.com/v3/pulls/#list-pull-requests-files */ "GET /repos/:owner/:repo/pulls/:pull_number/files": { parameters: Endpoints["GET /repos/:owner/:repo/pulls/:pull_number/files"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/pulls/:pull_number/files"]["response"]; }; /** * @see https://developer.github.com/v3/pulls/review_requests/#list-requested-reviewers-for-a-pull-request */ "GET /repos/:owner/:repo/pulls/:pull_number/requested_reviewers": { parameters: Endpoints["GET /repos/:owner/:repo/pulls/:pull_number/requested_reviewers"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/pulls/:pull_number/requested_reviewers"]["response"] & { data: Endpoints["GET /repos/:owner/:repo/pulls/:pull_number/requested_reviewers"]["response"]["data"]["users"]; }; }; /** * @see https://developer.github.com/v3/pulls/reviews/#list-reviews-for-a-pull-request */ "GET /repos/:owner/:repo/pulls/:pull_number/reviews": { parameters: Endpoints["GET /repos/:owner/:repo/pulls/:pull_number/reviews"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/pulls/:pull_number/reviews"]["response"]; }; /** * @see https://developer.github.com/v3/pulls/reviews/#list-comments-for-a-pull-request-review */ "GET /repos/:owner/:repo/pulls/:pull_number/reviews/:review_id/comments": { parameters: Endpoints["GET /repos/:owner/:repo/pulls/:pull_number/reviews/:review_id/comments"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/pulls/:pull_number/reviews/:review_id/comments"]["response"]; }; /** * @see https://developer.github.com/v3/pulls/comments/#list-review-comments-in-a-repository */ "GET /repos/:owner/:repo/pulls/comments": { parameters: Endpoints["GET /repos/:owner/:repo/pulls/comments"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/pulls/comments"]["response"]; }; /** * @see https://developer.github.com/v3/reactions/#list-reactions-for-a-pull-request-review-comment */ "GET /repos/:owner/:repo/pulls/comments/:comment_id/reactions": { parameters: Endpoints["GET /repos/:owner/:repo/pulls/comments/:comment_id/reactions"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/pulls/comments/:comment_id/reactions"]["response"]; }; /** * @see https://developer.github.com/v3/repos/releases/#list-releases */ "GET /repos/:owner/:repo/releases": { parameters: Endpoints["GET /repos/:owner/:repo/releases"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/releases"]["response"]; }; /** * @see https://developer.github.com/v3/repos/releases/#list-release-assets */ "GET /repos/:owner/:repo/releases/:release_id/assets": { parameters: Endpoints["GET /repos/:owner/:repo/releases/:release_id/assets"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/releases/:release_id/assets"]["response"]; }; /** * @see https://developer.github.com/v3/activity/starring/#list-stargazers */ "GET /repos/:owner/:repo/stargazers": { parameters: Endpoints["GET /repos/:owner/:repo/stargazers"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/stargazers"]["response"]; }; /** * @see https://developer.github.com/v3/activity/watching/#list-watchers */ "GET /repos/:owner/:repo/subscribers": { parameters: Endpoints["GET /repos/:owner/:repo/subscribers"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/subscribers"]["response"]; }; /** * @see https://developer.github.com/v3/repos/#list-repository-tags */ "GET /repos/:owner/:repo/tags": { parameters: Endpoints["GET /repos/:owner/:repo/tags"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/tags"]["response"]; }; /** * @see https://developer.github.com/v3/repos/#list-repository-teams */ "GET /repos/:owner/:repo/teams": { parameters: Endpoints["GET /repos/:owner/:repo/teams"]["parameters"]; response: Endpoints["GET /repos/:owner/:repo/teams"]["response"]; }; /** * @see https://developer.github.com/v3/repos/#list-public-repositories */ "GET /repositories": { parameters: Endpoints["GET /repositories"]["parameters"]; response: Endpoints["GET /repositories"]["response"]; }; /** * @see https://developer.github.com/v3/enterprise-admin/scim/#list-provisioned-scim groups-for-an-enterprise */ "GET /scim/v2/enterprises/:enterprise/Groups": { parameters: Endpoints["GET /scim/v2/enterprises/:enterprise/Groups"]["parameters"]; response: Endpoints["GET /scim/v2/enterprises/:enterprise/Groups"]["response"] & { data: Endpoints["GET /scim/v2/enterprises/:enterprise/Groups"]["response"]["data"]["schemas"]; }; }; /** * @see https://developer.github.com/v3/enterprise-admin/scim/#list-scim-provisioned-identities-for-an-enterprise */ "GET /scim/v2/enterprises/:enterprise/Users": { parameters: Endpoints["GET /scim/v2/enterprises/:enterprise/Users"]["parameters"]; response: Endpoints["GET /scim/v2/enterprises/:enterprise/Users"]["response"] & { data: Endpoints["GET /scim/v2/enterprises/:enterprise/Users"]["response"]["data"]["schemas"]; }; }; /** * @see https://developer.github.com/v3/scim/#list-scim-provisioned-identities */ "GET /scim/v2/organizations/:org/Users": { parameters: Endpoints["GET /scim/v2/organizations/:org/Users"]["parameters"]; response: Endpoints["GET /scim/v2/organizations/:org/Users"]["response"] & { data: Endpoints["GET /scim/v2/organizations/:org/Users"]["response"]["data"]["schemas"]; }; }; /** * @see https://developer.github.com/v3/search/#search-code */ "GET /search/code": { parameters: Endpoints["GET /search/code"]["parameters"]; response: Endpoints["GET /search/code"]["response"] & { data: Endpoints["GET /search/code"]["response"]["data"]["items"]; }; }; /** * @see https://developer.github.com/v3/search/#search-commits */ "GET /search/commits": { parameters: Endpoints["GET /search/commits"]["parameters"]; response: Endpoints["GET /search/commits"]["response"] & { data: Endpoints["GET /search/commits"]["response"]["data"]["items"]; }; }; /** * @see https://developer.github.com/v3/search/#search-issues-and-pull-requests */ "GET /search/issues": { parameters: Endpoints["GET /search/issues"]["parameters"]; response: Endpoints["GET /search/issues"]["response"] & { data: Endpoints["GET /search/issues"]["response"]["data"]["items"]; }; }; /** * @see https://developer.github.com/v3/search/#search-labels */ "GET /search/labels": { parameters: Endpoints["GET /search/labels"]["parameters"]; response: Endpoints["GET /search/labels"]["response"] & { data: Endpoints["GET /search/labels"]["response"]["data"]["items"]; }; }; /** * @see https://developer.github.com/v3/search/#search-repositories */ "GET /search/repositories": { parameters: Endpoints["GET /search/repositories"]["parameters"]; response: Endpoints["GET /search/repositories"]["response"] & { data: Endpoints["GET /search/repositories"]["response"]["data"]["items"]; }; }; /** * @see https://developer.github.com/v3/search/#search-topics */ "GET /search/topics": { parameters: Endpoints["GET /search/topics"]["parameters"]; response: Endpoints["GET /search/topics"]["response"] & { data: Endpoints["GET /search/topics"]["response"]["data"]["items"]; }; }; /** * @see https://developer.github.com/v3/search/#search-users */ "GET /search/users": { parameters: Endpoints["GET /search/users"]["parameters"]; response: Endpoints["GET /search/users"]["response"] & { data: Endpoints["GET /search/users"]["response"]["data"]["items"]; }; }; /** * @see https://developer.github.com/v3/teams/discussions/#list-discussions-legacy */ "GET /teams/:team_id/discussions": { parameters: Endpoints["GET /teams/:team_id/discussions"]["parameters"]; response: Endpoints["GET /teams/:team_id/discussions"]["response"]; }; /** * @see https://developer.github.com/v3/teams/discussion_comments/#list-discussion-comments-legacy */ "GET /teams/:team_id/discussions/:discussion_number/comments": { parameters: Endpoints["GET /teams/:team_id/discussions/:discussion_number/comments"]["parameters"]; response: Endpoints["GET /teams/:team_id/discussions/:discussion_number/comments"]["response"]; }; /** * @see https://developer.github.com/v3/reactions/#list-reactions-for-a-team-discussion-comment-legacy */ "GET /teams/:team_id/discussions/:discussion_number/comments/:comment_number/reactions": { parameters: Endpoints["GET /teams/:team_id/discussions/:discussion_number/comments/:comment_number/reactions"]["parameters"]; response: Endpoints["GET /teams/:team_id/discussions/:discussion_number/comments/:comment_number/reactions"]["response"]; }; /** * @see https://developer.github.com/v3/reactions/#list-reactions-for-a-team-discussion-legacy */ "GET /teams/:team_id/discussions/:discussion_number/reactions": { parameters: Endpoints["GET /teams/:team_id/discussions/:discussion_number/reactions"]["parameters"]; response: Endpoints["GET /teams/:team_id/discussions/:discussion_number/reactions"]["response"]; }; /** * @see https://developer.github.com/v3/teams/members/#list-pending-team-invitations-legacy */ "GET /teams/:team_id/invitations": { parameters: Endpoints["GET /teams/:team_id/invitations"]["parameters"]; response: Endpoints["GET /teams/:team_id/invitations"]["response"]; }; /** * @see https://developer.github.com/v3/teams/members/#list-team-members-legacy */ "GET /teams/:team_id/members": { parameters: Endpoints["GET /teams/:team_id/members"]["parameters"]; response: Endpoints["GET /teams/:team_id/members"]["response"]; }; /** * @see https://developer.github.com/v3/teams/#list-team-projects-legacy */ "GET /teams/:team_id/projects": { parameters: Endpoints["GET /teams/:team_id/projects"]["parameters"]; response: Endpoints["GET /teams/:team_id/projects"]["response"]; }; /** * @see https://developer.github.com/v3/teams/#list-team-repositories-legacy */ "GET /teams/:team_id/repos": { parameters: Endpoints["GET /teams/:team_id/repos"]["parameters"]; response: Endpoints["GET /teams/:team_id/repos"]["response"]; }; /** * @see https://developer.github.com/v3/teams/team_sync/#list-idp-groups-for-a-team-legacy */ "GET /teams/:team_id/team-sync/group-mappings": { parameters: Endpoints["GET /teams/:team_id/team-sync/group-mappings"]["parameters"]; response: Endpoints["GET /teams/:team_id/team-sync/group-mappings"]["response"] & { data: Endpoints["GET /teams/:team_id/team-sync/group-mappings"]["response"]["data"]["groups"]; }; }; /** * @see https://developer.github.com/v3/teams/#list-child-teams-legacy */ "GET /teams/:team_id/teams": { parameters: Endpoints["GET /teams/:team_id/teams"]["parameters"]; response: Endpoints["GET /teams/:team_id/teams"]["response"]; }; /** * @see https://developer.github.com/v3/users/blocking/#list-users-blocked-by-the-authenticated-user */ "GET /user/blocks": { parameters: Endpoints["GET /user/blocks"]["parameters"]; response: Endpoints["GET /user/blocks"]["response"]; }; /** * @see https://developer.github.com/v3/users/emails/#list-email-addresses-for-the-authenticated-user */ "GET /user/emails": { parameters: Endpoints["GET /user/emails"]["parameters"]; response: Endpoints["GET /user/emails"]["response"]; }; /** * @see https://developer.github.com/v3/users/followers/#list-followers-of-the-authenticated-user */ "GET /user/followers": { parameters: Endpoints["GET /user/followers"]["parameters"]; response: Endpoints["GET /user/followers"]["response"]; }; /** * @see https://developer.github.com/v3/users/followers/#list-the-people-the-authenticated-user-follows */ "GET /user/following": { parameters: Endpoints["GET /user/following"]["parameters"]; response: Endpoints["GET /user/following"]["response"]; }; /** * @see https://developer.github.com/v3/users/gpg_keys/#list-gpg-keys-for-the-authenticated-user */ "GET /user/gpg_keys": { parameters: Endpoints["GET /user/gpg_keys"]["parameters"]; response: Endpoints["GET /user/gpg_keys"]["response"]; }; /** * @see https://developer.github.com/v3/apps/installations/#list-app-installations-accessible-to-the-user-access-token */ "GET /user/installations": { parameters: Endpoints["GET /user/installations"]["parameters"]; response: Endpoints["GET /user/installations"]["response"] & { data: Endpoints["GET /user/installations"]["response"]["data"]["installations"]; }; }; /** * @see https://developer.github.com/v3/apps/installations/#list-repositories-accessible-to-the-user-access-token */ "GET /user/installations/:installation_id/repositories": { parameters: Endpoints["GET /user/installations/:installation_id/repositories"]["parameters"]; response: Endpoints["GET /user/installations/:installation_id/repositories"]["response"] & { data: Endpoints["GET /user/installations/:installation_id/repositories"]["response"]["data"]["repositories"]; }; }; /** * @see https://developer.github.com/v3/issues/#list-user-account-issues-assigned-to-the-authenticated-user */ "GET /user/issues": { parameters: Endpoints["GET /user/issues"]["parameters"]; response: Endpoints["GET /user/issues"]["response"]; }; /** * @see https://developer.github.com/v3/users/keys/#list-public-ssh-keys-for-the-authenticated-user */ "GET /user/keys": { parameters: Endpoints["GET /user/keys"]["parameters"]; response: Endpoints["GET /user/keys"]["response"]; }; /** * @see https://developer.github.com/v3/apps/marketplace/#list-subscriptions-for-the-authenticated-user */ "GET /user/marketplace_purchases": { parameters: Endpoints["GET /user/marketplace_purchases"]["parameters"]; response: Endpoints["GET /user/marketplace_purchases"]["response"]; }; /** * @see https://developer.github.com/v3/apps/marketplace/#list-subscriptions-for-the-authenticated-user-stubbed */ "GET /user/marketplace_purchases/stubbed": { parameters: Endpoints["GET /user/marketplace_purchases/stubbed"]["parameters"]; response: Endpoints["GET /user/marketplace_purchases/stubbed"]["response"]; }; /** * @see https://developer.github.com/v3/orgs/members/#list-organization-memberships-for-the-authenticated-user */ "GET /user/memberships/orgs": { parameters: Endpoints["GET /user/memberships/orgs"]["parameters"]; response: Endpoints["GET /user/memberships/orgs"]["response"]; }; /** * @see https://developer.github.com/v3/migrations/users/#list-user-migrations */ "GET /user/migrations": { parameters: Endpoints["GET /user/migrations"]["parameters"]; response: Endpoints["GET /user/migrations"]["response"]; }; /** * @see https://developer.github.com/v3/migrations/users/#list-repositories-for-a-user-migration */ "GET /user/migrations/:migration_id/repositories": { parameters: Endpoints["GET /user/migrations/:migration_id/repositories"]["parameters"]; response: Endpoints["GET /user/migrations/:migration_id/repositories"]["response"]; }; /** * @see https://developer.github.com/v3/orgs/#list-organizations-for-the-authenticated-user */ "GET /user/orgs": { parameters: Endpoints["GET /user/orgs"]["parameters"]; response: Endpoints["GET /user/orgs"]["response"]; }; /** * @see https://developer.github.com/v3/users/emails/#list-public-email-addresses-for-the-authenticated-user */ "GET /user/public_emails": { parameters: Endpoints["GET /user/public_emails"]["parameters"]; response: Endpoints["GET /user/public_emails"]["response"]; }; /** * @see https://developer.github.com/v3/repos/invitations/#list-repository-invitations-for-the-authenticated-user */ "GET /user/repository_invitations": { parameters: Endpoints["GET /user/repository_invitations"]["parameters"]; response: Endpoints["GET /user/repository_invitations"]["response"]; }; /** * @see https://developer.github.com/v3/activity/starring/#list-repositories-starred-by-the-authenticated-user */ "GET /user/starred": { parameters: Endpoints["GET /user/starred"]["parameters"]; response: Endpoints["GET /user/starred"]["response"]; }; /** * @see https://developer.github.com/v3/activity/watching/#list-repositories-watched-by-the-authenticated-user */ "GET /user/subscriptions": { parameters: Endpoints["GET /user/subscriptions"]["parameters"]; response: Endpoints["GET /user/subscriptions"]["response"]; }; /** * @see https://developer.github.com/v3/teams/#list-teams-for-the-authenticated-user */ "GET /user/teams": { parameters: Endpoints["GET /user/teams"]["parameters"]; response: Endpoints["GET /user/teams"]["response"]; }; /** * @see https://developer.github.com/v3/users/#list-users */ "GET /users": { parameters: Endpoints["GET /users"]["parameters"]; response: Endpoints["GET /users"]["response"]; }; /** * @see https://developer.github.com/v3/users/followers/#list-followers-of-a-user */ "GET /users/:username/followers": { parameters: Endpoints["GET /users/:username/followers"]["parameters"]; response: Endpoints["GET /users/:username/followers"]["response"]; }; /** * @see https://developer.github.com/v3/users/followers/#list-the-people-a-user-follows */ "GET /users/:username/following": { parameters: Endpoints["GET /users/:username/following"]["parameters"]; response: Endpoints["GET /users/:username/following"]["response"]; }; /** * @see https://developer.github.com/v3/gists/#list-gists-for-a-user */ "GET /users/:username/gists": { parameters: Endpoints["GET /users/:username/gists"]["parameters"]; response: Endpoints["GET /users/:username/gists"]["response"]; }; /** * @see https://developer.github.com/v3/users/gpg_keys/#list-gpg-keys-for-a-user */ "GET /users/:username/gpg_keys": { parameters: Endpoints["GET /users/:username/gpg_keys"]["parameters"]; response: Endpoints["GET /users/:username/gpg_keys"]["response"]; }; /** * @see https://developer.github.com/v3/users/keys/#list-public-keys-for-a-user */ "GET /users/:username/keys": { parameters: Endpoints["GET /users/:username/keys"]["parameters"]; response: Endpoints["GET /users/:username/keys"]["response"]; }; /** * @see https://developer.github.com/v3/orgs/#list-organizations-for-a-user */ "GET /users/:username/orgs": { parameters: Endpoints["GET /users/:username/orgs"]["parameters"]; response: Endpoints["GET /users/:username/orgs"]["response"]; }; /** * @see https://developer.github.com/v3/projects/#list-user-projects */ "GET /users/:username/projects": { parameters: Endpoints["GET /users/:username/projects"]["parameters"]; response: Endpoints["GET /users/:username/projects"]["response"]; }; /** * @see https://developer.github.com/v3/activity/starring/#list-repositories-starred-by-a-user */ "GET /users/:username/starred": { parameters: Endpoints["GET /users/:username/starred"]["parameters"]; response: Endpoints["GET /users/:username/starred"]["response"]; }; /** * @see https://developer.github.com/v3/activity/watching/#list-repositories-watched-by-a-user */ "GET /users/:username/subscriptions": { parameters: Endpoints["GET /users/:username/subscriptions"]["parameters"]; response: Endpoints["GET /users/:username/subscriptions"]["response"]; }; }
the_stack
import { Query } from '../../src/query'; import { Source } from '../../src/source'; import { RequestOptions } from '../../src/request'; import { ResponseHints } from '../../src/response'; import { queryable, isQueryable, Queryable } from '../../src/source-interfaces/queryable'; import { Record, FindRecords, RecordData, RecordResponse, RecordOperation, RecordQueryExpression, RecordQueryBuilder } from '../support/record-data'; const { module, test } = QUnit; module('@queryable', function (hooks) { interface MySource extends Source, Queryable< RecordData, RecordResponse, RecordOperation, RecordQueryExpression, RecordQueryBuilder, RequestOptions > {} @queryable class MySource extends Source {} let source: MySource; hooks.beforeEach(function () { source = new MySource({ name: 'src1' }); }); test('isQueryable - tests for the application of the @queryable decorator', function (assert) { assert.ok(isQueryable(source)); }); test('should be applied to a Source', function (assert) { assert.throws( function () { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: Test of bad typing @queryable class Vanilla {} }, Error( 'Assertion failed: Queryable interface can only be applied to a Source' ), 'assertion raised' ); }); test('#query should resolve as a failure when _query fails', async function (assert) { assert.expect(2); source._query = function () { return Promise.reject(':('); }; try { await source.query({ op: 'findRecords', type: 'planet' }); } catch (error) { assert.ok(true, 'query promise resolved as a failure'); assert.equal(error, ':(', 'failure'); } }); test('#query should trigger `query` event after a successful action in which `_query` resolves successfully', async function (assert) { assert.expect(7); let order = 0; let qe = { op: 'findRecords', type: 'planet' } as FindRecords; const fullResponse = { data: [ { type: 'planet', id: 'p1' } ] }; source._query = async function (query) { assert.equal(++order, 1, 'action performed after beforeQuery'); assert.strictEqual(query.expressions, qe, 'query object matches'); return fullResponse; }; source.on('query', (query, result) => { assert.equal( ++order, 2, 'query triggered after action performed successfully' ); assert.strictEqual(query.expressions, qe, 'query matches'); assert.strictEqual(result, fullResponse, 'result matches'); }); let result = await source.query<Record[]>(qe); assert.equal(++order, 3, 'promise resolved last'); assert.deepEqual(result, fullResponse.data, 'success!'); }); test('#query should trigger `query` event after a successful action in which `_query` just returns (not a promise)', async function (assert) { assert.expect(7); const qe = { op: 'findRecords', type: 'planet' } as FindRecords; const fullResponse = { data: undefined }; let order = 0; source._query = async function (query) { assert.equal(++order, 1, 'action performed after beforeQuery'); assert.strictEqual(query.expressions, qe, 'query object matches'); return fullResponse; }; source.on('query', (query, result) => { assert.equal( ++order, 2, 'query triggered after action performed successfully' ); assert.strictEqual(query.expressions, qe, 'query matches'); assert.equal(result, fullResponse, 'result matches'); }); let result = await source.query<Record[]>(qe); assert.equal(++order, 3, 'promise resolved last'); assert.equal(result, fullResponse.data, 'undefined result'); }); test('`query` event should receive results as the last argument, even if they are an array', async function (assert) { assert.expect(7); let order = 0; let qe = { op: 'findRecords', type: 'planet' } as FindRecords; const fullResponse = { data: [ { type: 'planet', id: 'p1' } ] }; source._query = async function (query) { assert.equal(++order, 1, 'action performed after beforeQuery'); assert.strictEqual(query.expressions, qe, 'query object matches'); return fullResponse; }; source.on('query', (query, result) => { assert.equal( ++order, 2, 'query triggered after action performed successfully' ); assert.strictEqual(query.expressions, qe, 'query matches'); assert.deepEqual(result, fullResponse, 'result matches'); }); let result = await source.query(qe); assert.equal(++order, 3, 'promise resolved last'); assert.deepEqual(result, fullResponse.data, 'success!'); }); test('#query should trigger `queryFail` event after an unsuccessful query', async function (assert) { assert.expect(7); let order = 0; let qe = { op: 'findRecords', type: 'planet' } as FindRecords; source._query = function (query) { assert.equal(++order, 1, 'action performed after beforeQuery'); assert.strictEqual(query.expressions, qe, 'query object matches'); return Promise.reject(':('); }; source.on('query', () => { assert.ok(false, 'query should not be triggered'); }); source.on('queryFail', (query, error) => { assert.equal( ++order, 2, 'queryFail triggered after an unsuccessful query' ); assert.strictEqual(query.expressions, qe, 'query matches'); assert.equal(error, ':(', 'error matches'); }); try { await source.query(qe); } catch (error) { assert.equal(++order, 3, 'promise resolved last'); assert.equal(error, ':(', 'failure'); } }); test('#query should resolve all promises returned from `beforeQuery` before calling `_query`', async function (assert) { assert.expect(7); let order = 0; let qe = { op: 'findRecords', type: 'planet' } as FindRecords; source.on('beforeQuery', () => { assert.equal(++order, 1, 'beforeQuery triggered first'); return Promise.resolve(); }); source.on('beforeQuery', () => { assert.equal(++order, 2, 'beforeQuery triggered second'); return undefined; }); source.on('beforeQuery', () => { assert.equal(++order, 3, 'beforeQuery triggered third'); return Promise.resolve(); }); const result1 = [ { type: 'planet', id: 'p1' } ]; source._query = async function (query) { assert.equal( ++order, 4, '_query invoked after all `beforeQuery` handlers' ); return { data: result1 }; }; source.on('query', () => { assert.equal( ++order, 5, 'query triggered after action performed successfully' ); }); let result = await source.query(qe); assert.equal(++order, 6, 'promise resolved last'); assert.deepEqual(result, result1, 'success!'); }); test('#query should resolve all promises returned from `beforeQuery` and fail if any fail', async function (assert) { assert.expect(5); let order = 0; let qe = { op: 'findRecords', type: 'planet' } as FindRecords; source.on('beforeQuery', () => { assert.equal(++order, 1, 'beforeQuery triggered first'); return Promise.resolve(); }); source.on('beforeQuery', () => { assert.equal(++order, 2, 'beforeQuery triggered again'); return Promise.reject(':('); }); source._query = async function () { assert.ok(false, '_query should not be invoked'); return { data: undefined }; }; source.on('query', () => { assert.ok(false, 'query should not be triggered'); }); source.on('queryFail', () => { assert.equal(++order, 3, 'queryFail triggered after action failed'); }); try { await source.query(qe); } catch (error) { assert.equal(++order, 4, 'promise failed because no actions succeeded'); assert.equal(error, ':(', 'failure'); } }); test('#query should pass a common `hints` object to all `beforeQuery` events and forward it to `_query`', async function (assert) { assert.expect(11); let order = 0; let qe = { op: 'findRecords', type: 'planet' } as FindRecords; let h: ResponseHints<RecordData, RecordResponse>; source.on( 'beforeQuery', async function ( query: Query<RecordQueryExpression>, hints: ResponseHints<RecordData, RecordResponse> ) { assert.equal(++order, 1, 'beforeQuery triggered first'); assert.deepEqual( hints, {}, 'beforeQuery is passed empty `hints` object' ); h = hints; hints.data = [ { type: 'planet', id: 'venus' }, { type: 'planet', id: 'mars' } ]; } ); source.on( 'beforeQuery', async function ( query: Query<RecordQueryExpression>, hints: ResponseHints<RecordData, RecordResponse> ) { assert.equal(++order, 2, 'beforeQuery triggered second'); assert.strictEqual( hints, h, 'beforeQuery is passed same hints instance' ); } ); source.on( 'beforeQuery', async function ( query: Query<RecordQueryExpression>, hints: ResponseHints<RecordData, RecordResponse> ) { assert.equal(++order, 3, 'beforeQuery triggered third'); assert.strictEqual( hints, h, 'beforeQuery is passed same hints instance' ); } ); source._query = async function ( query: Query<RecordQueryExpression>, hints?: ResponseHints<RecordData, RecordResponse> ) { assert.equal( ++order, 4, '_query invoked after all `beforeQuery` handlers' ); assert.strictEqual(hints, h, '_query is passed same hints instance'); return { data: hints?.data }; }; source.on('query', async function () { assert.equal( ++order, 5, 'query triggered after action performed successfully' ); }); let result = await source.query(qe); assert.equal(++order, 6, 'promise resolved last'); assert.deepEqual( result, [ { type: 'planet', id: 'venus' }, { type: 'planet', id: 'mars' } ], 'success!' ); }); test('#query can return a full response, with `data` nested in a response object', async function (assert) { assert.expect(7); let order = 0; let qe = { op: 'findRecords', type: 'planet' } as FindRecords; const result1 = [ { type: 'planet', id: 'p1' } ]; source._query = async function (query) { assert.equal(++order, 1, 'action performed after beforeQuery'); assert.strictEqual(query.expressions, qe, 'query object matches'); return { data: result1 }; }; source.on('query', (query, result) => { assert.equal( ++order, 2, 'query triggered after action performed successfully' ); assert.strictEqual(query.expressions, qe, 'query matches'); assert.deepEqual(result, { data: result1 }, 'result matches'); }); let result = await source.query(qe, { fullResponse: true }); assert.equal(++order, 3, 'promise resolved last'); assert.deepEqual(result, { data: result1 }, 'success!'); }); test('#query can return a full response, with `data`, `details`, and `sources` nested in a response object', async function (assert) { assert.expect(9); let order = 0; let qe = { op: 'findRecords', type: 'planet' } as FindRecords; const data1 = [ { type: 'planet', id: 'p1' } ]; const details1 = { data: data1, links: { self: 'https://example.com/api/planets' } }; const expectedResult = { data: data1, details: details1, // source-specific responses are based on beforeQuery responses sources: { remote: { details: details1 } } }; source.on('beforeQuery', async (query) => { assert.equal(++order, 1, 'beforeQuery triggered first'); assert.strictEqual(query.expressions, qe, 'beforeQuery: query matches'); return ['remote', { details: details1 }]; }); source._query = async function (query) { assert.equal(++order, 2, 'action performed after beforeQuery'); assert.strictEqual(query.expressions, qe, '_query: query matches'); return { data: data1, details: details1 }; }; source.on('query', (query, result) => { assert.equal( ++order, 3, 'query triggered after action performed successfully' ); assert.strictEqual(query.expressions, qe, 'query: query matches'); assert.deepEqual(result, expectedResult, 'result matches'); }); const result = await source.query(qe, { fullResponse: true }); assert.equal(++order, 4, 'request resolved last'); assert.deepEqual(result, expectedResult, 'success!'); }); });
the_stack
import * as assert from 'assert'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { TestDialogService } from 'vs/platform/dialogs/test/common/testDialogService'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { TestNotificationService } from 'vs/platform/notification/test/common/testNotificationService'; import { IQuickInputHideEvent, IQuickInputService, IQuickPickDidAcceptEvent } from 'vs/platform/quickinput/common/quickInput'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils'; import { MainThreadAuthentication } from 'vs/workbench/api/browser/mainThreadAuthentication'; import { ExtHostContext, MainContext } from 'vs/workbench/api/common/extHost.protocol'; import { ExtHostAuthentication } from 'vs/workbench/api/common/extHostAuthentication'; import { IActivityService } from 'vs/workbench/services/activity/common/activity'; import { AuthenticationService } from 'vs/workbench/services/authentication/browser/authenticationService'; import { IAuthenticationService } from 'vs/workbench/services/authentication/common/authentication'; import { IExtensionService, nullExtensionDescription as extensionDescription } from 'vs/workbench/services/extensions/common/extensions'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; import { TestRPCProtocol } from 'vs/workbench/api/test/common/testRPCProtocol'; import { TestQuickInputService, TestRemoteAgentService } from 'vs/workbench/test/browser/workbenchTestServices'; import { TestActivityService, TestExtensionService, TestStorageService } from 'vs/workbench/test/common/workbenchTestServices'; import type { AuthenticationProvider, AuthenticationSession } from 'vscode'; class AuthQuickPick { private listener: ((e: IQuickPickDidAcceptEvent) => any) | undefined; public items = []; public get selectedItems(): string[] { return this.items; } onDidAccept(listener: (e: IQuickPickDidAcceptEvent) => any) { this.listener = listener; } onDidHide(listener: (e: IQuickInputHideEvent) => any) { } dispose() { } show() { this.listener!({ inBackground: false }); } } class AuthTestQuickInputService extends TestQuickInputService { override createQuickPick() { return <any>new AuthQuickPick(); } } class TestAuthProvider implements AuthenticationProvider { private id = 1; private sessions = new Map<string, AuthenticationSession>(); onDidChangeSessions = () => { return { dispose() { } }; }; async getSessions(scopes?: readonly string[]): Promise<AuthenticationSession[]> { if (!scopes) { return [...this.sessions.values()]; } if (scopes[0] === 'return multiple') { return [...this.sessions.values()]; } const sessions = this.sessions.get(scopes.join(' ')); return sessions ? [sessions] : []; } async createSession(scopes: readonly string[]): Promise<AuthenticationSession> { const scopesStr = scopes.join(' '); const session = { scopes, id: `${this.id}`, account: { label: `${this.id}`, id: `${this.id}`, }, accessToken: Math.random() + '', }; this.sessions.set(scopesStr, session); this.id++; return session; } async removeSession(sessionId: string): Promise<void> { this.sessions.delete(sessionId); } } suite('ExtHostAuthentication', () => { let disposables: DisposableStore; let extHostAuthentication: ExtHostAuthentication; let instantiationService: TestInstantiationService; suiteSetup(async () => { instantiationService = new TestInstantiationService(); instantiationService.stub(IDialogService, new TestDialogService()); instantiationService.stub(IStorageService, new TestStorageService()); instantiationService.stub(IQuickInputService, new AuthTestQuickInputService()); instantiationService.stub(IExtensionService, new TestExtensionService()); instantiationService.stub(IActivityService, new TestActivityService()); instantiationService.stub(IRemoteAgentService, new TestRemoteAgentService()); instantiationService.stub(INotificationService, new TestNotificationService()); instantiationService.stub(ITelemetryService, NullTelemetryService); const rpcProtocol = new TestRPCProtocol(); instantiationService.stub(IAuthenticationService, instantiationService.createInstance(AuthenticationService)); rpcProtocol.set(MainContext.MainThreadAuthentication, instantiationService.createInstance(MainThreadAuthentication, rpcProtocol)); extHostAuthentication = new ExtHostAuthentication(rpcProtocol); rpcProtocol.set(ExtHostContext.ExtHostAuthentication, extHostAuthentication); }); setup(async () => { disposables = new DisposableStore(); disposables.add(extHostAuthentication.registerAuthenticationProvider('test', 'test provider', new TestAuthProvider())); disposables.add(extHostAuthentication.registerAuthenticationProvider( 'test-multiple', 'test multiple provider', new TestAuthProvider(), { supportsMultipleAccounts: true })); }); teardown(() => { disposables.dispose(); }); test('createIfNone - true', async () => { const scopes = ['foo']; const session = await extHostAuthentication.getSession( extensionDescription, 'test', scopes, { createIfNone: true }); assert.strictEqual(session?.id, '1'); assert.strictEqual(session?.scopes[0], 'foo'); }); test('createIfNone - false', async () => { const scopes = ['foo']; const nosession = await extHostAuthentication.getSession( extensionDescription, 'test', scopes, {}); assert.strictEqual(nosession, undefined); // Now create the session const session = await extHostAuthentication.getSession( extensionDescription, 'test', scopes, { createIfNone: true }); assert.strictEqual(session?.id, '1'); assert.strictEqual(session?.scopes[0], 'foo'); const session2 = await extHostAuthentication.getSession( extensionDescription, 'test', scopes, {}); assert.strictEqual(session.id, session2?.id); assert.strictEqual(session.scopes[0], session2?.scopes[0]); assert.strictEqual(session.accessToken, session2?.accessToken); }); // should behave the same as createIfNone: false test('silent - true', async () => { const scopes = ['foo']; const nosession = await extHostAuthentication.getSession( extensionDescription, 'test', scopes, { silent: true }); assert.strictEqual(nosession, undefined); // Now create the session const session = await extHostAuthentication.getSession( extensionDescription, 'test', scopes, { createIfNone: true }); assert.strictEqual(session?.id, '1'); assert.strictEqual(session?.scopes[0], 'foo'); const session2 = await extHostAuthentication.getSession( extensionDescription, 'test', scopes, { silent: true }); assert.strictEqual(session.id, session2?.id); assert.strictEqual(session.scopes[0], session2?.scopes[0]); }); test('forceNewSession - true', async () => { const scopes = ['foo']; const session1 = await extHostAuthentication.getSession( extensionDescription, 'test', scopes, { createIfNone: true }); // Now create the session const session2 = await extHostAuthentication.getSession( extensionDescription, 'test', scopes, { forceNewSession: true }); assert.strictEqual(session2?.id, '2'); assert.strictEqual(session2?.scopes[0], 'foo'); assert.notStrictEqual(session1.accessToken, session2?.accessToken); }); test('forceNewSession - detail', async () => { const scopes = ['foo']; const session1 = await extHostAuthentication.getSession( extensionDescription, 'test', scopes, { createIfNone: true }); // Now create the session const session2 = await extHostAuthentication.getSession( extensionDescription, 'test', scopes, { forceNewSession: { detail: 'bar' } }); assert.strictEqual(session2?.id, '2'); assert.strictEqual(session2?.scopes[0], 'foo'); assert.notStrictEqual(session1.accessToken, session2?.accessToken); }); //#region Multi-Account AuthProvider test('clearSessionPreference - true', async () => { const scopes = ['foo']; // Now create the session const session = await extHostAuthentication.getSession( extensionDescription, 'test-multiple', scopes, { createIfNone: true }); assert.strictEqual(session?.id, '1'); assert.strictEqual(session?.scopes[0], scopes[0]); const scopes2 = ['bar']; const session2 = await extHostAuthentication.getSession( extensionDescription, 'test-multiple', scopes2, { createIfNone: true }); assert.strictEqual(session2?.id, '2'); assert.strictEqual(session2?.scopes[0], scopes2[0]); const session3 = await extHostAuthentication.getSession( extensionDescription, 'test-multiple', ['return multiple'], { clearSessionPreference: true, createIfNone: true }); // clearing session preference causes us to get the first session // because it would normally show a quick pick for the user to choose assert.strictEqual(session.id, session3?.id); assert.strictEqual(session.scopes[0], session3?.scopes[0]); assert.strictEqual(session.accessToken, session3?.accessToken); }); test('silently getting session should return a session (if any) regardless of preference - fixes #137819', async () => { const scopes = ['foo']; // Now create the session const session = await extHostAuthentication.getSession( extensionDescription, 'test-multiple', scopes, { createIfNone: true }); assert.strictEqual(session?.id, '1'); assert.strictEqual(session?.scopes[0], scopes[0]); const scopes2 = ['bar']; const session2 = await extHostAuthentication.getSession( extensionDescription, 'test-multiple', scopes2, { createIfNone: true }); assert.strictEqual(session2?.id, '2'); assert.strictEqual(session2?.scopes[0], scopes2[0]); const shouldBeSession1 = await extHostAuthentication.getSession( extensionDescription, 'test-multiple', scopes, {}); assert.strictEqual(session.id, shouldBeSession1?.id); assert.strictEqual(session.scopes[0], shouldBeSession1?.scopes[0]); assert.strictEqual(session.accessToken, shouldBeSession1?.accessToken); const shouldBeSession2 = await extHostAuthentication.getSession( extensionDescription, 'test-multiple', scopes2, {}); assert.strictEqual(session2.id, shouldBeSession2?.id); assert.strictEqual(session2.scopes[0], shouldBeSession2?.scopes[0]); assert.strictEqual(session2.accessToken, shouldBeSession2?.accessToken); }); //#endregion //#region error cases test('forceNewSession with no sessions', async () => { try { await extHostAuthentication.getSession( extensionDescription, 'test', ['foo'], { forceNewSession: true }); assert.fail('should have thrown an Error.'); } catch (e) { assert.strictEqual(e.message, 'No existing sessions found.'); } }); test('createIfNone and forceNewSession', async () => { try { await extHostAuthentication.getSession( extensionDescription, 'test', ['foo'], { createIfNone: true, forceNewSession: true }); assert.fail('should have thrown an Error.'); } catch (e) { assert.ok(e); } }); test('forceNewSession and silent', async () => { try { await extHostAuthentication.getSession( extensionDescription, 'test', ['foo'], { forceNewSession: true, silent: true }); assert.fail('should have thrown an Error.'); } catch (e) { assert.ok(e); } }); test('createIfNone and silent', async () => { try { await extHostAuthentication.getSession( extensionDescription, 'test', ['foo'], { createIfNone: true, silent: true }); assert.fail('should have thrown an Error.'); } catch (e) { assert.ok(e); } }); test('Can get multiple sessions (with different scopes) in one extension', async () => { let session: AuthenticationSession | undefined = await extHostAuthentication.getSession( extensionDescription, 'test-multiple', ['foo'], { createIfNone: true }); session = await extHostAuthentication.getSession( extensionDescription, 'test-multiple', ['bar'], { createIfNone: true }); assert.strictEqual(session?.id, '2'); assert.strictEqual(session?.scopes[0], 'bar'); session = await extHostAuthentication.getSession( extensionDescription, 'test-multiple', ['foo'], { createIfNone: false }); assert.strictEqual(session?.id, '1'); assert.strictEqual(session?.scopes[0], 'foo'); }); //#endregion });
the_stack
import React from "react"; import styled from "styled-components"; import { Heading, Text, FontWeight, Span, Link, FontStyle } from "styled-typography"; import NextLink from "next/link"; import { Stylable } from "../types/component.types"; import { Code } from "../components/atoms/code.component"; import { Callout } from "../components/atoms/callout.component"; import { BookmarkHeading } from "../components/atoms/bookmark_heading.component"; type Props = Stylable; export const RawIndex = ({ className }: Props) => ( <section className={className}> <Heading>Docs</Heading> <BookmarkHeading id="installation" level={2}> Installation </BookmarkHeading> <Text> To download <Span fontWeight={FontWeight.Bold}>styled-typography</Span>{" "} run the following from within your project: </Text> <Code language="shell">{`npm install styled-typography`}</Code> <BookmarkHeading id="configuring-the-theme" level={2}> Configuring the theme </BookmarkHeading> <Text> You can customize{" "} <Span fontWeight={FontWeight.Bold}>styled-typography</Span> as much or as little as you’d like. A default will be provided that looks nice, visually. </Text> <Text> The minimum to get started is to have a <code>ThemeProvider</code>{" "} somewhere near the top of your react tree. You don’t need to provide a theme if you want the default configuration. </Text> <Code>{`import React from "react"; import { ThemeProvider } from "styled-components"; export const App = ({ children }) => ( <ThemeProvider theme={{}}>{children}</ThemeProvider> );`}</Code> <Text> To configure the typographic setup, you can pass any and all{" "} <NextLink href="#options" passHref> <Link>configuration options</Link> </NextLink>{" "} listed below. </Text> <Code>{`import React from "react"; import { ThemeProvider } from "styled-components"; // only customizes these three options. The rest will come from the default implementation const typographyTheme = { fontSizes: ["2.369rem", "1.777rem", "1.333rem", "1rem", "0.75rem", "10px"], bodyFontFamily: "Source Code Pro, Input, monospace", headingFontFamily: "SF Display, Helvetica Neue, Circular, sans-serif" }; export const App = ({ children }) => ( <ThemeProvider theme={{ typography: typographyTheme }}> {children} </ThemeProvider> );`}</Code> <BookmarkHeading id="components" level={2}> Components </BookmarkHeading> <Text> <code>styled-typography</code> provides give components for you to use and extend if needed: <code>GlobalTypeStyles</code>, <code>Text</code>,{" "} <code>Heading</code>, <code>Span</code>, and <code>Link</code>. </Text> <BookmarkHeading id="global-type-styles" level={3}> <code>GlobalTypeStyles</code> </BookmarkHeading> <Text> The <code>GlobalStyleStyles</code> component is a way to quickly get global type styles into your app. This is useful if you intent to use{" "} <code>Span</code> or <code>Link</code> outside of <code>Text</code>/ <code>Heading</code>, or other non-<code>styled-typography</code>{" "} components in your app. It’s important, however, that you place it within the <code>ThemeProvider</code> component. </Text> <Code>{`import React from "react"; import { ThemeProvider } from "styled-components"; import { GlobalTypeStyles } from "styled-typography"; export const App = ({ children }) => ( <ThemeProvider theme={{}}> <GlobalTypeStyles /> {children} </ThemeProvider> );`}</Code> <BookmarkHeading id="text" level={3}> <code>Text</code> </BookmarkHeading> <Text> The <code>Text</code> component resolves, by default, to a <code>p</code>{" "} component within the DOM. It accepts all props passable to <code>p</code>, as well as <code>TextProps</code>. </Text> <Code>{`import React from "react"; import { Text, FontWeight, FontStyle } from "styled-typography"; export const HelloWorld = ({ className }) => ( <Text className={className} level={4} fontWeight={FontWeight.Bold} fontStyle={FontStyle.Normal} color="red" lineHeight={1.3} > Hello, World! </Text> );`}</Code> <BookmarkHeading id="heading" level={3}> <code>Heading</code> </BookmarkHeading> <Text> The <code>Heading</code> component resolves, by default, to a{" "} <code>div</code> component within the DOM. It accepts all props passable to <code>div</code>, as well as <code>TextProps</code>. </Text> <Callout> <Text> But wait, you say! That’s not accessible! I know. By default, a{" "} <code>div</code> is not semantically an <code>h1</code> element.{" "} <code>ARIA</code>, however, provides attributes that{" "} <Span fontStyle={FontStyle.Italic}>can</Span> make it a semantic header. Thus, the <code>Header</code> component automatically gets{" "} <code>role="heading"</code> and <code>aria-level="#"</code> attributes. </Text> </Callout> <Code>{`import React from "react"; import { Heading, FontWeight, FontStyle } from "styled-typography"; export const HelloWorld = ({ className }) => ( <Heading className={className} level={1} // semantic level displayLevel={2} // display/visual level fontWeight={FontWeight.Bold} fontStyle={FontStyle.Normal} color="red" lineHeight={1} > Hello, World! </Heading> );`}</Code> <BookmarkHeading id="span" level={3}> <code>Span</code> </BookmarkHeading> <Text> The <code>Span</code> component resolves, by default, to a{" "} <code>span</code> component within the DOM. It accepts all props passable to <code>span</code>, as well as <code>TextProps</code>. </Text> <Code>{`import React from "react"; import { Span, FontWeight, FontStyle } from "styled-typography"; export const HelloWorld = ({ className }) => ( <Span className={className} level={4} fontWeight={FontWeight.Bold} fontStyle={FontStyle.Normal} color="red" lineHeight={1.3} > Hello, World! </Span> );`}</Code> <BookmarkHeading id="link" level={3}> <code>Link</code> </BookmarkHeading> <Text> The <code>Link</code> component resolves, by default, to an <code>a</code>{" "} component within the DOM. It accepts all props passable to <code>a</code>, as well as <code>TextProps</code>. </Text> <Code>{`import React from "react"; import { Link, FontWeight, FontStyle } from "styled-typography"; export const HelloWorld = ({ className }) => ( <Link className={className} level={4} fontWeight={FontWeight.Bold} fontStyle={FontStyle.Normal} color="red" lineHeight={1.3} href="https://reactjs.org" target="_blank" > Hello, World! </Link> );`}</Code> <BookmarkHeading id="options" level={2}> Configuration options </BookmarkHeading> <Text> Each of these options has what I consider to be a good default. You may override all of them, choose just a few to change, or do nothing. </Text> <BookmarkHeading id="fontsizes" level={3}> <code>fontSizes</code> </BookmarkHeading> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Type:</Span> [string, string, string, string, string, string] </code> </Callout> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Default:</Span> ["2.369rem", "1.777rem", "1.333rem", "1rem", "0.750rem", "10px"] </code> </Callout> <Text> <code>fontSizes</code> controls the 6 font size levels available to you. This generally corresponds to <code>h1</code> through <code>h6</code>. 6 levels are required. If your app has less than that, just duplicate the smallest value until there are 6. </Text> <Text> If only having 6 levels doesn’t work for you, please{" "} <Link href="https://github.com/mike-engel/styled-typography/issues" target="_blank" > file an issue </Link> ! </Text> <BookmarkHeading id="bodyfontfamily" level={3}> <code>bodyFontFamily</code> </BookmarkHeading> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Type:</Span> string </code> </Callout> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Default:</Span> "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif" </code> </Callout> <Text> <code>bodyFontFamily</code> sets the font family for <code>Text</code>{" "} elements. <code>Span</code> and <code>Link</code> will inherit the global styles unless used within a <code>Text</code> or <code>Heading</code>{" "} element. </Text> <BookmarkHeading id="bodySize" level={3}> <code>bodySize</code> </BookmarkHeading> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Type:</Span> number </code> </Callout> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Default:</Span> 4 </code> </Callout> <Text> <code>bodySize</code> sets the default font size level for{" "} <code>Text</code> elements. <code>Span</code> and <code>Link</code> will inherit the global styles unless used within a <code>Text</code> or{" "} <code>Heading</code> element. </Text> <BookmarkHeading id="bodyweight" level={3}> <code>bodyWeight</code> </BookmarkHeading> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Type:</Span> FontWeight </code> </Callout> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Default:</Span> FontWeight.Normal </code> </Callout> <Text> <code>bodyWeight</code> sets the default <code>font-weight</code> for{" "} <code>Text</code> elements. <code>Span</code> and <code>Link</code> will inherit the global styles unless used within a <code>Text</code> or{" "} <code>Heading</code> element. </Text> <Text> Available options are tied to the{" "} <Link href="https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#Common_weight_name_mapping" target="_blank" > common name mapping system </Link> . </Text> <Callout> <ul className="plain-list"> <li> <code>FontWeight.Hairline = "100"</code> </li> <li> <code>FontWeight.ExtraLight = "200"</code> </li> <li> <code>FontWeight.Light = "300"</code> </li> <li> <code>FontWeight.Normal = "400"</code> </li> <li> <code>FontWeight.Medium = "500"</code> </li> <li> <code>FontWeight.SemiBold = "600"</code> </li> <li> <code>FontWeight.Bold = "700"</code> </li> <li> <code>FontWeight.ExtraBold = "800"</code> </li> <li> <code>FontWeight.Heavy = "900"</code> </li> <li> <code>FontWeight.Inherit = "inherit</code> </li> </ul> </Callout> <BookmarkHeading id="bodystyle" level={3}> <code>bodyStyle</code> </BookmarkHeading> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Type:</Span> FontStyle </code> </Callout> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Default:</Span> FontStyle.Regular </code> </Callout> <Text> <code>bodyStyle</code> sets the default <code>font-style</code> for{" "} <code>Text</code> elements. <code>Span</code> and <code>Link</code> will inherit the global styles unless used within a <code>Text</code> or{" "} <code>Heading</code> element. </Text> <Text> Available options are tied to the{" "} <Link href="https://developer.mozilla.org/en-US/docs/Web/CSS/font-style#Values" target="_blank" > standard <code>font-style</code> options </Link>{" "} with an exception for <code>oblique &lt;angle&gt;</code> </Text> <Callout> <ul className="plain-list"> <li> <code>FontStyle.Italic = "italic"</code> </li> <li> <code>FontStyle.Oblique = "oblique"</code> </li> <li> <code>FontStyle.Normal = "normal"</code> </li> <li> <code>FontStyle.Inherit = "inherit</code> </li> </ul> </Callout> <BookmarkHeading id="bodycolor" level={3}> <code>bodyColor</code> </BookmarkHeading> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Type:</Span> string </code> </Callout> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Default:</Span> #000000 </code> </Callout> <Text> <code>bodyColor</code> sets the default <code>color</code> for{" "} <code>Text</code> elements. <code>Span</code> and <code>Link</code> will inherit the global styles unless used within a <code>Text</code> or{" "} <code>Heading</code> element. </Text> <BookmarkHeading id="bodylineheight" level={3}> <code>bodyLineHeight</code> </BookmarkHeading> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Type:</Span> string | number </code> </Callout> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Default:</Span> 1.4 </code> </Callout> <Text> <code>bodyColor</code> sets the default <code>line-height</code> for{" "} <code>Text</code> elements. <code>Span</code> and <code>Link</code> will inherit the global styles unless used within a <code>Text</code> or{" "} <code>Heading</code> element. </Text> <BookmarkHeading id="headingfontfamily" level={3}> <code>headingFontFamily</code> </BookmarkHeading> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Type:</Span> string </code> </Callout> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Default:</Span> "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif" </code> </Callout> <Text> <code>headingFontFamily</code> sets the font family for{" "} <code>Heading</code> elements. <code>Span</code> and <code>Link</code>{" "} will inherit the global styles unless used within a <code>Text</code> or{" "} <code>Heading</code> element. </Text> <BookmarkHeading id="headingSize" level={3}> <code>headingSize</code> </BookmarkHeading> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Type:</Span> number </code> </Callout> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Default:</Span> 4 </code> </Callout> <Text> <code>headingSize</code> sets the default font size level for{" "} <code>Heading</code> elements. <code>Span</code> and <code>Link</code>{" "} will inherit the global styles unless used within a <code>Text</code> or{" "} <code>Heading</code> element. </Text> <BookmarkHeading id="headingweight" level={3}> <code>headingWeight</code> </BookmarkHeading> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Type:</Span> FontWeight </code> </Callout> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Default:</Span> FontWeight.Normal </code> </Callout> <Text> <code>headingWeight</code> sets the default <code>font-weight</code> for{" "} <code>Heading</code> elements. <code>Span</code> and <code>Link</code>{" "} will inherit the global styles unless used within a <code>Text</code> or{" "} <code>Heading</code> element. </Text> <Text> Available options are tied to the{" "} <Link href="https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#Common_weight_name_mapping" target="_blank" > common name mapping system </Link> . </Text> <Callout> <ul className="plain-list"> <li> <code>FontWeight.Hairline = "100"</code> </li> <li> <code>FontWeight.ExtraLight = "200"</code> </li> <li> <code>FontWeight.Light = "300"</code> </li> <li> <code>FontWeight.Normal = "400"</code> </li> <li> <code>FontWeight.Medium = "500"</code> </li> <li> <code>FontWeight.SemiBold = "600"</code> </li> <li> <code>FontWeight.Bold = "700"</code> </li> <li> <code>FontWeight.ExtraBold = "800"</code> </li> <li> <code>FontWeight.Heavy = "900"</code> </li> <li> <code>FontWeight.Inherit = "inherit</code> </li> </ul> </Callout> <BookmarkHeading id="headingstyle" level={3}> <code>headingStyle</code> </BookmarkHeading> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Type:</Span> FontStyle </code> </Callout> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Default:</Span> FontStyle.Regular </code> </Callout> <Text> <code>headingStyle</code> sets the default <code>font-style</code> for{" "} <code>Heading</code> elements. <code>Span</code> and <code>Link</code>{" "} will inherit the global styles unless used within a <code>Text</code> or{" "} <code>Heading</code> element. </Text> <Text> Available options are tied to the{" "} <Link href="https://developer.mozilla.org/en-US/docs/Web/CSS/font-style#Values" target="_blank" > standard <code>font-style</code> options </Link>{" "} with an exception for <code>oblique &lt;angle&gt;</code> </Text> <Callout> <ul className="plain-list"> <li> <code>FontStyle.Italic = "italic"</code> </li> <li> <code>FontStyle.Oblique = "oblique"</code> </li> <li> <code>FontStyle.Normal = "normal"</code> </li> <li> <code>FontStyle.Inherit = "inherit</code> </li> </ul> </Callout> <BookmarkHeading id="headingcolor" level={3}> <code>headingColor</code> </BookmarkHeading> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Type:</Span> string </code> </Callout> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Default:</Span> #000000 </code> </Callout> <Text> <code>headingColor</code> sets the default <code>color</code> for{" "} <code>Heading</code> elements. <code>Span</code> and <code>Link</code>{" "} will inherit the global styles unless used within a <code>Text</code> or{" "} <code>Heading</code> element. </Text> <BookmarkHeading id="headinglineheight" level={3}> <code>headingLineHeight</code> </BookmarkHeading> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Type:</Span> string | number </code> </Callout> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Default:</Span> 1.4 </code> </Callout> <Text> <code>headingColor</code> sets the default <code>line-height</code> for{" "} <code>Heading</code> elements. <code>Span</code> and <code>Link</code>{" "} will inherit the global styles unless used within a <code>Text</code> or{" "} <code>Heading</code> element. </Text> <BookmarkHeading id="extra" level={3}> <code>extra</code> </BookmarkHeading> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Type:</Span>{" "} {`{ text: string, heading: string, span: string, link: string }`} </code> </Callout> <Callout> <code> <Span fontWeight={FontWeight.Bold}>Default:</Span> {`{}`} </code> </Callout> <Text> <code>extra</code> injects extra styles for each type of component. Template strings and plain strings are acceptable values for each key. </Text> </section> ); export default styled(RawIndex)``;
the_stack
import { anyObject } from "jest-mock-extended"; import { merge } from "lodash"; import mockFs from "mock-fs"; import logger from "../../main/logger"; import { AppPaths } from "../app-paths"; import type { CatalogEntity, CatalogEntityData, CatalogEntityKindData } from "../catalog"; import { ClusterStore } from "../cluster-store"; import { HotbarStore } from "../hotbar-store"; jest.mock("../../main/catalog/catalog-entity-registry", () => ({ catalogEntityRegistry: { items: [ { metadata: { uid: "1dfa26e2ebab15780a3547e9c7fa785c", name: "mycluster", source: "local", }, }, { metadata: { uid: "55b42c3c7ba3b04193416cda405269a5", name: "my_shiny_cluster", source: "remote", }, }, { metadata: { uid: "catalog-entity", name: "Catalog", source: "app", }, }, ], }, })); function getMockCatalogEntity(data: Partial<CatalogEntityData> & CatalogEntityKindData): CatalogEntity { return merge(data, { getName: jest.fn(() => data.metadata?.name), getId: jest.fn(() => data.metadata?.uid), getSource: jest.fn(() => data.metadata?.source ?? "unknown"), isEnabled: jest.fn(() => data.status?.enabled ?? true), onContextMenuOpen: jest.fn(), onSettingsOpen: jest.fn(), metadata: {}, spec: {}, status: {}, }) as CatalogEntity; } const testCluster = getMockCatalogEntity({ apiVersion: "v1", kind: "Cluster", status: { phase: "Running", }, metadata: { uid: "test", name: "test", labels: {}, }, }); const minikubeCluster = getMockCatalogEntity({ apiVersion: "v1", kind: "Cluster", status: { phase: "Running", }, metadata: { uid: "minikube", name: "minikube", labels: {}, }, }); const awsCluster = getMockCatalogEntity({ apiVersion: "v1", kind: "Cluster", status: { phase: "Running", }, metadata: { uid: "aws", name: "aws", labels: {}, }, }); jest.mock("electron", () => ({ app: { getVersion: () => "99.99.99", getName: () => "lens", setName: jest.fn(), setPath: jest.fn(), getPath: () => "tmp", getLocale: () => "en", setLoginItemSettings: jest.fn(), }, ipcMain: { on: jest.fn(), handle: jest.fn(), }, })); AppPaths.init(); describe("HotbarStore", () => { beforeEach(() => { mockFs({ "tmp": { "lens-hotbar-store.json": JSON.stringify({}), }, }); ClusterStore.createInstance(); HotbarStore.createInstance(); }); afterEach(() => { ClusterStore.resetInstance(); HotbarStore.resetInstance(); mockFs.restore(); }); describe("load", () => { it("loads one hotbar by default", () => { expect(HotbarStore.getInstance().hotbars.length).toEqual(1); }); }); describe("add", () => { it("adds a hotbar", () => { const hotbarStore = HotbarStore.getInstance(); hotbarStore.add({ name: "hottest" }); expect(hotbarStore.hotbars.length).toEqual(2); }); }); describe("hotbar items", () => { it("initially creates 12 empty cells", () => { const hotbarStore = HotbarStore.getInstance(); expect(hotbarStore.getActive().items.length).toEqual(12); }); it("initially adds catalog entity as first item", () => { const hotbarStore = HotbarStore.getInstance(); expect(hotbarStore.getActive().items[0].entity.name).toEqual("Catalog"); }); it("adds items", () => { const hotbarStore = HotbarStore.getInstance(); hotbarStore.addToHotbar(testCluster); const items = hotbarStore.getActive().items.filter(Boolean); expect(items.length).toEqual(2); }); it("removes items", () => { const hotbarStore = HotbarStore.getInstance(); hotbarStore.addToHotbar(testCluster); hotbarStore.removeFromHotbar("test"); hotbarStore.removeFromHotbar("catalog-entity"); const items = hotbarStore.getActive().items.filter(Boolean); expect(items).toStrictEqual([]); }); it("does nothing if removing with invalid uid", () => { const hotbarStore = HotbarStore.getInstance(); hotbarStore.addToHotbar(testCluster); hotbarStore.removeFromHotbar("invalid uid"); const items = hotbarStore.getActive().items.filter(Boolean); expect(items.length).toEqual(2); }); it("moves item to empty cell", () => { const hotbarStore = HotbarStore.getInstance(); hotbarStore.addToHotbar(testCluster); hotbarStore.addToHotbar(minikubeCluster); hotbarStore.addToHotbar(awsCluster); expect(hotbarStore.getActive().items[6]).toBeNull(); hotbarStore.restackItems(1, 5); expect(hotbarStore.getActive().items[5]).toBeTruthy(); expect(hotbarStore.getActive().items[5].entity.uid).toEqual("test"); }); it("moves items down", () => { const hotbarStore = HotbarStore.getInstance(); hotbarStore.addToHotbar(testCluster); hotbarStore.addToHotbar(minikubeCluster); hotbarStore.addToHotbar(awsCluster); // aws -> catalog hotbarStore.restackItems(3, 0); const items = hotbarStore.getActive().items.map(item => item?.entity.uid || null); expect(items.slice(0, 4)).toEqual(["aws", "catalog-entity", "test", "minikube"]); }); it("moves items up", () => { const hotbarStore = HotbarStore.getInstance(); hotbarStore.addToHotbar(testCluster); hotbarStore.addToHotbar(minikubeCluster); hotbarStore.addToHotbar(awsCluster); // test -> aws hotbarStore.restackItems(1, 3); const items = hotbarStore.getActive().items.map(item => item?.entity.uid || null); expect(items.slice(0, 4)).toEqual(["catalog-entity", "minikube", "aws", "test"]); }); it("logs an error if cellIndex is out of bounds", () => { const hotbarStore = HotbarStore.getInstance(); hotbarStore.add({ name: "hottest", id: "hottest" }); hotbarStore.activeHotbarId = "hottest"; const { error } = logger; const mocked = jest.fn(); logger.error = mocked; hotbarStore.addToHotbar(testCluster, -1); expect(mocked).toBeCalledWith("[HOTBAR-STORE]: cannot pin entity to hotbar outside of index range", anyObject()); hotbarStore.addToHotbar(testCluster, 12); expect(mocked).toBeCalledWith("[HOTBAR-STORE]: cannot pin entity to hotbar outside of index range", anyObject()); hotbarStore.addToHotbar(testCluster, 13); expect(mocked).toBeCalledWith("[HOTBAR-STORE]: cannot pin entity to hotbar outside of index range", anyObject()); logger.error = error; }); it("throws an error if getId is invalid or returns not a string", () => { const hotbarStore = HotbarStore.getInstance(); expect(() => hotbarStore.addToHotbar({} as any)).toThrowError(TypeError); expect(() => hotbarStore.addToHotbar({ getId: () => true } as any)).toThrowError(TypeError); }); it("throws an error if getName is invalid or returns not a string", () => { const hotbarStore = HotbarStore.getInstance(); expect(() => hotbarStore.addToHotbar({ getId: () => "" } as any)).toThrowError(TypeError); expect(() => hotbarStore.addToHotbar({ getId: () => "", getName: () => 4 } as any)).toThrowError(TypeError); }); it("does nothing when item moved to same cell", () => { const hotbarStore = HotbarStore.getInstance(); hotbarStore.addToHotbar(testCluster); hotbarStore.restackItems(1, 1); expect(hotbarStore.getActive().items[1].entity.uid).toEqual("test"); }); it("new items takes first empty cell", () => { const hotbarStore = HotbarStore.getInstance(); hotbarStore.addToHotbar(testCluster); hotbarStore.addToHotbar(awsCluster); hotbarStore.restackItems(0, 3); hotbarStore.addToHotbar(minikubeCluster); expect(hotbarStore.getActive().items[0].entity.uid).toEqual("minikube"); }); it("throws if invalid arguments provided", () => { // Prevent writing to stderr during this render. const { error, warn } = console; console.error = jest.fn(); console.warn = jest.fn(); const hotbarStore = HotbarStore.getInstance(); hotbarStore.addToHotbar(testCluster); expect(() => hotbarStore.restackItems(-5, 0)).toThrow(); expect(() => hotbarStore.restackItems(2, -1)).toThrow(); expect(() => hotbarStore.restackItems(14, 1)).toThrow(); expect(() => hotbarStore.restackItems(11, 112)).toThrow(); // Restore writing to stderr. console.error = error; console.warn = warn; }); it("checks if entity already pinned to hotbar", () => { const hotbarStore = HotbarStore.getInstance(); hotbarStore.addToHotbar(testCluster); expect(hotbarStore.isAddedToActive(testCluster)).toBeTruthy(); expect(hotbarStore.isAddedToActive(awsCluster)).toBeFalsy(); }); }); describe("pre beta-5 migrations", () => { beforeEach(() => { HotbarStore.resetInstance(); const mockOpts = { "tmp": { "lens-hotbar-store.json": JSON.stringify({ __internal__: { migrations: { version: "5.0.0-beta.3", }, }, "hotbars": [ { "id": "3caac17f-aec2-4723-9694-ad204465d935", "name": "myhotbar", "items": [ { "entity": { "uid": "1dfa26e2ebab15780a3547e9c7fa785c", }, }, { "entity": { "uid": "55b42c3c7ba3b04193416cda405269a5", }, }, { "entity": { "uid": "176fd331968660832f62283219d7eb6e", }, }, { "entity": { "uid": "61c4fb45528840ebad1badc25da41d14", "name": "user1-context", "source": "local", }, }, { "entity": { "uid": "27d6f99fe9e7548a6e306760bfe19969", "name": "foo2", "source": "local", }, }, null, { "entity": { "uid": "c0b20040646849bb4dcf773e43a0bf27", "name": "multinode-demo", "source": "local", }, }, null, null, null, null, null, ], }, ], }), }, }; mockFs(mockOpts); HotbarStore.createInstance(); }); afterEach(() => { mockFs.restore(); }); it("allows to retrieve a hotbar", () => { const hotbar = HotbarStore.getInstance().getById("3caac17f-aec2-4723-9694-ad204465d935"); expect(hotbar.id).toBe("3caac17f-aec2-4723-9694-ad204465d935"); }); it("clears cells without entity", () => { const items = HotbarStore.getInstance().hotbars[0].items; expect(items[2]).toBeNull(); }); it("adds extra data to cells with according entity", () => { const items = HotbarStore.getInstance().hotbars[0].items; expect(items[0]).toEqual({ entity: { name: "mycluster", source: "local", uid: "1dfa26e2ebab15780a3547e9c7fa785c", }, }); expect(items[1]).toEqual({ entity: { name: "my_shiny_cluster", source: "remote", uid: "55b42c3c7ba3b04193416cda405269a5", }, }); }); }); });
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { CreateOrderCommand, CreateOrderCommandInput, CreateOrderCommandOutput } from "./commands/CreateOrderCommand"; import { CreateOutpostCommand, CreateOutpostCommandInput, CreateOutpostCommandOutput, } from "./commands/CreateOutpostCommand"; import { DeleteOutpostCommand, DeleteOutpostCommandInput, DeleteOutpostCommandOutput, } from "./commands/DeleteOutpostCommand"; import { DeleteSiteCommand, DeleteSiteCommandInput, DeleteSiteCommandOutput } from "./commands/DeleteSiteCommand"; import { GetOutpostCommand, GetOutpostCommandInput, GetOutpostCommandOutput } from "./commands/GetOutpostCommand"; import { GetOutpostInstanceTypesCommand, GetOutpostInstanceTypesCommandInput, GetOutpostInstanceTypesCommandOutput, } from "./commands/GetOutpostInstanceTypesCommand"; import { ListOutpostsCommand, ListOutpostsCommandInput, ListOutpostsCommandOutput, } from "./commands/ListOutpostsCommand"; import { ListSitesCommand, ListSitesCommandInput, ListSitesCommandOutput } from "./commands/ListSitesCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { OutpostsClient } from "./OutpostsClient"; /** * <p>AWS Outposts is a fully managed service that extends AWS infrastructure, APIs, and tools * to customer premises. By providing local access to AWS managed infrastructure, AWS Outposts * enables customers to build and run applications on premises using the same programming * interfaces as in AWS Regions, while using local compute and storage resources for lower * latency and local data processing needs.</p> */ export class Outposts extends OutpostsClient { /** * <p>Creates an order for an Outpost.</p> */ public createOrder(args: CreateOrderCommandInput, options?: __HttpHandlerOptions): Promise<CreateOrderCommandOutput>; public createOrder(args: CreateOrderCommandInput, cb: (err: any, data?: CreateOrderCommandOutput) => void): void; public createOrder( args: CreateOrderCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateOrderCommandOutput) => void ): void; public createOrder( args: CreateOrderCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateOrderCommandOutput) => void), cb?: (err: any, data?: CreateOrderCommandOutput) => void ): Promise<CreateOrderCommandOutput> | void { const command = new CreateOrderCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates an Outpost.</p> * <p>You can specify <code>AvailabilityZone</code> or <code>AvailabilityZoneId</code>.</p> */ public createOutpost( args: CreateOutpostCommandInput, options?: __HttpHandlerOptions ): Promise<CreateOutpostCommandOutput>; public createOutpost( args: CreateOutpostCommandInput, cb: (err: any, data?: CreateOutpostCommandOutput) => void ): void; public createOutpost( args: CreateOutpostCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateOutpostCommandOutput) => void ): void; public createOutpost( args: CreateOutpostCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateOutpostCommandOutput) => void), cb?: (err: any, data?: CreateOutpostCommandOutput) => void ): Promise<CreateOutpostCommandOutput> | void { const command = new CreateOutpostCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the Outpost.</p> */ public deleteOutpost( args: DeleteOutpostCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteOutpostCommandOutput>; public deleteOutpost( args: DeleteOutpostCommandInput, cb: (err: any, data?: DeleteOutpostCommandOutput) => void ): void; public deleteOutpost( args: DeleteOutpostCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteOutpostCommandOutput) => void ): void; public deleteOutpost( args: DeleteOutpostCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteOutpostCommandOutput) => void), cb?: (err: any, data?: DeleteOutpostCommandOutput) => void ): Promise<DeleteOutpostCommandOutput> | void { const command = new DeleteOutpostCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the site.</p> */ public deleteSite(args: DeleteSiteCommandInput, options?: __HttpHandlerOptions): Promise<DeleteSiteCommandOutput>; public deleteSite(args: DeleteSiteCommandInput, cb: (err: any, data?: DeleteSiteCommandOutput) => void): void; public deleteSite( args: DeleteSiteCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteSiteCommandOutput) => void ): void; public deleteSite( args: DeleteSiteCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteSiteCommandOutput) => void), cb?: (err: any, data?: DeleteSiteCommandOutput) => void ): Promise<DeleteSiteCommandOutput> | void { const command = new DeleteSiteCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets information about the specified Outpost.</p> */ public getOutpost(args: GetOutpostCommandInput, options?: __HttpHandlerOptions): Promise<GetOutpostCommandOutput>; public getOutpost(args: GetOutpostCommandInput, cb: (err: any, data?: GetOutpostCommandOutput) => void): void; public getOutpost( args: GetOutpostCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetOutpostCommandOutput) => void ): void; public getOutpost( args: GetOutpostCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetOutpostCommandOutput) => void), cb?: (err: any, data?: GetOutpostCommandOutput) => void ): Promise<GetOutpostCommandOutput> | void { const command = new GetOutpostCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the instance types for the specified Outpost.</p> */ public getOutpostInstanceTypes( args: GetOutpostInstanceTypesCommandInput, options?: __HttpHandlerOptions ): Promise<GetOutpostInstanceTypesCommandOutput>; public getOutpostInstanceTypes( args: GetOutpostInstanceTypesCommandInput, cb: (err: any, data?: GetOutpostInstanceTypesCommandOutput) => void ): void; public getOutpostInstanceTypes( args: GetOutpostInstanceTypesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetOutpostInstanceTypesCommandOutput) => void ): void; public getOutpostInstanceTypes( args: GetOutpostInstanceTypesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetOutpostInstanceTypesCommandOutput) => void), cb?: (err: any, data?: GetOutpostInstanceTypesCommandOutput) => void ): Promise<GetOutpostInstanceTypesCommandOutput> | void { const command = new GetOutpostInstanceTypesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Create a list of the Outposts for your AWS account. Add filters to your request to return * a more specific list of results. Use filters to match an Outpost lifecycle status, * Availibility Zone (<code>us-east-1a</code>), and AZ ID (<code>use1-az1</code>). </p> * * <p>If you specify multiple filters, the filters are joined with an <code>AND</code>, and the request returns only * results that match all of the specified filters.</p> */ public listOutposts( args: ListOutpostsCommandInput, options?: __HttpHandlerOptions ): Promise<ListOutpostsCommandOutput>; public listOutposts(args: ListOutpostsCommandInput, cb: (err: any, data?: ListOutpostsCommandOutput) => void): void; public listOutposts( args: ListOutpostsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListOutpostsCommandOutput) => void ): void; public listOutposts( args: ListOutpostsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListOutpostsCommandOutput) => void), cb?: (err: any, data?: ListOutpostsCommandOutput) => void ): Promise<ListOutpostsCommandOutput> | void { const command = new ListOutpostsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the sites for the specified AWS account.</p> */ public listSites(args: ListSitesCommandInput, options?: __HttpHandlerOptions): Promise<ListSitesCommandOutput>; public listSites(args: ListSitesCommandInput, cb: (err: any, data?: ListSitesCommandOutput) => void): void; public listSites( args: ListSitesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListSitesCommandOutput) => void ): void; public listSites( args: ListSitesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListSitesCommandOutput) => void), cb?: (err: any, data?: ListSitesCommandOutput) => void ): Promise<ListSitesCommandOutput> | void { const command = new ListSitesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the tags for the specified resource.</p> */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds tags to the specified resource.</p> */ public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>; public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void; public tagResource( args: TagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TagResourceCommandOutput) => void ): void; public tagResource( args: TagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void), cb?: (err: any, data?: TagResourceCommandOutput) => void ): Promise<TagResourceCommandOutput> | void { const command = new TagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes tags from the specified resource.</p> */ public untagResource( args: UntagResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UntagResourceCommandOutput>; public untagResource( args: UntagResourceCommandInput, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void), cb?: (err: any, data?: UntagResourceCommandOutput) => void ): Promise<UntagResourceCommandOutput> | void { const command = new UntagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; import * as Root from '../../core/root/root.js'; import * as SDK from '../../core/sdk/sdk.js'; import type * as Protocol from '../../generated/protocol.js'; import {TimelineJSProfileProcessor} from './TimelineJSProfile.js'; const UIStrings = { /** *@description Text for the name of a thread of the page *@example {1} PH1 */ threadS: 'Thread {PH1}', /** *@description Title of a worker in the timeline flame chart of the Performance panel *@example {https://google.com} PH1 */ workerS: '`Worker` — {PH1}', /** *@description Title of a worker in the timeline flame chart of the Performance panel */ dedicatedWorker: 'Dedicated `Worker`', /** *@description Title of a worker in the timeline flame chart of the Performance panel *@example {FormatterWorker} PH1 *@example {https://google.com} PH2 */ workerSS: '`Worker`: {PH1} — {PH2}', }; const str_ = i18n.i18n.registerUIStrings('models/timeline_model/TimelineModel.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class TimelineModelImpl { private isGenericTraceInternal!: boolean; private tracksInternal!: Track[]; private namedTracks!: Map<TrackType, Track>; private inspectedTargetEventsInternal!: SDK.TracingModel.Event[]; private timeMarkerEventsInternal!: SDK.TracingModel.Event[]; private sessionId!: string|null; private mainFrameNodeId!: number|null; private pageFrames!: Map<Protocol.Page.FrameId, PageFrame>; private cpuProfilesInternal!: SDK.CPUProfileDataModel.CPUProfileDataModel[]; private workerIdByThread!: WeakMap<SDK.TracingModel.Thread, string>; private requestsFromBrowser!: Map<string, SDK.TracingModel.Event>; private mainFrame!: PageFrame; private minimumRecordTimeInternal: number; private maximumRecordTimeInternal: number; private totalBlockingTimeInternal: number; private estimatedTotalBlockingTime: number; private asyncEventTracker!: TimelineAsyncEventTracker; private invalidationTracker!: InvalidationTracker; private layoutInvalidate!: { [x: string]: SDK.TracingModel.Event|null, }; private lastScheduleStyleRecalculation!: { [x: string]: SDK.TracingModel.Event, }; private paintImageEventByPixelRefId!: { [x: string]: SDK.TracingModel.Event, }; private lastPaintForLayer!: { [x: string]: SDK.TracingModel.Event, }; private lastRecalculateStylesEvent!: SDK.TracingModel.Event|null; private currentScriptEvent!: SDK.TracingModel.Event|null; private eventStack!: SDK.TracingModel.Event[]; private knownInputEvents!: Set<string>; private browserFrameTracking!: boolean; private persistentIds!: boolean; private legacyCurrentPage!: any; private currentTaskLayoutAndRecalcEvents: SDK.TracingModel.Event[]; private tracingModelInternal: SDK.TracingModel.TracingModel|null; private mainFrameLayerTreeId?: any; constructor() { this.minimumRecordTimeInternal = 0; this.maximumRecordTimeInternal = 0; this.totalBlockingTimeInternal = 0; this.estimatedTotalBlockingTime = 0; this.reset(); this.resetProcessingState(); this.currentTaskLayoutAndRecalcEvents = []; this.tracingModelInternal = null; } static forEachEvent( events: SDK.TracingModel.Event[], onStartEvent: (arg0: SDK.TracingModel.Event) => void, onEndEvent: (arg0: SDK.TracingModel.Event) => void, onInstantEvent?: ((arg0: SDK.TracingModel.Event, arg1: SDK.TracingModel.Event|null) => any), startTime?: number, endTime?: number, filter?: ((arg0: SDK.TracingModel.Event) => boolean)): void { startTime = startTime || 0; endTime = endTime || Infinity; const stack: SDK.TracingModel.Event[] = []; const startEvent = TimelineModelImpl.topLevelEventEndingAfter(events, startTime); for (let i = startEvent; i < events.length; ++i) { const e = events[i]; if ((e.endTime || e.startTime) < startTime) { continue; } if (e.startTime >= endTime) { break; } if (SDK.TracingModel.TracingModel.isAsyncPhase(e.phase) || SDK.TracingModel.TracingModel.isFlowPhase(e.phase)) { continue; } let last: SDK.TracingModel.Event = stack[stack.length - 1]; while (last && last.endTime !== undefined && last.endTime <= e.startTime) { stack.pop(); onEndEvent(last); last = stack[stack.length - 1]; } if (filter && !filter(e)) { continue; } if (e.duration) { onStartEvent(e); stack.push(e); } else { onInstantEvent && onInstantEvent(e, stack[stack.length - 1] || null); } } while (stack.length) { const last = stack.pop(); if (last) { onEndEvent(last); } } } private static topLevelEventEndingAfter(events: SDK.TracingModel.Event[], time: number): number { let index = Platform.ArrayUtilities.upperBound(events, time, (time, event) => time - event.startTime) - 1; while (index > 0 && !SDK.TracingModel.TracingModel.isTopLevelEvent(events[index])) { index--; } return Math.max(index, 0); } isMarkerEvent(event: SDK.TracingModel.Event): boolean { switch (event.name) { case RecordType.TimeStamp: return true; case RecordType.MarkFirstPaint: case RecordType.MarkFCP: return Boolean(this.mainFrame) && event.args.frame === this.mainFrame.frameId && Boolean(event.args.data); case RecordType.MarkDOMContent: case RecordType.MarkLoad: case RecordType.MarkLCPCandidate: case RecordType.MarkLCPInvalidate: return Boolean(event.args['data']['isMainFrame']); default: return false; } } isInteractiveTimeEvent(event: SDK.TracingModel.Event): boolean { return event.name === RecordType.InteractiveTime; } isLayoutShiftEvent(event: SDK.TracingModel.Event): boolean { return event.name === RecordType.LayoutShift; } isUserTimingEvent(event: SDK.TracingModel.Event): boolean { return event.categoriesString === TimelineModelImpl.Category.UserTiming; } isParseHTMLEvent(event: SDK.TracingModel.Event): boolean { return event.name === RecordType.ParseHTML; } isLCPCandidateEvent(event: SDK.TracingModel.Event): boolean { return event.name === RecordType.MarkLCPCandidate && Boolean(event.args['data']['isMainFrame']); } isLCPInvalidateEvent(event: SDK.TracingModel.Event): boolean { return event.name === RecordType.MarkLCPInvalidate && Boolean(event.args['data']['isMainFrame']); } isFCPEvent(event: SDK.TracingModel.Event): boolean { return event.name === RecordType.MarkFCP && Boolean(this.mainFrame) && event.args['frame'] === this.mainFrame.frameId; } isLongRunningTask(event: SDK.TracingModel.Event): boolean { return event.name === RecordType.Task && TimelineData.forEvent(event).warning === TimelineModelImpl.WarningType.LongTask; } isNavigationStartEvent(event: SDK.TracingModel.Event): boolean { return event.name === RecordType.NavigationStart; } isMainFrameNavigationStartEvent(event: SDK.TracingModel.Event): boolean { return this.isNavigationStartEvent(event) && event.args['data']['isLoadingMainFrame'] && event.args['data']['documentLoaderURL']; } static globalEventId(event: SDK.TracingModel.Event, field: string): string { const data = event.args['data'] || event.args['beginData']; const id = data && data[field]; if (!id) { return ''; } return `${event.thread.process().id()}.${id}`; } static eventFrameId(event: SDK.TracingModel.Event): Protocol.Page.FrameId|null { const data = event.args['data'] || event.args['beginData']; return data && data['frame'] || null; } cpuProfiles(): SDK.CPUProfileDataModel.CPUProfileDataModel[] { return this.cpuProfilesInternal; } totalBlockingTime(): { time: number, estimated: boolean, } { if (this.totalBlockingTimeInternal === -1) { return {time: this.estimatedTotalBlockingTime, estimated: true}; } return {time: this.totalBlockingTimeInternal, estimated: false}; } targetByEvent(event: SDK.TracingModel.Event): SDK.Target.Target|null { // FIXME: Consider returning null for loaded traces. const workerId = this.workerIdByThread.get(event.thread); const mainTarget = SDK.TargetManager.TargetManager.instance().mainTarget(); return workerId ? SDK.TargetManager.TargetManager.instance().targetById(workerId) : mainTarget; } navStartTimes(): Map<string, SDK.TracingModel.Event> { if (!this.tracingModelInternal) { return new Map(); } return this.tracingModelInternal.navStartTimes(); } setEvents(tracingModel: SDK.TracingModel.TracingModel): void { this.reset(); this.resetProcessingState(); this.tracingModelInternal = tracingModel; this.minimumRecordTimeInternal = tracingModel.minimumRecordTime(); this.maximumRecordTimeInternal = tracingModel.maximumRecordTime(); // Remove LayoutShift events from the main thread list of events because they are // represented in the experience track. This is done prior to the main thread being processed for its own events. const layoutShiftEvents = []; for (const process of tracingModel.sortedProcesses()) { if (process.name() !== 'Renderer') { continue; } for (const thread of process.sortedThreads()) { const shifts = thread.removeEventsByName(RecordType.LayoutShift); layoutShiftEvents.push(...shifts); } } this.processSyncBrowserEvents(tracingModel); if (this.browserFrameTracking) { this.processThreadsForBrowserFrames(tracingModel); } else { // The next line is for loading legacy traces recorded before M67. // TODO(alph): Drop the support at some point. const metadataEvents = this.processMetadataEvents(tracingModel); this.isGenericTraceInternal = !metadataEvents; if (metadataEvents) { this.processMetadataAndThreads(tracingModel, metadataEvents); } else { this.processGenericTrace(tracingModel); } } this.inspectedTargetEventsInternal.sort(SDK.TracingModel.Event.compareStartTime); this.processAsyncBrowserEvents(tracingModel); this.buildGPUEvents(tracingModel); this.buildLoadingEvents(tracingModel, layoutShiftEvents); this.resetProcessingState(); } private processGenericTrace(tracingModel: SDK.TracingModel.TracingModel): void { let browserMainThread = SDK.TracingModel.TracingModel.browserMainThread(tracingModel); if (!browserMainThread && tracingModel.sortedProcesses().length) { browserMainThread = tracingModel.sortedProcesses()[0].sortedThreads()[0]; } for (const process of tracingModel.sortedProcesses()) { for (const thread of process.sortedThreads()) { this.processThreadEvents( tracingModel, [{from: 0, to: Infinity}], thread, thread === browserMainThread, false, true, null); } } } private processMetadataAndThreads(tracingModel: SDK.TracingModel.TracingModel, metadataEvents: MetadataEvents): void { let startTime = 0; for (let i = 0, length = metadataEvents.page.length; i < length; i++) { const metaEvent = metadataEvents.page[i]; const process = metaEvent.thread.process(); const endTime = i + 1 < length ? metadataEvents.page[i + 1].startTime : Infinity; if (startTime === endTime) { continue; } this.legacyCurrentPage = metaEvent.args['data'] && metaEvent.args['data']['page']; for (const thread of process.sortedThreads()) { let workerUrl: null = null; if (thread.name() === TimelineModelImpl.WorkerThreadName || thread.name() === TimelineModelImpl.WorkerThreadNameLegacy) { const workerMetaEvent = metadataEvents.workers.find(e => { if (e.args['data']['workerThreadId'] !== thread.id()) { return false; } // This is to support old traces. if (e.args['data']['sessionId'] === this.sessionId) { return true; } const frameId = TimelineModelImpl.eventFrameId(e); return frameId ? Boolean(this.pageFrames.get(frameId)) : false; }); if (!workerMetaEvent) { continue; } const workerId = workerMetaEvent.args['data']['workerId']; if (workerId) { this.workerIdByThread.set(thread, workerId); } workerUrl = workerMetaEvent.args['data']['url'] || ''; } this.processThreadEvents( tracingModel, [{from: startTime, to: endTime}], thread, thread === metaEvent.thread, Boolean(workerUrl), true, workerUrl); } startTime = endTime; } } private processThreadsForBrowserFrames(tracingModel: SDK.TracingModel.TracingModel): void { const processData = new Map<number, { from: number, to: number, main: boolean, url: string, }[]>(); for (const frame of this.pageFrames.values()) { for (let i = 0; i < frame.processes.length; i++) { const pid = frame.processes[i].processId; let data = processData.get(pid); if (!data) { data = []; processData.set(pid, data); } const to = i === frame.processes.length - 1 ? (frame.deletedTime || Infinity) : frame.processes[i + 1].time; data.push({from: frame.processes[i].time, to: to, main: !frame.parent, url: frame.processes[i].url}); } } const allMetadataEvents = tracingModel.devToolsMetadataEvents(); for (const process of tracingModel.sortedProcesses()) { const data = processData.get(process.id()); if (!data) { continue; } data.sort((a, b) => a.from - b.from || a.to - b.to); const ranges = []; let lastUrl: string|null = null; let lastMainUrl: string|null = null; let hasMain = false; for (const item of data) { const last = ranges[ranges.length - 1]; if (!last || item.from > last.to) { ranges.push({from: item.from, to: item.to}); } else { last.to = item.to; } if (item.main) { hasMain = true; } if (item.url) { if (item.main) { lastMainUrl = item.url; } lastUrl = item.url; } } for (const thread of process.sortedThreads()) { if (thread.name() === TimelineModelImpl.RendererMainThreadName) { this.processThreadEvents( tracingModel, ranges, thread, true /* isMainThread */, false /* isWorker */, hasMain, hasMain ? lastMainUrl : lastUrl); } else if ( thread.name() === TimelineModelImpl.WorkerThreadName || thread.name() === TimelineModelImpl.WorkerThreadNameLegacy) { const workerMetaEvent = allMetadataEvents.find(e => { if (e.name !== TimelineModelImpl.DevToolsMetadataEvent.TracingSessionIdForWorker) { return false; } if (e.thread.process() !== process) { return false; } if (e.args['data']['workerThreadId'] !== thread.id()) { return false; } const frameId = TimelineModelImpl.eventFrameId(e); return frameId ? Boolean(this.pageFrames.get(frameId)) : false; }); if (!workerMetaEvent) { continue; } this.workerIdByThread.set(thread, workerMetaEvent.args['data']['workerId'] || ''); this.processThreadEvents( tracingModel, ranges, thread, false /* isMainThread */, true /* isWorker */, false /* forMainFrame */, workerMetaEvent.args['data']['url'] || ''); } else { this.processThreadEvents( tracingModel, ranges, thread, false /* isMainThread */, false /* isWorker */, false /* forMainFrame */, null); } } } } private processMetadataEvents(tracingModel: SDK.TracingModel.TracingModel): MetadataEvents|null { const metadataEvents = tracingModel.devToolsMetadataEvents(); const pageDevToolsMetadataEvents = []; const workersDevToolsMetadataEvents = []; for (const event of metadataEvents) { if (event.name === TimelineModelImpl.DevToolsMetadataEvent.TracingStartedInPage) { pageDevToolsMetadataEvents.push(event); if (event.args['data'] && event.args['data']['persistentIds']) { this.persistentIds = true; } const frames = ((event.args['data'] && event.args['data']['frames']) || [] as PageFrame[]); frames.forEach((payload: PageFrame) => this.addPageFrame(event, payload)); this.mainFrame = this.rootFrames()[0]; } else if (event.name === TimelineModelImpl.DevToolsMetadataEvent.TracingSessionIdForWorker) { workersDevToolsMetadataEvents.push(event); } else if (event.name === TimelineModelImpl.DevToolsMetadataEvent.TracingStartedInBrowser) { console.assert(!this.mainFrameNodeId, 'Multiple sessions in trace'); this.mainFrameNodeId = event.args['frameTreeNodeId']; } } if (!pageDevToolsMetadataEvents.length) { return null; } const sessionId = pageDevToolsMetadataEvents[0].args['sessionId'] || pageDevToolsMetadataEvents[0].args['data']['sessionId']; this.sessionId = sessionId; const mismatchingIds = new Set<any>(); function checkSessionId(event: SDK.TracingModel.Event): boolean { let args = event.args; // FIXME: put sessionId into args["data"] for TracingStartedInPage event. if (args['data']) { args = args['data']; } const id = args['sessionId']; if (id === sessionId) { return true; } mismatchingIds.add(id); return false; } const result = { page: pageDevToolsMetadataEvents.filter(checkSessionId).sort(SDK.TracingModel.Event.compareStartTime), workers: workersDevToolsMetadataEvents.sort(SDK.TracingModel.Event.compareStartTime), }; if (mismatchingIds.size) { Common.Console.Console.instance().error( 'Timeline recording was started in more than one page simultaneously. Session id mismatch: ' + this.sessionId + ' and ' + [...mismatchingIds] + '.'); } return result; } private processSyncBrowserEvents(tracingModel: SDK.TracingModel.TracingModel): void { const browserMain = SDK.TracingModel.TracingModel.browserMainThread(tracingModel); if (browserMain) { browserMain.events().forEach(this.processBrowserEvent, this); } } private processAsyncBrowserEvents(tracingModel: SDK.TracingModel.TracingModel): void { const browserMain = SDK.TracingModel.TracingModel.browserMainThread(tracingModel); if (browserMain) { this.processAsyncEvents(browserMain, [{from: 0, to: Infinity}]); } } private buildGPUEvents(tracingModel: SDK.TracingModel.TracingModel): void { const thread = tracingModel.getThreadByName('GPU Process', 'CrGpuMain'); if (!thread) { return; } const gpuEventName = RecordType.GPUTask; const track = this.ensureNamedTrack(TrackType.GPU); track.thread = thread; track.events = thread.events().filter(event => event.name === gpuEventName); } private buildLoadingEvents(tracingModel: SDK.TracingModel.TracingModel, events: SDK.TracingModel.Event[]): void { const thread = tracingModel.getThreadByName('Renderer', 'CrRendererMain'); if (!thread) { return; } const experienceCategory = 'experience'; const track = this.ensureNamedTrack(TrackType.Experience); track.thread = thread; track.events = events; // Even though the event comes from 'loading', in order to color it differently we // rename its category. for (const trackEvent of track.events) { trackEvent.categoriesString = experienceCategory; if (trackEvent.name === RecordType.LayoutShift) { const eventData = trackEvent.args['data'] || trackEvent.args['beginData'] || {}; const timelineData = TimelineData.forEvent(trackEvent); if (eventData['impacted_nodes']) { for (let i = 0; i < eventData['impacted_nodes'].length; ++i) { timelineData.backendNodeIds.push(eventData['impacted_nodes'][i]['node_id']); } } } } } private resetProcessingState(): void { this.asyncEventTracker = new TimelineAsyncEventTracker(); this.invalidationTracker = new InvalidationTracker(); this.layoutInvalidate = {}; this.lastScheduleStyleRecalculation = {}; this.paintImageEventByPixelRefId = {}; this.lastPaintForLayer = {}; this.lastRecalculateStylesEvent = null; this.currentScriptEvent = null; this.eventStack = []; this.knownInputEvents = new Set(); this.browserFrameTracking = false; this.persistentIds = false; this.legacyCurrentPage = null; } private extractCpuProfile(tracingModel: SDK.TracingModel.TracingModel, thread: SDK.TracingModel.Thread): SDK.CPUProfileDataModel.CPUProfileDataModel|null { const events = thread.events(); let cpuProfile; let target: (SDK.Target.Target|null)|null = null; // Check for legacy CpuProfile event format first. let cpuProfileEvent: (SDK.TracingModel.Event|undefined)|SDK.TracingModel.Event = events[events.length - 1]; if (cpuProfileEvent && cpuProfileEvent.name === RecordType.CpuProfile) { const eventData = cpuProfileEvent.args['data']; cpuProfile = (eventData && eventData['cpuProfile'] as Protocol.Profiler.Profile | null); target = this.targetByEvent(cpuProfileEvent); } if (!cpuProfile) { cpuProfileEvent = events.find(e => e.name === RecordType.Profile); if (!cpuProfileEvent) { return null; } target = this.targetByEvent(cpuProfileEvent); const profileGroup = tracingModel.profileGroup(cpuProfileEvent); if (!profileGroup) { Common.Console.Console.instance().error('Invalid CPU profile format.'); return null; } cpuProfile = ({ startTime: cpuProfileEvent.startTime * 1000, endTime: 0, nodes: [], samples: [], timeDeltas: [], lines: [], } as any); for (const profileEvent of profileGroup.children) { const eventData = profileEvent.args['data']; if ('startTime' in eventData) { // Do not use |eventData['startTime']| as it is in CLOCK_MONOTONIC domain, // but use |profileEvent.startTime| (|ts| in the trace event) which has // been translated to Perfetto's clock domain. // // Also convert from ms to us. cpuProfile.startTime = profileEvent.startTime * 1000; } if ('endTime' in eventData) { // Do not use |eventData['endTime']| as it is in CLOCK_MONOTONIC domain, // but use |profileEvent.startTime| (|ts| in the trace event) which has // been translated to Perfetto's clock domain. // // Despite its name, |profileEvent.startTime| was recorded right after // |eventData['endTime']| within v8 and is a reasonable substitute. // // Also convert from ms to us. cpuProfile.endTime = profileEvent.startTime * 1000; } const nodesAndSamples = eventData['cpuProfile'] || {}; const samples = nodesAndSamples['samples'] || []; const lines = eventData['lines'] || Array(samples.length).fill(0); cpuProfile.nodes.push(...(nodesAndSamples['nodes'] || [])); cpuProfile.lines.push(...lines); if (cpuProfile.samples) { cpuProfile.samples.push(...samples); } if (cpuProfile.timeDeltas) { cpuProfile.timeDeltas.push(...(eventData['timeDeltas'] || [])); } if (cpuProfile.samples && cpuProfile.timeDeltas && cpuProfile.samples.length !== cpuProfile.timeDeltas.length) { Common.Console.Console.instance().error('Failed to parse CPU profile.'); return null; } } if (!cpuProfile.endTime && cpuProfile.timeDeltas) { const timeDeltas: number[] = cpuProfile.timeDeltas; cpuProfile.endTime = timeDeltas.reduce((x, y) => x + y, cpuProfile.startTime); } } try { const profile = (cpuProfile as Protocol.Profiler.Profile); const jsProfileModel = new SDK.CPUProfileDataModel.CPUProfileDataModel(profile, target); this.cpuProfilesInternal.push(jsProfileModel); return jsProfileModel; } catch (e) { Common.Console.Console.instance().error('Failed to parse CPU profile.'); } return null; } private injectJSFrameEvents(tracingModel: SDK.TracingModel.TracingModel, thread: SDK.TracingModel.Thread): SDK.TracingModel.Event[] { const jsProfileModel = this.extractCpuProfile(tracingModel, thread); let events = thread.events(); const jsSamples = jsProfileModel ? TimelineJSProfileProcessor.generateTracingEventsFromCpuProfile(jsProfileModel, thread) : null; if (jsSamples && jsSamples.length) { events = Platform.ArrayUtilities.mergeOrdered(events, jsSamples, SDK.TracingModel.Event.orderedCompareStartTime); } if (jsSamples || events.some(e => e.name === RecordType.JSSample)) { const jsFrameEvents = TimelineJSProfileProcessor.generateJSFrameEvents(events, { showAllEvents: Root.Runtime.experiments.isEnabled('timelineShowAllEvents'), showRuntimeCallStats: Root.Runtime.experiments.isEnabled('timelineV8RuntimeCallStats'), showNativeFunctions: Common.Settings.Settings.instance().moduleSetting('showNativeFunctionsInJSProfile').get(), }); if (jsFrameEvents && jsFrameEvents.length) { events = Platform.ArrayUtilities.mergeOrdered(jsFrameEvents, events, SDK.TracingModel.Event.orderedCompareStartTime); } } return events; } private processThreadEvents( tracingModel: SDK.TracingModel.TracingModel, ranges: { from: number, to: number, }[], thread: SDK.TracingModel.Thread, isMainThread: boolean, isWorker: boolean, forMainFrame: boolean, url: string|null): void { const track = new Track(); track.name = thread.name() || i18nString(UIStrings.threadS, {PH1: thread.id()}); track.type = TrackType.Other; track.thread = thread; if (isMainThread) { track.type = TrackType.MainThread; track.url = url || ''; track.forMainFrame = forMainFrame; } else if (isWorker) { track.type = TrackType.Worker; track.url = url || ''; track.name = track.url ? i18nString(UIStrings.workerS, {PH1: track.url}) : i18nString(UIStrings.dedicatedWorker); } else if (thread.name().startsWith('CompositorTileWorker')) { track.type = TrackType.Raster; } this.tracksInternal.push(track); const events = this.injectJSFrameEvents(tracingModel, thread); this.eventStack = []; const eventStack = this.eventStack; // Get the worker name from the target. if (isWorker) { const cpuProfileEvent = events.find(event => event.name === RecordType.Profile); if (cpuProfileEvent) { const target = this.targetByEvent(cpuProfileEvent); if (target) { track.name = i18nString(UIStrings.workerSS, {PH1: target.name(), PH2: track.url}); } } } for (const range of ranges) { let i = Platform.ArrayUtilities.lowerBound(events, range.from, (time, event) => time - event.startTime); for (; i < events.length; i++) { const event = events[i]; if (event.startTime >= range.to) { break; } // There may be several TTI events, only take the first one. if (this.isInteractiveTimeEvent(event) && this.totalBlockingTimeInternal === -1) { this.totalBlockingTimeInternal = event.args['args']['total_blocking_time_ms']; } const isLongRunningTask = event.name === RecordType.Task && event.duration && event.duration > 50; if (isMainThread && isLongRunningTask && event.duration) { // We only track main thread events that are over 50ms, and the amount of time in the // event (over 50ms) is what constitutes the blocking time. An event of 70ms, therefore, // contributes 20ms to TBT. this.estimatedTotalBlockingTime += event.duration - 50; } let last: SDK.TracingModel.Event = eventStack[eventStack.length - 1]; while (last && last.endTime !== undefined && last.endTime <= event.startTime) { eventStack.pop(); last = eventStack[eventStack.length - 1]; } if (!this.processEvent(event)) { continue; } if (!SDK.TracingModel.TracingModel.isAsyncPhase(event.phase) && event.duration) { if (eventStack.length) { const parent = eventStack[eventStack.length - 1]; if (parent) { parent.selfTime -= event.duration; if (parent.selfTime < 0) { this.fixNegativeDuration(parent, event); } } } event.selfTime = event.duration; if (!eventStack.length) { track.tasks.push(event); } eventStack.push(event); } if (this.isMarkerEvent(event)) { this.timeMarkerEventsInternal.push(event); } track.events.push(event); this.inspectedTargetEventsInternal.push(event); } } this.processAsyncEvents(thread, ranges); } private fixNegativeDuration(event: SDK.TracingModel.Event, child: SDK.TracingModel.Event): void { const epsilon = 1e-3; if (event.selfTime < -epsilon) { console.error( `Children are longer than parent at ${event.startTime} ` + `(${(child.startTime - this.minimumRecordTime()).toFixed(3)} by ${(-event.selfTime).toFixed(3)}`); } event.selfTime = 0; } private processAsyncEvents(thread: SDK.TracingModel.Thread, ranges: { from: number, to: number, }[]): void { const asyncEvents = thread.asyncEvents(); const groups = new Map<TrackType, SDK.TracingModel.AsyncEvent[]>(); function group(type: TrackType): SDK.TracingModel.AsyncEvent[] { if (!groups.has(type)) { groups.set(type, []); } return groups.get(type) as SDK.TracingModel.AsyncEvent[]; } for (const range of ranges) { let i = Platform.ArrayUtilities.lowerBound(asyncEvents, range.from, function(time, asyncEvent) { return time - asyncEvent.startTime; }); for (; i < asyncEvents.length; ++i) { const asyncEvent = asyncEvents[i]; if (asyncEvent.startTime >= range.to) { break; } if (asyncEvent.hasCategory(TimelineModelImpl.Category.Console)) { group(TrackType.Console).push(asyncEvent); continue; } if (asyncEvent.hasCategory(TimelineModelImpl.Category.UserTiming)) { group(TrackType.Timings).push(asyncEvent); continue; } if (asyncEvent.name === RecordType.Animation) { group(TrackType.Animation).push(asyncEvent); continue; } if (asyncEvent.hasCategory(TimelineModelImpl.Category.LatencyInfo) || asyncEvent.name === RecordType.ImplSideFling) { const lastStep = asyncEvent.steps[asyncEvent.steps.length - 1]; if (!lastStep) { throw new Error('AsyncEvent.steps access is out of bounds.'); } // FIXME: fix event termination on the back-end instead. if (lastStep.phase !== SDK.TracingModel.Phase.AsyncEnd) { continue; } const data = lastStep.args['data']; asyncEvent.causedFrame = Boolean(data && data['INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT']); if (asyncEvent.hasCategory(TimelineModelImpl.Category.LatencyInfo)) { if (lastStep.id && !this.knownInputEvents.has(lastStep.id)) { continue; } if (asyncEvent.name === RecordType.InputLatencyMouseMove && !asyncEvent.causedFrame) { continue; } // Coalesced events are not really been processed, no need to track them. if (data['is_coalesced']) { continue; } const rendererMain = data['INPUT_EVENT_LATENCY_RENDERER_MAIN_COMPONENT']; if (rendererMain) { const time = rendererMain['time'] / 1000; TimelineData.forEvent(asyncEvent.steps[0]).timeWaitingForMainThread = time - asyncEvent.steps[0].startTime; } } group(TrackType.Input).push(asyncEvent); continue; } } } for (const [type, events] of groups) { const track = this.ensureNamedTrack(type); track.thread = thread; track.asyncEvents = Platform.ArrayUtilities.mergeOrdered(track.asyncEvents, events, SDK.TracingModel.Event.compareStartTime); } } private processEvent(event: SDK.TracingModel.Event): boolean { const eventStack = this.eventStack; if (!eventStack.length) { if (this.currentTaskLayoutAndRecalcEvents && this.currentTaskLayoutAndRecalcEvents.length) { const totalTime = this.currentTaskLayoutAndRecalcEvents.reduce((time, event) => { return event.duration === undefined ? time : time + event.duration; }, 0); if (totalTime > TimelineModelImpl.Thresholds.ForcedLayout) { for (const e of this.currentTaskLayoutAndRecalcEvents) { const timelineData = TimelineData.forEvent(e); timelineData.warning = e.name === RecordType.Layout ? TimelineModelImpl.WarningType.ForcedLayout : TimelineModelImpl.WarningType.ForcedStyle; } } } this.currentTaskLayoutAndRecalcEvents = []; } if (this.currentScriptEvent) { if (this.currentScriptEvent.endTime !== undefined && event.startTime > this.currentScriptEvent.endTime) { this.currentScriptEvent = null; } } const eventData = event.args['data'] || event.args['beginData'] || {}; const timelineData = TimelineData.forEvent(event); if (eventData['stackTrace']) { timelineData.stackTrace = eventData['stackTrace'].map((callFrameOrProfileNode: Protocol.Runtime.CallFrame) => { // `callFrameOrProfileNode` can also be a `SDK.ProfileTreeModel.ProfileNode` for JSSample; that class // has accessors to mimic a `CallFrame`, but apparently we don't adjust stack traces in that case. Whether // we should is unclear. if (event.name !== RecordType.JSSample) { // We need to copy the data so we can safely modify it below. const frame = {...callFrameOrProfileNode}; // TraceEvents come with 1-based line & column numbers. The frontend code // requires 0-based ones. Adjust the values. --frame.lineNumber; --frame.columnNumber; return frame; } return callFrameOrProfileNode; }); } let pageFrameId = TimelineModelImpl.eventFrameId(event); const last = eventStack[eventStack.length - 1]; if (!pageFrameId && last) { pageFrameId = TimelineData.forEvent(last).frameId; } timelineData.frameId = pageFrameId || (this.mainFrame && this.mainFrame.frameId) || ''; this.asyncEventTracker.processEvent(event); if (this.isMarkerEvent(event)) { this.ensureNamedTrack(TrackType.Timings); } switch (event.name) { case RecordType.ResourceSendRequest: case RecordType.WebSocketCreate: { timelineData.setInitiator(eventStack[eventStack.length - 1] || null); timelineData.url = eventData['url']; break; } case RecordType.ScheduleStyleRecalculation: { this.lastScheduleStyleRecalculation[eventData['frame']] = event; break; } case RecordType.UpdateLayoutTree: case RecordType.RecalculateStyles: { this.invalidationTracker.didRecalcStyle(event); if (event.args['beginData']) { timelineData.setInitiator(this.lastScheduleStyleRecalculation[event.args['beginData']['frame']]); } this.lastRecalculateStylesEvent = event; if (this.currentScriptEvent) { this.currentTaskLayoutAndRecalcEvents.push(event); } break; } case RecordType.ScheduleStyleInvalidationTracking: case RecordType.StyleRecalcInvalidationTracking: case RecordType.StyleInvalidatorInvalidationTracking: case RecordType.LayoutInvalidationTracking: { this.invalidationTracker.addInvalidation(new InvalidationTrackingEvent(event, timelineData)); break; } case RecordType.InvalidateLayout: { // Consider style recalculation as a reason for layout invalidation, // but only if we had no earlier layout invalidation records. let layoutInitator: (SDK.TracingModel.Event|null)|SDK.TracingModel.Event = event; const frameId = eventData['frame']; if (!this.layoutInvalidate[frameId] && this.lastRecalculateStylesEvent && this.lastRecalculateStylesEvent.endTime !== undefined && this.lastRecalculateStylesEvent.endTime > event.startTime) { layoutInitator = TimelineData.forEvent(this.lastRecalculateStylesEvent).initiator(); } this.layoutInvalidate[frameId] = layoutInitator; break; } case RecordType.Layout: { this.invalidationTracker.didLayout(event); const frameId = event.args['beginData']['frame']; timelineData.setInitiator(this.layoutInvalidate[frameId]); // In case we have no closing Layout event, endData is not available. if (event.args['endData']) { if (event.args['endData']['layoutRoots']) { for (let i = 0; i < event.args['endData']['layoutRoots'].length; ++i) { timelineData.backendNodeIds.push(event.args['endData']['layoutRoots'][i]['nodeId']); } } else { timelineData.backendNodeIds.push(event.args['endData']['rootNode']); } } this.layoutInvalidate[frameId] = null; if (this.currentScriptEvent) { this.currentTaskLayoutAndRecalcEvents.push(event); } break; } case RecordType.Task: { if (event.duration !== undefined && event.duration > TimelineModelImpl.Thresholds.LongTask) { timelineData.warning = TimelineModelImpl.WarningType.LongTask; } break; } case RecordType.EventDispatch: { if (event.duration !== undefined && event.duration > TimelineModelImpl.Thresholds.RecurringHandler) { timelineData.warning = TimelineModelImpl.WarningType.LongHandler; } break; } case RecordType.TimerFire: case RecordType.FireAnimationFrame: { if (event.duration !== undefined && event.duration > TimelineModelImpl.Thresholds.RecurringHandler) { timelineData.warning = TimelineModelImpl.WarningType.LongRecurringHandler; } break; } // @ts-ignore fallthrough intended. case RecordType.FunctionCall: { // Compatibility with old format. if (typeof eventData['scriptName'] === 'string') { eventData['url'] = eventData['scriptName']; } if (typeof eventData['scriptLine'] === 'number') { eventData['lineNumber'] = eventData['scriptLine']; } } case RecordType.EvaluateScript: case RecordType.CompileScript: // @ts-ignore fallthrough intended. case RecordType.CacheScript: { if (typeof eventData['lineNumber'] === 'number') { --eventData['lineNumber']; } if (typeof eventData['columnNumber'] === 'number') { --eventData['columnNumber']; } } case RecordType.RunMicrotasks: { // Microtasks technically are not necessarily scripts, but for purpose of // forced sync style recalc or layout detection they are. if (!this.currentScriptEvent) { this.currentScriptEvent = event; } break; } case RecordType.SetLayerTreeId: { // This is to support old traces. if (this.sessionId && eventData['sessionId'] && this.sessionId === eventData['sessionId']) { this.mainFrameLayerTreeId = eventData['layerTreeId']; break; } // We currently only show layer tree for the main frame. const frameId = TimelineModelImpl.eventFrameId(event); const pageFrame = frameId ? this.pageFrames.get(frameId) : null; if (!pageFrame || pageFrame.parent) { return false; } this.mainFrameLayerTreeId = eventData['layerTreeId']; break; } case RecordType.Paint: { this.invalidationTracker.didPaint = true; // With CompositeAfterPaint enabled, paint events are no longer // associated with a Node, and nodeId will not be present. if ('nodeId' in eventData) { timelineData.backendNodeIds.push(eventData['nodeId']); } // Only keep layer paint events, skip paints for subframes that get painted to the same layer as parent. if (!eventData['layerId']) { break; } const layerId = eventData['layerId']; this.lastPaintForLayer[layerId] = event; break; } case RecordType.DisplayItemListSnapshot: case RecordType.PictureSnapshot: { const layerUpdateEvent = this.findAncestorEvent(RecordType.UpdateLayer); if (!layerUpdateEvent || layerUpdateEvent.args['layerTreeId'] !== this.mainFrameLayerTreeId) { break; } const paintEvent = this.lastPaintForLayer[layerUpdateEvent.args['layerId']]; if (paintEvent) { TimelineData.forEvent(paintEvent).picture = (event as SDK.TracingModel.ObjectSnapshot); } break; } case RecordType.ScrollLayer: { timelineData.backendNodeIds.push(eventData['nodeId']); break; } case RecordType.PaintImage: { timelineData.backendNodeIds.push(eventData['nodeId']); timelineData.url = eventData['url']; break; } case RecordType.DecodeImage: case RecordType.ResizeImage: { let paintImageEvent = this.findAncestorEvent(RecordType.PaintImage); if (!paintImageEvent) { const decodeLazyPixelRefEvent = this.findAncestorEvent(RecordType.DecodeLazyPixelRef); paintImageEvent = decodeLazyPixelRefEvent && this.paintImageEventByPixelRefId[decodeLazyPixelRefEvent.args['LazyPixelRef']]; } if (!paintImageEvent) { break; } const paintImageData = TimelineData.forEvent(paintImageEvent); timelineData.backendNodeIds.push(paintImageData.backendNodeIds[0]); timelineData.url = paintImageData.url; break; } case RecordType.DrawLazyPixelRef: { const paintImageEvent = this.findAncestorEvent(RecordType.PaintImage); if (!paintImageEvent) { break; } this.paintImageEventByPixelRefId[event.args['LazyPixelRef']] = paintImageEvent; const paintImageData = TimelineData.forEvent(paintImageEvent); timelineData.backendNodeIds.push(paintImageData.backendNodeIds[0]); timelineData.url = paintImageData.url; break; } case RecordType.FrameStartedLoading: { if (timelineData.frameId !== event.args['frame']) { return false; } break; } case RecordType.MarkLCPCandidate: { timelineData.backendNodeIds.push(eventData['nodeId']); break; } case RecordType.MarkDOMContent: case RecordType.MarkLoad: { const frameId = TimelineModelImpl.eventFrameId(event); if (!frameId || !this.pageFrames.has(frameId)) { return false; } break; } case RecordType.CommitLoad: { if (this.browserFrameTracking) { break; } const frameId = TimelineModelImpl.eventFrameId(event); const isMainFrame = Boolean(eventData['isMainFrame']); const pageFrame = frameId ? this.pageFrames.get(frameId) : null; if (pageFrame) { pageFrame.update(event.startTime, eventData); } else { // We should only have one main frame which has persistent id, // unless it's an old trace without 'persistentIds' flag. if (!this.persistentIds) { if (eventData['page'] && eventData['page'] !== this.legacyCurrentPage) { return false; } } else if (isMainFrame) { return false; } else if (!this.addPageFrame(event, eventData)) { return false; } } if (isMainFrame && frameId) { const frame = this.pageFrames.get(frameId); if (frame) { this.mainFrame = frame; } } break; } case RecordType.FireIdleCallback: { if (event.duration !== undefined && event.duration > eventData['allottedMilliseconds'] + TimelineModelImpl.Thresholds.IdleCallbackAddon) { timelineData.warning = TimelineModelImpl.WarningType.IdleDeadlineExceeded; } break; } } return true; } private processBrowserEvent(event: SDK.TracingModel.Event): void { if (event.name === RecordType.LatencyInfoFlow) { const frameId = event.args['frameTreeNodeId']; if (typeof frameId === 'number' && frameId === this.mainFrameNodeId && event.bind_id) { this.knownInputEvents.add(event.bind_id); } return; } if (event.name === RecordType.ResourceWillSendRequest) { const requestId = event.args?.data?.requestId; if (typeof requestId === 'string') { this.requestsFromBrowser.set(requestId, event); } return; } if (event.hasCategory(SDK.TracingModel.DevToolsMetadataEventCategory) && event.args['data']) { const data = event.args['data']; if (event.name === TimelineModelImpl.DevToolsMetadataEvent.TracingStartedInBrowser) { if (!data['persistentIds']) { return; } this.browserFrameTracking = true; this.mainFrameNodeId = data['frameTreeNodeId']; const frames: any[] = data['frames'] || []; frames.forEach(payload => { const parent = payload['parent'] && this.pageFrames.get(payload['parent']); if (payload['parent'] && !parent) { return; } let frame = this.pageFrames.get(payload['frame']); if (!frame) { frame = new PageFrame(payload); this.pageFrames.set(frame.frameId, frame); if (parent) { parent.addChild(frame); } else { this.mainFrame = frame; } } // TODO(dgozman): this should use event.startTime, but due to races between tracing start // in different processes we cannot do this yet. frame.update(this.minimumRecordTimeInternal, payload); }); return; } if (event.name === TimelineModelImpl.DevToolsMetadataEvent.FrameCommittedInBrowser && this.browserFrameTracking) { let frame = this.pageFrames.get(data['frame']); if (!frame) { const parent = data['parent'] && this.pageFrames.get(data['parent']); if (!parent) { return; } frame = new PageFrame(data); this.pageFrames.set(frame.frameId, frame); parent.addChild(frame); } frame.update(event.startTime, data); return; } if (event.name === TimelineModelImpl.DevToolsMetadataEvent.ProcessReadyInBrowser && this.browserFrameTracking) { const frame = this.pageFrames.get(data['frame']); if (frame) { frame.processReady(data['processPseudoId'], data['processId']); } return; } if (event.name === TimelineModelImpl.DevToolsMetadataEvent.FrameDeletedInBrowser && this.browserFrameTracking) { const frame = this.pageFrames.get(data['frame']); if (frame) { frame.deletedTime = event.startTime; } return; } } } private ensureNamedTrack(type: TrackType): Track { let track = this.namedTracks.get(type); if (track) { return track; } track = new Track(); track.type = type; this.tracksInternal.push(track); this.namedTracks.set(type, track); return track; } private findAncestorEvent(name: string): SDK.TracingModel.Event|null { for (let i = this.eventStack.length - 1; i >= 0; --i) { const event = this.eventStack[i]; if (event.name === name) { return event; } } return null; } private addPageFrame(event: SDK.TracingModel.Event, payload: any): boolean { const parent = payload['parent'] && this.pageFrames.get(payload['parent']); if (payload['parent'] && !parent) { return false; } const pageFrame = new PageFrame(payload); this.pageFrames.set(pageFrame.frameId, pageFrame); pageFrame.update(event.startTime, payload); if (parent) { parent.addChild(pageFrame); } return true; } private reset(): void { this.isGenericTraceInternal = false; this.tracksInternal = []; this.namedTracks = new Map(); this.inspectedTargetEventsInternal = []; this.timeMarkerEventsInternal = []; this.sessionId = null; this.mainFrameNodeId = null; this.cpuProfilesInternal = []; this.workerIdByThread = new WeakMap(); this.pageFrames = new Map(); this.requestsFromBrowser = new Map(); this.minimumRecordTimeInternal = 0; this.maximumRecordTimeInternal = 0; this.totalBlockingTimeInternal = -1; this.estimatedTotalBlockingTime = 0; } isGenericTrace(): boolean { return this.isGenericTraceInternal; } tracingModel(): SDK.TracingModel.TracingModel|null { return this.tracingModelInternal; } minimumRecordTime(): number { return this.minimumRecordTimeInternal; } maximumRecordTime(): number { return this.maximumRecordTimeInternal; } inspectedTargetEvents(): SDK.TracingModel.Event[] { return this.inspectedTargetEventsInternal; } tracks(): Track[] { return this.tracksInternal; } isEmpty(): boolean { return this.minimumRecordTime() === 0 && this.maximumRecordTime() === 0; } timeMarkerEvents(): SDK.TracingModel.Event[] { return this.timeMarkerEventsInternal; } rootFrames(): PageFrame[] { return Array.from(this.pageFrames.values()).filter(frame => !frame.parent); } pageURL(): string { return this.mainFrame && this.mainFrame.url || ''; } pageFrameById(frameId: Protocol.Page.FrameId): PageFrame|null { return frameId ? this.pageFrames.get(frameId) || null : null; } networkRequests(): NetworkRequest[] { if (this.isGenericTrace()) { return []; } const requests = new Map<string, NetworkRequest>(); const requestsList: NetworkRequest[] = []; const zeroStartRequestsList: NetworkRequest[] = []; const resourceTypes = new Set<string>([ RecordType.ResourceWillSendRequest, RecordType.ResourceSendRequest, RecordType.ResourceReceiveResponse, RecordType.ResourceReceivedData, RecordType.ResourceFinish, RecordType.ResourceMarkAsCached, ]); const events = this.inspectedTargetEvents(); for (let i = 0; i < events.length; ++i) { const e = events[i]; if (!resourceTypes.has(e.name)) { continue; } const id = TimelineModelImpl.globalEventId(e, 'requestId'); const requestId = e.args?.data?.requestId; if (e.name === RecordType.ResourceSendRequest && requestId && this.requestsFromBrowser.has(requestId)) { const event = this.requestsFromBrowser.get(requestId); if (event) { addRequest(event, id); } } addRequest(e, id); } function addRequest(e: SDK.TracingModel.Event, id: string): void { let request = requests.get(id); if (request) { request.addEvent(e); } else { request = new NetworkRequest(e); requests.set(id, request); if (request.startTime) { requestsList.push(request); } else { zeroStartRequestsList.push(request); } } } return zeroStartRequestsList.concat(requestsList); } } // TODO(crbug.com/1167717): Make this a const enum again // eslint-disable-next-line rulesdir/const_enum export enum RecordType { Task = 'RunTask', Program = 'Program', EventDispatch = 'EventDispatch', GPUTask = 'GPUTask', Animation = 'Animation', RequestMainThreadFrame = 'RequestMainThreadFrame', BeginFrame = 'BeginFrame', NeedsBeginFrameChanged = 'NeedsBeginFrameChanged', BeginMainThreadFrame = 'BeginMainThreadFrame', ActivateLayerTree = 'ActivateLayerTree', DrawFrame = 'DrawFrame', DroppedFrame = 'DroppedFrame', HitTest = 'HitTest', ScheduleStyleRecalculation = 'ScheduleStyleRecalculation', RecalculateStyles = 'RecalculateStyles', UpdateLayoutTree = 'UpdateLayoutTree', InvalidateLayout = 'InvalidateLayout', Layout = 'Layout', LayoutShift = 'LayoutShift', UpdateLayer = 'UpdateLayer', UpdateLayerTree = 'UpdateLayerTree', PaintSetup = 'PaintSetup', Paint = 'Paint', PaintImage = 'PaintImage', Rasterize = 'Rasterize', RasterTask = 'RasterTask', ScrollLayer = 'ScrollLayer', CompositeLayers = 'CompositeLayers', ComputeIntersections = 'IntersectionObserverController::computeIntersections', InteractiveTime = 'InteractiveTime', ScheduleStyleInvalidationTracking = 'ScheduleStyleInvalidationTracking', StyleRecalcInvalidationTracking = 'StyleRecalcInvalidationTracking', StyleInvalidatorInvalidationTracking = 'StyleInvalidatorInvalidationTracking', LayoutInvalidationTracking = 'LayoutInvalidationTracking', ParseHTML = 'ParseHTML', ParseAuthorStyleSheet = 'ParseAuthorStyleSheet', TimerInstall = 'TimerInstall', TimerRemove = 'TimerRemove', TimerFire = 'TimerFire', XHRReadyStateChange = 'XHRReadyStateChange', XHRLoad = 'XHRLoad', CompileScript = 'v8.compile', CompileCode = 'V8.CompileCode', OptimizeCode = 'V8.OptimizeCode', EvaluateScript = 'EvaluateScript', CacheScript = 'v8.produceCache', CompileModule = 'v8.compileModule', EvaluateModule = 'v8.evaluateModule', CacheModule = 'v8.produceModuleCache', WasmStreamFromResponseCallback = 'v8.wasm.streamFromResponseCallback', WasmCompiledModule = 'v8.wasm.compiledModule', WasmCachedModule = 'v8.wasm.cachedModule', WasmModuleCacheHit = 'v8.wasm.moduleCacheHit', WasmModuleCacheInvalid = 'v8.wasm.moduleCacheInvalid', FrameStartedLoading = 'FrameStartedLoading', CommitLoad = 'CommitLoad', MarkLoad = 'MarkLoad', MarkDOMContent = 'MarkDOMContent', MarkFirstPaint = 'firstPaint', MarkFCP = 'firstContentfulPaint', MarkLCPCandidate = 'largestContentfulPaint::Candidate', MarkLCPInvalidate = 'largestContentfulPaint::Invalidate', NavigationStart = 'navigationStart', TimeStamp = 'TimeStamp', ConsoleTime = 'ConsoleTime', UserTiming = 'UserTiming', ResourceWillSendRequest = 'ResourceWillSendRequest', ResourceSendRequest = 'ResourceSendRequest', ResourceReceiveResponse = 'ResourceReceiveResponse', ResourceReceivedData = 'ResourceReceivedData', ResourceFinish = 'ResourceFinish', ResourceMarkAsCached = 'ResourceMarkAsCached', RunMicrotasks = 'RunMicrotasks', FunctionCall = 'FunctionCall', GCEvent = 'GCEvent', MajorGC = 'MajorGC', MinorGC = 'MinorGC', JSFrame = 'JSFrame', JSSample = 'JSSample', // V8Sample events are coming from tracing and contain raw stacks with function addresses. // After being processed with help of JitCodeAdded and JitCodeMoved events they // get translated into function infos and stored as stacks in JSSample events. V8Sample = 'V8Sample', JitCodeAdded = 'JitCodeAdded', JitCodeMoved = 'JitCodeMoved', StreamingCompileScript = 'v8.parseOnBackground', StreamingCompileScriptWaiting = 'v8.parseOnBackgroundWaiting', StreamingCompileScriptParsing = 'v8.parseOnBackgroundParsing', V8Execute = 'V8.Execute', UpdateCounters = 'UpdateCounters', RequestAnimationFrame = 'RequestAnimationFrame', CancelAnimationFrame = 'CancelAnimationFrame', FireAnimationFrame = 'FireAnimationFrame', RequestIdleCallback = 'RequestIdleCallback', CancelIdleCallback = 'CancelIdleCallback', FireIdleCallback = 'FireIdleCallback', WebSocketCreate = 'WebSocketCreate', WebSocketSendHandshakeRequest = 'WebSocketSendHandshakeRequest', WebSocketReceiveHandshakeResponse = 'WebSocketReceiveHandshakeResponse', WebSocketDestroy = 'WebSocketDestroy', EmbedderCallback = 'EmbedderCallback', SetLayerTreeId = 'SetLayerTreeId', TracingStartedInPage = 'TracingStartedInPage', TracingSessionIdForWorker = 'TracingSessionIdForWorker', DecodeImage = 'Decode Image', ResizeImage = 'Resize Image', DrawLazyPixelRef = 'Draw LazyPixelRef', DecodeLazyPixelRef = 'Decode LazyPixelRef', LazyPixelRef = 'LazyPixelRef', LayerTreeHostImplSnapshot = 'cc::LayerTreeHostImpl', PictureSnapshot = 'cc::Picture', DisplayItemListSnapshot = 'cc::DisplayItemList', LatencyInfo = 'LatencyInfo', LatencyInfoFlow = 'LatencyInfo.Flow', InputLatencyMouseMove = 'InputLatency::MouseMove', InputLatencyMouseWheel = 'InputLatency::MouseWheel', ImplSideFling = 'InputHandlerProxy::HandleGestureFling::started', GCCollectGarbage = 'BlinkGC.AtomicPhase', CryptoDoEncrypt = 'DoEncrypt', CryptoDoEncryptReply = 'DoEncryptReply', CryptoDoDecrypt = 'DoDecrypt', CryptoDoDecryptReply = 'DoDecryptReply', CryptoDoDigest = 'DoDigest', CryptoDoDigestReply = 'DoDigestReply', CryptoDoSign = 'DoSign', CryptoDoSignReply = 'DoSignReply', CryptoDoVerify = 'DoVerify', CryptoDoVerifyReply = 'DoVerifyReply', // CpuProfile is a virtual event created on frontend to support // serialization of CPU Profiles within tracing timeline data. CpuProfile = 'CpuProfile', Profile = 'Profile', AsyncTask = 'AsyncTask', } export namespace TimelineModelImpl { export const Category = { Console: 'blink.console', UserTiming: 'blink.user_timing', LatencyInfo: 'latencyInfo', Loading: 'loading', }; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line rulesdir/const_enum export enum WarningType { LongTask = 'LongTask', ForcedStyle = 'ForcedStyle', ForcedLayout = 'ForcedLayout', IdleDeadlineExceeded = 'IdleDeadlineExceeded', LongHandler = 'LongHandler', LongRecurringHandler = 'LongRecurringHandler', V8Deopt = 'V8Deopt', } export const WorkerThreadName = 'DedicatedWorker thread'; export const WorkerThreadNameLegacy = 'DedicatedWorker Thread'; export const RendererMainThreadName = 'CrRendererMain'; export const BrowserMainThreadName = 'CrBrowserMain'; export const DevToolsMetadataEvent = { TracingStartedInBrowser: 'TracingStartedInBrowser', TracingStartedInPage: 'TracingStartedInPage', TracingSessionIdForWorker: 'TracingSessionIdForWorker', FrameCommittedInBrowser: 'FrameCommittedInBrowser', ProcessReadyInBrowser: 'ProcessReadyInBrowser', FrameDeletedInBrowser: 'FrameDeletedInBrowser', }; export const Thresholds = { LongTask: 50, Handler: 150, RecurringHandler: 50, ForcedLayout: 30, IdleCallbackAddon: 5, }; } export class Track { name: string; type: TrackType; forMainFrame: boolean; url: string; events: SDK.TracingModel.Event[]; asyncEvents: SDK.TracingModel.AsyncEvent[]; tasks: SDK.TracingModel.Event[]; private syncEventsInternal: SDK.TracingModel.Event[]|null; thread: SDK.TracingModel.Thread|null; constructor() { this.name = ''; this.type = TrackType.Other; // TODO(dgozman): replace forMainFrame with a list of frames, urls and time ranges. this.forMainFrame = false; this.url = ''; // TODO(dgozman): do not distinguish between sync and async events. this.events = []; this.asyncEvents = []; this.tasks = []; this.syncEventsInternal = null; this.thread = null; } syncEvents(): SDK.TracingModel.Event[] { if (this.events.length) { return this.events; } if (this.syncEventsInternal) { return this.syncEventsInternal; } const stack: SDK.TracingModel.Event[] = []; function peekLastEndTime(): number { const last = stack[stack.length - 1]; if (last !== undefined) { const endTime = last.endTime; if (endTime !== undefined) { return endTime; } } throw new Error('End time does not exist on event.'); } this.syncEventsInternal = []; for (const event of this.asyncEvents) { const startTime = event.startTime; let endTime: number|(number | undefined) = event.endTime; if (endTime === undefined) { endTime = startTime; } while (stack.length && startTime >= peekLastEndTime()) { stack.pop(); } if (stack.length && endTime > peekLastEndTime()) { this.syncEventsInternal = []; break; } const syncEvent = new SDK.TracingModel.Event( event.categoriesString, event.name, SDK.TracingModel.Phase.Complete, startTime, event.thread); syncEvent.setEndTime(endTime); syncEvent.addArgs(event.args); this.syncEventsInternal.push(syncEvent); stack.push(syncEvent); } return this.syncEventsInternal; } } // TODO(crbug.com/1167717): Make this a const enum again // eslint-disable-next-line rulesdir/const_enum export enum TrackType { MainThread = 'MainThread', Worker = 'Worker', Input = 'Input', Animation = 'Animation', Timings = 'Timings', Console = 'Console', Raster = 'Raster', GPU = 'GPU', Experience = 'Experience', Other = 'Other', } export class PageFrame { frameId: any; url: any; name: any; children: PageFrame[]; parent: PageFrame|null; processes: { time: number, processId: number, processPseudoId: string|null, url: string, }[]; deletedTime: number|null; ownerNode: SDK.DOMModel.DeferredDOMNode|null; constructor(payload: any) { this.frameId = payload['frame']; this.url = payload['url'] || ''; this.name = payload['name']; this.children = []; this.parent = null; this.processes = []; this.deletedTime = null; // TODO(dgozman): figure this out. // this.ownerNode = target && payload['nodeId'] ? new SDK.DOMModel.DeferredDOMNode(target, payload['nodeId']) : null; this.ownerNode = null; } update(time: number, payload: any): void { this.url = payload['url'] || ''; this.name = payload['name']; if (payload['processId']) { this.processes.push( {time: time, processId: payload['processId'], processPseudoId: '', url: payload['url'] || ''}); } else { this.processes.push( {time: time, processId: -1, processPseudoId: payload['processPseudoId'], url: payload['url'] || ''}); } } processReady(processPseudoId: string, processId: number): void { for (const process of this.processes) { if (process.processPseudoId === processPseudoId) { process.processPseudoId = ''; process.processId = processId; } } } addChild(child: PageFrame): void { this.children.push(child); child.parent = this; } } export class NetworkRequest { startTime: number; endTime: number; encodedDataLength: number; decodedBodyLength: number; children: SDK.TracingModel.Event[]; timing!: { pushStart: number, requestTime: number, sendStart: number, receiveHeadersEnd: number, }; mimeType!: string; url!: string; requestMethod!: string; private transferSize: number; private maybeDiskCached: boolean; private memoryCachedInternal: boolean; priority?: any; finishTime?: number; responseTime?: number; fromServiceWorker?: boolean; hasCachedResource?: boolean; constructor(event: SDK.TracingModel.Event) { const isInitial = event.name === RecordType.ResourceSendRequest || event.name === RecordType.ResourceWillSendRequest; this.startTime = isInitial ? event.startTime : 0; this.endTime = Infinity; this.encodedDataLength = 0; this.decodedBodyLength = 0; this.children = []; this.transferSize = 0; this.maybeDiskCached = false; this.memoryCachedInternal = false; this.addEvent(event); } addEvent(event: SDK.TracingModel.Event): void { this.children.push(event); // This Math.min is likely because of BUG(chromium:865066). this.startTime = Math.min(this.startTime, event.startTime); const eventData = event.args['data']; if (eventData['mimeType']) { this.mimeType = eventData['mimeType']; } if ('priority' in eventData) { this.priority = eventData['priority']; } if (event.name === RecordType.ResourceFinish) { this.endTime = event.startTime; } if (eventData['finishTime']) { this.finishTime = eventData['finishTime'] * 1000; } if (!this.responseTime && (event.name === RecordType.ResourceReceiveResponse || event.name === RecordType.ResourceReceivedData)) { this.responseTime = event.startTime; } const encodedDataLength = eventData['encodedDataLength'] || 0; if (event.name === RecordType.ResourceMarkAsCached) { // This is a reliable signal for memory caching. this.memoryCachedInternal = true; } if (event.name === RecordType.ResourceReceiveResponse) { if (eventData['fromCache']) { // See BUG(chromium:998397): back-end over-approximates caching. this.maybeDiskCached = true; } if (eventData['fromServiceWorker']) { this.fromServiceWorker = true; } if (eventData['hasCachedResource']) { this.hasCachedResource = true; } this.encodedDataLength = encodedDataLength; } if (event.name === RecordType.ResourceReceivedData) { this.encodedDataLength += encodedDataLength; } if (event.name === RecordType.ResourceFinish && encodedDataLength) { this.encodedDataLength = encodedDataLength; // If a ResourceFinish event with an encoded data length is received, // then the resource was not cached; it was fetched before it was // requested, e.g. because it was pushed in this navigation. this.transferSize = encodedDataLength; } const decodedBodyLength = eventData['decodedBodyLength']; if (event.name === RecordType.ResourceFinish && decodedBodyLength) { this.decodedBodyLength = decodedBodyLength; } if (!this.url) { this.url = eventData['url']; } if (!this.requestMethod) { this.requestMethod = eventData['requestMethod']; } if (!this.timing) { this.timing = eventData['timing']; } if (eventData['fromServiceWorker']) { this.fromServiceWorker = true; } } /** * Return whether this request was cached. This works around BUG(chromium:998397), * which reports pushed resources, and resources serverd by a service worker as * disk cached. Pushed resources that were not disk cached, however, have a non-zero * `transferSize`. */ cached(): boolean { return Boolean(this.memoryCachedInternal) || (Boolean(this.maybeDiskCached) && !this.transferSize && !this.fromServiceWorker); } /** * Return whether this request was served from a memory cache. */ memoryCached(): boolean { return this.memoryCachedInternal; } /** * Get the timing information for this request. If the request was cached, * the timing refers to the original (uncached) load, and should not be used. */ getSendReceiveTiming(): { sendStartTime: number, headersEndTime: number, } { if (this.cached() || !this.timing) { // If the request is served from cache, the timing refers to the original // resource load, and should not be used. return {sendStartTime: this.startTime, headersEndTime: this.startTime}; } const requestTime = this.timing.requestTime * 1000; const sendStartTime = requestTime + this.timing.sendStart; const headersEndTime = requestTime + this.timing.receiveHeadersEnd; return {sendStartTime, headersEndTime}; } /** * Get the start time of this request, i.e. the time when the browser or * renderer queued this request. There are two cases where request time is * earlier than `startTime`: (1) if the request is served from cache, because * it refers to the original load of the resource. (2) if the request was * initiated by the browser instead of the renderer. Only in case (2) the * the request time must be used instead of the start time to work around * BUG(chromium:865066). */ getStartTime(): number { return Math.min(this.startTime, !this.cached() && this.timing && this.timing.requestTime * 1000 || Infinity); } /** * Returns the time where the earliest event belonging to this request starts. * This differs from `getStartTime()` if a previous HTTP/2 request pushed the * resource proactively: Then `beginTime()` refers to the time the push was received. */ beginTime(): number { // `pushStart` is referring to the original push if the request was cached (i.e. in // general not the most recent push), and should hence only be used for requests that were not cached. return Math.min(this.getStartTime(), !this.cached() && this.timing && this.timing.pushStart * 1000 || Infinity); } } export class InvalidationTrackingEvent { type: string; startTime: number; readonly tracingEvent: SDK.TracingModel.Event; frame: number; nodeId: number|null; nodeName: string|null; invalidationSet: number|null; invalidatedSelectorId: string|null; changedId: string|null; changedClass: string|null; changedAttribute: string|null; changedPseudo: string|null; selectorPart: string|null; extraData: string|null; invalidationList: { [x: string]: number, }[]|null; cause: InvalidationCause; linkedRecalcStyleEvent: boolean; linkedLayoutEvent: boolean; constructor(event: SDK.TracingModel.Event, timelineData: TimelineData) { this.type = event.name; this.startTime = event.startTime; this.tracingEvent = event; const eventData = event.args['data']; this.frame = eventData['frame']; this.nodeId = eventData['nodeId']; this.nodeName = eventData['nodeName']; this.invalidationSet = eventData['invalidationSet']; this.invalidatedSelectorId = eventData['invalidatedSelectorId']; this.changedId = eventData['changedId']; this.changedClass = eventData['changedClass']; this.changedAttribute = eventData['changedAttribute']; this.changedPseudo = eventData['changedPseudo']; this.selectorPart = eventData['selectorPart']; this.extraData = eventData['extraData']; this.invalidationList = eventData['invalidationList']; this.cause = {reason: eventData['reason'], stackTrace: timelineData.stackTrace}; this.linkedRecalcStyleEvent = false; this.linkedLayoutEvent = false; // FIXME: Move this to TimelineUIUtils.js. if (!this.cause.reason && this.cause.stackTrace && this.type === RecordType.LayoutInvalidationTracking) { this.cause.reason = 'Layout forced'; } } } export class InvalidationTracker { private lastRecalcStyle: SDK.TracingModel.Event|null; private lastPaintWithLayer: SDK.TracingModel.Event|null; didPaint: boolean; private invalidations: { [x: string]: InvalidationTrackingEvent[], }; private invalidationsByNodeId: { [x: number]: InvalidationTrackingEvent[], }; constructor() { this.lastRecalcStyle = null; this.lastPaintWithLayer = null; this.didPaint = false; this.initializePerFrameState(); this.invalidations = {}; this.invalidationsByNodeId = {}; } static invalidationEventsFor(event: SDK.TracingModel.Event): InvalidationTrackingEvent[]|null { return eventToInvalidation.get(event) || null; } addInvalidation(invalidation: InvalidationTrackingEvent): void { this.startNewFrameIfNeeded(); if (!invalidation.nodeId) { console.error('Invalidation lacks node information.'); console.error(invalidation); return; } // Suppress StyleInvalidator StyleRecalcInvalidationTracking invalidations because they // will be handled by StyleInvalidatorInvalidationTracking. // FIXME: Investigate if we can remove StyleInvalidator invalidations entirely. if (invalidation.type === RecordType.StyleRecalcInvalidationTracking && invalidation.cause.reason === 'StyleInvalidator') { return; } // Style invalidation events can occur before and during recalc style. didRecalcStyle // handles style invalidations that occur before the recalc style event but we need to // handle style recalc invalidations during recalc style here. const styleRecalcInvalidation = (invalidation.type === RecordType.ScheduleStyleInvalidationTracking || invalidation.type === RecordType.StyleInvalidatorInvalidationTracking || invalidation.type === RecordType.StyleRecalcInvalidationTracking); if (styleRecalcInvalidation) { const duringRecalcStyle = invalidation.startTime && this.lastRecalcStyle && this.lastRecalcStyle.endTime !== undefined && invalidation.startTime >= this.lastRecalcStyle.startTime && invalidation.startTime <= this.lastRecalcStyle.endTime; if (duringRecalcStyle) { this.associateWithLastRecalcStyleEvent(invalidation); } } // Record the invalidation so later events can look it up. if (this.invalidations[invalidation.type]) { this.invalidations[invalidation.type].push(invalidation); } else { this.invalidations[invalidation.type] = [invalidation]; } if (invalidation.nodeId) { if (this.invalidationsByNodeId[invalidation.nodeId]) { this.invalidationsByNodeId[invalidation.nodeId].push(invalidation); } else { this.invalidationsByNodeId[invalidation.nodeId] = [invalidation]; } } } didRecalcStyle(recalcStyleEvent: SDK.TracingModel.Event): void { this.lastRecalcStyle = recalcStyleEvent; const types = [ RecordType.ScheduleStyleInvalidationTracking, RecordType.StyleInvalidatorInvalidationTracking, RecordType.StyleRecalcInvalidationTracking, ]; for (const invalidation of this.invalidationsOfTypes(types)) { this.associateWithLastRecalcStyleEvent(invalidation); } } private associateWithLastRecalcStyleEvent(invalidation: InvalidationTrackingEvent): void { if (invalidation.linkedRecalcStyleEvent) { return; } if (!this.lastRecalcStyle) { throw new Error('Last recalculate style event not set.'); } const recalcStyleFrameId = this.lastRecalcStyle.args['beginData']['frame']; if (invalidation.type === RecordType.StyleInvalidatorInvalidationTracking) { // Instead of calling addInvalidationToEvent directly, we create synthetic // StyleRecalcInvalidationTracking events which will be added in addInvalidationToEvent. this.addSyntheticStyleRecalcInvalidations(this.lastRecalcStyle, recalcStyleFrameId, invalidation); } else if (invalidation.type === RecordType.ScheduleStyleInvalidationTracking) { // ScheduleStyleInvalidationTracking events are only used for adding information to // StyleInvalidatorInvalidationTracking events. See: addSyntheticStyleRecalcInvalidations. } else { this.addInvalidationToEvent(this.lastRecalcStyle, recalcStyleFrameId, invalidation); } invalidation.linkedRecalcStyleEvent = true; } private addSyntheticStyleRecalcInvalidations( event: SDK.TracingModel.Event, frameId: number, styleInvalidatorInvalidation: InvalidationTrackingEvent): void { if (!styleInvalidatorInvalidation.invalidationList) { this.addSyntheticStyleRecalcInvalidation(styleInvalidatorInvalidation.tracingEvent, styleInvalidatorInvalidation); return; } if (!styleInvalidatorInvalidation.nodeId) { console.error('Invalidation lacks node information.'); console.error(styleInvalidatorInvalidation); return; } for (let i = 0; i < styleInvalidatorInvalidation.invalidationList.length; i++) { const setId = styleInvalidatorInvalidation.invalidationList[i]['id']; let lastScheduleStyleRecalculation; const nodeInvalidations = this.invalidationsByNodeId[styleInvalidatorInvalidation.nodeId] || []; for (let j = 0; j < nodeInvalidations.length; j++) { const invalidation = nodeInvalidations[j]; if (invalidation.frame !== frameId || invalidation.invalidationSet !== setId || invalidation.type !== RecordType.ScheduleStyleInvalidationTracking) { continue; } lastScheduleStyleRecalculation = invalidation; } if (!lastScheduleStyleRecalculation) { console.error('Failed to lookup the event that scheduled a style invalidator invalidation.'); continue; } this.addSyntheticStyleRecalcInvalidation( lastScheduleStyleRecalculation.tracingEvent, styleInvalidatorInvalidation); } } private addSyntheticStyleRecalcInvalidation( baseEvent: SDK.TracingModel.Event, styleInvalidatorInvalidation: InvalidationTrackingEvent): void { const timelineData = TimelineData.forEvent(baseEvent); const invalidation = new InvalidationTrackingEvent(baseEvent, timelineData); invalidation.type = RecordType.StyleRecalcInvalidationTracking; if (styleInvalidatorInvalidation.cause.reason) { invalidation.cause.reason = styleInvalidatorInvalidation.cause.reason; } if (styleInvalidatorInvalidation.selectorPart) { invalidation.selectorPart = styleInvalidatorInvalidation.selectorPart; } this.addInvalidation(invalidation); if (!invalidation.linkedRecalcStyleEvent) { this.associateWithLastRecalcStyleEvent(invalidation); } } didLayout(layoutEvent: SDK.TracingModel.Event): void { const layoutFrameId = layoutEvent.args['beginData']['frame']; for (const invalidation of this.invalidationsOfTypes([RecordType.LayoutInvalidationTracking])) { if (invalidation.linkedLayoutEvent) { continue; } this.addInvalidationToEvent(layoutEvent, layoutFrameId, invalidation); invalidation.linkedLayoutEvent = true; } } private addInvalidationToEvent( event: SDK.TracingModel.Event, eventFrameId: number, invalidation: InvalidationTrackingEvent): void { if (eventFrameId !== invalidation.frame) { return; } const invalidations = eventToInvalidation.get(event); if (!invalidations) { eventToInvalidation.set(event, [invalidation]); } else { invalidations.push(invalidation); } } private invalidationsOfTypes(types?: string[]): Generator<InvalidationTrackingEvent, any, any> { const invalidations = this.invalidations; if (!types) { types = Object.keys(invalidations); } function* generator(): Generator<InvalidationTrackingEvent, void, unknown> { if (!types) { return; } for (let i = 0; i < types.length; ++i) { const invalidationList = invalidations[types[i]] || []; for (let j = 0; j < invalidationList.length; ++j) { yield invalidationList[j]; } } } return generator(); } private startNewFrameIfNeeded(): void { if (!this.didPaint) { return; } this.initializePerFrameState(); } private initializePerFrameState(): void { this.invalidations = {}; this.invalidationsByNodeId = {}; this.lastRecalcStyle = null; this.lastPaintWithLayer = null; this.didPaint = false; } } export class TimelineAsyncEventTracker { private readonly initiatorByType: Map<RecordType, Map<RecordType, SDK.TracingModel.Event>>; constructor() { TimelineAsyncEventTracker.initialize(); this.initiatorByType = new Map(); if (TimelineAsyncEventTracker.asyncEvents) { for (const initiator of TimelineAsyncEventTracker.asyncEvents.keys()) { this.initiatorByType.set(initiator, new Map()); } } } private static initialize(): void { if (TimelineAsyncEventTracker.asyncEvents) { return; } const events = new Map<RecordType, { causes: RecordType[], joinBy: string, }>(); events.set(RecordType.TimerInstall, {causes: [RecordType.TimerFire], joinBy: 'timerId'}); events.set(RecordType.ResourceSendRequest, { causes: [ RecordType.ResourceMarkAsCached, RecordType.ResourceReceiveResponse, RecordType.ResourceReceivedData, RecordType.ResourceFinish, ], joinBy: 'requestId', }); events.set(RecordType.RequestAnimationFrame, {causes: [RecordType.FireAnimationFrame], joinBy: 'id'}); events.set(RecordType.RequestIdleCallback, {causes: [RecordType.FireIdleCallback], joinBy: 'id'}); events.set(RecordType.WebSocketCreate, { causes: [ RecordType.WebSocketSendHandshakeRequest, RecordType.WebSocketReceiveHandshakeResponse, RecordType.WebSocketDestroy, ], joinBy: 'identifier', }); TimelineAsyncEventTracker.asyncEvents = events; TimelineAsyncEventTracker.typeToInitiator = new Map(); for (const entry of events) { const types = entry[1].causes; for (const currentType of types) { TimelineAsyncEventTracker.typeToInitiator.set(currentType, entry[0]); } } } processEvent(event: SDK.TracingModel.Event): void { if (!TimelineAsyncEventTracker.typeToInitiator || !TimelineAsyncEventTracker.asyncEvents) { return; } let initiatorType: RecordType|undefined = TimelineAsyncEventTracker.typeToInitiator.get((event.name as RecordType)); const isInitiator = !initiatorType; if (!initiatorType) { initiatorType = (event.name as RecordType); } const initiatorInfo = TimelineAsyncEventTracker.asyncEvents.get(initiatorType); if (!initiatorInfo) { return; } const id = (TimelineModelImpl.globalEventId(event, initiatorInfo.joinBy) as RecordType); if (!id) { return; } const initiatorMap: Map<RecordType, SDK.TracingModel.Event>|undefined = this.initiatorByType.get(initiatorType); if (initiatorMap) { if (isInitiator) { initiatorMap.set(id, event); return; } const initiator = initiatorMap.get(id); const timelineData = TimelineData.forEvent(event); timelineData.setInitiator(initiator ? initiator : null); if (!timelineData.frameId && initiator) { timelineData.frameId = TimelineModelImpl.eventFrameId(initiator); } } } private static asyncEvents: Map<RecordType, {causes: RecordType[], joinBy: string}>|null = null; private static typeToInitiator: Map<RecordType, RecordType>|null = null; } export class TimelineData { warning: string|null; previewElement: Element|null; url: string|null; backendNodeIds: Protocol.DOM.BackendNodeId[]; stackTrace: Protocol.Runtime.CallFrame[]|null; picture: SDK.TracingModel.ObjectSnapshot|null; private initiatorInternal: SDK.TracingModel.Event|null; frameId: Protocol.Page.FrameId|null; timeWaitingForMainThread?: number; constructor() { this.warning = null; this.previewElement = null; this.url = null; this.backendNodeIds = []; this.stackTrace = null; this.picture = null; this.initiatorInternal = null; this.frameId = null; } setInitiator(initiator: SDK.TracingModel.Event|null): void { this.initiatorInternal = initiator; if (!initiator || this.url) { return; } const initiatorURL = TimelineData.forEvent(initiator).url; if (initiatorURL) { this.url = initiatorURL; } } initiator(): SDK.TracingModel.Event|null { return this.initiatorInternal; } topFrame(): Protocol.Runtime.CallFrame|null { const stackTrace = this.stackTraceForSelfOrInitiator(); return stackTrace && stackTrace[0] || null; } stackTraceForSelfOrInitiator(): Protocol.Runtime.CallFrame[]|null { return this.stackTrace || (this.initiatorInternal && TimelineData.forEvent(this.initiatorInternal).stackTrace); } static forEvent(event: SDK.TracingModel.Event): TimelineData { let data = eventToData.get(event); if (!data) { data = new TimelineData(); eventToData.set(event, data); } return data; } } const eventToData = new WeakMap(); const eventToInvalidation = new WeakMap(); export interface InvalidationCause { reason: string; stackTrace: Protocol.Runtime.CallFrame[]|null; } export interface MetadataEvents { page: SDK.TracingModel.Event[]; workers: SDK.TracingModel.Event[]; }
the_stack
import { Priority, Task, Timer } from "@clarity-types/core"; import { Code, Event, Metric, Severity } from "@clarity-types/data"; import { Constant, MutationHistory, MutationQueue, Setting, Source } from "@clarity-types/layout"; import { bind } from "@src/core/event"; import measure from "@src/core/measure"; import * as task from "@src/core/task"; import { time } from "@src/core/time"; import { clearTimeout, setTimeout } from "@src/core/timeout"; import { id } from "@src/data/metadata"; import * as summary from "@src/data/summary"; import * as internal from "@src/diagnostic/internal"; import * as doc from "@src/layout/document"; import * as dom from "@src/layout/dom"; import encode from "@src/layout/encode"; import * as region from "@src/layout/region"; import traverse from "@src/layout/traverse"; import processNode from "./node"; let observers: MutationObserver[] = []; let mutations: MutationQueue[] = []; let insertRule: (rule: string, index?: number) => number = null; let deleteRule: (index?: number) => void = null; let attachShadow: (init: ShadowRootInit) => ShadowRoot = null; let queue: Node[] = []; let timeout: number = null; let activePeriod = null; let history: MutationHistory = {}; export function start(): void { observers = []; queue = []; timeout = null; activePeriod = 0; history = {}; if (insertRule === null) { insertRule = CSSStyleSheet.prototype.insertRule; } if (deleteRule === null) { deleteRule = CSSStyleSheet.prototype.deleteRule; } if (attachShadow === null) { attachShadow = Element.prototype.attachShadow; } // Some popular open source libraries, like styled-components, optimize performance // by injecting CSS using insertRule API vs. appending text node. A side effect of // using javascript API is that it doesn't trigger DOM mutation and therefore we // need to override the insertRule API and listen for changes manually. CSSStyleSheet.prototype.insertRule = function(): number { schedule(this.ownerNode); return insertRule.apply(this, arguments); }; CSSStyleSheet.prototype.deleteRule = function(): void { schedule(this.ownerNode); return deleteRule.apply(this, arguments); }; // Add a hook to attachShadow API calls // In case we are unable to add a hook and browser throws an exception, // reset attachShadow variable and resume processing like before try { Element.prototype.attachShadow = function (): ShadowRoot { return schedule(attachShadow.apply(this, arguments)) as ShadowRoot; } } catch { attachShadow = null; } } export function observe(node: Node): void { // Create a new observer for every time a new DOM tree (e.g. root document or shadowdom root) is discovered on the page // In the case of shadow dom, any mutations that happen within the shadow dom are not bubbled up to the host document // For this reason, we need to wire up mutations every time we see a new shadow dom. // Also, wrap it inside a try / catch. In certain browsers (e.g. legacy Edge), observer on shadow dom can throw errors try { // In an edge case, it's possible to get stuck into infinite Mutation loop within Angular applications // This appears to be an issue with Zone.js package, see: https://github.com/angular/angular/issues/31712 // As a temporary work around, ensuring Clarity can invoke MutationObserver outside of Zone (and use native implementation instead) let api: string = window[Constant.Zone] && Constant.Symbol in window[Constant.Zone] ? window[Constant.Zone][Constant.Symbol](Constant.MutationObserver) : Constant.MutationObserver; let observer = api in window ? new window[api](measure(handle) as MutationCallback) : null; if (observer) { observer.observe(node, { attributes: true, childList: true, characterData: true, subtree: true }); observers.push(observer); } } catch (e) { internal.log(Code.MutationObserver, Severity.Info, e ? e.name : null); } } export function monitor(frame: HTMLIFrameElement): void { // Bind to iframe's onload event so we get notified anytime there's an update to iframe content. // This includes cases where iframe location is updated without explicitly updating src attribute // E.g. iframe.contentWindow.location.href = "new-location"; if (dom.has(frame) === false) { bind(frame, Constant.LoadEvent, generate.bind(this, frame, Constant.ChildList), true); } } export function stop(): void { for (let observer of observers) { if (observer) { observer.disconnect(); } } observers = []; // Restoring original insertRule if (insertRule !== null) { CSSStyleSheet.prototype.insertRule = insertRule; insertRule = null; } // Restoring original deleteRule if (deleteRule !== null) { CSSStyleSheet.prototype.deleteRule = deleteRule; deleteRule = null; } // Restoring original attachShadow if (attachShadow != null) { Element.prototype.attachShadow = attachShadow; attachShadow = null; } history = {}; mutations = []; queue = []; activePeriod = 0; timeout = null; } export function active(): void { activePeriod = time() + Setting.MutationActivePeriod; } function handle(m: MutationRecord[]): void { // Queue up mutation records for asynchronous processing let now = time(); summary.track(Event.Mutation, now); mutations.push({ time: now, mutations: m}); task.schedule(process, Priority.High).then((): void => { measure(doc.compute)(); measure(region.compute)(); }); } async function process(): Promise<void> { let timer: Timer = { id: id(), cost: Metric.LayoutCost }; task.start(timer); while (mutations.length > 0) { let record = mutations.shift(); for (let mutation of record.mutations) { let state = task.state(timer); if (state === Task.Wait) { state = await task.suspend(timer); } if (state === Task.Stop) { break; } let target = mutation.target; let type = track(mutation, timer); if (type && target && target.ownerDocument) { dom.parse(target.ownerDocument); } if (type && target && target.nodeType == Node.DOCUMENT_FRAGMENT_NODE && (target as ShadowRoot).host) { dom.parse(target as ShadowRoot); } switch (type) { case Constant.Attributes: processNode(target, Source.Attributes); break; case Constant.CharacterData: processNode(target, Source.CharacterData); break; case Constant.ChildList: processNodeList(mutation.addedNodes, Source.ChildListAdd, timer); processNodeList(mutation.removedNodes, Source.ChildListRemove, timer); break; case Constant.Suspend: let value = dom.get(target); if (value) { value.metadata.suspend = true; } break; default: break; } } await encode(Event.Mutation, timer, record.time); } task.stop(timer); } function track(m: MutationRecord, timer: Timer): string { let value = m.target ? dom.get(m.target.parentNode) : null; // Check if the parent is already discovered and that the parent is not the document root if (value && value.data.tag !== Constant.HTML) { let inactive = time() > activePeriod; let target = dom.get(m.target); let element = target && target.selector ? target.selector.join() : m.target.nodeName; let parent = value.selector ? value.selector.join() : Constant.Empty; // We use selector, instead of id, to determine the key (signature for the mutation) because in some cases // repeated mutations can cause elements to be destroyed and then recreated as new DOM nodes // In those cases, IDs will change however the selector (which is relative to DOM xPath) remains the same let key = [parent, element, m.attributeName, names(m.addedNodes), names(m.removedNodes)].join(); // Initialize an entry if it doesn't already exist history[key] = key in history ? history[key] : [0]; let h = history[key]; // Lookup any pending nodes queued up for removal, and process them now if we suspended a mutation before if (inactive === false && h[0] >= Setting.MutationSuspendThreshold) { processNodeList(h[1], Source.ChildListRemove, timer); } // Update the counter h[0] = inactive ? h[0] + 1 : 1; // Return updated mutation type based on if we have already hit the threshold or not if (h[0] === Setting.MutationSuspendThreshold) { // Store a reference to removedNodes so we can process them later // when we resume mutations again on user interactions h[1] = m.removedNodes; return Constant.Suspend; } else if (h[0] > Setting.MutationSuspendThreshold) { return Constant.Empty; } } return m.type; } function names(nodes: NodeList): string { let output: string[] = []; for (let i = 0; nodes && i < nodes.length; i++) { output.push(nodes[i].nodeName); } return output.join(); } async function processNodeList(list: NodeList, source: Source, timer: Timer): Promise<void> { let length = list ? list.length : 0; for (let i = 0; i < length; i++) { if (source === Source.ChildListAdd) { traverse(list[i], timer, source); } else { let state = task.state(timer); if (state === Task.Wait) { state = await task.suspend(timer); } if (state === Task.Stop) { break; } processNode(list[i], source); } } } function schedule(node: Node): Node { // Only schedule manual trigger for this node if it's not already in the queue if (queue.indexOf(node) < 0) { queue.push(node); } // Cancel any previous trigger before scheduling a new one. // It's common for a webpage to call multiple synchronous "insertRule" / "deleteRule" calls. // And in those cases we do not wish to monitor changes multiple times for the same node. if (timeout) { clearTimeout(timeout); } timeout = setTimeout(trigger, Setting.LookAhead); return node; } function trigger(): void { for (let node of queue) { let shadowRoot = node && node.nodeType === Node.DOCUMENT_FRAGMENT_NODE; // Skip re-processing shadowRoot if it was already discovered if (shadowRoot && dom.has(node)) { continue; } generate(node, shadowRoot ? Constant.ChildList : Constant.CharacterData); } queue = []; } function generate(target: Node, type: MutationRecordType): void { measure(handle)([{ addedNodes: [target], attributeName: null, attributeNamespace: null, nextSibling: null, oldValue: null, previousSibling: null, removedNodes: [], target, type }]); }
the_stack
import { InternalSchema, ModelAttributeAuthAllow, ModelAttributeAuthProperty, ModelAttributeAuthProvider, ModelOperation, } from '../src/types'; import { NAMESPACES } from '../src/util'; import { GRAPHQL_AUTH_MODE } from '@aws-amplify/auth'; describe('Auth Strategies', () => { describe('multiAuthStrategy', () => { const rules = { function: { provider: ModelAttributeAuthProvider.FUNCTION, allow: ModelAttributeAuthAllow.CUSTOM, operations: ['create', 'update', 'delete', 'read'], }, owner: { provider: ModelAttributeAuthProvider.USER_POOLS, ownerField: 'owner', allow: ModelAttributeAuthAllow.OWNER, identityClaim: 'cognito:username', operations: ['create', 'update', 'delete', 'read'], }, ownerOIDC: { provider: ModelAttributeAuthProvider.OIDC, ownerField: 'owner', allow: ModelAttributeAuthAllow.OWNER, identityClaim: 'sub', operations: ['create', 'update', 'delete', 'read'], }, group: { groupClaim: 'cognito:groups', provider: ModelAttributeAuthProvider.USER_POOLS, allow: ModelAttributeAuthAllow.GROUPS, groups: ['Admin'], operations: ['create', 'update', 'delete', 'read'], }, groupOIDC: { groupClaim: 'customGroups', provider: ModelAttributeAuthProvider.OIDC, allow: ModelAttributeAuthAllow.GROUPS, customGroups: ['Admin'], operations: ['create', 'update', 'delete', 'read'], }, privateUserPoolsExplicit: { provider: ModelAttributeAuthProvider.USER_POOLS, allow: ModelAttributeAuthAllow.PRIVATE, operations: ['create', 'update', 'delete', 'read'], }, privateUserPoolsImplicit: { allow: ModelAttributeAuthAllow.PRIVATE, operations: ['create', 'update', 'delete', 'read'], }, privateIAM: { provider: ModelAttributeAuthProvider.IAM, allow: ModelAttributeAuthAllow.PRIVATE, operations: ['create', 'update', 'delete', 'read'], }, publicIAM: { provider: ModelAttributeAuthProvider.IAM, allow: ModelAttributeAuthAllow.PUBLIC, operations: ['create', 'update', 'delete', 'read'], }, publicAPIKeyExplicit: { provider: ModelAttributeAuthProvider.API_KEY, allow: ModelAttributeAuthAllow.PUBLIC, operations: ['create', 'update', 'delete', 'read'], }, publicAPIKeyImplicit: { allow: ModelAttributeAuthAllow.PUBLIC, operations: ['create', 'update', 'delete', 'read'], }, }; test('function', async () => { const authRules = [rules.function]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AWS_LAMBDA'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: ['AWS_LAMBDA'], }); }); test('owner', async () => { const authRules = [rules.owner]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: [], }); }); test('owner OIDC', async () => { const authRules = [rules.ownerOIDC]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['OPENID_CONNECT'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: [], }); }); test('group', async () => { const authRules = [rules.group]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: [], }); }); test('group OIDC', async () => { const authRules = [rules.groupOIDC]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['OPENID_CONNECT'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: [], }); }); test('private User Pools', async () => { let authRules: any = [rules.privateUserPoolsExplicit]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: [], }); // private with no provider implies that the provider is AMAZON_COGNITO_USER_POOLS authRules = [rules.privateUserPoolsImplicit]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: [], }); }); test('private IAM', async () => { const authRules = [rules.privateIAM]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AWS_IAM'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: [], }); }); test('public IAM', async () => { const authRules = [rules.publicIAM]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AWS_IAM'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: ['AWS_IAM'], }); }); test('API key', async () => { let authRules: any = [rules.publicAPIKeyExplicit]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['API_KEY'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: ['API_KEY'], }); // public with no provider implies that the provider is API_KEY authRules = [rules.publicAPIKeyImplicit]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['API_KEY'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: ['API_KEY'], }); }); test('owner/group', async () => { const authRules = [rules.owner, rules.group]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: [], }); }); test('owner/OIDC', async () => { let authRules = [rules.owner, rules.ownerOIDC]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS', 'OPENID_CONNECT'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: [], }); // Test again with rules in reverse order authRules = [rules.ownerOIDC, rules.owner]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS', 'OPENID_CONNECT'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: [], }); }); test('owner/IAM private', async () => { const authRules = [rules.owner, rules.privateIAM]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS', 'AWS_IAM'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: [], }); }); test('owner/IAM public', async () => { const authRules = [rules.owner, rules.publicIAM]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS', 'AWS_IAM'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: ['AWS_IAM'], }); }); test('owner/API key', async () => { const authRules = [rules.owner, rules.publicAPIKeyExplicit]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS', 'API_KEY'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: ['API_KEY'], }); }); test('private User Pools/private IAM', async () => { let authRules = [rules.privateUserPoolsExplicit, rules.privateIAM]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS', 'AWS_IAM'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: [], }); // Test again with rules in reverse order authRules = [rules.privateIAM, rules.privateUserPoolsExplicit]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS', 'AWS_IAM'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: [], }); }); test('owner/private IAM/API key', async () => { const authRules = [ rules.owner, rules.privateIAM, rules.publicAPIKeyExplicit, ]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS', 'AWS_IAM', 'API_KEY'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: ['API_KEY'], }); }); test('owner/public IAM/API key', async () => { const authRules = [ rules.owner, rules.publicIAM, rules.publicAPIKeyExplicit, ]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS', 'AWS_IAM', 'API_KEY'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: ['AWS_IAM', 'API_KEY'], }); }); test('function/owner/public IAM/API key', async () => { const authRules = [ rules.function, rules.owner, rules.publicIAM, rules.publicAPIKeyExplicit, ]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: [ 'AWS_LAMBDA', 'AMAZON_COGNITO_USER_POOLS', 'AWS_IAM', 'API_KEY', ], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: ['AWS_LAMBDA', 'AWS_IAM', 'API_KEY'], }); }); test('duplicates', async () => { const authRules = [ rules.owner, rules.owner, rules.privateIAM, rules.privateIAM, rules.publicAPIKeyExplicit, rules.publicAPIKeyExplicit, rules.publicAPIKeyExplicit, ]; await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: true, result: ['AMAZON_COGNITO_USER_POOLS', 'AWS_IAM', 'API_KEY'], }); await testMultiAuthStrategy({ authRules, hasAuthenticatedUser: false, result: ['API_KEY'], }); }); }); describe('defaultAuthStrategy', () => { test('default', () => { const defaultAuthStrategy = require('../src/authModeStrategies/defaultAuthStrategy').defaultAuthStrategy; const schema = getAuthSchema(); expect( defaultAuthStrategy({ schema, modelName: 'Post', operation: ModelOperation.READ, }) ).toEqual([]); }); }); }); async function testMultiAuthStrategy({ authRules, hasAuthenticatedUser, result, }: { authRules: ModelAttributeAuthProperty[]; hasAuthenticatedUser: boolean; result: any; }) { mockCurrentUser({ hasAuthenticatedUser }); const multiAuthStrategy = require('../src/authModeStrategies/multiAuthStrategy').multiAuthStrategy; const schema = getAuthSchema(authRules); const authModes = await multiAuthStrategy({ schema, modelName: 'Post', // multiAuthStrategy does not currently use the `operation` param // but it still technically a required attribute in TS, since customers // won't actually be calling the function directly in their app. operation: ModelOperation.READ, }); expect(authModes).toEqual(result); jest.resetModules(); jest.resetAllMocks(); } function getAuthSchema( authRules: ModelAttributeAuthProperty[] = [] ): InternalSchema { const baseSchema: InternalSchema = { namespaces: { [NAMESPACES.USER]: { name: NAMESPACES.USER, models: { Post: { syncable: true, name: 'Post', pluralName: 'Posts', attributes: [{ type: 'model', properties: {} }], fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, title: { name: 'title', isArray: false, type: 'String', isRequired: true, attributes: [], }, }, }, }, enums: {}, nonModels: {}, }, }, version: 'a77c7728256031f4909aab05bfcaf798', }; return { ...baseSchema, namespaces: { ...baseSchema.namespaces, [NAMESPACES.USER]: { ...baseSchema.namespaces[NAMESPACES.USER], models: { ...baseSchema.namespaces[NAMESPACES.USER].models, Post: { ...baseSchema.namespaces[NAMESPACES.USER].models.Post, attributes: [ ...baseSchema.namespaces[NAMESPACES.USER].models.Post.attributes, { type: 'auth', properties: { rules: authRules, }, }, ], }, }, }, }, }; } function mockCurrentUser({ hasAuthenticatedUser, }: { hasAuthenticatedUser: boolean; }) { jest.mock('@aws-amplify/auth', () => ({ currentAuthenticatedUser: () => { return new Promise((res, rej) => { if (hasAuthenticatedUser) { res(hasAuthenticatedUser); } else { rej(hasAuthenticatedUser); } }); }, GRAPHQL_AUTH_MODE, })); }
the_stack
import { TextDocument, Position, CompletionList, CompletionItem, SnippetString, MarkdownString, CompletionItemKind, Range } from "vscode"; import { createTopicDocumentation, SelectedClusterProvider, TopicProvider } from "../kafkaFileLanguageService"; import { consumerModel, fakerjsAPIModel, Model, ModelDefinition, producerModel } from "../model"; import { Block, BlockType, Chunk, ConsumerBlock, KafkaFileDocument, CalleeFunction, MustacheExpression, NodeKind, Parameter, ProducerBlock, Property } from "../parser/kafkaFileParser"; /** * Supported encoding by nodejs Buffer. * * @see https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings */ const bufferEncoding = ["utf8", "utf16le", "base64", "latin1", "hex"]; /** * Kafka file completion support. */ export class KafkaFileCompletion { constructor(private selectedClusterProvider: SelectedClusterProvider, private topicProvider: TopicProvider) { } async doComplete(document: TextDocument, kafkaFileDocument: KafkaFileDocument, producerFakerJSEnabled: boolean, position: Position): Promise<CompletionList | undefined> { // Get the AST node before the position where complation was triggered const node = kafkaFileDocument.findNodeBefore(position); if (!node) { return; } // Following comments with use the '|' character to show the position where the compilation is triggered const items: Array<CompletionItem> = []; switch (node.kind) { case NodeKind.consumerBlock: { if (node.start.line !== position.line) { // CONSUMER // | const lineRange = document.lineAt(position.line).range; await this.collectConsumerPropertyNames(undefined, lineRange, <ConsumerBlock>node, items); } break; } case NodeKind.producerBlock: { if (node.start.line !== position.line) { // PRODUCER // | const lineRange = document.lineAt(position.line).range; await this.collectProducerPropertyNames(undefined, lineRange, <ProducerBlock>node, items); } break; } case NodeKind.producerValue: { // Check if previous line is a property const previous = new Position(position.line - 1, 1); const previousNode = kafkaFileDocument.findNodeBefore(previous); if (previousNode && previousNode.kind !== NodeKind.producerValue) { // PRODUCER // topic: abcd // | // or // PRODUCER // to|pic const lineRange = document.lineAt(position.line).range; const block = (previousNode.kind === NodeKind.producerBlock) ? <ProducerBlock>previousNode : <ProducerBlock>previousNode.parent; await this.collectProducerPropertyNames(undefined, lineRange, block, items); } break; } case NodeKind.property: { const property = <Property>node; const block = <Block>property.parent; if (property.isBeforeAssigner(position)) { const propertyName = position.line === property.start.line ? property.propertyName : undefined; const lineRange = document.lineAt(position.line).range; if (block.type === BlockType.consumer) { // CONSUMER // key|: // or // CONSUMER // key| await this.collectConsumerPropertyNames(propertyName, lineRange, <ConsumerBlock>block, items); } else { // PRODUCER // key|: await this.collectProducerPropertyNames(propertyName, lineRange, <ProducerBlock>block, items); } } else { const propertyValue = property.value; // Property value can be: // - a simple value -> abcd // - a mustache expression -> {{...}} // - a method parameter -> string(utf-8) const previousNode = propertyValue?.findNodeBefore(position); switch (previousNode?.kind) { case NodeKind.mustacheExpression: { // Completion was triggered inside a mustache expression which is inside the property value // PRODUCER // key: abcd-{{|}} const expression = <MustacheExpression>previousNode; this.collectFakerJSExpressions(expression, producerFakerJSEnabled, position, items); break; } case NodeKind.calleeFunction: { // Check if completion was triggered inside an empty method parameter const callee = <CalleeFunction>previousNode; if (callee.startParametersCharacter) { // PRODUCER // key-format: string(|) this.collectMethodParameters(callee, position, items); } else { // PRODUCER // key-format: | await this.collectDefaultPropertyValues(property, propertyValue, items); } break; } case NodeKind.parameter: { // Completion was triggered inside a method parameter which is inside the property value // PRODUCER // key-format: string(ut|f) // OR // PRODUCER // key-format: string(utf8, u|t) const parameter = <Parameter>previousNode; this.collectMethodParameters(<CalleeFunction>parameter.parent, position, items); break; } default: { await this.collectDefaultPropertyValues(property, propertyValue, items); } } } break; } case NodeKind.mustacheExpression: { // Completion was triggered inside a mustache expression which is inside the PRODUCER value // PRODUCER // topic: abcd // {{|}} const expression = <MustacheExpression>node; this.collectFakerJSExpressions(expression, producerFakerJSEnabled, position, items); break; } } return new CompletionList(items, true); } async collectConsumerPropertyNames(propertyName: string | undefined, lineRange: Range, block: ConsumerBlock, items: Array<CompletionItem>) { await this.collectPropertyNames(propertyName, lineRange, block, consumerModel, items); } async collectProducerPropertyNames(propertyName: string | undefined, lineRange: Range, block: ProducerBlock, items: Array<CompletionItem>) { await this.collectPropertyNames(propertyName, lineRange, block, producerModel, items); } async collectPropertyNames(propertyName: string | undefined, lineRange: Range, block: Block, metadata: Model, items: Array<CompletionItem>) { const existingProperties = block.properties .filter(property => property.key) .map(property => property.key?.content); for (const definition of metadata.definitions) { const currentName = definition.name; if (existingProperties.indexOf(currentName) === -1 || propertyName === currentName) { const item = new CompletionItem(currentName); item.kind = CompletionItemKind.Property; if (definition.description) { item.documentation = createMarkdownString(definition.description); } const insertText = new SnippetString(`${currentName}: `); const values = await this.getValues(definition); if (values) { insertText.appendChoice(values); } else { insertText.appendPlaceholder(currentName); } item.insertText = insertText; item.range = lineRange; items.push(item); } }; } async collectConsumerPropertyValues(propertyValue: Chunk | undefined, property: Property, block: ConsumerBlock, items: Array<CompletionItem>) { const propertyName = property.propertyName; switch (propertyName) { case 'topic': // CONSUMER // topic: | await this.collectTopics(property, items); break; default: // CONSUMER // key-format: | this.collectPropertyValues(propertyValue, property, block, consumerModel, items); break; } } async collectProducerPropertyValues(propertyValue: Chunk | undefined, property: Property, block: ProducerBlock, items: Array<CompletionItem>) { const propertyName = property.propertyName; switch (propertyName) { case 'topic': // PRODUCER // topic: | await this.collectTopics(property, items); break; default: // PRODUCER // key-format: | this.collectPropertyValues(propertyValue, property, block, producerModel, items); break; } } collectPropertyValues(propertyValue: Chunk | undefined, property: Property, block: Block, metadata: Model, items: Array<CompletionItem>) { const propertyName = property.propertyName; if (!propertyName) { return; } const definition = metadata.getDefinition(propertyName); if (!definition || !definition.enum) { return; } const valueRange = property.propertyValueRange; definition.enum.forEach((definition) => { const value = definition.name; const item = new CompletionItem(value); item.kind = CompletionItemKind.Value; if (definition.description) { item.documentation = createMarkdownString(definition.description); } const insertText = new SnippetString(' '); insertText.appendText(value); item.insertText = insertText; item.range = valueRange; items.push(item); if (value === 'string' && (propertyName === 'key-format' || propertyName === 'value-format')) { const item = new CompletionItem('string with encoding...'); item.kind = CompletionItemKind.Value; const insertText = new SnippetString(' '); insertText.appendText(value); insertText.appendText('('); insertText.appendChoice(bufferEncoding); insertText.appendText(')'); item.insertText = insertText; item.range = valueRange; items.push(item); } }); } collectFakerJSExpressions(expression: MustacheExpression, producerFakerJSEnabled: boolean, position: Position, items: CompletionItem[]) { if (!producerFakerJSEnabled || expression.isAfterAnUnexpectedEdge(position)) { return; } const expressionRange = expression.enclosedExpressionRange; const fakerjsAPI = fakerjsAPIModel.definitions; fakerjsAPI.forEach((definition) => { const value = definition.name; const item = new CompletionItem(value); item.kind = CompletionItemKind.Variable; if (definition.description) { item.documentation = createMarkdownString(definition.description); } const insertText = new SnippetString(''); insertText.appendText(value); item.insertText = insertText; item.range = expressionRange; items.push(item); }); } async collectTopics(property: Property, items: Array<CompletionItem>) { const { clusterId } = this.selectedClusterProvider.getSelectedCluster(); if (!clusterId) { return; } const valueRange = property.propertyValueRange; try { const topics = await this.topicProvider.getTopics(clusterId); topics.forEach((topic) => { const value = topic.id; const item = new CompletionItem(value); item.kind = CompletionItemKind.Value; item.documentation = new MarkdownString(createTopicDocumentation(topic)); const insertText = new SnippetString(' '); insertText.appendText(value); item.insertText = insertText; item.range = valueRange; items.push(item); }); } catch (e) { } } async getValues(definition: ModelDefinition): Promise<string[] | undefined> { if (definition.enum) { return definition.enum.map(item => item.name); } if (definition.name === 'topic') { // TODO : manage list of topics as choices, but how to handle when cluster is not available? /*const { clusterId } = this.selectedClusterProvider.getSelectedCluster(); if (clusterId) { try { const topics = await this.topicProvider.getTopics(clusterId); if (topics.length > 0) { return topics.map(item => item.id); } } catch (e) { return; } }*/ } } collectMethodParameters(callee: CalleeFunction, position: Position, items: CompletionItem[]) { const parameter = callee.parameters.find(p => position.isAfterOrEqual(p.start) && position.isBeforeOrEqual(p.end)); if (!parameter) { return; } switch (callee.functionName) { case 'string': { const range = parameter.range(); bufferEncoding.forEach(encoding => { const item = new CompletionItem(encoding); item.kind = CompletionItemKind.EnumMember; item.range = range; items.push(item); }); } } } async collectDefaultPropertyValues(property: Property, propertyValue: Chunk | undefined, items: CompletionItem[]) { const block = <Block>property.parent; if (block.type === BlockType.consumer) { // CONSUMER // key-format: | await this.collectConsumerPropertyValues(propertyValue, property, <ConsumerBlock>block, items); } else { // PRODUCER // key-format: | await this.collectProducerPropertyValues(propertyValue, property, <ProducerBlock>block, items); } } } function createMarkdownString(contents: string) { const doc = new MarkdownString(contents); doc.isTrusted = true; return doc; }
the_stack
import * as chai from "chai"; import * as crypto from "crypto"; import Arweave from "../../web"; import { bufferToString, stringToBuffer } from "../../src/common/lib/utils"; const expect = chai.expect; let globals = <any>global; // globals.window = { Arweave: {} }; //@ts-ignore const arweave: Arweave = window.Arweave.init({ host: "arweave.net", protocol: "https", logging: false, }); //@ts-ignore window.arweave = arweave; const digestRegex = /^[a-z0-9-_]{43}$/i; const liveAddressBalance = "498557055636"; const liveAddress = "9_666Wkk2GzL0LGd3xhb0jY7HqNy71BaV4sULQlJsBQ"; const liveTxid = "CE-1SFiXqWUEu0aSTebE6LC0-5JBAc3IAehYGwdF5iI"; const liveDataTxid = "H53lxlOS3ZZ6_yHiTEYIoEkw-aBWjJ-koXssCKCU3z4"; describe("Initialization", function () { it("should have components", function () { expect(arweave.api).to.an("object"); expect(arweave.transactions).to.an("object"); expect(arweave.wallets).to.an("object"); expect(arweave.network).to.an("object"); expect(arweave.crypto).to.an("object"); expect(arweave.silo).to.an("object"); }); }); describe("Network Info", function () { it("should get network info", async function () { this.timeout(3000); const info = await arweave.network.getInfo(); const peers = await arweave.network.getPeers(); expect(info).to.be.an("object"); expect(Object.keys(info)).to.contain.members([ "height", "current", "release", "version", "blocks", ]); expect(info.height).to.be.a("number").greaterThan(0); expect(peers).to.be.an("array"); }); }); describe("Wallets and keys", function () { it("should generate valid JWKs", async function () { this.timeout(15000); const walletA = await arweave.wallets.generate(); const walletB = await arweave.wallets.generate(); expect(walletA).to.be.an("object", "New wallet is not an object"); expect(walletA).to.have.all.keys( "kty", "n", "e", "d", "p", "q", "dp", "dq", "qi" ); expect(walletA.kty).to.equal("RSA"); expect(walletA.e).to.equal("AQAB"); expect(walletA.n).to.match(/^[a-z0-9-_]{683}$/i); expect(walletA.d).to.match(/^[a-z0-9-_]{683}$/i); const addressA = await arweave.wallets.jwkToAddress(walletA); const addressB = await arweave.wallets.jwkToAddress(walletB); expect(addressA).to.be.a("string"); expect(addressA).to.match(digestRegex); expect(addressB).to.match(digestRegex); expect(addressA).to.not.equal(addressB); }); it("should get wallet info", async function () { this.timeout(5000); const wallet = await arweave.wallets.generate(); const address = await arweave.wallets.jwkToAddress(wallet); const balance = await arweave.wallets.getBalance(address); const lastTx = await arweave.wallets.getLastTransactionID(address); expect(balance).to.be.a("string"); expect(balance).to.equal("0"); expect(lastTx).to.be.a("string"); expect(lastTx).to.equal(""); const balanceB = await arweave.wallets.getBalance(liveAddress); const lastTxB = await arweave.wallets.getLastTransactionID(liveAddress); expect(balanceB).to.be.a("string"); expect(balanceB).to.equal(liveAddressBalance); expect(lastTxB).to.be.a("string"); expect(lastTxB).to.equal(liveTxid); }); }); describe("Transactions", function () { it("should create and sign transactions", async function () { this.timeout(5000); const wallet = await arweave.wallets.generate(); const transaction = await arweave.createTransaction( { data: "test" }, wallet ); transaction.addTag("test-tag-1", "test-value-1"); transaction.addTag("test-tag-2", "test-value-2"); transaction.addTag("test-tag-3", "test-value-3"); expect(transaction).to.be.an("object"); expect(transaction.get("data")).to.equal("dGVzdA"); expect(transaction.reward).to.match(/^[0-9]+$/); await arweave.transactions.sign(transaction, wallet); expect(Object.keys(transaction)).to.contain.members([ "id", "data", "tags", "signature", "reward", "owner", "last_tx", ]); expect(transaction.signature).to.match(/^[a-z0-9-_]+$/i); expect(transaction.id).to.match(digestRegex); const verified = await arweave.transactions.verify(transaction); expect(verified).to.be.a("boolean").and.to.be.true; //@ts-ignore // Needs ts-ignoring as tags are readonly so chaning the tag like this isn't // normally an allowed operation, but it's a test, so... transaction.tags[1].value = "dGVzdDI"; const verifiedWithModififedTags = await arweave.transactions.verify( transaction ); expect(verifiedWithModififedTags).to.be.a("boolean"); expect(verifiedWithModififedTags).to.be.false; }); it("should create and sign transactions using wallet", async function () { this.timeout(120000); const transaction = await arweave.createTransaction({ data: "test" }); await arweave.transactions.sign(transaction); const verified = await arweave.transactions.verify(transaction); expect(verified).to.be.a("boolean").and.to.be.true; }); it("should get transaction info", async function () { this.timeout(5000); const transactionStatus = await arweave.transactions.getStatus( liveDataTxid ); const transaction = await arweave.transactions.get(liveDataTxid); expect(transactionStatus).to.be.a("object"); expect(transactionStatus.confirmed).to.be.a("object"); expect(Object.keys(transactionStatus.confirmed!)).to.contain.members([ "block_indep_hash", "block_height", "number_of_confirmations", ]); expect(transactionStatus.confirmed!.block_indep_hash).to.be.a("string"); expect(transactionStatus.confirmed!.block_height).to.be.a("number"); expect(transactionStatus.confirmed!.number_of_confirmations).to.be.a( "number" ); expect(transaction.get("data", { decode: true, string: true })).to.contain( "<title>CommunityXYZ</title>" ); const verify = await arweave.transactions.verify(transaction); expect(verify).to.be.a("boolean").and.to.be.true; transaction.signature = "xxx"; const verifyResult = await (() => { return new Promise((resolve) => { arweave.transactions.verify(transaction).catch((error: any) => { resolve(error); }); }); })(); expect(verifyResult) .to.be.an.instanceOf(Error) .with.property("message") .and.match(/^.*invalid transaction signature.*$/i); }); it("should find transactions", async function () { this.timeout(5000); const results = await arweave.transactions.search( "Silo-Name", "BmjRGIsemI77+eQb4zX8" ); expect(results) .to.be.an("array") .which.contains("Sgmyo7nUqPpVQWUfK72p5yIpd85QQbhGaWAF-I8L6yE"); }); }); describe("Encryption", function () { it("should encrypt and decrypt using key round trip", async function () { this.timeout(5000); const text = "some data to encrypt"; const data = stringToBuffer(text); const key = crypto.randomBytes(32); const encrypted = await arweave.crypto.encrypt(data, key); expect(encrypted).to.have.lengthOf(48); const decrypted = await arweave.crypto.decrypt(encrypted, key); expect(bufferToString(decrypted)).to.equal(text); }); it("should encrypt and decrypt using passphrase round trip", async function () { this.timeout(5000); const text = "some data to encrypt"; const data = stringToBuffer(text); const key = "super-secret-password"; const encrypted = await arweave.crypto.encrypt(data, key); expect(encrypted).to.have.lengthOf(48); const decrypted = await arweave.crypto.decrypt(encrypted, key); expect(bufferToString(decrypted)).to.equal(text); }); }); describe("Silo Web", function () { it("should read Silo transaction", async function () { this.skip(); this.timeout(5000); // This is a manually generated silo transaction // data = 'something' // uri = 'secret.1' const transaction = arweave.transactions.fromRaw({ last_tx: "Sgmyo7nUqPpVQWUfK72p5yIpd85QQbhGaWAF-I8L6yE", owner: "pJjRtSRLpHUVAKCtWC9pjajI_VEpiPEEAHX0k1B1jrB_jDlZsMJPyGRVX6n7N16vNyDTnKAofC_aNmTFegW-uyJmdxsteO1TXKrR_KJvuv_vACX4N8BkSgplB7mTTALBMNPmiINHXkDSxZEkBxAGV0GyL8pLd2-0X6TG16wDFShyS7rZzW8xFsQYiAp9-g330hPhCV7KBdVFtCxA0h1RifDYloMUwHbAWCTvzm72aLI1nWaLzotcM4cZTTdzw5VTdGtjo9fMdoT7uTqikIIhM3C4f9Ws-ECqjBUXtZFg7q6jYbUcTVNr1o2UFPKbLnDl4vcUZBaeqkL0FWQuo7F1hw36PVm_b9lVVzSVVkeA_HF2tQotkaITyOQmYfTHi1d31m5fwFZje_M-YgeyvOIuiqX4-lIGz8pohTutY3Z5_LKfO_a8jsJL8_jFLqcjSCRvVZSRmQDpzB4hJ9-W89m95DDmZci2wLbxFR8GwekNbpHeeC2EaJorhU0qBn_Hlcxql30fLveycjhSO03bu3MJwN9moT2q0T222iIXutEjpNezt5VzZKao8_JuI3ZnTFy5dM5GYO773TbgUihlVjVQsnv73FFPZaHfaRssK4sfGlBHjItwkzEQe9gOtFhkAFihiw45ppo6FnBkvmNcD59GfteifKPg5oSGYqMWZWcKPt0", tags: [ { name: "Q29udGVudC1UeXBl", value: "dGV4dC9odG1s" }, { name: "VXNlci1BZ2VudA", value: "QXJ3ZWF2ZURlcGxveS8xLjAuMA" }, { name: "U2lsby1WZXJzaW9u", value: "MC4xLjA" }, ], target: "", quantity: "0", data: "0HgHqou5BTRNYJIsCciZb2-85Qlg9cYpiHO62KbRCEeX_cjSvn--Cex8uksInemd6FWWkczaqjs3SWzr7BRc0BSjHXxlVHkKuQp7WvRRJeNJPk_nC0KZrjkFSIPLIx_oOSeXigaPSEBSC4ry_5Iygt7z0Dgl7z1eFplIs6MlxKuBwiXfCtlwRDQK_fJlPWZhGjOpNLP5dyOLwMKrvG2dbAOeyAYbr117rn19CiDkTQAI3m2gAcJlXDZTNeA-1rJqb6X73u0AQt4Ao-OkktxdZ1UMfMfXnwdlsAEKK14NiKRbL1UbVRGh1nyWjUl90BP5Qj74L6_CKxQc_us7gxdeUhkzIKr4-LMY4LoCr-l0Law_tIGekkRsqb5oN7JiketqWazgsyo-Gq-0Blvhwh8nww", reward: "349612332", signature: "DJ6V8zXFMvkyNS4nNHxdFgXx1cbMuzQfWdtP_navPG1STMUarYKHWnJvFQqNkFl5CekNql0xTOjY5hWLt2AVxfMWgvvi5498vNUpbFoWxjrVl6fk86ARx2lzYB7iQK4YFIuIQ7MdR0w8Dy836hW7c8gXe_FPRAqOI7J_l8fqUSzaUtlcwLSfvhXJM-2a3WmoGLcg8Gvj53B8-RizvM3BrKQQWrcat78zeOgb-Fzl3PQ_Ej3CiRIDgAYnTxmd7M6jI84uck1gBRjMql42n0F8pQuTgMqzDbeXW2iBuvIE5tYVmUgnNrPjkDedLWe0Hp4KLDQyDY9lO-zIJLpiYCbc7kUfDBontxCCJIy9N8XM9gHqQofCItYAEO4v3B7sXgdSAQzcibnM3j6EhB9-mhiDcKKRuTSvyJh3sBTWHFrnWylfq84JOJLNhR4aZA_UfjkccA7Z-yqoiMI0mOB0HaAEmsa6ZsoLs5C-6vDnGaBCqYeVKKqKizfOQGsc9IuzdsSQwY7yTE-C3Xb3eAgnq0BLn6iUNqFU-mkwHi-c_hpxoR0lY91k98Ra9UhrgFS5m_9x3BhCXNhDaUXb16p0fHKGYSggqgqS3FbEcdOnsQlhw3IFEccFOTvuv1xEoE1zYeZ06q6NkFKMik6soXl9LXXgJgZvpEut_2LaHKtojbWqSkc", id: "S-9ICDleH3PEx9LXVEbguVffe5dHEM0I3wEr_MJidqU", }); const verified = await arweave.transactions.verify(transaction); expect(verified).to.be.a("boolean").and.to.be.true; const decrypted = await arweave.silo.readTransactionData( transaction, "thing.1" ); expect(bufferToString(decrypted)) .to.be.a("string") .and.contain("<title>Hello world!</title>"); }); it("should pass a Silo transaction roundtrip", async function () { this.timeout(10000); const wallet = await arweave.wallets.generate(); const transaction = await arweave.createSiloTransaction( { data: "test data" }, wallet, "my-silo-ref.1" ); await arweave.transactions.sign(transaction, wallet); const verified = await arweave.transactions.verify(transaction); expect(verified).to.be.a("boolean").and.to.be.true; let decrypted = await arweave.silo.readTransactionData( transaction, "my-silo-ref.1" ); expect(bufferToString(decrypted)).to.be.a("string").and.equal("test data"); }); }); describe("GraphQL", function () { it("should return a list of results", async function () { const txs = ( await arweave.api.post("/graphql", { query: ` { transactions( tags: [ { name: "App-Name", values: ["CommunityXYZ"] } ] ) { edges { node { id } } } }`, }) ).data.data.transactions.edges; expect(txs).to.be.an("array"); expect(txs.length).to.be.greaterThan(0); }); it("should return an empty list when no results are found", async function () { const txs = ( await arweave.api.post("/graphql", { query: ` { transactions( owners: ["hnRI7JoN2vpv__w90o4MC_ybE9fse6SUemwQeY8hFxM"] ) { edges { node { id } } } }`, }) ).data.data.transactions.edges; expect(txs).to.be.an("array"); expect(txs.length).to.equal(0); }); });
the_stack
import { Resolver, schemaComposer, ObjectTypeComposer } from 'graphql-compose'; import { GraphQLNonNull } from 'graphql-compose/lib/graphql'; import { UserModel, IUser } from '../../__mocks__/userModel'; import { updateById } from '../updateById'; import GraphQLMongoID from '../../types/MongoID'; import { convertModelToGraphQL } from '../../fieldsConverter'; import { ExtendedResolveParams } from '..'; import { testFieldConfig } from '../../utils/testHelpers'; beforeAll(() => UserModel.base.createConnection()); afterAll(() => UserModel.base.disconnect()); describe('updateById() ->', () => { let UserTC: ObjectTypeComposer; beforeEach(() => { schemaComposer.clear(); UserTC = convertModelToGraphQL(UserModel, 'User', schemaComposer); UserTC.setRecordIdFn((source) => (source ? `${source._id}` : '')); }); let user1: IUser; let user2: IUser; beforeEach(async () => { await UserModel.deleteMany({}); user1 = new UserModel({ name: 'userName1', skills: ['js', 'ruby', 'php', 'python'], gender: 'male', relocation: true, contacts: { email: 'mail' }, }); user2 = new UserModel({ name: 'userName2', skills: ['go', 'erlang'], gender: 'female', relocation: true, contacts: { email: 'mail' }, }); await user1.save(); await user2.save(); }); it('should return Resolver object', () => { const resolver = updateById(UserModel, UserTC); expect(resolver).toBeInstanceOf(Resolver); }); describe('Resolver.args', () => { it('should have `record` arg', () => { const resolver = updateById(UserModel, UserTC); const argConfig: any = resolver.getArgConfig('record'); expect(argConfig.type).toBeInstanceOf(GraphQLNonNull); expect(argConfig.type.ofType.name).toBe('UpdateByIdUserInput'); }); it('should have `_id` required arg', () => { const resolver = updateById(UserModel, UserTC); expect(resolver.getArgTypeName('_id')).toBe('MongoID!'); }); }); describe('Resolver.resolve():Promise', () => { it('should be promise', () => { const result = updateById(UserModel, UserTC).resolve({}); expect(result).toBeInstanceOf(Promise); result.catch(() => 'catch error if appear, hide it from mocha'); }); it('should rejected with Error if args._id is empty', async () => { const result = updateById(UserModel, UserTC).resolve({ // @ts-expect-error args: { record: {} }, }); await expect(result).rejects.toThrow('User.updateById resolver requires args._id value'); }); it('should return payload.recordId', async () => { const result = await testFieldConfig({ field: updateById(UserModel, UserTC), args: { _id: user1.id, record: { name: 'some name' }, }, selection: `{ recordId }`, }); expect(result.recordId).toBe(user1.id); }); it('should return resolver runtime error in payload.error', async () => { const resolver = updateById(UserModel, UserTC); await expect(resolver.resolve({ projection: { error: true } })).resolves.toEqual({ error: expect.objectContaining({ message: expect.stringContaining('requires args.record'), }), }); // should throw error if error not requested in graphql query await expect(resolver.resolve({})).rejects.toThrowError('requires args.record'); }); it('should return empty payload.error', async () => { const result = await updateById(UserModel, UserTC).resolve({ args: { _id: user1.id, record: { name: 'some name' }, }, }); expect(result.error).toEqual(undefined); }); it('should return payload.error', async () => { const result = await updateById(UserModel, UserTC).resolve({ args: { _id: user1.id, record: { name: 'some name', valid: 'AlwaysFails' }, }, projection: { error: true, }, }); expect(result.error.message).toEqual( 'User validation failed: valid: this is a validate message' ); expect(result.error.errors).toEqual([ { message: 'this is a validate message', path: 'valid', value: 'AlwaysFails', }, ]); }); it('should throw GraphQLError if client does not request errors field in payload', async () => { await expect( updateById(UserModel, UserTC).resolve({ args: { _id: user1.id, record: { name: 'some name', valid: 'AlwaysFails' }, }, }) ).rejects.toThrowError('User validation failed: valid: this is a validate message'); }); it('should change data via args.record in model', async () => { const result = await updateById(UserModel, UserTC).resolve({ args: { _id: user1.id, record: { name: 'newName' }, }, }); expect(result.record.name).toBe('newName'); }); it('should change data via args.record in database', async () => { const checkedName = 'nameForMongoDB'; await updateById(UserModel, UserTC).resolve({ args: { _id: user1.id, record: { name: checkedName }, }, }); await expect(UserModel.findOne({ _id: user1._id })).resolves.toEqual( expect.objectContaining({ name: checkedName }) ); }); it('should return payload.record', async () => { const checkedName = 'anyName123'; const result = await updateById(UserModel, UserTC).resolve({ args: { _id: user1.id, record: { name: checkedName }, }, }); expect(result.record.id).toBe(user1.id); expect(result.record.name).toBe(checkedName); }); it('should pass empty projection to findById and got full document data', async () => { const result = await updateById(UserModel, UserTC).resolve({ args: { _id: user1.id, record: {}, }, projection: { record: { name: true, }, }, }); expect(result.record.id).toBe(user1.id); expect(result.record.name).toBe(user1.name); expect(result.record.gender).toBe(user1.gender); }); it('should return mongoose document', async () => { const result = await updateById(UserModel, UserTC).resolve({ args: { _id: user1.id, record: {} }, }); expect(result.record).toBeInstanceOf(UserModel); }); it('should call `beforeRecordMutate` method with founded `record` and `resolveParams` as args', async () => { let beforeMutationId; const result = await updateById(UserModel, UserTC).resolve({ args: { _id: user1.id, record: {} }, context: { ip: '1.1.1.1' }, beforeRecordMutate: (record: any, rp: ExtendedResolveParams) => { beforeMutationId = record.id; record.someDynamic = rp.context.ip; return record; }, }); expect(result.record).toBeInstanceOf(UserModel); expect(result.record.someDynamic).toBe('1.1.1.1'); expect(beforeMutationId).toBe(user1.id); }); it('`beforeRecordMutate` may reject operation', async () => { const result = updateById(UserModel, UserTC).resolve({ args: { _id: user1.id, record: { name: 'new name' } }, context: { readOnly: true }, beforeRecordMutate: (record: any, rp: ExtendedResolveParams) => { if (rp.context.readOnly) { return Promise.reject(new Error('Denied due context ReadOnly')); } return record; }, }); await expect(result).rejects.toThrow('Denied due context ReadOnly'); const exist = await UserModel.collection.findOne({ _id: user1._id }); expect(exist?.n).toBe(user1.name); }); it('should call `beforeQuery` method with non-executed `query` as arg', async () => { let beforeQueryCalled = false; const result = await updateById(UserModel, UserTC).resolve({ args: { _id: user1.id, record: { name: 'new name' } }, beforeQuery: (query: any, rp: ExtendedResolveParams) => { expect(query).toHaveProperty('exec'); expect(rp.model).toBe(UserModel); beforeQueryCalled = true; // modify query before execution return query.where({ _id: user2.id }); }, }); expect(result).toHaveProperty('record._id', user2._id); expect(beforeQueryCalled).toBe(true); }); }); describe('Resolver.getType()', () => { it('should have correct output type name', () => { const outputType: any = updateById(UserModel, UserTC).getType(); expect(outputType.name).toBe(`UpdateById${UserTC.getTypeName()}Payload`); }); it('should have recordId field', () => { const outputType: any = updateById(UserModel, UserTC).getType(); const typeComposer = schemaComposer.createObjectTC(outputType); expect(typeComposer.hasField('recordId')).toBe(true); expect(typeComposer.getFieldType('recordId')).toBe(GraphQLMongoID); }); it('should have record field', () => { const outputType: any = updateById(UserModel, UserTC).getType(); const typeComposer = schemaComposer.createObjectTC(outputType); expect(typeComposer.hasField('record')).toBe(true); expect(typeComposer.getFieldType('record')).toBe(UserTC.getType()); }); it('should reuse existed outputType', () => { const outputTypeName = `UpdateById${UserTC.getTypeName()}Payload`; const existedType = schemaComposer.createObjectTC(outputTypeName); schemaComposer.set(outputTypeName, existedType); const outputType = updateById(UserModel, UserTC).getType(); expect(outputType).toBe(existedType.getType()); }); it('should have all fields optional in record', () => { const resolver = updateById(UserModel, UserTC); expect(resolver.getArgTypeName('_id')).toBe('MongoID!'); expect(resolver.getArgITC('record').getFieldTypeName('name')).toBe('String'); expect(resolver.getArgITC('record').getFieldTypeName('age')).toBe('Float'); }); }); });
the_stack
import { composite } from 'seemly' import type { GlobalThemeOverrides } from 'naive-ui' import { commonDark } from 'naive-ui' import vars from './vars' function createHoverColor (color: string, overlayAlpha: number = 0.15): string { return composite(color, [255, 255, 255, overlayAlpha]) } function createPressedColor ( color: string, overlayAlpha: number = 0.15 ): string { return composite(color, [0, 0, 0, overlayAlpha]) } // TODO // 2. input suffix & prefix text color // 3. input icon color? // 6. notification size customization // 7. upload style // 8. missing attrs // // Some demands are really not easy to implement, // particularly related to component layout. // // It's nearly impossible to expose all layout params (with a balanced count) export const colors = { primaryColor: '#4FB233', primaryColorHover: createHoverColor('#4FB233'), primaryColorPressed: createPressedColor('#4FB233'), infoColor: '#335FFF', infoColorHover: createHoverColor('#335FFF'), infoColorPressed: createPressedColor('#335FFF'), successColor: '#4FB233', successColorHover: createHoverColor('#4FB233'), successColorPressed: createPressedColor('#4FB233'), errorColor: '#D92149', errorColorHover: createHoverColor('#D92149'), errorColorPressed: createPressedColor('#D92149'), warningColor: '#FFAC26', warningColorHover: createHoverColor('#FFAC26', 0.2), warningColorPressed: createPressedColor('#FFAC26', 0.05), textColorDisabled: '#5B5B5B', textColor1: '#FFFFFF', textColor2: '#D6D6D6' } export const themeOverridesDark: GlobalThemeOverrides = { common: { fontSize: '16px', fontSizeMedium: '16px', fontWeightStrong: '700', borderRadius: '16px', borderColor: '#5B5B5B', opacity1: '0.8', opacity2: '0.6', opacity3: '0.4', opacity4: '0.2', opacity5: '0.2', baseColor: '#FFFFFF', dividerColor: '#5B5B5B', popoverColor: '#333333', inputColor: '#282828', inputColorDisabled: '#333333', textColor3: '#ADADAD', placeholderColor: '#5B5B5B', // disabled, placeholder, icon placeholderColorDisabled: '#848484', tableHeaderColor: '#282828', hoverColor: 'rgba(79, 178, 51, 0.15)', closeColor: '#D6D6D6', modalColor: '#282828', clearColor: '#ADADAD', boxShadow2: vars.NORMAL_BOX_SHADOW_DARK_THEME, ...colors }, Avatar: { borderRadius: '50%' }, Badge: { color: '#EB3B61' }, BackTop: { width: '48px', height: '48px', iconSize: '24px', borderRadius: '24px', color: '#333', iconColor: '#ADADAD', iconColorHover: colors.primaryColor, iconColorPressed: colors.primaryColorPressed, boxShadow: '0 40px 16px -24px rgba(0,0,0,0.04), 0 8px 16px -8px rgba(0,0,0,0.12), 0 16px 40px 16px rgba(0,0,0,0.04)', boxShadowHover: '0 40px 16px -24px rgba(0,0,0,0.04), 0 8px 16px -8px rgba(0,0,0,0.12), 0 16px 40px 16px rgba(0,0,0,0.04)', boxShadowPressed: '0 40px 16px -24px rgba(0,0,0,0.04), 0 8px 16px -8px rgba(0,0,0,0.12), 0 16px 40px 16px rgba(0,0,0,0.04)' }, Breadcrumb: { fontSize: '16px', fontWeightActive: '500', itemTextColorPressed: colors.primaryColor, itemTextColor: '#ADADAD' }, Button: { fontWeightStrong: commonDark.fontWeightStrong, textColor: '#FFFFFF', textColorWarning: '#333', textColorSuccess: '#333', textColorPrimary: '#333', iconSizeTiny: '24px', iconSizeSmall: '24px', iconSizeMedium: '24px', iconSizeLarge: '36px', borderRadiusTiny: '16px', borderRadiusSmall: '16px', borderRadiusMedium: '24px', borderRadiusLarge: '40px', heightTiny: '24px', heightSmall: '32px', heightMedium: '48px', heightLarge: '80px', fontSizeTiny: '14px', fontSizeSmall: '16px', fontSizeMedium: '16px', fontSizeLarge: '24px', paddingTiny: '0 16px', paddingSmall: '0 24px', paddingMedium: '0 48px', paddingLarge: '0 80px', paddingRoundTiny: '0 12px', paddingRoundSmall: '0 24px', paddingRoundMedium: '0 48px', paddingRoundLarge: '0 80px', opacityDisabled: '1', colorDisabled: '#0000', colorDisabledPrimary: '#333', colorDisabledInfo: '#333', colorDisabledSuccess: '#333', colorDisabledWarning: '#333', colorDisabledError: '#333', border: '1px solid #ADADAD', borderDisabled: '1px solid #5B5B5B', borderDisabledPrimary: '1px solid #333', borderDisabledInfo: '1px solid #333', borderDisabledSuccess: '1px solid #333', borderDisabledWarning: '1px solid #333', borderDisabledError: '1px solid #333', textColorGhost: '#FFFFFF', textColorDisabled: '#5B5B5B', textColorDisabledPrimary: '#5B5B5B', textColorDisabledInfo: '#5B5B5B', textColorDisabledSuccess: '#5B5B5B', textColorDisabledWarning: '#5B5B5B', textColorDisabledError: '#5B5B5B', textColorGhostDisabled: '#5B5B5B', textColorGhostDisabledPrimary: '#5B5B5B', textColorGhostDisabledInfo: '#5B5B5B', textColorGhostDisabledSuccess: '#5B5B5B', textColorGhostDisabledWarning: '#5B5B5B', textColorGhostDisabledError: '#5B5B5B', textColorTextDisabled: '#5B5B5B', textColorTextDisabledPrimary: '#5B5B5B', textColorTextDisabledInfo: '#5B5B5B', textColorTextDisabledSuccess: '#5B5B5B', textColorTextDisabledWarning: '#5B5B5B', textColorTextDisabledError: '#5B5B5B', iconMarginSmall: '8px', iconMarginMedium: '8px', iconMarginLarge: '12px' }, Checkbox: { labelPadding: '0 8px 0 12px', sizeMedium: '16px', fontSizeMedium: '16px', borderRadius: '4px', borderDisabled: '1px solid #5B5B5B', colorDisabled: '#0000', colorDisabledChecked: '#D8D8D8', textColor: '#FFFFFF' }, Card: { paddingSmall: '20px', paddingMedium: '20px', paddingLarge: '20px', paddingHuge: '20px', color: '#282828', borderColor: '#5b5b5b', closeColorHover: colors.primaryColor, closeColorPressed: colors.primaryColorPressed }, Cascader: { menuHeight: '290px' }, DataTable: { fontSizeMedium: '16px', borderColor: '5B5B5B', thColor: '#282828', thTextColor: '#FFFFFF', tdColor: '#1E1E1E', tdTextColor: '#FFFFFF', thFontWeight: commonDark.fontWeight, tdColorHover: '#222C1F', thButtonColorHover: '#0000', thColorModal: '#282828', tdColorModal: '#1E1E1E', tdColorHoverModal: '#222C1F', thIconColor: '#848484', thColorHover: '#0000', thPaddingSmall: '10px 20px', thPaddingMedium: '10px 20px', thPaddingLarge: '10px 20px', tdPaddingSmall: '10px 20px', tdPaddingMedium: '10px 20px', tdPaddingLarge: '10px 20px' }, DatePicker: { itemTextColor: '#FFF', itemColorHover: 'rgba(79, 178, 51, 0.15)', itemTextColorActive: '#333333', iconColor: '#848484', itemBorderRadius: '14px', panelHeaderDividerColor: '#0000', calendarDaysDividerColor: '#0000', arrowColor: '#CCC', arrowSize: '24px', itemFontSize: '16px', calendarDaysFontSize: '16px', calendarTitleFontSize: '16px', panelActionPadding: '12px 20px', itemSize: '28px', itemCellHeight: '34px', itemCellWidth: '40px', calendarTitlePadding: '0 8px 8px 8px', calendarTitleHeight: '32px', calendarLeftPaddingDate: '12px 16px 9px 16px', calendarLeftPaddingDaterange: '12px 16px 9px 16px', calendarLeftPaddingDatetime: '6px 16px 9px 16px', calendarLeftPaddingDatetimerange: '6px 16px 9px 16px', calendarRightPaddingDaterange: '12px 16px 9px 16px', calendarRightPaddingDatetimerange: '6px 16px 9px 16px', calendarDividerColor: '#0000', panelHeaderPadding: '12px 20px 8px 20px' }, Dialog: { padding: '40px', iconSize: '36px', iconMarginIconTop: '0 0 20px 0', closeMarginIconTop: '24px 24px 0 0', titleFontSize: '24px', fontSize: '16px', actionSpace: '20px', contentMargin: '12px 0 40px 0', closeColorHover: colors.primaryColor, closeColorPressed: colors.primaryColorPressed }, Divider: { color: '#5B5B5B' }, Drawer: { bodyPadding: '20px' }, DynamicTags: { peers: { Tag: { heightMedium: '24px' }, Input: { heightSmall: '24px' } } }, Empty: { iconColor: colors.textColorDisabled, textColor: colors.textColorDisabled, extraTextColor: colors.textColorDisabled }, Input: { heightSmall: '24px', heightMedium: '32px', fontSizeMedium: '16px', paddingSmall: '0 12px', paddingMedium: '0 12px', paddingLarge: '0 12px', iconSize: '24px', border: '1px solid #5B5B5B', borderWarning: '1px solid #FAB23E', borderError: '1px solid EB3B61', borderDisabled: '1px #333333 !important', colorDisabled: '#333333', borderHover: `1px solid ${colors.primaryColor}`, borderFocus: `1px solid ${colors.primaryColor}`, color: '#282828', textColor: '#FFFFFF', placeholderColor: '#848484', lineHeight: '22px', groupLabelColor: '#5B5B5B', groupLabelTextColor: '#FFF' }, InternalSelection: { heightMedium: '32px', fontSizeMedium: '16px', paddingSingle: '0 36px 0 12px' }, InternalSelectMenu: { height: '290px', optionTextColor: colors.textColor1, optionFontSizeMedium: '16px', optionPaddingMedium: '0 12px', optionHeightMedium: '38px', paddingSmall: '4px 0', paddingMedium: '6px 0', paddingLarge: '6px 0', paddingHuge: '8px 0' }, Form: { blankHeightSmall: vars.CONTENT_SPACE, blankHeightMedium: vars.CONTENT_SPACE, blankHeightLarge: vars.CONTENT_SPACE, feedbackHeightSmall: vars.CONTENT_SPACE, feedbackHeightMedium: vars.CONTENT_SPACE, feedbackHeightLarge: vars.CONTENT_SPACE, feedbackFontSizeSmall: vars.SMALL_FRONT_SIZE, feedbackFontSizeMedium: vars.SMALL_FRONT_SIZE, feedbackFontSizeLarge: vars.SMALL_FRONT_SIZE, labelFontSizeLeftSmall: vars.SMALL_FRONT_SIZE, labelFontSizeLeftMedium: vars.SMALL_FRONT_SIZE, labelFontSizeLeftLarge: vars.NORMAL_FRONT_SIZE, labelFontSizeTopSmall: vars.SMALL_FRONT_SIZE, labelFontSizeTopMedium: vars.SMALL_FRONT_SIZE, labelFontSizeTopLarge: vars.NORMAL_FRONT_SIZE, labelHeightSmall: '22px', labelHeightMedium: '22px', labelHeightLarge: '22px', labelTextAlignHorizontal: 'left' }, Icon: { color: '#848484', opacity1Depth: '1', opacity2Depth: '1', opacity3Depth: '1' }, List: { color: '#333', borderColor: '#5B5B5B' }, Menu: { borderRadius: '100px', itemIconColor: '#D6D6D6' }, Message: { padding: '12px 20px 12px 12px', borderRadius: '32px', maxWidth: '720px', minWidth: '420px', iconMargin: '0 20px 0 0', closeMargin: '0 -8px 0 20px', colorSuccess: colors.successColor, colorInfo: colors.warningColor, colorWarning: colors.errorColor, colorError: colors.errorColor, boxShadowInfo: vars.SPECIAL_BOX_SHADOW_DARK_THEME, boxShadowSuccess: vars.SPECIAL_BOX_SHADOW_DARK_THEME, boxShadowError: vars.SPECIAL_BOX_SHADOW_DARK_THEME, boxShadowWarning: vars.SPECIAL_BOX_SHADOW_DARK_THEME, textColorError: '#FFF', textColorSuccess: '#FFF', textColorInfo: '#FFF', textColorWarning: '#FFF', iconColorInfo: 'rgb(255, 255, 255)', iconColorSuccess: '#333333', iconColorWarning: '#333333', iconColorError: 'rgb(255, 255, 255)', iconColorLoading: 'rgb(255, 255, 255)', closeColorInfo: 'rgb(255, 255, 255)', closeColorHoverInfo: 'rgb(255, 255, 255)', closeColorPressedInfo: 'rgb(255, 255, 255)', closeColorSuccess: '#333333', closeColorHoverSuccess: '#333333', closeColorPressedSuccess: '#333333', closeColorError: 'rgb(255, 255, 255)', closeColorHoverError: 'rgb(255, 255, 255)', closeColorPressedError: 'rgb(255, 255, 255)', closeColorWarning: '#333333', closeColorHoverWarning: '#333333', closeColorPressedWarning: '#333333', closeColorLoading: 'rgb(255, 255, 255)', closeColorHoverLoading: 'rgb(255, 255, 255)', closeColorPressedLoading: 'rgb(255, 255, 255)', closeSize: '24px', iconSize: '20px' }, Modal: { textColor: '#FFF', color: '#545454' }, Notification: { fontSize: '16px', headerTextColor: '#FFF', descriptionTextColor: '#ADADAD', textColor: colors.textColor2, closeColor: '#FFFFFF', closeColorHover: colors.primaryColor, closeColorPressed: colors.primaryColorPressed, boxShadow: vars.SPECIAL_BOX_SHADOW_DARK_THEME }, Pagination: { itemSize: '32px', itemPadding: '0', // buttonFontSize: '24px', itemFontSize: '16px', inputWidth: '80px', selectWidth: '100px', inputMargin: '0 20px', itemMargin: '0 0 0 20px', itemBorder: '0 solid #0000', itemBorderActive: '0 solid #0000', itemBorderDisabled: '0 solid #0000', itemColor: '#0000', itemColorHover: 'rgba(79, 178, 51, 0.15)', itemColorActive: '#0000', itemColorDisabled: '#0000', itemBorderRadius: '100px', itemTextColor: colors.textColor1, itemTextColorHover: colors.primaryColor, itemTextColorDisabled: '#5B5B5B', buttonIconColor: '#FFFFFF', buttonBorder: '0 solid #0000', buttonIconColorHover: commonDark.primaryColor }, Popover: { padding: '20px', fontSize: '16px', arrowOffset: '40px', arrowOffsetVertical: '16px', arrowHeight: '8px', spaceArrow: '14px', textColor: '#FFF', boxShadow: vars.NORMAL_BOX_SHADOW_DARK_THEME }, Popconfirm: { iconColor: '#FAB23E !important' }, Progress: { fontWeightCircle: '700', railHeight: '4px', fontSizeCircle: '24px', iconSizeCircle: '30px', iconSizeLine: '20px', iconColor: colors.warningColor, iconColorInfo: colors.warningColor, iconColorSuccess: colors.successColor, iconColorWarning: colors.errorColor, iconColorError: colors.errorColor, fillColor: colors.warningColor, fillColorInfo: colors.warningColor, fillColorSuccess: colors.successColor, fillColorWarning: colors.warningColor, fillColorError: colors.errorColor, textColorCircle: '#666666' }, Radio: { labelPadding: '0 8px 0 12px', fontSizeMedium: '16px', radioSizeMedium: '16px', dotColorDisabled: '#5B5B5B', boxShadowDisabled: 'inset 0 0 0 1px #5B5B5B' }, Slider: { railColor: '#5B5B5B', fillColor: colors.primaryColor, fillColorHover: colors.primaryColorHover, handleBoxShadow: vars.NORMAL_BOX_SHADOW_DARK_THEME, handleBoxShadowHover: vars.NORMAL_BOX_SHADOW_DARK_THEME, handleBoxShadowActive: vars.NORMAL_BOX_SHADOW_DARK_THEME, handleBoxShadowFocus: vars.NORMAL_BOX_SHADOW_DARK_THEME, dotColor: '#333333', dotBorder: '2px solid #333333', dotBorderActive: `2px solid ${colors.primaryColor}` }, Switch: { railHeightMedium: '15px', railHeightLarge: '20px', railBorderRadiusMedium: '8px', railBorderRadiusLarge: '10px', railWidthMedium: '40px', railWidthLarge: '50px', buttonHeightMedium: '24px', buttonHeightLarge: '32px', buttonWidthMedium: '24px', buttonWidthLarge: '32px', buttonWidthPressedMedium: '30px', buttonWidthPressedLarge: '38px', buttonBorderRadiusMedium: '12px', buttonBorderRadiusLarge: '16px', railColor: '#5B5B5B', railColorActive: '#5B5B5B', buttonColor: '#5B5B5B', buttonBoxShadow: '0 2px 3px 0 rgba(0,0,0,0.10)' }, Table: { thColor: '#282828', thTextColor: '#FFFFFF', tdColor: '#1E1E1E', tdTextColor: '#FFFFFF', thFontWeight: commonDark.fontWeight, borderColor: '#5B5B5B', thPaddingSmall: '10px 20px', thPaddingMedium: '10px 20px', thPaddingLarge: '10px 20px', tdPaddingSmall: '10px 20px', tdPaddingMedium: '10px 20px', tdPaddingLarge: '10px 20px' }, Tabs: { tabTextColorLine: '#D6D6D6', tabTextColorBar: '#D6D6D6' }, Tag: { borderRadius: '100px', border: '1px solid #0000', color: 'rgba(153,153,153,0.10)', colorError: 'rgba(235,59,97,0.15)', colorInfo: 'rgba(51,95,255,0.15)', colorSuccess: 'rgba(79,178,51,0.15)', closeColor: commonDark.closeColor, closeColorHover: commonDark.closeColor, closeColorPressed: commonDark.closeColor, borderPrimary: '1px solid #0000', closeColorPrimary: commonDark.closeColor, closeColorHoverPrimary: commonDark.closeColor, closeColorPressedPrimary: commonDark.closeColor, closeColorError: colors.errorColor, closeColorHoverError: colors.errorColorHover, closeColorPressedError: colors.errorColorPressed, closeColorInfo: colors.infoColor, closeColorHoverInfo: colors.infoColorHover, closeColorPressedInfo: colors.infoColorPressed, closeColorSuccess: colors.successColor, closeColorHoverSuccess: colors.successColorHover, closeColorPressedSuccess: colors.successColorPressed, closeColorWarning: colors.warningColor, closeColorHoverWarning: colors.warningColorHover, closeColorPressedWarning: colors.warningColorPressed, borderInfo: '1px solid #0000', borderSuccess: '1px solid #0000', borderWarning: '1px solid #0000', borderError: '1px solid #0000', padding: '0 12px', closeMargin: '0 0 0 8px', heightMedium: '24px', closeSizeSmall: '24px', closeSizeMedium: '24px', closeSizeLarge: '24px', fontSizeSmall: '12px', fontSizeMedium: '16px', fontSizeLarge: '16px', textColorCheckable: colors.textColor1, textColorHoverCheckable: colors.primaryColor, textColorChecked: '#000', colorCheckable: 'rgba(173,173,173,0.20)', colorHoverCheckable: 'rgba(79,178,51,0.15)', colorPressedCheckable: 'rgba(79,178,51,0.15)', colorChecked: colors.primaryColor, colorCheckedHover: colors.primaryColorHover, colorCheckedPressed: colors.primaryColorPressed }, TimePicker: { itemFontSize: '16px', itemHeight: '38px', itemWidth: '66px', panelActionPadding: '12px 20px', itemTextColor: '#FFF' }, Tooltip: { peers: { Popover: { padding: '20px', fontSize: '16px', color: '#D6D6D6', textColor: '#333333' } } }, Transfer: { borderColor: '#5B5B5B', headerColor: '#333333', extraTextColor: colors.textColor1 }, Typography: { headerPrefixWidth3: '15px', headerPrefixWidth4: '15px', headerPrefixWidth5: '15px', headerPrefixWidth6: '15px', headerBarColor: '#ADADAD' }, Upload: { itemColorHover: '#0000', itemColorHoverError: '#0000', itemIconColor: '#FFFFFF', fontSize: '16px' } }
the_stack
import { Component } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { FormGroup, FormArray, FormBuilder, FormControl } from '@angular/forms'; import { Select2OptionData } from 'ng2-select2'; import { ContainerService, GroupService, LogService } from './../../../../services'; import { IContainer } from './../../../../interfaces'; import { IPValidator } from './../../../../validators'; declare let _: any; declare let messager: any; @Component({ selector: 'hb-container-clone', templateUrl: './container-clone.html', styleUrls: ['./container-clone.css'] }) export class ContainerClonePage { private groups: Array<any>; private groupInfo: any; private ip: string; private containerId: string; private containerInfo: any; private selectedGroupId: string = ''; private selectedGroup: any; private serversSelect2Options: any; private servers: Array<any> = []; private selectedServers: Array<any>; private currentEditEnvServer: string; private cloneProcessModalOptions: any; private cloneProcessMsg: Array<any>; private isCloneDone: Array<any>; private form: FormGroup; private submitted: boolean = false; private subscribers: Array<any> = []; constructor( private _route: ActivatedRoute, private _router: Router, private _fb: FormBuilder, private _containerService: ContainerService, private _groupService: GroupService, private _logService: LogService) { } ngOnInit() { this.cloneProcessModalOptions = { show: false, title: 'INFO', closable: false, hideCloseBtn: true } this.serversSelect2Options = { multiple: true, closeOnSelect: false, minimumResultsForSearch: -1, placeholder: 'Select server', dropdownAutoWidth: true }; let paramSub = this._route.params.subscribe(params => { let groupId = params['groupId']; this.ip = params['ip']; this.containerId = params["containerId"]; this.groupInfo = { ID: groupId }; this.containerInfo = {}; this._groupService.get() .then(data => { this.groupInfo = _.find(data, (item: any) => { return item.ID === groupId; }); if (!this.groupInfo) { return Promise.reject('No group found.'); } this.groups = data; return this._containerService.getById(this.ip, this.containerId, true); }) .then(containerInfo => { this.containerInfo = containerInfo; this.buildForm(containerInfo); }) .catch(err => { messager.error(err); this._router.navigate(['/group']); }); }); this.subscribers.push(paramSub); } ngOnDestroy() { this.subscribers.forEach((item: any) => item.unsubscribe()); } private buildForm(data: any) { this.form = this._fb.group({ Name: [''], Image: [data.Image], Command: [data.CommandWithoutEntryPoint || data.Command], HostName: [''], NetworkMode: [data.NetworkMode], RestartPolicy: [data.RestartPolicy], Ports: this._fb.array([]), Volumes: this._fb.array([]), // Envs: this._fb.array([]), Links: this._fb.array([]), EnableLogFile: data.LogConfig ? (data.LogConfig.Type ? 1 : 0) : 0, Labels: this._fb.array([]), LogDriver: data.LogConfig ? (data.LogConfig.Type || 'json-file') : 'json-file', LogOpts: this._fb.array([]), Ulimits: this._fb.array([]), Dns: [data.Dns], CPUShares: data.CPUShares === 0 ? '' : data.CPUShares, Memory: data.Memory === 0 ? '' : data.Memory, ServerEnvs: this._fb.group({}) }); if (data.RestartPolicy === 'on-failure') { let tempCtrl = new FormControl(data.RestartRetryCount); this.form.addControl('RestartRetryCount', tempCtrl); } if (data.NetworkMode !== 'host' && data.Ports.length > 0) { let portsCtrl = <FormArray>this.form.controls['Ports']; data.Ports.forEach((item: any) => { portsCtrl.push(this._fb.group({ PrivatePort: [item.PrivatePort], Type: [item.Type || 'tcp'], PublicPort: [item.PublicPort === 0 ? '' : item.PublicPort], IP: [item.Ip] })) }); } if (data.Volumes) { let volumeCtrl = <FormArray>this.form.controls['Volumes']; data.Volumes.forEach((item: any) => { volumeCtrl.push(this._fb.group({ ContainerVolume: item.ContainerVolume, HostVolume: item.HostVolume })); }); } // if (data.Env) { // let envCtrl = <FormArray>this.form.controls['Envs']; // data.Env.forEach((item: any) => { // envCtrl.push(this._fb.group({ // Value: item // })); // }); // } if (data.Links) { let control = <FormArray>this.form.controls['Links']; data.Links.forEach((item: any) => { control.push(this._fb.group({ "Value": [item] })); }) } if (data.Labels) { let control = <FormArray>this.form.controls['Labels']; for (let key in data.Labels) { control.push(this._fb.group({ "Value": [`${key}:${data.Labels[key]}`] })); } } if(data.LogConfig){ if(data.LogConfig.Config){ let cloneOptsArr = []; for(let key in data.LogConfig.Config){ cloneOptsArr.push(`${key}=${data.LogConfig.Config[key]}`) } let control = <FormArray>this.form.controls['LogOpts']; cloneOptsArr.forEach((item: any) => { control.push(this._fb.group({ "Value": [item] })); }) } } if (data.Ulimits) { let control = <FormArray>this.form.controls['Ulimits']; data.Ulimits.forEach((item: any) => { control.push(this._fb.group({ "Name": [item['Name']], "Soft": [item['Soft']], "Hard": [item['Hard']] })); }) } let restartSub = this.form.controls['RestartPolicy'].valueChanges.subscribe(value => { if (value === 'on-failure') { let control = new FormControl(''); this.form.addControl('RestartRetryCount', control); } else { this.form.removeControl('RestartRetryCount'); } }); this.subscribers.push(restartSub); let logConfigSub = this.form.controls['EnableLogFile'].valueChanges.subscribe(value => { if (value) { let logDriverCtrol = new FormControl('json-file'); this.form.addControl('LogDriver', logDriverCtrol); let logOptsCtrl = this._fb.array([]); this.form.addControl('LogOpts', logOptsCtrl); } else { this.form.removeControl('LogDriver'); this.form.removeControl('LogOpts'); } }) this.subscribers.push(logConfigSub); let networkModeSub = this.form.controls['NetworkMode'].valueChanges.subscribe(value => { if (value === 'host') { this.form.removeControl('HostName'); this.form.removeControl('Ports'); this.form.removeControl('NetworkName'); } else { let hostNameCtrl = new FormControl(''); this.form.addControl('HostName', hostNameCtrl); let portBindingCtrl = this._fb.array([]); this.form.addControl('Ports', portBindingCtrl); } if (value === "custom") { let networkNameCtrl = new FormControl(''); this.form.addControl('NetworkName', networkNameCtrl); } }); this.subscribers.push(networkModeSub); } private selectedGroupChanged(value: any) { this.selectedGroup = _.find(this.groups, (item: any) => { return item.ID === value; }); this.servers = []; let tempData = this.selectedGroup.Servers || []; tempData.forEach((item: any) => { let temp: any = { id: item.IP || item.Name, text: item.IP }; if (item.Name) { temp.text = item.Name; if (item.IP) temp.text = `${item.Name}(${item.IP})`; } this.servers.push({ id: item.IP || item.Name, text: item.Name || item.IP }) }); } private refreshSelectedServer(data: any) { let selectedServers = (data.value || []).sort(); let control = <FormGroup>this.form.controls['ServerEnvs']; if (!control) { control = this._fb.group({}); this.form.addControl('ServerEnvs', control); } let currentServers = Object.keys(control.controls); for (let server of currentServers) { if (selectedServers.indexOf(server) !== -1) continue; control.removeControl(server); } for (let server of selectedServers) { if (!control.contains[server]) { let envCtrl = this._fb.array([]); if (this.containerInfo && this.containerInfo.Env) { this.containerInfo.Env.forEach((item: any) => { envCtrl.push(this._fb.group({ Value: item })); }); } control.addControl(server, envCtrl); } } this.selectedServers = selectedServers; this.currentEditEnvServer = this.selectedServers[0] || ''; } private addPortBinding() { let control = <FormArray>this.form.controls['Ports']; control.push(this._fb.group({ PrivatePort: [''], Type: ['tcp'], PublicPort: [''], IP: ['0.0.0.0'] })); } private removePortBinding(i: number) { let control = <FormArray>this.form.controls['Ports']; control.removeAt(i); } private addVolumeBinding() { let control = <FormArray>this.form.controls['Volumes']; control.push(this._fb.group({ ContainerVolume: [''], HostVolume: [''] })); } private removeVolumeBinding(i: number) { let control = <FormArray>this.form.controls['Volumes']; control.removeAt(i); } private addEnv(server: string) { let control = <FormGroup>this.form.controls['ServerEnvs']; let envCtrl = <FormArray>control.controls[server]; envCtrl.push(this._fb.group({ "Value": [''] })); } private removeEnv(server: string, i: number) { let control = <FormGroup>this.form.controls['ServerEnvs']; let envCtrl = <FormArray>control.controls[server]; envCtrl.removeAt(i); } private addLink() { let control = <FormArray>this.form.controls['Links']; control.push(this._fb.group({ "Value": [''] })); } private removeLink(i: number) { let control = <FormArray>this.form.controls['Links']; control.removeAt(i); } private addLogOpt() { let control = <FormArray>this.form.controls['LogOpts']; control.push(this._fb.group({ "Value": [''] })); } private removeLogOpt(i: number) { let control = <FormArray>this.form.controls['LogOpts']; control.removeAt(i); } private addLabel() { let control = <FormArray>this.form.controls['Labels']; control.push(this._fb.group({ "Value": [''] })); } private removeLabel(i: number) { let control = <FormArray>this.form.controls['Labels']; control.removeAt(i); } private addUlimit() { let control = <FormArray>this.form.controls['Ulimits']; control.push(this._fb.group({ Name: [''], Soft: [''], Hard: [''] })); } private removeUlimit(i: number) { let control = <FormArray>this.form.controls['Ulimits']; control.removeAt(i); } private onSubmit() { this.submitted = true; if (!this.selectedServers || !this.selectedServers.length) { messager.error('Please select one server at least'); return; } if (this.form.invalid) return; let formData = _.cloneDeep(this.form.value); let optsObj = {}; let postLables = {}; if(this.form.controls.EnableLogFile.value){ let optsArr = (formData.LogOpts || []).map((item: any) => item.Value); optsArr.forEach((item: any) => { let splitArr = item.split('='); optsObj[splitArr[0]] = splitArr[1]; }) } if (formData.Labels) { if (formData.Labels.length > 0) { formData.Labels.forEach((item: any) => { let key = item.Value.split(":")[0]; let value = item.Value.split(":")[1]; postLables[key] = value; }) } } let config: any = { Name: this.form.controls.Name.value, Image: formData.Image, Command: formData.Command, HostName: formData.HostName, NetworkMode: formData.NetworkMode === 'custom' ? formData.NetworkName : formData.NetworkMode, RestartPolicy: formData.RestartPolicy, RestartRetryCount: formData.RestartRetryCount, Ports: (formData.Ports || []).map((item: any) => { item.PublicPort = item.PublicPort || 0; return item; }), Volumes: formData.Volumes, Labels: postLables || {}, Env: [], Dns: formData.Dns, Links: (formData.Links || []).map((item: any) => item.Value), CPUShares: formData.CPUShares || 0, Memory: formData.Memory || 0 } if(this.form.controls.EnableLogFile.value){ config.LogConfig = { Type: formData.LogDriver, Config: optsObj } } if (formData.Ulimits.length > 0) { config.Ulimits = formData.Ulimits; } this.cloneProcessMsg = []; this.isCloneDone = []; this.cloneProcessModalOptions.show = true; let self = this; for (let server of this.selectedServers) { let containerConf = _.cloneDeep(config); (function (server: string, containerConf: IContainer) { containerConf.Env = (formData.ServerEnvs[server] || []).map((item: any) => item.Value); self.addCloneMsg(server, "Begin to create container"); self._containerService.create(server, containerConf, true) .then((data) => { self.addCloneMsg(server, "Done!"); self._logService.addLog(`Clone ${containerConf.Name} from ${self.ip} to ${server}`, 'Container', self.groupInfo.ID, self.ip); self.isCloneDone.push(true); }) .catch((err) => { let errMsg = err.Detail || JSON.stringify(err); self.addCloneMsg(server, `Failed! Detail: ${errMsg}`); self.isCloneDone.push(false); }); })(server, containerConf); } } private addCloneMsg(server: string, msg: string) { this.cloneProcessMsg.push({ time: new Date(), server: server, msg: msg }); } private closeUpgradeProgressModal() { this.cloneProcessModalOptions.show = false; this._router.navigate(['/group', this.groupInfo.ID, 'overview']); } }
the_stack
declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class GoogleSignInAccount { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.GoogleSignInAccount>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.GoogleSignInAccount>; public getAccount(): globalAndroid.accounts.Account; public getGrantedScopes(): java.util.Set<com.google.android.gms.common.api.Scope>; public getGivenName(): string; public static createDefault(): com.google.android.gms.auth.api.signin.GoogleSignInAccount; public equals(param0: any): boolean; public getIdToken(): string; public getDisplayName(): string; public isExpired(): boolean; public zab(): string; public getFamilyName(): string; public getRequestedScopes(): java.util.Set<com.google.android.gms.common.api.Scope>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public static zaa(param0: string): com.google.android.gms.auth.api.signin.GoogleSignInAccount; public getPhotoUrl(): globalAndroid.net.Uri; public getEmail(): string; public getServerAuthCode(): string; public zac(): string; public requestExtraScopes(param0: native.Array<com.google.android.gms.common.api.Scope>): com.google.android.gms.auth.api.signin.GoogleSignInAccount; public getId(): string; public hashCode(): number; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class GoogleSignInOptions implements com.google.android.gms.common.api.Api.ApiOptions.Optional { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.GoogleSignInOptions>; public static zar: com.google.android.gms.common.api.Scope; public static zas: com.google.android.gms.common.api.Scope; public static zat: com.google.android.gms.common.api.Scope; public static zau: com.google.android.gms.common.api.Scope; public static zav: com.google.android.gms.common.api.Scope; public static DEFAULT_SIGN_IN: com.google.android.gms.auth.api.signin.GoogleSignInOptions; public static DEFAULT_GAMES_SIGN_IN: com.google.android.gms.auth.api.signin.GoogleSignInOptions; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.GoogleSignInOptions>; public getAccount(): globalAndroid.accounts.Account; public getServerClientId(): string; public isForceCodeForRefreshToken(): boolean; public equals(param0: any): boolean; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public static zab(param0: string): com.google.android.gms.auth.api.signin.GoogleSignInOptions; public zae(): string; public getScopes(): java.util.ArrayList<com.google.android.gms.common.api.Scope>; public isServerAuthCodeRequested(): boolean; public isIdTokenRequested(): boolean; public hashCode(): number; public getExtensions(): java.util.ArrayList<com.google.android.gms.auth.api.signin.internal.GoogleSignInOptionsExtensionParcelable>; public getScopeArray(): native.Array<com.google.android.gms.common.api.Scope>; } export module GoogleSignInOptions { export class Builder { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder>; public requestServerAuthCode(param0: string): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public constructor(); public requestScopes(param0: com.google.android.gms.common.api.Scope, param1: native.Array<com.google.android.gms.common.api.Scope>): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public requestIdToken(param0: string): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public addExtension(param0: com.google.android.gms.auth.api.signin.GoogleSignInOptionsExtension): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public requestEmail(): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public setAccountName(param0: string): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public requestServerAuthCode(param0: string, param1: boolean): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public setHostedDomain(param0: string): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public constructor(param0: com.google.android.gms.auth.api.signin.GoogleSignInOptions); public requestId(): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public requestProfile(): com.google.android.gms.auth.api.signin.GoogleSignInOptions.Builder; public build(): com.google.android.gms.auth.api.signin.GoogleSignInOptions; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class GoogleSignInOptionsExtension { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.GoogleSignInOptionsExtension>; /** * Constructs a new instance of the com.google.android.gms.auth.api.signin.GoogleSignInOptionsExtension interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getExtensionType(): number; toBundle(): globalAndroid.os.Bundle; getImpliedScopes(): java.util.List<com.google.android.gms.common.api.Scope>; }); public constructor(); public static FITNESS: number; public static GAMES: number; public toBundle(): globalAndroid.os.Bundle; public getImpliedScopes(): java.util.List<com.google.android.gms.common.api.Scope>; public getExtensionType(): number; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class GoogleSignInOptionsExtensionParcelable { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.GoogleSignInOptionsExtensionParcelable>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.internal.GoogleSignInOptionsExtensionParcelable>; public constructor(param0: com.google.android.gms.auth.api.signin.GoogleSignInOptionsExtension); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getType(): number; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class HashAccumulator { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.HashAccumulator>; public constructor(); public zaa(param0: boolean): com.google.android.gms.auth.api.signin.internal.HashAccumulator; public addObject(param0: any): com.google.android.gms.auth.api.signin.internal.HashAccumulator; public hash(): number; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class Storage { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.Storage>; public getSavedRefreshToken(): string; public getSavedDefaultGoogleSignInAccount(): com.google.android.gms.auth.api.signin.GoogleSignInAccount; public clear(): void; public zaf(): void; public getSavedDefaultGoogleSignInOptions(): com.google.android.gms.auth.api.signin.GoogleSignInOptions; public static getInstance(param0: globalAndroid.content.Context): com.google.android.gms.auth.api.signin.internal.Storage; public saveDefaultGoogleSignInAccount(param0: com.google.android.gms.auth.api.signin.GoogleSignInAccount, param1: com.google.android.gms.auth.api.signin.GoogleSignInOptions): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export module internal { export class zaa extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.internal.GoogleSignInOptionsExtensionParcelable> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.internal.zaa>; public constructor(); } } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class zaa { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.zaa>; public compare(param0: any, param1: any): number; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class zab extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.GoogleSignInAccount> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.zab>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class zac extends java.util.Comparator<com.google.android.gms.common.api.Scope> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.zac>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module auth { export module api { export module signin { export class zad extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.auth.api.signin.GoogleSignInOptions> { public static class: java.lang.Class<com.google.android.gms.auth.api.signin.zad>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export class ErrorDialogFragment { public static class: java.lang.Class<com.google.android.gms.common.ErrorDialogFragment>; public show(param0: globalAndroid.app.FragmentManager, param1: string): void; public constructor(); public static newInstance(param0: globalAndroid.app.Dialog): com.google.android.gms.common.ErrorDialogFragment; public onCancel(param0: globalAndroid.content.DialogInterface): void; public onCreateDialog(param0: globalAndroid.os.Bundle): globalAndroid.app.Dialog; public static newInstance(param0: globalAndroid.app.Dialog, param1: globalAndroid.content.DialogInterface.OnCancelListener): com.google.android.gms.common.ErrorDialogFragment; } } } } } } declare module com { export module google { export module android { export module gms { export module common { export class GoogleApiAvailability { public static class: java.lang.Class<com.google.android.gms.common.GoogleApiAvailability>; public static GOOGLE_PLAY_SERVICES_VERSION_CODE: number; public static GOOGLE_PLAY_SERVICES_PACKAGE: string; public makeGooglePlayServicesAvailable(param0: globalAndroid.app.Activity): com.google.android.gms.tasks.Task<java.lang.Void>; public static zaa(param0: globalAndroid.app.Activity, param1: globalAndroid.content.DialogInterface.OnCancelListener): globalAndroid.app.Dialog; public constructor(); public showErrorNotification(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.ConnectionResult): void; public getErrorResolutionPendingIntent(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.ConnectionResult): globalAndroid.app.PendingIntent; public getErrorDialog(param0: globalAndroid.app.Activity, param1: number, param2: number, param3: globalAndroid.content.DialogInterface.OnCancelListener): globalAndroid.app.Dialog; public zaa(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.internal.zabr): com.google.android.gms.common.api.internal.zabq; public getClientVersion(param0: globalAndroid.content.Context): number; public static getInstance(): com.google.android.gms.common.GoogleApiAvailability; public showErrorDialogFragment(param0: globalAndroid.app.Activity, param1: number, param2: number): boolean; public zaa(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.ConnectionResult, param2: number): boolean; public checkApiAvailability(param0: com.google.android.gms.common.api.GoogleApi<any>, param1: native.Array<com.google.android.gms.common.api.GoogleApi<any>>): com.google.android.gms.tasks.Task<java.lang.Void>; public showErrorNotification(param0: globalAndroid.content.Context, param1: number): void; public getErrorResolutionPendingIntent(param0: globalAndroid.content.Context, param1: number, param2: number): globalAndroid.app.PendingIntent; public getErrorResolutionIntent(param0: globalAndroid.content.Context, param1: number, param2: string): globalAndroid.content.Intent; public zaa(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.internal.LifecycleFragment, param2: number, param3: number, param4: globalAndroid.content.DialogInterface.OnCancelListener): boolean; public setDefaultNotificationChannelId(param0: globalAndroid.content.Context, param1: string): void; public showErrorDialogFragment(param0: globalAndroid.app.Activity, param1: number, param2: number, param3: globalAndroid.content.DialogInterface.OnCancelListener): boolean; public getErrorDialog(param0: globalAndroid.app.Activity, param1: number, param2: number): globalAndroid.app.Dialog; public getErrorString(param0: number): string; public isGooglePlayServicesAvailable(param0: globalAndroid.content.Context): number; public isGooglePlayServicesAvailable(param0: globalAndroid.content.Context, param1: number): number; public isUserResolvableError(param0: number): boolean; } export module GoogleApiAvailability { export class zaa extends com.google.android.gms.internal.base.zap { public static class: java.lang.Class<com.google.android.gms.common.GoogleApiAvailability.zaa>; public constructor(); public constructor(param0: globalAndroid.os.Looper); public constructor(param0: com.google.android.gms.common.GoogleApiAvailability, param1: globalAndroid.content.Context); public constructor(param0: globalAndroid.os.Looper, param1: globalAndroid.os.Handler.Callback); public handleMessage(param0: globalAndroid.os.Message): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export class GooglePlayServicesUtil { public static class: java.lang.Class<com.google.android.gms.common.GooglePlayServicesUtil>; public static GMS_ERROR_DIALOG: string; public static GOOGLE_PLAY_SERVICES_VERSION_CODE: number; public static GOOGLE_PLAY_SERVICES_PACKAGE: string; public static GOOGLE_PLAY_STORE_PACKAGE: string; public static showErrorDialogFragment(param0: number, param1: globalAndroid.app.Activity, param2: globalAndroid.support.v4.app.Fragment, param3: number, param4: globalAndroid.content.DialogInterface.OnCancelListener): boolean; public static showErrorNotification(param0: number, param1: globalAndroid.content.Context): void; public static isGooglePlayServicesAvailable(param0: globalAndroid.content.Context): number; public static isUserRecoverableError(param0: number): boolean; public static getRemoteContext(param0: globalAndroid.content.Context): globalAndroid.content.Context; public static getRemoteResource(param0: globalAndroid.content.Context): globalAndroid.content.res.Resources; public static getErrorString(param0: number): string; public static getErrorDialog(param0: number, param1: globalAndroid.app.Activity, param2: number, param3: globalAndroid.content.DialogInterface.OnCancelListener): globalAndroid.app.Dialog; public static showErrorDialogFragment(param0: number, param1: globalAndroid.app.Activity, param2: number, param3: globalAndroid.content.DialogInterface.OnCancelListener): boolean; public static getErrorPendingIntent(param0: number, param1: globalAndroid.content.Context, param2: number): globalAndroid.app.PendingIntent; public static showErrorDialogFragment(param0: number, param1: globalAndroid.app.Activity, param2: number): boolean; public static getErrorDialog(param0: number, param1: globalAndroid.app.Activity, param2: number): globalAndroid.app.Dialog; public static isGooglePlayServicesAvailable(param0: globalAndroid.content.Context, param1: number): number; } } } } } } declare module com { export module google { export module android { export module gms { export module common { export class SignInButton { public static class: java.lang.Class<com.google.android.gms.common.SignInButton>; public static SIZE_STANDARD: number; public static SIZE_WIDE: number; public static SIZE_ICON_ONLY: number; public static COLOR_DARK: number; public static COLOR_LIGHT: number; public static COLOR_AUTO: number; public setSize(param0: number): void; public constructor(param0: globalAndroid.content.Context); public setColorScheme(param0: number): void; public setScopes(param0: native.Array<com.google.android.gms.common.api.Scope>): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet, param2: number); public setStyle(param0: number, param1: number, param2: native.Array<com.google.android.gms.common.api.Scope>): void; public setOnClickListener(param0: globalAndroid.view.View.OnClickListener): void; public setStyle(param0: number, param1: number): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet); public setEnabled(param0: boolean): void; public onClick(param0: globalAndroid.view.View): void; } export module SignInButton { export class ButtonSize { public static class: java.lang.Class<com.google.android.gms.common.SignInButton.ButtonSize>; /** * Constructs a new instance of the com.google.android.gms.common.SignInButton$ButtonSize interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } export class ColorScheme { public static class: java.lang.Class<com.google.android.gms.common.SignInButton.ColorScheme>; /** * Constructs a new instance of the com.google.android.gms.common.SignInButton$ColorScheme interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export class SupportErrorDialogFragment { public static class: java.lang.Class<com.google.android.gms.common.SupportErrorDialogFragment>; public constructor(); public onCancel(param0: globalAndroid.content.DialogInterface): void; public show(param0: globalAndroid.support.v4.app.FragmentManager, param1: string): void; public static newInstance(param0: globalAndroid.app.Dialog, param1: globalAndroid.content.DialogInterface.OnCancelListener): com.google.android.gms.common.SupportErrorDialogFragment; public onCreateDialog(param0: globalAndroid.os.Bundle): globalAndroid.app.Dialog; public static newInstance(param0: globalAndroid.app.Dialog): com.google.android.gms.common.SupportErrorDialogFragment; } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class Api<O> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.Api<any>>; public constructor(param0: string, param1: com.google.android.gms.common.api.Api.AbstractClientBuilder<any,any>, param2: com.google.android.gms.common.api.Api.ClientKey<any>); public zah(): com.google.android.gms.common.api.Api.BaseClientBuilder<any,O>; public getClientKey(): com.google.android.gms.common.api.Api.AnyClientKey<any>; public zai(): com.google.android.gms.common.api.Api.AbstractClientBuilder<any,O>; public getName(): string; } export module Api { export abstract class AbstractClientBuilder<T, O> extends com.google.android.gms.common.api.Api.BaseClientBuilder<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.Api.AbstractClientBuilder<any,any>>; public buildClient(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.ClientSettings, param3: any, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): any; public constructor(); } export class AnyClient { public static class: java.lang.Class<com.google.android.gms.common.api.Api.AnyClient>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$AnyClient interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } export class AnyClientKey<C> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.Api.AnyClientKey<any>>; public constructor(); } export class ApiOptions { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ApiOptions>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$ApiOptions interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } export module ApiOptions { export class HasAccountOptions implements com.google.android.gms.common.api.Api.ApiOptions.HasOptions, com.google.android.gms.common.api.Api.ApiOptions.NotRequiredOptions { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ApiOptions.HasAccountOptions>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$ApiOptions$HasAccountOptions interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getAccount(): globalAndroid.accounts.Account; }); public constructor(); public getAccount(): globalAndroid.accounts.Account; } export class HasGoogleSignInAccountOptions extends com.google.android.gms.common.api.Api.ApiOptions.HasOptions { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ApiOptions.HasGoogleSignInAccountOptions>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$ApiOptions$HasGoogleSignInAccountOptions interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getGoogleSignInAccount(): com.google.android.gms.auth.api.signin.GoogleSignInAccount; }); public constructor(); public getGoogleSignInAccount(): com.google.android.gms.auth.api.signin.GoogleSignInAccount; } export class HasOptions extends com.google.android.gms.common.api.Api.ApiOptions { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ApiOptions.HasOptions>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$ApiOptions$HasOptions interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } export class NoOptions extends com.google.android.gms.common.api.Api.ApiOptions.NotRequiredOptions { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ApiOptions.NoOptions>; } export class NotRequiredOptions extends com.google.android.gms.common.api.Api.ApiOptions { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ApiOptions.NotRequiredOptions>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$ApiOptions$NotRequiredOptions interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } export class Optional implements com.google.android.gms.common.api.Api.ApiOptions.HasOptions, com.google.android.gms.common.api.Api.ApiOptions.NotRequiredOptions { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ApiOptions.Optional>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$ApiOptions$Optional interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } export class BaseClientBuilder<T, O> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.Api.BaseClientBuilder<any,any>>; public static API_PRIORITY_GAMES: number; public static API_PRIORITY_PLUS: number; public static API_PRIORITY_OTHER: number; public getImpliedScopes(param0: O): java.util.List<com.google.android.gms.common.api.Scope>; public getPriority(): number; public constructor(); } export class Client extends com.google.android.gms.common.api.Api.AnyClient { public static class: java.lang.Class<com.google.android.gms.common.api.Api.Client>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$Client interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; disconnect(): void; isConnected(): boolean; isConnecting(): boolean; getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; requiresSignIn(): boolean; onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; requiresAccount(): boolean; requiresGooglePlayServices(): boolean; providesSignIn(): boolean; getSignInIntent(): globalAndroid.content.Intent; dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; getServiceBrokerBinder(): globalAndroid.os.IBinder; getRequiredFeatures(): native.Array<com.google.android.gms.common.Feature>; getEndpointPackageName(): string; getMinApkVersion(): number; getAvailableFeatures(): native.Array<com.google.android.gms.common.Feature>; }); public constructor(); public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public requiresSignIn(): boolean; public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public getSignInIntent(): globalAndroid.content.Intent; public getRequiredFeatures(): native.Array<com.google.android.gms.common.Feature>; public getServiceBrokerBinder(): globalAndroid.os.IBinder; public getEndpointPackageName(): string; public requiresGooglePlayServices(): boolean; public isConnected(): boolean; public requiresAccount(): boolean; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public getMinApkVersion(): number; public disconnect(): void; public getAvailableFeatures(): native.Array<com.google.android.gms.common.Feature>; public isConnecting(): boolean; public providesSignIn(): boolean; } export class ClientKey<C> extends com.google.android.gms.common.api.Api.AnyClientKey<any> { public static class: java.lang.Class<com.google.android.gms.common.api.Api.ClientKey<any>>; public constructor(); } export class SimpleClient<T> extends com.google.android.gms.common.api.Api.AnyClient { public static class: java.lang.Class<com.google.android.gms.common.api.Api.SimpleClient<any>>; /** * Constructs a new instance of the com.google.android.gms.common.api.Api$SimpleClient interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getStartServiceAction(): string; getServiceDescriptor(): string; createServiceInterface(param0: globalAndroid.os.IBinder): any; getContext(): globalAndroid.content.Context; setState(param0: number, param1: any): void; }); public constructor(); public getStartServiceAction(): string; public createServiceInterface(param0: globalAndroid.os.IBinder): any; public getContext(): globalAndroid.content.Context; public getServiceDescriptor(): string; public setState(param0: number, param1: any): void; } export class zaa<T, O> extends com.google.android.gms.common.api.Api.BaseClientBuilder<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.Api.zaa<any,any>>; } export class zab<C> extends com.google.android.gms.common.api.Api.AnyClientKey<any> { public static class: java.lang.Class<com.google.android.gms.common.api.Api.zab<any>>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class AvailabilityException { public static class: java.lang.Class<com.google.android.gms.common.api.AvailabilityException>; public zaj(): globalAndroid.support.v4.util.ArrayMap<com.google.android.gms.common.api.internal.zai<any>,com.google.android.gms.common.ConnectionResult>; public constructor(param0: globalAndroid.support.v4.util.ArrayMap<com.google.android.gms.common.api.internal.zai<any>,com.google.android.gms.common.ConnectionResult>); public getMessage(): string; public getConnectionResult(param0: com.google.android.gms.common.api.GoogleApi<any>): com.google.android.gms.common.ConnectionResult; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class Batch extends com.google.android.gms.common.api.internal.BasePendingResult<com.google.android.gms.common.api.BatchResult> { public static class: java.lang.Class<com.google.android.gms.common.api.Batch>; public cancel(): void; public createFailedResult(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.BatchResult; public createFailedResult(param0: com.google.android.gms.common.api.Status): any; } export module Batch { export class Builder { public static class: java.lang.Class<com.google.android.gms.common.api.Batch.Builder>; public build(): com.google.android.gms.common.api.Batch; public add(param0: com.google.android.gms.common.api.PendingResult<any>): com.google.android.gms.common.api.BatchResultToken<any>; public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class BatchResult { public static class: java.lang.Class<com.google.android.gms.common.api.BatchResult>; public getStatus(): com.google.android.gms.common.api.Status; public take(param0: com.google.android.gms.common.api.BatchResultToken<any>): com.google.android.gms.common.api.Result; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class BatchResultToken<R> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.BatchResultToken<any>>; public mId: number; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class BooleanResult { public static class: java.lang.Class<com.google.android.gms.common.api.BooleanResult>; public constructor(param0: com.google.android.gms.common.api.Status, param1: boolean); public getStatus(): com.google.android.gms.common.api.Status; public hashCode(): number; public getValue(): boolean; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class DataBufferResponse<T, R> extends com.google.android.gms.common.api.Response<any> implements com.google.android.gms.common.data.DataBuffer<any> { public static class: java.lang.Class<com.google.android.gms.common.api.DataBufferResponse<any,any>>; public constructor(); public singleRefIterator(): java.util.Iterator<any>; public getMetadata(): globalAndroid.os.Bundle; public close(): void; public iterator(): java.util.Iterator<any>; public get(param0: number): any; public isClosed(): boolean; public release(): void; public getCount(): number; public constructor(param0: any); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class GoogleApi<O> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApi<any>>; public zabm: com.google.android.gms.common.api.internal.GoogleApiManager; public doRegisterEventListener(param0: com.google.android.gms.common.api.internal.RegistrationMethods<any,any>): com.google.android.gms.tasks.Task; public registerListener(param0: any, param1: string): com.google.android.gms.common.api.internal.ListenerHolder<any>; public zaa(param0: globalAndroid.os.Looper, param1: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<O>): com.google.android.gms.common.api.Api.Client; public doWrite(param0: com.google.android.gms.common.api.internal.TaskApiCall<any,any>): com.google.android.gms.tasks.Task; public doBestEffortWrite(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<O>, param2: O, param3: com.google.android.gms.common.api.internal.StatusExceptionMapper); public doUnregisterEventListener(param0: com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<any>): com.google.android.gms.tasks.Task<java.lang.Boolean>; public getLooper(): globalAndroid.os.Looper; public getApi(): com.google.android.gms.common.api.Api<O>; public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<O>, param2: O, param3: globalAndroid.os.Looper, param4: com.google.android.gms.common.api.internal.StatusExceptionMapper); public getApiOptions(): O; public constructor(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.Api<O>, param2: O, param3: com.google.android.gms.common.api.GoogleApi.Settings); public zak(): com.google.android.gms.common.api.internal.zai<O>; public createClientSettingsBuilder(): com.google.android.gms.common.internal.ClientSettings.Builder; public getInstanceId(): number; public doRead(param0: com.google.android.gms.common.api.internal.TaskApiCall<any,any>): com.google.android.gms.tasks.Task; public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<O>, param2: globalAndroid.os.Looper); public getApplicationContext(): globalAndroid.content.Context; public doWrite(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public constructor(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.Api<O>, param2: O, param3: com.google.android.gms.common.api.internal.StatusExceptionMapper); public disconnectService(): com.google.android.gms.tasks.Task<java.lang.Boolean>; public zaa(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler): com.google.android.gms.common.api.internal.zace; public doBestEffortWrite(param0: com.google.android.gms.common.api.internal.TaskApiCall<any,any>): com.google.android.gms.tasks.Task; public asGoogleApiClient(): com.google.android.gms.common.api.GoogleApiClient; public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<O>, param2: O, param3: com.google.android.gms.common.api.GoogleApi.Settings); public doRead(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public doRegisterEventListener(param0: com.google.android.gms.common.api.internal.RegisterListenerMethod<any,any>, param1: com.google.android.gms.common.api.internal.UnregisterListenerMethod<any,any>): com.google.android.gms.tasks.Task; } export module GoogleApi { export class Settings { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApi.Settings>; public static DEFAULT_SETTINGS: com.google.android.gms.common.api.GoogleApi.Settings; public zabn: com.google.android.gms.common.api.internal.StatusExceptionMapper; public zabo: globalAndroid.os.Looper; } export module Settings { export class Builder { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApi.Settings.Builder>; public constructor(); public setLooper(param0: globalAndroid.os.Looper): com.google.android.gms.common.api.GoogleApi.Settings.Builder; public build(): com.google.android.gms.common.api.GoogleApi.Settings; public setMapper(param0: com.google.android.gms.common.api.internal.StatusExceptionMapper): com.google.android.gms.common.api.GoogleApi.Settings.Builder; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class GoogleApiActivity { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApiActivity>; public constructor(); public onCancel(param0: globalAndroid.content.DialogInterface): void; public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): void; public onCreate(param0: globalAndroid.os.Bundle): void; public static zaa(param0: globalAndroid.content.Context, param1: globalAndroid.app.PendingIntent, param2: number): globalAndroid.app.PendingIntent; public static zaa(param0: globalAndroid.content.Context, param1: globalAndroid.app.PendingIntent, param2: number, param3: boolean): globalAndroid.content.Intent; public onSaveInstanceState(param0: globalAndroid.os.Bundle): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export abstract class GoogleApiClient { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApiClient>; public static DEFAULT_ACCOUNT: string; public static SIGN_IN_MODE_REQUIRED: number; public static SIGN_IN_MODE_OPTIONAL: number; public isConnectionFailedListenerRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): boolean; public static dumpAll(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public registerConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public unregisterConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public registerConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public getLooper(): globalAndroid.os.Looper; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public zaa(param0: com.google.android.gms.common.api.internal.zacm<any>): void; public hasConnectedApi(param0: com.google.android.gms.common.api.Api<any>): boolean; public blockingConnect(): com.google.android.gms.common.ConnectionResult; public zab(param0: com.google.android.gms.common.api.internal.zacm<any>): void; public connect(): void; public stopAutoManage(param0: globalAndroid.support.v4.app.FragmentActivity): void; public execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public maybeSignOut(): void; public clearDefaultAccountAndReconnect(): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public hasApi(param0: com.google.android.gms.common.api.Api<any>): boolean; public constructor(); public isConnectionCallbacksRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): boolean; public getContext(): globalAndroid.content.Context; public disconnect(): void; public isConnected(): boolean; public reconnect(): void; public unregisterConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public getConnectionResult(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; public isConnecting(): boolean; public enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public registerListener(param0: any): com.google.android.gms.common.api.internal.ListenerHolder<any>; public blockingConnect(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; public maybeSignIn(param0: com.google.android.gms.common.api.internal.SignInConnectionListener): boolean; public static getAllClients(): java.util.Set<com.google.android.gms.common.api.GoogleApiClient>; public getClient(param0: com.google.android.gms.common.api.Api.AnyClientKey<any>): com.google.android.gms.common.api.Api.Client; public connect(param0: number): void; } export module GoogleApiClient { export class Builder { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApiClient.Builder>; public build(): com.google.android.gms.common.api.GoogleApiClient; public useDefaultAccount(): com.google.android.gms.common.api.GoogleApiClient.Builder; public addConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): com.google.android.gms.common.api.GoogleApiClient.Builder; public buildClientSettings(): com.google.android.gms.common.internal.ClientSettings; public addScopeNames(param0: native.Array<string>): com.google.android.gms.common.api.GoogleApiClient.Builder; public addScope(param0: com.google.android.gms.common.api.Scope): com.google.android.gms.common.api.GoogleApiClient.Builder; public addOnConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): com.google.android.gms.common.api.GoogleApiClient.Builder; public enableAutoManage(param0: globalAndroid.support.v4.app.FragmentActivity, param1: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): com.google.android.gms.common.api.GoogleApiClient.Builder; public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param2: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public enableAutoManage(param0: globalAndroid.support.v4.app.FragmentActivity, param1: number, param2: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): com.google.android.gms.common.api.GoogleApiClient.Builder; public setViewForPopups(param0: globalAndroid.view.View): com.google.android.gms.common.api.GoogleApiClient.Builder; public setHandler(param0: globalAndroid.os.Handler): com.google.android.gms.common.api.GoogleApiClient.Builder; public addApiIfAvailable(param0: com.google.android.gms.common.api.Api<any>, param1: native.Array<com.google.android.gms.common.api.Scope>): com.google.android.gms.common.api.GoogleApiClient.Builder; public constructor(param0: globalAndroid.content.Context); public addApi(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.api.GoogleApiClient.Builder; public addApi(param0: com.google.android.gms.common.api.Api<any>, param1: com.google.android.gms.common.api.Api.ApiOptions.HasOptions): com.google.android.gms.common.api.GoogleApiClient.Builder; public addApiIfAvailable(param0: com.google.android.gms.common.api.Api<any>, param1: com.google.android.gms.common.api.Api.ApiOptions.HasOptions, param2: native.Array<com.google.android.gms.common.api.Scope>): com.google.android.gms.common.api.GoogleApiClient.Builder; public setGravityForPopups(param0: number): com.google.android.gms.common.api.GoogleApiClient.Builder; public setAccountName(param0: string): com.google.android.gms.common.api.GoogleApiClient.Builder; } export class ConnectionCallbacks { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks>; /** * Constructs a new instance of the com.google.android.gms.common.api.GoogleApiClient$ConnectionCallbacks interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onConnected(param0: globalAndroid.os.Bundle): void; onConnectionSuspended(param0: number): void; }); public constructor(); public static CAUSE_SERVICE_DISCONNECTED: number; public static CAUSE_NETWORK_LOST: number; public onConnected(param0: globalAndroid.os.Bundle): void; public onConnectionSuspended(param0: number): void; } export class OnConnectionFailedListener { public static class: java.lang.Class<com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener>; /** * Constructs a new instance of the com.google.android.gms.common.api.GoogleApiClient$OnConnectionFailedListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; }); public constructor(); public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export abstract class OptionalPendingResult<R> extends com.google.android.gms.common.api.PendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.OptionalPendingResult<any>>; public constructor(); public get(): any; public isDone(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export abstract class PendingResult<R> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.PendingResult<any>>; public constructor(); public cancel(): void; public isCanceled(): boolean; public await(param0: number, param1: java.util.concurrent.TimeUnit): R; public await(): R; public addStatusListener(param0: com.google.android.gms.common.api.PendingResult.StatusListener): void; public then(param0: com.google.android.gms.common.api.ResultTransform<any,any>): com.google.android.gms.common.api.TransformedResult<any>; public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>, param1: number, param2: java.util.concurrent.TimeUnit): void; public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>): void; public zam(): java.lang.Integer; } export module PendingResult { export class StatusListener { public static class: java.lang.Class<com.google.android.gms.common.api.PendingResult.StatusListener>; /** * Constructs a new instance of the com.google.android.gms.common.api.PendingResult$StatusListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onComplete(param0: com.google.android.gms.common.api.Status): void; }); public constructor(); public onComplete(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class PendingResults { public static class: java.lang.Class<com.google.android.gms.common.api.PendingResults>; public static immediateFailedResult(param0: com.google.android.gms.common.api.Result, param1: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<any>; public static immediatePendingResult(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public static canceledPendingResult(param0: com.google.android.gms.common.api.Result): com.google.android.gms.common.api.PendingResult<any>; public static immediatePendingResult(param0: com.google.android.gms.common.api.Result, param1: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.OptionalPendingResult<any>; public static immediatePendingResult(param0: com.google.android.gms.common.api.Result): com.google.android.gms.common.api.OptionalPendingResult<any>; public static immediatePendingResult(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public static canceledPendingResult(): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; } export module PendingResults { export class zaa<R> extends com.google.android.gms.common.api.internal.BasePendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.PendingResults.zaa<any>>; public constructor(param0: any); public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public createFailedResult(param0: com.google.android.gms.common.api.Status): any; public constructor(param0: globalAndroid.os.Looper); public constructor(); } export class zab<R> extends com.google.android.gms.common.api.internal.BasePendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.PendingResults.zab<any>>; public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public constructor(param0: com.google.android.gms.common.api.GoogleApiClient, param1: any); public createFailedResult(param0: com.google.android.gms.common.api.Status): any; public constructor(param0: globalAndroid.os.Looper); public constructor(); } export class zac<R> extends com.google.android.gms.common.api.internal.BasePendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.PendingResults.zac<any>>; public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public createFailedResult(param0: com.google.android.gms.common.api.Status): any; public constructor(param0: globalAndroid.os.Looper); public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export abstract class ResultTransform<R, S> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.ResultTransform<any,any>>; public constructor(); public onSuccess(param0: R): com.google.android.gms.common.api.PendingResult<S>; public createFailedResult(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.PendingResult<S>; public onFailure(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.Status; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export abstract class TransformedResult<R> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.TransformedResult<any>>; public constructor(); public then(param0: com.google.android.gms.common.api.ResultTransform<any,any>): com.google.android.gms.common.api.TransformedResult<any>; public andFinally(param0: com.google.android.gms.common.api.ResultCallbacks<any>): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class ActivityLifecycleObserver { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ActivityLifecycleObserver>; public onStopCallOnce(param0: java.lang.Runnable): com.google.android.gms.common.api.internal.ActivityLifecycleObserver; public static of(param0: globalAndroid.app.Activity): com.google.android.gms.common.api.internal.ActivityLifecycleObserver; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class ApiExceptionMapper { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ApiExceptionMapper>; public constructor(); public getException(param0: com.google.android.gms.common.api.Status): java.lang.Exception; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class BaseImplementation { public static class: java.lang.Class<com.google.android.gms.common.api.internal.BaseImplementation>; public constructor(); } export module BaseImplementation { export abstract class ApiMethodImpl<R, A> extends com.google.android.gms.common.api.internal.BasePendingResult<any> implements com.google.android.gms.common.api.internal.BaseImplementation.ResultHolder<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>>; public constructor(); public getApi(): com.google.android.gms.common.api.Api<any>; public constructor(param0: com.google.android.gms.common.api.Api.AnyClientKey<any>, param1: com.google.android.gms.common.api.GoogleApiClient); public run(param0: any): void; public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public setFailedResult(param0: com.google.android.gms.common.api.Status): void; public getClientKey(): com.google.android.gms.common.api.Api.AnyClientKey<any>; public onSetFailedResult(param0: any): void; public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public doExecute(param0: any): void; public setResult(param0: any): void; public constructor(param0: globalAndroid.os.Looper); public constructor(param0: com.google.android.gms.common.api.Api<any>, param1: com.google.android.gms.common.api.GoogleApiClient); } export class ResultHolder<R> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.BaseImplementation.ResultHolder<any>>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.BaseImplementation$ResultHolder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { setResult(param0: R): void; setFailedResult(param0: com.google.android.gms.common.api.Status): void; }); public constructor(); public setResult(param0: R): void; public setFailedResult(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class BasePendingResult<R> extends com.google.android.gms.common.api.PendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.BasePendingResult<any>>; public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>): void; public setCancelToken(param0: com.google.android.gms.common.internal.ICancelToken): void; public then(param0: com.google.android.gms.common.api.ResultTransform<any,any>): com.google.android.gms.common.api.TransformedResult<any>; public static zab(param0: com.google.android.gms.common.api.Result): void; public cancel(): void; public zab(param0: com.google.android.gms.common.api.Status): void; public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public zat(): boolean; public createFailedResult(param0: com.google.android.gms.common.api.Status): any; public constructor(); public constructor(param0: globalAndroid.os.Looper); public await(param0: number, param1: java.util.concurrent.TimeUnit): any; public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>, param1: number, param2: java.util.concurrent.TimeUnit): void; public setResult(param0: any): void; public await(): any; public zaa(param0: com.google.android.gms.common.api.internal.zacs): void; public zau(): void; public isCanceled(): boolean; public isReady(): boolean; public addStatusListener(param0: com.google.android.gms.common.api.PendingResult.StatusListener): void; public zam(): java.lang.Integer; } export module BasePendingResult { export class CallbackHandler<R> extends com.google.android.gms.internal.base.zap { public static class: java.lang.Class<com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>>; public constructor(); public zaa(param0: com.google.android.gms.common.api.ResultCallback<any>, param1: any): void; public constructor(param0: globalAndroid.os.Looper, param1: globalAndroid.os.Handler.Callback); public handleMessage(param0: globalAndroid.os.Message): void; public constructor(param0: globalAndroid.os.Looper); } export class zaa { public static class: java.lang.Class<com.google.android.gms.common.api.internal.BasePendingResult.zaa>; public finalize(): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class DataHolderNotifier<L> extends com.google.android.gms.common.api.internal.ListenerHolder.Notifier<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.DataHolderNotifier<any>>; public onNotifyListenerFailed(): void; public notifyListener(param0: any, param1: com.google.android.gms.common.data.DataHolder): void; public notifyListener(param0: any): void; public constructor(param0: com.google.android.gms.common.data.DataHolder); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class DataHolderResult { public static class: java.lang.Class<com.google.android.gms.common.api.internal.DataHolderResult>; public mStatus: com.google.android.gms.common.api.Status; public mDataHolder: com.google.android.gms.common.data.DataHolder; public constructor(param0: com.google.android.gms.common.data.DataHolder, param1: com.google.android.gms.common.api.Status); public getStatus(): com.google.android.gms.common.api.Status; public release(): void; public constructor(param0: com.google.android.gms.common.data.DataHolder); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class GoogleApiManager { public static class: java.lang.Class<com.google.android.gms.common.api.internal.GoogleApiManager>; public static zahx: com.google.android.gms.common.api.Status; public zac(param0: com.google.android.gms.common.api.GoogleApi<any>): com.google.android.gms.tasks.Task<java.lang.Boolean>; public zao(): void; public handleMessage(param0: globalAndroid.os.Message): boolean; public zaa(param0: com.google.android.gms.common.api.internal.zaae): void; public static zabc(): com.google.android.gms.common.api.internal.GoogleApiManager; public zabd(): number; public zaa(param0: com.google.android.gms.common.api.GoogleApi<any>, param1: com.google.android.gms.common.api.internal.RegisterListenerMethod<any,any>, param2: com.google.android.gms.common.api.internal.UnregisterListenerMethod<any,any>): com.google.android.gms.tasks.Task; public zaa(param0: com.google.android.gms.common.api.GoogleApi<any>, param1: com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<any>): com.google.android.gms.tasks.Task; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: number): void; public static reportSignOut(): void; public zaa(param0: java.lang.Iterable<any>): com.google.android.gms.tasks.Task<java.util.Map<com.google.android.gms.common.api.internal.zai<any>,string>>; public zaa(param0: com.google.android.gms.common.api.GoogleApi<any>): void; public static zab(param0: globalAndroid.content.Context): com.google.android.gms.common.api.internal.GoogleApiManager; public zaa(param0: com.google.android.gms.common.api.GoogleApi<any>, param1: number, param2: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): void; public zaa(param0: com.google.android.gms.common.api.GoogleApi<any>, param1: number, param2: com.google.android.gms.common.api.internal.TaskApiCall<any,any>, param3: com.google.android.gms.tasks.TaskCompletionSource, param4: com.google.android.gms.common.api.internal.StatusExceptionMapper): void; } export module GoogleApiManager { export class zaa<O> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>>; public zag(param0: com.google.android.gms.common.ConnectionResult): void; public zabm(): com.google.android.gms.common.ConnectionResult; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; public requiresSignIn(): boolean; public zaa(param0: com.google.android.gms.common.api.internal.zab): void; public connect(): void; public zabl(): void; public zaa(param0: com.google.android.gms.common.api.internal.zak): void; public getInstanceId(): number; public onConnected(param0: globalAndroid.os.Bundle): void; public constructor(param0: com.google.android.gms.common.api.GoogleApi<O>); public zabp(): boolean; public onConnectionSuspended(param0: number): void; public zaab(): com.google.android.gms.common.api.Api.Client; public zabk(): java.util.Map<com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<any>,com.google.android.gms.common.api.internal.zabw>; public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; public resume(): void; public zaav(): void; public zabj(): void; public zac(param0: com.google.android.gms.common.api.Status): void; } export class zab { public static class: java.lang.Class<com.google.android.gms.common.api.internal.GoogleApiManager.zab>; public hashCode(): number; public equals(param0: any): boolean; public toString(): string; } export class zac extends com.google.android.gms.common.api.internal.zach { public static class: java.lang.Class<com.google.android.gms.common.api.internal.GoogleApiManager.zac>; public zag(param0: com.google.android.gms.common.ConnectionResult): void; public onReportServiceBinding(param0: com.google.android.gms.common.ConnectionResult): void; public constructor(param0: com.google.android.gms.common.api.Api.Client, param1: com.google.android.gms.common.api.internal.zai<any>); public zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class IStatusCallback { public static class: java.lang.Class<com.google.android.gms.common.api.internal.IStatusCallback>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.IStatusCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onResult(param0: com.google.android.gms.common.api.Status): void; }); public constructor(); public onResult(param0: com.google.android.gms.common.api.Status): void; } export module IStatusCallback { export abstract class Stub extends com.google.android.gms.internal.base.zab implements com.google.android.gms.common.api.internal.IStatusCallback { public static class: java.lang.Class<com.google.android.gms.common.api.internal.IStatusCallback.Stub>; public constructor(param0: string); public constructor(); public onResult(param0: com.google.android.gms.common.api.Status): void; public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public static asInterface(param0: globalAndroid.os.IBinder): com.google.android.gms.common.api.internal.IStatusCallback; } export module Stub { export class zaa extends com.google.android.gms.internal.base.zaa implements com.google.android.gms.common.api.internal.IStatusCallback { public static class: java.lang.Class<com.google.android.gms.common.api.internal.IStatusCallback.Stub.zaa>; public onResult(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class ListenerHolder<L> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ListenerHolder<any>>; public getListenerKey(): com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<L>; public clear(): void; public notifyListener(param0: com.google.android.gms.common.api.internal.ListenerHolder.Notifier<any>): void; public hasListener(): boolean; } export module ListenerHolder { export class ListenerKey<L> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<any>>; public hashCode(): number; public equals(param0: any): boolean; } export class Notifier<L> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ListenerHolder.Notifier<any>>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.ListenerHolder$Notifier interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { notifyListener(param0: L): void; onNotifyListenerFailed(): void; }); public constructor(); public notifyListener(param0: L): void; public onNotifyListenerFailed(): void; } export class zaa extends com.google.android.gms.internal.base.zap { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ListenerHolder.zaa>; public constructor(); public constructor(param0: globalAndroid.os.Looper, param1: globalAndroid.os.Handler.Callback); public handleMessage(param0: globalAndroid.os.Message): void; public constructor(param0: globalAndroid.os.Looper); public constructor(param0: com.google.android.gms.common.api.internal.ListenerHolder<any>, param1: globalAndroid.os.Looper); } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class ListenerHolders { public static class: java.lang.Class<com.google.android.gms.common.api.internal.ListenerHolders>; public static createListenerKey(param0: any, param1: string): com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<any>; public constructor(); public static createListenerHolder(param0: any, param1: globalAndroid.os.Looper, param2: string): com.google.android.gms.common.api.internal.ListenerHolder<any>; public release(): void; public zaa(param0: any, param1: globalAndroid.os.Looper, param2: string): com.google.android.gms.common.api.internal.ListenerHolder<any>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class OptionalPendingResultImpl<R> extends com.google.android.gms.common.api.OptionalPendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.OptionalPendingResultImpl<any>>; public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>): void; public then(param0: com.google.android.gms.common.api.ResultTransform<any,any>): com.google.android.gms.common.api.TransformedResult<any>; public cancel(): void; public get(): any; public constructor(); public isDone(): boolean; public await(param0: number, param1: java.util.concurrent.TimeUnit): any; public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>, param1: number, param2: java.util.concurrent.TimeUnit): void; public await(): any; public isCanceled(): boolean; public constructor(param0: com.google.android.gms.common.api.PendingResult<any>); public addStatusListener(param0: com.google.android.gms.common.api.PendingResult.StatusListener): void; public zam(): java.lang.Integer; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class PendingResultFacade<A, B> extends com.google.android.gms.common.api.PendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.PendingResultFacade<any,any>>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class RegisterListenerMethod<A, L> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.RegisterListenerMethod<any,any>>; public registerListener(param0: A, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Void>): void; public getListenerKey(): com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<L>; public clearListener(): void; public constructor(param0: com.google.android.gms.common.api.internal.ListenerHolder<L>, param1: native.Array<com.google.android.gms.common.Feature>, param2: boolean); public constructor(param0: com.google.android.gms.common.api.internal.ListenerHolder<L>); public getRequiredFeatures(): native.Array<com.google.android.gms.common.Feature>; public shouldAutoResolveMissingFeatures(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class RegistrationMethods<A, L> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.RegistrationMethods<any,any>>; public zajz: com.google.android.gms.common.api.internal.RegisterListenerMethod<A,L>; public zaka: com.google.android.gms.common.api.internal.UnregisterListenerMethod<A,L>; public static builder(): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<any,any>; } export module RegistrationMethods { export class Builder<A, L> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.RegistrationMethods.Builder<any,any>>; public setAutoResolveMissingFeatures(param0: boolean): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; public withHolder(param0: com.google.android.gms.common.api.internal.ListenerHolder<L>): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; public unregister(param0: com.google.android.gms.common.api.internal.RemoteCall<A,com.google.android.gms.tasks.TaskCompletionSource<java.lang.Boolean>>): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; public register(param0: com.google.android.gms.common.util.BiConsumer<A,com.google.android.gms.tasks.TaskCompletionSource<java.lang.Void>>): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; public register(param0: com.google.android.gms.common.api.internal.RemoteCall<A,com.google.android.gms.tasks.TaskCompletionSource<java.lang.Void>>): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; public unregister(param0: com.google.android.gms.common.util.BiConsumer<A,com.google.android.gms.tasks.TaskCompletionSource<java.lang.Boolean>>): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; public build(): com.google.android.gms.common.api.internal.RegistrationMethods<A,L>; public setFeatures(param0: native.Array<com.google.android.gms.common.Feature>): com.google.android.gms.common.api.internal.RegistrationMethods.Builder<A,L>; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class RemoteCall<T, U> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.RemoteCall<any,any>>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.RemoteCall<any,any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { accept(param0: T, param1: U): void; }); public constructor(); public accept(param0: T, param1: U): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class SignInConnectionListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.SignInConnectionListener>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.SignInConnectionListener 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; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class StatusCallback extends com.google.android.gms.common.api.internal.IStatusCallback.Stub { public static class: java.lang.Class<com.google.android.gms.common.api.internal.StatusCallback>; public constructor(param0: com.google.android.gms.common.api.internal.BaseImplementation.ResultHolder<com.google.android.gms.common.api.Status>); public constructor(); public onResult(param0: com.google.android.gms.common.api.Status): void; public constructor(param0: string); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class StatusPendingResult extends com.google.android.gms.common.api.internal.BasePendingResult<com.google.android.gms.common.api.Status> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.StatusPendingResult>; public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public constructor(param0: globalAndroid.os.Looper); public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class TaskApiCall<A, ResultT> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.TaskApiCall<any,any>>; public zabt(): native.Array<com.google.android.gms.common.Feature>; public doExecute(param0: A, param1: com.google.android.gms.tasks.TaskCompletionSource<ResultT>): void; public constructor(); public shouldAutoResolveMissingFeatures(): boolean; public static builder(): com.google.android.gms.common.api.internal.TaskApiCall.Builder<any,any>; } export module TaskApiCall { export class Builder<A, ResultT> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.TaskApiCall.Builder<any,any>>; public setFeatures(param0: native.Array<com.google.android.gms.common.Feature>): com.google.android.gms.common.api.internal.TaskApiCall.Builder<A,ResultT>; public build(): com.google.android.gms.common.api.internal.TaskApiCall<A,ResultT>; public run(param0: com.google.android.gms.common.api.internal.RemoteCall<A,com.google.android.gms.tasks.TaskCompletionSource<ResultT>>): com.google.android.gms.common.api.internal.TaskApiCall.Builder<A,ResultT>; public execute(param0: com.google.android.gms.common.util.BiConsumer<A,com.google.android.gms.tasks.TaskCompletionSource<ResultT>>): com.google.android.gms.common.api.internal.TaskApiCall.Builder<A,ResultT>; public setAutoResolveMissingFeatures(param0: boolean): com.google.android.gms.common.api.internal.TaskApiCall.Builder<A,ResultT>; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class TaskUtil { public static class: java.lang.Class<com.google.android.gms.common.api.internal.TaskUtil>; public static setResultOrApiException(param0: com.google.android.gms.common.api.Status, param1: any, param2: com.google.android.gms.tasks.TaskCompletionSource): void; public static setResultOrApiException(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Void>): void; public constructor(); public static toVoidTaskThatFailsOnFalse(param0: com.google.android.gms.tasks.Task<java.lang.Boolean>): com.google.android.gms.tasks.Task<java.lang.Void>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class UnregisterListenerMethod<A, L> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.UnregisterListenerMethod<any,any>>; public getListenerKey(): com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<L>; public unregisterListener(param0: A, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Boolean>): void; public constructor(param0: com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<L>); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaa extends com.google.android.gms.common.api.internal.ActivityLifecycleObserver { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaa>; public onStopCallOnce(param0: java.lang.Runnable): com.google.android.gms.common.api.internal.ActivityLifecycleObserver; public constructor(param0: globalAndroid.app.Activity); public constructor(); } export module zaa { export class zaa { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaa.zaa>; public onStop(): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaaa extends com.google.android.gms.tasks.OnCompleteListener<java.util.Map<com.google.android.gms.common.api.internal.zai<any>,string>> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaaa>; public onComplete(param0: com.google.android.gms.tasks.Task<java.util.Map<com.google.android.gms.common.api.internal.zai<any>,string>>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaab { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaab>; public constructor(); public zaai(): void; public zaah(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaac extends com.google.android.gms.common.api.PendingResult.StatusListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaac>; public onComplete(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaad extends com.google.android.gms.tasks.OnCompleteListener<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaad>; public onComplete(param0: com.google.android.gms.tasks.Task<any>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaae extends com.google.android.gms.common.api.internal.zal { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaae>; public zao(): void; public static zaa(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.internal.GoogleApiManager, param2: com.google.android.gms.common.api.internal.zai<any>): void; public onResume(): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: number): void; public onStop(): void; public onStart(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaaf { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaaf>; public constructor(param0: com.google.android.gms.common.api.internal.zai<any>); public zaal(): com.google.android.gms.tasks.TaskCompletionSource<java.lang.Boolean>; public zak(): com.google.android.gms.common.api.internal.zai<any>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaag extends com.google.android.gms.common.api.GoogleApiClient { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaag>; public unregisterConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public clearDefaultAccountAndReconnect(): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public blockingConnect(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; public registerConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public blockingConnect(): com.google.android.gms.common.ConnectionResult; public constructor(); public connect(param0: number): void; public connect(): void; public registerConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public stopAutoManage(param0: globalAndroid.support.v4.app.FragmentActivity): void; public isConnected(): boolean; public isConnectionFailedListenerRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): boolean; public getConnectionResult(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; public reconnect(): void; public isConnectionCallbacksRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): boolean; public unregisterConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public hasConnectedApi(param0: com.google.android.gms.common.api.Api<any>): boolean; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public constructor(param0: string); public disconnect(): void; public isConnecting(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaah extends com.google.android.gms.common.api.internal.zabd { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaah>; public disconnect(): boolean; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; public enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public constructor(param0: com.google.android.gms.common.api.internal.zabe); public begin(): void; public onConnected(param0: globalAndroid.os.Bundle): void; public execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public connect(): void; public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaai extends com.google.android.gms.common.api.internal.zabf { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaai>; public zaan(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaaj extends com.google.android.gms.common.api.internal.zabf { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaaj>; public zaan(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaak extends com.google.android.gms.common.api.internal.zabd { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaak>; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; public disconnect(): boolean; public enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public begin(): void; public onConnected(param0: globalAndroid.os.Bundle): void; public execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public constructor(param0: com.google.android.gms.common.api.internal.zabe, param1: com.google.android.gms.common.internal.ClientSettings, param2: java.util.Map<com.google.android.gms.common.api.Api<any>,java.lang.Boolean>, param3: com.google.android.gms.common.GoogleApiAvailabilityLight, param4: com.google.android.gms.common.api.Api.AbstractClientBuilder<any,com.google.android.gms.signin.SignInOptions>, param5: java.util.concurrent.locks.Lock, param6: globalAndroid.content.Context); public connect(): void; public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaal { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaal>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaam { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaam>; public onReportServiceBinding(param0: com.google.android.gms.common.ConnectionResult): void; public constructor(param0: com.google.android.gms.common.api.internal.zaak, param1: com.google.android.gms.common.api.Api<any>, param2: boolean); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaan extends com.google.android.gms.common.api.internal.zaau { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaan>; public constructor(param0: java.util.Map<com.google.android.gms.common.api.Api.Client,com.google.android.gms.common.api.internal.zaam>); public zaan(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaao extends com.google.android.gms.common.api.internal.zabf { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaao>; public zaan(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaap extends com.google.android.gms.common.api.internal.zabf { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaap>; public zaan(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaaq extends com.google.android.gms.common.api.internal.zaau { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaaq>; public constructor(param0: java.util.ArrayList<com.google.android.gms.common.api.Api.Client>); public zaan(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaar extends com.google.android.gms.signin.internal.zac { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaar>; public zah(param0: com.google.android.gms.common.api.Status): void; public zag(param0: com.google.android.gms.common.api.Status): void; public zab(param0: com.google.android.gms.signin.internal.zaj): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.signin.internal.zaa): void; public zaa(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.signin.GoogleSignInAccount): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaas extends com.google.android.gms.common.api.internal.zabf { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaas>; public zaan(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaat implements com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaat>; public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; public onConnected(param0: globalAndroid.os.Bundle): void; public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class zaau { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaau>; public zaan(): void; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaav extends com.google.android.gms.common.api.internal.zabd { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaav>; public disconnect(): boolean; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; public enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public constructor(param0: com.google.android.gms.common.api.internal.zabe); public begin(): void; public onConnected(param0: globalAndroid.os.Bundle): void; public execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public connect(): void; public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaaw extends com.google.android.gms.common.api.GoogleApiClient implements com.google.android.gms.common.api.internal.zabt { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaaw>; public unregisterConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public constructor(param0: globalAndroid.content.Context, param1: java.util.concurrent.locks.Lock, param2: globalAndroid.os.Looper, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.GoogleApiAvailability, param5: com.google.android.gms.common.api.Api.AbstractClientBuilder<any,com.google.android.gms.signin.SignInOptions>, param6: java.util.Map<com.google.android.gms.common.api.Api<any>,java.lang.Boolean>, param7: java.util.List<com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks>, param8: java.util.List<com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener>, param9: java.util.Map<com.google.android.gms.common.api.Api.AnyClientKey<any>,com.google.android.gms.common.api.Api.Client>, param10: number, param11: number, param12: java.util.ArrayList<com.google.android.gms.common.api.internal.zaq>, param13: boolean); public blockingConnect(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; public getClient(param0: com.google.android.gms.common.api.Api.AnyClientKey<any>): com.google.android.gms.common.api.Api.Client; public zab(param0: globalAndroid.os.Bundle): void; public zab(param0: com.google.android.gms.common.api.internal.zacm<any>): void; public getContext(): globalAndroid.content.Context; public connect(param0: number): void; public zaa(param0: com.google.android.gms.common.api.internal.zacm<any>): void; public connect(): void; public static zaa(param0: java.lang.Iterable<com.google.android.gms.common.api.Api.Client>, param1: boolean): number; public stopAutoManage(param0: globalAndroid.support.v4.app.FragmentActivity): void; public isConnectionCallbacksRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): boolean; public unregisterConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public hasConnectedApi(param0: com.google.android.gms.common.api.Api<any>): boolean; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public clearDefaultAccountAndReconnect(): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; public enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public registerConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public blockingConnect(): com.google.android.gms.common.ConnectionResult; public constructor(); public maybeSignOut(): void; public registerConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public zab(param0: number, param1: boolean): void; public maybeSignIn(param0: com.google.android.gms.common.api.internal.SignInConnectionListener): boolean; public zac(param0: com.google.android.gms.common.ConnectionResult): void; public isConnected(): boolean; public isConnectionFailedListenerRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): boolean; public getConnectionResult(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; public reconnect(): void; public hasApi(param0: com.google.android.gms.common.api.Api<any>): boolean; public execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public disconnect(): void; public isConnecting(): boolean; public registerListener(param0: any): com.google.android.gms.common.api.internal.ListenerHolder<any>; public getLooper(): globalAndroid.os.Looper; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaax extends com.google.android.gms.common.internal.GmsClientEventManager.GmsClientEventState { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaax>; public getConnectionHint(): globalAndroid.os.Bundle; public isConnected(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaay extends com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaay>; public onConnected(param0: globalAndroid.os.Bundle): void; public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaaz extends com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaaz>; public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class zab { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zab>; public zaa(param0: com.google.android.gms.common.api.Status): void; public constructor(param0: number); public zaa(param0: java.lang.RuntimeException): void; public zaa(param0: com.google.android.gms.common.api.internal.zaab, param1: boolean): void; public zaa(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaba extends com.google.android.gms.common.api.ResultCallback<com.google.android.gms.common.api.Status> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaba>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabb extends com.google.android.gms.internal.base.zap { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabb>; public handleMessage(param0: globalAndroid.os.Message): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabc extends com.google.android.gms.common.api.internal.zabr { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabc>; public zas(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabd { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabd>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.zabd interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { begin(): void; enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; disconnect(): boolean; connect(): void; onConnected(param0: globalAndroid.os.Bundle): void; zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; onConnectionSuspended(param0: number): void; }); public constructor(); public disconnect(): boolean; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; public enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public begin(): void; public onConnected(param0: globalAndroid.os.Bundle): void; public execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public connect(): void; public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabe implements com.google.android.gms.common.api.internal.zabs, com.google.android.gms.common.api.internal.zar { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabe>; public enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public blockingConnect(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; public blockingConnect(): com.google.android.gms.common.ConnectionResult; public maybeSignOut(): void; public connect(): void; public maybeSignIn(param0: com.google.android.gms.common.api.internal.SignInConnectionListener): boolean; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; public isConnected(): boolean; public getConnectionResult(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.internal.zaaw, param2: java.util.concurrent.locks.Lock, param3: globalAndroid.os.Looper, param4: com.google.android.gms.common.GoogleApiAvailabilityLight, param5: java.util.Map<com.google.android.gms.common.api.Api.AnyClientKey<any>,com.google.android.gms.common.api.Api.Client>, param6: com.google.android.gms.common.internal.ClientSettings, param7: java.util.Map<com.google.android.gms.common.api.Api<any>,java.lang.Boolean>, param8: com.google.android.gms.common.api.Api.AbstractClientBuilder<any,com.google.android.gms.signin.SignInOptions>, param9: java.util.ArrayList<com.google.android.gms.common.api.internal.zaq>, param10: com.google.android.gms.common.api.internal.zabt); public onConnected(param0: globalAndroid.os.Bundle): void; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public disconnect(): void; public zaw(): void; public isConnecting(): boolean; public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class zabf { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabf>; public zaan(): void; public constructor(param0: com.google.android.gms.common.api.internal.zabd); public zac(param0: com.google.android.gms.common.api.internal.zabe): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabg extends com.google.android.gms.internal.base.zap { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabg>; public handleMessage(param0: globalAndroid.os.Message): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabh { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabh>; public static zabb(): java.util.concurrent.ExecutorService; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabi { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabi>; public onBackgroundStateChanged(param0: boolean): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabj { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabj>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabk { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabk>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabl { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabl>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabm { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabm>; public onSignOutComplete(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabn { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabn>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabo { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabo>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabp<O> extends com.google.android.gms.common.api.internal.zaag { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabp<any>>; public constructor(param0: com.google.android.gms.common.api.GoogleApi<any>); public enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public constructor(); public constructor(param0: string); public execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public zab(param0: com.google.android.gms.common.api.internal.zacm<any>): void; public getContext(): globalAndroid.content.Context; public zaa(param0: com.google.android.gms.common.api.internal.zacm<any>): void; public getLooper(): globalAndroid.os.Looper; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabq { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabq>; public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void; public constructor(param0: com.google.android.gms.common.api.internal.zabr); public zac(param0: globalAndroid.content.Context): void; public unregister(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class zabr { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabr>; public constructor(); public zas(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabs { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabs>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.zabs interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; connect(): void; blockingConnect(): com.google.android.gms.common.ConnectionResult; blockingConnect(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; disconnect(): void; getConnectionResult(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; isConnected(): boolean; isConnecting(): boolean; maybeSignIn(param0: com.google.android.gms.common.api.internal.SignInConnectionListener): boolean; maybeSignOut(): void; dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; zaw(): void; }); public constructor(); public enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public blockingConnect(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; public blockingConnect(): com.google.android.gms.common.ConnectionResult; public maybeSignOut(): void; public connect(): void; public maybeSignIn(param0: com.google.android.gms.common.api.internal.SignInConnectionListener): boolean; public isConnected(): boolean; public getConnectionResult(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public disconnect(): void; public zaw(): void; public isConnecting(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabt { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabt>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.zabt interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zab(param0: globalAndroid.os.Bundle): void; zac(param0: com.google.android.gms.common.ConnectionResult): void; zab(param0: number, param1: boolean): void; }); public constructor(); public zac(param0: com.google.android.gms.common.ConnectionResult): void; public zab(param0: globalAndroid.os.Bundle): void; public zab(param0: number, param1: boolean): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabu extends com.google.android.gms.common.api.internal.zal { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabu>; public zao(): void; public getTask(): com.google.android.gms.tasks.Task<java.lang.Void>; public onDestroy(): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: number): void; public static zac(param0: globalAndroid.app.Activity): com.google.android.gms.common.api.internal.zabu; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabv { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabv>; public zajr: com.google.android.gms.common.api.internal.zab; public zajs: number; public zajt: com.google.android.gms.common.api.GoogleApi<any>; public constructor(param0: com.google.android.gms.common.api.internal.zab, param1: number, param2: com.google.android.gms.common.api.GoogleApi<any>); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabw { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabw>; public zajx: com.google.android.gms.common.api.internal.RegisterListenerMethod<com.google.android.gms.common.api.Api.AnyClient,any>; public zajy: com.google.android.gms.common.api.internal.UnregisterListenerMethod<com.google.android.gms.common.api.Api.AnyClient,any>; public constructor(param0: com.google.android.gms.common.api.internal.RegisterListenerMethod<com.google.android.gms.common.api.Api.AnyClient,any>, param1: com.google.android.gms.common.api.internal.UnregisterListenerMethod<com.google.android.gms.common.api.Api.AnyClient,any>); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabx { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabx>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaby extends com.google.android.gms.common.api.internal.RemoteCall<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaby>; public accept(param0: any, param1: any): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zabz extends com.google.android.gms.common.api.internal.RemoteCall<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zabz>; public accept(param0: any, param1: any): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class zac extends com.google.android.gms.common.api.internal.zab { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zac>; public zac(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): boolean; public constructor(param0: number); public zab(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): native.Array<com.google.android.gms.common.Feature>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaca extends com.google.android.gms.common.api.internal.RegisterListenerMethod<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaca>; public registerListener(param0: any, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Void>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacb extends com.google.android.gms.common.api.internal.UnregisterListenerMethod<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacb>; public unregisterListener(param0: any, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Boolean>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacc { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacc>; public static zabb(): java.util.concurrent.ExecutorService; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacd<R> extends com.google.android.gms.common.api.PendingResult<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacd<any>>; public constructor(param0: com.google.android.gms.common.api.Status); public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>): void; public then(param0: com.google.android.gms.common.api.ResultTransform<any,any>): com.google.android.gms.common.api.TransformedResult<any>; public cancel(): void; public isCanceled(): boolean; public addStatusListener(param0: com.google.android.gms.common.api.PendingResult.StatusListener): void; public constructor(); public await(param0: number, param1: java.util.concurrent.TimeUnit): any; public setResultCallback(param0: com.google.android.gms.common.api.ResultCallback<any>, param1: number, param2: java.util.concurrent.TimeUnit): void; public await(): any; public zam(): java.lang.Integer; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zace extends com.google.android.gms.signin.internal.zac implements com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zace>; public zag(param0: com.google.android.gms.common.api.Status): void; public zaa(param0: com.google.android.gms.common.api.internal.zach): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: com.google.android.gms.common.internal.ClientSettings, param3: com.google.android.gms.common.api.Api.AbstractClientBuilder<any,com.google.android.gms.signin.SignInOptions>); public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.signin.internal.zaa): void; public zaa(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.signin.GoogleSignInAccount): void; public constructor(); public zabq(): com.google.android.gms.signin.zad; public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; public zabs(): void; public zah(param0: com.google.android.gms.common.api.Status): void; public onConnected(param0: globalAndroid.os.Bundle): void; public zab(param0: com.google.android.gms.signin.internal.zaj): void; public constructor(param0: string); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: com.google.android.gms.common.internal.ClientSettings); public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacf { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacf>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacg { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacg>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zach { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zach>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.zach interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zag(param0: com.google.android.gms.common.ConnectionResult): void; zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; }); public constructor(); public zag(param0: com.google.android.gms.common.ConnectionResult): void; public zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaci { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaci>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacj extends com.google.android.gms.common.api.internal.RemoteCall<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacj>; public accept(param0: any, param1: any): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zack extends com.google.android.gms.common.api.internal.TaskApiCall<any,any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zack>; public doExecute(param0: any, param1: com.google.android.gms.tasks.TaskCompletionSource<any>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacl extends com.google.android.gms.tasks.Continuation<java.lang.Boolean,java.lang.Void> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacl>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacm<R> extends com.google.android.gms.common.api.TransformedResult<any> implements com.google.android.gms.common.api.ResultCallback<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacm<any>>; public constructor(param0: java.lang.ref.WeakReference<com.google.android.gms.common.api.GoogleApiClient>); public then(param0: com.google.android.gms.common.api.ResultTransform<any,any>): com.google.android.gms.common.api.TransformedResult<any>; public zaa(param0: com.google.android.gms.common.api.PendingResult<any>): void; public constructor(); public onResult(param0: any): void; public andFinally(param0: com.google.android.gms.common.api.ResultCallbacks<any>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacn { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacn>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaco extends com.google.android.gms.internal.base.zap { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaco>; public constructor(param0: com.google.android.gms.common.api.internal.zacm<any>, param1: globalAndroid.os.Looper); public constructor(param0: globalAndroid.os.Looper, param1: globalAndroid.os.Handler.Callback); public handleMessage(param0: globalAndroid.os.Message): void; public constructor(); public constructor(param0: globalAndroid.os.Looper); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacp { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacp>; public static zakx: com.google.android.gms.common.api.Status; public constructor(param0: java.util.Map<com.google.android.gms.common.api.Api.AnyClientKey<any>,com.google.android.gms.common.api.Api.Client>); public release(): void; public zabx(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacq extends com.google.android.gms.common.api.internal.zacs { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacq>; public zac(param0: com.google.android.gms.common.api.internal.BasePendingResult<any>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacr extends com.google.android.gms.common.api.internal.zacs { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacr>; public binderDied(): void; public zac(param0: com.google.android.gms.common.api.internal.BasePendingResult<any>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zacs { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zacs>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.zacs interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zac(param0: com.google.android.gms.common.api.internal.BasePendingResult<any>): void; }); public constructor(); public zac(param0: com.google.android.gms.common.api.internal.BasePendingResult<any>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class zad<T> extends com.google.android.gms.common.api.internal.zac { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zad<any>>; public zacn: com.google.android.gms.tasks.TaskCompletionSource<any>; public constructor(param0: number, param1: com.google.android.gms.tasks.TaskCompletionSource<any>); public zaa(param0: com.google.android.gms.common.api.Status): void; public constructor(param0: number); public zaa(param0: java.lang.RuntimeException): void; public zaa(param0: com.google.android.gms.common.api.internal.zaab, param1: boolean): void; public zaa(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): void; public zad(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zae<A> extends com.google.android.gms.common.api.internal.zab { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zae<any>>; public zaa(param0: com.google.android.gms.common.api.Status): void; public constructor(param0: number); public zaa(param0: java.lang.RuntimeException): void; public zaa(param0: com.google.android.gms.common.api.internal.zaab, param1: boolean): void; public zaa(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): void; public constructor(param0: number, param1: any); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaf extends com.google.android.gms.common.api.internal.zad<java.lang.Void> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaf>; public constructor(param0: number, param1: com.google.android.gms.tasks.TaskCompletionSource<any>); public zac(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): boolean; public constructor(param0: number); public zad(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): void; public constructor(param0: com.google.android.gms.common.api.internal.zabw, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Void>); public zab(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): native.Array<com.google.android.gms.common.Feature>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zag<ResultT> extends com.google.android.gms.common.api.internal.zac { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zag<any>>; public zaa(param0: com.google.android.gms.common.api.Status): void; public zac(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): boolean; public constructor(param0: number); public constructor(param0: number, param1: com.google.android.gms.common.api.internal.TaskApiCall<com.google.android.gms.common.api.Api.AnyClient,any>, param2: com.google.android.gms.tasks.TaskCompletionSource<any>, param3: com.google.android.gms.common.api.internal.StatusExceptionMapper); public zaa(param0: java.lang.RuntimeException): void; public zaa(param0: com.google.android.gms.common.api.internal.zaab, param1: boolean): void; public zaa(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): void; public zab(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): native.Array<com.google.android.gms.common.Feature>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zah extends com.google.android.gms.common.api.internal.zad<java.lang.Boolean> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zah>; public constructor(param0: number, param1: com.google.android.gms.tasks.TaskCompletionSource<any>); public zac(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): boolean; public constructor(param0: number); public constructor(param0: com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey<any>, param1: com.google.android.gms.tasks.TaskCompletionSource<java.lang.Boolean>); public zad(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): void; public zab(param0: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): native.Array<com.google.android.gms.common.Feature>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zai<O> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zai<any>>; public equals(param0: any): boolean; public zan(): string; public static zaa(param0: com.google.android.gms.common.api.Api<any>, param1: com.google.android.gms.common.api.Api.ApiOptions): com.google.android.gms.common.api.internal.zai<any>; public static zaa(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.api.internal.zai<any>; public hashCode(): number; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaj extends com.google.android.gms.common.api.internal.zal { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaj>; public zao(): void; public static zaa(param0: com.google.android.gms.common.api.internal.LifecycleActivity): com.google.android.gms.common.api.internal.zaj; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public zaa(param0: number, param1: com.google.android.gms.common.api.GoogleApiClient, param2: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: number): void; public zaa(param0: number): void; public onStop(): void; public onStart(): void; } export module zaj { export class zaa extends com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaj.zaa>; public zacx: number; public zacy: com.google.android.gms.common.api.GoogleApiClient; public zacz: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; public constructor(param0: com.google.android.gms.common.api.internal.zaj, param1: number, param2: com.google.android.gms.common.api.GoogleApiClient, param3: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zak { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zak>; public constructor(param0: java.lang.Iterable<any>); public zap(): java.util.Set<com.google.android.gms.common.api.internal.zai<any>>; public getTask(): com.google.android.gms.tasks.Task<java.util.Map<com.google.android.gms.common.api.internal.zai<any>,string>>; public zaa(param0: com.google.android.gms.common.api.internal.zai<any>, param1: com.google.android.gms.common.ConnectionResult, param2: string): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export abstract class zal { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zal>; public mStarted: boolean; public zadf: java.util.concurrent.atomic.AtomicReference<com.google.android.gms.common.api.internal.zam>; public zacd: com.google.android.gms.common.GoogleApiAvailability; public zab(param0: com.google.android.gms.common.ConnectionResult, param1: number): void; public zao(): void; public onCreate(param0: globalAndroid.os.Bundle): void; public onCancel(param0: globalAndroid.content.DialogInterface): void; public zaq(): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: number): void; public onStop(): void; public constructor(param0: com.google.android.gms.common.api.internal.LifecycleFragment); public onSaveInstanceState(param0: globalAndroid.os.Bundle): void; public onStart(): void; public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zam { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zam>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zan { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zan>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zao extends com.google.android.gms.common.api.internal.zabr { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zao>; public zas(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zap extends java.lang.ThreadLocal<java.lang.Boolean> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zap>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaq implements com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaq>; public mApi: com.google.android.gms.common.api.Api<any>; public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; public onConnected(param0: globalAndroid.os.Bundle): void; public constructor(param0: com.google.android.gms.common.api.Api<any>, param1: boolean); public onConnectionSuspended(param0: number): void; public zaa(param0: com.google.android.gms.common.api.internal.zar): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zar extends com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zar>; /** * Constructs a new instance of the com.google.android.gms.common.api.internal.zar interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; onConnected(param0: globalAndroid.os.Bundle): void; onConnectionSuspended(param0: number): void; }); public constructor(); public static CAUSE_SERVICE_DISCONNECTED: number; public static CAUSE_NETWORK_LOST: number; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.common.api.Api<any>, param2: boolean): void; public onConnected(param0: globalAndroid.os.Bundle): void; public onConnectionSuspended(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zas extends com.google.android.gms.common.api.internal.zabs { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zas>; public enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public blockingConnect(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; public blockingConnect(): com.google.android.gms.common.ConnectionResult; public maybeSignOut(): void; public connect(): void; public maybeSignIn(param0: com.google.android.gms.common.api.internal.SignInConnectionListener): boolean; public isConnected(): boolean; public getConnectionResult(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public disconnect(): void; public zaw(): void; public static zaa(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.internal.zaaw, param2: java.util.concurrent.locks.Lock, param3: globalAndroid.os.Looper, param4: com.google.android.gms.common.GoogleApiAvailabilityLight, param5: java.util.Map<com.google.android.gms.common.api.Api.AnyClientKey<any>,com.google.android.gms.common.api.Api.Client>, param6: com.google.android.gms.common.internal.ClientSettings, param7: java.util.Map<com.google.android.gms.common.api.Api<any>,java.lang.Boolean>, param8: com.google.android.gms.common.api.Api.AbstractClientBuilder<any,com.google.android.gms.signin.SignInOptions>, param9: java.util.ArrayList<com.google.android.gms.common.api.internal.zaq>): com.google.android.gms.common.api.internal.zas; public isConnecting(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zat { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zat>; public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zau extends com.google.android.gms.common.api.internal.zabt { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zau>; public zac(param0: com.google.android.gms.common.ConnectionResult): void; public zab(param0: globalAndroid.os.Bundle): void; public zab(param0: number, param1: boolean): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zav extends com.google.android.gms.common.api.internal.zabt { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zav>; public zac(param0: com.google.android.gms.common.ConnectionResult): void; public zab(param0: globalAndroid.os.Bundle): void; public zab(param0: number, param1: boolean): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaw<O> extends com.google.android.gms.common.api.GoogleApi<any> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaw<any>>; public constructor(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.GoogleApi.Settings); public zaab(): com.google.android.gms.common.api.Api.Client; public zaa(param0: globalAndroid.os.Looper, param1: com.google.android.gms.common.api.internal.GoogleApiManager.zaa<any>): com.google.android.gms.common.api.Api.Client; public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: globalAndroid.os.Looper, param4: com.google.android.gms.common.api.internal.StatusExceptionMapper); public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: globalAndroid.os.Looper); public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.internal.StatusExceptionMapper); public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.GoogleApi.Settings); public constructor(param0: globalAndroid.app.Activity, param1: com.google.android.gms.common.api.Api<any>, param2: any, param3: com.google.android.gms.common.api.internal.StatusExceptionMapper); public zaa(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler): com.google.android.gms.common.api.internal.zace; public constructor(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api<any>, param2: globalAndroid.os.Looper, param3: com.google.android.gms.common.api.Api.Client, param4: com.google.android.gms.common.api.internal.zaq, param5: com.google.android.gms.common.internal.ClientSettings, param6: com.google.android.gms.common.api.Api.AbstractClientBuilder<any,com.google.android.gms.signin.SignInOptions>); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zax extends com.google.android.gms.common.api.internal.zabs { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zax>; public constructor(param0: globalAndroid.content.Context, param1: java.util.concurrent.locks.Lock, param2: globalAndroid.os.Looper, param3: com.google.android.gms.common.GoogleApiAvailabilityLight, param4: java.util.Map<com.google.android.gms.common.api.Api.AnyClientKey<any>,com.google.android.gms.common.api.Api.Client>, param5: com.google.android.gms.common.internal.ClientSettings, param6: java.util.Map<com.google.android.gms.common.api.Api<any>,java.lang.Boolean>, param7: com.google.android.gms.common.api.Api.AbstractClientBuilder<any,com.google.android.gms.signin.SignInOptions>, param8: java.util.ArrayList<com.google.android.gms.common.api.internal.zaq>, param9: com.google.android.gms.common.api.internal.zaaw, param10: boolean); public enqueue(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public blockingConnect(param0: number, param1: java.util.concurrent.TimeUnit): com.google.android.gms.common.ConnectionResult; public blockingConnect(): com.google.android.gms.common.ConnectionResult; public maybeSignOut(): void; public connect(): void; public maybeSignIn(param0: com.google.android.gms.common.api.internal.SignInConnectionListener): boolean; public isConnected(): boolean; public getConnectionResult(param0: com.google.android.gms.common.api.Api<any>): com.google.android.gms.common.ConnectionResult; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public execute(param0: com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>): com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,any>; public disconnect(): void; public zaw(): void; public isConnecting(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zay { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zay>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export module internal { export class zaz extends com.google.android.gms.tasks.OnCompleteListener<java.util.Map<com.google.android.gms.common.api.internal.zai<any>,string>> { public static class: java.lang.Class<com.google.android.gms.common.api.internal.zaz>; public onComplete(param0: com.google.android.gms.tasks.Task<java.util.Map<com.google.android.gms.common.api.internal.zai<any>,string>>): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class zaa extends com.google.android.gms.common.api.PendingResult.StatusListener { public static class: java.lang.Class<com.google.android.gms.common.api.zaa>; public onComplete(param0: com.google.android.gms.common.api.Status): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export class zab { public static class: java.lang.Class<com.google.android.gms.common.api.zab>; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module api { export abstract class zac { public static class: java.lang.Class<com.google.android.gms.common.api.zac>; public constructor(); public remove(param0: number): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export abstract class AbstractDataBuffer<T> extends com.google.android.gms.common.data.DataBuffer<any> { public static class: java.lang.Class<com.google.android.gms.common.data.AbstractDataBuffer<any>>; public mDataHolder: com.google.android.gms.common.data.DataHolder; public singleRefIterator(): java.util.Iterator<any>; public close(): void; public getMetadata(): globalAndroid.os.Bundle; public iterator(): java.util.Iterator<any>; public get(param0: number): any; public isClosed(): boolean; public release(): void; public constructor(param0: com.google.android.gms.common.data.DataHolder); public getCount(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class BitmapTeleporter { public static class: java.lang.Class<com.google.android.gms.common.data.BitmapTeleporter>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.data.BitmapTeleporter>; public constructor(param0: globalAndroid.graphics.Bitmap); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public release(): void; public setTempDir(param0: java.io.File): void; public get(): globalAndroid.graphics.Bitmap; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataBuffer<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.data.DataBuffer<any>>; /** * Constructs a new instance of the com.google.android.gms.common.data.DataBuffer<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getCount(): number; get(param0: number): T; getMetadata(): globalAndroid.os.Bundle; close(): void; isClosed(): boolean; iterator(): java.util.Iterator<T>; singleRefIterator(): java.util.Iterator<T>; release(): void; }); public constructor(); public get(param0: number): T; public getMetadata(): globalAndroid.os.Bundle; public close(): void; public isClosed(): boolean; public release(): void; public singleRefIterator(): java.util.Iterator<T>; public getCount(): number; public iterator(): java.util.Iterator<T>; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataBufferIterator<T> extends java.util.Iterator<any> { public static class: java.lang.Class<com.google.android.gms.common.data.DataBufferIterator<any>>; public zalk: com.google.android.gms.common.data.DataBuffer<any>; public zall: number; public constructor(param0: com.google.android.gms.common.data.DataBuffer<any>); public hasNext(): boolean; public remove(): void; public next(): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataBufferObserver { public static class: java.lang.Class<com.google.android.gms.common.data.DataBufferObserver>; /** * Constructs a new instance of the com.google.android.gms.common.data.DataBufferObserver interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onDataChanged(): void; onDataRangeChanged(param0: number, param1: number): void; onDataRangeInserted(param0: number, param1: number): void; onDataRangeRemoved(param0: number, param1: number): void; onDataRangeMoved(param0: number, param1: number, param2: number): void; }); public constructor(); public onDataRangeInserted(param0: number, param1: number): void; public onDataChanged(): void; public onDataRangeChanged(param0: number, param1: number): void; public onDataRangeRemoved(param0: number, param1: number): void; public onDataRangeMoved(param0: number, param1: number, param2: number): void; } export module DataBufferObserver { export class Observable { public static class: java.lang.Class<com.google.android.gms.common.data.DataBufferObserver.Observable>; /** * Constructs a new instance of the com.google.android.gms.common.data.DataBufferObserver$Observable interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { addObserver(param0: com.google.android.gms.common.data.DataBufferObserver): void; removeObserver(param0: com.google.android.gms.common.data.DataBufferObserver): void; }); public constructor(); public removeObserver(param0: com.google.android.gms.common.data.DataBufferObserver): void; public addObserver(param0: com.google.android.gms.common.data.DataBufferObserver): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataBufferObserverSet implements com.google.android.gms.common.data.DataBufferObserver, com.google.android.gms.common.data.DataBufferObserver.Observable { public static class: java.lang.Class<com.google.android.gms.common.data.DataBufferObserverSet>; public constructor(); public addObserver(param0: com.google.android.gms.common.data.DataBufferObserver): void; public removeObserver(param0: com.google.android.gms.common.data.DataBufferObserver): void; public hasObservers(): boolean; public onDataRangeInserted(param0: number, param1: number): void; public clear(): void; public onDataChanged(): void; public onDataRangeChanged(param0: number, param1: number): void; public onDataRangeRemoved(param0: number, param1: number): void; public onDataRangeMoved(param0: number, param1: number, param2: number): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataBufferRef { public static class: java.lang.Class<com.google.android.gms.common.data.DataBufferRef>; public mDataHolder: com.google.android.gms.common.data.DataHolder; public mDataRow: number; public getInteger(param0: string): number; public hasColumn(param0: string): boolean; public hashCode(): number; public getFloat(param0: string): number; public parseUri(param0: string): globalAndroid.net.Uri; public getByteArray(param0: string): native.Array<number>; public copyToBuffer(param0: string, param1: globalAndroid.database.CharArrayBuffer): void; public getDouble(param0: string): number; public hasNull(param0: string): boolean; public isDataValid(): boolean; public getLong(param0: string): number; public getString(param0: string): string; public zag(param0: number): void; public constructor(param0: com.google.android.gms.common.data.DataHolder, param1: number); public getDataRow(): number; public equals(param0: any): boolean; public getBoolean(param0: string): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataBufferSafeParcelable<T> extends com.google.android.gms.common.data.AbstractDataBuffer<any> { public static class: java.lang.Class<com.google.android.gms.common.data.DataBufferSafeParcelable<any>>; public singleRefIterator(): java.util.Iterator<any>; public constructor(param0: com.google.android.gms.common.data.DataHolder, param1: globalAndroid.os.Parcelable.Creator<any>); public getMetadata(): globalAndroid.os.Bundle; public close(): void; public iterator(): java.util.Iterator<any>; public get(param0: number): any; public static addValue(param0: com.google.android.gms.common.data.DataHolder.Builder, param1: com.google.android.gms.common.internal.safeparcel.SafeParcelable): void; public isClosed(): boolean; public release(): void; public constructor(param0: com.google.android.gms.common.data.DataHolder); public getCount(): number; public static buildDataHolder(): com.google.android.gms.common.data.DataHolder.Builder; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataBufferUtils { public static class: java.lang.Class<com.google.android.gms.common.data.DataBufferUtils>; public static KEY_NEXT_PAGE_TOKEN: string; public static KEY_PREV_PAGE_TOKEN: string; public static freezeAndClose(param0: com.google.android.gms.common.data.DataBuffer<any>): java.util.ArrayList; public static hasData(param0: com.google.android.gms.common.data.DataBuffer<any>): boolean; public static hasPrevPage(param0: com.google.android.gms.common.data.DataBuffer<any>): boolean; public static hasNextPage(param0: com.google.android.gms.common.data.DataBuffer<any>): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class DataHolder { public static class: java.lang.Class<com.google.android.gms.common.data.DataHolder>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.data.DataHolder>; public getString(param0: string, param1: number, param2: number): string; public close(): void; public static empty(param0: number): com.google.android.gms.common.data.DataHolder; public hasColumn(param0: string): boolean; public hasNull(param0: string, param1: number, param2: number): boolean; public constructor(param0: globalAndroid.database.Cursor, param1: number, param2: globalAndroid.os.Bundle); public finalize(): void; public zaca(): void; public getLong(param0: string, param1: number, param2: number): number; public isClosed(): boolean; public zab(param0: string, param1: number, param2: number): number; public getCount(): number; public zaa(param0: string, param1: number, param2: number, param3: globalAndroid.database.CharArrayBuffer): void; public constructor(param0: native.Array<string>, param1: native.Array<globalAndroid.database.CursorWindow>, param2: number, param3: globalAndroid.os.Bundle); public getStatusCode(): number; public getMetadata(): globalAndroid.os.Bundle; public getInteger(param0: string, param1: number, param2: number): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public static builder(param0: native.Array<string>): com.google.android.gms.common.data.DataHolder.Builder; public zaa(param0: string, param1: number, param2: number): number; public getBoolean(param0: string, param1: number, param2: number): boolean; public getByteArray(param0: string, param1: number, param2: number): native.Array<number>; public getWindowIndex(param0: number): number; } export module DataHolder { export class Builder { public static class: java.lang.Class<com.google.android.gms.common.data.DataHolder.Builder>; public build(param0: number, param1: globalAndroid.os.Bundle): com.google.android.gms.common.data.DataHolder; public zaa(param0: java.util.HashMap<string,any>): com.google.android.gms.common.data.DataHolder.Builder; public build(param0: number): com.google.android.gms.common.data.DataHolder; public withRow(param0: globalAndroid.content.ContentValues): com.google.android.gms.common.data.DataHolder.Builder; } export class zaa { public static class: java.lang.Class<com.google.android.gms.common.data.DataHolder.zaa>; public constructor(param0: string); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export abstract class EntityBuffer<T> extends com.google.android.gms.common.data.AbstractDataBuffer<any> { public static class: java.lang.Class<com.google.android.gms.common.data.EntityBuffer<any>>; public singleRefIterator(): java.util.Iterator<any>; public getMetadata(): globalAndroid.os.Bundle; public close(): void; public getChildDataMarkerColumn(): string; public iterator(): java.util.Iterator<any>; public getPrimaryDataMarkerColumn(): string; public get(param0: number): any; public isClosed(): boolean; public release(): void; public constructor(param0: com.google.android.gms.common.data.DataHolder); public getCount(): number; public getEntry(param0: number, param1: number): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class Freezable<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.data.Freezable<any>>; /** * Constructs a new instance of the com.google.android.gms.common.data.Freezable<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { freeze(): T; isDataValid(): boolean; }); public constructor(); public isDataValid(): boolean; public freeze(): T; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class FreezableUtils { public static class: java.lang.Class<com.google.android.gms.common.data.FreezableUtils>; public constructor(); public static freezeIterable(param0: java.lang.Iterable): java.util.ArrayList; public static freeze(param0: java.util.ArrayList): java.util.ArrayList; public static freeze(param0: native.Array<com.google.android.gms.common.data.Freezable<any>>): java.util.ArrayList; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class SingleRefDataBufferIterator<T> extends com.google.android.gms.common.data.DataBufferIterator<any> { public static class: java.lang.Class<com.google.android.gms.common.data.SingleRefDataBufferIterator<any>>; public constructor(param0: com.google.android.gms.common.data.DataBuffer<any>); public next(): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class zaa extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.data.BitmapTeleporter> { public static class: java.lang.Class<com.google.android.gms.common.data.zaa>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class zab extends com.google.android.gms.common.data.DataHolder.Builder { public static class: java.lang.Class<com.google.android.gms.common.data.zab>; public withRow(param0: globalAndroid.content.ContentValues): com.google.android.gms.common.data.DataHolder.Builder; public zaa(param0: java.util.HashMap<string,any>): com.google.android.gms.common.data.DataHolder.Builder; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module data { export class zac extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.data.DataHolder> { public static class: java.lang.Class<com.google.android.gms.common.data.zac>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export class ImageManager { public static class: java.lang.Class<com.google.android.gms.common.images.ImageManager>; public loadImage(param0: globalAndroid.widget.ImageView, param1: globalAndroid.net.Uri): void; public loadImage(param0: com.google.android.gms.common.images.ImageManager.OnImageLoadedListener, param1: globalAndroid.net.Uri, param2: number): void; public loadImage(param0: globalAndroid.widget.ImageView, param1: number): void; public loadImage(param0: com.google.android.gms.common.images.ImageManager.OnImageLoadedListener, param1: globalAndroid.net.Uri): void; public loadImage(param0: globalAndroid.widget.ImageView, param1: globalAndroid.net.Uri, param2: number): void; public static create(param0: globalAndroid.content.Context): com.google.android.gms.common.images.ImageManager; } export module ImageManager { export class ImageReceiver { public static class: java.lang.Class<com.google.android.gms.common.images.ImageManager.ImageReceiver>; public zace(): void; public zab(param0: com.google.android.gms.common.images.zaa): void; public zac(param0: com.google.android.gms.common.images.zaa): void; public onReceiveResult(param0: number, param1: globalAndroid.os.Bundle): void; } export class OnImageLoadedListener { public static class: java.lang.Class<com.google.android.gms.common.images.ImageManager.OnImageLoadedListener>; /** * Constructs a new instance of the com.google.android.gms.common.images.ImageManager$OnImageLoadedListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onImageLoaded(param0: globalAndroid.net.Uri, param1: globalAndroid.graphics.drawable.Drawable, param2: boolean): void; }); public constructor(); public onImageLoaded(param0: globalAndroid.net.Uri, param1: globalAndroid.graphics.drawable.Drawable, param2: boolean): void; } export class zaa extends globalAndroid.support.v4.util.LruCache<com.google.android.gms.common.images.zab,globalAndroid.graphics.Bitmap> { public static class: java.lang.Class<com.google.android.gms.common.images.ImageManager.zaa>; } export class zab { public static class: java.lang.Class<com.google.android.gms.common.images.ImageManager.zab>; public constructor(param0: com.google.android.gms.common.images.ImageManager, param1: globalAndroid.net.Uri, param2: globalAndroid.os.ParcelFileDescriptor); public run(): void; } export class zac { public static class: java.lang.Class<com.google.android.gms.common.images.ImageManager.zac>; public constructor(param0: com.google.android.gms.common.images.ImageManager, param1: com.google.android.gms.common.images.zaa); public run(): void; } export class zad { public static class: java.lang.Class<com.google.android.gms.common.images.ImageManager.zad>; public constructor(param0: com.google.android.gms.common.images.ImageManager, param1: globalAndroid.net.Uri, param2: globalAndroid.graphics.Bitmap, param3: boolean, param4: java.util.concurrent.CountDownLatch); public run(): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export class Size { public static class: java.lang.Class<com.google.android.gms.common.images.Size>; public getWidth(): number; public getHeight(): number; public constructor(param0: number, param1: number); public hashCode(): number; public toString(): string; public equals(param0: any): boolean; public static parseSize(param0: string): com.google.android.gms.common.images.Size; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export class WebImage { public static class: java.lang.Class<com.google.android.gms.common.images.WebImage>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.images.WebImage>; public getWidth(): number; public getHeight(): number; public constructor(param0: globalAndroid.net.Uri); public getUrl(): globalAndroid.net.Uri; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: globalAndroid.net.Uri, param1: number, param2: number); public constructor(param0: org.json.JSONObject); public hashCode(): number; public toJson(): org.json.JSONObject; public toString(): string; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export abstract class zaa { public static class: java.lang.Class<com.google.android.gms.common.images.zaa>; public zamx: number; public constructor(param0: globalAndroid.net.Uri, param1: number); public zaa(param0: globalAndroid.graphics.drawable.Drawable, param1: boolean, param2: boolean, param3: boolean): void; public zaa(param0: boolean, param1: boolean): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export class zab { public static class: java.lang.Class<com.google.android.gms.common.images.zab>; public uri: globalAndroid.net.Uri; public constructor(param0: globalAndroid.net.Uri); public hashCode(): number; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export class zac extends com.google.android.gms.common.images.zaa { public static class: java.lang.Class<com.google.android.gms.common.images.zac>; public constructor(param0: globalAndroid.widget.ImageView, param1: globalAndroid.net.Uri); public hashCode(): number; public constructor(param0: globalAndroid.net.Uri, param1: number); public zaa(param0: globalAndroid.graphics.drawable.Drawable, param1: boolean, param2: boolean, param3: boolean): void; public equals(param0: any): boolean; public zaa(param0: boolean, param1: boolean): boolean; public constructor(param0: globalAndroid.widget.ImageView, param1: number); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export class zad extends com.google.android.gms.common.images.zaa { public static class: java.lang.Class<com.google.android.gms.common.images.zad>; public hashCode(): number; public constructor(param0: globalAndroid.net.Uri, param1: number); public zaa(param0: globalAndroid.graphics.drawable.Drawable, param1: boolean, param2: boolean, param3: boolean): void; public equals(param0: any): boolean; public constructor(param0: com.google.android.gms.common.images.ImageManager.OnImageLoadedListener, param1: globalAndroid.net.Uri); public zaa(param0: boolean, param1: boolean): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module images { export class zae extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.images.WebImage> { public static class: java.lang.Class<com.google.android.gms.common.images.zae>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class ApiExceptionUtil { public static class: java.lang.Class<com.google.android.gms.common.internal.ApiExceptionUtil>; public constructor(); public static fromStatus(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.ApiException; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class AuthAccountRequest { public static class: java.lang.Class<com.google.android.gms.common.internal.AuthAccountRequest>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.AuthAccountRequest>; public constructor(param0: globalAndroid.accounts.Account, param1: java.util.Set<com.google.android.gms.common.api.Scope>); public constructor(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>); public setPolicyAction(param0: java.lang.Integer): com.google.android.gms.common.internal.AuthAccountRequest; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getScopes(): java.util.Set<com.google.android.gms.common.api.Scope>; public getAccount(): globalAndroid.accounts.Account; public setOauthPolicy(param0: java.lang.Integer): com.google.android.gms.common.internal.AuthAccountRequest; public getPolicyAction(): java.lang.Integer; public getOauthPolicy(): java.lang.Integer; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class ClientIdentity { public static class: java.lang.Class<com.google.android.gms.common.internal.ClientIdentity>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.ClientIdentity>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public hashCode(): number; public toString(): string; public equals(param0: any): boolean; public constructor(param0: number, param1: string); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class ClientSettings { public static class: java.lang.Class<com.google.android.gms.common.internal.ClientSettings>; public static KEY_CLIENT_SESSION_ID: string; public getClientSessionId(): java.lang.Integer; public getGravityForPopups(): number; public getRealClientPackageName(): string; public setClientSessionId(param0: java.lang.Integer): void; public constructor(param0: globalAndroid.accounts.Account, param1: java.util.Set<com.google.android.gms.common.api.Scope>, param2: java.util.Map<com.google.android.gms.common.api.Api<any>,com.google.android.gms.common.internal.ClientSettings.OptionalApiSettings>, param3: number, param4: globalAndroid.view.View, param5: string, param6: string, param7: com.google.android.gms.signin.SignInOptions, param8: boolean); public static createDefault(param0: globalAndroid.content.Context): com.google.android.gms.common.internal.ClientSettings; public getViewForPopups(): globalAndroid.view.View; public getOptionalApiSettings(): java.util.Map<com.google.android.gms.common.api.Api<any>,com.google.android.gms.common.internal.ClientSettings.OptionalApiSettings>; public isSignInClientDisconnectFixEnabled(): boolean; public getRequiredScopes(): java.util.Set<com.google.android.gms.common.api.Scope>; public getRealClientClassName(): string; public getAccountOrDefault(): globalAndroid.accounts.Account; public getApplicableScopes(param0: com.google.android.gms.common.api.Api<any>): java.util.Set<com.google.android.gms.common.api.Scope>; public getAccount(): globalAndroid.accounts.Account; public getAccountName(): string; public getAllRequestedScopes(): java.util.Set<com.google.android.gms.common.api.Scope>; public getSignInOptions(): com.google.android.gms.signin.SignInOptions; public constructor(param0: globalAndroid.accounts.Account, param1: java.util.Set<com.google.android.gms.common.api.Scope>, param2: java.util.Map<com.google.android.gms.common.api.Api<any>,com.google.android.gms.common.internal.ClientSettings.OptionalApiSettings>, param3: number, param4: globalAndroid.view.View, param5: string, param6: string, param7: com.google.android.gms.signin.SignInOptions); } export module ClientSettings { export class Builder { public static class: java.lang.Class<com.google.android.gms.common.internal.ClientSettings.Builder>; public setGravityForPopups(param0: number): com.google.android.gms.common.internal.ClientSettings.Builder; public setRealClientClassName(param0: string): com.google.android.gms.common.internal.ClientSettings.Builder; public setAccount(param0: globalAndroid.accounts.Account): com.google.android.gms.common.internal.ClientSettings.Builder; public setSignInOptions(param0: com.google.android.gms.signin.SignInOptions): com.google.android.gms.common.internal.ClientSettings.Builder; public enableSignInClientDisconnectFix(): com.google.android.gms.common.internal.ClientSettings.Builder; public build(): com.google.android.gms.common.internal.ClientSettings; public setViewForPopups(param0: globalAndroid.view.View): com.google.android.gms.common.internal.ClientSettings.Builder; public addAllRequiredScopes(param0: java.util.Collection<com.google.android.gms.common.api.Scope>): com.google.android.gms.common.internal.ClientSettings.Builder; public setOptionalApiSettingsMap(param0: java.util.Map<com.google.android.gms.common.api.Api<any>,com.google.android.gms.common.internal.ClientSettings.OptionalApiSettings>): com.google.android.gms.common.internal.ClientSettings.Builder; public addRequiredScope(param0: com.google.android.gms.common.api.Scope): com.google.android.gms.common.internal.ClientSettings.Builder; public constructor(); public setRealClientPackageName(param0: string): com.google.android.gms.common.internal.ClientSettings.Builder; } export class OptionalApiSettings { public static class: java.lang.Class<com.google.android.gms.common.internal.ClientSettings.OptionalApiSettings>; public mScopes: java.util.Set<com.google.android.gms.common.api.Scope>; public constructor(param0: java.util.Set<com.google.android.gms.common.api.Scope>); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class ConnectionErrorMessages { public static class: java.lang.Class<com.google.android.gms.common.internal.ConnectionErrorMessages>; public static getErrorMessage(param0: globalAndroid.content.Context, param1: number): string; public static getAppName(param0: globalAndroid.content.Context): string; public static getErrorTitle(param0: globalAndroid.content.Context, param1: number): string; public static getDefaultNotificationChannelName(param0: globalAndroid.content.Context): string; public static getErrorDialogButtonMessage(param0: globalAndroid.content.Context, param1: number): string; public static getErrorNotificationMessage(param0: globalAndroid.content.Context, param1: number): string; public static getErrorNotificationTitle(param0: globalAndroid.content.Context, param1: number): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export abstract class DialogRedirect { public static class: java.lang.Class<com.google.android.gms.common.internal.DialogRedirect>; public constructor(); public static getInstance(param0: globalAndroid.support.v4.app.Fragment, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.DialogRedirect; public redirect(): void; public static getInstance(param0: globalAndroid.app.Activity, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.DialogRedirect; public static getInstance(param0: com.google.android.gms.common.api.internal.LifecycleFragment, param1: globalAndroid.content.Intent, param2: number): com.google.android.gms.common.internal.DialogRedirect; public onClick(param0: globalAndroid.content.DialogInterface, param1: number): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export abstract class FallbackServiceBroker { public static class: java.lang.Class<com.google.android.gms.common.internal.FallbackServiceBroker>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export abstract class GmsClient<T> extends com.google.android.gms.common.internal.BaseGmsClient<any> { public static class: java.lang.Class<com.google.android.gms.common.internal.GmsClient<any>>; public requiresGooglePlayServices(): boolean; public getServiceBrokerBinder(): globalAndroid.os.IBinder; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public validateScopes(param0: java.util.Set<com.google.android.gms.common.api.Scope>): java.util.Set<com.google.android.gms.common.api.Scope>; public getAvailableFeatures(): native.Array<com.google.android.gms.common.Feature>; public getAccount(): globalAndroid.accounts.Account; public getClientSettings(): com.google.android.gms.common.internal.ClientSettings; public getEndpointPackageName(): string; public getSignInIntent(): globalAndroid.content.Intent; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public getConnectionHint(): globalAndroid.os.Bundle; public requiresAccount(): boolean; public getScopes(): java.util.Set<com.google.android.gms.common.api.Scope>; public disconnect(): void; public isConnected(): boolean; public providesSignIn(): boolean; public isConnecting(): boolean; public getMinApkVersion(): number; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.GmsClientSupervisor, param3: com.google.android.gms.common.GoogleApiAvailability, param4: number, param5: com.google.android.gms.common.internal.ClientSettings, param6: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param7: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: com.google.android.gms.common.internal.GmsClientSupervisor, param3: com.google.android.gms.common.GoogleApiAvailability, param4: number, param5: com.google.android.gms.common.internal.ClientSettings, param6: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param7: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public getRequiredFeatures(): native.Array<com.google.android.gms.common.Feature>; public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public requiresSignIn(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class GmsClientEventManager { public static class: java.lang.Class<com.google.android.gms.common.internal.GmsClientEventManager>; public isConnectionCallbacksRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): boolean; public isConnectionFailedListenerRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): boolean; public onUnintentionalDisconnection(param0: number): void; public registerConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public unregisterConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public disableCallbacks(): void; public registerConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public unregisterConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public onConnectionSuccess(): void; public onConnectionFailure(param0: com.google.android.gms.common.ConnectionResult): void; public handleMessage(param0: globalAndroid.os.Message): boolean; public constructor(param0: globalAndroid.os.Looper, param1: com.google.android.gms.common.internal.GmsClientEventManager.GmsClientEventState); public onConnectionSuccess(param0: globalAndroid.os.Bundle): void; public enableCallbacks(): void; public areCallbacksEnabled(): boolean; } export module GmsClientEventManager { export class GmsClientEventState { public static class: java.lang.Class<com.google.android.gms.common.internal.GmsClientEventManager.GmsClientEventState>; /** * Constructs a new instance of the com.google.android.gms.common.internal.GmsClientEventManager$GmsClientEventState interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { isConnected(): boolean; getConnectionHint(): globalAndroid.os.Bundle; }); public constructor(); public getConnectionHint(): globalAndroid.os.Bundle; public isConnected(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class GoogleApiAvailabilityCache { public static class: java.lang.Class<com.google.android.gms.common.internal.GoogleApiAvailabilityCache>; public constructor(); public getClientAvailability(param0: globalAndroid.content.Context, param1: com.google.android.gms.common.api.Api.Client): number; public constructor(param0: com.google.android.gms.common.GoogleApiAvailabilityLight); public flush(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class IResolveAccountCallbacks { public static class: java.lang.Class<com.google.android.gms.common.internal.IResolveAccountCallbacks>; /** * Constructs a new instance of the com.google.android.gms.common.internal.IResolveAccountCallbacks interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onAccountResolutionComplete(param0: com.google.android.gms.common.internal.ResolveAccountResponse): void; }); public constructor(); public onAccountResolutionComplete(param0: com.google.android.gms.common.internal.ResolveAccountResponse): void; } export module IResolveAccountCallbacks { export abstract class Stub extends com.google.android.gms.internal.base.zab implements com.google.android.gms.common.internal.IResolveAccountCallbacks { public static class: java.lang.Class<com.google.android.gms.common.internal.IResolveAccountCallbacks.Stub>; public static asInterface(param0: globalAndroid.os.IBinder): com.google.android.gms.common.internal.IResolveAccountCallbacks; public onAccountResolutionComplete(param0: com.google.android.gms.common.internal.ResolveAccountResponse): void; public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public constructor(); public constructor(param0: string); } export module Stub { export class Proxy extends com.google.android.gms.internal.base.zaa implements com.google.android.gms.common.internal.IResolveAccountCallbacks { public static class: java.lang.Class<com.google.android.gms.common.internal.IResolveAccountCallbacks.Stub.Proxy>; public onAccountResolutionComplete(param0: com.google.android.gms.common.internal.ResolveAccountResponse): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class ISignInButtonCreator { public static class: java.lang.Class<com.google.android.gms.common.internal.ISignInButtonCreator>; /** * Constructs a new instance of the com.google.android.gms.common.internal.ISignInButtonCreator interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { newSignInButton(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: number, param2: number): com.google.android.gms.dynamic.IObjectWrapper; newSignInButtonFromConfig(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: com.google.android.gms.common.internal.SignInButtonConfig): com.google.android.gms.dynamic.IObjectWrapper; }); public constructor(); public newSignInButtonFromConfig(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: com.google.android.gms.common.internal.SignInButtonConfig): com.google.android.gms.dynamic.IObjectWrapper; public newSignInButton(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: number, param2: number): com.google.android.gms.dynamic.IObjectWrapper; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export abstract class LegacyInternalGmsClient<T> extends com.google.android.gms.common.internal.GmsClient<any> { public static class: java.lang.Class<com.google.android.gms.common.internal.LegacyInternalGmsClient<any>>; public onConnectedLocked(param0: any): void; public isConnectionFailedListenerRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): boolean; public registerConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public unregisterConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public registerConnectionCallbacks(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): void; public requiresGooglePlayServices(): boolean; public getServiceBrokerBinder(): globalAndroid.os.IBinder; public onConnectionSuspended(param0: number): void; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public getAvailableFeatures(): native.Array<com.google.android.gms.common.Feature>; public getEndpointPackageName(): string; public getSignInIntent(): globalAndroid.content.Intent; public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public getConnectionHint(): globalAndroid.os.Bundle; public isConnectionCallbacksRegistered(param0: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks): boolean; public requiresAccount(): boolean; public checkAvailabilityAndConnect(): void; public disconnect(): void; public constructor(param0: globalAndroid.content.Context, param1: number, param2: com.google.android.gms.common.internal.ClientSettings, param3: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param4: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public isConnected(): boolean; public providesSignIn(): boolean; public unregisterConnectionFailedListener(param0: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener): void; public isConnecting(): boolean; public getMinApkVersion(): number; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.GmsClientSupervisor, param3: com.google.android.gms.common.GoogleApiAvailability, param4: number, param5: com.google.android.gms.common.internal.ClientSettings, param6: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param7: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: com.google.android.gms.common.internal.GmsClientSupervisor, param3: com.google.android.gms.common.GoogleApiAvailability, param4: number, param5: com.google.android.gms.common.internal.ClientSettings, param6: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param7: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public getRequiredFeatures(): native.Array<com.google.android.gms.common.Feature>; public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public requiresSignIn(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class PendingResultUtil { public static class: java.lang.Class<com.google.android.gms.common.internal.PendingResultUtil>; public constructor(); public static toVoidTask(param0: com.google.android.gms.common.api.PendingResult<any>): com.google.android.gms.tasks.Task; public static toTask(param0: com.google.android.gms.common.api.PendingResult<any>, param1: com.google.android.gms.common.internal.PendingResultUtil.ResultConverter<any,any>): com.google.android.gms.tasks.Task; public static toResponseTask(param0: com.google.android.gms.common.api.PendingResult<any>, param1: com.google.android.gms.common.api.Response): com.google.android.gms.tasks.Task; } export module PendingResultUtil { export class ResultConverter<R, T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.internal.PendingResultUtil.ResultConverter<any,any>>; /** * Constructs a new instance of the com.google.android.gms.common.internal.PendingResultUtil$ResultConverter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { convert(param0: R): T; }); public constructor(); public convert(param0: R): T; } export class zaa { public static class: java.lang.Class<com.google.android.gms.common.internal.PendingResultUtil.zaa>; /** * Constructs a new instance of the com.google.android.gms.common.internal.PendingResultUtil$zaa interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaf(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.ApiException; }); public constructor(); public zaf(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.ApiException; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class ResolveAccountRequest { public static class: java.lang.Class<com.google.android.gms.common.internal.ResolveAccountRequest>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.ResolveAccountRequest>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getAccount(): globalAndroid.accounts.Account; public getSessionId(): number; public constructor(param0: globalAndroid.accounts.Account, param1: number, param2: com.google.android.gms.auth.api.signin.GoogleSignInAccount); public getSignInAccountHint(): com.google.android.gms.auth.api.signin.GoogleSignInAccount; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class ResolveAccountResponse { public static class: java.lang.Class<com.google.android.gms.common.internal.ResolveAccountResponse>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.ResolveAccountResponse>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public setSaveDefaultAccount(param0: boolean): com.google.android.gms.common.internal.ResolveAccountResponse; public getSaveDefaultAccount(): boolean; public setIsFromCrossClientAuth(param0: boolean): com.google.android.gms.common.internal.ResolveAccountResponse; public getAccountAccessor(): com.google.android.gms.common.internal.IAccountAccessor; public setAccountAccessor(param0: com.google.android.gms.common.internal.IAccountAccessor): com.google.android.gms.common.internal.ResolveAccountResponse; public isFromCrossClientAuth(): boolean; public equals(param0: any): boolean; public constructor(param0: com.google.android.gms.common.ConnectionResult); public constructor(param0: number); public getConnectionResult(): com.google.android.gms.common.ConnectionResult; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class SignInButtonConfig { public static class: java.lang.Class<com.google.android.gms.common.internal.SignInButtonConfig>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.SignInButtonConfig>; public getScopes(): native.Array<com.google.android.gms.common.api.Scope>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getButtonSize(): number; public getColorScheme(): number; public constructor(param0: number, param1: number, param2: native.Array<com.google.android.gms.common.api.Scope>); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class SignInButtonCreator extends com.google.android.gms.dynamic.RemoteCreator<com.google.android.gms.common.internal.ISignInButtonCreator> { public static class: java.lang.Class<com.google.android.gms.common.internal.SignInButtonCreator>; public static createView(param0: globalAndroid.content.Context, param1: number, param2: number): globalAndroid.view.View; public getRemoteCreator(param0: globalAndroid.os.IBinder): com.google.android.gms.common.internal.ISignInButtonCreator; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class SignInButtonImpl { public static class: java.lang.Class<com.google.android.gms.common.internal.SignInButtonImpl>; public configure(param0: globalAndroid.content.res.Resources, param1: com.google.android.gms.common.internal.SignInButtonConfig): void; public configure(param0: globalAndroid.content.res.Resources, param1: number, param2: number): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet); public constructor(param0: globalAndroid.content.Context); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class SimpleClientAdapter<T> extends com.google.android.gms.common.internal.GmsClient<any> { public static class: java.lang.Class<com.google.android.gms.common.internal.SimpleClientAdapter<any>>; public getStartServiceAction(): string; public getClient(): com.google.android.gms.common.api.Api.SimpleClient<any>; public requiresGooglePlayServices(): boolean; public getServiceBrokerBinder(): globalAndroid.os.IBinder; public getServiceDescriptor(): string; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public getAvailableFeatures(): native.Array<com.google.android.gms.common.Feature>; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param4: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener, param5: com.google.android.gms.common.internal.ClientSettings, param6: com.google.android.gms.common.api.Api.SimpleClient<any>); public getEndpointPackageName(): string; public getSignInIntent(): globalAndroid.content.Intent; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public getConnectionHint(): globalAndroid.os.Bundle; public createServiceInterface(param0: globalAndroid.os.IBinder): any; public requiresAccount(): boolean; public disconnect(): void; public isConnected(): boolean; public providesSignIn(): boolean; public onSetConnectState(param0: number, param1: any): void; public isConnecting(): boolean; public getMinApkVersion(): number; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.GmsClientSupervisor, param3: com.google.android.gms.common.GoogleApiAvailability, param4: number, param5: com.google.android.gms.common.internal.ClientSettings, param6: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param7: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: com.google.android.gms.common.internal.GmsClientSupervisor, param3: com.google.android.gms.common.GoogleApiAvailability, param4: number, param5: com.google.android.gms.common.internal.ClientSettings, param6: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param7: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public getRequiredFeatures(): native.Array<com.google.android.gms.common.Feature>; public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public requiresSignIn(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class Common { public static class: java.lang.Class<com.google.android.gms.common.internal.service.Common>; public static CLIENT_KEY: com.google.android.gms.common.api.Api.ClientKey<com.google.android.gms.common.internal.service.zai>; public static API: com.google.android.gms.common.api.Api<com.google.android.gms.common.api.Api.ApiOptions.NoOptions>; public static zapi: com.google.android.gms.common.internal.service.zac; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zaa extends com.google.android.gms.common.internal.service.zak { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zaa>; public zaj(param0: number): void; public constructor(); public constructor(param0: string); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zab extends com.google.android.gms.common.api.Api.AbstractClientBuilder<com.google.android.gms.common.internal.service.zai,com.google.android.gms.common.api.Api.ApiOptions.NoOptions> { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zab>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zac { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zac>; /** * Constructs a new instance of the com.google.android.gms.common.internal.service.zac interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; }); public constructor(); public zaa(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zad extends com.google.android.gms.common.internal.service.zac { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zad>; public constructor(); public zaa(param0: com.google.android.gms.common.api.GoogleApiClient): com.google.android.gms.common.api.PendingResult<com.google.android.gms.common.api.Status>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zae extends com.google.android.gms.common.internal.service.zah { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zae>; public setResult(param0: any): void; public setFailedResult(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zaf extends com.google.android.gms.common.internal.service.zaa { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zaf>; public constructor(param0: com.google.android.gms.common.api.internal.BaseImplementation.ResultHolder<com.google.android.gms.common.api.Status>); public zaj(param0: number): void; public constructor(); public constructor(param0: string); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export abstract class zag<R> extends com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl<any,com.google.android.gms.common.internal.service.zai> { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zag<any>>; public constructor(param0: com.google.android.gms.common.api.Api.AnyClientKey<any>, param1: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.Api<any>, param1: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: globalAndroid.os.Looper); public constructor(); public setResult(param0: any): void; public setFailedResult(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export abstract class zah extends com.google.android.gms.common.internal.service.zag<com.google.android.gms.common.api.Status> { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zah>; public constructor(param0: com.google.android.gms.common.api.Api.AnyClientKey<any>, param1: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.Api<any>, param1: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.GoogleApiClient); public constructor(param0: com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler<any>); public constructor(param0: globalAndroid.os.Looper); public constructor(); public setResult(param0: any): void; public setFailedResult(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zai extends com.google.android.gms.common.internal.GmsClient<com.google.android.gms.common.internal.service.zal> { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zai>; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.ClientSettings, param3: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param4: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public getRequiredFeatures(): native.Array<com.google.android.gms.common.Feature>; public getServiceBrokerBinder(): globalAndroid.os.IBinder; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public getEndpointPackageName(): string; public requiresGooglePlayServices(): boolean; public requiresAccount(): boolean; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public getMinApkVersion(): number; public getAvailableFeatures(): native.Array<com.google.android.gms.common.Feature>; public getServiceDescriptor(): string; public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public getConnectionHint(): globalAndroid.os.Bundle; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.GmsClientSupervisor, param3: com.google.android.gms.common.GoogleApiAvailability, param4: number, param5: com.google.android.gms.common.internal.ClientSettings, param6: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param7: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public requiresSignIn(): boolean; public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public getSignInIntent(): globalAndroid.content.Intent; public isConnected(): boolean; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: com.google.android.gms.common.internal.GmsClientSupervisor, param3: com.google.android.gms.common.GoogleApiAvailability, param4: number, param5: com.google.android.gms.common.internal.ClientSettings, param6: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param7: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public getStartServiceAction(): string; public disconnect(): void; public isConnecting(): boolean; public providesSignIn(): boolean; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zaj { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zaj>; /** * Constructs a new instance of the com.google.android.gms.common.internal.service.zaj interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaj(param0: number): void; }); public constructor(); public zaj(param0: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export abstract class zak extends com.google.android.gms.internal.base.zab implements com.google.android.gms.common.internal.service.zaj { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zak>; public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public zaj(param0: number): void; public constructor(); public constructor(param0: string); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zal { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zal>; /** * Constructs a new instance of the com.google.android.gms.common.internal.service.zal interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.internal.service.zaj): void; }); public constructor(); public zaa(param0: com.google.android.gms.common.internal.service.zaj): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export module service { export class zam extends com.google.android.gms.internal.base.zaa implements com.google.android.gms.common.internal.service.zal { public static class: java.lang.Class<com.google.android.gms.common.internal.service.zam>; public zaa(): globalAndroid.os.Parcel; public zaa(param0: com.google.android.gms.common.internal.service.zaj): void; public zaa(param0: number, param1: globalAndroid.os.Parcel): globalAndroid.os.Parcel; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zaa extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.AuthAccountRequest> { public static class: java.lang.Class<com.google.android.gms.common.internal.zaa>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zab extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.ClientIdentity> { public static class: java.lang.Class<com.google.android.gms.common.internal.zab>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zac extends com.google.android.gms.common.internal.DialogRedirect { public static class: java.lang.Class<com.google.android.gms.common.internal.zac>; public redirect(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zad extends com.google.android.gms.common.internal.DialogRedirect { public static class: java.lang.Class<com.google.android.gms.common.internal.zad>; public redirect(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zae extends com.google.android.gms.common.internal.DialogRedirect { public static class: java.lang.Class<com.google.android.gms.common.internal.zae>; public redirect(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zaf { public static class: java.lang.Class<com.google.android.gms.common.internal.zaf>; public onConnected(param0: globalAndroid.os.Bundle): void; public onConnectionSuspended(param0: number): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zag { public static class: java.lang.Class<com.google.android.gms.common.internal.zag>; public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zah extends com.google.android.gms.internal.base.zaa implements com.google.android.gms.common.internal.ISignInButtonCreator { public static class: java.lang.Class<com.google.android.gms.common.internal.zah>; public newSignInButtonFromConfig(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: com.google.android.gms.common.internal.SignInButtonConfig): com.google.android.gms.dynamic.IObjectWrapper; public newSignInButton(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: number, param2: number): com.google.android.gms.dynamic.IObjectWrapper; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zai extends com.google.android.gms.common.internal.PendingResultUtil.zaa { public static class: java.lang.Class<com.google.android.gms.common.internal.zai>; public zaf(param0: com.google.android.gms.common.api.Status): com.google.android.gms.common.api.ApiException; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zaj extends com.google.android.gms.common.api.PendingResult.StatusListener { public static class: java.lang.Class<com.google.android.gms.common.internal.zaj>; public onComplete(param0: com.google.android.gms.common.api.Status): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zak extends com.google.android.gms.common.internal.PendingResultUtil.ResultConverter<any,any> { public static class: java.lang.Class<com.google.android.gms.common.internal.zak>; public convert(param0: any): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zal extends com.google.android.gms.common.internal.PendingResultUtil.ResultConverter<any,java.lang.Void> { public static class: java.lang.Class<com.google.android.gms.common.internal.zal>; public convert(param0: any): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zam extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.ResolveAccountRequest> { public static class: java.lang.Class<com.google.android.gms.common.internal.zam>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zan extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.ResolveAccountResponse> { public static class: java.lang.Class<com.google.android.gms.common.internal.zan>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module internal { export class zao extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.internal.SignInButtonConfig> { public static class: java.lang.Class<com.google.android.gms.common.internal.zao>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export class FavaDiagnosticsEntity { public static class: java.lang.Class<com.google.android.gms.common.server.FavaDiagnosticsEntity>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.FavaDiagnosticsEntity>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: number, param1: string, param2: number); public constructor(param0: string, param1: number); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module converter { export class StringToIntConverter extends com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable implements com.google.android.gms.common.server.response.FastJsonResponse.FieldConverter<string,java.lang.Integer> { public static class: java.lang.Class<com.google.android.gms.common.server.converter.StringToIntConverter>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.converter.StringToIntConverter>; public convert(param0: any): any; public zacj(): number; public zack(): number; public add(param0: string, param1: number): com.google.android.gms.common.server.converter.StringToIntConverter; public constructor(); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public convertBack(param0: any): any; } export module StringToIntConverter { export class zaa { public static class: java.lang.Class<com.google.android.gms.common.server.converter.StringToIntConverter.zaa>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.converter.StringToIntConverter.zaa>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module converter { export class zaa { public static class: java.lang.Class<com.google.android.gms.common.server.converter.zaa>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.converter.zaa>; public zaci(): com.google.android.gms.common.server.response.FastJsonResponse.FieldConverter<any,any>; public static zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.FieldConverter<any,any>): com.google.android.gms.common.server.converter.zaa; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module converter { export class zab extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.converter.zaa> { public static class: java.lang.Class<com.google.android.gms.common.server.converter.zab>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module converter { export class zac extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.converter.StringToIntConverter> { public static class: java.lang.Class<com.google.android.gms.common.server.converter.zac>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module converter { export class zad extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.converter.StringToIntConverter.zaa> { public static class: java.lang.Class<com.google.android.gms.common.server.converter.zad>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export abstract class FastJsonResponse { public static class: java.lang.Class<com.google.android.gms.common.server.response.FastJsonResponse>; public toString(): string; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.Map): void; public setIntegerInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: number): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Integer>): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.Map<string,string>): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.math.BigInteger): void; public zad(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Float>): void; public addConcreteTypeInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: com.google.android.gms.common.server.response.FastJsonResponse): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: number): void; public setStringsInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<string>): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.math.BigDecimal): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.math.BigDecimal): void; public zae(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public setLongInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: number): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zab(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public setDecodedBytesInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: native.Array<number>): void; public zad(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zac(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Long>): void; public zac(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zag(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Boolean>): void; public zag(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: native.Array<number>): void; public static zab(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: any): any; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: boolean): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.math.BigInteger): void; public zaf(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string): void; public zab(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.math.BigInteger>): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: number): void; public constructor(); public zah(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public getFieldMappings(): java.util.Map<string,com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>>; public zae(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Double>): void; public isPrimitiveFieldSet(param0: string): boolean; public addConcreteTypeArrayInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList): void; public isFieldSet(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>): boolean; public getValueObject(param0: string): any; public zaf(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.math.BigDecimal>): void; public setBooleanInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: boolean): void; public getFieldValue(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>): any; public setStringInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: string): void; } export module FastJsonResponse { export class Field<I, O> extends com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable { public static class: java.lang.Class<com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>>; public zapr: number; public zaps: boolean; public zapt: number; public zapu: boolean; public zapv: string; public zapw: number; public zapx: java.lang.Class<any>; public static CREATOR: com.google.android.gms.common.server.response.zai; public static forBase64(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<native.Array<number>,native.Array<number>>; public zacp(): com.google.android.gms.common.server.response.FastJsonResponse; public convertBack(param0: any): any; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public static forConcreteTypeArray(param0: string, param1: number, param2: java.lang.Class): com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>; public static forBoolean(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<java.lang.Boolean,java.lang.Boolean>; public toString(): string; public convert(param0: any): any; public static forLong(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<java.lang.Long,java.lang.Long>; public static forStrings(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<java.util.ArrayList<string>,java.util.ArrayList<string>>; public static forFloat(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<java.lang.Float,java.lang.Float>; public zacl(): com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>; public getSafeParcelableFieldId(): number; public static forString(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<string,string>; public static forDouble(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<java.lang.Double,java.lang.Double>; public zacq(): java.util.Map<string,com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>>; public zaa(param0: com.google.android.gms.common.server.response.zak): void; public static forConcreteType(param0: string, param1: number, param2: java.lang.Class): com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>; public static forInteger(param0: string, param1: number): com.google.android.gms.common.server.response.FastJsonResponse.Field<java.lang.Integer,java.lang.Integer>; public static withConverter(param0: string, param1: number, param2: com.google.android.gms.common.server.response.FastJsonResponse.FieldConverter<any,any>, param3: boolean): com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>; public zacn(): boolean; } export class FieldConverter<I, O> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.server.response.FastJsonResponse.FieldConverter<any,any>>; /** * Constructs a new instance of the com.google.android.gms.common.server.response.FastJsonResponse$FieldConverter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zacj(): number; zack(): number; convert(param0: I): O; convertBack(param0: O): I; }); public constructor(); public zack(): number; public convertBack(param0: O): I; public zacj(): number; public convert(param0: I): O; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class FastParser<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.server.response.FastParser<any>>; public constructor(); public parse(param0: java.io.InputStream, param1: T): void; } export module FastParser { export class ParseException { public static class: java.lang.Class<com.google.android.gms.common.server.response.FastParser.ParseException>; public constructor(param0: java.lang.Throwable); public constructor(param0: string); public constructor(param0: string, param1: java.lang.Throwable); } export class zaa<O> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.common.server.response.FastParser.zaa<any>>; /** * Constructs a new instance of the com.google.android.gms.common.server.response.FastParser$zaa interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zah(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): O; }); public constructor(); public zah(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): O; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export abstract class FastSafeParcelableJsonResponse extends com.google.android.gms.common.server.response.FastJsonResponse { public static class: java.lang.Class<com.google.android.gms.common.server.response.FastSafeParcelableJsonResponse>; public describeContents(): number; public isPrimitiveFieldSet(param0: string): boolean; public equals(param0: any): boolean; public toByteArray(): native.Array<number>; public getValueObject(param0: string): any; public constructor(); public hashCode(): number; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class SafeParcelResponse extends com.google.android.gms.common.server.response.FastSafeParcelableJsonResponse { public static class: java.lang.Class<com.google.android.gms.common.server.response.SafeParcelResponse>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.SafeParcelResponse>; public toString(): string; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.Map): void; public setIntegerInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: number): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Integer>): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.Map<string,string>): void; public static from(param0: com.google.android.gms.common.server.response.FastJsonResponse): com.google.android.gms.common.server.response.SafeParcelResponse; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.math.BigInteger): void; public zad(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Float>): void; public addConcreteTypeInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: com.google.android.gms.common.server.response.FastJsonResponse): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: number): void; public setStringsInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<string>): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.math.BigDecimal): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.math.BigDecimal): void; public zae(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public setLongInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: number): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zab(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public setDecodedBytesInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: native.Array<number>): void; public zac(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Long>): void; public zad(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zac(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zag(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Boolean>): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: native.Array<number>): void; public zag(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public static zab(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: any): any; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: boolean): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.math.BigInteger): void; public zaf(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: java.util.ArrayList): void; public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string): void; public zab(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.math.BigInteger>): void; public constructor(param0: com.google.android.gms.common.server.response.zak, param1: string); public zaa(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: number): void; public constructor(); public getFieldMappings(): java.util.Map<string,com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>>; public zae(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.lang.Double>): void; public isPrimitiveFieldSet(param0: string): boolean; public addConcreteTypeArrayInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList): void; public getValueObject(param0: string): any; public zaf(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: java.util.ArrayList<java.math.BigDecimal>): void; public setBooleanInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: boolean): void; public setStringInternal(param0: com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>, param1: string, param2: string): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zaa extends com.google.android.gms.common.server.response.FastParser.zaa<java.lang.Integer> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zaa>; public zah(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zab extends com.google.android.gms.common.server.response.FastParser.zaa<java.lang.Long> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zab>; public zah(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zac extends com.google.android.gms.common.server.response.FastParser.zaa<java.lang.Float> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zac>; public zah(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zad extends com.google.android.gms.common.server.response.FastParser.zaa<java.lang.Double> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zad>; public zah(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zae extends com.google.android.gms.common.server.response.FastParser.zaa<java.lang.Boolean> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zae>; public zah(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zaf extends com.google.android.gms.common.server.response.FastParser.zaa<string> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zaf>; public zah(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zag extends com.google.android.gms.common.server.response.FastParser.zaa<java.math.BigInteger> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zag>; public zah(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zah extends com.google.android.gms.common.server.response.FastParser.zaa<java.math.BigDecimal> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zah>; public zah(param0: com.google.android.gms.common.server.response.FastParser<any>, param1: java.io.BufferedReader): any; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zai extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zai>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zaj extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.zam> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zaj>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zak { public static class: java.lang.Class<com.google.android.gms.common.server.response.zak>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.zak>; public zaa(param0: java.lang.Class<any>): boolean; public toString(): string; public zai(param0: string): java.util.Map<string,com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>>; public zacs(): void; public zaa(param0: java.lang.Class<any>, param1: java.util.Map<string,com.google.android.gms.common.server.response.FastJsonResponse.Field<any,any>>): void; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public zacr(): void; public constructor(param0: java.lang.Class<any>); public zact(): string; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zal { public static class: java.lang.Class<com.google.android.gms.common.server.response.zal>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.zal>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zam { public static class: java.lang.Class<com.google.android.gms.common.server.response.zam>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.zam>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zan extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.zak> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zan>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zao extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.zal> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zao>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export module response { export class zap extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.response.SafeParcelResponse> { public static class: java.lang.Class<com.google.android.gms.common.server.response.zap>; public constructor(); } } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export module server { export class zaa extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.common.server.FavaDiagnosticsEntity> { public static class: java.lang.Class<com.google.android.gms.common.server.zaa>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module common { export class zaa extends com.google.android.gms.tasks.Continuation<java.util.Map<com.google.android.gms.common.api.internal.zai<any>,string>,java.lang.Void> { public static class: java.lang.Class<com.google.android.gms.common.zaa>; } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export abstract class DeferredLifecycleHelper<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.dynamic.DeferredLifecycleHelper<any>>; public constructor(); public onResume(): void; public createDelegate(param0: com.google.android.gms.dynamic.OnDelegateCreatedListener<T>): void; public handleGooglePlayUnavailable(param0: globalAndroid.widget.FrameLayout): void; public onStop(): void; public onLowMemory(): void; public onPause(): void; public onDestroyView(): void; public onDestroy(): void; public onInflate(param0: globalAndroid.app.Activity, param1: globalAndroid.os.Bundle, param2: globalAndroid.os.Bundle): void; public onCreate(param0: globalAndroid.os.Bundle): 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 static showGooglePlayUnavailableMessage(param0: globalAndroid.widget.FrameLayout): void; public onStart(): void; public getDelegate(): T; } export module DeferredLifecycleHelper { export class zaa { public static class: java.lang.Class<com.google.android.gms.dynamic.DeferredLifecycleHelper.zaa>; /** * Constructs a new instance of the com.google.android.gms.dynamic.DeferredLifecycleHelper$zaa interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getState(): number; zaa(param0: com.google.android.gms.dynamic.LifecycleDelegate): void; }); public constructor(); public zaa(param0: com.google.android.gms.dynamic.LifecycleDelegate): void; public getState(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export class zaa extends com.google.android.gms.dynamic.OnDelegateCreatedListener<any> { public static class: java.lang.Class<com.google.android.gms.dynamic.zaa>; public onDelegateCreated(param0: any): void; } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export class zab extends com.google.android.gms.dynamic.DeferredLifecycleHelper.zaa { public static class: java.lang.Class<com.google.android.gms.dynamic.zab>; public getState(): number; public zaa(param0: com.google.android.gms.dynamic.LifecycleDelegate): void; } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export class zac extends com.google.android.gms.dynamic.DeferredLifecycleHelper.zaa { public static class: java.lang.Class<com.google.android.gms.dynamic.zac>; public getState(): number; public zaa(param0: com.google.android.gms.dynamic.LifecycleDelegate): void; } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export class zad extends com.google.android.gms.dynamic.DeferredLifecycleHelper.zaa { public static class: java.lang.Class<com.google.android.gms.dynamic.zad>; public getState(): number; public zaa(param0: com.google.android.gms.dynamic.LifecycleDelegate): void; } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export class zae { public static class: java.lang.Class<com.google.android.gms.dynamic.zae>; public onClick(param0: globalAndroid.view.View): void; } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export class zaf extends com.google.android.gms.dynamic.DeferredLifecycleHelper.zaa { public static class: java.lang.Class<com.google.android.gms.dynamic.zaf>; public getState(): number; public zaa(param0: com.google.android.gms.dynamic.LifecycleDelegate): void; } } } } } } declare module com { export module google { export module android { export module gms { export module dynamic { export class zag extends com.google.android.gms.dynamic.DeferredLifecycleHelper.zaa { public static class: java.lang.Class<com.google.android.gms.dynamic.zag>; public getState(): number; public zaa(param0: com.google.android.gms.dynamic.LifecycleDelegate): void; } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zaa { public static class: java.lang.Class<com.google.android.gms.internal.base.zaa>; public constructor(param0: globalAndroid.os.IBinder, param1: string); public asBinder(): globalAndroid.os.IBinder; public zaa(param0: number, param1: globalAndroid.os.Parcel): globalAndroid.os.Parcel; public zac(param0: number, param1: globalAndroid.os.Parcel): void; public zaa(): globalAndroid.os.Parcel; public zab(param0: number, param1: globalAndroid.os.Parcel): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zab { public static class: java.lang.Class<com.google.android.gms.internal.base.zab>; public asBinder(): globalAndroid.os.IBinder; public constructor(param0: string); public onTransact(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zac { public static class: java.lang.Class<com.google.android.gms.internal.base.zac>; public static writeBoolean(param0: globalAndroid.os.Parcel, param1: boolean): void; public static zaa(param0: globalAndroid.os.Parcel, param1: globalAndroid.os.Parcelable.Creator): globalAndroid.os.Parcelable; public static zaa(param0: globalAndroid.os.Parcel, param1: globalAndroid.os.Parcelable): void; public static zaa(param0: globalAndroid.os.Parcel, param1: globalAndroid.os.IInterface): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zad { public static class: java.lang.Class<com.google.android.gms.internal.base.zad>; /** * Constructs a new instance of the com.google.android.gms.internal.base.zad interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zae { public static class: java.lang.Class<com.google.android.gms.internal.base.zae>; public invalidateDrawable(param0: globalAndroid.graphics.drawable.Drawable): void; public getConstantState(): globalAndroid.graphics.drawable.Drawable.ConstantState; public unscheduleDrawable(param0: globalAndroid.graphics.drawable.Drawable, param1: java.lang.Runnable): void; public startTransition(param0: number): void; public onBoundsChange(param0: globalAndroid.graphics.Rect): void; public draw(param0: globalAndroid.graphics.Canvas): void; public setColorFilter(param0: globalAndroid.graphics.ColorFilter): void; public getIntrinsicHeight(): number; public scheduleDrawable(param0: globalAndroid.graphics.drawable.Drawable, param1: java.lang.Runnable, param2: number): void; public getChangingConfigurations(): number; public mutate(): globalAndroid.graphics.drawable.Drawable; public setAlpha(param0: number): void; public zacf(): globalAndroid.graphics.drawable.Drawable; public constructor(param0: globalAndroid.graphics.drawable.Drawable, param1: globalAndroid.graphics.drawable.Drawable); public getIntrinsicWidth(): number; public getOpacity(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zaf { public static class: java.lang.Class<com.google.android.gms.internal.base.zaf>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zag { public static class: java.lang.Class<com.google.android.gms.internal.base.zag>; public setAlpha(param0: number): void; public getConstantState(): globalAndroid.graphics.drawable.Drawable.ConstantState; public draw(param0: globalAndroid.graphics.Canvas): void; public getOpacity(): number; public setColorFilter(param0: globalAndroid.graphics.ColorFilter): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zah { public static class: java.lang.Class<com.google.android.gms.internal.base.zah>; public newDrawable(): globalAndroid.graphics.drawable.Drawable; public getChangingConfigurations(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zai { public static class: java.lang.Class<com.google.android.gms.internal.base.zai>; public newDrawable(): globalAndroid.graphics.drawable.Drawable; public getChangingConfigurations(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zaj { public static class: java.lang.Class<com.google.android.gms.internal.base.zaj>; public onMeasure(param0: number, param1: number): void; public static zach(): number; public onDraw(param0: globalAndroid.graphics.Canvas): void; public static zaa(param0: globalAndroid.net.Uri): void; public static zai(param0: number): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zak extends globalAndroid.support.v4.util.LruCache<any,globalAndroid.graphics.drawable.Drawable> { public static class: java.lang.Class<com.google.android.gms.internal.base.zak>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zal { public static class: java.lang.Class<com.google.android.gms.internal.base.zal>; /** * Constructs a new instance of the com.google.android.gms.internal.base.zal interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: number, param1: java.util.concurrent.ThreadFactory, param2: number): java.util.concurrent.ExecutorService; }); public constructor(); public zaa(param0: number, param1: java.util.concurrent.ThreadFactory, param2: number): java.util.concurrent.ExecutorService; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zam { public static class: java.lang.Class<com.google.android.gms.internal.base.zam>; public static zacv(): com.google.android.gms.internal.base.zal; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zan { public static class: java.lang.Class<com.google.android.gms.internal.base.zan>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zao extends com.google.android.gms.internal.base.zal { public static class: java.lang.Class<com.google.android.gms.internal.base.zao>; public zaa(param0: number, param1: java.util.concurrent.ThreadFactory, param2: number): java.util.concurrent.ExecutorService; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zap { public static class: java.lang.Class<com.google.android.gms.internal.base.zap>; public constructor(); public constructor(param0: globalAndroid.os.Looper); public constructor(param0: globalAndroid.os.Looper, param1: globalAndroid.os.Handler.Callback); public dispatchMessage(param0: globalAndroid.os.Message): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module base { export class zaq { public static class: java.lang.Class<com.google.android.gms.internal.base.zaq>; /** * Constructs a new instance of the com.google.android.gms.internal.base.zaq interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export class SignInOptions extends com.google.android.gms.common.api.Api.ApiOptions.Optional { public static class: java.lang.Class<com.google.android.gms.signin.SignInOptions>; public static DEFAULT: com.google.android.gms.signin.SignInOptions; public isIdTokenRequested(): boolean; public waitForAccessTokenRefresh(): boolean; public getServerClientId(): string; public isForceCodeForRefreshToken(): boolean; public getHostedDomain(): string; public isOfflineAccessRequested(): boolean; public getAuthApiSignInModuleVersion(): java.lang.Long; public getRealClientLibraryVersion(): java.lang.Long; } export module SignInOptions { export class zaa { public static class: java.lang.Class<com.google.android.gms.signin.SignInOptions.zaa>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class SignInClientImpl extends com.google.android.gms.common.internal.GmsClient<com.google.android.gms.signin.internal.zaf> implements com.google.android.gms.signin.zad { public static class: java.lang.Class<com.google.android.gms.signin.internal.SignInClientImpl>; public getStartServiceAction(): string; public requiresGooglePlayServices(): boolean; public getServiceBrokerBinder(): globalAndroid.os.IBinder; public getServiceDescriptor(): string; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; public getAvailableFeatures(): native.Array<com.google.android.gms.common.Feature>; public connect(): void; public getEndpointPackageName(): string; public getSignInIntent(): globalAndroid.content.Intent; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public static createBundleFromClientSettings(param0: com.google.android.gms.common.internal.ClientSettings): globalAndroid.os.Bundle; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: number, param3: com.google.android.gms.common.internal.ClientSettings); public getConnectionHint(): globalAndroid.os.Bundle; public getGetServiceRequestExtraArgs(): globalAndroid.os.Bundle; public zacw(): void; public requiresAccount(): boolean; public disconnect(): void; public isConnected(): boolean; public providesSignIn(): boolean; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: boolean, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.signin.SignInOptions, param5: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param6: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public zaa(param0: com.google.android.gms.signin.internal.zad): void; public isConnecting(): boolean; public zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: boolean): void; public getMinApkVersion(): number; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: number, param3: com.google.android.gms.common.internal.ClientSettings, param4: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param5: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.GmsClientSupervisor, param3: com.google.android.gms.common.GoogleApiAvailability, param4: number, param5: com.google.android.gms.common.internal.ClientSettings, param6: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param7: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Handler, param2: com.google.android.gms.common.internal.GmsClientSupervisor, param3: com.google.android.gms.common.GoogleApiAvailability, param4: number, param5: com.google.android.gms.common.internal.ClientSettings, param6: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param7: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public getRequiredFeatures(): native.Array<com.google.android.gms.common.Feature>; public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public requiresSignIn(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zaa { public static class: java.lang.Class<com.google.android.gms.signin.internal.zaa>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.signin.internal.zaa>; public constructor(); public getStatus(): com.google.android.gms.common.api.Status; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zab extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.signin.internal.zaa> { public static class: java.lang.Class<com.google.android.gms.signin.internal.zab>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zac extends com.google.android.gms.signin.internal.zae { public static class: java.lang.Class<com.google.android.gms.signin.internal.zac>; public constructor(); public constructor(param0: string); public zah(param0: com.google.android.gms.common.api.Status): void; public zag(param0: com.google.android.gms.common.api.Status): void; public zab(param0: com.google.android.gms.signin.internal.zaj): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.signin.internal.zaa): void; public zaa(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.signin.GoogleSignInAccount): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zad { public static class: java.lang.Class<com.google.android.gms.signin.internal.zad>; /** * Constructs a new instance of the com.google.android.gms.signin.internal.zad interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.signin.internal.zaa): void; zag(param0: com.google.android.gms.common.api.Status): void; zah(param0: com.google.android.gms.common.api.Status): void; zaa(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.signin.GoogleSignInAccount): void; zab(param0: com.google.android.gms.signin.internal.zaj): void; }); public constructor(); public zah(param0: com.google.android.gms.common.api.Status): void; public zag(param0: com.google.android.gms.common.api.Status): void; public zab(param0: com.google.android.gms.signin.internal.zaj): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.signin.internal.zaa): void; public zaa(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.signin.GoogleSignInAccount): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export abstract class zae extends com.google.android.gms.internal.base.zab implements com.google.android.gms.signin.internal.zad { public static class: java.lang.Class<com.google.android.gms.signin.internal.zae>; public constructor(); public constructor(param0: string); public zah(param0: com.google.android.gms.common.api.Status): void; public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public zag(param0: com.google.android.gms.common.api.Status): void; public zab(param0: com.google.android.gms.signin.internal.zaj): void; public zaa(param0: com.google.android.gms.common.ConnectionResult, param1: com.google.android.gms.signin.internal.zaa): void; public zaa(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.auth.api.signin.GoogleSignInAccount): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zaf { public static class: java.lang.Class<com.google.android.gms.signin.internal.zaf>; /** * Constructs a new instance of the com.google.android.gms.signin.internal.zaf interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zam(param0: number): void; zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: number, param2: boolean): void; zaa(param0: com.google.android.gms.signin.internal.zah, param1: com.google.android.gms.signin.internal.zad): void; }); public constructor(); public zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: number, param2: boolean): void; public zaa(param0: com.google.android.gms.signin.internal.zah, param1: com.google.android.gms.signin.internal.zad): void; public zam(param0: number): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zag extends com.google.android.gms.internal.base.zaa implements com.google.android.gms.signin.internal.zaf { public static class: java.lang.Class<com.google.android.gms.signin.internal.zag>; public zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: number, param2: boolean): void; public zaa(param0: com.google.android.gms.signin.internal.zah, param1: com.google.android.gms.signin.internal.zad): void; public zaa(param0: number, param1: globalAndroid.os.Parcel): globalAndroid.os.Parcel; public zaa(): globalAndroid.os.Parcel; public zam(param0: number): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zah { public static class: java.lang.Class<com.google.android.gms.signin.internal.zah>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.signin.internal.zah>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: com.google.android.gms.common.internal.ResolveAccountRequest); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zai extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.signin.internal.zah> { public static class: java.lang.Class<com.google.android.gms.signin.internal.zai>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zaj { public static class: java.lang.Class<com.google.android.gms.signin.internal.zaj>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.signin.internal.zaj>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public zacx(): com.google.android.gms.common.internal.ResolveAccountResponse; public constructor(param0: number); public getConnectionResult(): com.google.android.gms.common.ConnectionResult; } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export module internal { export class zak extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.signin.internal.zaj> { public static class: java.lang.Class<com.google.android.gms.signin.internal.zak>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export class zaa { public static class: java.lang.Class<com.google.android.gms.signin.zaa>; public static zaph: com.google.android.gms.common.api.Api.AbstractClientBuilder<com.google.android.gms.signin.internal.SignInClientImpl,com.google.android.gms.signin.SignInOptions>; public static API: com.google.android.gms.common.api.Api<com.google.android.gms.signin.SignInOptions>; } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export class zab extends com.google.android.gms.common.api.Api.AbstractClientBuilder<com.google.android.gms.signin.internal.SignInClientImpl,com.google.android.gms.signin.SignInOptions> { public static class: java.lang.Class<com.google.android.gms.signin.zab>; } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export class zac extends com.google.android.gms.common.api.Api.AbstractClientBuilder<com.google.android.gms.signin.internal.SignInClientImpl,any> { public static class: java.lang.Class<com.google.android.gms.signin.zac>; } } } } } } declare module com { export module google { export module android { export module gms { export module signin { export class zad extends com.google.android.gms.common.api.Api.Client { public static class: java.lang.Class<com.google.android.gms.signin.zad>; /** * Constructs a new instance of the com.google.android.gms.signin.zad interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zaa(param0: com.google.android.gms.signin.internal.zad): void; zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: boolean): void; zacw(): void; connect(): void; connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; disconnect(): void; isConnected(): boolean; isConnecting(): boolean; getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; requiresSignIn(): boolean; onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; requiresAccount(): boolean; requiresGooglePlayServices(): boolean; providesSignIn(): boolean; getSignInIntent(): globalAndroid.content.Intent; dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; getServiceBrokerBinder(): globalAndroid.os.IBinder; getRequiredFeatures(): native.Array<com.google.android.gms.common.Feature>; getEndpointPackageName(): string; getMinApkVersion(): number; getAvailableFeatures(): native.Array<com.google.android.gms.common.Feature>; }); public constructor(); public requiresGooglePlayServices(): boolean; public requiresAccount(): boolean; public zaa(param0: com.google.android.gms.signin.internal.zad): void; public getServiceBrokerBinder(): globalAndroid.os.IBinder; public providesSignIn(): boolean; public isConnected(): boolean; public getEndpointPackageName(): string; public zaa(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: boolean): void; public connect(param0: com.google.android.gms.common.internal.BaseGmsClient.ConnectionProgressReportCallbacks): void; public connect(): void; public getMinApkVersion(): number; public isConnecting(): boolean; public getRemoteService(param0: com.google.android.gms.common.internal.IAccountAccessor, param1: java.util.Set<com.google.android.gms.common.api.Scope>): void; public getRequiredFeatures(): native.Array<com.google.android.gms.common.Feature>; public disconnect(): void; public zacw(): void; public onUserSignOut(param0: com.google.android.gms.common.internal.BaseGmsClient.SignOutCallbacks): void; public getSignInIntent(): globalAndroid.content.Intent; public getAvailableFeatures(): native.Array<com.google.android.gms.common.Feature>; public requiresSignIn(): boolean; public dump(param0: string, param1: java.io.FileDescriptor, param2: java.io.PrintWriter, param3: native.Array<string>): void; } } } } } } //Generics information: //com.google.android.gms.common.api.Api:1 //com.google.android.gms.common.api.Api.AbstractClientBuilder:2 //com.google.android.gms.common.api.Api.AnyClientKey:1 //com.google.android.gms.common.api.Api.BaseClientBuilder:2 //com.google.android.gms.common.api.Api.ClientKey:1 //com.google.android.gms.common.api.Api.SimpleClient:1 //com.google.android.gms.common.api.Api.zaa:2 //com.google.android.gms.common.api.Api.zab:1 //com.google.android.gms.common.api.BatchResultToken:1 //com.google.android.gms.common.api.DataBufferResponse:2 //com.google.android.gms.common.api.GoogleApi:1 //com.google.android.gms.common.api.OptionalPendingResult:1 //com.google.android.gms.common.api.PendingResult:1 //com.google.android.gms.common.api.PendingResults.zaa:1 //com.google.android.gms.common.api.PendingResults.zab:1 //com.google.android.gms.common.api.PendingResults.zac:1 //com.google.android.gms.common.api.ResultTransform:2 //com.google.android.gms.common.api.TransformedResult:1 //com.google.android.gms.common.api.internal.BaseImplementation.ApiMethodImpl:2 //com.google.android.gms.common.api.internal.BaseImplementation.ResultHolder:1 //com.google.android.gms.common.api.internal.BasePendingResult:1 //com.google.android.gms.common.api.internal.BasePendingResult.CallbackHandler:1 //com.google.android.gms.common.api.internal.DataHolderNotifier:1 //com.google.android.gms.common.api.internal.GoogleApiManager.zaa:1 //com.google.android.gms.common.api.internal.ListenerHolder:1 //com.google.android.gms.common.api.internal.ListenerHolder.ListenerKey:1 //com.google.android.gms.common.api.internal.ListenerHolder.Notifier:1 //com.google.android.gms.common.api.internal.OptionalPendingResultImpl:1 //com.google.android.gms.common.api.internal.PendingResultFacade:2 //com.google.android.gms.common.api.internal.RegisterListenerMethod:2 //com.google.android.gms.common.api.internal.RegistrationMethods:2 //com.google.android.gms.common.api.internal.RegistrationMethods.Builder:2 //com.google.android.gms.common.api.internal.RemoteCall:2 //com.google.android.gms.common.api.internal.TaskApiCall:2 //com.google.android.gms.common.api.internal.TaskApiCall.Builder:2 //com.google.android.gms.common.api.internal.UnregisterListenerMethod:2 //com.google.android.gms.common.api.internal.zabp:1 //com.google.android.gms.common.api.internal.zacd:1 //com.google.android.gms.common.api.internal.zacm:1 //com.google.android.gms.common.api.internal.zad:1 //com.google.android.gms.common.api.internal.zae:1 //com.google.android.gms.common.api.internal.zag:1 //com.google.android.gms.common.api.internal.zai:1 //com.google.android.gms.common.api.internal.zaw:1 //com.google.android.gms.common.data.AbstractDataBuffer:1 //com.google.android.gms.common.data.DataBuffer:1 //com.google.android.gms.common.data.DataBufferIterator:1 //com.google.android.gms.common.data.DataBufferSafeParcelable:1 //com.google.android.gms.common.data.EntityBuffer:1 //com.google.android.gms.common.data.Freezable:1 //com.google.android.gms.common.data.SingleRefDataBufferIterator:1 //com.google.android.gms.common.internal.GmsClient:1 //com.google.android.gms.common.internal.LegacyInternalGmsClient:1 //com.google.android.gms.common.internal.PendingResultUtil.ResultConverter:2 //com.google.android.gms.common.internal.SimpleClientAdapter:1 //com.google.android.gms.common.internal.service.zag:1 //com.google.android.gms.common.server.response.FastJsonResponse.Field:2 //com.google.android.gms.common.server.response.FastJsonResponse.FieldConverter:2 //com.google.android.gms.common.server.response.FastParser:1 //com.google.android.gms.common.server.response.FastParser.zaa:1 //com.google.android.gms.dynamic.DeferredLifecycleHelper:1
the_stack
import {ByRoleMatcher, Matcher, MatcherOptions} from './matches' import {SelectorMatcherOptions} from './query-helpers' import {waitForOptions} from './wait-for' export type QueryByBoundAttribute<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, id: Matcher, options?: MatcherOptions, ) => T | null export type AllByBoundAttribute<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, id: Matcher, options?: MatcherOptions, ) => T[] export type FindAllByBoundAttribute<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, id: Matcher, options?: MatcherOptions, waitForElementOptions?: waitForOptions, ) => Promise<T[]> export type GetByBoundAttribute<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, id: Matcher, options?: MatcherOptions, ) => T export type FindByBoundAttribute<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, id: Matcher, options?: MatcherOptions, waitForElementOptions?: waitForOptions, ) => Promise<T> export type QueryByText<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, id: Matcher, options?: SelectorMatcherOptions, ) => T | null export type AllByText<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, id: Matcher, options?: SelectorMatcherOptions, ) => T[] export type FindAllByText<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, id: Matcher, options?: SelectorMatcherOptions, waitForElementOptions?: waitForOptions, ) => Promise<T[]> export type GetByText<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, id: Matcher, options?: SelectorMatcherOptions, ) => T export type FindByText<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, id: Matcher, options?: SelectorMatcherOptions, waitForElementOptions?: waitForOptions, ) => Promise<T> export interface ByRoleOptions extends MatcherOptions { /** * If true includes elements in the query set that are usually excluded from * the accessibility tree. `role="none"` or `role="presentation"` are included * in either case. */ hidden?: boolean /** * If true only includes elements in the query set that are marked as * selected in the accessibility tree, i.e., `aria-selected="true"` */ selected?: boolean /** * If true only includes elements in the query set that are marked as * checked in the accessibility tree, i.e., `aria-checked="true"` */ checked?: boolean /** * If true only includes elements in the query set that are marked as * pressed in the accessibility tree, i.e., `aria-pressed="true"` */ pressed?: boolean /** * Filters elements by their `aria-current` state. `true` and `false` match `aria-current="true"` and `aria-current="false"` (as well as a missing `aria-current` attribute) respectively. */ current?: boolean | string /** * If true only includes elements in the query set that are marked as * expanded in the accessibility tree, i.e., `aria-expanded="true"` */ expanded?: boolean /** * Includes elements with the `"heading"` role matching the indicated level, * either by the semantic HTML heading elements `<h1>-<h6>` or matching * the `aria-level` attribute. */ level?: number /** * Includes every role used in the `role` attribute * For example *ByRole('progressbar', {queryFallbacks: true})` will find <div role="meter progressbar">`. */ queryFallbacks?: boolean /** * Only considers elements with the specified accessible name. */ name?: | RegExp | string | ((accessibleName: string, element: Element) => boolean) /** * Only considers elements with the specified accessible description. */ description?: | RegExp | string | ((accessibleDescription: string, element: Element) => boolean) } export type AllByRole<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, role: ByRoleMatcher, options?: ByRoleOptions, ) => T[] export type GetByRole<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, role: ByRoleMatcher, options?: ByRoleOptions, ) => T export type QueryByRole<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, role: ByRoleMatcher, options?: ByRoleOptions, ) => T | null export type FindByRole<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, role: ByRoleMatcher, options?: ByRoleOptions, waitForElementOptions?: waitForOptions, ) => Promise<T> export type FindAllByRole<T extends HTMLElement = HTMLElement> = ( container: HTMLElement, role: ByRoleMatcher, options?: ByRoleOptions, waitForElementOptions?: waitForOptions, ) => Promise<T[]> export function getByLabelText<T extends HTMLElement = HTMLElement>( ...args: Parameters<GetByText<T>> ): ReturnType<GetByText<T>> export function getAllByLabelText<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByText<T>> ): ReturnType<AllByText<T>> export function queryByLabelText<T extends HTMLElement = HTMLElement>( ...args: Parameters<QueryByText<T>> ): ReturnType<QueryByText<T>> export function queryAllByLabelText<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByText<T>> ): ReturnType<AllByText<T>> export function findByLabelText<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindByText<T>> ): ReturnType<FindByText<T>> export function findAllByLabelText<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindAllByText<T>> ): ReturnType<FindAllByText<T>> export function getByPlaceholderText<T extends HTMLElement = HTMLElement>( ...args: Parameters<GetByBoundAttribute<T>> ): ReturnType<GetByBoundAttribute<T>> export function getAllByPlaceholderText<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByBoundAttribute<T>> ): ReturnType<AllByBoundAttribute<T>> export function queryByPlaceholderText<T extends HTMLElement = HTMLElement>( ...args: Parameters<QueryByBoundAttribute<T>> ): ReturnType<QueryByBoundAttribute<T>> export function queryAllByPlaceholderText<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByBoundAttribute<T>> ): ReturnType<AllByBoundAttribute<T>> export function findByPlaceholderText<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindByBoundAttribute<T>> ): ReturnType<FindByBoundAttribute<T>> export function findAllByPlaceholderText<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindAllByBoundAttribute<T>> ): ReturnType<FindAllByBoundAttribute<T>> export function getByText<T extends HTMLElement = HTMLElement>( ...args: Parameters<GetByText<T>> ): ReturnType<GetByText<T>> export function getAllByText<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByText<T>> ): ReturnType<AllByText<T>> export function queryByText<T extends HTMLElement = HTMLElement>( ...args: Parameters<QueryByText<T>> ): ReturnType<QueryByText<T>> export function queryAllByText<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByText<T>> ): ReturnType<AllByText<T>> export function findByText<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindByText<T>> ): ReturnType<FindByText<T>> export function findAllByText<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindAllByText<T>> ): ReturnType<FindAllByText<T>> export function getByAltText<T extends HTMLElement = HTMLElement>( ...args: Parameters<GetByBoundAttribute<T>> ): ReturnType<GetByBoundAttribute<T>> export function getAllByAltText<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByBoundAttribute<T>> ): ReturnType<AllByBoundAttribute<T>> export function queryByAltText<T extends HTMLElement = HTMLElement>( ...args: Parameters<QueryByBoundAttribute<T>> ): ReturnType<QueryByBoundAttribute<T>> export function queryAllByAltText<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByBoundAttribute<T>> ): ReturnType<AllByBoundAttribute<T>> export function findByAltText<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindByBoundAttribute<T>> ): ReturnType<FindByBoundAttribute<T>> export function findAllByAltText<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindAllByBoundAttribute<T>> ): ReturnType<FindAllByBoundAttribute<T>> export function getByTitle<T extends HTMLElement = HTMLElement>( ...args: Parameters<GetByBoundAttribute<T>> ): ReturnType<GetByBoundAttribute<T>> export function getAllByTitle<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByBoundAttribute<T>> ): ReturnType<AllByBoundAttribute<T>> export function queryByTitle<T extends HTMLElement = HTMLElement>( ...args: Parameters<QueryByBoundAttribute<T>> ): ReturnType<QueryByBoundAttribute<T>> export function queryAllByTitle<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByBoundAttribute<T>> ): ReturnType<AllByBoundAttribute<T>> export function findByTitle<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindByBoundAttribute<T>> ): ReturnType<FindByBoundAttribute<T>> export function findAllByTitle<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindAllByBoundAttribute<T>> ): ReturnType<FindAllByBoundAttribute<T>> export function getByDisplayValue<T extends HTMLElement = HTMLElement>( ...args: Parameters<GetByBoundAttribute<T>> ): ReturnType<GetByBoundAttribute<T>> export function getAllByDisplayValue<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByBoundAttribute<T>> ): ReturnType<AllByBoundAttribute<T>> export function queryByDisplayValue<T extends HTMLElement = HTMLElement>( ...args: Parameters<QueryByBoundAttribute<T>> ): ReturnType<QueryByBoundAttribute<T>> export function queryAllByDisplayValue<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByBoundAttribute<T>> ): ReturnType<AllByBoundAttribute<T>> export function findByDisplayValue<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindByBoundAttribute<T>> ): ReturnType<FindByBoundAttribute<T>> export function findAllByDisplayValue<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindAllByBoundAttribute<T>> ): ReturnType<FindAllByBoundAttribute<T>> export function getByRole<T extends HTMLElement = HTMLElement>( ...args: Parameters<GetByRole<T>> ): ReturnType<GetByRole<T>> export function getAllByRole<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByRole<T>> ): ReturnType<AllByRole<T>> export function queryByRole<T extends HTMLElement = HTMLElement>( ...args: Parameters<QueryByRole<T>> ): ReturnType<QueryByRole<T>> export function queryAllByRole<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByRole<T>> ): ReturnType<AllByRole<T>> export function findByRole<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindByRole<T>> ): ReturnType<FindByRole<T>> export function findAllByRole<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindAllByRole<T>> ): ReturnType<FindAllByRole<T>> export function getByTestId<T extends HTMLElement = HTMLElement>( ...args: Parameters<GetByBoundAttribute<T>> ): ReturnType<GetByBoundAttribute<T>> export function getAllByTestId<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByBoundAttribute<T>> ): ReturnType<AllByBoundAttribute<T>> export function queryByTestId<T extends HTMLElement = HTMLElement>( ...args: Parameters<QueryByBoundAttribute<T>> ): ReturnType<QueryByBoundAttribute<T>> export function queryAllByTestId<T extends HTMLElement = HTMLElement>( ...args: Parameters<AllByBoundAttribute<T>> ): ReturnType<AllByBoundAttribute<T>> export function findByTestId<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindByBoundAttribute<T>> ): ReturnType<FindByBoundAttribute<T>> export function findAllByTestId<T extends HTMLElement = HTMLElement>( ...args: Parameters<FindAllByBoundAttribute<T>> ): ReturnType<FindAllByBoundAttribute<T>>
the_stack
import { stringify } from './util'; import { Type, FactoryProvider, StaticClassProvider, ValueProvider, ExistingProvider, ConstructorProvider, isValueProvider, StaticProvider, isExistingProvider, isStaticClassProvider, isFactoryProvider, InjectFlags, OptionFlags } from './type' import { InjectionToken } from './injection_token'; export const NG_TEMP_TOKEN_PATH = 'ngTempTokenPath'; export const SOURCE = '__source'; const NG_TOKEN_PATH = 'ngTokenPath'; const NEW_LINE = /\n/gm; const _THROW_IF_NOT_FOUND = new Object(); export const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND; const NO_NEW_LINE = 'ɵ'; const IDENT = function <T>(value: T): T { return value; }; const EMPTY = <any[]>[]; const CIRCULAR = IDENT; // record定义 export class Record { constructor( public fn: Function, public deps: DependencyRecord[] = [], public value: any = EMPTY ) { } } export interface DependencyRecord { token: any; options: number; } // 全局record记录map export const globalRecord: Map<any, Record | Record[]> = new Map(); // 设置全局record export function setRecord(token: any, record: Record | Record[] | undefined) { if (record) globalRecord.set(token, record) } export function setStaticProvider(provider: StaticProvider) { createStaticRecrod(provider, globalRecord) } // 从全局里获取 export function inject<T>(token: any, notFound?: T, flags: InjectFlags = InjectFlags.Default): T | T[] | undefined { const record = globalRecord.get(token); try { return tryResolveToken( token, record, globalRecord, ERROR_INJECTOR, notFound, flags, undefined ); } catch (e) { return catchInjectorError(e, token, 'StaticInjectorError', this.source); } } // 解析token,刨出错误 function tryResolveToken( token: any, record: Record | Record[] | undefined, records: Map<any, Record | Record[]>, parent: Injector, notFoundValue: any, flags: InjectFlags, current: Injector | undefined ): any { try { return resolveToken(token, record, records, parent, notFoundValue, flags, current); } catch (e) { // ensure that 'e' is of type Error. if (!(e instanceof Error)) { e = new Error(e); } const path: any[] = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || []; path.unshift(token); if (Array.isArray(record)) { record = record.map(rec => { if (rec && rec.value == CIRCULAR) { // Reset the Circular flag. rec.value = EMPTY; } return rec; }) } else { if (record && record.value == CIRCULAR) { // Reset the Circular flag. record.value = EMPTY; } } throw e; } } export function createFactoryProviderRecord(val: FactoryProvider): Record { return new Record((...params: any[]) => val.useFactory(...params), createDependencyRecord(val.deps), undefined); } export function createStaticClassProviderRecord(val: StaticClassProvider): Record { return new Record((...params: any[]) => new val.useClass(...params), createDependencyRecord(val.deps), undefined) } export function createValueProviderRecord(val: ValueProvider): Record { return new Record(() => val.useValue, [], undefined); } export function createExistingProviderRecord(val: ExistingProvider): Record { return new Record((injector: Injector) => { return injector.get(val.useExisting) }, createDeps([Injector]), undefined); } /** * deps: [ * [InjectFlags.Host,InjectFlags.Optional,ImsServices] * ImsServices, * [ImsServices] * ... * ] */ export function createDeps(deps: any[]): DependencyRecord[] { return deps.map((dep, index) => { // [InjectFlags.Host] if (Array.isArray(dep)) { let token, options = OptionFlags.Default; dep.map(opt => { if (typeof opt === 'number') { if (opt === InjectFlags.Self) { options = options & ~OptionFlags.CheckParent; } else if (opt === InjectFlags.Optional) { options = options | OptionFlags.Optional; } else if (opt === InjectFlags.SkipSelf) { options = options & ~OptionFlags.CheckSelf; } } else { token = opt; } }); return { token, options } } else { return { token: dep, options: OptionFlags.Default } } }) } /** * deps: [ * [InjectFlags.Host,InjectFlags.Optional,ImsServices] * ImsServices, * [ImsServices] * ... * ] */ export function createDependencyRecord(deps: any[] | undefined): DependencyRecord[] { if (deps && deps.length > 0) { return createDeps(deps) } return []; } export function createConstructorProvider(val: ConstructorProvider): Record { return new Record((...params: any[]) => { if (val.provide) { if (typeof val.provide === 'function') { return new val.provide(...params) } return val.provide; } return undefined; }, createDependencyRecord(val.deps), undefined) } export function createMultiRecord(res: Record | Record[] | undefined, newRecord: Record) { let records: Record[] = []; if (Array.isArray(res)) { records = [...res, newRecord] } else if (res) { records = [res, newRecord] } else { records = [newRecord] } return records; } export function createStaticRecrod(record: StaticProvider, records: Map<any, Record | Record[]>) { if (isValueProvider(record)) { if (!!record.multi) { return createMultiRecord(records.get(record.provide), createValueProviderRecord(record)); } else { return createValueProviderRecord(record) } } else if (isExistingProvider(record)) { if (!!record.multi) { return createMultiRecord(records.get(record.provide), createExistingProviderRecord(record)); } else { return createExistingProviderRecord(record) } } else if (isStaticClassProvider(record)) { if (!!record.multi) { return createMultiRecord(records.get(record.provide), createStaticClassProviderRecord(record)); } else { return createStaticClassProviderRecord(record) } } else if (isFactoryProvider(record)) { if (!!record.multi) { return createMultiRecord(records.get(record.provide), createFactoryProviderRecord(record)); } else { return createFactoryProviderRecord(record) } } else { if (!!record.multi) { return createMultiRecord(records.get(record.provide), createConstructorProvider(record)); } else { return createConstructorProvider(record) } } } export interface Abstract<T> extends Function { prototype: T; } export type ITokenString<T> = string & { target: T } export type ITokenAny<T> = (number | string | object | Function | Array<any>) & { target?: T; } export type IToken<T> = Type<T> | Abstract<T> | InjectionToken<T> | ITokenString<T> | ITokenAny<T>; export const topInjector = { get: inject } as Injector; export interface IInjector { get<T>(token: IToken<T>, notFound?: T, flags?: InjectFlags, ): T | T[] | undefined; } export class ErrorInjector implements IInjector { source = `ErrorInjector` get(token: any, notFoundValue: any = _THROW_IF_NOT_FOUND, flags: InjectFlags): any { // 如果是Optional if (notFoundValue === _THROW_IF_NOT_FOUND) { const error = new Error(`NullInjectorError: No provider for ${stringify(token)}`); error.name = 'NullInjectorError'; throw error; } return notFoundValue; } } // null export class NullInjector implements IInjector { source: string | null = 'NullInjector' get(token: any, notFoundValue: any = _THROW_IF_NOT_FOUND, flags: InjectFlags): any { // 如果是Optional const res = inject(token, notFoundValue, flags); if (res === _THROW_IF_NOT_FOUND) { const error = new Error(`NullInjectorError: No provider for ${stringify(token)}!`); error.name = 'NullInjectorError'; throw error; } return res; } } const NULL_INJECTOR = new NullInjector() as Injector; const ERROR_INJECTOR = new ErrorInjector() as Injector; export function catchInjectorError( e: any, token: any, injectorErrorName: string, source: string | null ): never { const tokenPath: any[] = e[NG_TEMP_TOKEN_PATH]; if (token[SOURCE]) { tokenPath.unshift(token[SOURCE]); } e.message = formatError('\n' + e.message, tokenPath, injectorErrorName, source); e[NG_TOKEN_PATH] = tokenPath; e[NG_TEMP_TOKEN_PATH] = null; throw e; } export class Injector implements IInjector { static THROW_IF_NOT_FOUND = THROW_IF_NOT_FOUND; static NULL: Injector = NULL_INJECTOR as Injector; _records: Map<any, Record | Record[]> = new Map(); exports: Map<any, Record | Record[]> = new Map(); parent: Injector; constructor( records: StaticProvider[], parent: Injector | null = null, public source: string | null = null ) { if (!parent) { parent = Injector.NULL as Injector; } this.parent = parent; this._records.set(Injector, new Record(() => this, [], undefined)); setRecord(Injector, new Record(() => this, [], undefined)); records.map(record => { // todo this._records.set(record.provide, createStaticRecrod(record, this._records)) }); } static create(options: { providers: StaticProvider[], parent?: Injector, name?: string }): Injector { return new Injector(options.providers, options.parent, options.name) } clearCache(token: any) { const record = this._records.get(token) if (Array.isArray(record)) { record.map(rec => rec.value = undefined) } else if (record) { record.value = undefined; } } create(records: StaticProvider[], source: string | null = null) { return new Injector(records, this, source) } setStatic(records: StaticProvider[]) { records.map(record => { const recs = createStaticRecrod(record, this._records); this._records.set(record.provide, recs); }); } debug() { this._records.forEach((item, key) => { if (Array.isArray(item)) { console.debug(`injector:multi:${this.source} ${key.name} registed ${item.length}`) } else { console.debug(`injector:${this.source} ${(key && key.name) || ''} registed, Dependeny: ${stringify(item.deps.map(dep => dep.token))}`) } }); } set(token: any, record: Record | Record[]) { this._records.set(token, record) } // 这个是替换 extend(injector: Injector) { injector._records.forEach((rec, key) => { let record = this._records.get(key) if (Array.isArray(record)) { if (Array.isArray(rec)) { record = [...record, ...rec] this._records.set(key, record) } else { record = [...record, rec] this._records.set(key, record) } } else if (record) { // 啥也不做 还是覆盖 // todo todo todo // this._records.set(key, record) } else { this._records.set(key, rec) } this._records.set(key, rec) }); } setParent(injector: Injector) { this.parent = injector; } get<T>(token: IToken<T>, notFound?: T | null, flags: InjectFlags = InjectFlags.Default): T { const record = this._records.get(token); try { return resolveToken( token, record, this._records, this.parent, notFound, flags, this ); } catch (e) { return catchInjectorError(e, token, `StaticInjectorError`, this.source); } } } function formatError( text: string, obj: any, injectorErrorName: string, source: string | null = null): string { text = text && text.charAt(0) === '\n' && text.charAt(1) == NO_NEW_LINE ? text.substr(2) : text; let context = stringify(obj); if (obj instanceof Array) { context = obj.map(stringify).join(' -> '); } else if (typeof obj === 'object') { let parts = <string[]>[]; for (let key in obj) { if (obj.hasOwnProperty(key)) { let value = obj[key]; parts.push( key + ':' + (typeof value === 'string' ? JSON.stringify(value) : stringify(value))); } } context = `{${parts.join(', ')}}`; } return `${injectorErrorName}${source ? '(' + source + ')' : ''}[${context}]: ${text.replace(NEW_LINE, '\n ')}`; } // 解析token export function resolveToken( token: any, record: Record | Record[] | undefined, records: Map<any, Record | Record[]>, parent: Injector, notFoundValue: any, flags: InjectFlags, current: Injector | undefined ) { let value; if (record && !(flags & InjectFlags.SkipSelf)) { // If we don't have a record, this implies that we don't own the provider hence don't know how // to resolve it. function handler(record: Record) { value = record.value; if (value == CIRCULAR) { throw Error(NO_NEW_LINE + 'Circular dependency'); } else if (value === EMPTY) { record.value = CIRCULAR; let fn = record.fn; let depRecords = record.deps; let deps = EMPTY; if (depRecords.length) { deps = []; for (let i = 0; i < depRecords.length; i++) { const depRecord: DependencyRecord = depRecords[i]; const options = depRecord.options; const childRecord = options & OptionFlags.CheckSelf ? records.get(depRecord.token) : undefined; deps.push(tryResolveToken( // Current Token to resolve depRecord.token, // A record which describes how to resolve the token. // If undefined, this means we don't have such a record childRecord, // Other records we know about. records, // If we don't know how to resolve dependency and we should not check parent for it, // than pass in Null injector. !childRecord && !(options & OptionFlags.CheckParent) ? ERROR_INJECTOR : parent, options & OptionFlags.Optional ? null : Injector.THROW_IF_NOT_FOUND, InjectFlags.Default, current )); } } value = fn(...deps); record.value = value; return value; } return value; } if (Array.isArray(record)) { value = record.map(rec => handler(rec)) } else { value = handler(record) } } else if (!(flags & InjectFlags.Self)) { value = parent.get(token, notFoundValue, InjectFlags.Default); } return value; }
the_stack
import { Representation } from "../../../manifest"; import selectOptimalRepresentation from "../select_optimal_representation"; describe("ABR - selectOptimalRepresentation", () => { const fakeReps = [ { bitrate : 100 }, { bitrate : 1000 }, { bitrate : 10000 }, { bitrate : 100000 }, ]; // eslint-disable-next-line max-len it("should return the best representation when the optimal bitrate given is Infinity and no higher limit exists", () => { expect(selectOptimalRepresentation(fakeReps as Representation[], Infinity, 0, Infinity)) .toBe(fakeReps[fakeReps.length - 1]); expect(selectOptimalRepresentation(fakeReps as Representation[], Infinity, 100, Infinity)) .toBe(fakeReps[fakeReps.length - 1]); expect(selectOptimalRepresentation(fakeReps as Representation[], Infinity, Infinity, Infinity)) .toBe(fakeReps[fakeReps.length - 1]); }); // eslint-disable-next-line max-len it("should return the best representation when both the optimal bitrate and the higher limit given are higher or equal than the highest Representation", () => { expect(selectOptimalRepresentation(fakeReps as Representation[], 100000, 0, 100000)) .toBe(fakeReps[fakeReps.length - 1]); expect(selectOptimalRepresentation(fakeReps as Representation[], 100000, 0, 900000)) .toBe(fakeReps[fakeReps.length - 1]); expect(selectOptimalRepresentation(fakeReps as Representation[], 900000, 0, 100000)) .toBe(fakeReps[fakeReps.length - 1]); expect(selectOptimalRepresentation(fakeReps as Representation[], 900000, 0, 900000)) .toBe(fakeReps[fakeReps.length - 1]); }); // eslint-disable-next-line max-len it("should return one below or equal to the maximum bitrate even if optimal is superior", () => { expect(selectOptimalRepresentation(fakeReps as Representation[], Infinity, 0, 999)) .toBe(fakeReps[0]); expect(selectOptimalRepresentation(fakeReps as Representation[], Infinity, 0, 100)) .toBe(fakeReps[0]); expect(selectOptimalRepresentation(fakeReps as Representation[], 1001, 0, 999)) .toBe(fakeReps[0]); expect(selectOptimalRepresentation(fakeReps as Representation[], 1001, 0, 1000)) .toBe(fakeReps[1]); expect(selectOptimalRepresentation(fakeReps as Representation[], Infinity, 0, 9999)) .toBe(fakeReps[1]); expect(selectOptimalRepresentation(fakeReps as Representation[], 1001, 0, 1000)) .toBe(fakeReps[1]); }); // eslint-disable-next-line max-len it("should chose the minimum if no Representation is below or equal to the maximum bitrate", () => { expect(selectOptimalRepresentation(fakeReps as Representation[], 1, 0, 0)) .toBe(fakeReps[0]); expect(selectOptimalRepresentation(fakeReps as Representation[], 101, 0, 0)) .toBe(fakeReps[0]); expect(selectOptimalRepresentation(fakeReps as Representation[], Infinity, 0, 0)) .toBe(fakeReps[0]); expect(selectOptimalRepresentation(fakeReps as Representation[], Infinity, 0, 99)) .toBe(fakeReps[0]); expect(selectOptimalRepresentation(fakeReps as Representation[], 0, 0, 99)) .toBe(fakeReps[0]); }); // eslint-disable-next-line max-len it("should return the worst representation when the optimal bitrate given is 0 and no lower limit exists", () => { expect(selectOptimalRepresentation(fakeReps as Representation[], 0, 0, Infinity)) .toBe(fakeReps[0]); expect(selectOptimalRepresentation(fakeReps as Representation[], 0, 0, 0)) .toBe(fakeReps[0]); expect(selectOptimalRepresentation(fakeReps as Representation[], 0, 0, 1000)) .toBe(fakeReps[0]); }); // eslint-disable-next-line max-len it("should return the worst representation when both the optimal bitrate and the lower limit given are lower or equal than the lowest Representation", () => { expect(selectOptimalRepresentation(fakeReps as Representation[], 4, 0, Infinity)) .toBe(fakeReps[0]); expect(selectOptimalRepresentation(fakeReps as Representation[], 100, 100, Infinity)) .toBe(fakeReps[0]); expect(selectOptimalRepresentation(fakeReps as Representation[], 0, 100, 100000)) .toBe(fakeReps[0]); expect(selectOptimalRepresentation(fakeReps as Representation[], 100, 0, 100000)) .toBe(fakeReps[0]); }); // eslint-disable-next-line max-len it("should return one higher or equal to the minimum bitrate even if optimal is inferior", () => { expect(selectOptimalRepresentation(fakeReps as Representation[], 0, 1000, Infinity)) .toBe(fakeReps[1]); expect(selectOptimalRepresentation(fakeReps as Representation[], 0, 1000, 1000)) .toBe(fakeReps[1]); expect(selectOptimalRepresentation(fakeReps as Representation[], 1000, 10000, Infinity)) .toBe(fakeReps[2]); }); // eslint-disable-next-line max-len it("should chose the maximum if no Representation is higher or equal to the minimum bitrate", () => { expect(selectOptimalRepresentation(fakeReps as Representation[], 0, 10000000, Infinity)) .toBe(fakeReps[fakeReps.length - 1]); expect(selectOptimalRepresentation(fakeReps as Representation[], 0, Infinity, Infinity)) .toBe(fakeReps[fakeReps.length - 1]); expect(selectOptimalRepresentation(fakeReps as Representation[], 100, Infinity, Infinity)) .toBe(fakeReps[fakeReps.length - 1]); }); // eslint-disable-next-line max-len it("should chose one respecting either the minimum or maximum when the minimum is higher than the maximum", () => { expect([fakeReps[0], fakeReps[fakeReps.length - 1]]) .toContain(selectOptimalRepresentation(fakeReps as Representation[], 1000, Infinity, 0)); expect([fakeReps[0], fakeReps[fakeReps.length - 1]]) .toContain(selectOptimalRepresentation(fakeReps as Representation[], 0, Infinity, 0)); expect([fakeReps[0], fakeReps[fakeReps.length - 1]]) .toContain(selectOptimalRepresentation(fakeReps as Representation[], Infinity, Infinity, 0)); expect([fakeReps[1], fakeReps[2]]) .toContain(selectOptimalRepresentation(fakeReps as Representation[], 1000, 10000, 1000)); expect([fakeReps[1], fakeReps[2]]) .toContain(selectOptimalRepresentation(fakeReps as Representation[], 10000, 10000, 1000)); }); });
the_stack
import { LogEntry } from '../../../definitions'; export type BranchGrapProps = { hideGraph: boolean; logEntries: LogEntry[]; itemHeight?: number; updateTick?: number; }; let branches: { hash: string; path: any; x?: number; wasFictional: boolean }[] = []; let branchColor = 0; const COLORS = [ '#ffab1d', '#fd8c25', '#f36e4a', '#fc6148', '#d75ab6', '#b25ade', '#6575ff', '#7b77e9', '#4ea8ec', '#00d0f5', '#4eb94e', '#51af23', '#8b9f1c', '#d0b02f', '#d0853a', '#a4a4a4', '#ffc51f', '#fe982c', '#fd7854', '#ff705f', '#e467c3', '#bd65e9', '#7183ff', '#8985f7', '#55b6ff', '#10dcff', '#51cd51', '#5cba2e', '#9eb22f', '#debe3d', '#e19344', '#b8b8b8', '#ffd03b', '#ffae38', '#ff8a6a', '#ff7e7e', '#ef72ce', '#c56df1', '#8091ff', '#918dff', '#69caff', '#3ee1ff', '#72da72', '#71cf43', '#abbf3c', '#e6c645', '#eda04e', '#c5c5c5', '#ffd84c', '#ffb946', '#ff987c', '#ff8f8f', '#fb7eda', '#ce76fa', '#90a0ff', '#9c98ff', '#74cbff', '#64e7ff', '#7ce47c', '#85e357', '#b8cc49', '#edcd4c', '#f9ad58', '#d0d0d0', '#ffe651', '#ffbf51', '#ffa48b', '#ff9d9e', '#ff8de1', '#d583ff', '#97a9ff', '#a7a4ff', '#82d3ff', '#76eaff', '#85ed85', '#8deb5f', '#c2d653', '#f5d862', '#fcb75c', '#d7d7d7', '#fff456', '#ffc66d', '#ffb39e', '#ffabad', '#ff9de5', '#da90ff', '#9fb2ff', '#b2afff', '#8ddaff', '#8bedff', '#99f299', '#97f569', '#cde153', '#fbe276', '#ffc160', '#e1e1e1', '#fff970', '#ffd587', '#ffc2b2', '#ffb9bd', '#ffa5e7', '#de9cff', '#afbeff', '#bbb8ff', '#9fd4ff', '#9aefff', '#b3f7b3', '#a0fe72', '#dbef6c', '#fcee98', '#ffca69', '#eaeaea', '#763700', '#9f241e', '#982c0e', '#a81300', '#80035f', '#650d90', '#082fca', '#3531a3', '#1d4892', '#006f84', '#036b03', '#236600', '#445200', '#544509', '#702408', '#343434', '#9a5000', '#b33a20', '#b02f0f', '#c8210a', '#950f74', '#7b23a7', '#263dd4', '#4642b4', '#1d5cac', '#00849c', '#0e760e', '#287800', '#495600', '#6c5809', '#8d3a13', '#4e4e4e', '#c36806', '#c85120', '#bf3624', '#df2512', '#aa2288', '#933bbf', '#444cde', '#5753c5', '#1d71c6', '#0099bf', '#188018', '#2e8c00', '#607100', '#907609', '#ab511f', '#686868', '#e47b07', '#e36920', '#d34e2a', '#ec3b24', '#ba3d99', '#9d45c9', '#4f5aec', '#615dcf', '#3286cf', '#00abca', '#279227', '#3a980c', '#6c7f00', '#ab8b0a', '#b56427', '#757575', '#ff911a', '#fc8120', '#e7623e', '#fa5236', '#ca4da9', '#a74fd3', '#5a68ff', '#6d69db', '#489bd9', '#00bcde', '#36a436', '#47a519', '#798d0a', '#c1a120', '#bf7730', '#8e8e8e', ]; type Point = { x: number; y: number }; /** * Plan is to create a Branch class, that will encapsulate: * - Branch color * - Branch information (nodes) * - SVG element (will draw the paths on the Svg) via the PathGenerator class. */ class PathGenerator { private previousPoint?: Point; private svgPath?: string; private points = 0; public get path() { return this.svgPath; } public addPoint(point: Point) { if (!this.previousPoint || !this.svgPath) { this.addFirstPoint(point); } else if (this.previousPoint.x !== point.x) { // If the x values are not the same, then lets curve the connection. this.connectToLineSmoothly(point); } else { this.connectToLine(point); } this.previousPoint = point; this.points += 1; } private addFirstPoint(point: Point) { this.svgPath = `M ${point.x} ${point.y} `; } /** * Join two lines using a cubic bezier curve. */ private connectToLineSmoothly(point: Point) { if (!this.previousPoint) { throw new Error('Previous point not available'); } if (this.points === 1 && point.x > this.previousPoint.x) { // Merge curves, see here https://github.com/DonJayamanne/gitHistoryVSCode/pull/463#issuecomment-590137053 const handle = Math.abs((point.x - this.previousPoint.x) / 2); const startPoint = `${this.previousPoint.x + handle} ${this.previousPoint.y}`; const controlPoint = `${point.x} ${this.previousPoint.y}`; const endPoint = `${point.x} ${point.y}`; this.svgPath += ` C ${startPoint}, ${controlPoint}, ${endPoint}`; } else { // Fork curves, see here https://github.com/DonJayamanne/gitHistoryVSCode/pull/463#issue-378655710 const handle = (point.y - this.previousPoint.y) / 2; const startPoint = `${this.previousPoint.x} ${this.previousPoint.y + handle}`; const controlPoint = `${point.x} ${point.y - handle}`; const endPoint = `${point.x} ${point.y}`; this.svgPath += ` C ${startPoint}, ${controlPoint}, ${endPoint}`; } } private connectToLine(point: Point) { this.svgPath += ` L ${point.x} ${point.y}`; } } // TODO: Think about appending (could be very expensive, but could be something worthwhile) // Appending could produce a better UX // Dunno, I think, cuz this way you can see where merges take place, rather than seeing a line vanish off export function drawGitGraph( svg: SVGSVGElement, content: HTMLElement, startAt: number, logEntryHeight = 60.8, entries: LogEntry[], hideGraph = false, ) { while (svg.children.length > 0) { svg.removeChild(svg.children[0]); } if (hideGraph) { for (let i = 0; i < content.children.length; i += 1) { const element = content.children[i]; element.setAttribute('style', element.getAttribute('style') + ';padding-left:0px'); } svg.style.display = 'none'; return; } if (startAt === 0) { branches = []; branchColor = 0; } svg.style.display = ''; const svgPaths = new Map<SVGElement, string>(); // Draw the graph const circleOffset = 0; const standardOffset = (0 + 0.5) * logEntryHeight; let currentY = (0 + 0.5) * logEntryHeight; const topMostY = (0 + 0.5) * logEntryHeight; let maxLeft = 0; let lastXOffset = 12; let maxXOffset = 12; if (startAt === 0) { branchColor = 0; } for (let i = 0; i < startAt; i++) { content.children[i].className = 'hidden'; } // Use this for new orphaned branches const circlesToAppend: SVGCircleElement[] = []; let fictionalBranches: { path: string; x?: number }[] = []; // let fictionalBranch2; let tabbedOnce = false; let fictionalBranchesUsed = false; let branched = false; for (let i = startAt; i < content.children.length; ++i) { if (i >= entries.length) { break; } const entry = entries[i]; const entryElement = content.children[i]; if (!entry) { break; } let index = 0; (entryElement as any).branchesOnLeft = branches.length; // Find branches to join let childCount = 0; const xOffset = 12; let removedBranches = 0; let branchFound = i === startAt ? true : false; let padParentCount = 0; for (let j = 0; j < branches.length; ) { const branch = branches[j]; if (branch.hash === entry.hash.full) { branchFound = true; if (childCount === 0) { // Replace the branch branch.path.setAttribute('d', branch.path.cmds + currentY); svgPaths.set(branch.path, branch.path.cmds + currentY); if (entry.parents.length === 0) { branches.splice(j, 1); branched = true; } else { branch.hash = entry.parents[0].full; } index = j; ++j; } else { // Join the branch const x = (index + 1) * xOffset; branch.path.setAttribute( 'd', branch.path.cmds + (currentY - logEntryHeight / 2) + ' L ' + x + ' ' + currentY, ); svgPaths.set( branch.path, branch.path.cmds + (currentY - logEntryHeight / 2) + ' L ' + x + ' ' + currentY, ); branches.splice(j, 1); branched = true; ++removedBranches; } ++childCount; } else { if (removedBranches !== 0) { const x = (j + 1) * xOffset; branch.path.setAttribute( 'd', branch.path.cmds + (currentY - logEntryHeight / 2) + ' L ' + x + ' ' + currentY, ); svgPaths.set( branch.path, branch.path.cmds + (currentY - logEntryHeight / 2) + ' L ' + x + ' ' + currentY, ); } ++j; } } // Add new branches let xFromFictionalBranch = 0; let j = 0; for (j = 0; j < entry.parents.length; ++j) { const parent = entry.parents[j]; const x = (index + j + 1) * xOffset; if (j !== 0 || branches.length === 0) { const svgPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); svgPaths.set(svgPath, ''); ++branchColor; if (branchColor === COLORS.length) { branchColor = 0; } svgPath.setAttribute('style', 'stroke:' + COLORS[branchColor]); const origX = (index + 1) * xOffset; let origY = currentY === standardOffset ? 0 : currentY; origY = currentY; if (entry.isLastCommit && !entry.isThisLastCommitMerged) { origY = currentY; } (svgPath as any).cmds = 'M ' + origX + ' ' + origY + ' L ' + x + ' ' + (currentY + logEntryHeight / 2) + ' L ' + x + ' '; svg.appendChild(svgPath); const obj = { hash: parent.full, path: svgPath, wasFictional: false, }; if (fictionalBranches.length === 0 || !fictionalBranchesUsed) { // Re-set the fictional branches if they haven't been used // In case we have a merge as the very first step, // Why? If we have a merge as the first step, then the fictional branch will have to move to the right // due to the second parent which will take another index if (!fictionalBranchesUsed) { fictionalBranches = []; } // Generate at least 10 fictional branches, so we can lay them out neatly for (let counter = 1; counter < 50; counter++) { const newOrigX = (index + 1 + counter) * xOffset; const fictionalBranch = 'M ' + newOrigX + ' ' + currentY + ' L ' + newOrigX + ' ' + topMostY + ' L ' + newOrigX + ' '; fictionalBranches.push({ path: fictionalBranch, x: newOrigX }); } } branchFound = true; branches.splice(index + j, 0, obj); } if (!branchFound && i > 0) { index = branches.length; const svgPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); svgPaths.set(svgPath, ''); ++branchColor; if (branchColor === COLORS.length) { branchColor = 0; } svgPath.setAttribute('style', 'stroke:' + COLORS[branchColor]); fictionalBranchesUsed = true; const fictionalBranch = fictionalBranches.splice(0, 1)[0]; if (entry.isLastCommit && !entry.isThisLastCommitMerged) { // Don't start from the very top, this is the last commit for this branch fictionalBranch.path = 'M ' + fictionalBranch.x + ' ' + currentY + ' L ' + fictionalBranch.x + ' ' + currentY + ' L ' + fictionalBranch.x + ' '; } if (fictionalBranch.x !== undefined) { xFromFictionalBranch = fictionalBranch.x; } (svgPath as any).cmds = fictionalBranch.path; svg.appendChild(svgPath); const obj = { hash: parent.full, path: svgPath, wasFictional: true, }; branches.splice(index + j, 0, obj); // We need to padd all parent log entries to take this into account padParentCount += 1; } // Incremental updates for debugging for (let i = 0; i < branches.length; ++i) { const branch = branches[i]; branch.path.setAttribute('d', branch.path.cmds + currentY); svgPaths.set(branch.path, branch.path.cmds + currentY); } } // What does this do? let tabBranch = false; for (j = index + j; j < branches.length; ++j) { tabBranch = true; const branch = branches[j]; const x = (j + 1) * xOffset; branch.path.cmds += currentY - logEntryHeight / 2 + ' L ' + x + ' ' + currentY + ' L ' + x + ' '; } tabBranch = tabBranch ? tabBranch : entry.parents.length > 1 || branched; if (tabBranch && fictionalBranches.length > 0) { for (let counter = 0; counter < fictionalBranches.length; counter++) { const x = (j + 1 + counter) * xOffset; const fictionalBranch = fictionalBranches[counter]; if (tabbedOnce) { fictionalBranch.path += currentY - logEntryHeight / 2 + ' L ' + x + ' ' + currentY + ' L ' + x + ' '; } else { if (currentY <= logEntryHeight) { fictionalBranch.path += currentY + ' L ' + x + ' ' + logEntryHeight + ' L ' + x + ' '; } else { fictionalBranch.path += currentY + ' L ' + x + ' ' + (currentY + logEntryHeight / 2) + ' L ' + x + ' '; } } fictionalBranch.x = x; } tabbedOnce = true; } const svgCircle = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); let cx = ((branchFound || i === 0 ? index : branches.length - 1) + 1) * xOffset; if (xFromFictionalBranch > 0) { cx = xFromFictionalBranch; } svgCircle.setAttribute('cx', cx.toString()); svgCircle.setAttribute('cy', (currentY + circleOffset).toString()); svgCircle.setAttribute('r', '4'); // Enabled only for debugging svg.appendChild(svgCircle); circlesToAppend.push(svgCircle); (entryElement as any).branchesOnLeft = Math.max((entryElement as any).branchesOnLeft, branches.length); maxLeft = Math.max(maxLeft, (entryElement as any).branchesOnLeft); currentY += logEntryHeight; lastXOffset = xOffset; if (maxXOffset < xOffset) { maxXOffset = xOffset; } if (padParentCount > 0) { for (let parentElemtnCounter = startAt; parentElemtnCounter <= i; parentElemtnCounter++) { if (parentElemtnCounter >= entries.length) { break; } const el = content.children[parentElemtnCounter]; (el as any).branchesOnLeft += padParentCount; } } } branches.forEach(branch => { const svgPath = branch.path.cmds + currentY; branch.path.setAttribute('d', svgPath); svgPaths.set(branch.path, svgPath); }); const lines: Point[][] = []; svgPaths.forEach((pathOrSvg, svg) => { try { const points = getPointsFromPath(pathOrSvg); lines.push(points); // Re-generate the paths with smooth curvy edges. const pathGenerator = new PathGenerator(); points.forEach(point => pathGenerator.addPoint(point)); svg.setAttribute('d', pathGenerator.path); } catch (ex) { console.error('Failed to generate SVG line path', ex); } }); // Sort all points in lines. lines.forEach((points, i) => { lines[i] = points.sort((a, b) => a.y - b.y); }); for (let i = startAt; i < content.children.length; ++i) { const element = content.children[i]; if (i >= entries.length) { break; } const minLeft = Math.min(maxLeft, 3); const left = element ? Math.max(minLeft, (element as any).branchesOnLeft) : minLeft; const originalStyle = element.getAttribute('style'); element.setAttribute('style', originalStyle + ';padding-left:' + (left + 1) * lastXOffset + 'px'); try { const pointsAtY = lines.map(points => getPointAtY((i + 1) * logEntryHeight, points)); const maxX = Math.max(...pointsAtY.map(p => p.x)); element.setAttribute('style', `${originalStyle};padding-left:${maxX + 12}px`); } catch (ex) { console.error('Failed to set padding of commit', ex); } } // calculate the height if (entries.length > 0 && !isNaN(logEntryHeight)) { svg.setAttribute('height', (entries.length * logEntryHeight).toString()); } } function getPointAtY(y: number, points: Point[]): Point { y = Math.floor(y); // if the first point has has greater y, then ignore. // I.e. if this branch/line starts after the required y, then ignore it. if (points.length === 0) { return { x: 0, y: 0 }; } if (points[0].y > y) { return { x: 0, y: 0 }; } // points = points.sort((a, b) => a.y - b.y); return points.reduce<Point>((previous, current) => { if (current.y === y) { return current; } if (current.y > y) { return previous; } return current; }, points[0]); } function getPointsFromPath(svgPath: string): Point[] { const points: Point[] = []; svgPath = svgPath.trim(); svgPath = svgPath.startsWith('M') ? svgPath.substring(1) : svgPath; svgPath .split('L') .map(item => item.trim()) .forEach(path => { const parts = path.split(' '); const x = parseInt(parts[0], 10); const y = parseInt(parts[1], 10); points.push({ x, y }); }); return points; }
the_stack
import _ from "lodash" import path from "path" import * as semver from "semver" import * as stringSimilarity from "string-similarity" import { version as gatsbyVersion } from "gatsby/package.json" import reporter from "gatsby-cli/lib/reporter" import { validateOptionsSchema, Joi } from "gatsby-plugin-utils" import { IPluginRefObject } from "gatsby-plugin-utils/dist/types" import { stripIndent } from "common-tags" import { trackCli } from "gatsby-telemetry" import { isWorker } from "gatsby-worker" import { resolveModuleExports } from "../resolve-module-exports" import { getLatestAPIs } from "../../utils/get-latest-apis" import { GatsbyNode, PackageJson } from "../../../" import { IPluginInfo, IFlattenedPlugin, IPluginInfoOptions, ISiteConfig, } from "./types" import { resolvePlugin } from "./load" interface IApi { version?: string } export interface IEntry { exportName: string pluginName: string pluginVersion: string api?: IApi } export type ExportType = "node" | "browser" | "ssr" type IEntryMap = { [exportType in ExportType]: Array<IEntry> } export type ICurrentAPIs = { [exportType in ExportType]: Array<string> } const getGatsbyUpgradeVersion = (entries: ReadonlyArray<IEntry>): string => entries.reduce((version, entry) => { if (entry.api && entry.api.version) { return semver.gt(entry.api.version, version || `0.0.0`) ? entry.api.version : version } return version }, ``) // Given a plugin object, an array of the API names it exports and an // array of valid API names, return an array of invalid API exports. function getBadExports( plugin: IPluginInfo, pluginAPIKeys: ReadonlyArray<string>, apis: ReadonlyArray<string> ): Array<IEntry> { let badExports: Array<IEntry> = [] // Discover any exports from plugins which are not "known" badExports = badExports.concat( _.difference(pluginAPIKeys, apis).map(e => { return { exportName: e, pluginName: plugin.name, pluginVersion: plugin.version, } }) ) return badExports } function getErrorContext( badExports: Array<IEntry>, exportType: ExportType, currentAPIs: ICurrentAPIs, latestAPIs: { [exportType in ExportType]: { [exportName: string]: IApi } } ): { errors: Array<string> entries: Array<IEntry> exportType: ExportType fixes: Array<string> sourceMessage: string } { const entries = badExports.map(ex => { return { ...ex, api: latestAPIs[exportType][ex.exportName], } }) const gatsbyUpgradeVersion = getGatsbyUpgradeVersion(entries) const errors: Array<string> = [] const fixes = gatsbyUpgradeVersion ? [`npm install gatsby@^${gatsbyUpgradeVersion}`] : [] entries.forEach(entry => { const similarities = stringSimilarity.findBestMatch( entry.exportName, currentAPIs[exportType] ) const isDefaultPlugin = entry.pluginName == `default-site-plugin` const message = entry.api ? entry.api.version ? `was introduced in gatsby@${entry.api.version}` : `is not available in your version of Gatsby` : `is not a known API` if (isDefaultPlugin) { errors.push( `- Your local gatsby-${exportType}.js is using the API "${entry.exportName}" which ${message}.` ) } else { errors.push( `- The plugin ${entry.pluginName}@${entry.pluginVersion} is using the API "${entry.exportName}" which ${message}.` ) } if (similarities.bestMatch.rating > 0.5) { fixes.push( `Rename "${entry.exportName}" -> "${similarities.bestMatch.target}"` ) } }) return { errors, entries, exportType, fixes, // note: this is a fallback if gatsby-cli is not updated with structured error sourceMessage: [ `Your plugins must export known APIs from their gatsby-node.js.`, ] .concat(errors) .concat( fixes.length > 0 ? [`\n`, `Some of the following may help fix the error(s):`, ...fixes] : [] ) .filter(Boolean) .join(`\n`), } } export async function handleBadExports({ currentAPIs, badExports, }: { currentAPIs: ICurrentAPIs badExports: { [api in ExportType]: Array<IEntry> } }): Promise<void> { const hasBadExports = Object.keys(badExports).find( api => badExports[api].length > 0 ) if (hasBadExports) { const latestAPIs = await getLatestAPIs() // Output error messages for all bad exports _.toPairs(badExports).forEach(badItem => { const [exportType, entries] = badItem if (entries.length > 0) { const context = getErrorContext( entries, exportType as keyof typeof badExports, currentAPIs, latestAPIs ) reporter.error({ id: `11329`, context, }) } }) } } async function validatePluginsOptions( plugins: Array<IPluginRefObject>, rootDir: string | null ): Promise<{ errors: number plugins: Array<IPluginRefObject> }> { let errors = 0 const newPlugins = await Promise.all( plugins.map(async plugin => { let gatsbyNode try { const resolvedPlugin = resolvePlugin(plugin, rootDir) gatsbyNode = require(`${resolvedPlugin.resolve}/gatsby-node`) } catch (err) { gatsbyNode = {} } if (!gatsbyNode.pluginOptionsSchema) return plugin const subPluginPaths = new Set<string>() let optionsSchema = ( gatsbyNode.pluginOptionsSchema as Exclude< GatsbyNode["pluginOptionsSchema"], undefined > )({ Joi: Joi.extend(joi => { return { base: joi.any(), type: `subPlugins`, args: (_, args: any): any => { const entry = args?.entry ?? `index` return joi .array() .items( joi .alternatives( joi.string(), joi.object({ resolve: Joi.string(), options: Joi.object({}).unknown(true), }) ) .custom((value, helpers) => { if (typeof value === `string`) { value = { resolve: value } } try { const resolvedPlugin = resolvePlugin(value, rootDir) const modulePath = require.resolve( `${resolvedPlugin.resolve}/${entry}` ) value.modulePath = modulePath value.module = require(modulePath) const normalizedPath = helpers.state.path .map((key, index) => { // if subplugin is part of an array - swap concrete index key with `[]` if ( typeof key === `number` && Array.isArray( helpers.state.ancestors[ helpers.state.path.length - index - 1 ] ) ) { if (index !== helpers.state.path.length - 1) { throw new Error( `No support for arrays not at the end of path` ) } return `[]` } return key }) .join(`.`) subPluginPaths.add(normalizedPath) } catch (err) { console.log(err) } return value }, `Gatsby specific subplugin validation`) ) .default([]) }, } }), }) if (!Joi.isSchema(optionsSchema) || optionsSchema.type !== `object`) { // Validate correct usage of pluginOptionsSchema reporter.warn( `Plugin "${plugin.resolve}" has an invalid options schema so we cannot verify your configuration for it.` ) return plugin } try { if (!optionsSchema.describe().keys.plugins) { // All plugins have "plugins: []"" added to their options in load.ts, even if they // do not have subplugins. We add plugins to the schema if it does not exist already // to make sure they pass validation. optionsSchema = optionsSchema.append({ plugins: Joi.array().length(0), }) } plugin.options = await validateOptionsSchema( optionsSchema, (plugin.options as IPluginInfoOptions) || {} ) if (plugin.options?.plugins) { const { errors: subErrors, plugins: subPlugins } = await validatePluginsOptions( plugin.options.plugins as Array<IPluginRefObject>, rootDir ) plugin.options.plugins = subPlugins if (subPlugins.length > 0) { subPluginPaths.add(`plugins.[]`) } errors += subErrors } if (subPluginPaths.size > 0) { plugin.subPluginPaths = Array.from(subPluginPaths) } } catch (error) { if (error instanceof Joi.ValidationError) { // Show a small warning on unknown options rather than erroring const validationWarnings = error.details.filter( err => err.type === `object.unknown` ) const validationErrors = error.details.filter( err => err.type !== `object.unknown` ) // If rootDir and plugin.parentDir are the same, i.e. if this is a plugin a user configured in their gatsby-config.js (and not a sub-theme that added it), this will be "" // Otherwise, this will contain (and show) the relative path const configDir = (plugin.parentDir && rootDir && path.relative(rootDir, plugin.parentDir)) || null if (validationErrors.length > 0) { reporter.error({ id: `11331`, context: { configDir, validationErrors, pluginName: plugin.resolve, }, }) errors++ } if (validationWarnings.length > 0) { reporter.warn( stripIndent(` Warning: there are unknown plugin options for "${ plugin.resolve }"${ configDir ? `, configured by ${configDir}` : `` }: ${validationWarnings .map(error => error.path.join(`.`)) .join(`, `)} Please open an issue at ghub.io/${ plugin.resolve } if you believe this option is valid. `) ) trackCli(`UNKNOWN_PLUGIN_OPTION`, { name: plugin.resolve, valueString: validationWarnings .map(error => error.path.join(`.`)) .join(`, `), }) // We do not increment errors++ here as we do not want to process.exit if there are only warnings } return plugin } throw error } return plugin }) ) return { errors, plugins: newPlugins } } export async function validateConfigPluginsOptions( config: ISiteConfig = {}, rootDir: string | null ): Promise<void> { if (!config.plugins) return const { errors, plugins } = await validatePluginsOptions( config.plugins, rootDir ) config.plugins = plugins if (errors > 0) { process.exit(1) } } /** * Identify which APIs each plugin exports */ export function collatePluginAPIs({ currentAPIs, flattenedPlugins, }: { currentAPIs: ICurrentAPIs flattenedPlugins: Array<IPluginInfo & Partial<IFlattenedPlugin>> }): { flattenedPlugins: Array<IFlattenedPlugin>; badExports: IEntryMap } { // Get a list of bad exports const badExports: IEntryMap = { node: [], browser: [], ssr: [], } flattenedPlugins.forEach(plugin => { plugin.nodeAPIs = [] plugin.browserAPIs = [] plugin.ssrAPIs = [] // Discover which APIs this plugin implements and store an array against // the plugin node itself *and* in an API to plugins map for faster lookups // later. const pluginNodeExports = resolveModuleExports( `${plugin.resolve}/gatsby-node`, { mode: `require`, } ) const pluginBrowserExports = resolveModuleExports( `${plugin.resolve}/gatsby-browser` ) const pluginSSRExports = resolveModuleExports( `${plugin.resolve}/gatsby-ssr` ) if (pluginNodeExports.length > 0) { plugin.nodeAPIs = _.intersection(pluginNodeExports, currentAPIs.node) badExports.node = badExports.node.concat( getBadExports(plugin, pluginNodeExports, currentAPIs.node) ) // Collate any bad exports } if (pluginBrowserExports.length > 0) { plugin.browserAPIs = _.intersection( pluginBrowserExports, currentAPIs.browser ) badExports.browser = badExports.browser.concat( getBadExports(plugin, pluginBrowserExports, currentAPIs.browser) ) // Collate any bad exports } if (pluginSSRExports.length > 0) { plugin.ssrAPIs = _.intersection(pluginSSRExports, currentAPIs.ssr) badExports.ssr = badExports.ssr.concat( getBadExports(plugin, pluginSSRExports, currentAPIs.ssr) ) // Collate any bad exports } }) return { flattenedPlugins: flattenedPlugins as Array<IFlattenedPlugin>, badExports, } } export const handleMultipleReplaceRenderers = ({ flattenedPlugins, }: { flattenedPlugins: Array<IFlattenedPlugin> }): Array<IFlattenedPlugin> => { // multiple replaceRenderers may cause problems at build time const rendererPlugins = flattenedPlugins .filter(plugin => plugin.ssrAPIs.includes(`replaceRenderer`)) .map(plugin => plugin.name) if (rendererPlugins.length > 1) { if (rendererPlugins.includes(`default-site-plugin`)) { reporter.warn(`replaceRenderer API found in these plugins:`) reporter.warn(rendererPlugins.join(`, `)) reporter.warn( `This might be an error, see: https://www.gatsbyjs.org/docs/debugging-replace-renderer-api/` ) } else { console.log(``) reporter.error( `Gatsby's replaceRenderer API is implemented by multiple plugins:` ) reporter.error(rendererPlugins.join(`, `)) reporter.error(`This will break your build`) reporter.error( `See: https://www.gatsbyjs.org/docs/debugging-replace-renderer-api/` ) if (process.env.NODE_ENV === `production`) process.exit(1) } // Now update plugin list so only final replaceRenderer will run const ignorable = rendererPlugins.slice(0, -1) // For each plugin in ignorable, set a skipSSR flag to true // This prevents apiRunnerSSR() from attempting to run it later const messages: Array<string> = [] flattenedPlugins.forEach((fp, i) => { if (ignorable.includes(fp.name)) { messages.push( `Duplicate replaceRenderer found, skipping gatsby-ssr.js for plugin: ${fp.name}` ) flattenedPlugins[i].skipSSR = true } }) if (messages.length > 0) { console.log(``) messages.forEach(m => reporter.warn(m)) console.log(``) } } return flattenedPlugins } export function warnOnIncompatiblePeerDependency( name: string, packageJSON: PackageJson ): void { // Note: In the future the peer dependency should be enforced for all plugins. const gatsbyPeerDependency = _.get(packageJSON, `peerDependencies.gatsby`) if ( !isWorker && gatsbyPeerDependency && !semver.satisfies(gatsbyVersion, gatsbyPeerDependency, { includePrerelease: true, }) ) { reporter.warn( `Plugin ${name} is not compatible with your gatsby version ${gatsbyVersion} - It requires gatsby@${gatsbyPeerDependency}` ) } }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [kendra](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonkendra.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Kendra extends PolicyStatement { public servicePrefix = 'kendra'; /** * Statement provider for service [kendra](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonkendra.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to batch delete document * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_BatchDeleteDocument.html */ public toBatchDeleteDocument() { return this.to('BatchDeleteDocument'); } /** * Grants permission to do batch get document status * * Access Level: Read * * https://docs.aws.amazon.com/kendra/latest/dg/API_BatchGetDocumentStatus.html */ public toBatchGetDocumentStatus() { return this.to('BatchGetDocumentStatus'); } /** * Grants permission to batch put document * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_BatchPutDocument.html */ public toBatchPutDocument() { return this.to('BatchPutDocument'); } /** * Grants permission to clear out the suggestions for a given index, generated so far * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_ClearQuerySuggestions.html */ public toClearQuerySuggestions() { return this.to('ClearQuerySuggestions'); } /** * Grants permission to create a data source * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/kendra/latest/dg/API_CreateDataSource.html */ public toCreateDataSource() { return this.to('CreateDataSource'); } /** * Grants permission to create an Faq * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/kendra/latest/dg/API_CreateFaq.html */ public toCreateFaq() { return this.to('CreateFaq'); } /** * Grants permission to create an Index * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/kendra/latest/dg/API_CreateIndex.html */ public toCreateIndex() { return this.to('CreateIndex'); } /** * Grants permission to create a QuerySuggestions BlockList * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/kendra/latest/dg/API_CreateQuerySuggestionsBlockList.html */ public toCreateQuerySuggestionsBlockList() { return this.to('CreateQuerySuggestionsBlockList'); } /** * Grants permission to create a Thesaurus * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/kendra/latest/dg/API_CreateThesaurus.html */ public toCreateThesaurus() { return this.to('CreateThesaurus'); } /** * Grants permission to delete a data source * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_DeleteDataSource.html */ public toDeleteDataSource() { return this.to('DeleteDataSource'); } /** * Grants permission to delete an Faq * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_DeleteFaq.html */ public toDeleteFaq() { return this.to('DeleteFaq'); } /** * Grants permission to delete an Index * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_DeleteIndex.html */ public toDeleteIndex() { return this.to('DeleteIndex'); } /** * Grants permission to delete principal mapping from index * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_DeletePrincipalMapping.html */ public toDeletePrincipalMapping() { return this.to('DeletePrincipalMapping'); } /** * Grants permission to delete a QuerySuggestions BlockList * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_DeleteQuerySuggestionsBlockList.html */ public toDeleteQuerySuggestionsBlockList() { return this.to('DeleteQuerySuggestionsBlockList'); } /** * Grants permission to delete a Thesaurus * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_DeleteThesaurus.html */ public toDeleteThesaurus() { return this.to('DeleteThesaurus'); } /** * Grants permission to describe a data source * * Access Level: Read * * https://docs.aws.amazon.com/kendra/latest/dg/API_DescribeDataSource.html */ public toDescribeDataSource() { return this.to('DescribeDataSource'); } /** * Grants permission to describe an Faq * * Access Level: Read * * https://docs.aws.amazon.com/kendra/latest/dg/API_DescribeFaq.html */ public toDescribeFaq() { return this.to('DescribeFaq'); } /** * Grants permission to describe an Index * * Access Level: Read * * https://docs.aws.amazon.com/kendra/latest/dg/API_DescribeIndex.html */ public toDescribeIndex() { return this.to('DescribeIndex'); } /** * Grants permission to describe principal mapping from index * * Access Level: Read * * https://docs.aws.amazon.com/kendra/latest/dg/API_DescribePrincipalMapping.html */ public toDescribePrincipalMapping() { return this.to('DescribePrincipalMapping'); } /** * Grants permission to describe a QuerySuggestions BlockList * * Access Level: Read * * https://docs.aws.amazon.com/kendra/latest/dg/API_DescribeQuerySuggestionsBlockList.html */ public toDescribeQuerySuggestionsBlockList() { return this.to('DescribeQuerySuggestionsBlockList'); } /** * Grants permission to describe the query suggestions configuration for an index * * Access Level: Read * * https://docs.aws.amazon.com/kendra/latest/dg/API_DescribeQuerySuggestionsConfig.html */ public toDescribeQuerySuggestionsConfig() { return this.to('DescribeQuerySuggestionsConfig'); } /** * Grants permission to describe a Thesaurus * * Access Level: Read * * https://docs.aws.amazon.com/kendra/latest/dg/API_DescribeThesaurus.html */ public toDescribeThesaurus() { return this.to('DescribeThesaurus'); } /** * Grants permission to get suggestions for a query prefix * * Access Level: Read * * https://docs.aws.amazon.com/kendra/latest/dg/API_GetQuerySuggestions.html */ public toGetQuerySuggestions() { return this.to('GetQuerySuggestions'); } /** * Grants permission to get Data Source sync job history * * Access Level: List * * https://docs.aws.amazon.com/kendra/latest/dg/API_ListDataSourceSyncJobs.html */ public toListDataSourceSyncJobs() { return this.to('ListDataSourceSyncJobs'); } /** * Grants permission to list the data sources * * Access Level: List * * https://docs.aws.amazon.com/kendra/latest/dg/API_ListDataSources.html */ public toListDataSources() { return this.to('ListDataSources'); } /** * Grants permission to list the Faqs * * Access Level: List * * https://docs.aws.amazon.com/kendra/latest/dg/API_ListFaqs.html */ public toListFaqs() { return this.to('ListFaqs'); } /** * Grants permission to list groups that are older than an ordering id * * Access Level: List * * https://docs.aws.amazon.com/kendra/latest/dg/API_ListGroupsOlderThanOrderingId.html */ public toListGroupsOlderThanOrderingId() { return this.to('ListGroupsOlderThanOrderingId'); } /** * Grants permission to list the indexes * * Access Level: List * * https://docs.aws.amazon.com/kendra/latest/dg/API_ListIndices.html */ public toListIndices() { return this.to('ListIndices'); } /** * Grants permission to list the QuerySuggestions BlockLists * * Access Level: List * * https://docs.aws.amazon.com/kendra/latest/dg/API_ListQuerySuggestionsBlockLists.html */ public toListQuerySuggestionsBlockLists() { return this.to('ListQuerySuggestionsBlockLists'); } /** * Grants permission to list tags for a resource * * Access Level: Read * * https://docs.aws.amazon.com/kendra/latest/dg/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to list the Thesauri * * Access Level: List * * https://docs.aws.amazon.com/kendra/latest/dg/API_ListThesauri.html */ public toListThesauri() { return this.to('ListThesauri'); } /** * Grants permission to put principal mapping in index * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_PutPrincipalMapping.html */ public toPutPrincipalMapping() { return this.to('PutPrincipalMapping'); } /** * Grants permission to query documents and faqs * * Access Level: Read * * https://docs.aws.amazon.com/kendra/latest/dg/API_Query.html */ public toQuery() { return this.to('Query'); } /** * Grants permission to start Data Source sync job * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_StartDataSourceSyncJob.html */ public toStartDataSourceSyncJob() { return this.to('StartDataSourceSyncJob'); } /** * Grants permission to stop Data Source sync job * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_StopDataSourceSyncJob.html */ public toStopDataSourceSyncJob() { return this.to('StopDataSourceSyncJob'); } /** * Grants permission to send feedback about a query results * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_SubmitFeedback.html */ public toSubmitFeedback() { return this.to('SubmitFeedback'); } /** * Grants permission to tag a resource with given key value pairs * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/kendra/latest/dg/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to remove the tag with the given key from a resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/kendra/latest/dg/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update a data source * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_UpdateDataSource.html */ public toUpdateDataSource() { return this.to('UpdateDataSource'); } /** * Grants permission to update an Index * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_UpdateIndex.html */ public toUpdateIndex() { return this.to('UpdateIndex'); } /** * Grants permission to update a QuerySuggestions BlockList * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_UpdateQuerySuggestionsBlockList.html */ public toUpdateQuerySuggestionsBlockList() { return this.to('UpdateQuerySuggestionsBlockList'); } /** * Grants permission to update the query suggestions configuration for an index * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_UpdateQuerySuggestionsConfig.html */ public toUpdateQuerySuggestionsConfig() { return this.to('UpdateQuerySuggestionsConfig'); } /** * Grants permission to update a thesaurus * * Access Level: Write * * https://docs.aws.amazon.com/kendra/latest/dg/API_UpdateThesaurus.html */ public toUpdateThesaurus() { return this.to('UpdateThesaurus'); } protected accessLevelList: AccessLevelList = { "Write": [ "BatchDeleteDocument", "BatchPutDocument", "ClearQuerySuggestions", "CreateDataSource", "CreateFaq", "CreateIndex", "CreateQuerySuggestionsBlockList", "CreateThesaurus", "DeleteDataSource", "DeleteFaq", "DeleteIndex", "DeletePrincipalMapping", "DeleteQuerySuggestionsBlockList", "DeleteThesaurus", "PutPrincipalMapping", "StartDataSourceSyncJob", "StopDataSourceSyncJob", "SubmitFeedback", "UpdateDataSource", "UpdateIndex", "UpdateQuerySuggestionsBlockList", "UpdateQuerySuggestionsConfig", "UpdateThesaurus" ], "Read": [ "BatchGetDocumentStatus", "DescribeDataSource", "DescribeFaq", "DescribeIndex", "DescribePrincipalMapping", "DescribeQuerySuggestionsBlockList", "DescribeQuerySuggestionsConfig", "DescribeThesaurus", "GetQuerySuggestions", "ListTagsForResource", "Query" ], "List": [ "ListDataSourceSyncJobs", "ListDataSources", "ListFaqs", "ListGroupsOlderThanOrderingId", "ListIndices", "ListQuerySuggestionsBlockLists", "ListThesauri" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type index to the statement * * https://docs.aws.amazon.com/kendra/latest/dg/index.html * * @param indexId - Identifier for the indexId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onIndex(indexId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:kendra:${Region}:${Account}:index/${IndexId}'; arn = arn.replace('${IndexId}', indexId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type data-source to the statement * * https://docs.aws.amazon.com/kendra/latest/dg/data-source.html * * @param indexId - Identifier for the indexId. * @param dataSourceId - Identifier for the dataSourceId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onDataSource(indexId: string, dataSourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:kendra:${Region}:${Account}:index/${IndexId}/data-source/${DataSourceId}'; arn = arn.replace('${IndexId}', indexId); arn = arn.replace('${DataSourceId}', dataSourceId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type faq to the statement * * https://docs.aws.amazon.com/kendra/latest/dg/faq.html * * @param indexId - Identifier for the indexId. * @param faqId - Identifier for the faqId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onFaq(indexId: string, faqId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:kendra:${Region}:${Account}:index/${IndexId}/faq/${FaqId}'; arn = arn.replace('${IndexId}', indexId); arn = arn.replace('${FaqId}', faqId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type thesaurus to the statement * * https://docs.aws.amazon.com/kendra/latest/dg/thesaurus.html * * @param indexId - Identifier for the indexId. * @param thesaurusId - Identifier for the thesaurusId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onThesaurus(indexId: string, thesaurusId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:kendra:${Region}:${Account}:index/${IndexId}/thesaurus/${ThesaurusId}'; arn = arn.replace('${IndexId}', indexId); arn = arn.replace('${ThesaurusId}', thesaurusId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type query-suggestions-block-list to the statement * * https://docs.aws.amazon.com/kendra/latest/dg/query-suggestions-block-list.html * * @param indexId - Identifier for the indexId. * @param querySuggestionsBlockListId - Identifier for the querySuggestionsBlockListId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onQuerySuggestionsBlockList(indexId: string, querySuggestionsBlockListId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:kendra:${Region}:${Account}:index/${IndexId}/query-suggestions-block-list/${QuerySuggestionsBlockListId}'; arn = arn.replace('${IndexId}', indexId); arn = arn.replace('${QuerySuggestionsBlockListId}', querySuggestionsBlockListId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import React, { useState } from 'react'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import { ParentSize } from '@visx/responsive'; import { MemoryRouter as Router, Route, NavLink, Switch, } from 'react-router-dom'; import { Component } from 'react'; import { render } from 'react-dom'; import RenderingFrequency from './RenderingFrequency'; // import Switch from '@material-ui/core/Switch'; import BarGraph from './BarGraph'; import BarGraphComparison from './BarGraphComparison'; import { useStoreContext } from '../store'; // import snapshots from './snapshots'; import snapshots from './snapshots'; const exclude = ['childExpirationTime', 'staticContext', '_debugSource', 'actualDuration', 'actualStartTime', 'treeBaseDuration', '_debugID', '_debugIsCurrentlyTiming', 'selfBaseDuration', 'expirationTime', 'effectTag', 'alternate', '_owner', '_store', 'get key', 'ref', '_self', '_source', 'firstBaseUpdate', 'updateQueue', 'lastBaseUpdate', 'shared', 'responders', 'pending', 'lanes', 'childLanes', 'effects', 'memoizedState', 'pendingProps', 'lastEffect', 'firstEffect', 'tag', 'baseState', 'baseQueue', 'dependencies', 'Consumer', 'context', '_currentRenderer', '_currentRenderer2', 'mode', 'flags', 'nextEffect', 'sibling', 'create', 'deps', 'next', 'destroy', 'parentSub', 'child', 'key', 'return', 'children', '$$typeof', '_threadCount', '_calculateChangedBits', '_currentValue', '_currentValue2', 'Provider', '_context', 'stateNode', 'elementType', 'type']; /* NOTES Issue - Not fully compatible with recoil apps. Reference the recoil-todo-test. Barstacks display inconsistently...however, almost always displays upon initial test app load or when empty button is clicked. Updating state after initial app load typically makes bars disappear. However, cycling between updating state and then emptying sometimes fixes the stack bars. Important to note - all snapshots do render (check HTML doc) within the chrome extension but they do not display because height is not consistently passed to each bar. This side effect is only seen in recoil apps... */ // typescript for PROPS from StateRoute.tsx interface BarStackProps { width: number; height: number; snapshots: []; hierarchy: any; } const makePropsPretty = data => { const propsFormat = []; const nestedObj = []; if (typeof data !== 'object') { return <p>{data}</p>; } for (const key in data) { if (data[key] !== 'reactFiber' && typeof data[key] !== 'object' && exclude.includes(key) !== true) { propsFormat.push(<p className="stateprops"> {`${key}: ${data[key]}`} </p>); } else if (data[key] !== 'reactFiber' && typeof data[key] === 'object' && exclude.includes(key) !== true) { const result = makePropsPretty(data[key]); nestedObj.push(result); } } if (nestedObj) { propsFormat.push(nestedObj); } return propsFormat; }; const collectNodes = (snaps, componentName) => { const componentsResult = []; const renderResult = []; let trackChanges = 0; let newChange = true; for (let x = 0; x < snaps.length; x++) { const snapshotList = []; snapshotList.push(snaps[x]); for (let i = 0; i < snapshotList.length; i++) { const cur = snapshotList[i]; if (cur.name === componentName) { const renderTime = Number( Number.parseFloat(cur.componentData.actualDuration).toPrecision(5), ); if (renderTime === 0) { break; } else { renderResult.push(renderTime); } // compare the last pushed component Data from the array to the current one to see if there are differences if (x !== 0 && componentsResult.length !== 0) { // needs to be stringified because values are hard to determine if true or false if in they're seen as objects if (JSON.stringify(Object.values(componentsResult[newChange ? componentsResult.length - 1 : trackChanges])[0]) !== JSON.stringify(cur.componentData.props)) { newChange = true; // const props = { [`snapshot${x}`]: { rendertime: formatRenderTime(cur.componentData.actualDuration), ...cur.componentData.props } }; const props = { [`snapshot${x}`]: { ...cur.componentData.props } }; componentsResult.push(props); } else { newChange = false; trackChanges = componentsResult.length - 1; const props = { [`snapshot${x}`]: { state: 'Same state as prior snapshot' } }; componentsResult.push(props); } } else { // const props = { [`snapshot${x}`]: { ...cur.componentData.props}}; // props[`snapshot${x}`].rendertime = formatRenderTime(cur.componentData.actualDuration); const props = { [`snapshot${x}`]: { ...cur.componentData.props } }; componentsResult.push(props); } break; } if (cur.children && cur.children.length > 0) { for (const child of cur.children) { snapshotList.push(child); } } } } const finalResults = componentsResult.map((e, index) => { const name = Object.keys(e)[0]; e[name].rendertime = renderResult[index]; return e; }); for (let i = 0; i < finalResults.length; i++) { for (const componentSnapshot in finalResults[i]) { finalResults[i][componentSnapshot] = makePropsPretty(finalResults[i][componentSnapshot]).reverse(); } } return finalResults; }; /* DATA HANDLING HELPER FUNCTIONS */ const traverse = (snapshot, data, snapshots, currTotalRender = 0) => { if (!snapshot.children[0]) return; // loop through snapshots snapshot.children.forEach((child, idx) => { const componentName = child.name + -[idx + 1]; // Get component Rendering Time const renderTime = Number( Number.parseFloat(child.componentData.actualDuration).toPrecision(5), ); // sums render time for all children currTotalRender += renderTime; // components as keys and set the value to their rendering time data.barStack[data.barStack.length - 1][componentName] = renderTime; // Get component stateType if (!data.componentData[componentName]) { data.componentData[componentName] = { stateType: 'stateless', renderFrequency: 0, totalRenderTime: 0, rtid: '', information: {}, }; if (child.state !== 'stateless') data.componentData[componentName].stateType = 'stateful'; } // increment render frequencies if (renderTime > 0) { data.componentData[componentName].renderFrequency++; } // else { // } // add to total render time data.componentData[componentName].totalRenderTime += renderTime; // Get rtid for the hovering feature data.componentData[componentName].rtid = child.rtid; data.componentData[componentName].information = collectNodes(snapshots, child.name); traverse(snapshot.children[idx], data, snapshots, currTotalRender); }); // reassigns total render time to max render time data.maxTotalRender = Math.max(currTotalRender, data.maxTotalRender); return data; }; // Retrieve snapshot series data from Chrome's local storage. const allStorage = () => { const values = []; const keys = Object.keys(localStorage); let i = keys.length; while (i--) { const series = localStorage.getItem(keys[i]); values.push(JSON.parse(series)); } return values; }; // Gets snapshot Ids for the regular bar graph view. const getSnapshotIds = (obj, snapshotIds = []): string[] => { snapshotIds.push(`${obj.name}.${obj.branch}`); if (obj.children) { obj.children.forEach(child => { getSnapshotIds(child, snapshotIds); }); } return snapshotIds; }; // Returns array of snapshot objs each with components and corresponding render times. const getPerfMetrics = (snapshots, snapshotsIds): {} => { const perfData = { barStack: [], componentData: {}, maxTotalRender: 0, }; snapshots.forEach((snapshot, i) => { perfData.barStack.push({ snapshotId: snapshotsIds[i] }); traverse(snapshot, perfData, snapshots); }); return perfData; }; /* EXPORT COMPONENT */ const PerformanceVisx = (props: BarStackProps) => { // hook used to dispatch onhover action in rect const { width, height, snapshots, hierarchy, } = props; const [{ tabs, currentTab }, dispatch] = useStoreContext(); const [detailsView, setDetailsView] = useState('barStack'); const [comparisonView, setComparisonView] = useState('barStack'); const [comparisonData, setComparisonData] = useState(); const NO_STATE_MSG = 'No state change detected. Trigger an event to change state'; const data = getPerfMetrics(snapshots, getSnapshotIds(hierarchy)); const renderComparisonBargraph = () => { if (hierarchy) { return ( <BarGraphComparison comparison={allStorage()} data={data} width={width} height={height} /> ); } }; const renderBargraph = () => { if (hierarchy) { return <BarGraph data={data} width={width} height={height} />; } }; const renderComponentDetailsView = () => { if (hierarchy) { return <RenderingFrequency data={data.componentData} />; } return <div className="noState">{NO_STATE_MSG}</div>; }; return ( <Router> <div className="performance-nav-bar-container"> <NavLink className="router-link-performance" // className="router-link" activeClassName="is-active" exact to="/" > Snapshots View </NavLink> <NavLink className="router-link-performance" // className="router-link" activeClassName="is-active" to="/comparison" > Comparison View </NavLink> <NavLink className="router-link-performance" // className="router-link" activeClassName="is-active" to="/componentdetails" > Component Details </NavLink> </div> <Switch> <Route path="/comparison" render={renderComparisonBargraph} /> <Route path="/componentdetails" render={renderComponentDetailsView} /> <Route path="/" render={renderBargraph} /> </Switch> </Router> ); }; export default PerformanceVisx;
the_stack
namespace fgui { export const enum TransitionActionType { XY = 0, Size = 1, Scale = 2, Pivot = 3, Alpha = 4, Rotation = 5, Color = 6, Animation = 7, Visible = 8, Sound = 9, Transition = 10, Shake = 11, ColorFilter = 12, Skew = 13, Unknown = 14 } export interface TransitionPlaySetting { onComplete?: (...args: any[]) => void, onCompleteObj?: any, onCompleteParam?: any, times: number, delay: number }; export class Transition { public name: string; public autoPlayRepeat: number = 1; public autoPlayDelay: number = 0; private $owner: GComponent; private $ownerBaseX: number = 0; private $ownerBaseY: number = 0; private $items: TransitionItem[]; private $totalTimes: number = 0; private $totalTasks: number = 0; private $playing: boolean = false; private $onComplete: (...args: any[]) => void; private $onCompleteObj: any; private $onCompleteParam: any; private $options: number = 0; private $reversed: boolean; private $maxTime: number = 0; private $autoPlay: boolean; public static OPTION_IGNORE_DISPLAY_CONTROLLER: number = 1; public static OPTION_AUTO_STOP_DISABLED:number = 1 >> 1; public static OPTION_AUTO_STOP_AT_END:number = 1 >> 2; private static FRAME_RATE: number = 24; public constructor(owner: GComponent) { this.$owner = owner; this.$items = []; this.$owner.on(DisplayObjectEvent.VISIBLE_CHANGED, this.$ownerVisibleChanged, this); } private $ownerVisibleChanged(vis:boolean, owner:GComponent):void { if ((this.$options & Transition.OPTION_AUTO_STOP_DISABLED) == 0 && vis === false) this.stop((this.$options & Transition.OPTION_AUTO_STOP_AT_END) != 0 ? true : false, false); } public get autoPlay(): boolean { return this.$autoPlay; } public set autoPlay(value: boolean) { if (this.$autoPlay != value) { this.$autoPlay = value; if (this.$autoPlay) { if (this.$owner.onStage) this.play({ times: this.autoPlayRepeat, delay: this.autoPlayDelay }); } else { if (!this.$owner.onStage) this.stop(false, true); } } } public changeRepeat(value: number): void { this.$totalTimes = value | 0; } /** * Play transition by specified settings: * 1) pass whole parameters: onComplete?: (...args:any[]) => void, onCompleteObj?: any, onCompleteParam?: any, times: number, delay: number * 2) just pass 1 object which implements TransitionPlaySetting (recommended) */ public play(...args: any[]): void { if (args.length && typeof (args[0]) == "object") { let obj = args[0] as TransitionPlaySetting; this.$play(obj.onComplete, obj.onCompleteObj, obj.onCompleteParam, obj.times || 1, obj.delay || 0, false); } else this.$play(args[0], args[1], args[2], args[3] || 1, args[4] || 0, false); } /** * Play transition by specified settings: * 1) pass whole parameters: onComplete?: (...args:any[]) => void, onCompleteObj?: any, onCompleteParam?: any, times: number, delay: number * 2) just pass 1 object which implements TransitionPlaySetting (recommended) */ public playReverse(...args: any[]):void { if (args.length && typeof (args[0]) == "object") { let obj = args[0] as TransitionPlaySetting; this.$play(obj.onComplete, obj.onCompleteObj, obj.onCompleteParam, obj.times || 1, obj.delay || 0, true); } else this.$play(args[0], args[1], args[2], args[3] || 1, args[4] || 0, true); } private $play(onComplete?: (...args: any[]) => void, onCompleteObj?: any, onCompleteParam?: any, times?: number, delay?: number, reversed: boolean = false) { this.stop(); if (times == 0) times = 1; else if (times == -1) times = Number.MAX_VALUE; this.$totalTimes = times; this.$reversed = reversed; this.internalPlay(delay); this.$playing = this.$totalTasks > 0; if (this.$playing) { this.$onComplete = onComplete; this.$onCompleteParam = onCompleteParam; this.$onCompleteObj = onCompleteObj; if ((this.$options & Transition.OPTION_IGNORE_DISPLAY_CONTROLLER) != 0) { this.$items.forEach(item => { if (item.target != null && item.target != this.$owner) item.lockToken = item.target.lockGearDisplay(); }, this); } } else if (onComplete != null) { onCompleteParam && onCompleteParam.length ? onComplete.apply(onCompleteObj, onCompleteParam) : onComplete.call(onCompleteObj, onCompleteParam); } } public stop(setToComplete: boolean = true, processCallback: boolean = false) { if (this.$playing) { this.$playing = false; this.$totalTasks = 0; this.$totalTimes = 0; let func: Function = this.$onComplete; let param: any = this.$onCompleteParam; let thisObj: any = this.$onCompleteObj; this.$onComplete = null; this.$onCompleteParam = null; this.$onCompleteObj = null; let cnt: number = this.$items.length; let item: TransitionItem; if (this.$reversed) { for (let i = cnt - 1; i >= 0; i--) { item = this.$items[i]; if (item.target == null) continue; this.stopItem(item, setToComplete); } } else { for (let i = 0; i < cnt; i++) { item = this.$items[i]; if (item.target == null) continue; this.stopItem(item, setToComplete); } } if (processCallback && func != null) param && param.length > 0 ? func.apply(thisObj, param) : func.call(thisObj, param); } } private stopItem(item: TransitionItem, setToComplete: boolean): void { if (item.lockToken != 0) { item.target.releaseGearDisplay(item.lockToken); item.lockToken = 0; } if (item.type == TransitionActionType.ColorFilter && item.filterCreated) item.target.filters = null; if (item.completed) return; this.disposeTween(item); if (item.type == TransitionActionType.Transition) { let trans: Transition = (item.target as GComponent).getTransition(item.value.s); if (trans != null) trans.stop(setToComplete, false); } else if (item.type == TransitionActionType.Shake) { GTimer.inst.remove(item.$shake, item); item.target.$gearLocked = true; item.target.setXY(item.target.x - item.startValue.f1, item.target.y - item.startValue.f2); item.target.$gearLocked = false; } else { if (setToComplete) { if (item.tween) { if (!item.yoyo || item.repeat % 2 == 0) this.applyValue(item, this.$reversed ? item.startValue : item.endValue); else this.applyValue(item, this.$reversed ? item.endValue : item.startValue); } else if (item.type != TransitionActionType.Sound) this.applyValue(item, item.value); } } } public dispose(): void { GTimer.inst.remove(this.internalPlay, this); this.$owner.off(DisplayObjectEvent.VISIBLE_CHANGED, this.$ownerVisibleChanged, this); this.$playing = false; this.$items.forEach(item => { if (item.target == null || item.completed) return; this.disposeTween(item); if (item.type == TransitionActionType.Transition) { let trans: Transition = (item.target as GComponent).getTransition(item.value.s); if (trans != null) trans.dispose(); } else if (item.type == TransitionActionType.Shake) GTimer.inst.remove(item.$shake, item); }, this); } public get playing(): boolean { return this.$playing; } public setValue(label: string, ...args: any[]) { this.$items.forEach(item => { if (item.label == null && item.label2 == null) return; let value: TransitionValue; if (item.label == label) { if (item.tween) value = item.startValue; else value = item.value; } else if (item.label2 == label) value = item.endValue; else return; switch (item.type) { case TransitionActionType.XY: case TransitionActionType.Size: case TransitionActionType.Pivot: case TransitionActionType.Scale: case TransitionActionType.Skew: value.b1 = true; value.b2 = true; value.f1 = parseFloat(args[0]); value.f2 = parseFloat(args[1]); break; case TransitionActionType.Alpha: value.f1 = parseFloat(args[0]); break; case TransitionActionType.Rotation: value.i = parseInt(args[0]); break; case TransitionActionType.Color: value.c = parseFloat(args[0]); break; case TransitionActionType.Animation: value.i = parseInt(args[0]); if (args.length > 1) value.b = args[1]; break; case TransitionActionType.Visible: value.b = args[0]; break; case TransitionActionType.Sound: value.s = args[0]; if (args.length > 1) value.f1 = parseFloat(args[1]); break; case TransitionActionType.Transition: value.s = args[0]; if (args.length > 1) value.i = parseInt(args[1]); break; case TransitionActionType.Shake: value.f1 = parseFloat(args[0]); if (args.length > 1) value.f2 = parseFloat(args[1]); break; case TransitionActionType.ColorFilter: value.f1 = parseFloat(args[0]); value.f2 = parseFloat(args[1]); value.f3 = parseFloat(args[2]); value.f4 = parseFloat(args[3]); break; } }, this); } public setHook(label: string, callback: () => void, thisObj?: any): void { let cnt: number = this.$items.length; for (let i: number = 0; i < cnt; i++) { let item: TransitionItem = this.$items[i]; if (item.label == label) { item.hook = callback; item.hookObj = thisObj; break; } else if (item.label2 == label) { item.hook2 = callback; item.hook2Obj = thisObj; break; } } } public clearHooks() { this.$items.forEach(item => { item.hook = null; item.hookObj = null; item.hook2 = null; item.hook2Obj = null; }, this); } public setTarget(label: string, newTarget: GObject) { this.$items.forEach(item => { if (item.label == label) item.targetId = newTarget.id; }, this); } public setDuration(label: string, value: number) { this.$items.forEach(item => { if (item.tween && item.label == label) item.duration = value; }, this); } public updateFromRelations(targetId: string, dx: number, dy: number) { this.$items.forEach(item => { if (item.type == TransitionActionType.XY && item.targetId == targetId) { if (item.tween) { item.startValue.f1 += dx; item.startValue.f2 += dy; item.endValue.f1 += dx; item.endValue.f2 += dy; } else { item.value.f1 += dx; item.value.f2 += dy; } } }, this); } private internalPlay(delay: number = 0): void { this.$ownerBaseX = this.$owner.x; this.$ownerBaseY = this.$owner.y; this.$totalTasks = 0; this.$items.forEach(item => { if (item.targetId) item.target = this.$owner.getChildById(item.targetId); else item.target = this.$owner; if (item.target == null) return; let startTime: number; this.disposeTween(item); if (item.tween) { if (this.$reversed) startTime = delay + this.$maxTime - item.time - item.duration; else startTime = delay + item.time; if (startTime > 0) { this.$totalTasks++; item.completed = false; item.tweener = createjs.Tween.get(item.value).wait(startTime * 1000).call(this.$delayCall, [item], this); } else this.startTween(item); } else { if (this.$reversed) startTime = delay + this.$maxTime - item.time; else startTime = delay + item.time; if (startTime <= 0) this.applyValue(item, item.value); else { this.$totalTasks++; item.completed = false; item.tweener = createjs.Tween.get(item.value).wait(startTime * 1000).call(this.$delayCall2, [item], this); } } }, this); } private prepareValue(item: TransitionItem, toProps: TransitionValue, reversed: boolean = false): void { let startValue: TransitionValue; let endValue: TransitionValue; if (reversed) { startValue = item.endValue; endValue = item.startValue; } else { startValue = item.startValue; endValue = item.endValue; } switch (item.type) { case TransitionActionType.XY: case TransitionActionType.Size: if (item.type == TransitionActionType.XY) { if (item.target == this.$owner) { if (!startValue.b1) startValue.f1 = 0; if (!startValue.b2) startValue.f2 = 0; } else { if (!startValue.b1) startValue.f1 = item.target.x; if (!startValue.b2) startValue.f2 = item.target.y; } } else { if (!startValue.b1) startValue.f1 = item.target.width; if (!startValue.b2) startValue.f2 = item.target.height; } item.value.f1 = startValue.f1; item.value.f2 = startValue.f2; if (!endValue.b1) endValue.f1 = item.value.f1; if (!endValue.b2) endValue.f2 = item.value.f2; item.value.b1 = startValue.b1 || endValue.b1; item.value.b2 = startValue.b2 || endValue.b2; toProps.f1 = endValue.f1; toProps.f2 = endValue.f2; break; case TransitionActionType.Scale: case TransitionActionType.Skew: item.value.f1 = startValue.f1; item.value.f2 = startValue.f2; toProps.f1 = endValue.f1; toProps.f2 = endValue.f2; break; case TransitionActionType.Alpha: item.value.f1 = startValue.f1; toProps.f1 = endValue.f1; break; case TransitionActionType.Rotation: item.value.i = startValue.i; toProps.i = endValue.i; break; case TransitionActionType.ColorFilter: item.value.f1 = startValue.f1; item.value.f2 = startValue.f2; item.value.f3 = startValue.f3; item.value.f4 = startValue.f4; toProps.f1 = endValue.f1; toProps.f2 = endValue.f2; toProps.f3 = endValue.f3; toProps.f4 = endValue.f4; break; } } private startTween(item: TransitionItem) { let toProps: TransitionValue = new TransitionValue(); this.prepareValue(item, toProps, this.$reversed); this.applyValue(item, item.value); let completeHandler:(t:createjs.Tween) => any; if(item.repeat != 0) { item.tweenTimes = 0; completeHandler = utils.Binder.create(this.$tweenRepeatComplete, this, item); } else completeHandler = utils.Binder.create(this.$tweenComplete, this, item); this.$totalTasks++; item.completed = false; this.prepareValue(item, toProps, this.$reversed); item.tweener = createjs.Tween.get(item.value, { onChange: utils.Binder.create(this.$tweenUpdate, this, item) }).to(toProps, item.duration * 1000, item.easeType).call(completeHandler); if (item.hook != null) item.hook.call(item.hookObj); } private $delayCall(item: TransitionItem) { this.disposeTween(item); this.$totalTasks--; this.startTween(item); } private $delayCall2(item: TransitionItem) { this.disposeTween(item); this.$totalTasks--; item.completed = true; this.applyValue(item, item.value); if (item.hook != null) item.hook.call(item.hookObj); this.checkAllComplete(); } private $tweenUpdate(event:any, item: TransitionItem): void { this.applyValue(item, item.value); } private $tweenComplete(event:any, item: TransitionItem) { this.disposeTween(item); this.$totalTasks--; item.completed = true; if (item.hook2 != null) item.hook2.call(item.hook2Obj); this.checkAllComplete(); } private $tweenRepeatComplete(event:any, item: TransitionItem) { item.tweenTimes++; if (item.repeat == -1 || item.tweenTimes < item.repeat + 1) { let toProps: TransitionValue = new TransitionValue; let reversed: boolean; if (item.yoyo) { if (this.$reversed) reversed = item.tweenTimes % 2 == 0; else reversed = item.tweenTimes % 2 == 1; } else reversed = this.$reversed; this.prepareValue(item, toProps, reversed); this.disposeTween(item); item.tweener = createjs.Tween.get(item.value, { onChange: utils.Binder.create(this.$tweenUpdate, this, item) }).to(toProps, item.duration * 1000, item.easeType).call(this.$tweenRepeatComplete, [null, item], this); } else this.$tweenComplete(null, item); } private disposeTween(item:TransitionItem):void { if(!item) return; if(item.tweener) { item.tweener.paused = true; item.tweener.removeAllEventListeners(); createjs.Tween.removeTweens(item.value); item.tweener = null; } } private $playTransComplete(item: TransitionItem) { this.disposeTween(item); this.$totalTasks--; item.completed = true; this.checkAllComplete(); } private checkAllComplete() { if (this.$playing && this.$totalTasks == 0) { if (this.$totalTimes < 0) { //the reason we don't call 'internalPlay' immediately here is because of the onChange handler issue, the handler's been calling all the time even the tween is in waiting/complete status. GTimer.inst.callLater(this.internalPlay, this, 0); } else { this.$totalTimes--; if (this.$totalTimes > 0) GTimer.inst.callLater(this.internalPlay, this, 0); else { this.$playing = false; this.$items.forEach(item => { if (item.target != null) { if (item.lockToken != 0) { item.target.releaseGearDisplay(item.lockToken); item.lockToken = 0; } if (item.filterCreated) { item.filterCreated = false; item.target.filters = null; } this.disposeTween(item); } }); if (this.$onComplete != null) { let func: Function = this.$onComplete; let param: any = this.$onCompleteParam; let thisObj: any = this.$onCompleteObj; this.$onComplete = null; this.$onCompleteParam = null; this.$onCompleteObj = null; param && param.length ? func.apply(thisObj, param) : func.call(thisObj, param); } } } } } private applyValue(item: TransitionItem, value: TransitionValue) { item.target.$gearLocked = true; switch (item.type) { case TransitionActionType.XY: if (item.target == this.$owner) { let f1: number = 0, f2: number = 0; if (!value.b1) f1 = item.target.x; else f1 = value.f1 + this.$ownerBaseX; if (!value.b2) f2 = item.target.y; else f2 = value.f2 + this.$ownerBaseY; item.target.setXY(f1, f2); } else { if (!value.b1) value.f1 = item.target.x; if (!value.b2) value.f2 = item.target.y; item.target.setXY(value.f1, value.f2); } break; case TransitionActionType.Size: if (!value.b1) value.f1 = item.target.width; if (!value.b2) value.f2 = item.target.height; item.target.setSize(value.f1, value.f2); break; case TransitionActionType.Pivot: item.target.setPivot(value.f1, value.f2); break; case TransitionActionType.Alpha: item.target.alpha = value.f1; break; case TransitionActionType.Rotation: item.target.rotation = value.i; break; case TransitionActionType.Scale: item.target.setScale(value.f1, value.f2); break; case TransitionActionType.Skew: item.target.setSkew(value.f1, value.f2); break; case TransitionActionType.Color: if (fgui.isColorGear(item.target)) item.target.color = value.c; break; case TransitionActionType.Animation: if (fgui.isAnimationGear(item.target)) { if (!value.b1) value.i = item.target.frame; item.target.frame = value.i; item.target.playing = value.b; } break; case TransitionActionType.Visible: item.target.visible = value.b; break; case TransitionActionType.Transition: let trans: Transition = (item.target as GComponent).getTransition(value.s); if (trans != null) { if (value.i == 0) trans.stop(false, true); else if (trans.playing) trans.$totalTimes = value.i == -1 ? Number.MAX_VALUE : value.i; else { item.completed = false; this.$totalTasks++; if (this.$reversed) trans.playReverse(this.$playTransComplete, this, item, item.value.i); else trans.play(this.$playTransComplete, this, item, item.value.i); } } break; case TransitionActionType.Sound: //ignore break; case TransitionActionType.Shake: item.startValue.f1 = 0; //offsetX item.startValue.f2 = 0; //offsetY item.startValue.f3 = item.value.f2; //shakePeriod GTimer.inst.add(1, 0, item.$shake, item, [this]); this.$totalTasks++; item.completed = false; break; case TransitionActionType.ColorFilter: item.target.updateColorComponents(value.f1, value.f2, value.f3, value.f4); break; } item.target.$gearLocked = false; } /**@internal */ $shakeItem(item: TransitionItem, elapsedMS:number) { let r: number = Math.ceil(item.value.f1 * item.startValue.f3 / item.value.f2); let rx: number = (Math.random() * 2 - 1) * r; let ry: number = (Math.random() * 2 - 1) * r; rx = rx > 0 ? Math.ceil(rx) : Math.floor(rx); ry = ry > 0 ? Math.ceil(ry) : Math.floor(ry); item.target.$gearLocked = true; item.target.setXY(item.target.x - item.startValue.f1 + rx, item.target.y - item.startValue.f2 + ry); item.target.$gearLocked = false; item.startValue.f1 = rx; item.startValue.f2 = ry; item.startValue.f3 -= elapsedMS / 1000; if (item.startValue.f3 <= 0) { item.target.$gearLocked = true; item.target.setXY(item.target.x - item.startValue.f1, item.target.y - item.startValue.f2); item.target.$gearLocked = false; item.completed = true; this.$totalTasks--; GTimer.inst.remove(item.$shake, item); this.checkAllComplete(); } } public setup(xml: utils.XmlNode) { this.name = xml.attributes.name; let str: string = xml.attributes.options; if (str) this.$options = parseInt(str); this.$autoPlay = xml.attributes.autoPlay == "true"; if (this.$autoPlay) { str = xml.attributes.autoPlayRepeat; if (str) this.autoPlayRepeat = parseInt(str); str = xml.attributes.autoPlayDelay; if (str) this.autoPlayDelay = parseFloat(str); } let col: utils.XmlNode[] = xml.children; col.forEach(cxml => { if (cxml.nodeName != "item") return; let item: TransitionItem = new TransitionItem(); this.$items.push(item); item.time = parseInt(cxml.attributes.time) / Transition.FRAME_RATE; item.targetId = cxml.attributes.target; str = cxml.attributes.type; switch (str) { case "XY": item.type = TransitionActionType.XY; break; case "Size": item.type = TransitionActionType.Size; break; case "Scale": item.type = TransitionActionType.Scale; break; case "Pivot": item.type = TransitionActionType.Pivot; break; case "Alpha": item.type = TransitionActionType.Alpha; break; case "Rotation": item.type = TransitionActionType.Rotation; break; case "Color": item.type = TransitionActionType.Color; break; case "Animation": item.type = TransitionActionType.Animation; break; case "Visible": item.type = TransitionActionType.Visible; break; case "Sound": item.type = TransitionActionType.Sound; break; case "Transition": item.type = TransitionActionType.Transition; break; case "Shake": item.type = TransitionActionType.Shake; break; case "ColorFilter": item.type = TransitionActionType.ColorFilter; break; case "Skew": item.type = TransitionActionType.Skew; break; default: item.type = TransitionActionType.Unknown; break; } item.tween = cxml.attributes.tween == "true"; item.label = cxml.attributes.label; if (item.tween) { item.duration = parseInt(cxml.attributes.duration) / Transition.FRAME_RATE; if (item.time + item.duration > this.$maxTime) this.$maxTime = item.time + item.duration; str = cxml.attributes.ease; if (str) item.easeType = ParseEaseType(str); str = cxml.attributes.repeat; if (str) item.repeat = parseInt(str); item.yoyo = cxml.attributes.yoyo == "true"; item.label2 = cxml.attributes.label2; let v: string = cxml.attributes.endValue; if (v) { this.decodeValue(item.type, cxml.attributes.startValue, item.startValue); this.decodeValue(item.type, v, item.endValue); } else { item.tween = false; this.decodeValue(item.type, cxml.attributes.startValue, item.value); } } else { if (item.time > this.$maxTime) this.$maxTime = item.time; this.decodeValue(item.type, cxml.attributes.value, item.value); } }, this); } private decodeValue(type: number, str: string, value: TransitionValue) { let arr: string[]; switch (type) { case TransitionActionType.XY: case TransitionActionType.Size: case TransitionActionType.Pivot: case TransitionActionType.Skew: arr = str.split(","); if (arr[0] == "-") { value.b1 = false; } else { value.f1 = parseFloat(arr[0]); value.b1 = true; } if (arr[1] == "-") { value.b2 = false; } else { value.f2 = parseFloat(arr[1]); value.b2 = true; } break; case TransitionActionType.Alpha: value.f1 = parseFloat(str); break; case TransitionActionType.Rotation: value.i = parseInt(str); break; case TransitionActionType.Scale: arr = str.split(","); value.f1 = parseFloat(arr[0]); value.f2 = parseFloat(arr[1]); break; case TransitionActionType.Color: value.c = utils.StringUtil.convertFromHtmlColor(str); break; case TransitionActionType.Animation: arr = str.split(","); if (arr[0] == "-") { value.b1 = false; } else { value.i = parseInt(arr[0]); value.b1 = true; } value.b = arr[1] == "p"; break; case TransitionActionType.Visible: value.b = str == "true"; break; case TransitionActionType.Sound: arr = str.split(","); value.s = arr[0]; if (arr.length > 1) { let intv: number = parseInt(arr[1]); if (intv == 0 || intv == 100) value.f1 = 1; else value.f1 = intv / 100; } else value.f1 = 1; break; case TransitionActionType.Transition: arr = str.split(","); value.s = arr[0]; if (arr.length > 1) value.i = parseInt(arr[1]); else value.i = 1; break; case TransitionActionType.Shake: arr = str.split(","); value.f1 = parseFloat(arr[0]); value.f2 = parseFloat(arr[1]); break; case TransitionActionType.ColorFilter: arr = str.split(","); value.f1 = parseFloat(arr[0]); value.f2 = parseFloat(arr[1]); value.f3 = parseFloat(arr[2]); value.f4 = parseFloat(arr[3]); break; } } } class TransitionItem { public time: number = 0; public targetId: string; public type: number = 0; public duration: number = 0; public value: TransitionValue; public startValue: TransitionValue; public endValue: TransitionValue; public easeType: (t: number) => number; public repeat: number = 0; public yoyo: boolean = false; public tween: boolean = false; public label: string; public label2: string; public hook: () => void; public hookObj: any; public hook2: () => void; public hook2Obj: any; public tweenTimes: number = 0; public tweener: createjs.Tween; public completed: boolean = false; public target: GObject; public filterCreated: boolean; public lockToken:number = 0; public constructor() { this.easeType = ParseEaseType("Quad.Out"); this.value = new TransitionValue(); this.startValue = new TransitionValue(); this.endValue = new TransitionValue(); } /**@internal */ $shake(trans:Transition, elapsedMS:number):void { trans.$shakeItem(this, elapsedMS); } } class TransitionValue { public f1: number = 0; public f2: number = 0; public f3: number = 0; public f4: number = 0; public i: number = 0; public c: number = 0; public b: boolean = false; public s: string; public b1: boolean = true; public b2: boolean = true; } }
the_stack
import { convertPoint, getOffset, getScrollOrigin, setOpacity, setPrefixedStyle, } from '../../util/Utils'; import InternalEvent from '../event/InternalEvent'; import Point from '../geometry/Point'; import InternalMouseEvent from '../event/InternalMouseEvent'; import mxClient from '../../mxClient'; import Rectangle from '../geometry/Rectangle'; import { isAltDown, isMultiTouchEvent } from '../../util/EventUtils'; import { clearSelection } from '../../util/DomUtils'; import { Graph } from '../Graph'; import { GraphPlugin } from '../../types'; import EventObject from '../event/EventObject'; import EventSource from '../event/EventSource'; /** * Event handler that selects rectangular regions. * This is not built-into [mxGraph]. * To enable rubberband selection in a graph, use the following code. */ class RubberBand implements GraphPlugin { static pluginId = 'RubberBand'; constructor(graph: Graph) { this.graph = graph; this.graph.addMouseListener(this); // Handles force rubberband event this.forceRubberbandHandler = (sender: EventSource, evt: EventObject) => { const evtName = evt.getProperty('eventName'); const me = evt.getProperty('event'); if (evtName === InternalEvent.MOUSE_DOWN && this.isForceRubberbandEvent(me)) { const offset = getOffset(this.graph.container); const origin = getScrollOrigin(this.graph.container); origin.x -= offset.x; origin.y -= offset.y; this.start(me.getX() + origin.x, me.getY() + origin.y); me.consume(false); } }; this.graph.addListener(InternalEvent.FIRE_MOUSE_EVENT, this.forceRubberbandHandler); // Repaints the marquee after autoscroll this.panHandler = () => { this.repaint(); }; this.graph.addListener(InternalEvent.PAN, this.panHandler); // Does not show menu if any touch gestures take place after the trigger this.gestureHandler = (sender: EventSource, eo: EventObject) => { if (this.first) { this.reset(); } }; this.graph.addListener(InternalEvent.GESTURE, this.gestureHandler); } forceRubberbandHandler: Function; panHandler: Function; gestureHandler: Function; graph: Graph; first: Point | null = null; destroyed: boolean = false; dragHandler: ((evt: MouseEvent) => void) | null = null; dropHandler: ((evt: MouseEvent) => void) | null = null; x = 0; y = 0; width = 0; height = 0; /** * Specifies the default opacity to be used for the rubberband div. Default is 20. */ defaultOpacity: number = 20; /** * Variable: enabled * * Specifies if events are handled. Default is true. */ enabled = true; /** * Variable: div * * Holds the DIV element which is currently visible. */ div: HTMLElement | null = null; /** * Variable: sharedDiv * * Holds the DIV element which is used to display the rubberband. */ sharedDiv: HTMLElement | null = null; /** * Variable: currentX * * Holds the value of the x argument in the last call to <update>. */ currentX = 0; /** * Variable: currentY * * Holds the value of the y argument in the last call to <update>. */ currentY = 0; /** * Optional fade out effect. Default is false. */ fadeOut = false; /** * Creates the rubberband selection shape. */ isEnabled() { return this.enabled; } /** * Function: setEnabled * * Enables or disables event handling. This implementation updates * <enabled>. */ setEnabled(enabled: boolean) { this.enabled = enabled; } /** * Function: isForceRubberbandEvent * * Returns true if the given <mxMouseEvent> should start rubberband selection. * This implementation returns true if the alt key is pressed. */ isForceRubberbandEvent(me: InternalMouseEvent) { return isAltDown(me.getEvent()); } /** * Function: mouseDown * * Handles the event by initiating a rubberband selection. By consuming the * event all subsequent events of the gesture are redirected to this * handler. */ mouseDown(sender: EventSource, me: InternalMouseEvent) { if ( !me.isConsumed() && this.isEnabled() && this.graph.isEnabled() && !me.getState() && !isMultiTouchEvent(me.getEvent()) ) { const offset = getOffset(this.graph.container); const origin = getScrollOrigin(this.graph.container); origin.x -= offset.x; origin.y -= offset.y; this.start(me.getX() + origin.x, me.getY() + origin.y); // Does not prevent the default for this event so that the // event processing chain is still executed even if we start // rubberbanding. This is required eg. in ExtJs to hide the // current context menu. In mouseMove we'll make sure we're // not selecting anything while we're rubberbanding. me.consume(false); } } /** * Creates the rubberband selection shape. */ start(x: number, y: number) { this.first = new Point(x, y); const { container } = this.graph; function createMouseEvent(evt: MouseEvent) { const me = new InternalMouseEvent(evt); const pt = convertPoint(container, me.getX(), me.getY()); me.graphX = pt.x; me.graphY = pt.y; return me; } this.dragHandler = (evt: MouseEvent) => { this.mouseMove(this.graph, createMouseEvent(evt)); }; this.dropHandler = (evt: MouseEvent) => { this.mouseUp(this.graph, createMouseEvent(evt)); }; // Workaround for rubberband stopping if the mouse leaves the container in Firefox if (mxClient.IS_FF) { InternalEvent.addGestureListeners( document, null, this.dragHandler, this.dropHandler ); } } /** * Function: mouseMove * * Handles the event by updating therubberband selection. */ mouseMove(sender: EventSource, me: InternalMouseEvent) { if (!me.isConsumed() && this.first) { const origin = getScrollOrigin(this.graph.container); const offset = getOffset(this.graph.container); origin.x -= offset.x; origin.y -= offset.y; const x = me.getX() + origin.x; const y = me.getY() + origin.y; const dx = this.first.x - x; const dy = this.first.y - y; const tol = this.graph.getEventTolerance(); if (this.div || Math.abs(dx) > tol || Math.abs(dy) > tol) { if (!this.div) { this.div = this.createShape(); } // Clears selection while rubberbanding. This is required because // the event is not consumed in mouseDown. clearSelection(); this.update(x, y); me.consume(); } } } /** * Creates the rubberband selection shape. */ createShape() { if (!this.sharedDiv) { this.sharedDiv = document.createElement('div'); this.sharedDiv.className = 'mxRubberband'; setOpacity(this.sharedDiv, this.defaultOpacity); } this.graph.container.appendChild(this.sharedDiv); const result = this.sharedDiv; if (mxClient.IS_SVG && this.fadeOut) { this.sharedDiv = null; } return result; } /** * Function: isActive * * Returns true if this handler is active. */ isActive(sender?: EventSource, me?: InternalMouseEvent) { return this.div && this.div.style.display !== 'none'; } /** * Function: mouseUp * * Handles the event by selecting the region of the rubberband using * <mxGraph.selectRegion>. */ mouseUp(sender: EventSource, me: InternalMouseEvent) { const active = this.isActive(); this.reset(); if (active) { this.execute(me.getEvent()); me.consume(); } } /** * Function: execute * * Resets the state of this handler and selects the current region * for the given event. */ execute(evt: MouseEvent) { const rect = new Rectangle(this.x, this.y, this.width, this.height); this.graph.selectRegion(rect, evt); } /** * Function: reset * * Resets the state of the rubberband selection. */ reset() { if (this.div) { if (mxClient.IS_SVG && this.fadeOut) { const temp = this.div; setPrefixedStyle(temp.style, 'transition', 'all 0.2s linear'); temp.style.pointerEvents = 'none'; temp.style.opacity = String(0); window.setTimeout(() => { if (temp.parentNode) temp.parentNode.removeChild(temp); }, 200); } else { if (this.div.parentNode) this.div.parentNode.removeChild(this.div); } } InternalEvent.removeGestureListeners( document, null, this.dragHandler, this.dropHandler ); this.dragHandler = null; this.dropHandler = null; this.currentX = 0; this.currentY = 0; this.first = null; this.div = null; } /** * Function: update * * Sets <currentX> and <currentY> and calls <repaint>. */ update(x: number, y: number) { this.currentX = x; this.currentY = y; this.repaint(); } /** * Function: repaint * * Computes the bounding box and updates the style of the <div>. */ repaint() { if (this.div && this.first) { const x = this.currentX - this.graph.getPanDx(); const y = this.currentY - this.graph.getPanDy(); this.x = Math.min(this.first.x, x); this.y = Math.min(this.first.y, y); this.width = Math.max(this.first.x, x) - this.x; this.height = Math.max(this.first.y, y) - this.y; const dx = 0; const dy = 0; this.div.style.left = `${this.x + dx}px`; this.div.style.top = `${this.y + dy}px`; this.div.style.width = `${Math.max(1, this.width)}px`; this.div.style.height = `${Math.max(1, this.height)}px`; } } /** * Function: destroy * * Destroys the handler and all its resources and DOM nodes. This does * normally not need to be called, it is called automatically when the * window unloads. */ onDestroy() { if (!this.destroyed) { this.destroyed = true; this.graph.removeMouseListener(this); this.graph.removeListener(this.forceRubberbandHandler); this.graph.removeListener(this.panHandler); this.reset(); if (this.sharedDiv) { this.sharedDiv = null; } } } } export default RubberBand;
the_stack
import { TLPageState, Utils, TLBoundsWithCenter, TLSnapLine, TLBounds } from '@tldraw/core' import { Vec } from '@tldraw/vec' import { TDShape, TDBinding, TldrawCommand, TDStatus, ArrowShape, Patch, GroupShape, SessionType, ArrowBinding, TldrawPatch, TDShapeType, } from '~types' import { SLOW_SPEED, SNAP_DISTANCE } from '~constants' import { TLDR } from '~state/TLDR' import { BaseSession } from '../BaseSession' import type { TldrawApp } from '../../internal' type CloneInfo = | { state: 'empty' } | { state: 'ready' cloneMap: Record<string, string> clones: TDShape[] clonedBindings: ArrowBinding[] } type SnapInfo = | { state: 'empty' } | { state: 'ready' others: TLBoundsWithCenter[] bounds: TLBoundsWithCenter[] } export class TranslateSession extends BaseSession { performanceMode = undefined type = SessionType.Translate status = TDStatus.Translating delta = [0, 0] prev = [0, 0] prevPoint = [0, 0] speed = 1 cloneInfo: CloneInfo = { state: 'empty', } snapInfo: SnapInfo = { state: 'empty', } snapLines: TLSnapLine[] = [] isCloning = false isCreate: boolean link: 'left' | 'right' | 'center' | false initialIds: Set<string> hasUnlockedShapes: boolean initialSelectedIds: string[] initialCommonBounds: TLBounds initialShapes: TDShape[] initialParentChildren: Record<string, string[]> bindingsToDelete: ArrowBinding[] constructor(app: TldrawApp, isCreate = false, link: 'left' | 'right' | 'center' | false = false) { super(app) this.isCreate = isCreate this.link = link const { currentPageId, selectedIds, page } = this.app this.initialSelectedIds = [...selectedIds] const selectedShapes = ( link ? TLDR.getLinkedShapeIds(this.app.state, currentPageId, link, false) : selectedIds ) .map((id) => this.app.getShape(id)) .filter((shape) => !shape.isLocked) const selectedShapeIds = new Set(selectedShapes.map((shape) => shape.id)) this.hasUnlockedShapes = selectedShapes.length > 0 this.initialShapes = Array.from( new Set( selectedShapes .filter((shape) => !selectedShapeIds.has(shape.parentId)) .flatMap((shape) => { return shape.children ? [shape, ...shape.children.map((childId) => this.app.getShape(childId))] : [shape] }) ).values() ) this.initialIds = new Set(this.initialShapes.map((shape) => shape.id)) this.bindingsToDelete = [] Object.values(page.bindings) .filter((binding) => this.initialIds.has(binding.fromId) || this.initialIds.has(binding.toId)) .forEach((binding) => { if (this.initialIds.has(binding.fromId)) { if (!this.initialIds.has(binding.toId)) { this.bindingsToDelete.push(binding) } } }) this.initialParentChildren = {} this.initialShapes .map((s) => s.parentId) .filter((id) => id !== page.id) .forEach((id) => { this.initialParentChildren[id] = this.app.getShape(id).children! }) this.initialCommonBounds = Utils.getCommonBounds(this.initialShapes.map(TLDR.getRotatedBounds)) this.app.rotationInfo.selectedIds = [...this.app.selectedIds] } start = (): TldrawPatch | undefined => { const { bindingsToDelete, initialIds, app: { currentPageId, page }, } = this const allBounds: TLBoundsWithCenter[] = [] const otherBounds: TLBoundsWithCenter[] = [] Object.values(page.shapes).forEach((shape) => { const bounds = Utils.getBoundsWithCenter(TLDR.getRotatedBounds(shape)) allBounds.push(bounds) if (!initialIds.has(shape.id)) { otherBounds.push(bounds) } }) this.snapInfo = { state: 'ready', bounds: allBounds, others: otherBounds, } if (bindingsToDelete.length === 0) return const nextBindings: Patch<Record<string, TDBinding>> = {} bindingsToDelete.forEach((binding) => (nextBindings[binding.id] = undefined)) return { document: { pages: { [currentPageId]: { bindings: nextBindings, }, }, }, } } update = (): TldrawPatch | undefined => { const { initialParentChildren, initialShapes, initialCommonBounds, bindingsToDelete, app: { pageState: { camera }, settings: { isSnapping, showGrid }, currentPageId, viewport, selectedIds, currentPoint, previousPoint, originPoint, altKey, shiftKey, metaKey, currentGrid, }, } = this const nextBindings: Patch<Record<string, TDBinding>> = {} const nextShapes: Patch<Record<string, TDShape>> = {} const nextPageState: Patch<TLPageState> = {} let delta = Vec.sub(currentPoint, originPoint) let didChangeCloning = false if (!this.isCreate) { if (altKey && !this.isCloning) { this.isCloning = true didChangeCloning = true } else if (!altKey && this.isCloning) { this.isCloning = false didChangeCloning = true } } if (shiftKey) { if (Math.abs(delta[0]) < Math.abs(delta[1])) { delta[0] = 0 } else { delta[1] = 0 } } // Should we snap? // Speed is used to decide which snap points to use. At a high // speed, we don't use any snap points. At a low speed, we only // allow center-to-center snap points. At very low speed, we // enable all snap points (still preferring middle snaps). We're // using an acceleration function here to smooth the changes in // speed, but we also want the speed to accelerate faster than // it decelerates. const speed = Vec.dist(currentPoint, previousPoint) const change = speed - this.speed this.speed = this.speed + change * (change > 1 ? 0.5 : 0.15) this.snapLines = [] if ( ((isSnapping && !metaKey) || (!isSnapping && metaKey)) && this.speed * camera.zoom < SLOW_SPEED && this.snapInfo.state === 'ready' ) { const snapResult = Utils.getSnapPoints( Utils.getBoundsWithCenter( showGrid ? Utils.snapBoundsToGrid(Utils.translateBounds(initialCommonBounds, delta), currentGrid) : Utils.translateBounds(initialCommonBounds, delta) ), (this.isCloning ? this.snapInfo.bounds : this.snapInfo.others).filter((bounds) => { return Utils.boundsContain(viewport, bounds) || Utils.boundsCollide(viewport, bounds) }), SNAP_DISTANCE / camera.zoom ) if (snapResult) { this.snapLines = snapResult.snapLines delta = Vec.sub(delta, snapResult.offset) } } // We've now calculated the "delta", or difference between the // cursor's position (real or adjusted by snaps or axis locking) // and the cursor's original position ("origin"). // The "movement" is the actual change of position between this // computed position and the previous computed position. this.prev = delta // If cloning... if (this.isCloning) { // Not Cloning -> Cloning if (didChangeCloning) { if (this.cloneInfo.state === 'empty') { this.createCloneInfo() } if (this.cloneInfo.state === 'empty') { throw Error } const { clones, clonedBindings } = this.cloneInfo this.isCloning = true // Put back any bindings we deleted bindingsToDelete.forEach((binding) => (nextBindings[binding.id] = binding)) // Move original shapes back to start initialShapes.forEach((shape) => (nextShapes[shape.id] = { point: shape.point })) // Add the clones to the page clones.forEach((clone) => { nextShapes[clone.id] = { ...clone } // Add clones to non-selected parents if (clone.parentId !== currentPageId && !selectedIds.includes(clone.parentId)) { const children = nextShapes[clone.parentId]?.children || initialParentChildren[clone.parentId] if (!children.includes(clone.id)) { nextShapes[clone.parentId] = { ...nextShapes[clone.parentId], children: [...children, clone.id], } } } }) // Add the cloned bindings for (const binding of clonedBindings) { nextBindings[binding.id] = binding } // Set the selected ids to the clones nextPageState.selectedIds = clones.map((clone) => clone.id) // Either way, move the clones clones.forEach((clone) => { nextShapes[clone.id] = { ...clone, point: showGrid ? Vec.snap(Vec.toFixed(Vec.add(clone.point, delta)), currentGrid) : Vec.toFixed(Vec.add(clone.point, delta)), } }) } else { if (this.cloneInfo.state === 'empty') throw Error const { clones } = this.cloneInfo clones.forEach((clone) => { nextShapes[clone.id] = { point: showGrid ? Vec.snap(Vec.toFixed(Vec.add(clone.point, delta)), currentGrid) : Vec.toFixed(Vec.add(clone.point, delta)), } }) } } else { // If not cloning... // Cloning -> Not Cloning if (didChangeCloning) { if (this.cloneInfo.state === 'empty') throw Error const { clones, clonedBindings } = this.cloneInfo this.isCloning = false // Delete the bindings bindingsToDelete.forEach((binding) => (nextBindings[binding.id] = undefined)) // Remove the clones from parents clones.forEach((clone) => { if (clone.parentId !== currentPageId) { nextShapes[clone.parentId] = { ...nextShapes[clone.parentId], children: initialParentChildren[clone.parentId], } } }) // Delete the clones (including any parent clones) clones.forEach((clone) => (nextShapes[clone.id] = undefined)) // Move the original shapes back to the cursor position initialShapes.forEach((shape) => { nextShapes[shape.id] = { point: showGrid ? Vec.snap(Vec.toFixed(Vec.add(shape.point, delta)), currentGrid) : Vec.toFixed(Vec.add(shape.point, delta)), } }) // Delete the cloned bindings for (const binding of clonedBindings) { nextBindings[binding.id] = undefined } // Set selected ids nextPageState.selectedIds = initialShapes.map((shape) => shape.id) } else { // Move the shapes by the delta initialShapes.forEach((shape) => { // const current = (nextShapes[shape.id] || this.app.getShape(shape.id)) as TDShape nextShapes[shape.id] = { point: showGrid ? Vec.snap(Vec.toFixed(Vec.add(shape.point, delta)), currentGrid) : Vec.toFixed(Vec.add(shape.point, delta)), } }) } } return { appState: { snapLines: this.snapLines, }, document: { pages: { [currentPageId]: { shapes: nextShapes, bindings: nextBindings, }, }, pageStates: { [currentPageId]: nextPageState, }, }, } } cancel = (): TldrawPatch | undefined => { const { initialShapes, initialSelectedIds, bindingsToDelete, app: { currentPageId }, } = this const nextBindings: Record<string, Partial<TDBinding> | undefined> = {} const nextShapes: Record<string, Partial<TDShape> | undefined> = {} const nextPageState: Partial<TLPageState> = { editingId: undefined, hoveredId: undefined, } // Put back any deleted bindings bindingsToDelete.forEach((binding) => (nextBindings[binding.id] = binding)) if (this.isCreate) { initialShapes.forEach(({ id }) => (nextShapes[id] = undefined)) nextPageState.selectedIds = [] } else { // Put initial shapes back to where they started initialShapes.forEach(({ id, point }) => (nextShapes[id] = { ...nextShapes[id], point })) nextPageState.selectedIds = initialSelectedIds } if (this.cloneInfo.state === 'ready') { const { clones, clonedBindings } = this.cloneInfo // Delete clones clones.forEach((clone) => (nextShapes[clone.id] = undefined)) // Delete cloned bindings clonedBindings.forEach((binding) => (nextBindings[binding.id] = undefined)) } return { appState: { snapLines: [], }, document: { pages: { [currentPageId]: { shapes: nextShapes, bindings: nextBindings, }, }, pageStates: { [currentPageId]: nextPageState, }, }, } } complete = (): TldrawPatch | TldrawCommand | undefined => { const { initialShapes, initialParentChildren, bindingsToDelete, app: { currentPageId }, } = this const beforeBindings: Patch<Record<string, TDBinding>> = {} const beforeShapes: Patch<Record<string, TDShape>> = {} const afterBindings: Patch<Record<string, TDBinding>> = {} const afterShapes: Patch<Record<string, TDShape>> = {} if (this.isCloning) { if (this.cloneInfo.state === 'empty') { this.createCloneInfo() } if (this.cloneInfo.state !== 'ready') throw Error const { clones, clonedBindings } = this.cloneInfo // Update the clones clones.forEach((clone) => { beforeShapes[clone.id] = undefined afterShapes[clone.id] = this.app.getShape(clone.id) if (clone.parentId !== currentPageId) { beforeShapes[clone.parentId] = { ...beforeShapes[clone.parentId], children: initialParentChildren[clone.parentId], } afterShapes[clone.parentId] = { ...afterShapes[clone.parentId], children: this.app.getShape<GroupShape>(clone.parentId).children, } } }) // Update the cloned bindings clonedBindings.forEach((binding) => { beforeBindings[binding.id] = undefined afterBindings[binding.id] = this.app.getBinding(binding.id) }) } else { // If we aren't cloning, then update the initial shapes initialShapes.forEach((shape) => { beforeShapes[shape.id] = this.isCreate ? undefined : { ...beforeShapes[shape.id], point: shape.point, } afterShapes[shape.id] = { ...afterShapes[shape.id], ...(this.isCreate ? this.app.getShape(shape.id) : { point: this.app.getShape(shape.id).point }), } }) } // Update the deleted bindings and any associated shapes bindingsToDelete.forEach((binding) => { beforeBindings[binding.id] = binding for (const id of [binding.toId, binding.fromId]) { // Let's also look at the bound shape... const shape = this.app.getShape(id) // If the bound shape has a handle that references the deleted binding, delete that reference if (!shape.handles) continue Object.values(shape.handles) .filter((handle) => handle.bindingId === binding.id) .forEach((handle) => { beforeShapes[id] = { ...beforeShapes[id], handles: {} } afterShapes[id] = { ...afterShapes[id], handles: {} } // There should be before and after shapes // eslint-disable-next-line @typescript-eslint/no-non-null-assertion beforeShapes[id]!.handles![handle.id as keyof ArrowShape['handles']] = { bindingId: binding.id, } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion afterShapes[id]!.handles![handle.id as keyof ArrowShape['handles']] = { bindingId: undefined, } }) } }) return { id: 'translate', before: { appState: { snapLines: [], }, document: { pages: { [currentPageId]: { shapes: beforeShapes, bindings: beforeBindings, }, }, pageStates: { [currentPageId]: { selectedIds: this.isCreate ? [] : [...this.initialSelectedIds], }, }, }, }, after: { appState: { snapLines: [], }, document: { pages: { [currentPageId]: { shapes: afterShapes, bindings: afterBindings, }, }, pageStates: { [currentPageId]: { selectedIds: [...this.app.selectedIds], }, }, }, }, } } private createCloneInfo = () => { // Create clones when as they're needed. // Consider doing this work in a worker. const { initialShapes, initialParentChildren, app: { selectedIds, currentPageId, page }, } = this const cloneMap: Record<string, string> = {} const clonedBindingsMap: Record<string, string> = {} const clonedBindings: TDBinding[] = [] // Create clones of selected shapes const clones: TDShape[] = [] initialShapes.forEach((shape) => { const newId = Utils.uniqueId() initialParentChildren[newId] = initialParentChildren[shape.id] cloneMap[shape.id] = newId const clone = { ...Utils.deepClone(shape), id: newId, parentId: shape.parentId, childIndex: TLDR.getChildIndexAbove(this.app.state, shape.id, currentPageId), } if (clone.type === TDShapeType.Video) { const element = document.getElementById(shape.id + '_video') as HTMLVideoElement if (element) clone.currentTime = (element.currentTime + 16) % element.duration } clones.push(clone) }) clones.forEach((clone) => { if (clone.children !== undefined) { clone.children = clone.children.map((childId) => cloneMap[childId]) } }) clones.forEach((clone) => { if (selectedIds.includes(clone.parentId)) { clone.parentId = cloneMap[clone.parentId] } }) // Potentially confusing name here: these are the ids of the // original shapes that were cloned, not their clones' ids. const clonedShapeIds = new Set(Object.keys(cloneMap)) // Create cloned bindings for shapes where both to and from shapes are selected // (if the user clones, then we will create a new binding for the clones) Object.values(page.bindings) .filter((binding) => clonedShapeIds.has(binding.fromId) || clonedShapeIds.has(binding.toId)) .forEach((binding) => { if (clonedShapeIds.has(binding.fromId)) { if (clonedShapeIds.has(binding.toId)) { const cloneId = Utils.uniqueId() const cloneBinding = { ...Utils.deepClone(binding), id: cloneId, fromId: cloneMap[binding.fromId] || binding.fromId, toId: cloneMap[binding.toId] || binding.toId, } clonedBindingsMap[binding.id] = cloneId clonedBindings.push(cloneBinding) } } }) // Assign new binding ids to clones (or delete them!) clones.forEach((clone) => { if (clone.handles) { if (clone.handles) { for (const id in clone.handles) { const handle = clone.handles[id as keyof ArrowShape['handles']] handle.bindingId = handle.bindingId ? clonedBindingsMap[handle.bindingId] : undefined } } } }) clones.forEach((clone) => { if (page.shapes[clone.id]) { throw Error("uh oh, we didn't clone correctly") } }) this.cloneInfo = { state: 'ready', clones, cloneMap, clonedBindings, } } }
the_stack
import { Meteor } from 'meteor/meteor' import { BulkWriteOperation, BulkWriteOpResultObject } from 'mongodb' import _ from 'underscore' import { DBObj, waitForPromise, normalizeArrayToMap, ProtectedString, makePromise, sleep, deleteAllUndefinedProperties, } from '../../lib/lib' import { TransformedCollection, MongoQuery, FindOptions, MongoModifier, UpdateOptions, UpsertOptions, FindOneOptions, } from '../../lib/typings/meteor' import { profiler } from '../api/profiler' export interface Changes { added: number updated: number removed: number } export interface ChangedIds<T extends ProtectedString<any>> { added: T[] updated: T[] removed: T[] unchanged: T[] } export function sumChanges(...changes: (Changes | ChangedIds<any> | null)[]): Changes { let change: Changes = { added: 0, updated: 0, removed: 0, } _.each(changes, (c) => { if (c) { change.added += Array.isArray(c.added) ? c.added.length : c.added change.updated += Array.isArray(c.updated) ? c.updated.length : c.updated change.removed += Array.isArray(c.removed) ? c.removed.length : c.removed } }) return change } export function anythingChanged(changes: Changes): boolean { return !!(changes.added || changes.removed || changes.updated) } /** * Saves an array of data into a collection * No matter if the data needs to be created, updated or removed * @param collection The collection to be updated * @param filter The filter defining the data subset to be affected in db * @param newData The new data */ export function saveIntoDb<DocClass extends DBInterface, DBInterface extends DBObj>( collection: TransformedCollection<DocClass, DBInterface>, filter: MongoQuery<DBInterface>, newData: Array<DBInterface>, options?: SaveIntoDbHooks<DocClass, DBInterface> ): Changes { const preparedChanges = prepareSaveIntoDb(collection, filter, newData, options) const changes = savePreparedChanges(preparedChanges, collection, options ?? {}) return waitForPromise(changes) } export interface PreparedChanges<T> { inserted: T[] changed: T[] removed: T[] unchanged: T[] } function prepareSaveIntoDb<DocClass extends DBInterface, DBInterface extends DBObj>( collection: TransformedCollection<DocClass, DBInterface>, filter: MongoQuery<DBInterface>, newData: Array<DBInterface>, optionsOrg?: SaveIntoDbHooks<DocClass, DBInterface> ): PreparedChanges<DBInterface> { const preparedChanges: PreparedChanges<DBInterface> = { inserted: [], changed: [], removed: [], unchanged: [], } saveIntoBase((collection as any)._name, collection.find(filter).fetch(), newData, { ...optionsOrg, insert: (doc) => preparedChanges.inserted.push(doc), update: (doc) => preparedChanges.changed.push(doc), remove: (doc) => preparedChanges.removed.push(doc), unchanged: (doc) => preparedChanges.unchanged.push(doc), // supress hooks that are for the save phase afterInsert: undefined, afterRemove: undefined, afterRemoveAll: undefined, afterUpdate: undefined, }) return preparedChanges } async function savePreparedChanges<DocClass extends DBInterface, DBInterface extends DBObj>( preparedChanges: PreparedChanges<DBInterface>, collection: TransformedCollection<DocClass, DBInterface>, options: SaveIntoDbHooks<DocClass, DBInterface> ): Promise<Changes> { let change: Changes = { added: 0, updated: 0, removed: 0, } const newObjIds: { [identifier: string]: true } = {} const checkInsertId = (id) => { if (newObjIds[id]) { throw new Meteor.Error( 500, `savePreparedChanges into collection "${(collection as any)._name}": Duplicate identifier "${id}"` ) } newObjIds[id] = true } const updates: BulkWriteOperation<DBInterface>[] = [] const removedDocs: DocClass['_id'][] = [] _.each(preparedChanges.changed || [], (oUpdate) => { checkInsertId(oUpdate._id) updates.push({ replaceOne: { filter: { _id: oUpdate._id as any, }, replacement: oUpdate, }, }) change.updated++ if (options.afterUpdate) options.afterUpdate(oUpdate) }) _.each(preparedChanges.inserted || [], (oInsert) => { checkInsertId(oInsert._id) updates.push({ replaceOne: { filter: { _id: oInsert._id as any, }, replacement: oInsert, upsert: true, }, }) change.added++ if (options.afterInsert) options.afterInsert(oInsert) }) _.each(preparedChanges.removed || [], (oRemove) => { removedDocs.push(oRemove._id) change.removed++ if (options.afterRemove) options.afterRemove(oRemove) }) if (removedDocs.length) { updates.push({ deleteMany: { filter: { _id: { $in: removedDocs as any }, }, }, }) } const pBulkWriteResult = updates.length > 0 ? asyncCollectionBulkWrite(collection, updates) : null await pBulkWriteResult if (options.afterRemoveAll) { const objs = _.compact(preparedChanges.removed || []) if (objs.length > 0) { options.afterRemoveAll(objs) } } return change } export interface SaveIntoDbHooks<DocClass, DBInterface> { beforeInsert?: (o: DBInterface) => DBInterface beforeUpdate?: (o: DBInterface, pre?: DocClass) => DBInterface beforeRemove?: (o: DocClass) => DBInterface beforeDiff?: (o: DBInterface, oldObj: DocClass) => DBInterface afterInsert?: (o: DBInterface) => void afterUpdate?: (o: DBInterface) => void afterRemove?: (o: DBInterface) => void afterRemoveAll?: (o: Array<DBInterface>) => void } interface SaveIntoDbHandlers<DBInterface> { insert: (o: DBInterface) => void update: (o: DBInterface) => void remove: (o: DBInterface) => void unchanged?: (o: DBInterface) => void } export function saveIntoBase<DocClass extends DBInterface, DBInterface extends DBObj>( collectionName: string, oldDocs: DocClass[], newData: Array<DBInterface>, options: SaveIntoDbHooks<DocClass, DBInterface> & SaveIntoDbHandlers<DBInterface> ): ChangedIds<DBInterface['_id']> { const span = profiler.startSpan(`DBCache.saveIntoBase.${collectionName}`) const changes: ChangedIds<DBInterface['_id']> = { added: [], updated: [], removed: [], unchanged: [], } const newObjIds = new Set<DBInterface['_id']>() _.each(newData, (o) => { if (newObjIds.has(o._id)) { throw new Meteor.Error( 500, `saveIntoBase into collection "${collectionName}": Duplicate identifier _id: "${o._id}"` ) } newObjIds.add(o._id) }) const objectsToRemove = normalizeArrayToMap(oldDocs, '_id') for (const o of newData) { // const span2 = profiler.startSpan(`DBCache.saveIntoBase.${collectionName}.do.${o._id}`) const oldObj = objectsToRemove.get(o._id) if (oldObj) { const o2 = options.beforeDiff ? options.beforeDiff(o, oldObj) : o deleteAllUndefinedProperties(o2) const eql = _.isEqual(oldObj, o2) if (!eql) { const oUpdate = options.beforeUpdate ? options.beforeUpdate(o, oldObj) : o options.update(oUpdate) if (options.afterUpdate) options.afterUpdate(oUpdate) changes.updated.push(oUpdate._id) } else { if (options.unchanged) options.unchanged(o) changes.unchanged.push(oldObj._id) } } else { const oInsert = options.beforeInsert ? options.beforeInsert(o) : o options.insert(oInsert) if (options.afterInsert) options.afterInsert(oInsert) changes.added.push(oInsert._id) } objectsToRemove.delete(o._id) // span2?.end() } for (const obj of objectsToRemove.values()) { if (obj) { const oRemove = options.beforeRemove ? options.beforeRemove(obj) : obj options.remove(oRemove) if (options.afterRemove) options.afterRemove(oRemove) changes.removed.push(oRemove._id) } } if (options.afterRemoveAll) { const objs = _.compact(Array.from(objectsToRemove.values())) if (objs.length > 0) { options.afterRemoveAll(objs) } } span?.addLabels(changes as any) span?.end() return changes } export async function asyncCollectionFindFetch< DocClass extends DBInterface, DBInterface extends { _id: ProtectedString<any> } >( collection: TransformedCollection<DocClass, DBInterface>, selector: MongoQuery<DBInterface> | string, options?: FindOptions<DBInterface> ): Promise<Array<DocClass>> { // Make the collection fethcing in another Fiber: const p = makePromise(() => { return collection.find(selector as any, options).fetch() }) // Pause the current Fiber briefly, in order to allow for the other Fiber to start executing: await sleep(0) return p } export async function asyncCollectionFindOne< DocClass extends DBInterface, DBInterface extends { _id: ProtectedString<any> } >( collection: TransformedCollection<DocClass, DBInterface>, selector: MongoQuery<DBInterface> | DBInterface['_id'], options?: FindOneOptions<DBInterface> ): Promise<DocClass | undefined> { const arr = await asyncCollectionFindFetch(collection, selector, { ...options, limit: 1 }) return arr[0] } export async function asyncCollectionInsert< DocClass extends DBInterface, DBInterface extends { _id: ProtectedString<any> } >(collection: TransformedCollection<DocClass, DBInterface>, doc: DBInterface): Promise<DBInterface['_id']> { const p = makePromise(() => { return collection.insert(doc) }) // Pause the current Fiber briefly, in order to allow for the other Fiber to start executing: await sleep(0) return p } export function asyncCollectionInsertMany< DocClass extends DBInterface, DBInterface extends { _id: ProtectedString<any> } >(collection: TransformedCollection<DocClass, DBInterface>, docs: DBInterface[]): Promise<Array<DBInterface['_id']>> { return Promise.all(_.map(docs, (doc) => asyncCollectionInsert(collection, doc))) } /** Insert document, and ignore if document already exists */ export async function asyncCollectionInsertIgnore< DocClass extends DBInterface, DBInterface extends { _id: ProtectedString<any> } >(collection: TransformedCollection<DocClass, DBInterface>, doc: DBInterface): Promise<DBInterface['_id']> { const p = makePromise(() => { return collection.insert(doc) }).catch((err) => { if (err.toString().match(/duplicate key/i)) { // @ts-ignore id duplicate, doc._id must exist return doc._id } else { throw err } }) // Pause the current Fiber briefly, in order to allow for the other Fiber to start executing: await sleep(0) return p } export async function asyncCollectionUpdate< DocClass extends DBInterface, DBInterface extends { _id: ProtectedString<any> } >( collection: TransformedCollection<DocClass, DBInterface>, selector: MongoQuery<DBInterface> | DBInterface['_id'], modifier: MongoModifier<DBInterface>, options?: UpdateOptions ): Promise<number> { const p = makePromise(() => { return collection.update(selector, modifier, options) }) // Pause the current Fiber briefly, in order to allow for the other Fiber to start executing: await sleep(0) return p } export async function asyncCollectionUpsert< DocClass extends DBInterface, DBInterface extends { _id: ProtectedString<any> } >( collection: TransformedCollection<DocClass, DBInterface>, selector: MongoQuery<DBInterface> | DBInterface['_id'], modifier: MongoModifier<DBInterface>, options?: UpsertOptions ): Promise<{ numberAffected?: number; insertedId?: DBInterface['_id'] }> { const p = makePromise(() => { return collection.upsert(selector, modifier, options) }) // Pause the current Fiber briefly, in order to allow for the other Fiber to start executing: await sleep(0) return p } export async function asyncCollectionRemove< DocClass extends DBInterface, DBInterface extends { _id: ProtectedString<any> } >( collection: TransformedCollection<DocClass, DBInterface>, selector: MongoQuery<DBInterface> | DBInterface['_id'] ): Promise<number> { const p = makePromise(() => { return collection.remove(selector) }) // Pause the current Fiber briefly, in order to allow for the other Fiber to start executing: await sleep(0) return p } export async function asyncCollectionBulkWrite< DocClass extends DBInterface, DBInterface extends { _id: ProtectedString<any> } >( collection: TransformedCollection<DocClass, DBInterface>, ops: Array<BulkWriteOperation<DBInterface>> ): Promise<BulkWriteOpResultObject> { if (ops.length > 0) { const rawCollection = collection.rawCollection() const bulkWriteResult = await rawCollection.bulkWrite(ops, { ordered: false, }) if ( bulkWriteResult && _.isArray(bulkWriteResult.result?.writeErrors) && bulkWriteResult.result.writeErrors.length ) { throw new Meteor.Error( 500, `Errors in rawCollection.bulkWrite: ${bulkWriteResult.result.writeErrors.join(',')}` ) } return bulkWriteResult } else { return {} } }
the_stack
declare module 'react-native-onesignal' { /* O P T I O N T Y P E V A L U E S */ // 0 = None, 1 = Fatal, 2 = Errors, 3 = Warnings, 4 = Info, 5 = Debug, 6 = Verbose export type LogLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6; // 0 = NotDetermined, 1 = Denied, 2 = Authorized, 3 = Provisional, 4 = Ephemeral export type IosPermissionStatus = 0 | 1 | 2 | 3 | 4; // 0 = NotificationClicked, 1 = ButtonClicked export type OpenedEventActionType = 0 | 1; /* O B S E R V E R C H A N G E E V E N T S */ export interface ChangeEvent<T> { from : T; to : T; } export interface PermissionChange { status ?: IosPermissionStatus; // ios hasPrompted ?: boolean; // ios provisional ?: boolean; // ios areNotificationsEnabled ?: boolean; // android }; export interface SubscriptionChange { userId ?: string; pushToken ?: string; isSubscribed : boolean; isPushDisabled : boolean; }; export interface EmailSubscriptionChange { emailAddress ?: string; emailUserId ?: string; isEmailSubscribed : boolean; }; export interface SMSSubscriptionChange { smsNumber ?: string; smsUserId ?: string; isSMSSubscribed : boolean; }; /* N O T I F I C A T I O N S */ export interface OSNotification { body : string; sound ?: string; title ?: string; launchURL ?: string; rawPayload : object | string; // platform bridges return different types actionButtons ?: object[]; additionalData : object; notificationId : string; // android only groupKey ?: string; groupMessage ?: string; ledColor ?: string; priority ?: number; smallIcon ?: string; largeIcon ?: string; bigPicture ?: string; collapseId ?: string; fromProjectNumber ?: string; smallIconAccentColor ?: string; lockScreenVisibility ?: string; androidNotificationId ?: number; // ios only badge ?: string; badgeIncrement ?: string; category ?: string; threadId ?: string; subtitle ?: string; templateId ?: string; templateName ?: string; attachments ?: object; mutableContent ?: boolean; contentAvailable ?: string; relevanceScore ?: number; interruptionLevel ?: string; } /* N O T I F I C A T I O N & I A M E V E N T S */ export interface NotificationReceivedEvent { complete : (notification?: OSNotification) => void; getNotification : () => OSNotification; }; export interface OpenedEvent { action : OpenedEventAction; notification : OSNotification; } export interface OpenedEventAction { type : OpenedEventActionType } export interface InAppMessageAction { closes_message : boolean; first_click : boolean; click_name ?: string; click_url ?: string; outcomes ?: object[]; tags ?: object; } export interface OutcomeEvent { session : string; id : string; timestamp : number; weight : number; notification_ids: string[]; } /* D E V I C E */ export interface DeviceState { userId : string; pushToken : string; emailUserId : string; emailAddress : string; smsUserId : string; smsNumber : string; isSubscribed : boolean; isPushDisabled : boolean; isEmailSubscribed : boolean; isSMSSubscribed : boolean; hasNotificationPermission ?: boolean; // is areNotificationsEnabled on android notificationPermissionStatus ?: IosPermissionStatus; // ios only // areNotificationsEnabled (android) not included since it is converted to hasNotificationPermission in bridge } /* O N E S I G N A L I N T E R F A C E */ export interface OneSignal { /** * Completes OneSignal initialization by setting the OneSignal Application ID. * @param {string} appId * @returns void */ setAppId(appId: string): void; /** * Add a callback that fires when the native push permission changes. * @param {(event:ChangeEvent<PermissionChange>)=>void} observer * @returns void */ addPermissionObserver(observer: (event: ChangeEvent<PermissionChange>) => void): void; /** * Clears current permission observers. * @returns void */ clearPermissionObservers(): void; /** * Add a callback that fires when the OneSignal subscription state changes. * @param {(event:ChangeEvent<SubscriptionChange>)=>void} observer * @returns void */ addSubscriptionObserver(observer: (event: ChangeEvent<SubscriptionChange>) => void): void; /** * Clears current subscription observers. * @returns void */ clearSubscriptionObservers(): void; /** * Add a callback that fires when the OneSignal email subscription changes. * @param {(event:ChangeEvent<EmailSubscriptionChange>)=>void} observer * @returns void */ addEmailSubscriptionObserver(observer: (event: ChangeEvent<EmailSubscriptionChange>) => void): void; /** * Clears current email subscription observers. * @returns void */ clearEmailSubscriptionObservers(): void; /** * Add a callback that fires when the OneSignal sms subscription changes. * @param {(event:ChangeEvent<SMSSubscriptionChange>)=>void} observer * @returns void */ addSMSSubscriptionObserver(observer: (event: ChangeEvent<SMSSubscriptionChange>) => void): void; /** * Clears current SMS subscription observers. * @returns void */ clearSMSSubscriptionObservers(): void; /** * Set the callback to run just before displaying a notification while the app is in focus. * @param {(event:NotificationReceivedEvent)=>void} handler * @returns void */ setNotificationWillShowInForegroundHandler(handler: (event: NotificationReceivedEvent) => void): void; /** * Set the callback to run on notification open. * @param {(openedEvent:OpenedEvent)=>void} handler * @returns void */ setNotificationOpenedHandler(handler: (openedEvent: OpenedEvent) => void): void; /** * Prompts the iOS user for push notifications. * @param {(response:boolean)=>void} handler * @returns void */ promptForPushNotificationsWithUserResponse(handler: (response: boolean) => void): void; /** * Only applies to iOS (does nothing on Android as it always silently registers) * Request for Direct-To-History push notification authorization * * For more information: https://documentation.onesignal.com/docs/ios-customizations#provisional-push-notifications * * @param {(response:boolean)=>void} handler * @returns void */ registerForProvisionalAuthorization(handler?: (response: boolean) => void): void; /** * Disable the push notification subscription to OneSignal. * @param {boolean} disable * @returns void */ disablePush(disable: boolean): void; /** * Android Only. If notifications are disabled for your application, unsubscribe the user from OneSignal. * @param {boolean} unsubscribe * @returns void */ unsubscribeWhenNotificationsAreDisabled(unsubscribe: boolean): void; /** * True if the application has location share activated, false otherwise * @returns Promise<boolean> */ isLocationShared(): Promise<boolean>; /** * Disable or enable location collection (defaults to enabled if your app has location permission). * @param {boolean} shared * @returns void */ setLocationShared(shared: boolean): void; /** * Prompts the user for location permissions to allow geotagging from the OneSignal dashboard. * @returns void */ promptLocation(): void; /** * This method returns a "snapshot" of the device state for when it was called. * @returns Promise<DeviceState> */ getDeviceState(): Promise<DeviceState>; /** * Allows you to set the app defined language with the OneSignal SDK. * @param {string} language * @returns void */ setLanguage(language: string): void; /** * Tag a user based on an app event of your choosing so they can be targeted later via segments. * @param {string} key * @param {string} value * @returns void */ sendTag(key: string, value: string): void; /** * Tag a user wiht multiple tags based on an app event of your choosing so they can be targeted later via segments. * @param {object} tags * @returns void */ sendTags(tags: object): void; /** * Retrieve a list of tags that have been set on the user from the OneSignal server. * @param {(tags:object)=>void} handler * @returns void */ getTags(handler: (tags: object) => void): void; /** * Deletes a single tag that was previously set on a user. * @param {string} key * @returns void */ deleteTag(key: string): void; /** * Deletes multiple tags that were previously set on a user. * @param {string[]} keys */ deleteTags(keys: string[]); /** * Allows you to set the user's email address with the OneSignal SDK. * @param {string} email * @param {string} authCode * @param {Function} handler * @returns void */ setEmail(email: string, authCode?: string, handler?: Function): void; /** * If your app implements logout functionality, you can call logoutEmail to dissociate the email from the device. * @param {Function} handler */ logoutEmail(handler?: Function); /** * Allows you to set the user's SMS number with the OneSignal SDK. * @param {string} smsNumber * @param {string} authCode * @param {Function} handler * @returns void */ setSMSNumber(smsNumber: string, authCode?: string, handler?: Function): void; /** * If your app implements logout functionality, you can call logoutSMSNumber to dissociate the SMS number from the device. * @param {Function} handler */ logoutSMSNumber(handler?: Function); /** * Send a notification * @param {string} notificationObjectString - JSON string payload (see REST API reference) * @param {(success:object)=>void} onSuccess * @param {(failure:object)=>void} onFailure * @returns void */ postNotification(notificationObjectString: string, onSuccess?: (success: object) => void, onFailure?: (failure: object) => void): void; /** * Android Only. iOS provides a standard way to clear notifications by clearing badge count. * @returns void */ clearOneSignalNotifications(): void; /** * Removes a single OneSignal notification based on its Android notification integer id. * @param {number} id - notification id to cancel * @returns void */ removeNotification(id: number): void; /** * Removes all OneSignal notifications based on its Android notification group Id. * @param {string} id - notification group id to cancel * @returns void */ removeGroupedNotifications(id: string): void; /** * Allows you to use your own system's user ID's to send push notifications to your users. * @param {string} externalId * @param {(results:object)=>void} handler * @returns void */ setExternalUserId(externalId: string, handlerOrAuth?: ((results: object) => void) | string, handler?: (results: object) => void): void; /** * Removes whatever was set as the current user's external user ID. * @param {(results:object)=>void} handler * @returns void */ removeExternalUserId(handler?: (results: object) => void): void; /** * Sets an In-App Message click event handler. * @param {(action:InAppMessageAction)=>void} handler * @returns void */ setInAppMessageClickHandler(handler: (action: InAppMessageAction) => void): void; /** * Add an In-App Message Trigger. * @param {string} key * @param {string} value * @returns void */ addTrigger(key: string, value: string): void; /** * Adds Multiple In-App Message Triggers. * @param {object} triggers * @returns void */ addTriggers(triggers: object): void; /** * Removes a list of triggers based on a collection of keys. * @param {string[]} keys * @returns void */ removeTriggersForKeys(keys: string[]): void; /** * Removes a list of triggers based on a key. * @param {string} key * @returns void */ removeTriggerForKey(key: string): void; /** * Gets a trigger value for a provided trigger key. * @param {string} key * @returns void */ getTriggerValueForKey(key: string): Promise<string>; /** * Pause & unpause In-App Messages * @param {boolean} pause * @returns void */ pauseInAppMessages(pause: boolean): void; /** * Increases the "Count" of this Outcome by 1 and will be counted each time sent. * @param {string} name * @param {(event:OutcomeEvent)=>void} handler * @returns void */ sendOutcome(name: string, handler?: (event: OutcomeEvent) => void): void; /** * Increases "Count" by 1 only once. This can only be attributed to a single notification. * @param {string} name * @param {(event:OutcomeEvent)=>void} handler * @returns void */ sendUniqueOutcome(name: string, handler?: (event: OutcomeEvent) => void): void; /** * Increases the "Count" of this Outcome by 1 and the "Sum" by the value. Will be counted each time sent. * If the method is called outside of an attribution window, it will be unattributed until a new session occurs. * @param {string} name * @param {string|number} value * @param {(event:OutcomeEvent)=>void} handler * @returns void */ sendOutcomeWithValue(name: string, value: string|number, handler?: (event: OutcomeEvent) => void): void; /** * Enable logging to help debug if you run into an issue setting up OneSignal. * @param {LogLevel} nsLogLevel - Sets the logging level to print to the Android LogCat log or Xcode log. * @param {LogLevel} visualLogLevel - Sets the logging level to show as alert dialogs. * @returns void */ setLogLevel(nsLogLevel: LogLevel, visualLogLevel: LogLevel): void; /** * Clears all handlers and observers. * @returns void */ clearHandlers(): void; /** * Did the user provide privacy consent for GDPR purposes. * @returns Promise<boolean> */ userProvidedPrivacyConsent(): Promise<boolean>; /** * True if the application requires user privacy consent, false otherwise * @returns Promise<boolean> */ requiresUserPrivacyConsent(): Promise<boolean>; /** * For GDPR users, your application should call this method before setting the App ID. * @param {boolean} required * @returns void */ setRequiresUserPrivacyConsent(required: boolean): void; /** * If your application is set to require the user's privacy consent, you can provide this consent using this method. * @param {boolean} granted * @returns void */ provideUserConsent(granted: boolean): void; } const OneSignal: OneSignal; export default OneSignal; }
the_stack
import 'chrome://resources/cr_components/managed_dialog/managed_dialog.js'; import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_link_row/cr_link_row.js'; import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/cr_elements/md_select_css.m.js'; import '../controls/controlled_radio_button.js'; import '../controls/extension_controlled_indicator.js'; import '../controls/settings_radio_group.js'; import '../controls/settings_toggle_button.js'; import '../settings_page/settings_animated_pages.js'; import '../settings_page/settings_subpage.js'; import '../settings_shared_css.js'; import '../settings_vars_css.js'; import './home_url_input.js'; import '../controls/settings_dropdown_menu.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {BaseMixin} from '../base_mixin.js'; import {DropdownMenuOptionList} from '../controls/settings_dropdown_menu.js'; import {SettingsDropdownMenuElement} from '../controls/settings_dropdown_menu.js'; import {loadTimeData} from '../i18n_setup.js'; import {AppearancePageVisibility} from '../page_visibility.js'; import {PrefsMixin} from '../prefs/prefs_mixin.js'; import {routes} from '../route.js'; import {Router} from '../router.js'; import {AppearanceBrowserProxy, AppearanceBrowserProxyImpl} from './appearance_browser_proxy.js'; /** * This is the absolute difference maintained between standard and * fixed-width font sizes. http://crbug.com/91922. */ const SIZE_DIFFERENCE_FIXED_STANDARD: number = 3; /** * ID for autogenerated themes. Should match * |ThemeService::kAutogeneratedThemeID|. */ const AUTOGENERATED_THEME_ID: string = 'autogenerated_theme_id'; /** * 'settings-appearance-page' is the settings page containing appearance * settings. */ interface SettingsAppearancePageElement { $: { defaultFontSize: SettingsDropdownMenuElement, zoomLevel: HTMLSelectElement, }; } const SettingsAppearancePageElementBase = I18nMixin(PrefsMixin(BaseMixin(PolymerElement))); class SettingsAppearancePageElement extends SettingsAppearancePageElementBase { static get is() { return 'settings-appearance-page'; } static get template() { return html`{__html_template__}`; } static get properties() { return { /** * Dictionary defining page visibility. */ pageVisibility: Object, prefs: { type: Object, notify: true, }, defaultZoom_: Number, isWallpaperPolicyControlled_: {type: Boolean, value: true}, /** * List of options for the font size drop-down menu. */ fontSizeOptions_: { readOnly: true, type: Array, value() { return [ {value: 9, name: loadTimeData.getString('verySmall')}, {value: 12, name: loadTimeData.getString('small')}, {value: 16, name: loadTimeData.getString('medium')}, {value: 20, name: loadTimeData.getString('large')}, {value: 24, name: loadTimeData.getString('veryLarge')}, ]; }, }, /** * Predefined zoom factors to be used when zooming in/out. These are in * ascending order. Values are displayed in the page zoom drop-down menu * as percentages. */ pageZoomLevels_: Array, themeSublabel_: String, themeUrl_: String, useSystemTheme_: { type: Boolean, value: false, // Can only be true on Linux, but value exists everywhere. }, focusConfig_: { type: Object, value() { const map = new Map(); if (routes.FONTS) { map.set(routes.FONTS.path, '#customize-fonts-subpage-trigger'); } return map; }, }, showReaderModeOption_: { type: Boolean, value() { return loadTimeData.getBoolean('showReaderModeOption'); }, }, isForcedTheme_: { type: Boolean, computed: 'computeIsForcedTheme_(' + 'prefs.autogenerated.theme.policy.color.controlledBy)', }, // <if expr="is_linux and not chromeos and not lacros"> /** * Whether to show the "Custom Chrome Frame" setting. */ showCustomChromeFrame_: { type: Boolean, value() { return loadTimeData.getBoolean('showCustomChromeFrame'); }, }, // </if> showManagedThemeDialog_: Boolean, }; } static get observers() { return [ 'defaultFontSizeChanged_(prefs.webkit.webprefs.default_font_size.value)', 'themeChanged_(' + 'prefs.extensions.theme.id.value, useSystemTheme_, isForcedTheme_)', // <if expr="is_linux and not chromeos"> // NOTE: this pref only exists on Linux. 'useSystemThemePrefChanged_(prefs.extensions.theme.use_system.value)', // </if> ]; } pageVisibility: AppearancePageVisibility; private defaultZoom_: number; private isWallpaperPolicyControlled_: boolean; private fontSizeOptions_: DropdownMenuOptionList; private pageZoomLevels_: number[]; private themeSublabel_: string; private themeUrl_: string; private useSystemTheme_: boolean; private focusConfig_: Map<string, string>; private showReaderModeOption_: boolean; private isForcedTheme_: boolean; // <if expr="is_linux and not chromeos and not lacros"> private showCustomChromeFrame_: boolean; // </if> private showManagedThemeDialog_: boolean; private appearanceBrowserProxy_: AppearanceBrowserProxy = AppearanceBrowserProxyImpl.getInstance(); ready() { super.ready(); this.$.defaultFontSize.menuOptions = this.fontSizeOptions_; // TODO(dschuyler): Look into adding a listener for the // default zoom percent. this.appearanceBrowserProxy_.getDefaultZoom().then(zoom => { this.defaultZoom_ = zoom; }); this.pageZoomLevels_ = JSON.parse(loadTimeData.getString('presetZoomFactors')); } /** @return A zoom easier read by users. */ private formatZoom_(zoom: number): number { return Math.round(zoom * 100); } /** * @param showHomepage Whether to show home page. * @param isNtp Whether to use the NTP as the home page. * @param homepageValue If not using NTP, use this URL. */ private getShowHomeSubLabel_( showHomepage: boolean, isNtp: boolean, homepageValue: string): string { if (!showHomepage) { return this.i18n('homeButtonDisabled'); } if (isNtp) { return this.i18n('homePageNtp'); } return homepageValue || this.i18n('customWebAddress'); } private onCustomizeFontsTap_() { Router.getInstance().navigateTo(routes.FONTS); } private onDisableExtension_() { this.dispatchEvent(new CustomEvent( 'refresh-pref', {bubbles: true, composed: true, detail: 'homepage'})); } /** * @param value The changed font size slider value. */ private defaultFontSizeChanged_(value: number) { // This pref is handled separately in some extensions, but here it is tied // to default_font_size (to simplify the UI). this.set( 'prefs.webkit.webprefs.default_fixed_font_size.value', value - SIZE_DIFFERENCE_FIXED_STANDARD); } /** * Open URL for either current theme or the theme gallery. */ private openThemeUrl_() { window.open(this.themeUrl_ || loadTimeData.getString('themesGalleryUrl')); } private onUseDefaultTap_() { if (this.isForcedTheme_) { this.showManagedThemeDialog_ = true; return; } this.appearanceBrowserProxy_.useDefaultTheme(); } // <if expr="is_linux and not chromeos"> private useSystemThemePrefChanged_(useSystemTheme: boolean) { this.useSystemTheme_ = useSystemTheme; } /** @return Whether to show the "USE CLASSIC" button. */ private showUseClassic_(themeId: string, useSystemTheme: boolean): boolean { return !!themeId || useSystemTheme; } /** @return Whether to show the "USE GTK+" button. */ private showUseSystem_(themeId: string, useSystemTheme: boolean): boolean { return (!!themeId || !useSystemTheme) && !this.appearanceBrowserProxy_.isSupervised(); } /** * @return Whether to show the secondary area where "USE CLASSIC" and * "USE GTK+" buttons live. */ private showThemesSecondary_(themeId: string, useSystemTheme: boolean): boolean { return this.showUseClassic_(themeId, useSystemTheme) || this.showUseSystem_(themeId, useSystemTheme); } private onUseSystemTap_() { if (this.isForcedTheme_) { this.showManagedThemeDialog_ = true; return; } this.appearanceBrowserProxy_.useSystemTheme(); } // </if> private themeChanged_( themeId: string, useSystemTheme: boolean, isForcedTheme: boolean) { if (this.prefs === undefined || useSystemTheme === undefined) { return; } if (themeId.length > 0 && themeId !== AUTOGENERATED_THEME_ID && !isForcedTheme) { assert(!useSystemTheme); this.appearanceBrowserProxy_.getThemeInfo(themeId).then(info => { this.themeSublabel_ = info.name; }); this.themeUrl_ = 'https://chrome.google.com/webstore/detail/' + themeId; return; } this.themeUrl_ = ''; if (themeId === AUTOGENERATED_THEME_ID || isForcedTheme) { this.themeSublabel_ = this.i18n('chromeColors'); return; } let i18nId; // <if expr="is_linux and not chromeos and not lacros"> i18nId = useSystemTheme ? 'systemTheme' : 'classicTheme'; // </if> // <if expr="not is_linux or chromeos or lacros"> i18nId = 'chooseFromWebStore'; // </if> this.themeSublabel_ = this.i18n(i18nId); } /** @return Whether applied theme is set by policy. */ private computeIsForcedTheme_(): boolean { return !!this.getPref('autogenerated.theme.policy.color').controlledBy; } private onZoomLevelChange_() { chrome.settingsPrivate.setDefaultZoom(parseFloat(this.$.zoomLevel.value)); } /** @see blink::PageZoomValuesEqual(). */ private zoomValuesEqual_(zoom1: number, zoom2: number): boolean { return Math.abs(zoom1 - zoom2) <= 0.001; } private showHr_(previousIsVisible: boolean, nextIsVisible: boolean): boolean { return previousIsVisible && nextIsVisible; } private onManagedDialogClosed_() { this.showManagedThemeDialog_ = false; } } customElements.define( SettingsAppearancePageElement.is, SettingsAppearancePageElement);
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { CloudDirectoryClient } from "./CloudDirectoryClient"; import { AddFacetToObjectCommand, AddFacetToObjectCommandInput, AddFacetToObjectCommandOutput, } from "./commands/AddFacetToObjectCommand"; import { ApplySchemaCommand, ApplySchemaCommandInput, ApplySchemaCommandOutput } from "./commands/ApplySchemaCommand"; import { AttachObjectCommand, AttachObjectCommandInput, AttachObjectCommandOutput, } from "./commands/AttachObjectCommand"; import { AttachPolicyCommand, AttachPolicyCommandInput, AttachPolicyCommandOutput, } from "./commands/AttachPolicyCommand"; import { AttachToIndexCommand, AttachToIndexCommandInput, AttachToIndexCommandOutput, } from "./commands/AttachToIndexCommand"; import { AttachTypedLinkCommand, AttachTypedLinkCommandInput, AttachTypedLinkCommandOutput, } from "./commands/AttachTypedLinkCommand"; import { BatchReadCommand, BatchReadCommandInput, BatchReadCommandOutput } from "./commands/BatchReadCommand"; import { BatchWriteCommand, BatchWriteCommandInput, BatchWriteCommandOutput } from "./commands/BatchWriteCommand"; import { CreateDirectoryCommand, CreateDirectoryCommandInput, CreateDirectoryCommandOutput, } from "./commands/CreateDirectoryCommand"; import { CreateFacetCommand, CreateFacetCommandInput, CreateFacetCommandOutput } from "./commands/CreateFacetCommand"; import { CreateIndexCommand, CreateIndexCommandInput, CreateIndexCommandOutput } from "./commands/CreateIndexCommand"; import { CreateObjectCommand, CreateObjectCommandInput, CreateObjectCommandOutput, } from "./commands/CreateObjectCommand"; import { CreateSchemaCommand, CreateSchemaCommandInput, CreateSchemaCommandOutput, } from "./commands/CreateSchemaCommand"; import { CreateTypedLinkFacetCommand, CreateTypedLinkFacetCommandInput, CreateTypedLinkFacetCommandOutput, } from "./commands/CreateTypedLinkFacetCommand"; import { DeleteDirectoryCommand, DeleteDirectoryCommandInput, DeleteDirectoryCommandOutput, } from "./commands/DeleteDirectoryCommand"; import { DeleteFacetCommand, DeleteFacetCommandInput, DeleteFacetCommandOutput } from "./commands/DeleteFacetCommand"; import { DeleteObjectCommand, DeleteObjectCommandInput, DeleteObjectCommandOutput, } from "./commands/DeleteObjectCommand"; import { DeleteSchemaCommand, DeleteSchemaCommandInput, DeleteSchemaCommandOutput, } from "./commands/DeleteSchemaCommand"; import { DeleteTypedLinkFacetCommand, DeleteTypedLinkFacetCommandInput, DeleteTypedLinkFacetCommandOutput, } from "./commands/DeleteTypedLinkFacetCommand"; import { DetachFromIndexCommand, DetachFromIndexCommandInput, DetachFromIndexCommandOutput, } from "./commands/DetachFromIndexCommand"; import { DetachObjectCommand, DetachObjectCommandInput, DetachObjectCommandOutput, } from "./commands/DetachObjectCommand"; import { DetachPolicyCommand, DetachPolicyCommandInput, DetachPolicyCommandOutput, } from "./commands/DetachPolicyCommand"; import { DetachTypedLinkCommand, DetachTypedLinkCommandInput, DetachTypedLinkCommandOutput, } from "./commands/DetachTypedLinkCommand"; import { DisableDirectoryCommand, DisableDirectoryCommandInput, DisableDirectoryCommandOutput, } from "./commands/DisableDirectoryCommand"; import { EnableDirectoryCommand, EnableDirectoryCommandInput, EnableDirectoryCommandOutput, } from "./commands/EnableDirectoryCommand"; import { GetAppliedSchemaVersionCommand, GetAppliedSchemaVersionCommandInput, GetAppliedSchemaVersionCommandOutput, } from "./commands/GetAppliedSchemaVersionCommand"; import { GetDirectoryCommand, GetDirectoryCommandInput, GetDirectoryCommandOutput, } from "./commands/GetDirectoryCommand"; import { GetFacetCommand, GetFacetCommandInput, GetFacetCommandOutput } from "./commands/GetFacetCommand"; import { GetLinkAttributesCommand, GetLinkAttributesCommandInput, GetLinkAttributesCommandOutput, } from "./commands/GetLinkAttributesCommand"; import { GetObjectAttributesCommand, GetObjectAttributesCommandInput, GetObjectAttributesCommandOutput, } from "./commands/GetObjectAttributesCommand"; import { GetObjectInformationCommand, GetObjectInformationCommandInput, GetObjectInformationCommandOutput, } from "./commands/GetObjectInformationCommand"; import { GetSchemaAsJsonCommand, GetSchemaAsJsonCommandInput, GetSchemaAsJsonCommandOutput, } from "./commands/GetSchemaAsJsonCommand"; import { GetTypedLinkFacetInformationCommand, GetTypedLinkFacetInformationCommandInput, GetTypedLinkFacetInformationCommandOutput, } from "./commands/GetTypedLinkFacetInformationCommand"; import { ListAppliedSchemaArnsCommand, ListAppliedSchemaArnsCommandInput, ListAppliedSchemaArnsCommandOutput, } from "./commands/ListAppliedSchemaArnsCommand"; import { ListAttachedIndicesCommand, ListAttachedIndicesCommandInput, ListAttachedIndicesCommandOutput, } from "./commands/ListAttachedIndicesCommand"; import { ListDevelopmentSchemaArnsCommand, ListDevelopmentSchemaArnsCommandInput, ListDevelopmentSchemaArnsCommandOutput, } from "./commands/ListDevelopmentSchemaArnsCommand"; import { ListDirectoriesCommand, ListDirectoriesCommandInput, ListDirectoriesCommandOutput, } from "./commands/ListDirectoriesCommand"; import { ListFacetAttributesCommand, ListFacetAttributesCommandInput, ListFacetAttributesCommandOutput, } from "./commands/ListFacetAttributesCommand"; import { ListFacetNamesCommand, ListFacetNamesCommandInput, ListFacetNamesCommandOutput, } from "./commands/ListFacetNamesCommand"; import { ListIncomingTypedLinksCommand, ListIncomingTypedLinksCommandInput, ListIncomingTypedLinksCommandOutput, } from "./commands/ListIncomingTypedLinksCommand"; import { ListIndexCommand, ListIndexCommandInput, ListIndexCommandOutput } from "./commands/ListIndexCommand"; import { ListManagedSchemaArnsCommand, ListManagedSchemaArnsCommandInput, ListManagedSchemaArnsCommandOutput, } from "./commands/ListManagedSchemaArnsCommand"; import { ListObjectAttributesCommand, ListObjectAttributesCommandInput, ListObjectAttributesCommandOutput, } from "./commands/ListObjectAttributesCommand"; import { ListObjectChildrenCommand, ListObjectChildrenCommandInput, ListObjectChildrenCommandOutput, } from "./commands/ListObjectChildrenCommand"; import { ListObjectParentPathsCommand, ListObjectParentPathsCommandInput, ListObjectParentPathsCommandOutput, } from "./commands/ListObjectParentPathsCommand"; import { ListObjectParentsCommand, ListObjectParentsCommandInput, ListObjectParentsCommandOutput, } from "./commands/ListObjectParentsCommand"; import { ListObjectPoliciesCommand, ListObjectPoliciesCommandInput, ListObjectPoliciesCommandOutput, } from "./commands/ListObjectPoliciesCommand"; import { ListOutgoingTypedLinksCommand, ListOutgoingTypedLinksCommandInput, ListOutgoingTypedLinksCommandOutput, } from "./commands/ListOutgoingTypedLinksCommand"; import { ListPolicyAttachmentsCommand, ListPolicyAttachmentsCommandInput, ListPolicyAttachmentsCommandOutput, } from "./commands/ListPolicyAttachmentsCommand"; import { ListPublishedSchemaArnsCommand, ListPublishedSchemaArnsCommandInput, ListPublishedSchemaArnsCommandOutput, } from "./commands/ListPublishedSchemaArnsCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { ListTypedLinkFacetAttributesCommand, ListTypedLinkFacetAttributesCommandInput, ListTypedLinkFacetAttributesCommandOutput, } from "./commands/ListTypedLinkFacetAttributesCommand"; import { ListTypedLinkFacetNamesCommand, ListTypedLinkFacetNamesCommandInput, ListTypedLinkFacetNamesCommandOutput, } from "./commands/ListTypedLinkFacetNamesCommand"; import { LookupPolicyCommand, LookupPolicyCommandInput, LookupPolicyCommandOutput, } from "./commands/LookupPolicyCommand"; import { PublishSchemaCommand, PublishSchemaCommandInput, PublishSchemaCommandOutput, } from "./commands/PublishSchemaCommand"; import { PutSchemaFromJsonCommand, PutSchemaFromJsonCommandInput, PutSchemaFromJsonCommandOutput, } from "./commands/PutSchemaFromJsonCommand"; import { RemoveFacetFromObjectCommand, RemoveFacetFromObjectCommandInput, RemoveFacetFromObjectCommandOutput, } from "./commands/RemoveFacetFromObjectCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { UpdateFacetCommand, UpdateFacetCommandInput, UpdateFacetCommandOutput } from "./commands/UpdateFacetCommand"; import { UpdateLinkAttributesCommand, UpdateLinkAttributesCommandInput, UpdateLinkAttributesCommandOutput, } from "./commands/UpdateLinkAttributesCommand"; import { UpdateObjectAttributesCommand, UpdateObjectAttributesCommandInput, UpdateObjectAttributesCommandOutput, } from "./commands/UpdateObjectAttributesCommand"; import { UpdateSchemaCommand, UpdateSchemaCommandInput, UpdateSchemaCommandOutput, } from "./commands/UpdateSchemaCommand"; import { UpdateTypedLinkFacetCommand, UpdateTypedLinkFacetCommandInput, UpdateTypedLinkFacetCommandOutput, } from "./commands/UpdateTypedLinkFacetCommand"; import { UpgradeAppliedSchemaCommand, UpgradeAppliedSchemaCommandInput, UpgradeAppliedSchemaCommandOutput, } from "./commands/UpgradeAppliedSchemaCommand"; import { UpgradePublishedSchemaCommand, UpgradePublishedSchemaCommandInput, UpgradePublishedSchemaCommandOutput, } from "./commands/UpgradePublishedSchemaCommand"; /** * <fullname>Amazon Cloud Directory</fullname> * <p>Amazon Cloud Directory is a component of the AWS Directory Service that simplifies the * development and management of cloud-scale web, mobile, and IoT applications. This guide * describes the Cloud Directory operations that you can call programmatically and includes * detailed information on data types and errors. For information about Cloud Directory features, see <a href="https://aws.amazon.com/directoryservice/">AWS Directory * Service</a> and the <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/what_is_cloud_directory.html">Amazon Cloud Directory Developer Guide</a>.</p> */ export class CloudDirectory extends CloudDirectoryClient { /** * <p>Adds a new <a>Facet</a> to an object. An object can have more than one facet applied on it.</p> */ public addFacetToObject( args: AddFacetToObjectCommandInput, options?: __HttpHandlerOptions ): Promise<AddFacetToObjectCommandOutput>; public addFacetToObject( args: AddFacetToObjectCommandInput, cb: (err: any, data?: AddFacetToObjectCommandOutput) => void ): void; public addFacetToObject( args: AddFacetToObjectCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AddFacetToObjectCommandOutput) => void ): void; public addFacetToObject( args: AddFacetToObjectCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AddFacetToObjectCommandOutput) => void), cb?: (err: any, data?: AddFacetToObjectCommandOutput) => void ): Promise<AddFacetToObjectCommandOutput> | void { const command = new AddFacetToObjectCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Copies the input published schema, at the specified version, into the <a>Directory</a> with the same * name and version as that of the published schema.</p> */ public applySchema(args: ApplySchemaCommandInput, options?: __HttpHandlerOptions): Promise<ApplySchemaCommandOutput>; public applySchema(args: ApplySchemaCommandInput, cb: (err: any, data?: ApplySchemaCommandOutput) => void): void; public applySchema( args: ApplySchemaCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ApplySchemaCommandOutput) => void ): void; public applySchema( args: ApplySchemaCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ApplySchemaCommandOutput) => void), cb?: (err: any, data?: ApplySchemaCommandOutput) => void ): Promise<ApplySchemaCommandOutput> | void { const command = new ApplySchemaCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Attaches an existing object to another object. An object can be accessed in two * ways:</p> * <ol> * <li> * <p>Using the path</p> * </li> * <li> * <p>Using <code>ObjectIdentifier</code> * </p> * </li> * </ol> */ public attachObject( args: AttachObjectCommandInput, options?: __HttpHandlerOptions ): Promise<AttachObjectCommandOutput>; public attachObject(args: AttachObjectCommandInput, cb: (err: any, data?: AttachObjectCommandOutput) => void): void; public attachObject( args: AttachObjectCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AttachObjectCommandOutput) => void ): void; public attachObject( args: AttachObjectCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AttachObjectCommandOutput) => void), cb?: (err: any, data?: AttachObjectCommandOutput) => void ): Promise<AttachObjectCommandOutput> | void { const command = new AttachObjectCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Attaches a policy object to a regular object. An object can have a limited number of attached * policies.</p> */ public attachPolicy( args: AttachPolicyCommandInput, options?: __HttpHandlerOptions ): Promise<AttachPolicyCommandOutput>; public attachPolicy(args: AttachPolicyCommandInput, cb: (err: any, data?: AttachPolicyCommandOutput) => void): void; public attachPolicy( args: AttachPolicyCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AttachPolicyCommandOutput) => void ): void; public attachPolicy( args: AttachPolicyCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AttachPolicyCommandOutput) => void), cb?: (err: any, data?: AttachPolicyCommandOutput) => void ): Promise<AttachPolicyCommandOutput> | void { const command = new AttachPolicyCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Attaches the specified object to the specified index.</p> */ public attachToIndex( args: AttachToIndexCommandInput, options?: __HttpHandlerOptions ): Promise<AttachToIndexCommandOutput>; public attachToIndex( args: AttachToIndexCommandInput, cb: (err: any, data?: AttachToIndexCommandOutput) => void ): void; public attachToIndex( args: AttachToIndexCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AttachToIndexCommandOutput) => void ): void; public attachToIndex( args: AttachToIndexCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AttachToIndexCommandOutput) => void), cb?: (err: any, data?: AttachToIndexCommandOutput) => void ): Promise<AttachToIndexCommandOutput> | void { const command = new AttachToIndexCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Attaches a typed link to a specified source and target object. For more information, see <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/directory_objects_links.html#directory_objects_links_typedlink">Typed Links</a>.</p> */ public attachTypedLink( args: AttachTypedLinkCommandInput, options?: __HttpHandlerOptions ): Promise<AttachTypedLinkCommandOutput>; public attachTypedLink( args: AttachTypedLinkCommandInput, cb: (err: any, data?: AttachTypedLinkCommandOutput) => void ): void; public attachTypedLink( args: AttachTypedLinkCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AttachTypedLinkCommandOutput) => void ): void; public attachTypedLink( args: AttachTypedLinkCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AttachTypedLinkCommandOutput) => void), cb?: (err: any, data?: AttachTypedLinkCommandOutput) => void ): Promise<AttachTypedLinkCommandOutput> | void { const command = new AttachTypedLinkCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Performs all the read operations in a batch. </p> */ public batchRead(args: BatchReadCommandInput, options?: __HttpHandlerOptions): Promise<BatchReadCommandOutput>; public batchRead(args: BatchReadCommandInput, cb: (err: any, data?: BatchReadCommandOutput) => void): void; public batchRead( args: BatchReadCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: BatchReadCommandOutput) => void ): void; public batchRead( args: BatchReadCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchReadCommandOutput) => void), cb?: (err: any, data?: BatchReadCommandOutput) => void ): Promise<BatchReadCommandOutput> | void { const command = new BatchReadCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Performs all the write operations in a batch. Either all the operations succeed or * none.</p> */ public batchWrite(args: BatchWriteCommandInput, options?: __HttpHandlerOptions): Promise<BatchWriteCommandOutput>; public batchWrite(args: BatchWriteCommandInput, cb: (err: any, data?: BatchWriteCommandOutput) => void): void; public batchWrite( args: BatchWriteCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: BatchWriteCommandOutput) => void ): void; public batchWrite( args: BatchWriteCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchWriteCommandOutput) => void), cb?: (err: any, data?: BatchWriteCommandOutput) => void ): Promise<BatchWriteCommandOutput> | void { const command = new BatchWriteCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a <a>Directory</a> by copying the published schema into the * directory. A directory cannot be created without a schema.</p> * <p>You can also quickly create a directory using a managed schema, called the * <code>QuickStartSchema</code>. For more information, see <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/schemas_managed.html">Managed Schema</a> in the <i>Amazon Cloud Directory Developer Guide</i>.</p> */ public createDirectory( args: CreateDirectoryCommandInput, options?: __HttpHandlerOptions ): Promise<CreateDirectoryCommandOutput>; public createDirectory( args: CreateDirectoryCommandInput, cb: (err: any, data?: CreateDirectoryCommandOutput) => void ): void; public createDirectory( args: CreateDirectoryCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateDirectoryCommandOutput) => void ): void; public createDirectory( args: CreateDirectoryCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateDirectoryCommandOutput) => void), cb?: (err: any, data?: CreateDirectoryCommandOutput) => void ): Promise<CreateDirectoryCommandOutput> | void { const command = new CreateDirectoryCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new <a>Facet</a> in a schema. Facet creation is allowed only * in development or applied schemas.</p> */ public createFacet(args: CreateFacetCommandInput, options?: __HttpHandlerOptions): Promise<CreateFacetCommandOutput>; public createFacet(args: CreateFacetCommandInput, cb: (err: any, data?: CreateFacetCommandOutput) => void): void; public createFacet( args: CreateFacetCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateFacetCommandOutput) => void ): void; public createFacet( args: CreateFacetCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateFacetCommandOutput) => void), cb?: (err: any, data?: CreateFacetCommandOutput) => void ): Promise<CreateFacetCommandOutput> | void { const command = new CreateFacetCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates an index object. See <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/indexing_search.html">Indexing and search</a> for more information.</p> */ public createIndex(args: CreateIndexCommandInput, options?: __HttpHandlerOptions): Promise<CreateIndexCommandOutput>; public createIndex(args: CreateIndexCommandInput, cb: (err: any, data?: CreateIndexCommandOutput) => void): void; public createIndex( args: CreateIndexCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateIndexCommandOutput) => void ): void; public createIndex( args: CreateIndexCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateIndexCommandOutput) => void), cb?: (err: any, data?: CreateIndexCommandOutput) => void ): Promise<CreateIndexCommandOutput> | void { const command = new CreateIndexCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates an object in a <a>Directory</a>. Additionally attaches the object to * a parent, if a parent reference and <code>LinkName</code> is specified. An object is simply a * collection of <a>Facet</a> attributes. You can also use this API call to create a * policy object, if the facet from which you create the object is a policy facet. </p> */ public createObject( args: CreateObjectCommandInput, options?: __HttpHandlerOptions ): Promise<CreateObjectCommandOutput>; public createObject(args: CreateObjectCommandInput, cb: (err: any, data?: CreateObjectCommandOutput) => void): void; public createObject( args: CreateObjectCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateObjectCommandOutput) => void ): void; public createObject( args: CreateObjectCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateObjectCommandOutput) => void), cb?: (err: any, data?: CreateObjectCommandOutput) => void ): Promise<CreateObjectCommandOutput> | void { const command = new CreateObjectCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new schema in a development state. A schema can exist in three * phases:</p> * <ul> * <li> * <p> * <i>Development:</i> This is a mutable phase of the schema. All new * schemas are in the development phase. Once the schema is finalized, it can be * published.</p> * </li> * <li> * <p> * <i>Published:</i> Published schemas are immutable and have a version * associated with them.</p> * </li> * <li> * <p> * <i>Applied:</i> Applied schemas are mutable in a way that allows you * to add new schema facets. You can also add new, nonrequired attributes to existing schema * facets. You can apply only published schemas to directories. </p> * </li> * </ul> */ public createSchema( args: CreateSchemaCommandInput, options?: __HttpHandlerOptions ): Promise<CreateSchemaCommandOutput>; public createSchema(args: CreateSchemaCommandInput, cb: (err: any, data?: CreateSchemaCommandOutput) => void): void; public createSchema( args: CreateSchemaCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateSchemaCommandOutput) => void ): void; public createSchema( args: CreateSchemaCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateSchemaCommandOutput) => void), cb?: (err: any, data?: CreateSchemaCommandOutput) => void ): Promise<CreateSchemaCommandOutput> | void { const command = new CreateSchemaCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a <a>TypedLinkFacet</a>. For more information, see <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/directory_objects_links.html#directory_objects_links_typedlink">Typed Links</a>.</p> */ public createTypedLinkFacet( args: CreateTypedLinkFacetCommandInput, options?: __HttpHandlerOptions ): Promise<CreateTypedLinkFacetCommandOutput>; public createTypedLinkFacet( args: CreateTypedLinkFacetCommandInput, cb: (err: any, data?: CreateTypedLinkFacetCommandOutput) => void ): void; public createTypedLinkFacet( args: CreateTypedLinkFacetCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateTypedLinkFacetCommandOutput) => void ): void; public createTypedLinkFacet( args: CreateTypedLinkFacetCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateTypedLinkFacetCommandOutput) => void), cb?: (err: any, data?: CreateTypedLinkFacetCommandOutput) => void ): Promise<CreateTypedLinkFacetCommandOutput> | void { const command = new CreateTypedLinkFacetCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a directory. Only disabled directories can be deleted. A deleted directory cannot be undone. Exercise extreme * caution * when deleting directories.</p> */ public deleteDirectory( args: DeleteDirectoryCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteDirectoryCommandOutput>; public deleteDirectory( args: DeleteDirectoryCommandInput, cb: (err: any, data?: DeleteDirectoryCommandOutput) => void ): void; public deleteDirectory( args: DeleteDirectoryCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteDirectoryCommandOutput) => void ): void; public deleteDirectory( args: DeleteDirectoryCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteDirectoryCommandOutput) => void), cb?: (err: any, data?: DeleteDirectoryCommandOutput) => void ): Promise<DeleteDirectoryCommandOutput> | void { const command = new DeleteDirectoryCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a given <a>Facet</a>. All attributes and <a>Rule</a>s * that are associated with the facet will be deleted. Only development schema facets are allowed * deletion.</p> */ public deleteFacet(args: DeleteFacetCommandInput, options?: __HttpHandlerOptions): Promise<DeleteFacetCommandOutput>; public deleteFacet(args: DeleteFacetCommandInput, cb: (err: any, data?: DeleteFacetCommandOutput) => void): void; public deleteFacet( args: DeleteFacetCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteFacetCommandOutput) => void ): void; public deleteFacet( args: DeleteFacetCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteFacetCommandOutput) => void), cb?: (err: any, data?: DeleteFacetCommandOutput) => void ): Promise<DeleteFacetCommandOutput> | void { const command = new DeleteFacetCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes an object and its associated attributes. Only objects with no children and no * parents can be deleted. The maximum number of attributes that can be deleted during an object deletion is 30. For more information, see <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/limits.html">Amazon Cloud Directory Limits</a>.</p> */ public deleteObject( args: DeleteObjectCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteObjectCommandOutput>; public deleteObject(args: DeleteObjectCommandInput, cb: (err: any, data?: DeleteObjectCommandOutput) => void): void; public deleteObject( args: DeleteObjectCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteObjectCommandOutput) => void ): void; public deleteObject( args: DeleteObjectCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteObjectCommandOutput) => void), cb?: (err: any, data?: DeleteObjectCommandOutput) => void ): Promise<DeleteObjectCommandOutput> | void { const command = new DeleteObjectCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a given schema. Schemas in a development and published state can only be deleted. </p> */ public deleteSchema( args: DeleteSchemaCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteSchemaCommandOutput>; public deleteSchema(args: DeleteSchemaCommandInput, cb: (err: any, data?: DeleteSchemaCommandOutput) => void): void; public deleteSchema( args: DeleteSchemaCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteSchemaCommandOutput) => void ): void; public deleteSchema( args: DeleteSchemaCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteSchemaCommandOutput) => void), cb?: (err: any, data?: DeleteSchemaCommandOutput) => void ): Promise<DeleteSchemaCommandOutput> | void { const command = new DeleteSchemaCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a <a>TypedLinkFacet</a>. For more information, see <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/directory_objects_links.html#directory_objects_links_typedlink">Typed Links</a>.</p> */ public deleteTypedLinkFacet( args: DeleteTypedLinkFacetCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteTypedLinkFacetCommandOutput>; public deleteTypedLinkFacet( args: DeleteTypedLinkFacetCommandInput, cb: (err: any, data?: DeleteTypedLinkFacetCommandOutput) => void ): void; public deleteTypedLinkFacet( args: DeleteTypedLinkFacetCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteTypedLinkFacetCommandOutput) => void ): void; public deleteTypedLinkFacet( args: DeleteTypedLinkFacetCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteTypedLinkFacetCommandOutput) => void), cb?: (err: any, data?: DeleteTypedLinkFacetCommandOutput) => void ): Promise<DeleteTypedLinkFacetCommandOutput> | void { const command = new DeleteTypedLinkFacetCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Detaches the specified object from the specified index.</p> */ public detachFromIndex( args: DetachFromIndexCommandInput, options?: __HttpHandlerOptions ): Promise<DetachFromIndexCommandOutput>; public detachFromIndex( args: DetachFromIndexCommandInput, cb: (err: any, data?: DetachFromIndexCommandOutput) => void ): void; public detachFromIndex( args: DetachFromIndexCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DetachFromIndexCommandOutput) => void ): void; public detachFromIndex( args: DetachFromIndexCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DetachFromIndexCommandOutput) => void), cb?: (err: any, data?: DetachFromIndexCommandOutput) => void ): Promise<DetachFromIndexCommandOutput> | void { const command = new DetachFromIndexCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Detaches a given object from the parent object. The object that is to be detached from the * parent is specified by the link name.</p> */ public detachObject( args: DetachObjectCommandInput, options?: __HttpHandlerOptions ): Promise<DetachObjectCommandOutput>; public detachObject(args: DetachObjectCommandInput, cb: (err: any, data?: DetachObjectCommandOutput) => void): void; public detachObject( args: DetachObjectCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DetachObjectCommandOutput) => void ): void; public detachObject( args: DetachObjectCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DetachObjectCommandOutput) => void), cb?: (err: any, data?: DetachObjectCommandOutput) => void ): Promise<DetachObjectCommandOutput> | void { const command = new DetachObjectCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Detaches a policy from an object.</p> */ public detachPolicy( args: DetachPolicyCommandInput, options?: __HttpHandlerOptions ): Promise<DetachPolicyCommandOutput>; public detachPolicy(args: DetachPolicyCommandInput, cb: (err: any, data?: DetachPolicyCommandOutput) => void): void; public detachPolicy( args: DetachPolicyCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DetachPolicyCommandOutput) => void ): void; public detachPolicy( args: DetachPolicyCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DetachPolicyCommandOutput) => void), cb?: (err: any, data?: DetachPolicyCommandOutput) => void ): Promise<DetachPolicyCommandOutput> | void { const command = new DetachPolicyCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Detaches a typed link from a specified source and target object. For more information, see <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/directory_objects_links.html#directory_objects_links_typedlink">Typed Links</a>.</p> */ public detachTypedLink( args: DetachTypedLinkCommandInput, options?: __HttpHandlerOptions ): Promise<DetachTypedLinkCommandOutput>; public detachTypedLink( args: DetachTypedLinkCommandInput, cb: (err: any, data?: DetachTypedLinkCommandOutput) => void ): void; public detachTypedLink( args: DetachTypedLinkCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DetachTypedLinkCommandOutput) => void ): void; public detachTypedLink( args: DetachTypedLinkCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DetachTypedLinkCommandOutput) => void), cb?: (err: any, data?: DetachTypedLinkCommandOutput) => void ): Promise<DetachTypedLinkCommandOutput> | void { const command = new DetachTypedLinkCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Disables the specified directory. Disabled directories cannot be read or written to. * Only enabled directories can be disabled. Disabled directories may be reenabled.</p> */ public disableDirectory( args: DisableDirectoryCommandInput, options?: __HttpHandlerOptions ): Promise<DisableDirectoryCommandOutput>; public disableDirectory( args: DisableDirectoryCommandInput, cb: (err: any, data?: DisableDirectoryCommandOutput) => void ): void; public disableDirectory( args: DisableDirectoryCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DisableDirectoryCommandOutput) => void ): void; public disableDirectory( args: DisableDirectoryCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisableDirectoryCommandOutput) => void), cb?: (err: any, data?: DisableDirectoryCommandOutput) => void ): Promise<DisableDirectoryCommandOutput> | void { const command = new DisableDirectoryCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Enables the specified directory. Only disabled directories can be enabled. Once * enabled, the directory can then be read and written to.</p> */ public enableDirectory( args: EnableDirectoryCommandInput, options?: __HttpHandlerOptions ): Promise<EnableDirectoryCommandOutput>; public enableDirectory( args: EnableDirectoryCommandInput, cb: (err: any, data?: EnableDirectoryCommandOutput) => void ): void; public enableDirectory( args: EnableDirectoryCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: EnableDirectoryCommandOutput) => void ): void; public enableDirectory( args: EnableDirectoryCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: EnableDirectoryCommandOutput) => void), cb?: (err: any, data?: EnableDirectoryCommandOutput) => void ): Promise<EnableDirectoryCommandOutput> | void { const command = new EnableDirectoryCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns current applied schema version ARN, including the minor version in use.</p> */ public getAppliedSchemaVersion( args: GetAppliedSchemaVersionCommandInput, options?: __HttpHandlerOptions ): Promise<GetAppliedSchemaVersionCommandOutput>; public getAppliedSchemaVersion( args: GetAppliedSchemaVersionCommandInput, cb: (err: any, data?: GetAppliedSchemaVersionCommandOutput) => void ): void; public getAppliedSchemaVersion( args: GetAppliedSchemaVersionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetAppliedSchemaVersionCommandOutput) => void ): void; public getAppliedSchemaVersion( args: GetAppliedSchemaVersionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetAppliedSchemaVersionCommandOutput) => void), cb?: (err: any, data?: GetAppliedSchemaVersionCommandOutput) => void ): Promise<GetAppliedSchemaVersionCommandOutput> | void { const command = new GetAppliedSchemaVersionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Retrieves metadata about a directory.</p> */ public getDirectory( args: GetDirectoryCommandInput, options?: __HttpHandlerOptions ): Promise<GetDirectoryCommandOutput>; public getDirectory(args: GetDirectoryCommandInput, cb: (err: any, data?: GetDirectoryCommandOutput) => void): void; public getDirectory( args: GetDirectoryCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetDirectoryCommandOutput) => void ): void; public getDirectory( args: GetDirectoryCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetDirectoryCommandOutput) => void), cb?: (err: any, data?: GetDirectoryCommandOutput) => void ): Promise<GetDirectoryCommandOutput> | void { const command = new GetDirectoryCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets details of the <a>Facet</a>, such as facet name, attributes, <a>Rule</a>s, or <code>ObjectType</code>. You can call this on all kinds of schema * facets -- published, development, or applied.</p> */ public getFacet(args: GetFacetCommandInput, options?: __HttpHandlerOptions): Promise<GetFacetCommandOutput>; public getFacet(args: GetFacetCommandInput, cb: (err: any, data?: GetFacetCommandOutput) => void): void; public getFacet( args: GetFacetCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetFacetCommandOutput) => void ): void; public getFacet( args: GetFacetCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetFacetCommandOutput) => void), cb?: (err: any, data?: GetFacetCommandOutput) => void ): Promise<GetFacetCommandOutput> | void { const command = new GetFacetCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Retrieves attributes that are associated with a typed link.</p> */ public getLinkAttributes( args: GetLinkAttributesCommandInput, options?: __HttpHandlerOptions ): Promise<GetLinkAttributesCommandOutput>; public getLinkAttributes( args: GetLinkAttributesCommandInput, cb: (err: any, data?: GetLinkAttributesCommandOutput) => void ): void; public getLinkAttributes( args: GetLinkAttributesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetLinkAttributesCommandOutput) => void ): void; public getLinkAttributes( args: GetLinkAttributesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetLinkAttributesCommandOutput) => void), cb?: (err: any, data?: GetLinkAttributesCommandOutput) => void ): Promise<GetLinkAttributesCommandOutput> | void { const command = new GetLinkAttributesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Retrieves attributes within a facet that are associated with an object.</p> */ public getObjectAttributes( args: GetObjectAttributesCommandInput, options?: __HttpHandlerOptions ): Promise<GetObjectAttributesCommandOutput>; public getObjectAttributes( args: GetObjectAttributesCommandInput, cb: (err: any, data?: GetObjectAttributesCommandOutput) => void ): void; public getObjectAttributes( args: GetObjectAttributesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetObjectAttributesCommandOutput) => void ): void; public getObjectAttributes( args: GetObjectAttributesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetObjectAttributesCommandOutput) => void), cb?: (err: any, data?: GetObjectAttributesCommandOutput) => void ): Promise<GetObjectAttributesCommandOutput> | void { const command = new GetObjectAttributesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Retrieves metadata about an object.</p> */ public getObjectInformation( args: GetObjectInformationCommandInput, options?: __HttpHandlerOptions ): Promise<GetObjectInformationCommandOutput>; public getObjectInformation( args: GetObjectInformationCommandInput, cb: (err: any, data?: GetObjectInformationCommandOutput) => void ): void; public getObjectInformation( args: GetObjectInformationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetObjectInformationCommandOutput) => void ): void; public getObjectInformation( args: GetObjectInformationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetObjectInformationCommandOutput) => void), cb?: (err: any, data?: GetObjectInformationCommandOutput) => void ): Promise<GetObjectInformationCommandOutput> | void { const command = new GetObjectInformationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Retrieves a JSON representation of the schema. See <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/schemas_jsonformat.html#schemas_json">JSON Schema Format</a> for more information.</p> */ public getSchemaAsJson( args: GetSchemaAsJsonCommandInput, options?: __HttpHandlerOptions ): Promise<GetSchemaAsJsonCommandOutput>; public getSchemaAsJson( args: GetSchemaAsJsonCommandInput, cb: (err: any, data?: GetSchemaAsJsonCommandOutput) => void ): void; public getSchemaAsJson( args: GetSchemaAsJsonCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetSchemaAsJsonCommandOutput) => void ): void; public getSchemaAsJson( args: GetSchemaAsJsonCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetSchemaAsJsonCommandOutput) => void), cb?: (err: any, data?: GetSchemaAsJsonCommandOutput) => void ): Promise<GetSchemaAsJsonCommandOutput> | void { const command = new GetSchemaAsJsonCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns the identity attribute order for a specific <a>TypedLinkFacet</a>. For more information, see <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/directory_objects_links.html#directory_objects_links_typedlink">Typed Links</a>.</p> */ public getTypedLinkFacetInformation( args: GetTypedLinkFacetInformationCommandInput, options?: __HttpHandlerOptions ): Promise<GetTypedLinkFacetInformationCommandOutput>; public getTypedLinkFacetInformation( args: GetTypedLinkFacetInformationCommandInput, cb: (err: any, data?: GetTypedLinkFacetInformationCommandOutput) => void ): void; public getTypedLinkFacetInformation( args: GetTypedLinkFacetInformationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetTypedLinkFacetInformationCommandOutput) => void ): void; public getTypedLinkFacetInformation( args: GetTypedLinkFacetInformationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetTypedLinkFacetInformationCommandOutput) => void), cb?: (err: any, data?: GetTypedLinkFacetInformationCommandOutput) => void ): Promise<GetTypedLinkFacetInformationCommandOutput> | void { const command = new GetTypedLinkFacetInformationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists schema major versions applied to a directory. If <code>SchemaArn</code> is provided, lists the minor version.</p> */ public listAppliedSchemaArns( args: ListAppliedSchemaArnsCommandInput, options?: __HttpHandlerOptions ): Promise<ListAppliedSchemaArnsCommandOutput>; public listAppliedSchemaArns( args: ListAppliedSchemaArnsCommandInput, cb: (err: any, data?: ListAppliedSchemaArnsCommandOutput) => void ): void; public listAppliedSchemaArns( args: ListAppliedSchemaArnsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListAppliedSchemaArnsCommandOutput) => void ): void; public listAppliedSchemaArns( args: ListAppliedSchemaArnsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListAppliedSchemaArnsCommandOutput) => void), cb?: (err: any, data?: ListAppliedSchemaArnsCommandOutput) => void ): Promise<ListAppliedSchemaArnsCommandOutput> | void { const command = new ListAppliedSchemaArnsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists indices attached to the specified object.</p> */ public listAttachedIndices( args: ListAttachedIndicesCommandInput, options?: __HttpHandlerOptions ): Promise<ListAttachedIndicesCommandOutput>; public listAttachedIndices( args: ListAttachedIndicesCommandInput, cb: (err: any, data?: ListAttachedIndicesCommandOutput) => void ): void; public listAttachedIndices( args: ListAttachedIndicesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListAttachedIndicesCommandOutput) => void ): void; public listAttachedIndices( args: ListAttachedIndicesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListAttachedIndicesCommandOutput) => void), cb?: (err: any, data?: ListAttachedIndicesCommandOutput) => void ): Promise<ListAttachedIndicesCommandOutput> | void { const command = new ListAttachedIndicesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Retrieves each Amazon Resource Name (ARN) of schemas in the development * state.</p> */ public listDevelopmentSchemaArns( args: ListDevelopmentSchemaArnsCommandInput, options?: __HttpHandlerOptions ): Promise<ListDevelopmentSchemaArnsCommandOutput>; public listDevelopmentSchemaArns( args: ListDevelopmentSchemaArnsCommandInput, cb: (err: any, data?: ListDevelopmentSchemaArnsCommandOutput) => void ): void; public listDevelopmentSchemaArns( args: ListDevelopmentSchemaArnsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListDevelopmentSchemaArnsCommandOutput) => void ): void; public listDevelopmentSchemaArns( args: ListDevelopmentSchemaArnsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListDevelopmentSchemaArnsCommandOutput) => void), cb?: (err: any, data?: ListDevelopmentSchemaArnsCommandOutput) => void ): Promise<ListDevelopmentSchemaArnsCommandOutput> | void { const command = new ListDevelopmentSchemaArnsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists directories created within an account.</p> */ public listDirectories( args: ListDirectoriesCommandInput, options?: __HttpHandlerOptions ): Promise<ListDirectoriesCommandOutput>; public listDirectories( args: ListDirectoriesCommandInput, cb: (err: any, data?: ListDirectoriesCommandOutput) => void ): void; public listDirectories( args: ListDirectoriesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListDirectoriesCommandOutput) => void ): void; public listDirectories( args: ListDirectoriesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListDirectoriesCommandOutput) => void), cb?: (err: any, data?: ListDirectoriesCommandOutput) => void ): Promise<ListDirectoriesCommandOutput> | void { const command = new ListDirectoriesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Retrieves attributes attached to the facet.</p> */ public listFacetAttributes( args: ListFacetAttributesCommandInput, options?: __HttpHandlerOptions ): Promise<ListFacetAttributesCommandOutput>; public listFacetAttributes( args: ListFacetAttributesCommandInput, cb: (err: any, data?: ListFacetAttributesCommandOutput) => void ): void; public listFacetAttributes( args: ListFacetAttributesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListFacetAttributesCommandOutput) => void ): void; public listFacetAttributes( args: ListFacetAttributesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListFacetAttributesCommandOutput) => void), cb?: (err: any, data?: ListFacetAttributesCommandOutput) => void ): Promise<ListFacetAttributesCommandOutput> | void { const command = new ListFacetAttributesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Retrieves the names of facets that exist in a schema.</p> */ public listFacetNames( args: ListFacetNamesCommandInput, options?: __HttpHandlerOptions ): Promise<ListFacetNamesCommandOutput>; public listFacetNames( args: ListFacetNamesCommandInput, cb: (err: any, data?: ListFacetNamesCommandOutput) => void ): void; public listFacetNames( args: ListFacetNamesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListFacetNamesCommandOutput) => void ): void; public listFacetNames( args: ListFacetNamesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListFacetNamesCommandOutput) => void), cb?: (err: any, data?: ListFacetNamesCommandOutput) => void ): Promise<ListFacetNamesCommandOutput> | void { const command = new ListFacetNamesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a paginated list of all the incoming <a>TypedLinkSpecifier</a> * information for an object. It also supports filtering by typed link facet and identity * attributes. For more information, see <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/directory_objects_links.html#directory_objects_links_typedlink">Typed Links</a>.</p> */ public listIncomingTypedLinks( args: ListIncomingTypedLinksCommandInput, options?: __HttpHandlerOptions ): Promise<ListIncomingTypedLinksCommandOutput>; public listIncomingTypedLinks( args: ListIncomingTypedLinksCommandInput, cb: (err: any, data?: ListIncomingTypedLinksCommandOutput) => void ): void; public listIncomingTypedLinks( args: ListIncomingTypedLinksCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListIncomingTypedLinksCommandOutput) => void ): void; public listIncomingTypedLinks( args: ListIncomingTypedLinksCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListIncomingTypedLinksCommandOutput) => void), cb?: (err: any, data?: ListIncomingTypedLinksCommandOutput) => void ): Promise<ListIncomingTypedLinksCommandOutput> | void { const command = new ListIncomingTypedLinksCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists objects attached to the specified index.</p> */ public listIndex(args: ListIndexCommandInput, options?: __HttpHandlerOptions): Promise<ListIndexCommandOutput>; public listIndex(args: ListIndexCommandInput, cb: (err: any, data?: ListIndexCommandOutput) => void): void; public listIndex( args: ListIndexCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListIndexCommandOutput) => void ): void; public listIndex( args: ListIndexCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListIndexCommandOutput) => void), cb?: (err: any, data?: ListIndexCommandOutput) => void ): Promise<ListIndexCommandOutput> | void { const command = new ListIndexCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the major version families of each managed schema. If a major version ARN is provided as SchemaArn, the minor version revisions in that family are listed instead.</p> */ public listManagedSchemaArns( args: ListManagedSchemaArnsCommandInput, options?: __HttpHandlerOptions ): Promise<ListManagedSchemaArnsCommandOutput>; public listManagedSchemaArns( args: ListManagedSchemaArnsCommandInput, cb: (err: any, data?: ListManagedSchemaArnsCommandOutput) => void ): void; public listManagedSchemaArns( args: ListManagedSchemaArnsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListManagedSchemaArnsCommandOutput) => void ): void; public listManagedSchemaArns( args: ListManagedSchemaArnsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListManagedSchemaArnsCommandOutput) => void), cb?: (err: any, data?: ListManagedSchemaArnsCommandOutput) => void ): Promise<ListManagedSchemaArnsCommandOutput> | void { const command = new ListManagedSchemaArnsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists all attributes that are associated with an object. * </p> */ public listObjectAttributes( args: ListObjectAttributesCommandInput, options?: __HttpHandlerOptions ): Promise<ListObjectAttributesCommandOutput>; public listObjectAttributes( args: ListObjectAttributesCommandInput, cb: (err: any, data?: ListObjectAttributesCommandOutput) => void ): void; public listObjectAttributes( args: ListObjectAttributesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListObjectAttributesCommandOutput) => void ): void; public listObjectAttributes( args: ListObjectAttributesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListObjectAttributesCommandOutput) => void), cb?: (err: any, data?: ListObjectAttributesCommandOutput) => void ): Promise<ListObjectAttributesCommandOutput> | void { const command = new ListObjectAttributesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a paginated list of child objects that are associated with a given * object.</p> */ public listObjectChildren( args: ListObjectChildrenCommandInput, options?: __HttpHandlerOptions ): Promise<ListObjectChildrenCommandOutput>; public listObjectChildren( args: ListObjectChildrenCommandInput, cb: (err: any, data?: ListObjectChildrenCommandOutput) => void ): void; public listObjectChildren( args: ListObjectChildrenCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListObjectChildrenCommandOutput) => void ): void; public listObjectChildren( args: ListObjectChildrenCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListObjectChildrenCommandOutput) => void), cb?: (err: any, data?: ListObjectChildrenCommandOutput) => void ): Promise<ListObjectChildrenCommandOutput> | void { const command = new ListObjectChildrenCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Retrieves all available parent paths for any object type such as node, leaf node, * policy node, and index node objects. For more information about objects, see <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/key_concepts_directorystructure.html">Directory Structure</a>.</p> * <p>Use this API to evaluate all parents for an object. The call returns all objects from * the root of the directory up to the requested object. The API returns the number of paths * based on user-defined <code>MaxResults</code>, in case there are multiple paths to the parent. * The order of the paths and nodes returned is consistent among multiple API calls unless the * objects are deleted or moved. Paths not leading to the directory root are ignored from the * target object.</p> */ public listObjectParentPaths( args: ListObjectParentPathsCommandInput, options?: __HttpHandlerOptions ): Promise<ListObjectParentPathsCommandOutput>; public listObjectParentPaths( args: ListObjectParentPathsCommandInput, cb: (err: any, data?: ListObjectParentPathsCommandOutput) => void ): void; public listObjectParentPaths( args: ListObjectParentPathsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListObjectParentPathsCommandOutput) => void ): void; public listObjectParentPaths( args: ListObjectParentPathsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListObjectParentPathsCommandOutput) => void), cb?: (err: any, data?: ListObjectParentPathsCommandOutput) => void ): Promise<ListObjectParentPathsCommandOutput> | void { const command = new ListObjectParentPathsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists parent objects that are associated with a given object in pagination * fashion.</p> */ public listObjectParents( args: ListObjectParentsCommandInput, options?: __HttpHandlerOptions ): Promise<ListObjectParentsCommandOutput>; public listObjectParents( args: ListObjectParentsCommandInput, cb: (err: any, data?: ListObjectParentsCommandOutput) => void ): void; public listObjectParents( args: ListObjectParentsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListObjectParentsCommandOutput) => void ): void; public listObjectParents( args: ListObjectParentsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListObjectParentsCommandOutput) => void), cb?: (err: any, data?: ListObjectParentsCommandOutput) => void ): Promise<ListObjectParentsCommandOutput> | void { const command = new ListObjectParentsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns policies attached to an object in pagination fashion.</p> */ public listObjectPolicies( args: ListObjectPoliciesCommandInput, options?: __HttpHandlerOptions ): Promise<ListObjectPoliciesCommandOutput>; public listObjectPolicies( args: ListObjectPoliciesCommandInput, cb: (err: any, data?: ListObjectPoliciesCommandOutput) => void ): void; public listObjectPolicies( args: ListObjectPoliciesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListObjectPoliciesCommandOutput) => void ): void; public listObjectPolicies( args: ListObjectPoliciesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListObjectPoliciesCommandOutput) => void), cb?: (err: any, data?: ListObjectPoliciesCommandOutput) => void ): Promise<ListObjectPoliciesCommandOutput> | void { const command = new ListObjectPoliciesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a paginated list of all the outgoing <a>TypedLinkSpecifier</a> * information for an object. It also supports filtering by typed link facet and identity * attributes. For more information, see <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/directory_objects_links.html#directory_objects_links_typedlink">Typed Links</a>.</p> */ public listOutgoingTypedLinks( args: ListOutgoingTypedLinksCommandInput, options?: __HttpHandlerOptions ): Promise<ListOutgoingTypedLinksCommandOutput>; public listOutgoingTypedLinks( args: ListOutgoingTypedLinksCommandInput, cb: (err: any, data?: ListOutgoingTypedLinksCommandOutput) => void ): void; public listOutgoingTypedLinks( args: ListOutgoingTypedLinksCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListOutgoingTypedLinksCommandOutput) => void ): void; public listOutgoingTypedLinks( args: ListOutgoingTypedLinksCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListOutgoingTypedLinksCommandOutput) => void), cb?: (err: any, data?: ListOutgoingTypedLinksCommandOutput) => void ): Promise<ListOutgoingTypedLinksCommandOutput> | void { const command = new ListOutgoingTypedLinksCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns all of the <code>ObjectIdentifiers</code> to which a given policy is attached.</p> */ public listPolicyAttachments( args: ListPolicyAttachmentsCommandInput, options?: __HttpHandlerOptions ): Promise<ListPolicyAttachmentsCommandOutput>; public listPolicyAttachments( args: ListPolicyAttachmentsCommandInput, cb: (err: any, data?: ListPolicyAttachmentsCommandOutput) => void ): void; public listPolicyAttachments( args: ListPolicyAttachmentsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListPolicyAttachmentsCommandOutput) => void ): void; public listPolicyAttachments( args: ListPolicyAttachmentsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListPolicyAttachmentsCommandOutput) => void), cb?: (err: any, data?: ListPolicyAttachmentsCommandOutput) => void ): Promise<ListPolicyAttachmentsCommandOutput> | void { const command = new ListPolicyAttachmentsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the major version families of each published schema. If a major version ARN is provided as <code>SchemaArn</code>, the minor version revisions in that family are listed instead.</p> */ public listPublishedSchemaArns( args: ListPublishedSchemaArnsCommandInput, options?: __HttpHandlerOptions ): Promise<ListPublishedSchemaArnsCommandOutput>; public listPublishedSchemaArns( args: ListPublishedSchemaArnsCommandInput, cb: (err: any, data?: ListPublishedSchemaArnsCommandOutput) => void ): void; public listPublishedSchemaArns( args: ListPublishedSchemaArnsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListPublishedSchemaArnsCommandOutput) => void ): void; public listPublishedSchemaArns( args: ListPublishedSchemaArnsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListPublishedSchemaArnsCommandOutput) => void), cb?: (err: any, data?: ListPublishedSchemaArnsCommandOutput) => void ): Promise<ListPublishedSchemaArnsCommandOutput> | void { const command = new ListPublishedSchemaArnsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns tags for a resource. Tagging is currently supported only for directories with a * limit of 50 tags per directory. All 50 tags are returned for a given directory with this API * call.</p> */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a paginated list of all attribute definitions for a particular <a>TypedLinkFacet</a>. For more information, see <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/directory_objects_links.html#directory_objects_links_typedlink">Typed Links</a>.</p> */ public listTypedLinkFacetAttributes( args: ListTypedLinkFacetAttributesCommandInput, options?: __HttpHandlerOptions ): Promise<ListTypedLinkFacetAttributesCommandOutput>; public listTypedLinkFacetAttributes( args: ListTypedLinkFacetAttributesCommandInput, cb: (err: any, data?: ListTypedLinkFacetAttributesCommandOutput) => void ): void; public listTypedLinkFacetAttributes( args: ListTypedLinkFacetAttributesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTypedLinkFacetAttributesCommandOutput) => void ): void; public listTypedLinkFacetAttributes( args: ListTypedLinkFacetAttributesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTypedLinkFacetAttributesCommandOutput) => void), cb?: (err: any, data?: ListTypedLinkFacetAttributesCommandOutput) => void ): Promise<ListTypedLinkFacetAttributesCommandOutput> | void { const command = new ListTypedLinkFacetAttributesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a paginated list of <code>TypedLink</code> facet names for a particular schema. * For more information, see <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/directory_objects_links.html#directory_objects_links_typedlink">Typed Links</a>.</p> */ public listTypedLinkFacetNames( args: ListTypedLinkFacetNamesCommandInput, options?: __HttpHandlerOptions ): Promise<ListTypedLinkFacetNamesCommandOutput>; public listTypedLinkFacetNames( args: ListTypedLinkFacetNamesCommandInput, cb: (err: any, data?: ListTypedLinkFacetNamesCommandOutput) => void ): void; public listTypedLinkFacetNames( args: ListTypedLinkFacetNamesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTypedLinkFacetNamesCommandOutput) => void ): void; public listTypedLinkFacetNames( args: ListTypedLinkFacetNamesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTypedLinkFacetNamesCommandOutput) => void), cb?: (err: any, data?: ListTypedLinkFacetNamesCommandOutput) => void ): Promise<ListTypedLinkFacetNamesCommandOutput> | void { const command = new ListTypedLinkFacetNamesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists all policies from the root of the <a>Directory</a> to the object * specified. If there are no policies present, an empty list is returned. If policies are * present, and if some objects don't have the policies attached, it returns the <code>ObjectIdentifier</code> * for such objects. If policies are present, it returns <code>ObjectIdentifier</code>, <code>policyId</code>, and * <code>policyType</code>. Paths that don't lead to the root from the target object are ignored. For more * information, see <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/key_concepts_directory.html#key_concepts_policies">Policies</a>.</p> */ public lookupPolicy( args: LookupPolicyCommandInput, options?: __HttpHandlerOptions ): Promise<LookupPolicyCommandOutput>; public lookupPolicy(args: LookupPolicyCommandInput, cb: (err: any, data?: LookupPolicyCommandOutput) => void): void; public lookupPolicy( args: LookupPolicyCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: LookupPolicyCommandOutput) => void ): void; public lookupPolicy( args: LookupPolicyCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: LookupPolicyCommandOutput) => void), cb?: (err: any, data?: LookupPolicyCommandOutput) => void ): Promise<LookupPolicyCommandOutput> | void { const command = new LookupPolicyCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Publishes a development schema with a major version and a recommended minor version.</p> */ public publishSchema( args: PublishSchemaCommandInput, options?: __HttpHandlerOptions ): Promise<PublishSchemaCommandOutput>; public publishSchema( args: PublishSchemaCommandInput, cb: (err: any, data?: PublishSchemaCommandOutput) => void ): void; public publishSchema( args: PublishSchemaCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PublishSchemaCommandOutput) => void ): void; public publishSchema( args: PublishSchemaCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PublishSchemaCommandOutput) => void), cb?: (err: any, data?: PublishSchemaCommandOutput) => void ): Promise<PublishSchemaCommandOutput> | void { const command = new PublishSchemaCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Allows a schema to be updated using JSON upload. Only available for development schemas. See <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/schemas_jsonformat.html#schemas_json">JSON Schema Format</a> for more information.</p> */ public putSchemaFromJson( args: PutSchemaFromJsonCommandInput, options?: __HttpHandlerOptions ): Promise<PutSchemaFromJsonCommandOutput>; public putSchemaFromJson( args: PutSchemaFromJsonCommandInput, cb: (err: any, data?: PutSchemaFromJsonCommandOutput) => void ): void; public putSchemaFromJson( args: PutSchemaFromJsonCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutSchemaFromJsonCommandOutput) => void ): void; public putSchemaFromJson( args: PutSchemaFromJsonCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutSchemaFromJsonCommandOutput) => void), cb?: (err: any, data?: PutSchemaFromJsonCommandOutput) => void ): Promise<PutSchemaFromJsonCommandOutput> | void { const command = new PutSchemaFromJsonCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes the specified facet from the specified object.</p> */ public removeFacetFromObject( args: RemoveFacetFromObjectCommandInput, options?: __HttpHandlerOptions ): Promise<RemoveFacetFromObjectCommandOutput>; public removeFacetFromObject( args: RemoveFacetFromObjectCommandInput, cb: (err: any, data?: RemoveFacetFromObjectCommandOutput) => void ): void; public removeFacetFromObject( args: RemoveFacetFromObjectCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RemoveFacetFromObjectCommandOutput) => void ): void; public removeFacetFromObject( args: RemoveFacetFromObjectCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RemoveFacetFromObjectCommandOutput) => void), cb?: (err: any, data?: RemoveFacetFromObjectCommandOutput) => void ): Promise<RemoveFacetFromObjectCommandOutput> | void { const command = new RemoveFacetFromObjectCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>An API operation for adding tags to a resource.</p> */ public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>; public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void; public tagResource( args: TagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TagResourceCommandOutput) => void ): void; public tagResource( args: TagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void), cb?: (err: any, data?: TagResourceCommandOutput) => void ): Promise<TagResourceCommandOutput> | void { const command = new TagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>An API operation for removing tags from a resource.</p> */ public untagResource( args: UntagResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UntagResourceCommandOutput>; public untagResource( args: UntagResourceCommandInput, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void), cb?: (err: any, data?: UntagResourceCommandOutput) => void ): Promise<UntagResourceCommandOutput> | void { const command = new UntagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Does the following:</p> * <ol> * <li> * <p>Adds new <code>Attributes</code>, <code>Rules</code>, or <code>ObjectTypes</code>.</p> * </li> * <li> * <p>Updates existing <code>Attributes</code>, <code>Rules</code>, or <code>ObjectTypes</code>.</p> * </li> * <li> * <p>Deletes existing <code>Attributes</code>, <code>Rules</code>, or <code>ObjectTypes</code>.</p> * </li> * </ol> */ public updateFacet(args: UpdateFacetCommandInput, options?: __HttpHandlerOptions): Promise<UpdateFacetCommandOutput>; public updateFacet(args: UpdateFacetCommandInput, cb: (err: any, data?: UpdateFacetCommandOutput) => void): void; public updateFacet( args: UpdateFacetCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateFacetCommandOutput) => void ): void; public updateFacet( args: UpdateFacetCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateFacetCommandOutput) => void), cb?: (err: any, data?: UpdateFacetCommandOutput) => void ): Promise<UpdateFacetCommandOutput> | void { const command = new UpdateFacetCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates a given typed link’s attributes. Attributes to be updated must not contribute to the typed link’s identity, as defined by its <code>IdentityAttributeOrder</code>.</p> */ public updateLinkAttributes( args: UpdateLinkAttributesCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateLinkAttributesCommandOutput>; public updateLinkAttributes( args: UpdateLinkAttributesCommandInput, cb: (err: any, data?: UpdateLinkAttributesCommandOutput) => void ): void; public updateLinkAttributes( args: UpdateLinkAttributesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateLinkAttributesCommandOutput) => void ): void; public updateLinkAttributes( args: UpdateLinkAttributesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateLinkAttributesCommandOutput) => void), cb?: (err: any, data?: UpdateLinkAttributesCommandOutput) => void ): Promise<UpdateLinkAttributesCommandOutput> | void { const command = new UpdateLinkAttributesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates a given object's attributes.</p> */ public updateObjectAttributes( args: UpdateObjectAttributesCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateObjectAttributesCommandOutput>; public updateObjectAttributes( args: UpdateObjectAttributesCommandInput, cb: (err: any, data?: UpdateObjectAttributesCommandOutput) => void ): void; public updateObjectAttributes( args: UpdateObjectAttributesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateObjectAttributesCommandOutput) => void ): void; public updateObjectAttributes( args: UpdateObjectAttributesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateObjectAttributesCommandOutput) => void), cb?: (err: any, data?: UpdateObjectAttributesCommandOutput) => void ): Promise<UpdateObjectAttributesCommandOutput> | void { const command = new UpdateObjectAttributesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates the schema name with a new name. Only development schema names can be * updated.</p> */ public updateSchema( args: UpdateSchemaCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateSchemaCommandOutput>; public updateSchema(args: UpdateSchemaCommandInput, cb: (err: any, data?: UpdateSchemaCommandOutput) => void): void; public updateSchema( args: UpdateSchemaCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateSchemaCommandOutput) => void ): void; public updateSchema( args: UpdateSchemaCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateSchemaCommandOutput) => void), cb?: (err: any, data?: UpdateSchemaCommandOutput) => void ): Promise<UpdateSchemaCommandOutput> | void { const command = new UpdateSchemaCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates a <a>TypedLinkFacet</a>. For more information, see <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/directory_objects_links.html#directory_objects_links_typedlink">Typed Links</a>.</p> */ public updateTypedLinkFacet( args: UpdateTypedLinkFacetCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateTypedLinkFacetCommandOutput>; public updateTypedLinkFacet( args: UpdateTypedLinkFacetCommandInput, cb: (err: any, data?: UpdateTypedLinkFacetCommandOutput) => void ): void; public updateTypedLinkFacet( args: UpdateTypedLinkFacetCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateTypedLinkFacetCommandOutput) => void ): void; public updateTypedLinkFacet( args: UpdateTypedLinkFacetCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateTypedLinkFacetCommandOutput) => void), cb?: (err: any, data?: UpdateTypedLinkFacetCommandOutput) => void ): Promise<UpdateTypedLinkFacetCommandOutput> | void { const command = new UpdateTypedLinkFacetCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Upgrades a single directory in-place using the <code>PublishedSchemaArn</code> with schema updates found in <code>MinorVersion</code>. Backwards-compatible minor version upgrades are instantaneously available for readers on all objects in the directory. Note: This is a synchronous API call and upgrades only one schema on a given directory per call. To upgrade multiple directories from one schema, you would need to call this API on each directory.</p> */ public upgradeAppliedSchema( args: UpgradeAppliedSchemaCommandInput, options?: __HttpHandlerOptions ): Promise<UpgradeAppliedSchemaCommandOutput>; public upgradeAppliedSchema( args: UpgradeAppliedSchemaCommandInput, cb: (err: any, data?: UpgradeAppliedSchemaCommandOutput) => void ): void; public upgradeAppliedSchema( args: UpgradeAppliedSchemaCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpgradeAppliedSchemaCommandOutput) => void ): void; public upgradeAppliedSchema( args: UpgradeAppliedSchemaCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpgradeAppliedSchemaCommandOutput) => void), cb?: (err: any, data?: UpgradeAppliedSchemaCommandOutput) => void ): Promise<UpgradeAppliedSchemaCommandOutput> | void { const command = new UpgradeAppliedSchemaCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Upgrades a published schema under a new minor version revision using the current contents of <code>DevelopmentSchemaArn</code>.</p> */ public upgradePublishedSchema( args: UpgradePublishedSchemaCommandInput, options?: __HttpHandlerOptions ): Promise<UpgradePublishedSchemaCommandOutput>; public upgradePublishedSchema( args: UpgradePublishedSchemaCommandInput, cb: (err: any, data?: UpgradePublishedSchemaCommandOutput) => void ): void; public upgradePublishedSchema( args: UpgradePublishedSchemaCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpgradePublishedSchemaCommandOutput) => void ): void; public upgradePublishedSchema( args: UpgradePublishedSchemaCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpgradePublishedSchemaCommandOutput) => void), cb?: (err: any, data?: UpgradePublishedSchemaCommandOutput) => void ): Promise<UpgradePublishedSchemaCommandOutput> | void { const command = new UpgradePublishedSchemaCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import {Context as BaseContext, Api} from 'grammy' import {Message} from '@grammyjs/types' import {Body, TextBody, MediaBody, LocationBody, isMediaBody, isLocationBody, isTextBody, getBodyText, isVenueBody, VenueBody, isInvoiceBody} from './body' import {ensurePathMenu} from './path' import {InlineKeyboard} from './keyboard' import {MenuLike} from './menu-like' /** * Generic Method which is able to send a menu to a context (given a path where it is) */ export type SendMenuFunc<Context> = (menu: MenuLike<Context>, context: Context, path: string) => Promise<unknown> /** * Method which is able to send a menu to a chat. * Generated via `generateSendMenuToChatFunction`. */ export type SendMenuToChatFunction<Context> = (chatId: string | number, context: Context, other?: Readonly<Record<string, unknown>>) => Promise<Message> /** * Method which is able to edit a message in a chat into a menu. * Generated via `generateEditMessageIntoMenuFunction`. */ export type EditMessageIntoMenuFunction<Context> = (chatId: number | string, messageId: number, context: Context, other?: Readonly<Record<string, unknown>>) => Promise<Message | true> /** * Reply a menu to a context as a new message * @param menu menu to be shown * @param context current grammY context to reply the menu to it * @param path path of the menu * @param other optional additional options */ export async function replyMenuToContext<Context extends BaseContext>(menu: MenuLike<Context>, context: Context, path: string, other?: Readonly<Record<string, unknown>>) { ensurePathMenu(path) const body = await menu.renderBody(context, path) const keyboard = await menu.renderKeyboard(context, path) return replyRenderedMenuPartsToContext(body, keyboard, context, other) } /** * Edit the context into the menu. If thats not possible the current message is deleted and a new message is replied * @param menu menu to be shown * @param context current grammY context to edit the menu into * @param path path of the menu * @param other optional additional options */ export async function editMenuOnContext<Context extends BaseContext>(menu: MenuLike<Context>, context: Context, path: string, other: Readonly<Record<string, unknown>> = {}) { ensurePathMenu(path) const body = await menu.renderBody(context, path) const keyboard = await menu.renderKeyboard(context, path) const message = context.callbackQuery?.message if (!message) { return replyRenderedMenuPartsToContext(body, keyboard, context, other) } if (isMediaBody(body)) { if ('animation' in message || 'audio' in message || 'document' in message || 'photo' in message || 'video' in message) { return context.editMessageMedia( { type: body.type, media: body.media, caption: body.text, parse_mode: body.parse_mode, }, createGenericOther(keyboard, other), ) // eslint-disable-next-line promise/prefer-await-to-then .catch(catchMessageNotModified) } } else if (isLocationBody(body) || isVenueBody(body) || isInvoiceBody(body)) { // Dont edit the message, just recreate it. } else if (isTextBody(body)) { const text = getBodyText(body) if ('text' in message) { return context.editMessageText(text, createTextOther(body, keyboard, other)) // eslint-disable-next-line promise/prefer-await-to-then .catch(catchMessageNotModified) } } else { throw new TypeError('The body has to be a string or an object containing text or media. Check the grammy-inline-menu Documentation.') } // The current menu is incompatible: delete and reply new one const [repliedMessage] = await Promise.all([ replyRenderedMenuPartsToContext(body, keyboard, context, other), deleteMenuFromContext(context), ]) return repliedMessage } /** * Delete the message on the context. * If thats not possible the reply markup (keyboard) is removed. The user can not press any buttons on that old message. * @param context context of the message to be deleted */ export async function deleteMenuFromContext<Context extends BaseContext>(context: Context): Promise<void> { try { await context.deleteMessage() } catch { await context.editMessageReplyMarkup(undefined) } } /** * Deletes to menu of the current context and replies a new one ensuring the menu is at the end of the chat. * @param menu menu to be shown * @param context current grammY context to send the menu to * @param path path of the menu * @param other optional additional options */ export async function resendMenuToContext<Context extends BaseContext>(menu: MenuLike<Context>, context: Context, path: string, other: Readonly<Record<string, unknown>> = {}) { const [menuMessage] = await Promise.all([ replyMenuToContext(menu, context, path, other), deleteMenuFromContext(context), ]) return menuMessage } function catchMessageNotModified(error: unknown): false { if (error instanceof Error && error.message.includes('message is not modified')) { // ignore return false } throw error } async function replyRenderedMenuPartsToContext<Context extends BaseContext>(body: Body, keyboard: InlineKeyboard, context: Context, other: Readonly<Record<string, unknown>> = {}) { if (isMediaBody(body)) { const mediaOther = createSendMediaOther(body, keyboard, other) // eslint-disable-next-line default-case switch (body.type) { case 'animation': return context.replyWithAnimation(body.media, mediaOther) case 'audio': return context.replyWithAudio(body.media, mediaOther) case 'document': return context.replyWithDocument(body.media, mediaOther) case 'photo': return context.replyWithPhoto(body.media, mediaOther) case 'video': return context.replyWithVideo(body.media, mediaOther) } } if (isLocationBody(body)) { return context.replyWithLocation(body.location.latitude, body.location.longitude, createLocationOther(body, keyboard, other)) } if (isVenueBody(body)) { const {location, title, address} = body.venue return context.replyWithVenue(location.latitude, location.longitude, title, address, createVenueOther(body, keyboard, other)) } if (isInvoiceBody(body)) { const {title, description, payload, provider_token, currency, prices} = body.invoice return context.replyWithInvoice(title, description, payload, provider_token, currency, prices, createGenericOther(keyboard, other)) } if (isTextBody(body)) { const text = getBodyText(body) return context.reply(text, createTextOther(body, keyboard, other)) } throw new Error('The body has to be a string or an object containing text or media. Check the grammy-inline-menu Documentation.') } /** * Generate a function to send the menu towards a chat from external events * @param telegram The Telegram object to do the API calls with later on * @param menu menu to be shown * @param path path of the menu */ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types export function generateSendMenuToChatFunction<Context>(telegram: Readonly<Api>, menu: MenuLike<Context>, path: string): SendMenuToChatFunction<Context> { return async (chatId, context, other = {}) => { const body = await menu.renderBody(context, path) const keyboard = await menu.renderKeyboard(context, path) if (isMediaBody(body)) { const mediaOther = createSendMediaOther(body, keyboard, other) // eslint-disable-next-line default-case switch (body.type) { case 'animation': return telegram.sendAnimation(chatId, body.media, mediaOther) case 'audio': return telegram.sendAudio(chatId, body.media, mediaOther) case 'document': return telegram.sendDocument(chatId, body.media, mediaOther) case 'photo': return telegram.sendPhoto(chatId, body.media, mediaOther) case 'video': return telegram.sendVideo(chatId, body.media, mediaOther) } } if (isLocationBody(body)) { return telegram.sendLocation(chatId, body.location.latitude, body.location.longitude, createLocationOther(body, keyboard, other)) } if (isVenueBody(body)) { const {location, title, address} = body.venue return telegram.sendVenue(chatId, location.latitude, location.longitude, title, address, createVenueOther(body, keyboard, other)) } if (isInvoiceBody(body)) { const {title, description, payload, provider_token, currency, prices} = body.invoice return telegram.sendInvoice(chatId, title, description, payload, provider_token, currency, prices, createGenericOther(keyboard, other)) } if (isTextBody(body)) { const text = getBodyText(body) return telegram.sendMessage(chatId, text, createTextOther(body, keyboard, other)) } throw new Error('The body has to be a string or an object containing text or media. Check the grammy-inline-menu Documentation.') } } /** * Edit the message into the the menu. * This fails when the current message is not compatible with the menu (you cant edit a media message into a text message and vice versa) * @param telegram The Telegram object to do the API calls with later on * @param menu menu to be shown * @param path path of the menu */ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types export function generateEditMessageIntoMenuFunction<Context>(telegram: Readonly<Api>, menu: MenuLike<Context>, path: string): EditMessageIntoMenuFunction<Context> { return async (chatId, messageId, context, other = {}) => { const body = await menu.renderBody(context, path) const keyboard = await menu.renderKeyboard(context, path) if (isMediaBody(body)) { return telegram.editMessageMedia( chatId, messageId, { type: body.type, media: body.media, caption: body.text, parse_mode: body.parse_mode, }, createGenericOther(keyboard, other), ) } if (isLocationBody(body)) { throw new Error('You can not edit into a location body. You have to send the menu as a new message.') } if (isVenueBody(body)) { throw new Error('You can not edit into a venue body. You have to send the menu as a new message.') } if (isInvoiceBody(body)) { throw new Error('You can not edit into an invoice body. You have to send the menu as a new message.') } if (isTextBody(body)) { const text = getBodyText(body) return telegram.editMessageText(chatId, messageId, text, createTextOther(body, keyboard, other)) } throw new Error('The body has to be a string or an object containing text or media. Check the grammy-inline-menu Documentation.') } } function createTextOther(body: string | TextBody, keyboard: InlineKeyboard, base: Readonly<Record<string, unknown>>) { return { ...base, parse_mode: typeof body === 'string' ? undefined : body.parse_mode, disable_web_page_preview: typeof body !== 'string' && body.disable_web_page_preview, reply_markup: { inline_keyboard: keyboard.map(o => [...o]), }, } } function createSendMediaOther(body: MediaBody, keyboard: InlineKeyboard, base: Readonly<Record<string, unknown>>) { return { ...base, parse_mode: body.parse_mode, caption: body.text, reply_markup: { inline_keyboard: keyboard.map(o => [...o]), }, } } function createLocationOther(body: LocationBody, keyboard: InlineKeyboard, base: Readonly<Record<string, unknown>>) { return { ...base, live_period: body.live_period, reply_markup: { inline_keyboard: keyboard.map(o => [...o]), }, } } // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types function createVenueOther(body: VenueBody, keyboard: InlineKeyboard, base: Readonly<Record<string, unknown>>) { return { ...base, foursquare_id: body.venue.foursquare_id, foursquare_type: body.venue.foursquare_type, reply_markup: { inline_keyboard: keyboard.map(o => [...o]), }, } } function createGenericOther(keyboard: InlineKeyboard, base: Readonly<Record<string, unknown>>) { return { ...base, reply_markup: { inline_keyboard: keyboard.map(o => [...o]), }, } }
the_stack
import {AST, BindingPipe, LiteralPrimitive, PropertyRead, PropertyWrite, SafePropertyRead, TmplAstBoundAttribute, TmplAstBoundEvent, TmplAstNode, TmplAstReference, TmplAstTextAttribute, TmplAstVariable} from '@angular/compiler'; import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core'; import {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system'; import {DirectiveMeta, PipeMeta} from '@angular/compiler-cli/src/ngtsc/metadata'; import {DirectiveSymbol, ShimLocation, Symbol, SymbolKind, TemplateTypeChecker} from '@angular/compiler-cli/src/ngtsc/typecheck/api'; import {ExpressionIdentifier, hasExpressionIdentifier} from '@angular/compiler-cli/src/ngtsc/typecheck/src/comments'; import ts from 'typescript'; import {getTargetAtPosition, TargetNodeKind} from './template_target'; import {findTightestNode, getParentClassDeclaration} from './ts_utils'; import {getDirectiveMatchesForAttribute, getDirectiveMatchesForElementTag, getTemplateLocationFromShimLocation, isWithin, TemplateInfo, toTextSpan} from './utils'; /** Represents a location in a file. */ export interface FilePosition { fileName: string; position: number; } /** * Converts a `ShimLocation` to a more genericly named `FilePosition`. */ function toFilePosition(shimLocation: ShimLocation): FilePosition { return {fileName: shimLocation.shimPath, position: shimLocation.positionInShimFile}; } export interface TemplateLocationDetails { /** * A target node in a template. */ templateTarget: TmplAstNode|AST; /** * TypeScript locations which the template node maps to. A given template node might map to * several TS nodes. For example, a template node for an attribute might resolve to several * directives or a directive and one of its inputs. */ typescriptLocations: FilePosition[]; /** * The resolved Symbol for the template target. */ symbol: Symbol; } /** * Takes a position in a template and finds equivalent targets in TS files as well as details about * the targeted template node. */ export function getTargetDetailsAtTemplatePosition( {template, component}: TemplateInfo, position: number, templateTypeChecker: TemplateTypeChecker): TemplateLocationDetails[]|null { // Find the AST node in the template at the position. const positionDetails = getTargetAtPosition(template, position); if (positionDetails === null) { return null; } const nodes = positionDetails.context.kind === TargetNodeKind.TwoWayBindingContext ? positionDetails.context.nodes : [positionDetails.context.node]; const details: TemplateLocationDetails[] = []; for (const node of nodes) { // Get the information about the TCB at the template position. const symbol = templateTypeChecker.getSymbolOfNode(node, component); if (symbol === null) { continue; } const templateTarget = node; switch (symbol.kind) { case SymbolKind.Directive: case SymbolKind.Template: // References to elements, templates, and directives will be through template references // (#ref). They shouldn't be used directly for a Language Service reference request. break; case SymbolKind.Element: { const matches = getDirectiveMatchesForElementTag(symbol.templateNode, symbol.directives); details.push({ typescriptLocations: getPositionsForDirectives(matches), templateTarget, symbol, }); break; } case SymbolKind.DomBinding: { // Dom bindings aren't currently type-checked (see `checkTypeOfDomBindings`) so they don't // have a shim location. This means we can't match dom bindings to their lib.dom // reference, but we can still see if they match to a directive. if (!(node instanceof TmplAstTextAttribute) && !(node instanceof TmplAstBoundAttribute)) { return null; } const directives = getDirectiveMatchesForAttribute( node.name, symbol.host.templateNode, symbol.host.directives); details.push({ typescriptLocations: getPositionsForDirectives(directives), templateTarget, symbol, }); break; } case SymbolKind.Reference: { details.push({ typescriptLocations: [toFilePosition(symbol.referenceVarLocation)], templateTarget, symbol, }); break; } case SymbolKind.Variable: { if ((templateTarget instanceof TmplAstVariable)) { if (templateTarget.valueSpan !== undefined && isWithin(position, templateTarget.valueSpan)) { // In the valueSpan of the variable, we want to get the reference of the initializer. details.push({ typescriptLocations: [toFilePosition(symbol.initializerLocation)], templateTarget, symbol, }); } else if (isWithin(position, templateTarget.keySpan)) { // In the keySpan of the variable, we want to get the reference of the local variable. details.push({ typescriptLocations: [toFilePosition(symbol.localVarLocation)], templateTarget, symbol, }); } } else { // If the templateNode is not the `TmplAstVariable`, it must be a usage of the // variable somewhere in the template. details.push({ typescriptLocations: [toFilePosition(symbol.localVarLocation)], templateTarget, symbol, }); } break; } case SymbolKind.Input: case SymbolKind.Output: { details.push({ typescriptLocations: symbol.bindings.map(binding => toFilePosition(binding.shimLocation)), templateTarget, symbol, }); break; } case SymbolKind.Pipe: case SymbolKind.Expression: { details.push({ typescriptLocations: [toFilePosition(symbol.shimLocation)], templateTarget, symbol, }); break; } } } return details.length > 0 ? details : null; } /** * Given a set of `DirectiveSymbol`s, finds the equivalent `FilePosition` of the class declaration. */ function getPositionsForDirectives(directives: Set<DirectiveSymbol>): FilePosition[] { const allDirectives: FilePosition[] = []; for (const dir of directives.values()) { const dirClass = dir.tsSymbol.valueDeclaration; if (dirClass === undefined || !ts.isClassDeclaration(dirClass) || dirClass.name === undefined) { continue; } const {fileName} = dirClass.getSourceFile(); const position = dirClass.name.getStart(); allDirectives.push({fileName, position}); } return allDirectives; } /** * Creates a "key" for a rename/reference location by concatenating file name, span start, and span * length. This allows us to de-duplicate template results when an item may appear several times * in the TCB but map back to the same template location. */ export function createLocationKey(ds: ts.DocumentSpan) { return ds.fileName + ds.textSpan.start + ds.textSpan.length; } /** * Converts a given `ts.DocumentSpan` in a shim file to its equivalent `ts.DocumentSpan` in the * template. * * You can optionally provide a `requiredNodeText` that ensures the equivalent template node's text * matches. If it does not, this function will return `null`. */ export function convertToTemplateDocumentSpan<T extends ts.DocumentSpan>( shimDocumentSpan: T, templateTypeChecker: TemplateTypeChecker, program: ts.Program, requiredNodeText?: string): T|null { const sf = program.getSourceFile(shimDocumentSpan.fileName); if (sf === undefined) { return null; } const tcbNode = findTightestNode(sf, shimDocumentSpan.textSpan.start); if (tcbNode === undefined || hasExpressionIdentifier(sf, tcbNode, ExpressionIdentifier.EVENT_PARAMETER)) { // If the reference result is the $event parameter in the subscribe/addEventListener // function in the TCB, we want to filter this result out of the references. We really only // want to return references to the parameter in the template itself. return null; } // TODO(atscott): Determine how to consistently resolve paths. i.e. with the project // serverHost or LSParseConfigHost in the adapter. We should have a better defined way to // normalize paths. const mapping = getTemplateLocationFromShimLocation( templateTypeChecker, absoluteFrom(shimDocumentSpan.fileName), shimDocumentSpan.textSpan.start); if (mapping === null) { return null; } const {span, templateUrl} = mapping; if (requiredNodeText !== undefined && span.toString() !== requiredNodeText) { return null; } return { ...shimDocumentSpan, fileName: templateUrl, textSpan: toTextSpan(span), // Specifically clear other text span values because we do not have enough knowledge to // convert these to spans in the template. contextSpan: undefined, originalContextSpan: undefined, originalTextSpan: undefined, }; } /** * Finds the text and `ts.TextSpan` for the node at a position in a template. */ export function getRenameTextAndSpanAtPosition( node: TmplAstNode|AST, position: number): {text: string, span: ts.TextSpan}|null { if (node instanceof TmplAstBoundAttribute || node instanceof TmplAstTextAttribute || node instanceof TmplAstBoundEvent) { if (node.keySpan === undefined) { return null; } return {text: node.name, span: toTextSpan(node.keySpan)}; } else if (node instanceof TmplAstVariable || node instanceof TmplAstReference) { if (isWithin(position, node.keySpan)) { return {text: node.keySpan.toString(), span: toTextSpan(node.keySpan)}; } else if (node.valueSpan && isWithin(position, node.valueSpan)) { return {text: node.valueSpan.toString(), span: toTextSpan(node.valueSpan)}; } } if (node instanceof PropertyRead || node instanceof PropertyWrite || node instanceof SafePropertyRead || node instanceof BindingPipe) { return {text: node.name, span: toTextSpan(node.nameSpan)}; } else if (node instanceof LiteralPrimitive) { const span = toTextSpan(node.sourceSpan); const text = node.value; if (typeof text === 'string') { // The span of a string literal includes the quotes but they should be removed for renaming. span.start += 1; span.length -= 2; } return {text, span}; } return null; } /** * Retrives the `PipeMeta` or `DirectiveMeta` of the given `ts.Node`'s parent class. * * Returns `null` if the node has no parent class or there is no meta associated with the class. */ export function getParentClassMeta(requestNode: ts.Node, compiler: NgCompiler): PipeMeta| DirectiveMeta|null { const parentClass = getParentClassDeclaration(requestNode); if (parentClass === undefined) { return null; } return compiler.getMeta(parentClass); }
the_stack
import createEditor from '../../../helpers/create-editor' import mockCmdFn from '../../../helpers/command-mock' import mockFile from '../../../helpers/mock-file' import mockXHR from '../../../helpers/mock-xhr' import UploadImg from '../../../../src/menus/img/upload-img' let id = 1 const imgUrl = 'http://www.wangeditor.com/imgs/logo.jpeg' const errorUrl = 'error.jpeg' const uploadImgServer = 'http://106.12.198.214:3000/api/upload-img' const uploadImgServerWithHash = 'http://106.12.198.214:3000/api/upload-img#/123' const defaultRes = { status: 200, res: JSON.stringify({ data: ['url1'], errno: 0 }), } const mockXHRHttpRequest = (res: any = defaultRes) => { const mockXHRObject = mockXHR(res) const mockObject = jest.fn().mockImplementation(() => mockXHRObject) // @ts-ignore window.XMLHttpRequest = mockObject return mockXHRObject } const createUploadImgInstance = (config: any = {}) => { const editor = createEditor(document, `div${id++}`, '', config) const uploadImg = new UploadImg(editor) return uploadImg } const mockSupportCommand = () => { mockCmdFn(document) document.queryCommandSupported = jest.fn(() => true) } const defaultFiles = [{ name: 'test.png', size: 512, mimeType: 'image/png' }] const createMockFiles = (fileList: any[] = defaultFiles) => { const files = fileList.map(file => mockFile(file)) return files.filter(Boolean) } // mock img onload and onerror event const mockImgOnloadAndOnError = () => { // Mocking Image.prototype.src to call the onload or onerror // callbacks depending on the src passed to it // @ts-ignore Object.defineProperty(global.Image.prototype, 'src', { // Define the property setter set(src) { if (src === errorUrl) { // Call with setTimeout to simulate async loading setTimeout(() => this.onerror(new Error('mocked error'))) } else if (src === imgUrl) { setTimeout(() => this.onload()) } }, }) } describe('upload img', () => { beforeAll(() => { // mock img onload and onerror event mockImgOnloadAndOnError() }) test('调用 insertImg 可以网编辑器里插入图片', () => { const uploadImg = createUploadImgInstance() mockSupportCommand() uploadImg.insertImg(imgUrl) expect(document.execCommand).toBeCalledWith( 'insertHTML', false, `<img src="${imgUrl}" style="max-width:100%;" contenteditable="false"/>` ) }) test('调用 insertImg 可以网编辑器里插入图片,可以监听插入图片回调', () => { const callback = jest.fn() const uploadImg = createUploadImgInstance({ linkImgCallback: callback, }) mockSupportCommand() uploadImg.insertImg(imgUrl) expect(document.execCommand).toBeCalledWith( 'insertHTML', false, `<img src="${imgUrl}" style="max-width:100%;" contenteditable="false"/>` ) expect(callback).toBeCalledWith(imgUrl, undefined, undefined) }) test('调用 insertImg 可以网编辑器里插入图片,插入图片加载失败可以通过customAlert配置错误提示', done => { expect.assertions(1) const alertFn = jest.fn() const uploadImg = createUploadImgInstance({ customAlert: alertFn }) mockSupportCommand() uploadImg.insertImg(errorUrl) setTimeout(() => { expect(alertFn).toBeCalledWith( '插入图片错误', 'error', `wangEditor: 插入图片错误,图片链接 "${errorUrl}",下载链接失败` ) done() }, 200) }) test('可以调用 uploadImg 上传图片', done => { expect.assertions(1) const jestFn = jest.fn() const upload = createUploadImgInstance({ uploadImgServer, uploadImgHooks: { success: jestFn, }, }) const files = createMockFiles() const mockXHRObject = mockXHRHttpRequest() upload.uploadImg(files) mockXHRObject.onreadystatechange() setTimeout(() => { expect(jestFn).toBeCalled() done() }, 1000) }) test('调用 uploadImg 上传图片,如果传入的文件为空直接返回 undefined,不执行上传操作', () => { const upload = createUploadImgInstance() const res = upload.uploadImg([]) expect(res).toBeUndefined() }) test('调用 uploadImg 上传图片,如果没有配置customUploadImg, 则必须配置 uploadImgServer 或者 uploadImgShowBase64,否则直接返回', () => { const upload = createUploadImgInstance() const files = createMockFiles() const res = upload.uploadImg(files) expect(res).toBeUndefined() }) test('调用 uploadImg 上传图片,如果文件没有名字或者size为0,则会弹窗警告', () => { const fn = jest.fn() const upload = createUploadImgInstance({ uploadImgServer, customAlert: fn, }) const files = createMockFiles([{ name: '', size: 0, mimeType: 'image/png' }]) upload.uploadImg(files) expect(fn).toBeCalledWith('传入的文件不合法', 'warning') }) test('调用 uploadImg 上传图片,如果文件非图片,则提示错误信息', () => { const fn = jest.fn() const upload = createUploadImgInstance({ uploadImgServer, customAlert: fn, }) const files = createMockFiles([{ name: 'test.txt', size: 200, mimeType: 'text/plain' }]) upload.uploadImg(files) expect(fn).toBeCalledWith('图片验证未通过: \n【test.txt】不是图片', 'warning') }) test('调用 uploadImg 上传图片,如果文件体积大小超过配置的大小,则提示错误信息', () => { const fn = jest.fn() const upload = createUploadImgInstance({ uploadImgServer, uploadImgMaxSize: 5 * 1024 * 1024, customAlert: fn, }) const files = createMockFiles([ { name: 'test.png', size: 6 * 1024 * 1024, mimeType: 'image/png' }, ]) upload.uploadImg(files) expect(fn).toBeCalledWith(`图片验证未通过: \n【test.png】大于 5M`, 'warning') }) test('调用 uploadImg 上传图片,如果文件个数超过配置的的大小,则返回并提示错误信息', () => { const fn = jest.fn() const upload = createUploadImgInstance({ uploadImgServer, uploadImgMaxLength: 2, customAlert: fn, }) const files = createMockFiles([ { name: 'test1.png', size: 2048, mimeType: 'image/png' }, { name: 'test2.png', size: 2048, mimeType: 'image/png' }, { name: 'test3.png', size: 2048, mimeType: 'image/png' }, ]) upload.uploadImg(files) expect(fn).toBeCalledWith('一次最多上传2张图片', 'warning') }) test('调用 uploadImg 上传图片,如果配置了 customUploadImg 选项,则调用 customUploadImg 上传', () => { const fn = jest.fn() const upload = createUploadImgInstance({ uploadImgServer, customUploadImg: fn, }) const files = createMockFiles() upload.uploadImg(files) expect(fn).toBeCalled() }) test('调用 uploadImg 上传图片,如果配置了 uploadImgParamsWithUrl 为true, 则允许添加query参数', done => { expect.assertions(1) const fn = jest.fn() const upload = createUploadImgInstance({ uploadImgServer, uploadImgParams: { a: 'a', b: 'b', }, uploadImgParamsWithUrl: true, uploadImgHooks: { success: fn, }, }) const files = createMockFiles() const mockXHRObject = mockXHRHttpRequest() upload.uploadImg(files) mockXHRObject.onreadystatechange() setTimeout(() => { expect(mockXHRObject.open).toHaveBeenCalledWith('POST', `${uploadImgServer}?a=a&b=b`) done() }) }) test('调用 uploadImg 上传图片,uploadImgServer支持 hash query 参数拼接', done => { expect.assertions(1) const fn = jest.fn() const upload = createUploadImgInstance({ uploadImgServer: uploadImgServerWithHash, uploadImgParams: { a: 'a', b: 'b', }, uploadImgParamsWithUrl: true, uploadImgHooks: { success: fn, }, }) const files = createMockFiles([{ name: 'test1.png', size: 2048, mimeType: 'image/png' }]) const mockXHRObject = mockXHRHttpRequest() upload.uploadImg(files) mockXHRObject.onreadystatechange() setTimeout(() => { expect(mockXHRObject.open).toHaveBeenCalledWith( 'POST', `${uploadImgServer}?a=a&b=b#/123` ) done() }) }) test('调用 uploadImg 上传图片失败,支持配置 onError 钩子监听', done => { expect.assertions(1) const errorFn = jest.fn() const alertFn = jest.fn() const upload = createUploadImgInstance({ uploadImgServer, uploadImgHooks: { error: errorFn, }, customAlert: alertFn, }) const files = createMockFiles() const mockXHRObject = mockXHRHttpRequest({ status: 500 }) upload.uploadImg(files) mockXHRObject.onreadystatechange() setTimeout(() => { expect(errorFn).toBeCalled() done() }) }) test('调用 uploadImg 上传图片成功后数据返回格式不正常,支持配置 onFail 钩子监听', done => { expect.assertions(1) const fn = jest.fn() const alertFn = jest.fn() const upload = createUploadImgInstance({ uploadImgServer, uploadImgHooks: { fail: fn, }, customAlert: alertFn, }) const files = createMockFiles() const mockXHRObject = mockXHRHttpRequest({ status: 200, res: '{test: 123}', }) upload.uploadImg(files) mockXHRObject.onreadystatechange() setTimeout(() => { expect(fn).toBeCalled() done() }) }) test('调用 uploadImg 上传图片成功后,支持自定义插入图片函数', done => { expect.assertions(1) const insertFn = jest.fn() const upload = createUploadImgInstance({ uploadImgServer, uploadImgHooks: { customInsert: insertFn, }, }) const files = createMockFiles() const mockXHRObject = mockXHRHttpRequest() upload.uploadImg(files) mockXHRObject.onreadystatechange() setTimeout(() => { expect(insertFn).toBeCalled() done() }) }) test('调用 uploadImg, 如果配置 before 钩子阻止上传,会有错误提示', done => { expect.assertions(2) const beforeFn = jest.fn(() => ({ prevent: true, msg: '阻止发送请求' })) const alertFn = jest.fn() const upload = createUploadImgInstance({ uploadImgServer, uploadImgHooks: { before: beforeFn, }, customAlert: alertFn, }) const files = createMockFiles() const mockXHRObject = mockXHRHttpRequest() upload.uploadImg(files) mockXHRObject.onreadystatechange() setTimeout(() => { expect(beforeFn).toBeCalled() expect(alertFn).toBeCalledWith('阻止发送请求', 'error') done() }) }) test('调用 uploadImg 上传返回的错误码不符合条件, 会触发fail回调', done => { expect.assertions(1) const failFn = jest.fn() const alertFn = jest.fn() const upload = createUploadImgInstance({ uploadImgServer, uploadImgHooks: { fail: failFn, }, customAlert: alertFn, }) const files = createMockFiles() const mockXHRObject = mockXHRHttpRequest({ status: 200, res: { test: 123, errno: -1 }, }) upload.uploadImg(files) mockXHRObject.onreadystatechange() setTimeout(() => { expect(failFn).toBeCalled() done() }) }) test('调用 uploadImg 上传,如果配置 uploadImgShowBase64 参数,则直接插入图片 base64 字符串到编辑器', () => { const upload = createUploadImgInstance({ uploadImgShowBase64: true, }) const files = createMockFiles() const mockReadAsDataURL = jest.fn() // @ts-ignore jest.spyOn(global, 'FileReader').mockImplementation(() => { return { readAsDataURL: mockReadAsDataURL, } }) upload.uploadImg(files) expect(mockReadAsDataURL).toBeCalled() }) test('调用 uploadImg 上传超时会触发超时回调', done => { expect.assertions(1) const timeoutFn = jest.fn() const alertFn = jest.fn() const upload = createUploadImgInstance({ uploadImgServer, uploadImgHooks: { timeout: timeoutFn, }, customAlert: alertFn, }) const files = createMockFiles() const mockXHRObject = mockXHRHttpRequest() upload.uploadImg(files) mockXHRObject.ontimeout() setTimeout(() => { expect(timeoutFn).toBeCalled() done() }) }) })
the_stack
import { inspect } from 'util'; import type { AnyEntity, Constructor, Dictionary, EntityMetadata, EntityProperty, IPrimaryKey } from './typings'; export class ValidationError<T extends AnyEntity = AnyEntity> extends Error { constructor(message: string, private readonly entity?: T) { super(message); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = message; } /** * Gets instance of entity that caused this error. */ getEntity(): AnyEntity | undefined { return this.entity; } static fromWrongPropertyType(entity: AnyEntity, property: string, expectedType: string, givenType: string, givenValue: string): ValidationError { const entityName = entity.constructor.name; const msg = `Trying to set ${entityName}.${property} of type '${expectedType}' to '${givenValue}' of type '${givenType}'`; return new ValidationError(msg); } static fromCollectionNotInitialized(entity: AnyEntity, prop: EntityProperty): ValidationError { const entityName = entity.constructor.name; const msg = `${entityName}.${prop.name} is not initialized, define it as '${prop.name} = new Collection<${prop.type}>(this);'`; return new ValidationError(msg); } static fromMergeWithoutPK(meta: EntityMetadata): ValidationError { return new ValidationError(`You cannot merge entity '${meta.className}' without identifier!`); } static transactionRequired(): ValidationError { return new ValidationError('An open transaction is required for this operation'); } static entityNotManaged(entity: AnyEntity): ValidationError { return new ValidationError(`Entity ${entity.constructor.name} is not managed. An entity is managed if its fetched from the database or registered as new through EntityManager.persist()`); } static notEntity(owner: AnyEntity, prop: EntityProperty, data: any): ValidationError { const type = Object.prototype.toString.call(data).match(/\[object (\w+)]/)![1].toLowerCase(); return new ValidationError(`Entity of type ${prop.type} expected for property ${owner.constructor.name}.${prop.name}, ${inspect(data)} of type ${type} given. If you are using Object.assign(entity, data), use em.assign(entity, data) instead.`); } static notDiscoveredEntity(data: any, meta?: EntityMetadata): ValidationError { /* istanbul ignore next */ const type = meta?.className ?? Object.prototype.toString.call(data).match(/\[object (\w+)]/)![1].toLowerCase(); let err = `Trying to persist not discovered entity of type ${type}.`; /* istanbul ignore else */ if (meta) { err += ` Entity with this name was discovered, but not the prototype you are passing to the ORM. If using EntitySchema, be sure to point to the implementation via \`class\`.`; } return new ValidationError(err); } static invalidPropertyName(entityName: string, invalid: string): ValidationError { return new ValidationError(`Entity '${entityName}' does not have property '${invalid}'`); } static invalidType(type: Constructor<any>, value: any, mode: string): ValidationError { const valueType = Object.prototype.toString.call(value).match(/\[object (\w+)]/)![1].toLowerCase(); if (value instanceof Date) { value = value.toISOString(); } return new ValidationError(`Could not convert ${mode} value '${value}' of type '${valueType}' to type ${type.name}`); } static cannotModifyInverseCollection(owner: AnyEntity, property: EntityProperty): ValidationError { const inverseCollection = `${owner.constructor.name}.${property.name}`; const ownerCollection = `${property.type}.${property.mappedBy}`; const error = `You cannot modify inverse side of M:N collection ${inverseCollection} when the owning side is not initialized. ` + `Consider working with the owning side instead (${ownerCollection}).`; return new ValidationError(error, owner); } static cannotModifyReadonlyCollection(owner: AnyEntity, property: EntityProperty): ValidationError { return new ValidationError(`You cannot modify collection ${owner.constructor.name}.${property.name} as it is marked as readonly.`, owner); } static invalidCompositeIdentifier(meta: EntityMetadata): ValidationError { return new ValidationError(`Composite key required for entity ${meta.className}.`); } static cannotCommit(): ValidationError { return new ValidationError('You cannot call em.flush() from inside lifecycle hook handlers'); } static cannotUseOperatorsInsideEmbeddables(className: string, propName: string, payload: Dictionary): ValidationError { return new ValidationError(`Using operators inside embeddables is not allowed, move the operator above. (property: ${className}.${propName}, payload: ${inspect(payload)})`); } static invalidEmbeddableQuery(className: string, propName: string, embeddableType: string): ValidationError { return new ValidationError(`Invalid query for entity '${className}', property '${propName}' does not exist in embeddable '${embeddableType}'`); } } export class OptimisticLockError<T extends AnyEntity = AnyEntity> extends ValidationError<T> { static notVersioned(meta: EntityMetadata): OptimisticLockError { return new OptimisticLockError(`Cannot obtain optimistic lock on unversioned entity ${meta.className}`); } static lockFailed(entityOrName: AnyEntity | string): OptimisticLockError { const name = typeof entityOrName === 'string' ? entityOrName : entityOrName.constructor.name; const entity = typeof entityOrName === 'string' ? undefined : entityOrName; return new OptimisticLockError(`The optimistic lock on entity ${name} failed`, entity); } static lockFailedVersionMismatch(entity: AnyEntity, expectedLockVersion: number | Date, actualLockVersion: number | Date): OptimisticLockError { expectedLockVersion = expectedLockVersion instanceof Date ? expectedLockVersion.getTime() : expectedLockVersion; actualLockVersion = actualLockVersion instanceof Date ? actualLockVersion.getTime() : actualLockVersion; return new OptimisticLockError(`The optimistic lock failed, version ${expectedLockVersion} was expected, but is actually ${actualLockVersion}`, entity); } } export class MetadataError<T extends AnyEntity = AnyEntity> extends ValidationError<T> { static fromMissingPrimaryKey(meta: EntityMetadata): MetadataError { return new MetadataError(`${meta.className} entity is missing @PrimaryKey()`); } static fromWrongReference(meta: EntityMetadata, prop: EntityProperty, key: 'inversedBy' | 'mappedBy', owner?: EntityProperty): MetadataError { if (owner) { return MetadataError.fromMessage(meta, prop, `has wrong '${key}' reference type: ${owner.type} instead of ${meta.className}`); } return MetadataError.fromMessage(meta, prop, `has unknown '${key}' reference: ${prop.type}.${prop[key]}`); } static fromWrongTypeDefinition(meta: EntityMetadata, prop: EntityProperty): MetadataError { if (!prop.type) { return MetadataError.fromMessage(meta, prop, `is missing type definition`); } return MetadataError.fromMessage(meta, prop, `has unknown type: ${prop.type}`); } static fromWrongOwnership(meta: EntityMetadata, prop: EntityProperty, key: 'inversedBy' | 'mappedBy'): MetadataError { const type = key === 'inversedBy' ? 'owning' : 'inverse'; const other = key === 'inversedBy' ? 'mappedBy' : 'inversedBy'; return new MetadataError(`Both ${meta.className}.${prop.name} and ${prop.type}.${prop[key]} are defined as ${type} sides, use '${other}' on one of them`); } static fromWrongReferenceType(meta: EntityMetadata, owner: EntityProperty, prop: EntityProperty): MetadataError { return new MetadataError(`${meta.className}.${prop.name} is of type ${prop.reference} which is incompatible with its owning side ${prop.type}.${owner.name} of type ${owner.reference}`); } /* istanbul ignore next */ static entityNotFound(name: string, path: string): MetadataError { return new MetadataError(`Entity '${name}' not found in ${path}`); } static unknownIndexProperty(meta: EntityMetadata, prop: string, type: string): MetadataError { return new MetadataError(`Entity ${meta.className} has wrong ${type} definition: '${prop}' does not exist. You need to use property name, not column name.`); } static multipleVersionFields(meta: EntityMetadata, fields: string[]): MetadataError { return new MetadataError(`Entity ${meta.className} has multiple version properties defined: '${fields.join('\', \'')}'. Only one version property is allowed per entity.`); } static invalidVersionFieldType(meta: EntityMetadata): MetadataError { const prop = meta.properties[meta.versionProperty]; return new MetadataError(`Version property ${meta.className}.${prop.name} has unsupported type '${prop.type}'. Only 'number' and 'Date' are allowed.`); } static fromUnknownEntity(className: string, source: string): MetadataError { return new MetadataError(`Entity '${className}' was not discovered, please make sure to provide it in 'entities' array when initializing the ORM (used in ${source})`); } static noEntityDiscovered(): MetadataError { return new MetadataError('No entities were discovered'); } static onlyAbstractEntitiesDiscovered(): MetadataError { return new MetadataError('Only abstract entities were discovered, maybe you forgot to use @Entity() decorator?'); } static duplicateEntityDiscovered(paths: string[]): MetadataError { return new MetadataError(`Duplicate entity names are not allowed: ${paths.join(', ')}`); } static multipleDecorators(entityName: string, propertyName: string): MetadataError { return new MetadataError(`Multiple property decorators used on '${entityName}.${propertyName}' property`); } static missingMetadata(entity: string): MetadataError { return new MetadataError(`Metadata for entity ${entity} not found`); } static conflictingPropertyName(className: string, name: string, embeddedName: string): MetadataError { return new MetadataError(`Property ${className}:${name} is being overwritten by its child property ${embeddedName}:${name}. Consider using a prefix to overcome this issue.`); } private static fromMessage(meta: EntityMetadata, prop: EntityProperty, message: string): MetadataError { return new MetadataError(`${meta.className}.${prop.name} ${message}`); } } export class NotFoundError<T extends AnyEntity = AnyEntity> extends ValidationError<T> { static findOneFailed(name: string, where: Dictionary | IPrimaryKey): NotFoundError { return new NotFoundError(`${name} not found (${inspect(where)})`); } }
the_stack
import * as coreClient from "@azure/core-client"; /** Result of the request to list Microsoft.Features operations. It contains a list of operations and a URL link to get the next set of results. */ export interface OperationListResult { /** List of Microsoft.Features operations. */ value?: Operation[]; /** URL to get the next set of operation list results if there are any. */ nextLink?: string; } /** Microsoft.Features operation */ export interface Operation { /** Operation name: {provider}/{resource}/{operation} */ name?: string; /** The object that represents the operation. */ display?: OperationDisplay; } /** The object that represents the operation. */ export interface OperationDisplay { /** Service provider: Microsoft.Features */ provider?: string; /** Resource on which the operation is performed: Profile, endpoint, etc. */ resource?: string; /** Operation type: Read, write, delete, etc. */ operation?: string; } /** Error response indicates that the service is not able to process the incoming request. */ export interface ErrorResponse { /** The error details. */ error?: ErrorDefinition; } /** Error definition. */ export interface ErrorDefinition { /** * Service specific error code which serves as the substatus for the HTTP error code. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly code?: string; /** * Description of the error. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; /** Internal error details. */ details?: ErrorDefinition[]; } /** List of previewed features. */ export interface FeatureOperationsListResult { /** The array of features. */ value?: FeatureResult[]; /** The URL to use for getting the next set of results. */ nextLink?: string; } /** Previewed feature information. */ export interface FeatureResult { /** The name of the feature. */ name?: string; /** Properties of the previewed feature. */ properties?: FeatureProperties; /** The resource ID of the feature. */ id?: string; /** The resource type of the feature. */ type?: string; } /** Information about feature. */ export interface FeatureProperties { /** The registration state of the feature for the subscription. */ state?: string; } export interface SubscriptionFeatureRegistrationProperties { /** * The tenantId. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly tenantId?: string; /** * The subscriptionId. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly subscriptionId?: string; /** * The featureName. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly featureName?: string; /** * The featureDisplayName. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly displayName?: string; /** * The providerNamespace. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly providerNamespace?: string; /** The state. */ state?: SubscriptionFeatureRegistrationState; /** Authorization Profile */ authorizationProfile?: AuthorizationProfile; /** Key-value pairs for meta data. */ metadata?: { [propertyName: string]: string }; /** * The feature release date. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly releaseDate?: Date; /** * The feature registration date. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly registrationDate?: Date; /** * The feature documentation link. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly documentationLink?: string; /** * The feature approval type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly approvalType?: SubscriptionFeatureRegistrationApprovalType; /** Indicates whether feature should be displayed in Portal. */ shouldFeatureDisplayInPortal?: boolean; /** The feature description. */ description?: string; } /** Authorization Profile */ export interface AuthorizationProfile { /** * The requested time * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly requestedTime?: Date; /** * The requester * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly requester?: string; /** * The requester object id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly requesterObjectId?: string; /** * The approved time * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly approvedTime?: Date; /** * The approver * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly approver?: string; } /** An Azure proxy resource. */ export interface ProxyResource { /** * Azure resource Id. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * Azure resource name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * Azure resource type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; } /** The list of subscription feature registrations. */ export interface SubscriptionFeatureRegistrationList { /** The link used to get the next page of subscription feature registrations list. */ nextLink?: string; /** The list of subscription feature registrations. */ value?: SubscriptionFeatureRegistration[]; } /** Subscription feature registration details */ export type SubscriptionFeatureRegistration = ProxyResource & { properties?: SubscriptionFeatureRegistrationProperties; }; /** Known values of {@link SubscriptionFeatureRegistrationState} that the service accepts. */ export enum KnownSubscriptionFeatureRegistrationState { NotSpecified = "NotSpecified", NotRegistered = "NotRegistered", Pending = "Pending", Registering = "Registering", Registered = "Registered", Unregistering = "Unregistering", Unregistered = "Unregistered" } /** * Defines values for SubscriptionFeatureRegistrationState. \ * {@link KnownSubscriptionFeatureRegistrationState} can be used interchangeably with SubscriptionFeatureRegistrationState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **NotSpecified** \ * **NotRegistered** \ * **Pending** \ * **Registering** \ * **Registered** \ * **Unregistering** \ * **Unregistered** */ export type SubscriptionFeatureRegistrationState = string; /** Known values of {@link SubscriptionFeatureRegistrationApprovalType} that the service accepts. */ export enum KnownSubscriptionFeatureRegistrationApprovalType { NotSpecified = "NotSpecified", ApprovalRequired = "ApprovalRequired", AutoApproval = "AutoApproval" } /** * Defines values for SubscriptionFeatureRegistrationApprovalType. \ * {@link KnownSubscriptionFeatureRegistrationApprovalType} can be used interchangeably with SubscriptionFeatureRegistrationApprovalType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **NotSpecified** \ * **ApprovalRequired** \ * **AutoApproval** */ export type SubscriptionFeatureRegistrationApprovalType = string; /** Optional parameters. */ export interface ListOperationsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listOperations operation. */ export type ListOperationsResponse = OperationListResult; /** Optional parameters. */ export interface ListOperationsNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listOperationsNext operation. */ export type ListOperationsNextResponse = OperationListResult; /** Optional parameters. */ export interface FeaturesListAllOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAll operation. */ export type FeaturesListAllResponse = FeatureOperationsListResult; /** Optional parameters. */ export interface FeaturesListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type FeaturesListResponse = FeatureOperationsListResult; /** Optional parameters. */ export interface FeaturesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type FeaturesGetResponse = FeatureResult; /** Optional parameters. */ export interface FeaturesRegisterOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the register operation. */ export type FeaturesRegisterResponse = FeatureResult; /** Optional parameters. */ export interface FeaturesUnregisterOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the unregister operation. */ export type FeaturesUnregisterResponse = FeatureResult; /** Optional parameters. */ export interface FeaturesListAllNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAllNext operation. */ export type FeaturesListAllNextResponse = FeatureOperationsListResult; /** Optional parameters. */ export interface FeaturesListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type FeaturesListNextResponse = FeatureOperationsListResult; /** Optional parameters. */ export interface SubscriptionFeatureRegistrationsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type SubscriptionFeatureRegistrationsGetResponse = SubscriptionFeatureRegistration; /** Optional parameters. */ export interface SubscriptionFeatureRegistrationsCreateOrUpdateOptionalParams extends coreClient.OperationOptions { /** Subscription Feature Registration Type details. */ subscriptionFeatureRegistrationType?: SubscriptionFeatureRegistration; } /** Contains response data for the createOrUpdate operation. */ export type SubscriptionFeatureRegistrationsCreateOrUpdateResponse = SubscriptionFeatureRegistration; /** Optional parameters. */ export interface SubscriptionFeatureRegistrationsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface SubscriptionFeatureRegistrationsListBySubscriptionOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listBySubscription operation. */ export type SubscriptionFeatureRegistrationsListBySubscriptionResponse = SubscriptionFeatureRegistrationList; /** Optional parameters. */ export interface SubscriptionFeatureRegistrationsListAllBySubscriptionOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAllBySubscription operation. */ export type SubscriptionFeatureRegistrationsListAllBySubscriptionResponse = SubscriptionFeatureRegistrationList; /** Optional parameters. */ export interface SubscriptionFeatureRegistrationsListBySubscriptionNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listBySubscriptionNext operation. */ export type SubscriptionFeatureRegistrationsListBySubscriptionNextResponse = SubscriptionFeatureRegistrationList; /** Optional parameters. */ export interface SubscriptionFeatureRegistrationsListAllBySubscriptionNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAllBySubscriptionNext operation. */ export type SubscriptionFeatureRegistrationsListAllBySubscriptionNextResponse = SubscriptionFeatureRegistrationList; /** Optional parameters. */ export interface FeatureClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import React, { MemoExoticComponent } from 'react' import Post from 'src/pages/Post' import Settings from 'src/pages/Settings/index' import SettingsAppearance from 'src/pages/Settings/Appearance' import SettingsBlacklist from 'src/pages/Settings/Blacklist' import SettingsNewTheme from 'src/pages/Settings/NewTheme' import SettingsInterface from 'src/pages/Settings/Interface' import SettingsReader from 'src/pages/Settings/Reader' import SettingsPrivacy from 'src/pages/Settings/Privacy' import SettingsImport from 'src/pages/Settings/ImportSettings' import SettingsLanguage from 'src/pages/Settings/Language' import Search from 'src/pages/Search' import News from 'src/pages/News' import NotFound from 'src/pages/NotFound' import Thread from 'src/pages/Comments/Thread' import CommentsPage from 'src/pages/Comments' import getCachedMode from 'src/utils/getCachedMode' import AboutPage from 'src/pages/AboutPage' import Hubs from 'src/pages/Hubs/index' import User from 'src/pages/User/index' import { Redirect } from 'react-router' import Login from 'src/pages/Login' import { Theme } from '@material-ui/core' import Services from 'src/pages/Services' import Home from 'src/pages/Home/index' import Me from 'src/pages/Me' import UserArticles from 'src/pages/User/pages/Articles' import UserComments from 'src/pages/User/pages/Comments' import UserFavoriteArticles from 'src/pages/User/pages/FavArticles' import UserFavoriteComments from 'src/pages/User/pages/FavComments' import getContrastPaperColor from 'src/utils/getContrastPaperColor' import Hub from 'src/pages/Hub/index' import HubAuthors from 'src/pages/Hub/pages/Authors' import HubCompanies from 'src/pages/Hub/pages/Companies' export interface Route { path: string | string[] component: MemoExoticComponent<() => React.ReactElement> | React.ReactElement title?: string shouldShowAppBar?: boolean appBarColor?: (theme: Theme) => string shouldAppBarChangeColors?: boolean alias: string } export const routes: Route[] = [ { path: '/services', component: <Services />, title: 'Хабы', shouldShowAppBar: true, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'services', }, { path: '/auth', component: <Login />, title: 'Авторизация', shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'auth', }, { path: '/post/:id/comments/thread/:threadId', component: <Thread />, shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'commentsThread', }, { path: '/post/:id/comments', component: <CommentsPage />, shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'comments', }, { path: '/company/:alias/blog/:id/comments', component: <CommentsPage />, shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'comments', }, { path: '/company/:alias/blog/:id', component: <Post />, shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'post', }, { path: '/post/:id', component: <Post />, shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'post', }, { path: '/settings/reader', component: <SettingsReader />, title: 'Параметры чтения', shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => getContrastPaperColor(theme), alias: 'settingsReader', }, { path: '/settings/interface', component: <SettingsInterface />, title: 'Настройки интерфейса', shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => getContrastPaperColor(theme), alias: 'settingsInterface', }, { path: '/settings/privacy', component: <SettingsPrivacy />, title: 'Приватность', shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => getContrastPaperColor(theme), alias: 'settingsPrivacy', }, { path: '/settings/language', component: <SettingsLanguage />, title: 'Настройки языка', shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => getContrastPaperColor(theme), alias: 'settingsLanguage', }, { path: '/settings/appearance/new-theme', component: <SettingsNewTheme />, title: 'Новая тема', shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => getContrastPaperColor(theme), alias: 'settingsNewTheme', }, { path: '/settings/appearance/edit-theme/:themeType', component: <SettingsNewTheme isEditMode />, title: 'Изменение темы', shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => getContrastPaperColor(theme), alias: 'settingsEditTheme', }, { path: '/settings/appearance', component: <SettingsAppearance />, title: 'Внешний вид', shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => getContrastPaperColor(theme), alias: 'settingsAppearance', }, { path: '/settings/blacklist', component: <SettingsBlacklist />, title: 'Чёрный список', shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => getContrastPaperColor(theme), alias: 'settingsBlacklist', }, { path: '/settings/import', component: <SettingsImport />, title: 'Импорт настроек', shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => getContrastPaperColor(theme), alias: 'settingsBlacklist', }, { path: '/settings', component: <Settings />, title: 'Настройки', shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => getContrastPaperColor(theme), alias: 'settings', }, { path: '/geekr-about', component: <AboutPage />, title: 'О проекте', shouldShowAppBar: false, shouldAppBarChangeColors: true, appBarColor: (theme) => theme.palette.background.default, alias: 'geekrAbout', }, { path: ['/search', '/search/p/:page'], component: <Search />, title: 'Поиск', shouldShowAppBar: true, shouldAppBarChangeColors: true, appBarColor: (theme) => theme.palette.background.default, alias: 'search', }, { path: '/hubs/p/:page', component: <Hubs />, title: 'Хабы', shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'hubs', }, { path: '/hub/:alias/companies/p/:page', component: <HubCompanies />, shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'hubCompanies', }, { path: '/hub/:alias/authors/p/:page', component: <HubAuthors />, shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'hubAuthors', }, { path: [ '/hub/:alias/p/:page', '/hub/:alias/top0/p/:page', '/hub/:alias/top10/p/:page', '/hub/:alias/top25/p/:page', '/hub/:alias/top50/p/:page', '/hub/:alias/top100/p/:page', '/hub/:alias/top/daily/p/:page', '/hub/:alias/top/weekly/p/:page', '/hub/:alias/top/monthly/p/:page', '/hub/:alias/top/yearly/p/:page', '/hub/:alias/top/alltime/p/:page', ], component: <Hub />, shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'hub', }, { path: '/user/:login/favorites/comments/p/:page', component: <UserFavoriteComments />, shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'userFaviritesComments', }, { path: '/user/:login/favorites/articles/p/:page', component: <UserFavoriteArticles />, shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'userFaviritesArticles', }, { path: '/user/:login/comments/p/:page', component: <UserComments />, shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'userComments', }, { path: '/user/:login/articles/p/:page', component: <UserArticles />, shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'userArticles', }, { path: '/user/:login', component: <User />, shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'user', }, { path: '/news/p/:page', component: <News />, title: 'Новости', shouldShowAppBar: true, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.paper, alias: 'news', }, { path: [ '/all/p/:page', '/top0/p/:page', '/top10/p/:page', '/top25/p/:page', '/top50/p/:page', '/top100/p/:page', '/top/daily/p/:page', '/top/weekly/p/:page', '/top/monthly/p/:page', '/top/yearly/p/:page', '/top/alltime/p/:page', ], component: <Home />, shouldShowAppBar: true, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.paper, alias: 'feed', }, { path: '/me', component: <Me />, shouldShowAppBar: true, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: 'me', }, { path: '/', component: <Redirect to={`${getCachedMode().to}p/1`} />, shouldShowAppBar: true, shouldAppBarChangeColors: true, appBarColor: (theme) => theme.palette.background.default, alias: 'feed', }, { path: '/:404*', component: <NotFound />, title: '404', shouldShowAppBar: false, shouldAppBarChangeColors: false, appBarColor: (theme) => theme.palette.background.default, alias: '404', }, ]
the_stack
import {IViewSerialization} from "../datasetView"; import { allContentsKind, BasicColStats, CountWithConfidence, kindIsString, NextKList, RecordOrder, RemoteObjectId, } from "../javaBridge"; import {SchemaClass} from "../schemaClass"; import {IDataView} from "../ui/dataview"; import {Dialog, FieldKind} from "../ui/dialog"; import {FullPage, PageTitle} from "../ui/fullPage"; import {ContextMenu, SubMenu, TopMenu, TopMenuItem} from "../ui/menu"; import {TabularDisplay} from "../ui/tabularDisplay"; import { cloneToSet, formatNumber, ICancellable, Pair, PartialResult, significantDigits, Converters, assert } from "../util"; import {TableOperationCompleted, TableView} from "../modules"; import {TSViewBase} from "./tsViewBase"; import {BaseReceiver} from "../modules"; import {Receiver, RpcRequest} from "../rpc"; import {HillviewToplevel} from "../toplevel"; import {TableMeta} from "../ui/receiver"; /** * This class is used to browse through the columns of a table schema * and select columns from them. */ export class SchemaView extends TSViewBase { protected display: TabularDisplay; protected contextMenu: ContextMenu; protected stats: Map<string, BasicColStats> | null; protected counts: Map<string, CountWithConfidence> | null; protected nameDialog: Dialog; protected typeDialog: Dialog; constructor(remoteObjectId: RemoteObjectId, meta: TableMeta, page: FullPage) { super(remoteObjectId, meta, page, "Schema"); this.stats = null; this.defaultProvenance = "Schema view"; this.contextMenu = new ContextMenu(this.topLevel); const viewMenu = new SubMenu([{ text: "Table of selected columns", action: () => this.showTable(), help: "Show the data using a tabular view containing the selected columns (or all columns if none is selected).", }, { text: "Table of all columns", action: () => this.showTable(), help: "Show all columns in a tabular view.", }]); /* Dialog box for selecting columns based on name */ this.nameDialog = new Dialog("Select by name", "Allows selecting/deselecting columns by name using regular expressions"); const name = this.nameDialog.addTextField("selected", "Name (regex)", FieldKind.String, "", "Names of columns to select (regular expressions allowed)"); name.required = true; const actions: string[] = ["Add", "Remove"]; this.nameDialog.addSelectField("action", "Action", actions, "Add", "Add to or Remove from current selection"); this.nameDialog.setAction(() => { const regExp: RegExp = new RegExp(this.nameDialog.getFieldValue("selected")); // #nosec const action: string = this.nameDialog.getFieldValue("action"); this.nameAction(regExp, action); this.display.highlightSelectedRows(); this.selectedSummary(); }); /* Dialog box for selecting columns based on type*/ this.typeDialog = new Dialog("Select by type", "Allows selecting/deselecting columns based on type"); this.typeDialog.addSelectField("selectedType", "Type", allContentsKind, "String", "Type of columns you wish to select"); this.typeDialog.addSelectField("action", "Action", actions, "Add", "Add to or Remove from current selection"); this.typeDialog.setCacheTitle("SchemaTypeDialog"); this.typeDialog.setAction(() => { const selectedType: string = this.typeDialog.getFieldValue("selectedType"); const action: string = this.typeDialog.getFieldValue("action"); this.typeAction(selectedType, action); this.display.highlightSelectedRows(); this.selectedSummary(); }); const statDialog = new Dialog("Select by statistics", "Allow selecting/deselecting columns based on statistics\n" + "(only works on the columns whose statistics have been computed)."); statDialog.addBooleanField("selectEmpty", "All data missing", true, "Select all columns that only have missing data."); statDialog.addTextField("lowStder", "stddev/mean threshold", FieldKind.Double, ".1", "Select all columns where stddev/mean < threshold. If the mean is zero the columns is never selected."); statDialog.setCacheTitle("SchemaStatDialog"); statDialog.setAction(() => { const selE: boolean = statDialog.getBooleanValue("selectEmpty"); const stddev: number | null = statDialog.getFieldValueAsNumber("lowStder"); if (selE == null || stddev == null) { this.page.reportError("Illegal value"); return; } this.statAction(selE, stddev); this.display.highlightSelectedRows(); this.selectedSummary(); }); const selectMenu = new SubMenu([{ text: "By Name", action: () => this.nameDialog.show(), help: "Select Columns by name.", }, { text: "By Type", action: () => this.typeDialog.show(), help: "Select Columns by type.", }, { text: "By statistics", action: () => statDialog.show(), help: "Select columns by statistics." }]); const items: TopMenuItem[] = []; if (HillviewToplevel.instance.uiconfig.enableSaveAs) items.push(this.saveAsMenu()); items.push( {text: "View", subMenu: viewMenu, help: "Change the way the data is displayed."}, {text: "Select", subMenu: selectMenu, help: "Select columns based on attributes."}, this.chartMenu(), ); const menu = new TopMenu(items); this.page.setMenu(menu); this.topLevel.appendChild(document.createElement("br")); this.display = new TabularDisplay(); this.topLevel.appendChild(this.display.getHTMLRepresentation()); this.createDiv("summary"); } public export(): void { this.exportSchema(); } public static reconstruct(ser: IViewSerialization, page: FullPage): IDataView | null { const schema = new SchemaClass([]).deserialize(ser.schema); if (schema == null) return null; return new SchemaView(ser.remoteObjectId, { rowCount: ser.rowCount, schema, geoMetadata: ser.geoMetadata }, page); } public refresh(): void { this.show(0); } public show(elapsedMs: number): void { const scrollPos = this.display.scrollPosition(); this.display.clear(); const names = ["#", "Name", "Type"]; const descriptions = ["Column number", "Column name", "Type of data stored within the column"]; if (this.stats != null) { // This has to be kept in sync with basicColStats in TableTarget.java // There we ask for two moments. names.push("Min", "Max", "Average", "Stddev", "Missing"); descriptions.push("Minimum value", "Maximum value", "Average value", "Standard deviation", "Number of missing elements"); } if (this.counts != null) { names.push("~DistinctCount"); descriptions.push("Estimated number of distinct values"); } this.display.setColumns(names, descriptions); this.display.addRightClickHandler("Name", (e: Event) => { e.preventDefault(); this.nameDialog.show(); }); this.display.addRightClickHandler("Type", (e: Event) => { e.preventDefault(); this.typeDialog.show(); }); this.displayRows(); this.display.getHTMLRepresentation().setAttribute("overflow-x", "hidden"); if (this.meta.rowCount != null) this.summaryDiv!.textContent = formatNumber(this.meta.rowCount) + " rows"; this.page.setDataView(this); this.display.setScrollPosition(scrollPos); this.page.reportTime(elapsedMs); } private displayRows(): void { for (let i = 0; i < this.meta.schema.length; i++) { const cd = this.meta.schema.get(i); const data = [ (i + 1).toString(), cd.name, cd.kind.toString()]; if (this.stats != null) { const cs = this.stats.get(cd.name); if (cs != null) { if (cs.presentCount === 0) { data.push("", "", "", ""); } else { if (kindIsString(cd.kind)) { data.push(cs.minString!, cs.maxString!, "", ""); } else { let avg; let stddev; if (cd.kind === "Date" || cd.kind === "Time" || cd.kind === "LocalDate") { avg = Converters.valueToString(cs.moments[0], cd.kind, true); stddev = Converters.durationFromDouble(cs.moments[1]); } else { avg = significantDigits(cs.moments[0]); stddev = significantDigits(cs.moments[1]); } data.push( Converters.valueToString(cs.min!, cd.kind, true), Converters.valueToString(cs.max!, cd.kind, true), avg, stddev); } } data.push(formatNumber(cs.missingCount)); } else { data.push("", "", "", "", ""); } } if (this.counts != null) { const ct = this.counts.get(cd.name); if (ct != null) { data.push(String(ct.count)); } else { data.push(""); } } const row = this.display.addRow(data); row.oncontextmenu = (e) => this.createAndShowContextMenu(e); } } public createAndShowContextMenu(e: MouseEvent): void { if (e.ctrlKey && (e.button === 1)) { // Ctrl + click is interpreted as a right-click on macOS. // This makes sure it's interpreted as a column click with Ctrl. return; } const selectedColumn = this.getSelectedColNames().length === 1 ? this.getSelectedColNames()[0] : null; this.contextMenu.clear(); const selectedCount = this.display.selectedRows.size(); this.contextMenu.addItem({ text: "Drop", action: () => this.dropColumns(), help: "Drop the selected columns from the view." }, true); this.contextMenu.addItem({ text: "Show as table", action: () => this.showTable(), help: "Show the selected columns in a tabular view." }, true); this.contextMenu.addItem({ text: "Histogram", action: () => this.chart(this.meta.schema.getCheckedDescriptions(this.getSelectedColNames()), this.getSelectedColCount() == 1 ? "Histogram" : "2DHistogram"), help: "Plot the data in the selected columns as a histogram. Applies to one or two columns only." }, selectedCount >= 1 && selectedCount <= 2); this.contextMenu.addItem({ text: "Quartile vector", action: () => this.chart(this.meta.schema.getCheckedDescriptions(this.getSelectedColNames()), "QuartileVector"), help: "Plot the data in the selected columns as vector of quartiles. " + "Applies to two columns only.", }, selectedCount === 2); this.contextMenu.addItem({ text: "Heatmap", action: () => this.chart(this.meta.schema.getCheckedDescriptions(this.getSelectedColNames()), "Heatmap"), help: "Plot the data in the selected columns as a heatmap or as a Trellis plot of heatmaps. " + "Applies to two columns only.", }, selectedCount === 2); this.contextMenu.addItem({ text: "Trellis histograms", action: () => this.chart(this.meta.schema.getCheckedDescriptions(this.getSelectedColNames()), "TrellisHistogram"), help: "Plot the data in the selected columns as a Trellis plot of histograms. " + "Applies to two or three columns only.", }, selectedCount >= 2 && selectedCount <= 3); this.contextMenu.addItem({ text: "Trellis heatmaps", action: () => this.chart(this.meta.schema.getCheckedDescriptions(this.getSelectedColNames()), "TrellisHeatmap"), help: "Plot the data in the selected columns as a Trellis plot of heatmaps. " + "Applies to three columns only.", }, selectedCount === 3); this.contextMenu.addItem({ text: "Map", action: () => this.geo(this.meta.schema.find(this.getSelectedColNames()[0])!), help: "Plot the data in the selected columns on a map." }, selectedCount === 1 && this.hasGeo(this.getSelectedColNames()[0])); this.contextMenu.addItem({ text: "Estimate distinct elements", action: () => this.hLogLog(), help: "Compute an estimate of the number of different values that appear in the selected column.", }, selectedCount === 1); this.contextMenu.addItem({ text: "Filter...", action: () => this.showFilterDialog( selectedColumn, null, 0, null), help : "Eliminate data that matches/does not match a specific value.", }, selectedCount === 1); this.contextMenu.addItem({ text: "Compare...", action: () => this.showCompareDialog( selectedColumn, null, 0, null), help : "Eliminate data that matches/does not match a specific value.", }, selectedCount === 1); this.contextMenu.addItem({ text: "Create column in JS...", action: () => this.createJSColumnDialog(null, 0, null), help: "Add a new column computed from the selected columns.", }, true); this.contextMenu.addItem({ text: "Rename...", action: () => this.renameColumn(), help: "Give a new name to this column.", }, selectedCount === 1); this.contextMenu.addItem({ text: "Convert...", action: () => this.convert(selectedColumn != null ? selectedColumn : "", null, 0, null), help: "Convert the data in the selected column to a different data type.", }, selectedCount === 1); this.contextMenu.addItem({ text: "Frequent Elements...", action: () => this.heavyHittersDialog(), help: "Find the values that occur most frequently in the selected columns.", }, true); this.contextMenu.addItem({ text: "Basic statistics", action: () => this.getBasicStats(this.getSelectedColNames()), help: "Get basic statistics for the selected columns.", }, true); this.contextMenu.showAtMouse(e); } protected getBasicStats(cols: string[]): void { for (const desc of this.meta.schema.getCheckedDescriptions(cols)) if (desc.kind == "Interval") { this.page.reportError("Basic statistics not supported for interval column " + desc.name +"; skipping."); } cols = cols.filter(c => this.meta.schema.find(c)!.kind != "Interval"); if (cols.length === 0) return; const rr = this.createBasicColStatsRequest(cols); rr.invoke(new BasicColStatsReceiver(this.getPage(), this, cols, rr)); } public updateStats(cols: string[], stats: BasicColStats[]): void { console.assert(cols.length === stats.length); if (this.stats == null) this.stats = new Map<string, BasicColStats>(); for (let i = 0; i < cols.length; i++) { this.stats.set(cols[i], stats[i]); } this.show(0); } public updateCounts(cols: string[], counts: CountWithConfidence[]): void{ console.assert(cols.length === counts.length); if (this.counts == null) { this.counts = new Map<string, CountWithConfidence>(); } for (let i = 0; i < cols.length; i++) { this.counts.set(cols[i], counts[i]); } this.show(0); } public resize(): void { this.show(0); } protected doRenameColumn(from: string, to: string) { const rr = this.createRenameRequest(from, to); const schema = this.getSchema().renameColumn(from, to); if (schema == null) { this.page.reportError("Could not rename column '" + from + "' to '" + to + "'"); return; } const rec = new TableOperationCompleted(this.page, rr, { rowCount: this.meta.rowCount, schema, geoMetadata: this.meta.geoMetadata }, null, 0, null); rr.invoke(rec); } private dropColumns(): void { const selected = cloneToSet(this.getSelectedColNames()); const schema = this.meta.schema.filter((c) => !selected.has(c.name)); const rr = this.createProjectRequest(schema.schema); const rec = new TableOperationCompleted(this.page, rr, { rowCount: this.meta.rowCount, schema, geoMetadata: this.meta.geoMetadata }, null, 0, null); rr.invoke(rec); } private nameAction(regExp: RegExp, action: string): void { for (let i = 0; i < this.meta.schema.length; i++) { if (this.meta.schema.get(i).name.match(regExp)) { if (action === "Add") this.display.selectedRows.add(i); else if (action === "Remove") this.display.selectedRows.delete(i); } } } // Action triggered by the statistics selection menu. private statAction(allE: boolean, thresh: number): void { for (let i = 0; i < this.meta.schema.length; i++) { const name = this.meta.schema.get(i).name; const stat = this.stats!.get(name); if (stat == null) continue; if (allE && stat.presentCount === 0) this.display.selectedRows.add(i); const kind = this.meta.schema.get(i).kind; if (kind === "Date" || kind === "Time" || kind === "LocalDate") { if (stat.moments[0] === 0.0) this.display.selectedRows.add(i); continue; } if (stat.moments[0] > .001 && (stat.moments[1] / stat.moments[0]) < thresh) this.display.selectedRows.add(i); } } // noinspection JSUnusedLocalSymbols protected getCombineRenderer(title: PageTitle): (page: FullPage, operation: ICancellable<RemoteObjectId>) => BaseReceiver { assert(false); // not used } public getSelectedColCount(): number { return this.display.selectedRows.size(); } public getSelectedColNames(): string[] { const colNames: string[] = []; this.display.selectedRows.getStates().forEach((i) => colNames.push(this.meta.schema.get(i).name)); return colNames; } private selectedSummary(): void { this.summary!.set("selected", this.display.selectedRows.size()); this.summary!.display(); } /** * @param {string} selectedType: A type of column, from ContentsKind. * @param {string} action: Either Add or Remove. * This method updates the set of selected columns by adding/removing all columns of selectedType. */ private typeAction(selectedType: string, action: string): void { for (let i = 0; i < this.meta.schema.length; i++) { const kind = this.meta.schema.get(i).kind; if (kind === selectedType) { if (action === "Add") this.display.selectedRows.add(i); else if (action === "Remove") this.display.selectedRows.delete(i); } } } /** * This method displays the table consisting of only the columns contained in the schema above. */ private showTable(): void { const newPage = this.dataset.newPage(new PageTitle("Selected columns", "Schema view"), this.page); const selected = this.display.getSelectedRows(); let newSchema: SchemaClass; if (selected.size == 0) newSchema = this.meta.schema; else newSchema = this.meta.schema.filter((c) => selected.has(this.meta.schema.columnIndex(c.name))); const tv = new TableView(this.getRemoteObjectId()!, {rowCount: this.meta.rowCount, schema: newSchema, geoMetadata: this.meta.geoMetadata }, newPage); newPage.setDataView(tv); const nkl: NextKList = { rowsScanned: this.meta.rowCount, startPosition: 0, rows: [], aggregates: null }; tv.updateView(nkl, false, new RecordOrder([]), null); tv.updateCompleted(0); } } /** * Receives a set of basic column statistics and updates the SchemaView to display them. */ class BasicColStatsReceiver extends Receiver<Pair<BasicColStats, CountWithConfidence>[]> { constructor(page: FullPage, public sv: SchemaView, public cols: string[], rr: RpcRequest<Pair<BasicColStats, CountWithConfidence>[]>) { super(page, rr, "Get basic statistics"); } public onNext(value: PartialResult<Pair<BasicColStats, CountWithConfidence>[]>): void { super.onNext(value); if (value.data != null) { this.sv.updateStats(this.cols, value.data.map(p => p.first)); this.sv.updateCounts(this.cols, value.data.map(p => p.second)); } } }
the_stack
import type { Adapter } from "../adapters" import type { Provider, CredentialInput, ProviderType, OAuthConfig, EmailConfig, CredentialsConfig, } from "../providers" import type { TokenSetParameters } from "openid-client" import type { JWT, JWTOptions } from "../jwt" import type { LoggerInstance } from "../utils/logger" import type { CookieSerializeOptions } from "cookie" import type { NextApiRequest, NextApiResponse } from "next" import { InternalUrl } from "../utils/parse-url" export type Awaitable<T> = T | PromiseLike<T> export type { LoggerInstance } /** * Configure your NextAuth instance * * [Documentation](https://next-auth.js.org/configuration/options#options) */ export interface NextAuthOptions { /** * An array of authentication providers for signing in * (e.g. Google, Facebook, Twitter, GitHub, Email, etc) in any order. * This can be one of the built-in providers or an object with a custom provider. * * **Default value**: `[]` * * **Required**: *Yes* * * [Documentation](https://next-auth.js.org/configuration/options#providers) | [Providers documentation](https://next-auth.js.org/configuration/providers) */ providers: Provider[] /** * A random string used to hash tokens, sign cookies and generate cryptographic keys. * If not specified, it falls back to `jwt.secret` or `NEXTAUTH_SECRET` from environment vairables. * Otherwise it will use a hash of all configuration options, including Client ID / Secrets for entropy. * * NOTE: The last behavior is extrmely volatile, and will throw an error in production. * * **Default value**: `string` (SHA hash of the "options" object) * * **Required**: No - **but strongly recommended**! * * [Documentation](https://next-auth.js.org/configuration/options#secret) */ secret?: string /** * Configure your session like if you want to use JWT or a database, * how long until an idle session expires, or to throttle write operations in case you are using a database. * * **Default value**: See the documentation page * * **Required**: No * * [Documentation](https://next-auth.js.org/configuration/options#session) */ session?: Partial<SessionOptions> /** * JSON Web Tokens are enabled by default if you have not specified a database. * By default JSON Web Tokens are signed (JWS) but not encrypted (JWE), * as JWT encryption adds additional overhead and comes with some caveats. * You can enable encryption by setting `encryption: true`. * * **Default value**: See the documentation page * * **Required**: *No* * * [Documentation](https://next-auth.js.org/configuration/options#jwt) */ jwt?: Partial<JWTOptions> /** * Specify URLs to be used if you want to create custom sign in, sign out and error pages. * Pages specified will override the corresponding built-in page. * * **Default value**: `{}` * * **Required**: *No* * @example * * ```js * pages: { * signIn: '/auth/signin', * signOut: '/auth/signout', * error: '/auth/error', * verifyRequest: '/auth/verify-request', * newUser: '/auth/new-user' * } * ``` * * [Documentation](https://next-auth.js.org/configuration/options#pages) | [Pages documentation](https://next-auth.js.org/configuration/pages) */ pages?: Partial<PagesOptions> /** * Callbacks are asynchronous functions you can use to control what happens when an action is performed. * Callbacks are *extremely powerful*, especially in scenarios involving JSON Web Tokens * as they **allow you to implement access controls without a database** and to **integrate with external databases or APIs**. * * **Default value**: See the Callbacks documentation * * **Required**: *No* * * [Documentation](https://next-auth.js.org/configuration/options#callbacks) | [Callbacks documentation](https://next-auth.js.org/configuration/callbacks) */ callbacks?: Partial<CallbacksOptions> /** * Events are asynchronous functions that do not return a response, they are useful for audit logging. * You can specify a handler for any of these events below - e.g. for debugging or to create an audit log. * The content of the message object varies depending on the flow * (e.g. OAuth or Email authentication flow, JWT or database sessions, etc), * but typically contains a user object and/or contents of the JSON Web Token * and other information relevant to the event. * * **Default value**: `{}` * * **Required**: *No* * * [Documentation](https://next-auth.js.org/configuration/options#events) | [Events documentation](https://next-auth.js.org/configuration/events) */ events?: Partial<EventCallbacks> /** * You can use the adapter option to pass in your database adapter. * * * **Required**: *No* * * [Documentation](https://next-auth.js.org/configuration/options#adapter) | * [Community adapters](https://github.com/nextauthjs/adapters) */ adapter?: Adapter /** * Set debug to true to enable debug messages for authentication and database operations. * * **Default value**: `false` * * **Required**: *No* * * - ⚠ If you added a custom `logger`, this setting is ignored. * * [Documentation](https://next-auth.js.org/configuration/options#debug) | [Logger documentation](https://next-auth.js.org/configuration/options#logger) */ debug?: boolean /** * Override any of the logger levels (`undefined` levels will use the built-in logger), * and intercept logs in NextAuth. You can use this option to send NextAuth logs to a third-party logging service. * * **Default value**: `console` * * **Required**: *No* * * @example * * ```js * // /pages/api/auth/[...nextauth].js * import log from "logging-service" * export default NextAuth({ * logger: { * error(code, ...message) { * log.error(code, message) * }, * warn(code, ...message) { * log.warn(code, message) * }, * debug(code, ...message) { * log.debug(code, message) * } * } * }) * ``` * * - ⚠ When set, the `debug` option is ignored * * [Documentation](https://next-auth.js.org/configuration/options#logger) | * [Debug documentation](https://next-auth.js.org/configuration/options#debug) */ logger?: Partial<LoggerInstance> /** * Changes the theme of pages. * Set to `"light"` if you want to force pages to always be light. * Set to `"dark"` if you want to force pages to always be dark. * Set to `"auto"`, (or leave this option out)if you want the pages to follow the preferred system theme. * * **Default value**: `"auto"` * * **Required**: *No* * * [Documentation](https://next-auth.js.org/configuration/options#theme) | [Pages documentation]("https://next-auth.js.org/configuration/pages") */ theme?: Theme /** * When set to `true` then all cookies set by NextAuth.js will only be accessible from HTTPS URLs. * This option defaults to `false` on URLs that start with `http://` (e.g. http://localhost:3000) for developer convenience. * You can manually set this option to `false` to disable this security feature and allow cookies * to be accessible from non-secured URLs (this is not recommended). * * **Default value**: `true` for HTTPS and `false` for HTTP sites * * **Required**: No * * [Documentation](https://next-auth.js.org/configuration/options#usesecurecookies) * * - ⚠ **This is an advanced option.** Advanced options are passed the same way as basic options, * but **may have complex implications** or side effects. * You should **try to avoid using advanced options** unless you are very comfortable using them. */ useSecureCookies?: boolean /** * You can override the default cookie names and options for any of the cookies used by NextAuth.js. * You can specify one or more cookies with custom properties, * but if you specify custom options for a cookie you must provide all the options for that cookie. * If you use this feature, you will likely want to create conditional behavior * to support setting different cookies policies in development and production builds, * as you will be opting out of the built-in dynamic policy. * * **Default value**: `{}` * * **Required**: No * * - ⚠ **This is an advanced option.** Advanced options are passed the same way as basic options, * but **may have complex implications** or side effects. * You should **try to avoid using advanced options** unless you are very comfortable using them. * * [Documentation](https://next-auth.js.org/configuration/options#cookies) | [Usage example](https://next-auth.js.org/configuration/options#example) */ cookies?: Partial<CookiesOptions> } /** * Change the theme of the built-in pages. * * [Documentation](https://next-auth.js.org/configuration/options#theme) | * [Pages](https://next-auth.js.org/configuration/pages) */ export interface Theme { colorScheme: "auto" | "dark" | "light" logo?: string brandColor?: string } /** * Different tokens returned by OAuth Providers. * Some of them are available with different casing, * but they refer to the same value. */ export type TokenSet = TokenSetParameters /** * Usually contains information about the provider being used * and also extends `TokenSet`, which is different tokens returned by OAuth Providers. */ export interface DefaultAccount extends Partial<TokenSet> { /** * This value depends on the type of the provider being used to create the account. * - oauth: The OAuth account's id, returned from the `profile()` callback. * - email: The user's email address. * - credentials: `id` returned from the `authorize()` callback */ providerAccountId: string /** id of the user this account belongs to. */ userId: string /** id of the provider used for this account */ provider: string /** Provider's type for this account */ type: ProviderType } export interface Account extends Record<string, unknown>, DefaultAccount {} export interface DefaultProfile { sub?: string name?: string email?: string image?: string } /** The OAuth profile returned from your provider */ export interface Profile extends Record<string, unknown>, DefaultProfile {} /** [Documentation](https://next-auth.js.org/configuration/callbacks) */ export interface CallbacksOptions< P extends Record<string, unknown> = Profile, A extends Record<string, unknown> = Account > { /** * Use this callback to control if a user is allowed to sign in. * Returning true will continue the sign-in flow. * Throwing an error or returning a string will stop the flow, and redirect the user. * * [Documentation](https://next-auth.js.org/configuration/callbacks#sign-in-callback) */ signIn: (params: { user: User account: A /** * If OAuth provider is used, it contains the full * OAuth profile returned by your provider. */ profile: P & Record<string, unknown> /** * If Email provider is used, on the first call, it contains a * `verificationRequest: true` property to indicate it is being triggered in the verification request flow. * When the callback is invoked after a user has clicked on a sign in link, * this property will not be present. You can check for the `verificationRequest` property * to avoid sending emails to addresses or domains on a blocklist or to only explicitly generate them * for email address in an allow list. */ email: { verificationRequest?: boolean } /** If Credentials provider is used, it contains the user credentials */ credentials?: Record<string, CredentialInput> }) => Awaitable<string | boolean> /** * This callback is called anytime the user is redirected to a callback URL (e.g. on signin or signout). * By default only URLs on the same URL as the site are allowed, * you can use this callback to customise that behaviour. * * [Documentation](https://next-auth.js.org/configuration/callbacks#redirect-callback) */ redirect: (params: { /** URL provided as callback URL by the client */ url: string /** Default base URL of site (can be used as fallback) */ baseUrl: string }) => Awaitable<string> /** * This callback is called whenever a session is checked. * (Eg.: invoking the `/api/session` endpoint, using `useSession` or `getSession`) * * ⚠ By default, only a subset (email, name, image) * of the token is returned for increased security. * * If you want to make something available you added to the token through the `jwt` callback, * you have to explicitely forward it here to make it available to the client. * * [Documentation](https://next-auth.js.org/configuration/callbacks#session-callback) | * [`jwt` callback](https://next-auth.js.org/configuration/callbacks#jwt-callback) | * [`useSession`](https://next-auth.js.org/getting-started/client#usesession) | * [`getSession`](https://next-auth.js.org/getting-started/client#getsession) | * */ session: (params: { session: Session user: User token: JWT }) => Awaitable<Session> /** * This callback is called whenever a JSON Web Token is created (i.e. at sign in) * or updated (i.e whenever a session is accessed in the client). * Its content is forwarded to the `session` callback, * where you can control what should be returned to the client. * Anything else will be kept from your front-end. * * ⚠ By default the JWT is signed, but not encrypted. * * [Documentation](https://next-auth.js.org/configuration/callbacks#jwt-callback) | * [`session` callback](https://next-auth.js.org/configuration/callbacks#session-callback) */ jwt: (params: { token: JWT user?: User account?: A profile?: P isNewUser?: boolean }) => Awaitable<JWT> } /** [Documentation](https://next-auth.js.org/configuration/options#cookies) */ export interface CookieOption { name: string options: CookieSerializeOptions } /** [Documentation](https://next-auth.js.org/configuration/options#cookies) */ export interface CookiesOptions { sessionToken: CookieOption callbackUrl: CookieOption csrfToken: CookieOption pkceCodeVerifier: CookieOption state: CookieOption } /** * The various event callbacks you can register for from next-auth * * [Documentation](https://next-auth.js.org/configuration/events) */ export interface EventCallbacks { /** * If using a `credentials` type auth, the user is the raw response from your * credential provider. * For other providers, you'll get the User object from your adapter, the account, * and an indicator if the user was new to your Adapter. */ signIn: (message: { user: User account: Account profile?: Profile isNewUser?: boolean }) => Awaitable<void> /** * The message object will contain one of these depending on * if you use JWT or database persisted sessions: * - `token`: The JWT token for this session. * - `session`: The session object from your adapter that is being ended. */ signOut: (message: { session: Session; token: JWT }) => Awaitable<void> createUser: (message: { user: User }) => Awaitable<void> updateUser: (message: { user: User }) => Awaitable<void> linkAccount: (message: { user: User; account: Account }) => Awaitable<void> /** * The message object will contain one of these depending on * if you use JWT or database persisted sessions: * - `token`: The JWT token for this session. * - `session`: The session object from your adapter. */ session: (message: { session: Session; token: JWT }) => Awaitable<void> } export type EventType = keyof EventCallbacks /** [Documentation](https://next-auth.js.org/configuration/pages) */ export interface PagesOptions { signIn: string signOut: string /** Error code passed in query string as ?error= */ error: string verifyRequest: string /** If set, new users will be directed here on first sign in */ newUser: string } export type ISODateString = string export interface DefaultSession extends Record<string, unknown> { user?: { name?: string | null email?: string | null image?: string | null } expires: ISODateString } /** * Returned by `useSession`, `getSession`, returned by the `session` callback * and also the shape received as a prop on the `SessionProvider` React Context * * [`useSession`](https://next-auth.js.org/getting-started/client#usesession) | * [`getSession`](https://next-auth.js.org/getting-started/client#getsession) | * [`SessionProvider`](https://next-auth.js.org/getting-started/client#sessionprovider) | * [`session` callback](https://next-auth.js.org/configuration/callbacks#jwt-callback) */ export interface Session extends Record<string, unknown>, DefaultSession {} export type SessionStrategy = "jwt" | "database" /** [Documentation](https://next-auth.js.org/configuration/options#session) */ export interface SessionOptions { /** * Choose how you want to save the user session. * The default is `"jwt"`, an encrypted JWT (JWE) in the session cookie. * * If you use an `adapter` however, we default it to `"database"` instead. * You can still force a JWT session by explicitly defining `"jwt"`. * * When using `"database"`, the session cookie will only contain a `sessionToken` value, * which is used to look up the session in the database. * * [Documentation](https://next-auth.js.org/configuration/options#session) | [Adapter](https://next-auth.js.org/configuration/options#adapter) | [About JSON Web Tokens](https://next-auth.js.org/faq#json-web-tokens) */ strategy: SessionStrategy /** * Relative time from now in seconds when to expire the session * @default 2592000 // 30 days */ maxAge: number /** * How often the session should be updated in seconds. * If set to `0`, session is updated every time. * @default 86400 // 1 day */ updateAge: number } export interface DefaultUser { id: string name?: string | null email?: string | null image?: string | null } /** * The shape of the returned object in the OAuth providers' `profile` callback, * available in the `jwt` and `session` callbacks, * or the second parameter of the `session` callback, when using a database. * * [`signIn` callback](https://next-auth.js.org/configuration/callbacks#sign-in-callback) | * [`session` callback](https://next-auth.js.org/configuration/callbacks#jwt-callback) | * [`jwt` callback](https://next-auth.js.org/configuration/callbacks#jwt-callback) | * [`profile` OAuth provider callback](https://next-auth.js.org/configuration/providers#using-a-custom-provider) */ export interface User extends Record<string, unknown>, DefaultUser {} // Below are types that are only supposed be used by next-auth internally /** @internal */ export type InternalProvider<T extends ProviderType = any> = (T extends "oauth" ? OAuthConfig<any> : T extends "email" ? EmailConfig : T extends "credentials" ? CredentialsConfig : never) & { signinUrl: string callbackUrl: string } export type NextAuthAction = | "providers" | "session" | "csrf" | "signin" | "signout" | "callback" | "verify-request" | "error" | "_log" /** @internal */ export interface InternalOptions<T extends ProviderType = any> { providers: InternalProvider[] /** * Parsed from `NEXTAUTH_URL` or `x-forwarded-host` on Vercel. * @default "http://localhost:3000/api/auth" */ url: InternalUrl action: NextAuthAction provider: T extends string ? InternalProvider<T> : InternalProvider<T> | undefined csrfToken?: string csrfTokenVerified?: boolean secret: string theme: Theme debug: boolean logger: LoggerInstance session: Required<SessionOptions> pages: Partial<PagesOptions> jwt: JWTOptions events: Partial<EventCallbacks> adapter?: Adapter callbacks: CallbacksOptions cookies: CookiesOptions callbackUrl: string } /** @internal */ export interface NextAuthRequest extends NextApiRequest { options: InternalOptions } /** @internal */ export type NextAuthResponse<T = any> = NextApiResponse<T> /** @internal */ // eslint-disable-next-line @typescript-eslint/no-invalid-void-type export type NextAuthApiHandler<Result = void, Response = any> = ( req: NextAuthRequest, res: NextAuthResponse<Response> ) => Awaitable<Result>
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the RelayManagementClient. */ export interface Operations { /** * Lists all available Relay REST API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all available Relay REST API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; list(callback: ServiceCallback<models.OperationListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; /** * Lists all available Relay REST API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all available Relay REST API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.OperationListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; } /** * @class * Namespaces * __NOTE__: An instance of this class is automatically created for an * instance of the RelayManagementClient. */ export interface Namespaces { /** * Check the specified namespace name availability. * * @param {object} parameters Parameters to check availability of the specified * namespace name. * * @param {string} parameters.name The namespace name to check for * availability. The namespace name can contain only letters, numbers, and * hyphens. The namespace must start with a letter, and it must end with a * letter or number. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CheckNameAvailabilityResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ checkNameAvailabilityMethodWithHttpOperationResponse(parameters: models.CheckNameAvailability, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CheckNameAvailabilityResult>>; /** * Check the specified namespace name availability. * * @param {object} parameters Parameters to check availability of the specified * namespace name. * * @param {string} parameters.name The namespace name to check for * availability. The namespace name can contain only letters, numbers, and * hyphens. The namespace must start with a letter, and it must end with a * letter or number. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CheckNameAvailabilityResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CheckNameAvailabilityResult} [result] - The deserialized result object if an error did not occur. * See {@link CheckNameAvailabilityResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ checkNameAvailabilityMethod(parameters: models.CheckNameAvailability, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.CheckNameAvailabilityResult>; checkNameAvailabilityMethod(parameters: models.CheckNameAvailability, callback: ServiceCallback<models.CheckNameAvailabilityResult>): void; checkNameAvailabilityMethod(parameters: models.CheckNameAvailability, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CheckNameAvailabilityResult>): void; /** * Lists all the available namespaces within the subscription regardless of the * resourceGroups. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RelayNamespaceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RelayNamespaceListResult>>; /** * Lists all the available namespaces within the subscription regardless of the * resourceGroups. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RelayNamespaceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RelayNamespaceListResult} [result] - The deserialized result object if an error did not occur. * See {@link RelayNamespaceListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RelayNamespaceListResult>; list(callback: ServiceCallback<models.RelayNamespaceListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RelayNamespaceListResult>): void; /** * Lists all the available namespaces within the ResourceGroup. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RelayNamespaceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RelayNamespaceListResult>>; /** * Lists all the available namespaces within the ResourceGroup. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RelayNamespaceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RelayNamespaceListResult} [result] - The deserialized result object if an error did not occur. * See {@link RelayNamespaceListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RelayNamespaceListResult>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.RelayNamespaceListResult>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RelayNamespaceListResult>): void; /** * Create Azure Relay namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} parameters Parameters supplied to create a namespace * resource. * * @param {object} [parameters.sku] SKU of the namespace. * * @param {string} [parameters.sku.tier] The tier of this SKU. Possible values * include: 'Standard' * * @param {string} parameters.location Resource location. * * @param {object} [parameters.tags] Resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RelayNamespace>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, parameters: models.RelayNamespace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RelayNamespace>>; /** * Create Azure Relay namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} parameters Parameters supplied to create a namespace * resource. * * @param {object} [parameters.sku] SKU of the namespace. * * @param {string} [parameters.sku.tier] The tier of this SKU. Possible values * include: 'Standard' * * @param {string} parameters.location Resource location. * * @param {object} [parameters.tags] Resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RelayNamespace} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RelayNamespace} [result] - The deserialized result object if an error did not occur. * See {@link RelayNamespace} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, namespaceName: string, parameters: models.RelayNamespace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RelayNamespace>; createOrUpdate(resourceGroupName: string, namespaceName: string, parameters: models.RelayNamespace, callback: ServiceCallback<models.RelayNamespace>): void; createOrUpdate(resourceGroupName: string, namespaceName: string, parameters: models.RelayNamespace, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RelayNamespace>): void; /** * Deletes an existing namespace. This operation also removes all associated * resources under the namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes an existing namespace. This operation also removes all associated * resources under the namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, namespaceName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, namespaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Returns the description for the specified namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RelayNamespace>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RelayNamespace>>; /** * Returns the description for the specified namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RelayNamespace} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RelayNamespace} [result] - The deserialized result object if an error did not occur. * See {@link RelayNamespace} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RelayNamespace>; get(resourceGroupName: string, namespaceName: string, callback: ServiceCallback<models.RelayNamespace>): void; get(resourceGroupName: string, namespaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RelayNamespace>): void; /** * Creates or updates a namespace. Once created, this namespace's resource * manifest is immutable. This operation is idempotent. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} parameters Parameters for updating a namespace resource. * * @param {object} [parameters.sku] SKU of the namespace. * * @param {string} [parameters.sku.tier] The tier of this SKU. Possible values * include: 'Standard' * * @param {object} [parameters.tags] Resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RelayNamespace>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, parameters: models.RelayUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RelayNamespace>>; /** * Creates or updates a namespace. Once created, this namespace's resource * manifest is immutable. This operation is idempotent. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} parameters Parameters for updating a namespace resource. * * @param {object} [parameters.sku] SKU of the namespace. * * @param {string} [parameters.sku.tier] The tier of this SKU. Possible values * include: 'Standard' * * @param {object} [parameters.tags] Resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RelayNamespace} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RelayNamespace} [result] - The deserialized result object if an error did not occur. * See {@link RelayNamespace} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, namespaceName: string, parameters: models.RelayUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RelayNamespace>; update(resourceGroupName: string, namespaceName: string, parameters: models.RelayUpdateParameters, callback: ServiceCallback<models.RelayNamespace>): void; update(resourceGroupName: string, namespaceName: string, parameters: models.RelayUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RelayNamespace>): void; /** * Authorization rules for a namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AuthorizationRuleListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAuthorizationRulesWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AuthorizationRuleListResult>>; /** * Authorization rules for a namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AuthorizationRuleListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AuthorizationRuleListResult} [result] - The deserialized result object if an error did not occur. * See {@link AuthorizationRuleListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAuthorizationRules(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AuthorizationRuleListResult>; listAuthorizationRules(resourceGroupName: string, namespaceName: string, callback: ServiceCallback<models.AuthorizationRuleListResult>): void; listAuthorizationRules(resourceGroupName: string, namespaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AuthorizationRuleListResult>): void; /** * Creates or updates an authorization rule for a namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} parameters The authorization rule parameters. * * @param {array} [parameters.rights] The rights associated with the rule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AuthorizationRule>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.AuthorizationRule, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AuthorizationRule>>; /** * Creates or updates an authorization rule for a namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} parameters The authorization rule parameters. * * @param {array} [parameters.rights] The rights associated with the rule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AuthorizationRule} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AuthorizationRule} [result] - The deserialized result object if an error did not occur. * See {@link AuthorizationRule} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.AuthorizationRule, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AuthorizationRule>; createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.AuthorizationRule, callback: ServiceCallback<models.AuthorizationRule>): void; createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.AuthorizationRule, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AuthorizationRule>): void; /** * Deletes a namespace authorization rule. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a namespace authorization rule. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, callback: ServiceCallback<void>): void; deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Authorization rule for a namespace by name. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AuthorizationRule>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AuthorizationRule>>; /** * Authorization rule for a namespace by name. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AuthorizationRule} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AuthorizationRule} [result] - The deserialized result object if an error did not occur. * See {@link AuthorizationRule} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AuthorizationRule>; getAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, callback: ServiceCallback<models.AuthorizationRule>): void; getAuthorizationRule(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AuthorizationRule>): void; /** * Primary and secondary connection strings to the namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AccessKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listKeysWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccessKeys>>; /** * Primary and secondary connection strings to the namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AccessKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AccessKeys} [result] - The deserialized result object if an error did not occur. * See {@link AccessKeys} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listKeys(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccessKeys>; listKeys(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, callback: ServiceCallback<models.AccessKeys>): void; listKeys(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccessKeys>): void; /** * Regenerates the primary or secondary connection strings to the namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} parameters Parameters supplied to regenerate authorization * rule. * * @param {string} parameters.keyType The access key to regenerate. Possible * values include: 'PrimaryKey', 'SecondaryKey' * * @param {string} [parameters.key] Optional. If the key value is provided, * this is set to key type, or autogenerated key value set for key type. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AccessKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ regenerateKeysWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.RegenerateAccessKeyParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccessKeys>>; /** * Regenerates the primary or secondary connection strings to the namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} parameters Parameters supplied to regenerate authorization * rule. * * @param {string} parameters.keyType The access key to regenerate. Possible * values include: 'PrimaryKey', 'SecondaryKey' * * @param {string} [parameters.key] Optional. If the key value is provided, * this is set to key type, or autogenerated key value set for key type. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AccessKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AccessKeys} [result] - The deserialized result object if an error did not occur. * See {@link AccessKeys} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ regenerateKeys(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.RegenerateAccessKeyParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccessKeys>; regenerateKeys(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.RegenerateAccessKeyParameters, callback: ServiceCallback<models.AccessKeys>): void; regenerateKeys(resourceGroupName: string, namespaceName: string, authorizationRuleName: string, parameters: models.RegenerateAccessKeyParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccessKeys>): void; /** * Create Azure Relay namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} parameters Parameters supplied to create a namespace * resource. * * @param {object} [parameters.sku] SKU of the namespace. * * @param {string} [parameters.sku.tier] The tier of this SKU. Possible values * include: 'Standard' * * @param {string} parameters.location Resource location. * * @param {object} [parameters.tags] Resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RelayNamespace>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateOrUpdateWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, parameters: models.RelayNamespace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RelayNamespace>>; /** * Create Azure Relay namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} parameters Parameters supplied to create a namespace * resource. * * @param {object} [parameters.sku] SKU of the namespace. * * @param {string} [parameters.sku.tier] The tier of this SKU. Possible values * include: 'Standard' * * @param {string} parameters.location Resource location. * * @param {object} [parameters.tags] Resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RelayNamespace} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RelayNamespace} [result] - The deserialized result object if an error did not occur. * See {@link RelayNamespace} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateOrUpdate(resourceGroupName: string, namespaceName: string, parameters: models.RelayNamespace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RelayNamespace>; beginCreateOrUpdate(resourceGroupName: string, namespaceName: string, parameters: models.RelayNamespace, callback: ServiceCallback<models.RelayNamespace>): void; beginCreateOrUpdate(resourceGroupName: string, namespaceName: string, parameters: models.RelayNamespace, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RelayNamespace>): void; /** * Deletes an existing namespace. This operation also removes all associated * resources under the namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes an existing namespace. This operation also removes all associated * resources under the namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(resourceGroupName: string, namespaceName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(resourceGroupName: string, namespaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Lists all the available namespaces within the subscription regardless of the * resourceGroups. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RelayNamespaceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RelayNamespaceListResult>>; /** * Lists all the available namespaces within the subscription regardless of the * resourceGroups. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RelayNamespaceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RelayNamespaceListResult} [result] - The deserialized result object if an error did not occur. * See {@link RelayNamespaceListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RelayNamespaceListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.RelayNamespaceListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RelayNamespaceListResult>): void; /** * Lists all the available namespaces within the ResourceGroup. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RelayNamespaceListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RelayNamespaceListResult>>; /** * Lists all the available namespaces within the ResourceGroup. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RelayNamespaceListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RelayNamespaceListResult} [result] - The deserialized result object if an error did not occur. * See {@link RelayNamespaceListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RelayNamespaceListResult>; listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.RelayNamespaceListResult>): void; listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RelayNamespaceListResult>): void; /** * Authorization rules for a namespace. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AuthorizationRuleListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAuthorizationRulesNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AuthorizationRuleListResult>>; /** * Authorization rules for a namespace. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AuthorizationRuleListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AuthorizationRuleListResult} [result] - The deserialized result object if an error did not occur. * See {@link AuthorizationRuleListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAuthorizationRulesNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AuthorizationRuleListResult>; listAuthorizationRulesNext(nextPageLink: string, callback: ServiceCallback<models.AuthorizationRuleListResult>): void; listAuthorizationRulesNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AuthorizationRuleListResult>): void; } /** * @class * HybridConnections * __NOTE__: An instance of this class is automatically created for an * instance of the RelayManagementClient. */ export interface HybridConnections { /** * Lists the hybrid connection within the namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<HybridConnectionListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByNamespaceWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.HybridConnectionListResult>>; /** * Lists the hybrid connection within the namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {HybridConnectionListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {HybridConnectionListResult} [result] - The deserialized result object if an error did not occur. * See {@link HybridConnectionListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByNamespace(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.HybridConnectionListResult>; listByNamespace(resourceGroupName: string, namespaceName: string, callback: ServiceCallback<models.HybridConnectionListResult>): void; listByNamespace(resourceGroupName: string, namespaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.HybridConnectionListResult>): void; /** * Creates or updates a service hybrid connection. This operation is * idempotent. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {object} parameters Parameters supplied to create a hybrid * connection. * * @param {boolean} [parameters.requiresClientAuthorization] Returns true if * client authorization is needed for this hybrid connection; otherwise, false. * * @param {string} [parameters.userMetadata] The usermetadata is a placeholder * to store user-defined string data for the hybrid connection endpoint. For * example, it can be used to store descriptive data, such as a list of teams * and their contact information. Also, user-defined configuration settings can * be stored. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<HybridConnection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, parameters: models.HybridConnection, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.HybridConnection>>; /** * Creates or updates a service hybrid connection. This operation is * idempotent. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {object} parameters Parameters supplied to create a hybrid * connection. * * @param {boolean} [parameters.requiresClientAuthorization] Returns true if * client authorization is needed for this hybrid connection; otherwise, false. * * @param {string} [parameters.userMetadata] The usermetadata is a placeholder * to store user-defined string data for the hybrid connection endpoint. For * example, it can be used to store descriptive data, such as a list of teams * and their contact information. Also, user-defined configuration settings can * be stored. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {HybridConnection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {HybridConnection} [result] - The deserialized result object if an error did not occur. * See {@link HybridConnection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, parameters: models.HybridConnection, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.HybridConnection>; createOrUpdate(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, parameters: models.HybridConnection, callback: ServiceCallback<models.HybridConnection>): void; createOrUpdate(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, parameters: models.HybridConnection, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.HybridConnection>): void; /** * Deletes a hybrid connection. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a hybrid connection. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Returns the description for the specified hybrid connection. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<HybridConnection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.HybridConnection>>; /** * Returns the description for the specified hybrid connection. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {HybridConnection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {HybridConnection} [result] - The deserialized result object if an error did not occur. * See {@link HybridConnection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.HybridConnection>; get(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, callback: ServiceCallback<models.HybridConnection>): void; get(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.HybridConnection>): void; /** * Authorization rules for a hybrid connection. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AuthorizationRuleListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAuthorizationRulesWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AuthorizationRuleListResult>>; /** * Authorization rules for a hybrid connection. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AuthorizationRuleListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AuthorizationRuleListResult} [result] - The deserialized result object if an error did not occur. * See {@link AuthorizationRuleListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAuthorizationRules(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AuthorizationRuleListResult>; listAuthorizationRules(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, callback: ServiceCallback<models.AuthorizationRuleListResult>): void; listAuthorizationRules(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AuthorizationRuleListResult>): void; /** * Creates or updates an authorization rule for a hybrid connection. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} parameters The authorization rule parameters. * * @param {array} [parameters.rights] The rights associated with the rule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AuthorizationRule>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, parameters: models.AuthorizationRule, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AuthorizationRule>>; /** * Creates or updates an authorization rule for a hybrid connection. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} parameters The authorization rule parameters. * * @param {array} [parameters.rights] The rights associated with the rule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AuthorizationRule} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AuthorizationRule} [result] - The deserialized result object if an error did not occur. * See {@link AuthorizationRule} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, parameters: models.AuthorizationRule, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AuthorizationRule>; createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, parameters: models.AuthorizationRule, callback: ServiceCallback<models.AuthorizationRule>): void; createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, parameters: models.AuthorizationRule, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AuthorizationRule>): void; /** * Deletes a hybrid connection authorization rule. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a hybrid connection authorization rule. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, callback: ServiceCallback<void>): void; deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Hybrid connection authorization rule for a hybrid connection by name. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AuthorizationRule>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AuthorizationRule>>; /** * Hybrid connection authorization rule for a hybrid connection by name. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AuthorizationRule} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AuthorizationRule} [result] - The deserialized result object if an error did not occur. * See {@link AuthorizationRule} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getAuthorizationRule(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AuthorizationRule>; getAuthorizationRule(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, callback: ServiceCallback<models.AuthorizationRule>): void; getAuthorizationRule(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AuthorizationRule>): void; /** * Primary and secondary connection strings to the hybrid connection. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AccessKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listKeysWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccessKeys>>; /** * Primary and secondary connection strings to the hybrid connection. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AccessKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AccessKeys} [result] - The deserialized result object if an error did not occur. * See {@link AccessKeys} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listKeys(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccessKeys>; listKeys(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, callback: ServiceCallback<models.AccessKeys>): void; listKeys(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccessKeys>): void; /** * Regenerates the primary or secondary connection strings to the hybrid * connection. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} parameters Parameters supplied to regenerate authorization * rule. * * @param {string} parameters.keyType The access key to regenerate. Possible * values include: 'PrimaryKey', 'SecondaryKey' * * @param {string} [parameters.key] Optional. If the key value is provided, * this is set to key type, or autogenerated key value set for key type. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AccessKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ regenerateKeysWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, parameters: models.RegenerateAccessKeyParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccessKeys>>; /** * Regenerates the primary or secondary connection strings to the hybrid * connection. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} hybridConnectionName The hybrid connection name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} parameters Parameters supplied to regenerate authorization * rule. * * @param {string} parameters.keyType The access key to regenerate. Possible * values include: 'PrimaryKey', 'SecondaryKey' * * @param {string} [parameters.key] Optional. If the key value is provided, * this is set to key type, or autogenerated key value set for key type. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AccessKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AccessKeys} [result] - The deserialized result object if an error did not occur. * See {@link AccessKeys} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ regenerateKeys(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, parameters: models.RegenerateAccessKeyParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccessKeys>; regenerateKeys(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, parameters: models.RegenerateAccessKeyParameters, callback: ServiceCallback<models.AccessKeys>): void; regenerateKeys(resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, parameters: models.RegenerateAccessKeyParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccessKeys>): void; /** * Lists the hybrid connection within the namespace. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<HybridConnectionListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByNamespaceNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.HybridConnectionListResult>>; /** * Lists the hybrid connection within the namespace. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {HybridConnectionListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {HybridConnectionListResult} [result] - The deserialized result object if an error did not occur. * See {@link HybridConnectionListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByNamespaceNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.HybridConnectionListResult>; listByNamespaceNext(nextPageLink: string, callback: ServiceCallback<models.HybridConnectionListResult>): void; listByNamespaceNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.HybridConnectionListResult>): void; /** * Authorization rules for a hybrid connection. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AuthorizationRuleListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAuthorizationRulesNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AuthorizationRuleListResult>>; /** * Authorization rules for a hybrid connection. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AuthorizationRuleListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AuthorizationRuleListResult} [result] - The deserialized result object if an error did not occur. * See {@link AuthorizationRuleListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAuthorizationRulesNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AuthorizationRuleListResult>; listAuthorizationRulesNext(nextPageLink: string, callback: ServiceCallback<models.AuthorizationRuleListResult>): void; listAuthorizationRulesNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AuthorizationRuleListResult>): void; } /** * @class * WCFRelays * __NOTE__: An instance of this class is automatically created for an * instance of the RelayManagementClient. */ export interface WCFRelays { /** * Lists the WCF relays within the namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<WcfRelaysListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByNamespaceWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WcfRelaysListResult>>; /** * Lists the WCF relays within the namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {WcfRelaysListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {WcfRelaysListResult} [result] - The deserialized result object if an error did not occur. * See {@link WcfRelaysListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByNamespace(resourceGroupName: string, namespaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WcfRelaysListResult>; listByNamespace(resourceGroupName: string, namespaceName: string, callback: ServiceCallback<models.WcfRelaysListResult>): void; listByNamespace(resourceGroupName: string, namespaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WcfRelaysListResult>): void; /** * Creates or updates a WCF relay. This operation is idempotent. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {object} parameters Parameters supplied to create a WCF relay. * * @param {string} [parameters.relayType] WCF relay type. Possible values * include: 'NetTcp', 'Http' * * @param {boolean} [parameters.requiresClientAuthorization] Returns true if * client authorization is needed for this relay; otherwise, false. * * @param {boolean} [parameters.requiresTransportSecurity] Returns true if * transport security is needed for this relay; otherwise, false. * * @param {string} [parameters.userMetadata] The usermetadata is a placeholder * to store user-defined string data for the WCF Relay endpoint. For example, * it can be used to store descriptive data, such as list of teams and their * contact information. Also, user-defined configuration settings can be * stored. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<WcfRelay>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, relayName: string, parameters: models.WcfRelay, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WcfRelay>>; /** * Creates or updates a WCF relay. This operation is idempotent. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {object} parameters Parameters supplied to create a WCF relay. * * @param {string} [parameters.relayType] WCF relay type. Possible values * include: 'NetTcp', 'Http' * * @param {boolean} [parameters.requiresClientAuthorization] Returns true if * client authorization is needed for this relay; otherwise, false. * * @param {boolean} [parameters.requiresTransportSecurity] Returns true if * transport security is needed for this relay; otherwise, false. * * @param {string} [parameters.userMetadata] The usermetadata is a placeholder * to store user-defined string data for the WCF Relay endpoint. For example, * it can be used to store descriptive data, such as list of teams and their * contact information. Also, user-defined configuration settings can be * stored. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {WcfRelay} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {WcfRelay} [result] - The deserialized result object if an error did not occur. * See {@link WcfRelay} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, namespaceName: string, relayName: string, parameters: models.WcfRelay, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WcfRelay>; createOrUpdate(resourceGroupName: string, namespaceName: string, relayName: string, parameters: models.WcfRelay, callback: ServiceCallback<models.WcfRelay>): void; createOrUpdate(resourceGroupName: string, namespaceName: string, relayName: string, parameters: models.WcfRelay, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WcfRelay>): void; /** * Deletes a WCF relay. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, relayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a WCF relay. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, namespaceName: string, relayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, namespaceName: string, relayName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, namespaceName: string, relayName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Returns the description for the specified WCF relay. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<WcfRelay>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, relayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WcfRelay>>; /** * Returns the description for the specified WCF relay. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {WcfRelay} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {WcfRelay} [result] - The deserialized result object if an error did not occur. * See {@link WcfRelay} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, namespaceName: string, relayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WcfRelay>; get(resourceGroupName: string, namespaceName: string, relayName: string, callback: ServiceCallback<models.WcfRelay>): void; get(resourceGroupName: string, namespaceName: string, relayName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WcfRelay>): void; /** * Authorization rules for a WCF relay. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AuthorizationRuleListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAuthorizationRulesWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, relayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AuthorizationRuleListResult>>; /** * Authorization rules for a WCF relay. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AuthorizationRuleListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AuthorizationRuleListResult} [result] - The deserialized result object if an error did not occur. * See {@link AuthorizationRuleListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAuthorizationRules(resourceGroupName: string, namespaceName: string, relayName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AuthorizationRuleListResult>; listAuthorizationRules(resourceGroupName: string, namespaceName: string, relayName: string, callback: ServiceCallback<models.AuthorizationRuleListResult>): void; listAuthorizationRules(resourceGroupName: string, namespaceName: string, relayName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AuthorizationRuleListResult>): void; /** * Creates or updates an authorization rule for a WCF relay. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} parameters The authorization rule parameters. * * @param {array} [parameters.rights] The rights associated with the rule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AuthorizationRule>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, parameters: models.AuthorizationRule, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AuthorizationRule>>; /** * Creates or updates an authorization rule for a WCF relay. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} parameters The authorization rule parameters. * * @param {array} [parameters.rights] The rights associated with the rule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AuthorizationRule} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AuthorizationRule} [result] - The deserialized result object if an error did not occur. * See {@link AuthorizationRule} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, parameters: models.AuthorizationRule, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AuthorizationRule>; createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, parameters: models.AuthorizationRule, callback: ServiceCallback<models.AuthorizationRule>): void; createOrUpdateAuthorizationRule(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, parameters: models.AuthorizationRule, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AuthorizationRule>): void; /** * Deletes a WCF relay authorization rule. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a WCF relay authorization rule. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, callback: ServiceCallback<void>): void; deleteAuthorizationRule(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Get authorizationRule for a WCF relay by name. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AuthorizationRule>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getAuthorizationRuleWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AuthorizationRule>>; /** * Get authorizationRule for a WCF relay by name. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AuthorizationRule} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AuthorizationRule} [result] - The deserialized result object if an error did not occur. * See {@link AuthorizationRule} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getAuthorizationRule(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AuthorizationRule>; getAuthorizationRule(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, callback: ServiceCallback<models.AuthorizationRule>): void; getAuthorizationRule(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AuthorizationRule>): void; /** * Primary and secondary connection strings to the WCF relay. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AccessKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listKeysWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccessKeys>>; /** * Primary and secondary connection strings to the WCF relay. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AccessKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AccessKeys} [result] - The deserialized result object if an error did not occur. * See {@link AccessKeys} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listKeys(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccessKeys>; listKeys(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, callback: ServiceCallback<models.AccessKeys>): void; listKeys(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccessKeys>): void; /** * Regenerates the primary or secondary connection strings to the WCF relay. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} parameters Parameters supplied to regenerate authorization * rule. * * @param {string} parameters.keyType The access key to regenerate. Possible * values include: 'PrimaryKey', 'SecondaryKey' * * @param {string} [parameters.key] Optional. If the key value is provided, * this is set to key type, or autogenerated key value set for key type. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AccessKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ regenerateKeysWithHttpOperationResponse(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, parameters: models.RegenerateAccessKeyParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccessKeys>>; /** * Regenerates the primary or secondary connection strings to the WCF relay. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {string} relayName The relay name. * * @param {string} authorizationRuleName The authorization rule name. * * @param {object} parameters Parameters supplied to regenerate authorization * rule. * * @param {string} parameters.keyType The access key to regenerate. Possible * values include: 'PrimaryKey', 'SecondaryKey' * * @param {string} [parameters.key] Optional. If the key value is provided, * this is set to key type, or autogenerated key value set for key type. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AccessKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AccessKeys} [result] - The deserialized result object if an error did not occur. * See {@link AccessKeys} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ regenerateKeys(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, parameters: models.RegenerateAccessKeyParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccessKeys>; regenerateKeys(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, parameters: models.RegenerateAccessKeyParameters, callback: ServiceCallback<models.AccessKeys>): void; regenerateKeys(resourceGroupName: string, namespaceName: string, relayName: string, authorizationRuleName: string, parameters: models.RegenerateAccessKeyParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccessKeys>): void; /** * Lists the WCF relays within the namespace. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<WcfRelaysListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByNamespaceNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WcfRelaysListResult>>; /** * Lists the WCF relays within the namespace. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {WcfRelaysListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {WcfRelaysListResult} [result] - The deserialized result object if an error did not occur. * See {@link WcfRelaysListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByNamespaceNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WcfRelaysListResult>; listByNamespaceNext(nextPageLink: string, callback: ServiceCallback<models.WcfRelaysListResult>): void; listByNamespaceNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WcfRelaysListResult>): void; /** * Authorization rules for a WCF relay. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AuthorizationRuleListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAuthorizationRulesNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AuthorizationRuleListResult>>; /** * Authorization rules for a WCF relay. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AuthorizationRuleListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AuthorizationRuleListResult} [result] - The deserialized result object if an error did not occur. * See {@link AuthorizationRuleListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAuthorizationRulesNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AuthorizationRuleListResult>; listAuthorizationRulesNext(nextPageLink: string, callback: ServiceCallback<models.AuthorizationRuleListResult>): void; listAuthorizationRulesNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AuthorizationRuleListResult>): void; }
the_stack
declare var Velocity: jquery.velocity.VelocityStatic; import {SmartValue} from "../communicator/smartValue"; import {Constants} from "../constants"; import {Localization} from "../localization/localization"; import * as Log from "../logging/log"; import {AnimationHelper} from "./animations/animationHelper"; import {AnimationState} from "./animations/animationState"; import {AnimationStrategy} from "./animations/animationStrategy"; import {ExpandFromRightAnimationStrategy} from "./animations/expandFromRightAnimationStrategy"; import {FadeInAnimationStrategy} from "./animations/fadeInAnimationStrategy"; import {SlidingHeightAnimationStrategy} from "./animations/slidingHeightAnimationStrategy"; import {ClipMode} from "./clipMode"; import {ClipperStateProp} from "./clipperState"; import {ClipperStateUtilities} from "./clipperStateUtilities"; import {ComponentBase} from "./componentBase"; import {CloseButton} from "./components/closeButton"; import {Footer} from "./components/footer"; import {Clipper} from "./frontEndGlobals"; import {OneNoteApiUtils} from "./oneNoteApiUtils"; import {ClippingPanel} from "./panels/clippingPanel"; import {ClippingPanelWithDelayedMessage} from "./panels/clippingPanelWithDelayedMessage"; import {ClippingPanelWithProgressIndicator} from "./panels/clippingPanelWithProgressIndicator"; import {DialogButton} from "./panels/dialogPanel"; import {ErrorDialogPanel} from "./panels/errorDialogPanel"; import {LoadingPanel} from "./panels/loadingPanel"; import {OptionsPanel} from "./panels/optionsPanel"; import {RatingsPanel} from "./panels/ratingsPanel"; import {RegionSelectingPanel} from "./panels/regionSelectingPanel"; import {SignInPanel} from "./panels/signInPanel"; import {SuccessPanel} from "./panels/successPanel"; import {Status} from "./status"; export enum CloseReason { CloseButton, EscPress } export enum PanelType { None, BadState, Loading, SignInNeeded, ClipOptions, RegionInstructions, ClippingToApi, ClippingFailure, ClippingSuccess } export interface MainControllerState { currentPanel?: PanelType; ratingsPanelAnimationState?: SmartValue<AnimationState>; // stored for when the ratings subpanel re-renders while the MainController does not } export interface MainControllerProps extends ClipperStateProp { onSignInInvoked: () => void; onSignOutInvoked: (authType: string) => void; updateFrameHeight: (newContainerHeight: number) => void; onStartClip: () => void; } export class MainControllerClass extends ComponentBase<MainControllerState, MainControllerProps> { private popupIsOpen: boolean; private controllerAnimationStrategy: AnimationStrategy; private panelAnimationStrategy: AnimationStrategy; private heightAnimationStrategy: AnimationStrategy; constructor(props: MainControllerProps) { super(props); this.initAnimationStrategy(); // The user could have pressed esc when Clipper iframe was not in focus Clipper.getInjectCommunicator().registerFunction(Constants.FunctionKeys.escHandler, () => { this.handleEscPress(); }); document.onkeydown = (event) => { if (event.keyCode === Constants.KeyCodes.esc) { this.handleEscPress(); } }; } getInitialState(): MainControllerState { return { currentPanel: PanelType.None }; } handleEscPress() { if (this.isCloseable()) { this.closeClipper(CloseReason.EscPress); } } initAnimationStrategy() { this.controllerAnimationStrategy = new ExpandFromRightAnimationStrategy({ extShouldAnimateIn: () => { return this.props.clipperState.uiExpanded; }, extShouldAnimateOut: () => { return !this.props.clipperState.uiExpanded; }, onBeforeAnimateOut: () => { this.setState({currentPanel: PanelType.None}); }, onBeforeAnimateIn: () => { this.props.clipperState.reset(); }, onAnimateInExpand: () => { this.setState({currentPanel: this.getPanelTypeToShow()}); }, onAfterAnimateOut: () => { Clipper.getInjectCommunicator().callRemoteFunction(Constants.FunctionKeys.hideUi); } }); this.panelAnimationStrategy = new FadeInAnimationStrategy({ extShouldAnimateIn: () => { return this.state.currentPanel !== PanelType.None; }, extShouldAnimateOut: () => { return this.getPanelTypeToShow() !== this.state.currentPanel; }, onAfterAnimateOut: () => { this.setState({currentPanel: this.getPanelTypeToShow()}); }, onAfterAnimateIn: () => { this.setState({currentPanel: this.getPanelTypeToShow()}); } }); this.heightAnimationStrategy = new SlidingHeightAnimationStrategy(Constants.Ids.mainController, { onAfterHeightAnimatorDraw: (newHeightInfo) => { if (this.popupIsOpen) { // Sometimes during the delay, we open the popup, so the frame height update needs to account for that too this.updateFrameHeightAfterPopupToggle(this.popupIsOpen); } else { this.props.updateFrameHeight(newHeightInfo.newContainerHeight); } } }); } isCloseable() { let panelType = this.state.currentPanel; return panelType !== PanelType.None && panelType !== PanelType.ClippingToApi; } onPopupToggle(shouldNowBeOpen: boolean) { this.popupIsOpen = shouldNowBeOpen; this.updateFrameHeightAfterPopupToggle(shouldNowBeOpen); } private updateFrameHeightAfterPopupToggle(shouldNowBeOpen: boolean) { let saveToLocationContainer = document.getElementById(Constants.Ids.saveToLocationContainer); if (saveToLocationContainer) { let currentLocationContainerPosition: ClientRect = saveToLocationContainer.getBoundingClientRect(); let aboutToOpenHeight = Constants.Styles.sectionPickerContainerHeight + currentLocationContainerPosition.top + currentLocationContainerPosition.height; let aboutToCloseHeight = document.getElementById(Constants.Ids.mainController).offsetHeight; let newHeight = shouldNowBeOpen ? aboutToOpenHeight : aboutToCloseHeight; this.props.updateFrameHeight(newHeight); } } getPanelTypeToShow(): PanelType { if (this.props.clipperState.badState) { return PanelType.BadState; } if (!this.props.clipperState.uiExpanded) { return PanelType.None; } if ((this.props.clipperState.userResult && this.props.clipperState.userResult.status === Status.InProgress) || this.props.clipperState.fetchLocStringStatus === Status.InProgress || !this.props.clipperState.invokeOptions) { return PanelType.Loading; } if (!ClipperStateUtilities.isUserLoggedIn(this.props.clipperState)) { return PanelType.SignInNeeded; } if (this.props.clipperState.currentMode.get() === ClipMode.Region && this.props.clipperState.regionResult.status !== Status.Succeeded) { switch (this.props.clipperState.regionResult.status) { case Status.InProgress: return PanelType.Loading; default: return PanelType.RegionInstructions; } } switch (this.props.clipperState.oneNoteApiResult.status) { default: case Status.NotStarted: return PanelType.ClipOptions; case Status.InProgress: return PanelType.ClippingToApi; case Status.Failed: return PanelType.ClippingFailure; case Status.Succeeded: return PanelType.ClippingSuccess; } } closeClipper(closeReason?: CloseReason) { let closeEvent = new Log.Event.BaseEvent(Log.Event.Label.CloseClipper); closeEvent.setCustomProperty(Log.PropertyName.Custom.CurrentPanel, PanelType[this.state.currentPanel]); closeEvent.setCustomProperty(Log.PropertyName.Custom.CloseReason, CloseReason[closeReason]); Clipper.logger.logEvent(closeEvent); // Clear region selections on clipper exit rather than invoke to avoid conflicting logic with scenarios like context menu image selection this.props.clipperState.setState({ uiExpanded: false, regionResult: {status: Status.NotStarted, data: []} }); } onMainControllerDraw(mainControllerElement: HTMLElement) { this.controllerAnimationStrategy.animate(mainControllerElement); } onPanelAnimatorDraw(panelAnimator: HTMLElement) { let panelTypeToShow: PanelType = this.getPanelTypeToShow(); let panelIsCorrect = panelTypeToShow === this.state.currentPanel; if (panelTypeToShow === PanelType.ClipOptions && this.state.currentPanel !== PanelType.ClipOptions) { this.popupIsOpen = false; } this.panelAnimationStrategy.animate(panelAnimator); if (!panelIsCorrect && this.panelAnimationStrategy.getAnimationState() === AnimationState.GoingIn) { // We'll speed things up by stopping the current one, and trigger the next one AnimationHelper.stopAnimationsThen(panelAnimator, () => { this.panelAnimationStrategy.setAnimationState(AnimationState.In); this.setState({}); }); } } onHeightAnimatorDraw(heightAnimator: HTMLElement) { this.heightAnimationStrategy.animate(heightAnimator); } getCurrentPanel() { let panelType = this.state.currentPanel; let buttons: DialogButton[] = []; switch (panelType) { case PanelType.BadState: buttons.push({ id: Constants.Ids.refreshPageButton, label: Localization.getLocalizedString("WebClipper.Action.RefreshPage"), handler: () => { Clipper.getInjectCommunicator().callRemoteFunction(Constants.FunctionKeys.refreshPage); } }); return <ErrorDialogPanel message={Localization.getLocalizedString("WebClipper.Error.OrphanedWebClipperDetected")} buttons={buttons}/>; case PanelType.Loading: return <LoadingPanel clipperState={this.props.clipperState}/>; case PanelType.SignInNeeded: return <SignInPanel clipperState={this.props.clipperState} onSignInInvoked={this.props.onSignInInvoked}/>; case PanelType.ClipOptions: return <OptionsPanel onPopupToggle={this.onPopupToggle.bind(this)} clipperState={this.props.clipperState} onStartClip={this.props.onStartClip}/>; case PanelType.RegionInstructions: return <RegionSelectingPanel clipperState={this.props.clipperState}/>; case PanelType.ClippingToApi: if (this.props.clipperState.currentMode.get() === ClipMode.Pdf) { if (this.props.clipperState.pdfPreviewInfo.shouldDistributePages) { return <ClippingPanelWithProgressIndicator clipperState={this.props.clipperState}/>; } return <ClippingPanelWithDelayedMessage clipperState={this.props.clipperState} delay={Constants.Settings.pdfClippingMessageDelay} message={Localization.getLocalizedString("WebClipper.ClipType.Pdf.ProgressLabelDelay")}/>; } return <ClippingPanel clipperState={this.props.clipperState}/>; case PanelType.ClippingFailure: let error = this.props.clipperState.oneNoteApiResult.data as OneNoteApi.RequestError; let apiResponseCode: string = OneNoteApiUtils.getApiResponseCode(error); if (OneNoteApiUtils.isRetryable(apiResponseCode)) { buttons.push({ id: Constants.Ids.dialogTryAgainButton, label: Localization.getLocalizedString("WebClipper.Action.TryAgain"), handler: this.props.onStartClip }); } if (OneNoteApiUtils.requiresSignout(apiResponseCode)) { buttons.push({ id: Constants.Ids.dialogSignOutButton, label: Localization.getLocalizedString("WebClipper.Action.SignOut"), handler: () => { if (this.props.onSignOutInvoked) { this.props.onSignOutInvoked(this.props.clipperState.userResult.data.user.authType); } } }); } else { buttons.push({ id: Constants.Ids.dialogBackButton, label: Localization.getLocalizedString("WebClipper.Action.BackToHome"), handler: () => { this.props.clipperState.setState({ oneNoteApiResult: { data: this.props.clipperState.oneNoteApiResult.data, status: Status.NotStarted } }); } }); } return <ErrorDialogPanel message={OneNoteApiUtils.getLocalizedErrorMessage(apiResponseCode)} buttons={buttons}/>; case PanelType.ClippingSuccess: let panels: any[] = [<SuccessPanel clipperState={this.props.clipperState}/>]; if (!this.state.ratingsPanelAnimationState) { this.state.ratingsPanelAnimationState = new SmartValue<AnimationState>(AnimationState.Out); } if (this.props.clipperState.showRatingsPrompt) { panels.push(<RatingsPanel clipperState={this.props.clipperState} animationState={this.state.ratingsPanelAnimationState}/>); } return panels; default: return undefined; } } getCloseButtonForType() { if (this.isCloseable()) { return ( <CloseButton onClickHandler={this.closeClipper.bind(this)} onClickHandlerParams={[CloseReason.CloseButton]}/> ); } else { return undefined; } } getCurrentFooter(): any { let panelType = this.state.currentPanel; switch (panelType) { case PanelType.ClipOptions: case PanelType.ClippingFailure: let error = this.props.clipperState.oneNoteApiResult.data as OneNoteApi.RequestError; let apiResponseCode: string = OneNoteApiUtils.getApiResponseCode(error); if (OneNoteApiUtils.requiresSignout(apiResponseCode)) { // If the ResponseCode requires a SignOut to fix, then the dialogButton will handle SignOut // so we will not show the footer. If it doesn't require signout, show the Footer return undefined; } /* falls through */ case PanelType.SignInNeeded: return <Footer clipperState={this.props.clipperState} onSignOutInvoked={this.props.onSignOutInvoked}/>; case PanelType.ClippingSuccess: /* falls through */ default: return undefined; } } render() { let panelToRender = this.getCurrentPanel(); let closeButtonToRender = this.getCloseButtonForType(); let footerToRender = this.getCurrentFooter(); return ( <div id={Constants.Ids.mainController} {...this.onElementDraw(this.onMainControllerDraw)} role="main" aria-label={Localization.getLocalizedString("WebClipper.Label.OneNoteWebClipper")} > {closeButtonToRender} <div className="panelContent"> <div className={Constants.Classes.heightAnimator} {...this.onElementDraw(this.onHeightAnimatorDraw)}> <div className={Constants.Classes.panelAnimator} {...this.onElementDraw(this.onPanelAnimatorDraw)}> {panelToRender} {footerToRender} </div> </div> </div> </div> ); } } let component = MainControllerClass.componentize(); export {component as MainController};
the_stack
import { Registry } from 'vs/platform/registry/common/platform'; import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry, IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { LifecyclePhase, ILifecycleService, StartupKind } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IWorkbenchThemeService } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { language } from 'vs/base/common/platform'; import { Disposable } from 'vs/base/common/lifecycle'; import ErrorTelemetry from 'vs/platform/telemetry/browser/errorTelemetry'; import { configurationTelemetry } from 'vs/platform/telemetry/common/telemetryUtils'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ITextFileService, ITextFileSaveEvent, ITextFileResolveEvent } from 'vs/workbench/services/textfile/common/textfiles'; import { extname, basename, isEqual, isEqualOrParent } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { Schemas } from 'vs/base/common/network'; import { guessMimeTypes } from 'vs/base/common/mime'; import { hash } from 'vs/base/common/hash'; import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite'; import { ViewContainerLocation } from 'vs/workbench/common/views'; type TelemetryData = { mimeType: string; ext: string; path: number; reason?: number; allowlistedjson?: string; }; type FileTelemetryDataFragment = { mimeType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; ext: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; path: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; reason?: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; allowlistedjson?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; }; export class TelemetryContribution extends Disposable implements IWorkbenchContribution { private static ALLOWLIST_JSON = ['package.json', 'package-lock.json', 'tsconfig.json', 'jsconfig.json', 'bower.json', '.eslintrc.json', 'tslint.json', 'composer.json']; private static ALLOWLIST_WORKSPACE_JSON = ['settings.json', 'extensions.json', 'tasks.json', 'launch.json']; constructor( @ITelemetryService private readonly telemetryService: ITelemetryService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @ILifecycleService lifecycleService: ILifecycleService, @IEditorService editorService: IEditorService, @IKeybindingService keybindingsService: IKeybindingService, @IWorkbenchThemeService themeService: IWorkbenchThemeService, @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService, @IConfigurationService configurationService: IConfigurationService, @IPaneCompositePartService paneCompositeService: IPaneCompositePartService, @ITextFileService textFileService: ITextFileService ) { super(); const { filesToOpenOrCreate, filesToDiff } = environmentService.configuration; const activeViewlet = paneCompositeService.getActivePaneComposite(ViewContainerLocation.Sidebar); type WindowSizeFragment = { innerHeight: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; innerWidth: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; outerHeight: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; outerWidth: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; }; type WorkspaceLoadClassification = { userAgent: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; emptyWorkbench: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; windowSize: WindowSizeFragment; 'workbench.filesToOpenOrCreate': { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; 'workbench.filesToDiff': { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; customKeybindingsCount: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; theme: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; language: { classification: 'SystemMetaData', purpose: 'BusinessInsight' }; pinnedViewlets: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; restoredViewlet?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; restoredEditors: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; startupKind: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true }; }; type WorkspaceLoadEvent = { userAgent: string; windowSize: { innerHeight: number, innerWidth: number, outerHeight: number, outerWidth: number }; emptyWorkbench: boolean; 'workbench.filesToOpenOrCreate': number; 'workbench.filesToDiff': number; customKeybindingsCount: number; theme: string; language: string; pinnedViewlets: string[]; restoredViewlet?: string; restoredEditors: number; startupKind: StartupKind; }; telemetryService.publicLog2<WorkspaceLoadEvent, WorkspaceLoadClassification>('workspaceLoad', { userAgent: navigator.userAgent, windowSize: { innerHeight: window.innerHeight, innerWidth: window.innerWidth, outerHeight: window.outerHeight, outerWidth: window.outerWidth }, emptyWorkbench: contextService.getWorkbenchState() === WorkbenchState.EMPTY, 'workbench.filesToOpenOrCreate': filesToOpenOrCreate && filesToOpenOrCreate.length || 0, 'workbench.filesToDiff': filesToDiff && filesToDiff.length || 0, customKeybindingsCount: keybindingsService.customKeybindingsCount(), theme: themeService.getColorTheme().id, language, pinnedViewlets: paneCompositeService.getPinnedPaneCompositeIds(ViewContainerLocation.Sidebar), restoredViewlet: activeViewlet ? activeViewlet.getId() : undefined, restoredEditors: editorService.visibleEditors.length, startupKind: lifecycleService.startupKind }); // Error Telemetry this._register(new ErrorTelemetry(telemetryService)); // Configuration Telemetry this._register(configurationTelemetry(telemetryService, configurationService)); // Files Telemetry this._register(textFileService.files.onDidResolve(e => this.onTextFileModelResolved(e))); this._register(textFileService.files.onDidSave(e => this.onTextFileModelSaved(e))); // Lifecycle this._register(lifecycleService.onDidShutdown(() => this.dispose())); } private onTextFileModelResolved(e: ITextFileResolveEvent): void { const settingsType = this.getTypeIfSettings(e.model.resource); if (settingsType) { type SettingsReadClassification = { settingsType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; }; this.telemetryService.publicLog2<{ settingsType: string }, SettingsReadClassification>('settingsRead', { settingsType }); // Do not log read to user settings.json and .vscode folder as a fileGet event as it ruins our JSON usage data } else { type FileGetClassification = {} & FileTelemetryDataFragment; this.telemetryService.publicLog2<TelemetryData, FileGetClassification>('fileGet', this.getTelemetryData(e.model.resource, e.reason)); } } private onTextFileModelSaved(e: ITextFileSaveEvent): void { const settingsType = this.getTypeIfSettings(e.model.resource); if (settingsType) { type SettingsWrittenClassification = { settingsType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; }; this.telemetryService.publicLog2<{ settingsType: string }, SettingsWrittenClassification>('settingsWritten', { settingsType }); // Do not log write to user settings.json and .vscode folder as a filePUT event as it ruins our JSON usage data } else { type FilePutClassfication = {} & FileTelemetryDataFragment; this.telemetryService.publicLog2<TelemetryData, FilePutClassfication>('filePUT', this.getTelemetryData(e.model.resource, e.reason)); } } private getTypeIfSettings(resource: URI): string { if (extname(resource) !== '.json') { return ''; } // Check for global settings file if (isEqual(resource, this.environmentService.settingsResource)) { return 'global-settings'; } // Check for keybindings file if (isEqual(resource, this.environmentService.keybindingsResource)) { return 'keybindings'; } // Check for snippets if (isEqualOrParent(resource, this.environmentService.snippetsHome)) { return 'snippets'; } // Check for workspace settings file const folders = this.contextService.getWorkspace().folders; for (const folder of folders) { if (isEqualOrParent(resource, folder.toResource('.vscode'))) { const filename = basename(resource); if (TelemetryContribution.ALLOWLIST_WORKSPACE_JSON.indexOf(filename) > -1) { return `.vscode/${filename}`; } } } return ''; } private getTelemetryData(resource: URI, reason?: number): TelemetryData { let ext = extname(resource); // Remove query parameters from the resource extension const queryStringLocation = ext.indexOf('?'); ext = queryStringLocation !== -1 ? ext.substr(0, queryStringLocation) : ext; const fileName = basename(resource); const path = resource.scheme === Schemas.file ? resource.fsPath : resource.path; const telemetryData = { mimeType: guessMimeTypes(resource).join(', '), ext, path: hash(path), reason, allowlistedjson: undefined as string | undefined }; if (ext === '.json' && TelemetryContribution.ALLOWLIST_JSON.indexOf(fileName) > -1) { telemetryData['allowlistedjson'] = fileName; } return telemetryData; } } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(TelemetryContribution, LifecyclePhase.Restored);
the_stack
import { Scope } from '../entities/alert'; import AlertService from '../services/alert.service'; import ConsoleSettingsService from '../services/consoleSettings.service'; import EntrypointService from '../services/entrypoint.service'; import EnvironmentService from '../services/environment.service'; import FlowService from '../services/flow.service'; import GroupService from '../services/group.service'; import IdentityProviderService from '../services/identityProvider.service'; import NotificationTemplatesService from '../services/notificationTemplates.service'; import OrganizationService from '../services/organization.service'; import PolicyService from '../services/policy.service'; import PortalSettingsService from '../services/portalSettings.service'; import RoleService from '../services/role.service'; import TagService from '../services/tag.service'; import TenantService from '../services/tenant.service'; import UserService from '../services/user.service'; export default organizationRouterConfig; function organizationRouterConfig($stateProvider) { 'ngInject'; $stateProvider .state('organization', { url: '/organization', redirectTo: 'organization.settings', parent: 'withoutSidenav', }) .state('organization.settings', { url: '/settings', component: 'organizationSettings', resolve: { settings: (ConsoleSettingsService: ConsoleSettingsService) => ConsoleSettingsService.get().then((response) => response.data), }, data: { menu: null, perms: { only: [ // hack only read permissions is necessary but READ is also allowed for API_PUBLISHER 'organization-role-c', 'organization-role-u', 'organization-role-d', 'environment-documentation-d', ], }, }, }) .state('organization.settings.ajs-cockpit', { url: '/ajs-cockpit', component: 'cockpit', data: { menu: null, docs: { page: 'organization-configuration-cockpit', }, perms: { only: ['organization-installation-r'], }, }, }) .state('organization.settings.ng-cockpit', { url: '/cockpit', component: 'ngCockpit', data: { useAngularMaterial: true, menu: null, docs: { page: 'organization-configuration-cockpit', }, perms: { only: ['organization-installation-r'], }, }, }) .state('organization.settings.ajs-console', { url: '/ajs-console', component: 'consoleSettings', data: { menu: null, docs: { page: 'organization-configuration-console', }, perms: { only: ['organization-settings-r'], }, }, }) .state('organization.settings.ng-console', { url: '/console', component: 'ngConsoleSettings', data: { useAngularMaterial: true, menu: null, docs: { page: 'organization-configuration-console', }, perms: { only: ['organization-settings-r'], }, }, }) .state('organization.settings.ajs-roles', { url: '/ajs-roles', component: 'roles', resolve: { roleScopes: (RoleService: RoleService) => RoleService.listScopes(), organizationRoles: (RoleService: RoleService) => RoleService.list('ORGANIZATION'), environmentRoles: (RoleService: RoleService) => RoleService.list('ENVIRONMENT'), apiRoles: (RoleService: RoleService) => RoleService.list('API'), applicationRoles: (RoleService: RoleService) => RoleService.list('APPLICATION'), }, data: { menu: null, docs: { page: 'organization-configuration-roles', }, perms: { only: ['organization-role-r'], }, }, params: { roleScope: { type: 'string', value: 'ORGANIZATION', squash: false, }, }, }) .state('organization.settings.ng-roles', { url: '/roles', component: 'ngRoles', data: { useAngularMaterial: true, menu: null, docs: { page: 'organization-configuration-roles', }, perms: { only: ['organization-role-r'], }, }, }) .state('organization.settings.ajs-rolenew', { url: '/ajs-role/:roleScope/new', component: 'role', resolve: { roleScopes: (RoleService: RoleService) => RoleService.listScopes(), }, data: { menu: null, docs: { page: 'organization-configuration-roles', }, perms: { only: ['organization-role-c'], }, }, }) .state('organization.settings.ng-rolenew', { url: '/role/:roleScope/', component: 'ngOrgSettingsRole', data: { useAngularMaterial: true, menu: null, docs: { page: 'organization-configuration-roles', }, perms: { only: ['organization-role-u'], }, }, }) .state('organization.settings.ajs-roleedit', { url: '/ajs-role/:roleScope/:role', component: 'role', resolve: { roleScopes: (RoleService: RoleService) => RoleService.listScopes(), }, data: { menu: null, docs: { page: 'organization-configuration-roles', }, perms: { only: ['organization-role-u'], }, }, }) .state('organization.settings.ng-roleedit', { url: '/role/:roleScope/:role', component: 'ngOrgSettingsRole', data: { useAngularMaterial: true, menu: null, docs: { page: 'organization-configuration-roles', }, perms: { only: ['organization-role-u'], }, }, }) .state('organization.settings.ajs-rolemembers', { url: '/ajs-role/:roleScope/:role/members', component: 'roleMembers', data: { menu: null, docs: { page: 'organization-configuration-roles', }, perms: { only: ['organization-role-u'], }, }, resolve: { members: (RoleService: RoleService, $stateParams) => RoleService.listUsers($stateParams.roleScope, $stateParams.role).then((response) => response), }, }) .state('organization.settings.ng-rolemembers', { url: '/role/:roleScope/:role/members', component: 'ngRoleMembers', data: { useAngularMaterial: true, docs: { page: 'organization-configuration-roles', }, perms: { only: ['organization-role-u'], }, }, }) .state('organization.settings.ajs-users', { url: '/ajs-users?q&page', component: 'users', resolve: { usersPage: (UserService: UserService, $state, $stateParams) => UserService.list($stateParams.q, $stateParams.page).then((response) => response.data), }, data: { menu: null, docs: { page: 'organization-configuration-users', }, perms: { only: ['organization-user-c', 'organization-user-r', 'organization-user-u', 'organization-user-d'], }, }, params: { page: { value: '1', dynamic: true, }, }, }) .state('organization.settings.ng-users', { url: '/users?q&page', component: 'ngOrgSettingsUsers', data: { useAngularMaterial: true, menu: null, docs: { page: 'organization-configuration-users', }, perms: { only: ['organization-user-c', 'organization-user-r', 'organization-user-u', 'organization-user-d'], }, }, params: { page: { value: '1', dynamic: true, }, q: { dynamic: true, }, }, }) .state('organization.settings.ajs-user', { url: '/ajs-users/:userId', component: 'userDetail', resolve: { selectedUser: (UserService: UserService, $stateParams) => UserService.get($stateParams.userId).then((response) => response), groups: (UserService: UserService, $stateParams) => UserService.getUserGroups($stateParams.userId).then((response) => response.data), organizationRoles: (RoleService: RoleService) => RoleService.list('ORGANIZATION').then((roles) => roles), environments: (EnvironmentService: EnvironmentService) => EnvironmentService.list().then((response) => response.data), environmentRoles: (RoleService: RoleService) => RoleService.list('ENVIRONMENT').then((roles) => roles), apiRoles: (RoleService: RoleService) => RoleService.list('API').then((roles) => [{ scope: 'API', name: '', system: false }].concat(roles)), applicationRoles: (RoleService: RoleService) => RoleService.list('APPLICATION').then((roles) => [{ scope: 'APPLICATION', name: '', system: false }].concat(roles)), }, data: { menu: null, docs: { page: 'organization-configuration-user', }, perms: { only: ['organization-user-c', 'organization-user-r', 'organization-user-u', 'organization-user-d'], }, }, }) .state('organization.settings.ajs-newuser', { url: '/ajs-users/new', component: 'newUser', resolve: { identityProviders: (IdentityProviderService: IdentityProviderService) => IdentityProviderService.list(), }, data: { menu: null, docs: { page: 'organization-configuration-create-user', }, perms: { only: ['organization-user-c'], }, }, }) .state('organization.settings.ng-newuser', { url: '/users/new', component: 'ngOrgSettingsNewUser', data: { useAngularMaterial: true, menu: null, docs: { page: 'organization-configuration-create-user', }, perms: { only: ['organization-user-c'], }, }, }) .state('organization.settings.ng-user', { url: '/users/:userId', component: 'ngOrgSettingsUserDetail', data: { useAngularMaterial: true, menu: null, docs: { page: 'organization-configuration-user', }, perms: { only: ['organization-user-c', 'organization-user-r', 'organization-user-u', 'organization-user-d'], }, }, }) .state('organization.settings.ajs-identityproviders', { abstract: true, url: '/ajs-identities', }) .state('organization.settings.ajs-identityproviders.list', { url: '/', component: 'identityProviders', resolve: { target: () => 'ORGANIZATION', targetId: () => 'DEFAULT', identityProviders: (IdentityProviderService: IdentityProviderService) => IdentityProviderService.list().then((response) => response), identities: (OrganizationService: OrganizationService) => OrganizationService.listOrganizationIdentities().then((response) => response.data), settings: (ConsoleSettingsService: ConsoleSettingsService) => ConsoleSettingsService.get().then((response) => response.data), }, data: { menu: null, docs: { page: 'organization-configuration-identityproviders', }, perms: { only: ['organization-identity_provider-r'], }, }, }) .state('organization.settings.ng-identityproviders', { url: '/identities', component: 'ngOrgSettingsIdentityProviders', data: { useAngularMaterial: true, menu: null, docs: { page: 'organization-configuration-identityproviders', }, perms: { only: ['organization-identity_provider-r'], }, }, }) .state('organization.settings.ng-identityprovider-edit', { url: '/identities/:id', component: 'ngOrgSettingsIdentityProvider', data: { useAngularMaterial: true, menu: null, docs: { page: 'organization-configuration-identityproviders', }, perms: { only: ['organization-identity_provider-r', 'organization-identity_provider-u', 'organization-identity_provider-d'], }, }, }) .state('organization.settings.ng-identityprovider-new', { url: '/identities/', component: 'ngOrgSettingsIdentityProvider', data: { useAngularMaterial: true, menu: null, docs: { page: 'organization-configuration-identityproviders', }, perms: { only: ['organization-identity_provider-c'], }, }, }) .state('organization.settings.ajs-identityproviders.new', { url: '/new?:type', component: 'identityProvider', data: { menu: null, docs: { page: 'organization-configuration-identityprovider', }, perms: { only: ['organization-identity_provider-c'], }, }, }) .state('organization.settings.ajs-identityproviders.identityprovider', { url: '/:id', component: 'identityProvider', resolve: { identityProvider: (IdentityProviderService: IdentityProviderService, $stateParams) => IdentityProviderService.get($stateParams.id).then((response) => response), groups: (GroupService: GroupService) => GroupService.list().then((response) => response.data), environmentRoles: (RoleService: RoleService) => RoleService.list('ENVIRONMENT').then((roles) => roles), organizationRoles: (RoleService: RoleService) => RoleService.list('ORGANIZATION').then((roles) => roles), environments: (EnvironmentService: EnvironmentService) => EnvironmentService.list().then((response) => response.data), }, data: { menu: null, docs: { page: 'organization-configuration-identityprovider', }, perms: { only: ['organization-identity_provider-r', 'organization-identity_provider-u', 'organization-identity_provider-d'], }, }, }) .state('organization.settings.ajs-tags', { url: '/ajs-tags', component: 'tags', resolve: { tags: (TagService: TagService) => TagService.list().then((response) => response.data), entrypoints: (EntrypointService: EntrypointService) => EntrypointService.list().then((response) => response.data), groups: (GroupService: GroupService) => GroupService.listByOrganization().then((response) => response.data), settings: (PortalSettingsService: PortalSettingsService) => PortalSettingsService.get().then((response) => response.data), }, data: { menu: null, docs: { page: 'management-configuration-sharding-tags', }, perms: { only: ['organization-tag-r'], }, }, }) .state('organization.settings.ng-tags', { url: '/tags', component: 'ngOrgSettingsTags', data: { useAngularMaterial: true, menu: null, docs: { page: 'management-configuration-sharding-tags', }, perms: { only: ['organization-tag-r'], }, }, }) .state('organization.settings.ajs-policies', { url: '/ajs-policies', component: 'policies', resolve: { tags: (TagService: TagService) => TagService.list().then((response) => response.data), settings: (PortalSettingsService: PortalSettingsService) => PortalSettingsService.get().then((response) => response.data), resolvedFlowSchema: (FlowService: FlowService) => FlowService.getPlatformFlowSchemaForm(), resolvedPolicies: (PolicyService: PolicyService) => PolicyService.list(true, true, true), }, data: { docs: { page: 'management-configuration-policies', }, perms: { only: ['organization-policies-r'], }, }, }) .state('organization.settings.ng-policies', { url: '/policies', component: 'ngPlatformPolicies', data: { useAngularMaterial: true, docs: { page: 'management-configuration-policies', }, perms: { only: ['organization-policies-r'], }, }, }) .state('organization.settings.ajs-newEntrypoint', { url: '/ajs-tags/entrypoint/new', component: 'entrypoint', resolve: { tags: (TagService: TagService) => TagService.list().then((response) => response.data), }, data: { menu: null, docs: { page: 'management-configuration-entrypoint', }, perms: { only: ['organization-entrypoint-c'], }, }, }) .state('organization.settings.ajs-entrypoint', { url: '/ajs-tags/entrypoint/:entrypointId', component: 'entrypoint', resolve: { tags: (TagService: TagService) => TagService.list().then((response) => response.data), }, data: { menu: null, docs: { page: 'management-configuration-entrypoint', }, perms: { only: ['organization-entrypoint-u'], }, }, }) .state('organization.settings.ajs-tag', { url: '/ajs-tags/:tagId', component: 'tag', resolve: { groups: (GroupService: GroupService) => GroupService.listByOrganization().then((response) => response.data), }, data: { menu: null, docs: { page: 'management-configuration-sharding-tag', }, perms: { only: ['organization-tag-r', 'organization-tag-c', 'organization-tag-u'], }, }, }) .state('organization.settings.ajs-tenants', { url: '/ajs-tenants', component: 'tenants', resolve: { tenants: (TenantService: TenantService) => TenantService.list().then((response) => response.data), }, data: { menu: null, docs: { page: 'management-configuration-tenants', }, perms: { only: ['organization-tenant-r'], }, }, }) .state('organization.settings.ng-tenants', { url: '/tenants', component: 'ngTenants', data: { useAngularMaterial: true, menu: null, docs: { page: 'management-configuration-tenants', }, perms: { only: ['organization-tenant-r'], }, }, }) .state('organization.settings.ajs-notificationTemplates', { url: '/ajs-notification-templates', component: 'notificationTemplatesComponent', data: { menu: null, docs: { page: 'organization-configuration-notification-templates', }, perms: { only: ['organization-notification_templates-r'], }, }, resolve: { notificationTemplates: (NotificationTemplatesService: NotificationTemplatesService) => NotificationTemplatesService.getNotificationTemplates().then((response) => response.data), }, }) .state('organization.settings.ng-notificationTemplates', { url: '/notification-templates', component: 'ngNotificationTemplatesComponent', data: { useAngularMaterial: true, menu: null, docs: { page: 'organization-configuration-notification-templates', }, perms: { only: ['organization-notification_templates-r'], }, }, }) .state('organization.settings.ajs-notificationTemplate', { url: '/ajs-notification-templates/:scope/:hook', component: 'notificationTemplateComponent', data: { menu: null, docs: { page: 'organization-configuration-notification-template', }, perms: { only: ['organization-notification_templates-r'], }, }, resolve: { notifTemplates: (NotificationTemplatesService: NotificationTemplatesService, $stateParams) => { if ($stateParams.scope.toUpperCase() === 'TEMPLATES_TO_INCLUDE') { return NotificationTemplatesService.getNotificationTemplates('', $stateParams.scope).then((response) => response.data); } else { return NotificationTemplatesService.getNotificationTemplates($stateParams.hook, $stateParams.scope).then( (response) => response.data, ); } }, alertingStatus: (AlertService: AlertService) => AlertService.getStatus(undefined, Scope.PLATFORM).then((response) => response.data), }, }) .state('organization.settings.ng-notificationTemplate', { url: '/notification-templates/:scope/:hook', component: 'ngNotificationTemplateComponent', data: { useAngularMaterial: true, menu: null, docs: { page: 'organization-configuration-notification-template', }, perms: { only: ['organization-notification_templates-r'], }, }, }); }
the_stack
import { TypedEmitter } from 'tiny-typed-emitter' import { IPC as RawIpc } from 'node-ipc' import { IpcClientOptions, IpcClientSendOptions, IpcPacket, ShardingInstance } from '@src/sharding' import { Collection } from '@discordoo/collection' import { IpcEvents, IpcOpCodes, RAW_IPC_EVENT, SerializeModes } from '@src/constants' import { DiscordooError, DiscordooSnowflake } from '@src/utils' import { IpcBroadcastEvalRequestPacket, IpcBroadcastEvalResponsePacket, IpcCacheRequestPacket, IpcCacheResponsePacket, IpcDispatchPackets, IpcEmergencyGrlHitPacket, IpcEmergencyRestBlockPacket, IpcGuildMembersRequestPacket, IpcHeartbeatPacket, IpcHelloPacket } from '@src/sharding/interfaces/ipc/IpcPackets' import { IpcClientEvents } from '@src/sharding/interfaces/ipc/IpcClientEvents' import { filterAndMap } from '@src/utils/filterAndMap' import { IpcEmergencyOpCodes } from '@src/constants/sharding/IpcEmergencyOpCodes' export class LocalIpcClient extends TypedEmitter<IpcClientEvents> { private bucket: Collection = new Collection() private shardSocket: any private readonly INSTANCE_IPC: string private readonly eventsHandler: any private readonly MANAGER_IPC: string private helloInterval?: NodeJS.Timeout public instance: ShardingInstance public ipc: InstanceType<typeof RawIpc> public shards: number[] public totalShards: number constructor(instance: ShardingInstance, options: IpcClientOptions) { super() this.instance = instance this.INSTANCE_IPC = options.INSTANCE_IPC this.shards = options.shards this.MANAGER_IPC = options.MANAGER_IPC this.totalShards = options.totalShards this.ipc = new RawIpc() this.ipc.config = Object.assign(this.ipc.config, options.config ?? {}) this.eventsHandler = (packet: IpcPacket) => { this.emit('RAW', packet) this.onPacket(packet) } } public connect() { let promise return new Promise((resolve, reject) => { promise = { res: resolve, rej: reject } promise.timeout = setTimeout(() => { this.ipc.config.stopRetrying = true this.bucket.delete(this.INSTANCE_IPC) const err = new DiscordooError( 'LocalIpcClient#connect', 'the connection timed out.', 'the connection had to handle shards:', this.shards.join(', ') + '.', 'inter-process communication shard identifier:', this.INSTANCE_IPC + '.', 'ipc shard id contains:', DiscordooSnowflake.deconstruct(this.INSTANCE_IPC) ) promise.rej(err) }, this.shards.length * 30000) this.bucket.set(this.INSTANCE_IPC, promise) this.ipc.connectTo(this.INSTANCE_IPC, () => { this.ipc.of[this.INSTANCE_IPC].on(RAW_IPC_EVENT, this.eventsHandler) this.helloInterval = setInterval(() => { this.hello(this.ipc.of[this.INSTANCE_IPC]) }, 1000) }) }) } private onPacket(packet: IpcPacket) { // console.log('IPC CLIENT', this.id, 'ON PACKET', process.hrtime.bigint()) if (packet.d?.event_id) { const promise = this.bucket.get(packet.d.event_id) if (promise) { this.bucket.delete(packet.d.event_id) clearTimeout(promise.timeout) return packet.op === IpcOpCodes.ERROR ? promise.rej(packet) : promise.res(packet) } } switch (packet.op) { case IpcOpCodes.IDENTIFY: this.shardSocket = this.ipc.of[packet.d.id] if (this.helloInterval) clearInterval(this.helloInterval) break case IpcOpCodes.CACHE_OPERATE: // console.log('IPC CLIENT', this.id, 'ON CACHE OPERATE', process.hrtime.bigint()) this.cacheOperate(packet as IpcCacheRequestPacket) break case IpcOpCodes.DISPATCH: this.dispatch(packet as IpcDispatchPackets) break case IpcOpCodes.EMERGENCY: this.emergency(packet as IpcEmergencyGrlHitPacket) break } } private emergency(packet: IpcEmergencyGrlHitPacket) { const now = Date.now() if (packet.d.block_until > now) { this.instance.manager.internals.rest.locked = true setTimeout(() => { this.instance.manager.internals.rest.locked = false }, packet.d.block_until - now) const request: IpcEmergencyRestBlockPacket = { op: IpcOpCodes.EMERGENCY, d: { op: IpcEmergencyOpCodes.GLOBAL_RATE_LIMIT_HIT, block_until: packet.d.block_until } } this.instance.manager.instances.forEach(instance => { instance.ipc.send(request) }) } } private async dispatch(packet: IpcDispatchPackets) { switch (packet.t) { case IpcEvents.GUILD_MEMBERS_REQUEST: await this.guildMembersRequest(packet as IpcGuildMembersRequestPacket) break case IpcEvents.BROADCAST_EVAL: { const shards = (packet as IpcBroadcastEvalRequestPacket).d.shards, id = packet.d.event_id const promises: Array<undefined | Promise<any>> = shards.map(s => { const shard = this.instance.manager.instances.get(s) if (shard) packet.d.event_id = this.generate() return shard?.ipc.send(packet, { waitResponse: true }) }) await Promise.all(promises) .then(r => { r = r.filter(r => r !== undefined) const response: IpcBroadcastEvalResponsePacket = { op: IpcOpCodes.DISPATCH, t: IpcEvents.BROADCAST_EVAL, d: { event_id: id, result: r.map(p => p.d.result) } } this.send(response) }) .catch(e => { e.d.event_id = id this.send(e) }) } break case IpcEvents.MESSAGE: { const shards = filterAndMap<any, ShardingInstance>( packet.d.shards, id => this.instance.manager.instances.has(id), id => this.instance.manager.instances.get(id) ) shards.forEach(s => { s.ipc.send(packet) }) } break case IpcEvents.REST_LIMITS_SYNC: { if (!this.instance.manager.internals.rest.locked) { this.instance.manager.internals.rest.allowed -= 1 if (!packet.d.success) this.instance.manager.internals.rest.invalid -= 1 if (this.instance.manager.internals.rest.invalid <= 1) { this.instance.manager.internals.rest.locked = true setTimeout(() => { this.instance.manager.internals.rest.locked = false }, this.instance.manager.internals.rest.invalidResetAt - Date.now()) const request: IpcEmergencyRestBlockPacket = { op: IpcOpCodes.EMERGENCY, d: { op: IpcEmergencyOpCodes.INVALID_REQUEST_LIMIT_ALMOST_REACHED, block_until: this.instance.manager.internals.rest.invalidResetAt } } this.instance.manager.instances.forEach(instance => { instance.ipc.send(request) }) } else if (this.instance.manager.internals.rest.allowed <= 1) { this.instance.manager.internals.rest.locked = true setTimeout(() => { this.instance.manager.internals.rest.locked = false }, this.instance.manager.internals.rest.allowedResetAt - Date.now()) const request: IpcEmergencyRestBlockPacket = { op: IpcOpCodes.EMERGENCY, d: { op: IpcEmergencyOpCodes.GLOBAL_RATE_LIMIT_ALMOST_REACHED, block_until: this.instance.manager.internals.rest.allowedResetAt } } this.instance.manager.instances.forEach(instance => { instance.ipc.send(request) }) } } } break } } private async guildMembersRequest(packet: IpcGuildMembersRequestPacket) { const shard = this.instance.manager.shards.get(packet.d.shard_id), id = packet.d.event_id if (shard) { packet.d.event_id = this.generate() const result: any = await shard.ipc.send(packet, { waitResponse: true, responseTimeout: 100_000 }) result.d.event_id = id await this.send(result) } } private async cacheOperate(packet: IpcCacheRequestPacket) { const shards: number[] = packet.d.shards, id = packet.d.event_id // console.log('IPC CLIENT', this.instance.id, 'ON PROMISES', process.hrtime.bigint()) const promises: Array<undefined | Promise<any>> = shards.map(s => { const shard = this.instance.manager.shards.get(s) if (shard) packet.d.event_id = this.generate() return shard?.ipc.send(packet, { waitResponse: true }) }) // console.log('IPC CLIENT', this.instance.id, 'ON RESPONSES', process.hrtime.bigint()) const responses: Array<IpcCacheResponsePacket | undefined> = await Promise.all(promises) // console.log('IPC CLIENT', this.instance.id, 'ON SUCCESS', process.hrtime.bigint()) const success = responses.some(r => r?.d.success) let result if ('serialize' in packet.d && packet.d.serialize !== undefined) { // console.log('IPC CLIENT', this.instance.id, 'ON SERIALIZE', process.hrtime.bigint()) result = this.serializeResponses( responses.map(r => r?.d.success ? r?.d.result : undefined).filter(r => r ?? false), // filter undefined/null packet.d.serialize ) } else { result = responses.map(r => r?.d.result) } // console.log('IPC CLIENT', this.instance.id, 'ON CACHE OPERATE REPLY', process.hrtime.bigint()) return this.send({ op: IpcOpCodes.CACHE_OPERATE, d: { event_id: id, success, result } }) } private serializeResponses(replies: any[], type: SerializeModes) { switch (type) { case SerializeModes.ANY: return replies.find(r => r !== undefined && r !== null) case SerializeModes.ARRAY: return replies.flat() case SerializeModes.NUMBERS_ARRAY: { return replies.reduce((prev, curr) => { if (!prev.length) return curr else return prev.map((x, i) => x + (curr[i] ?? 0)) }, []) } case SerializeModes.BOOLEAN: return replies.find(r => r === true) ?? false case SerializeModes.NUMBER: return replies.reduce((prev, curr) => prev + curr, 0) default: return replies } } private hello(connection: any) { const data: IpcHelloPacket = { op: IpcOpCodes.HELLO, d: { id: this.MANAGER_IPC, event_id: this.generate(), heartbeat_interval: 5000, shards: this.shards, total_shards: this.totalShards } } this.send(data, { connection: connection }) } private sendHeartbeat() { const data: IpcHeartbeatPacket = { op: IpcOpCodes.HEARTBEAT, d: { id: this.MANAGER_IPC, event_id: this.generate() } } this.send(data) } public send(data: IpcPacket, options: IpcClientSendOptions = {}) { if (typeof options !== 'object') throw new DiscordooError('LocalIpcClient#send', 'options must be object type only') if (!options.connection) options.connection = this.shardSocket if (!options.connection) throw new DiscordooError('LocalIpcClient#send', 'cannot find socket to send packet:', data) let promise: any return new Promise((resolve, reject) => { promise = { res: resolve, rej: reject } if (options.waitResponse && data.d?.event_id) { promise.timeout = setTimeout(() => { reject(new DiscordooError('LocalIpcClient#send', 'response time is up')) }, options.responseTimeout ?? 60_000) this.bucket.set(data.d.event_id, promise) } options.connection.emit(RAW_IPC_EVENT, data) if (!options.waitResponse) resolve(void 0) }) } public generate() { // console.log('CLIENT', this.id) return DiscordooSnowflake.generate(this.instance.id, process.pid) } }
the_stack
import { Options, Sequelize, SyncOptions as SequelizeSyncOptions, } from 'sequelize'; import glob from 'glob'; import Table, { MergeOptions, TableOptions } from './table'; import { Model, ModelCtor } from './model'; import { requireModule } from './utils'; import _ from 'lodash'; import { EventEmitter } from 'events'; export interface SyncOptions extends SequelizeSyncOptions { /** * 指定需要更新字段的 tables */ tables?: string[] | Table[] | Map<string, Table>; } export interface ImportOptions { /** * 指定配置所在路径 */ directory: string; /** * 文件后缀,默认值 ['js', 'ts', 'json'] */ extensions?: string[]; } export interface DatabaseOptions extends Options { } // export type HookType = 'beforeTableInit' | 'afterTableInit' | 'beforeAddField' | 'afterAddField'; export class Extend { tableOptions: TableOptions; mergeOptions: MergeOptions constructor(tableOptions: TableOptions, mergeOptions?: MergeOptions) { this.tableOptions = tableOptions; this.mergeOptions = mergeOptions; } } export function extend(tableOptions: TableOptions, mergeOptions: MergeOptions = {}) { return new Extend(tableOptions, mergeOptions); } type HookType = 'beforeValidate' | 'afterValidate' | 'beforeCreate' | 'afterCreate' | 'beforeDestroy' | 'afterDestroy' | 'beforeRestore' | 'afterRestore' | 'beforeUpdate' | 'afterUpdate' | 'beforeSave' | 'afterSave' | 'beforeBulkCreate' | 'afterBulkCreate' | 'beforeBulkDestroy' | 'afterBulkDestroy' | 'beforeBulkRestore' | 'afterBulkRestore' | 'beforeBulkUpdate' | 'afterBulkUpdate' | 'beforeSync' | 'afterSync' | 'beforeBulkSync' | 'afterBulkSync' | 'beforeDefine' | 'afterDefine' | 'beforeInit' | 'afterInit' | 'beforeConnect' | 'afterConnect' | 'beforeDisconnect' | 'afterDisconnect'; export default class Database extends EventEmitter { public readonly sequelize: Sequelize; /** * 哪些 Model 需要建立表关系 */ public readonly associating = new Set<string>(); /** * 中间表 */ public readonly throughTables = new Map<string, Array<string>>(); protected tables = new Map<string, Table>(); protected options: DatabaseOptions; protected hooks = {}; protected extTableOptions = new Map<string, any>(); protected hookTypes = new Map(Object.entries({ beforeValidate: 1, afterValidate: 1, beforeCreate: 1, afterCreate: 1, beforeDestroy: 1, afterDestroy: 1, beforeRestore: 1, afterRestore: 1, beforeUpdate: 1, afterUpdate: 1, beforeSave: 1, afterSave: 1, beforeBulkCreate: 2, afterBulkCreate: 2, beforeBulkDestroy: 3, afterBulkDestroy: 3, beforeBulkRestore: 3, afterBulkRestore: 3, beforeBulkUpdate: 3, afterBulkUpdate: 3, beforeSync: 4, afterSync: 4, beforeBulkSync: 4, afterBulkSync: 4, beforeDefine: 0, afterDefine: 0, beforeInit: 0, afterInit: 0, beforeConnect: 0, afterConnect: 0, beforeDisconnect: 0, afterDisconnect: 0, })); constructor(options?: DatabaseOptions) { super(); this.options = options; this.sequelize = new Sequelize(options); } private _getHookType(event: any) { if (typeof event === 'string') { event = event.split('.'); } if (!Array.isArray(event)) { return; } const hookType = [...event].pop(); if (!this.hookTypes.has(hookType)) { return; } return hookType; } on(event: HookType | Omit<string, HookType> | symbol, listener: (...args: any[]) => void) { const hookType = this._getHookType(event); if (hookType) { const state = this.hookTypes.get(hookType); this.sequelize.addHook(hookType, async (...args: any[]) => { let modelName: string; switch (state) { case 1: modelName = args?.[0]?.constructor?.name; break; case 2: modelName = args?.[1]?.model?.name; break; case 3: modelName = args?.[0]?.model?.name; break; } // console.log({ modelName, args }); if (modelName) { await this.emitAsync(`${modelName}.${hookType}`, ...args); } await this.emitAsync(hookType, ...args); }); this.hookTypes.delete(hookType); } return super.on(event as any, listener); } async emitAsync(event: string | symbol, ...args: any[]): Promise<boolean> { // @ts-ignore const events = this._events; let callbacks = events?.[event]; if (!callbacks) { return false; } // helper function to reuse as much code as possible const run = (cb) => { switch (args.length) { // fast cases case 0: cb = cb.call(this); break; case 1: cb = cb.call(this, args[0]); break; case 2: cb = cb.call(this, args[0], args[1]); break; case 3: cb = cb.call(this, args[0], args[1], args[2]); break; // slower default: cb = cb.apply(this, args); } if ( cb && ( cb instanceof Promise || typeof cb.then === 'function' ) ) { return cb; } return Promise.resolve(true); }; if (typeof callbacks === 'function') { await run(callbacks); } else if (typeof callbacks === 'object') { callbacks = callbacks.slice().filter(Boolean); await callbacks.reduce((prev, next) => { return prev.then((res) => { return run(next).then((result) => Promise.resolve(res.concat(result))); }); }, Promise.resolve([])); } return true; } /** * 载入指定目录下 tables 配置(配置的文件驱动) * * TODO: 配置的文件驱动现在会全部初始化,大数据时可能存在性能瓶颈,后续可以加入动态加载 * * @param {object} [options] * @param {string} [options.directory] 指定配置所在路径 * @param {array} [options.extensions = ['js', 'ts', 'json']] 文件后缀 */ public import(options: ImportOptions): Map<string, Table> { const { extensions = ['js', 'ts', 'json'], directory } = options; const patten = `${directory}/*.{${extensions.join(',')}}`; const files = glob.sync(patten, { ignore: [ '**/*.d.ts' ] }); const tables = new Map<string, Table>(); files.forEach((file: string) => { const result = requireModule(file); if (result instanceof Extend) { // 如果还没初始化,extend 的先暂存起来,后续处理 if (!this.tables.has(result.tableOptions.name)) { this.extTableOptions.set(result.tableOptions.name, result); } else { const table = this.extend(result.tableOptions, result.mergeOptions); tables.set(table.getName(), table); } } else { let table = this.extend(typeof result === 'function' ? result(this) : result); // 如果有未处理的 extend 取回来合并 if (this.extTableOptions.has(table.getName())) { const result = this.extTableOptions.get(table.getName()); table = this.extend(result.tableOptions, result.mergeOptions); this.extTableOptions.delete(table.getName()); } tables.set(table.getName(), table); } }); return tables; } /** * 配置表 * * @param options */ public table(options: TableOptions): Table { const { name } = options; const table = new Table(options, { database: this }); this.tables.set(name, table); // 在 source 或 target 之后定义 through,需要更新 source 和 target 的 model if (this.throughTables.has(name)) { const [sourceTable, targetTable] = this.getTables(this.throughTables.get(name)); sourceTable && sourceTable.modelInit(true); targetTable && targetTable.modelInit(true); // this.throughTables.delete(name); } return table; } /** * 扩展配置(实验性 API) * * @param options */ public extend(options: TableOptions, mergeOptions?: MergeOptions): Table { const { name } = options; let table: Table; if (this.tables.has(name)) { table = this.tables.get(name); table.extend(options, mergeOptions); } else { table = this.table(options); this.tables.set(name, table); } return table; } /** * 是否已配置 * * @param name */ public isDefined(name: string): boolean { return this.sequelize.isDefined(name); } /** * 获取 Model * * TODO: 动态初始化并加载配置(懒汉式) * 动态初始化需要支持文件驱动和数据库驱动 * * @param name */ public getModel(name: string): ModelCtor<Model> { return this.isDefined(name) ? this.sequelize.model(name) as any : undefined; } /** * 获取指定 names 的 Models * * @param names */ public getModels(names: string[] = []): Array<ModelCtor<Model>> { if (names.length === 0) { return this.sequelize.models as any; } return names.map(name => this.getModel(name)); } /** * 获取 table 配置 * * TODO: * 未单独配置多对多中间表时,取不到中间表的 table,但是可以取到 Model * 动态初始化并加载配置(懒汉式),动态初始化需要支持文件驱动和数据库驱动 * * @param name */ public getTable(name: string): Table { return this.tables.has(name) ? this.tables.get(name) : undefined; } /** * 获取指定 names 的 table 配置 * * @param names */ public getTables(names: string[] = []): Array<Table> { if (names.length === 0) { return [...this.tables.values()]; } return names.map(name => this.getTable(name)); } /** * 建立表关系 * * 表关系相关字段是在 Model.init 之后进行的 */ public associate() { for (const name of this.associating) { const Model: any = this.getModel(name); Model.associate && Model.associate(this.sequelize.models); } } /** * 插件扩展 * * TODO: 细节待定 * * @param plugin * @param options */ public async plugin(plugin: any, options = {}) { await plugin(this, options); } /** * 表字段更新 * * @param options */ public async sync(options: SyncOptions = {}) { const { tables = [], ...restOptions } = options; let items: Array<any>; if (tables instanceof Map) { items = Array.from(tables.values()); } else { items = tables; } /** * sequelize.sync 只能处理全部 model 的字段更新 * Model.sync 只能处理当前 Model 的字段更新,不处理关系表 * database.sync 可以指定 tables 进行字段更新,也可以自动处理关系表的字段更新 */ if (items.length > 0) { // 指定 tables 时,新建 sequelize 实例来单独处理这些 tables 相关 models 的 sync const sequelize = new Sequelize(this.options); const names = new Set<string>(); for (const key in items) { let table = items[key]; if (typeof table === 'string') { table = this.getTable(table); } if (table instanceof Table) { for (const name of table.getRelatedTableNames()) { names.add(name); } } } for (const name of names) { // @ts-ignore const model = this.getModel(name); if (model) { sequelize.modelManager.addModel(model); } } await sequelize.sync(restOptions); await sequelize.close(); } else { await this.sequelize.sync(restOptions); } } /** * 关闭数据库连接 */ public async close() { this.removeAllListeners(); return this.sequelize.close(); } /** * 添加 hook * * @param hookType * @param fn */ public addHook(hookType: HookType | string, fn: Function) { const hooks = this.hooks[hookType] || []; hooks.push(fn); this.hooks[hookType] = hooks; } /** * 运行 hook * * @param hookType * @param args */ public async runHooks(hookType: HookType | string, ...args) { const hooks = this.hooks[hookType] || []; for (const hook of hooks) { if (typeof hook === 'function') { await hook(...args); } } } public getFieldByPath(fieldPath: string) { const [tableName, fieldName] = fieldPath.split('.'); return this.getTable(tableName).getField(fieldName); } }
the_stack
import { NetFieldsReverse } from '../types/net_fields'; export type LogDefinition = { type: string; name: string; // Parsed ACT log line type. messageType: string; // include all of these lines in any split globalInclude?: boolean; // include the last line of this type in any split lastInclude?: boolean; // whether this line can be anonymized canAnonymize?: boolean; // needs more information, never seen this log isUnknown?: boolean; // fields at this index and beyond are cleared, when anonymizing firstUnknownField?: number; fields?: { [fieldName: string]: number }; subFields?: { [fieldName: string]: { [fieldValue: string]: { name: string; canAnonymize: boolean; }; }; }; // map of indexes from a player id to the index of that player name playerIds?: { [fieldIdx: number]: number | null }; // a list of fields that are ok to not appear (or have invalid ids) optionalFields?: readonly number[]; }; export type LogDefinitionMap = { [name: string]: LogDefinition }; const logDefinitions = { GameLog: { type: '00', name: 'GameLog', messageType: 'ChatLog', fields: { type: 0, timestamp: 1, code: 2, name: 3, line: 4, }, subFields: { code: { '0039': { name: 'message', canAnonymize: true, }, '0038': { name: 'echo', canAnonymize: true, }, '0044': { name: 'dialog', canAnonymize: true, }, '0839': { name: 'message', canAnonymize: true, }, }, }, }, ChangeZone: { type: '01', name: 'ChangeZone', messageType: 'Territory', fields: { type: 0, timestamp: 1, id: 2, name: 3, }, lastInclude: true, canAnonymize: true, }, ChangedPlayer: { type: '02', name: 'ChangedPlayer', messageType: 'ChangePrimaryPlayer', fields: { type: 0, timestamp: 1, id: 2, name: 3, }, playerIds: { 2: 3, }, lastInclude: true, canAnonymize: true, }, AddedCombatant: { type: '03', name: 'AddedCombatant', messageType: 'AddCombatant', fields: { type: 0, timestamp: 1, id: 2, name: 3, job: 4, level: 5, ownerId: 6, worldId: 7, world: 8, npcNameId: 9, npcBaseId: 10, currentHp: 11, hp: 12, currentMp: 13, mp: 14, // maxTp: 15, // tp: 16, x: 17, y: 18, z: 19, heading: 20, }, playerIds: { 2: 3, 6: null, }, canAnonymize: true, }, RemovedCombatant: { type: '04', name: 'RemovedCombatant', messageType: 'RemoveCombatant', fields: { type: 0, timestamp: 1, id: 2, name: 3, job: 4, level: 5, owner: 6, world: 8, npcNameId: 9, npcBaseId: 10, hp: 12, x: 17, y: 18, z: 19, heading: 20, }, playerIds: { 2: 3, 6: null, }, canAnonymize: true, }, PartyList: { type: '11', name: 'PartyList', messageType: 'PartyList', fields: { type: 0, timestamp: 1, partyCount: 2, id0: 3, id1: 4, id2: 5, id3: 6, id4: 7, id5: 8, id6: 9, id7: 10, id8: 11, id9: 12, id10: 13, id11: 14, id12: 15, id13: 16, id14: 17, id15: 18, id16: 19, id17: 20, id18: 21, id19: 22, id20: 23, id21: 24, id22: 25, id23: 26, }, playerIds: { 3: null, 4: null, 5: null, 6: null, 7: null, 8: null, 9: null, 10: null, 11: null, 12: null, 13: null, 14: null, 15: null, 16: null, 17: null, 18: null, 19: null, 20: null, 21: null, 22: null, 23: null, 24: null, 25: null, 26: null, }, optionalFields: [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, ], canAnonymize: true, lastInclude: true, }, PlayerStats: { type: '12', name: 'PlayerStats', messageType: 'PlayerStats', fields: { type: 0, timestamp: 1, job: 2, strength: 3, dexterity: 4, vitality: 5, intelligence: 6, mind: 7, piety: 8, attackPower: 9, directHit: 10, criticalHit: 11, attackMagicPotency: 12, healMagicPotency: 13, determination: 14, skillSpeed: 15, spellSpeed: 16, tenacity: 18, localContentId: 19, }, canAnonymize: true, lastInclude: true, }, StartsUsing: { type: '20', name: 'StartsUsing', messageType: 'StartsCasting', fields: { type: 0, timestamp: 1, sourceId: 2, source: 3, id: 4, ability: 5, targetId: 6, target: 7, castTime: 8, x: 9, y: 10, z: 11, heading: 12, }, optionalFields: [6], playerIds: { 2: 3, 6: 7, }, canAnonymize: true, }, Ability: { type: '21', name: 'Ability', messageType: 'ActionEffect', fields: { type: 0, timestamp: 1, sourceId: 2, source: 3, id: 4, ability: 5, targetId: 6, target: 7, flags: 8, damage: 9, targetCurrentHp: 24, targetMaxHp: 25, targetCurrentMp: 26, targetMaxMp: 27, // targetCurrentTp: 28, // targetMaxTp: 29, targetX: 30, targetY: 31, targetZ: 32, targetHeading: 33, currentHp: 34, maxHp: 35, currentMp: 36, maxMp: 37, // currentTp: 38; // maxTp: 39; x: 40, y: 41, z: 42, heading: 43, sequence: 44, targetIndex: 45, }, playerIds: { 2: 3, 6: 7, }, optionalFields: [6], firstUnknownField: 44, canAnonymize: true, }, NetworkAOEAbility: { type: '22', name: 'NetworkAOEAbility', messageType: 'AOEActionEffect', fields: { type: 0, timestamp: 1, sourceId: 2, source: 3, id: 4, ability: 5, targetId: 6, target: 7, flags: 8, x: 40, y: 41, z: 42, heading: 43, }, playerIds: { 2: 3, 6: 7, }, optionalFields: [6], firstUnknownField: 44, canAnonymize: true, }, NetworkCancelAbility: { type: '23', name: 'NetworkCancelAbility', messageType: 'CancelAction', fields: { type: 0, timestamp: 1, sourceId: 2, source: 3, id: 4, name: 5, reason: 6, }, playerIds: { 2: 3, }, canAnonymize: true, }, NetworkDoT: { type: '24', name: 'NetworkDoT', messageType: 'DoTHoT', fields: { type: 0, timestamp: 1, id: 2, name: 3, which: 4, effectId: 5, damage: 6, currentHp: 7, maxHp: 8, currentMp: 9, maxMp: 10, // currentTp: 11, // maxTp: 12, x: 13, y: 14, z: 15, heading: 16, }, playerIds: { 2: 3, }, canAnonymize: true, }, WasDefeated: { type: '25', name: 'WasDefeated', messageType: 'Death', fields: { type: 0, timestamp: 1, targetId: 2, target: 3, sourceId: 4, source: 5, }, playerIds: { 2: 3, 4: 5, }, canAnonymize: true, }, GainsEffect: { type: '26', name: 'GainsEffect', messageType: 'StatusAdd', fields: { type: 0, timestamp: 1, effectId: 2, effect: 3, duration: 4, sourceId: 5, source: 6, targetId: 7, target: 8, count: 9, targetMaxHp: 10, sourceMaxHp: 11, }, playerIds: { 5: 6, 7: 8, }, canAnonymize: true, }, HeadMarker: { type: '27', name: 'HeadMarker', messageType: 'TargetIcon', fields: { type: 0, timestamp: 1, targetId: 2, target: 3, id: 6, }, playerIds: { 2: 3, }, canAnonymize: true, }, NetworkRaidMarker: { type: '28', name: 'NetworkRaidMarker', messageType: 'WaymarkMarker', fields: { type: 0, timestamp: 1, operation: 2, waymark: 3, id: 4, name: 5, x: 6, y: 7, z: 8, }, canAnonymize: true, }, NetworkTargetMarker: { type: '29', name: 'NetworkTargetMarker', messageType: 'SignMarker', fields: { type: 0, timestamp: 1, operation: 2, // Add, Update, Delete waymark: 3, id: 4, name: 5, targetId: 6, targetName: 7, }, playerIds: { 4: null, 5: null, }, }, LosesEffect: { type: '30', name: 'LosesEffect', messageType: 'StatusRemove', fields: { type: 0, timestamp: 1, effectId: 2, effect: 3, sourceId: 5, source: 6, targetId: 7, target: 8, count: 9, }, playerIds: { 5: 6, 7: 8, }, canAnonymize: true, }, NetworkGauge: { type: '31', name: 'NetworkGauge', messageType: 'Gauge', fields: { type: 0, timestamp: 1, id: 2, data0: 3, data1: 4, data2: 5, data3: 6, }, playerIds: { 2: null, }, // Sometimes this last field looks like a player id. // For safety, anonymize all of the gauge data. firstUnknownField: 3, canAnonymize: true, }, NetworkWorld: { type: '32', name: 'NetworkWorld', messageType: 'World', fields: { type: 0, timestamp: 1, }, isUnknown: true, }, ActorControl: { type: '33', name: 'ActorControl', messageType: 'Director', fields: { type: 0, timestamp: 1, instance: 2, command: 3, data0: 4, data1: 5, data2: 6, data3: 7, }, canAnonymize: true, }, NameToggle: { type: '34', name: 'NameToggle', messageType: 'NameToggle', fields: { type: 0, timestamp: 1, id: 2, name: 3, targetId: 4, targetName: 5, toggle: 6, }, playerIds: { 2: 3, 4: 5, }, canAnonymize: true, }, Tether: { type: '35', name: 'Tether', messageType: 'Tether', fields: { type: 0, timestamp: 1, sourceId: 2, source: 3, targetId: 4, target: 5, id: 8, }, playerIds: { 2: 3, 4: 5, }, canAnonymize: true, firstUnknownField: 9, }, LimitBreak: { type: '36', name: 'LimitBreak', messageType: 'LimitBreak', fields: { type: 0, timestamp: 1, valueHex: 2, bars: 3, }, canAnonymize: true, }, NetworkEffectResult: { type: '37', name: 'NetworkEffectResult', messageType: 'EffectResult', fields: { type: 0, timestamp: 1, id: 2, name: 3, sequenceId: 4, currentHp: 5, maxHp: 6, currentMp: 7, maxMp: 8, // currentTp: 9, // maxTp: 10, x: 11, y: 12, z: 13, heading: 14, }, playerIds: { 2: 3, }, firstUnknownField: 22, canAnonymize: true, }, StatusEffect: { type: '38', name: 'StatusEffect', messageType: 'StatusList', fields: { type: 0, timestamp: 1, targetId: 2, target: 3, jobLevelData: 4, hp: 5, maxHp: 6, mp: 7, maxMp: 8, x: 11, y: 12, z: 13, heading: 14, data0: 15, data1: 16, data2: 17, // Variable number of triplets here, but at least one. }, playerIds: { 2: 3, }, firstUnknownField: 20, canAnonymize: true, }, NetworkUpdateHP: { type: '39', name: 'NetworkUpdateHP', messageType: 'UpdateHp', fields: { type: 0, timestamp: 1, id: 2, name: 3, currentHp: 4, maxHp: 5, currentMp: 6, maxMp: 7, // currentTp: 8, // maxTp: 9, x: 10, y: 11, z: 12, heading: 13, }, playerIds: { 2: 3, }, canAnonymize: true, }, Map: { type: '40', name: 'Map', messageType: 'ChangeMap', fields: { type: 0, timestamp: 1, id: 2, regionName: 3, placeName: 4, placeNameSub: 5, }, canAnonymize: true, }, SystemLogMessage: { type: '41', name: 'SystemLogMessage', messageType: 'SystemLogMessage', fields: { type: 0, timestamp: 1, // unknown: 2, id: 3, param0: 4, param1: 5, param2: 6, }, canAnonymize: true, }, ParserInfo: { type: '249', name: 'ParserInfo', messageType: 'Settings', fields: { type: 0, timestamp: 1, }, globalInclude: true, canAnonymize: true, }, ProcessInfo: { type: '250', name: 'ProcessInfo', messageType: 'Process', fields: { type: 0, timestamp: 1, }, globalInclude: true, canAnonymize: true, }, Debug: { type: '251', name: 'Debug', messageType: 'Debug', fields: { type: 0, timestamp: 1, }, globalInclude: true, canAnonymize: false, }, PacketDump: { type: '252', name: 'PacketDump', messageType: 'PacketDump', fields: { type: 0, timestamp: 1, }, canAnonymize: false, }, Version: { type: '253', name: 'Version', messageType: 'Version', fields: { type: 0, timestamp: 1, }, globalInclude: true, canAnonymize: true, }, Error: { type: '254', name: 'Error', messageType: 'Error', fields: { type: 0, timestamp: 1, }, canAnonymize: false, }, None: { type: '[0-9]+', name: 'None', messageType: 'None', fields: { type: 0, timestamp: 1, }, isUnknown: true, }, } as const; // Verify that this has the right type, but export `as const`. const assertLogDefinitions: LogDefinitionMap = logDefinitions; console.assert(assertLogDefinitions); export type LogDefinitions = typeof logDefinitions; export type LogDefinitionTypes = keyof LogDefinitions; export type ParseHelperField< Type extends LogDefinitionTypes, Fields extends NetFieldsReverse[Type], Field extends keyof Fields, > = { field: Fields[Field] extends string ? Fields[Field] : never; value?: string; }; export type ParseHelperFields<T extends LogDefinitionTypes> = { [field in keyof NetFieldsReverse[T]]: ParseHelperField<T, NetFieldsReverse[T], field>; }; export default logDefinitions;
the_stack
module dragonBones { /** * @class dragonBones.FastArmature * @classdesc * FastArmature 是 DragonBones 高效率的骨骼动画系统。他能缓存动画数据,大大减少动画播放的计算 * 不支持动态添加Bone和Slot,换装请通过更换Slot的dispaly或子骨架childArmature来实现 * @extends dragonBones.EventDispatcher * @see dragonBones.ArmatureData * * @example <pre> //获取动画数据 var skeletonData = RES.getRes("skeleton"); //获取纹理集数据 var textureData = RES.getRes("textureConfig"); //获取纹理集图片 var texture = RES.getRes("texture"); //创建一个工厂,用来创建Armature var factory:dragonBones.EgretFactory = new dragonBones.EgretFactory(); //把动画数据添加到工厂里 factory.addSkeletonData(dragonBones.DataParser.parseDragonBonesData(skeletonData)); //把纹理集数据和图片添加到工厂里 factory.addTextureAtlas(new dragonBones.EgretTextureAtlas(texture, textureData)); //获取Armature的名字,dragonBones4.0的数据可以包含多个骨架,这里取第一个Armature var armatureName:string = skeletonData.armature[0].name; //从工厂里创建出Armature var armature:dragonBones.FastArmature = factory.buildFastArmature(armatureName); //获取装载Armature的容器 var armatureDisplay = armature.display; //把它添加到舞台上 this.addChild(armatureDisplay); //以60fps的帧率开启动画缓存,缓存所有的动画数据 var animationCachManager:dragonBones.AnimationCacheManager = armature.enableAnimationCache(60); //取得这个Armature动画列表中的第一个动画的名字 var curAnimationName = armature.animation.animationList[0]; //播放这个动画,gotoAndPlay各个参数说明 //第一个参数 animationName {string} 指定播放动画的名称. //第二个参数 fadeInTime {number} 动画淡入时间 (>= 0), 默认值:-1 意味着使用动画数据中的淡入时间. //第三个参数 duration {number} 动画播放时间。默认值:-1 意味着使用动画数据中的播放时间. //第四个参数 layTimes {number} 动画播放次数(0:循环播放, >=1:播放次数, NaN:使用动画数据中的播放时间), 默认值:NaN armature.animation.gotoAndPlay(curAnimationName,0.3,-1,0); //把Armature添加到心跳时钟里 dragonBones.WorldClock.clock.add(armature); //心跳时钟开启 egret.Ticker.getInstance().register(function (advancedTime) { dragonBones.WorldClock.clock.advanceTime(advancedTime / 1000); }, this); </pre> */ export class FastArmature extends EventDispatcher implements ICacheableArmature{ /** * The name should be same with ArmatureData's name */ public name:string; /** * An object that can contain any user extra data. */ public userData:any; private _enableCache:boolean; /** * 保证CacheManager是独占的前提下可以开启,开启后有助于性能提高 */ public isCacheManagerExclusive:boolean = false; /** @private */ public _animation:FastAnimation; /** @private */ public _display:any; /** @private Store bones based on bones' hierarchy (From root to leaf)*/ public boneList:Array<FastBone>; public _boneDic:any; /** @private Store slots based on slots' zOrder*/ public slotList:Array<FastSlot>; public _slotDic:any; public slotHasChildArmatureList:Array<FastSlot>; public _enableEventDispatch:boolean = true; public __dragonBonesData:DragonBonesData; public _armatureData:ArmatureData; public _slotsZOrderChanged:boolean; public _eventList:Array<any>; private _delayDispose:boolean; private _lockDispose:boolean; private useCache:boolean = true; public constructor(display:any){ super(); this._display = display; this._animation = new FastAnimation(this); this._slotsZOrderChanged = false; this._armatureData = null; this.boneList = []; this._boneDic = {}; this.slotList = []; this._slotDic = {}; this.slotHasChildArmatureList = []; this._eventList = []; this._delayDispose = false; this._lockDispose = false; } /** * Cleans up any resources used by this instance. */ public dispose():void{ this._delayDispose = true; if(!this._animation || this._lockDispose){ return; } this.userData = null; this._animation.dispose(); var i:number = this.slotList.length; while(i --){ this.slotList[i].dispose(); } i = this.boneList.length; while(i --){ this.boneList[i].dispose(); } this.slotList.length = 0; this.boneList.length = 0; this._armatureData = null; this._animation = null; this.slotList = null; this.boneList = null; this._eventList = null; } /** * Update the animation using this method typically in an ENTERFRAME Event or with a Timer. * @param The amount of second to move the playhead ahead. */ public advanceTime(passedTime:number):void{ this._lockDispose = true; this._animation.advanceTime(passedTime); var bone:FastBone; var slot:FastSlot; var i:number = 0; if(this._animation.animationState.isUseCache()){ if(!this.useCache){ this.useCache = true; } i = this.slotList.length; while(i --){ slot = this.slotList[i]; slot.updateByCache(); } } else{ if(this.useCache){ this.useCache = false; i = this.slotList.length; while(i --){ slot = this.slotList[i]; slot.switchTransformToBackup(); } } i = this.boneList.length; while(i --){ bone = this.boneList[i]; bone.update(); } i = this.slotList.length; while(i --){ slot = this.slotList[i]; slot._update(); } } i = this.slotHasChildArmatureList.length; while(i--){ slot = this.slotHasChildArmatureList[i]; var childArmature:FastArmature = slot.childArmature; if(childArmature){ childArmature.advanceTime(passedTime); } } if(this._slotsZOrderChanged){ this.updateSlotsZOrder(); } while(this._eventList.length > 0){ this.dispatchEvent(this._eventList.shift()); } this._lockDispose = false; if(this._delayDispose){ this.dispose(); } } /** * 开启动画缓存 * @param {number} 帧速率,每秒缓存多少次数据,越大越流畅,若值小于零会被设置为动画数据中的默认帧率 * @param {Array<any>} 需要缓存的动画列表,如果为null,则全部动画都缓存 * @param {boolean} 动画是否是循环动画,仅在3.0以下的数据格式使用,如果动画不是循环动画请设置为false,默认为true。 * @return {AnimationCacheManager} 返回缓存管理器,可以绑定到其他armature以减少内存 */ public enableAnimationCache(frameRate:number, animationList:Array<any> = null, loop:boolean = true):AnimationCacheManager{ var animationCacheManager:AnimationCacheManager = AnimationCacheManager.initWithArmatureData(this.armatureData,frameRate); if(animationList){ var length:number = animationList.length; for(var i:number = 0;i < length;i++){ var animationName:string = animationList[i]; animationCacheManager.initAnimationCache(animationName); } } else{ animationCacheManager.initAllAnimationCache(); } animationCacheManager.setCacheGeneratorArmature(this); animationCacheManager.generateAllAnimationCache(loop); animationCacheManager.bindCacheUserArmature(this); this.enableCache = true; return animationCacheManager; } /** * 获取指定名称的 Bone * @param boneName {string} Bone名称 * @returns {FastBone} */ public getBone(boneName:string):FastBone { return this._boneDic[boneName]; } /** * 获取指定名称的 Slot * @param slotName {string} Slot名称 * @returns {FastSlot} */ public getSlot(slotName:string):FastSlot { return this._slotDic[slotName]; } /** * 获取包含指定显示对象的 Bone * @param display {any} 显示对象实例 * @returns {FastBone} */ public getBoneByDisplay(display:any):FastBone { var slot:FastSlot = this.getSlotByDisplay(display); return slot?slot.parent:null; } /** * 获取包含指定显示对象的 Slot * @param displayObj {any} 显示对象实例 * @returns {FastSlot} */ public getSlotByDisplay(displayObj:any):FastSlot { if(displayObj) { for(var i:number = 0,len:number = this.slotList.length; i < len; i++) { if(this.slotList[i].display == displayObj) { return this.slotList[i]; } } } return null; } /** * 获取骨架包含的所有插槽 * @param returnCopy {boolean} 是否返回拷贝。默认:true * @returns {FastSlot[]} */ public getSlots(returnCopy:boolean = true):Array<FastSlot> { return returnCopy?this.slotList.concat():this.slotList; } public _updateBonesByCache():void{ var i:number = this.boneList.length; var bone:FastBone; while(i --){ bone = this.boneList[i]; bone.update(); } } /** * 在骨架中为指定名称的 FastBone 添加一个子 FastBone. * 和Armature不同,FastArmature的这个方法不能在运行时动态添加骨骼 * @param bone {FastBone} FastBone 实例 * @param parentName {string} 父骨头名称 默认:null */ public addBone(bone:FastBone, parentName:string = null):void{ var parentBone:FastBone; if(parentName){ parentBone = this.getBone(parentName); parentBone.boneList.push(bone); } bone.armature = this; bone.setParent(parentBone); this.boneList.unshift(bone); this._boneDic[bone.name] = bone; } /** * 为指定名称的 FastBone 添加一个子 FastSlot. * 和Armature不同,FastArmature的这个方法不能在运行时动态添加插槽 * @param slot {FastSlot} FastSlot 实例 * @param boneName {string} * @see dragonBones.Bone */ public addSlot(slot:FastSlot, parentBoneName:string):void{ var bone:FastBone = this.getBone(parentBoneName); if(bone){ slot.armature = this; slot.setParent(bone); bone.slotList.push(slot); slot._addDisplayToContainer(this.display); this.slotList.push(slot); this._slotDic[slot.name] = slot; if(slot.hasChildArmature){ this.slotHasChildArmatureList.push(slot); } } else{ throw new Error(); } } /** * 按照显示层级为所有 Slot 排序 */ public updateSlotsZOrder():void{ this.slotList.sort(this.sortSlot); var i:number = this.slotList.length; while(i --){ var slot:FastSlot = this.slotList[i]; if ((slot._frameCache && (<SlotFrameCache><any> (slot._frameCache)).displayIndex >= 0) ||(!slot._frameCache && slot.displayIndex >= 0)) { slot._addDisplayToContainer(this._display); } } this._slotsZOrderChanged = false; } private sortBoneList():void{ var i:number = this.boneList.length; if(i == 0){ return; } var helpArray:Array<any> = []; while(i --){ var level:number = 0; var bone:FastBone = this.boneList[i]; var boneParent:FastBone = bone; while(boneParent){ level ++; boneParent = boneParent.parent; } helpArray[i] = [level, bone]; } helpArray.sort(ArmatureData.sortBoneDataHelpArrayDescending); i = helpArray.length; while(i --){ this.boneList[i] = helpArray[i][1]; } helpArray.length = 0; } /** @private When AnimationState enter a key frame, call this func*/ public arriveAtFrame(frame:Frame, animationState:FastAnimationState):void{ if(frame.event && this.hasEventListener(FrameEvent.ANIMATION_FRAME_EVENT)){ var frameEvent:FrameEvent = new FrameEvent(FrameEvent.ANIMATION_FRAME_EVENT); frameEvent.animationState = animationState; frameEvent.frameLabel = frame.event; this._addEvent(frameEvent); } if(frame.action){ this.animation.gotoAndPlay(frame.action); } } public invalidUpdate(boneName:string = null):void { if(boneName) { var bone:FastBone = this.getBone(boneName); if(bone) { bone.invalidUpdate(); } } else { var i:number = this.boneList.length; while(i --) { this.boneList[i].invalidUpdate(); } } } public resetAnimation():void{ this.animation.animationState._resetTimelineStateList(); var length:number = this.boneList.length; for(var i:number = 0;i < length;i++){ var boneItem:FastBone = this.boneList[i]; boneItem._timelineState = null; } this.animation.stop(); } private sortSlot(slot1:FastSlot, slot2:FastSlot):number{ return slot1.zOrder < slot2.zOrder?1: -1; } /** * 获取FastAnimation实例 * @returns {any} FastAnimation实例 */ public getAnimation():any { return this._animation; } /** * ArmatureData. * @see dragonBones.ArmatureData. */ public get armatureData():ArmatureData{ return this._armatureData; } /** * An Animation instance * @see dragonBones.Animation */ public get animation():FastAnimation{ return this._animation; } /** * Armature's display object. It's instance type depends on render engine. For example "flash.display.DisplayObject" or "startling.display.DisplayObject" */ public get display():any{ return this._display; } public get enableCache():boolean { return this._enableCache; } public set enableCache(value:boolean) { this._enableCache = value; } public get enableEventDispatch():boolean { return this._enableEventDispatch; } public set enableEventDispatch(value:boolean) { this._enableEventDispatch = value; } public _addEvent(event:Event):void { if (this._enableEventDispatch) { this._eventList.push(event); } } } }
the_stack
import { ExtensionContext, window, WorkspaceConfiguration, workspace, RelativePattern, Uri, commands, QuickPickItem, WorkspaceFolder } from "vscode"; import { ServerOptions, TransportKind, LanguageClientOptions, LanguageClient, Disposable } from "vscode-languageclient"; import { join, sep, basename, dirname, normalize } from "path"; import { findFiles, getDWConfig, readFile, getCartridgesFolder } from "./lib/FileHelper"; import { reduce } from "rxjs/operators"; import { promises, readFileSync } from "fs"; let isOrderedCartridgesWarnShown = false; export async function getOrderedCartridges(workspaceFolders: readonly WorkspaceFolder[]) { let cartridgesPath = workspace.getConfiguration('extension.prophet').get('cartridges.path') as string; if (!cartridgesPath || !cartridgesPath.trim()) { const dwConfig = await getDWConfig(workspaceFolders); if (dwConfig.cartridgesPath) { cartridgesPath = dwConfig.cartridgesPath; } else if (dwConfig.cartridge && dwConfig.cartridge.length) { cartridgesPath = dwConfig.cartridge.join(':'); } else { const sitesXmlFile = await Promise.all(workspaceFolders.map( workspaceFolder => findFiles(new RelativePattern(workspaceFolder, '**/site.xml'), 1).toPromise() )); const sitesXmlFileFiltered = sitesXmlFile.filter(Boolean); if (sitesXmlFileFiltered.length) { const siteBuffer = await readFile(sitesXmlFileFiltered[0].fsPath); const site = siteBuffer.toString(); const match = (/<custom-cartridges>(.*?)<\/custom-cartridges>/ig).exec(site); if (match && match[1]) { cartridgesPath = match[1]; } } } } if (cartridgesPath) { const cartridges = cartridgesPath.split(':'); const cartridgesFolders = await Promise.all(workspaceFolders.map( workspaceFolder => getCartridgesFolder(workspaceFolder) .pipe(reduce<string, string[]>((acc, r) => acc.concat(r), [] as string[])).toPromise() )); const cartridgesFoldersFlat = ([] as string[]).concat(...cartridgesFolders); return cartridges.map(cartridgeName => { return { name: cartridgeName, fsPath: cartridgesFoldersFlat.find(cartridgesFolder => basename(cartridgesFolder) === cartridgeName) }; }); } else if (!isOrderedCartridgesWarnShown) { isOrderedCartridgesWarnShown = true; window.showInformationMessage('Cartridges path is not detected automatically, related features will be disabled. Consider specifying in your dw.json as \'cartridgesPath\' property, please.'); } } /** * Create the Script language server with the proper parameters * * @param context the extension context * @param configuration the extension configuration */ export async function createScriptLanguageServer(context: ExtensionContext, configuration: WorkspaceConfiguration = workspace.getConfiguration('extension.prophet', null)) { // The server is implemented in node const serverModule = context.asAbsolutePath(join('dist', 'scriptServer.js')); // The debug options for the server const debugOptions = { execArgv: ['--nolazy', '--inspect=6040'] }; const disposes : Disposable[] = []; // If the extension is launched in debug mode then the debug server options are used // Otherwise the run options are used const serverOptions: ServerOptions = { run: { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions } }; // Options to control the language client const clientOptions: LanguageClientOptions = { diagnosticCollectionName: 'prophet', // Register the server for plain text documents documentSelector: [{ scheme: 'file', pattern: '**/cartridge/{scripts,controllers,models}/**/*.js' }, { scheme: 'file', pattern: '**/cartridge/templates/default/**/*.isml' }], initializationOptions: { disableDiagnostics: configuration.get('script.server.disable.diagnostics', false) }, synchronize: { // Synchronize the setting section 'languageServerExample' to the server configurationSection: 'extension.prophet.script.server', // Notify the server about file changes to '.clientrc files contain in the workspace // fileEvents: workspace.createFileSystemWatcher('**/*.isml'), //fileEvents: workspace.createFileSystemWatcher('**/.htmlhintrc'), } }; disposes.push(commands.registerCommand('extension.prophet.command.override.script', async (fileURI?: Uri) => { if (workspace.workspaceFolders && fileURI && fileURI.scheme === 'file') { const cartridges = await getOrderedCartridges(workspace.workspaceFolders); if (cartridges && cartridges.length > 1) { const fileSep = '/cartridge/'.split('/').join(sep); const [, filePath] = fileURI.fsPath.split(fileSep); const selected = await window.showQuickPick(cartridges.map(cartridge => cartridge.name)); if (selected) { const selectedCartridge = cartridges.find(cartridge => cartridge.name === selected); if (selectedCartridge && selectedCartridge.fsPath) { const newDestPath = join(selectedCartridge.fsPath, 'cartridge', filePath); await promises.mkdir(dirname(newDestPath), { recursive: true }); try { await promises.access(newDestPath); await commands.executeCommand('vscode.open', Uri.parse(newDestPath)); } catch (e) { const fileContent = await promises.readFile(fileURI.fsPath); if (fileContent.includes('server.exports')) { await promises.writeFile(newDestPath, `var server = require('server'); server.extend(module.superModule); module.exports = server.exports(); `); await commands.executeCommand('vscode.open', Uri.file(newDestPath).with({ fragment: 'L4' })); } else { await promises.writeFile(newDestPath, `var base = module.superModule; module.exports = base; `); await commands.executeCommand('vscode.open', Uri.file(newDestPath).with({ fragment: 'L3' })); } } } } } } })); if (workspace.workspaceFolders) { const orderedCartridges = (await getOrderedCartridges(workspace.workspaceFolders))?.filter(cartridge => cartridge.fsPath); if (orderedCartridges && orderedCartridges.length) { // Create the language client and start the client. const scriptLanguageClient = new LanguageClient('dwScriptLanguageServer', 'Script Language Server', serverOptions, clientOptions); scriptLanguageClient.info('Client created'); scriptLanguageClient.info('Actual cartridges: ' + JSON.stringify(orderedCartridges)); //context.subscriptions.push(new SettingMonitor(ismlLanguageClient, 'extension.prophet.htmlhint.enabled').start()); scriptLanguageClient.onReady().then(async () => { scriptLanguageClient.info('Server Ready'); const orderedCartridgesWithFiles = await Promise.all(orderedCartridges.map(async cartridge => { if (cartridge.fsPath) { const files = await workspace.findFiles( new RelativePattern(cartridge.fsPath, '**/*.{js,json}'), new RelativePattern(cartridge.fsPath, '**/{controllers,node_modules,client,js,default,static}/**/*.{js,json}') ); const filesToSend = files.map(file => ({ path: file.fsPath.replace(cartridge.fsPath || '', '').split(sep).join('/'), fsPath: Uri.file(file.fsPath).toString() })) files.forEach(file => { const fileName = basename(file.fsPath); if (fileName === 'main.js') { filesToSend.push({ path: dirname(file.fsPath).replace(cartridge.fsPath || '', '').split(sep).join('/'), fsPath: Uri.file(file.fsPath).toString() }); } else if (fileName === 'package.json') { try { const fileContent = readFileSync(file.fsPath); const packageJsonContent = JSON.parse(fileContent.toString()); const main = packageJsonContent.main as string; if (main && typeof main === 'string') { const mainPath = main.split('/').join(sep); const dir = dirname(file.fsPath); const normalizedFullPath = normalize(join(dir, mainPath)); const fullPath = normalizedFullPath.endsWith('.js') ? normalizedFullPath : normalizedFullPath + '.js'; filesToSend.push({ path: dir.replace(cartridge.fsPath || '', '').split(sep).join('/'), fsPath: Uri.file(fullPath).toString() }); scriptLanguageClient.info(normalizedFullPath); } } catch (e) { scriptLanguageClient.warn('package.json error: ' + e.message); } } }); return { name: cartridge.name, fsPath: Uri.file(cartridge.fsPath).toString(), files: filesToSend.filter(file => { return !file.fsPath.endsWith('package.json') && !basename(file.fsPath).startsWith('.'); }) }; } })); scriptLanguageClient.info('Files list =>'); const orderedCartridgesWithFilesFiltered = orderedCartridgesWithFiles.filter(Boolean); if (orderedCartridgesWithFilesFiltered.length) { scriptLanguageClient.sendNotification('cartridges.files', { list: orderedCartridgesWithFilesFiltered }); } const orderedCartridgesWithTemplates = await Promise.all(orderedCartridges.map(async cartridge => { if (cartridge.fsPath) { const files = await findFiles(new RelativePattern(cartridge.fsPath, 'cartridge/templates/default/**/*.isml')) .pipe(reduce((acc, val) => { return acc.concat(val); }, [] as Uri[])).toPromise(); if (files.length) { return { name: cartridge.name, fsPath: Uri.file(cartridge.fsPath).toString(), files: files.map(file => ({ path: file.fsPath.split(sep).join('/').split('/cartridge/templates/default/').pop()?.replace('.isml', ''), fsPath: Uri.file(file.fsPath).toString() })) }; } } })); scriptLanguageClient.info('Templates list =>'); const orderedCartridgesWithTemplatesFiltered = orderedCartridgesWithTemplates.filter(Boolean); if (orderedCartridgesWithTemplatesFiltered.length) { scriptLanguageClient.sendNotification('cartridges.templates', { list: orderedCartridgesWithTemplatesFiltered }); } const orderedCartridgesWithControllers = await Promise.all(orderedCartridges.map(async cartridge => { if (cartridge.fsPath) { const files = await findFiles(new RelativePattern(cartridge.fsPath, 'cartridge/controllers/*.js')) .pipe(reduce((acc, val) => { return acc.concat(val); }, [] as Uri[])).toPromise(); if (files.length) { return { name: cartridge.name, fsPath: Uri.file(cartridge.fsPath).toString(), files: files.map(file => ({ path: file.fsPath.split(sep).join('/').split('/cartridge/').pop()?.replace('.isml', ''), fsPath: Uri.file(file.fsPath).toString() })) }; } } })); scriptLanguageClient.info('Controllers list =>'); const orderedCartridgesWithControllersFiltered = orderedCartridgesWithControllers.filter(Boolean); if (orderedCartridgesWithControllersFiltered.length) { scriptLanguageClient.sendNotification('cartridges.controllers', { list: orderedCartridgesWithControllersFiltered }); } disposes.push(commands.registerCommand('extension.prophet.command.controllers.find', async () => { scriptLanguageClient.sendNotification('get.controllers.list'); })); scriptLanguageClient.onNotification('get.controllers.list.result', ({ endpoints }) => { interface QuickPickTargetedItem extends QuickPickItem { target: any } const quickPickItems: QuickPickTargetedItem[] = (endpoints || []).map(endpoint => { return { label: endpoint.name, description: endpoint.mode + ' - ' + endpoint.cartridgeName, target: endpoint } }); window.showQuickPick(quickPickItems).then(selected => { if (selected) { commands.executeCommand( 'vscode.open', Uri.parse(selected.target.fsPath).with({ fragment: selected.target.startPosition.line + 1 }) ); } }); }); orderedCartridges.forEach(cartridge => { if (cartridge.fsPath) { const watcher = workspace.createFileSystemWatcher( new RelativePattern(cartridge.fsPath, 'cartridge/controllers/*.js')); disposes.push(watcher); ['Change', 'Create', 'Delete'].forEach(action => { disposes.push(watcher['onDid' + action](uri => { if (uri.scheme === 'file') { scriptLanguageClient.sendNotification('cartridges.controllers.modification', { action, cartridge: cartridge, uri: uri.toString() }); } })); }); } }); const orderedCartridgesWithProperties = await Promise.all(orderedCartridges.map(async cartridge => { if (cartridge.fsPath) { const files = await findFiles(new RelativePattern(cartridge.fsPath, 'cartridge/templates/resources/*.properties')) .pipe(reduce((acc, val) => { return acc.concat(val); }, [] as Uri[])).toPromise(); if (files.length) { return { name: cartridge.name, fsPath: Uri.file(cartridge.fsPath).toString(), files: files.map(file => ({ name: file.fsPath.split(sep).join('/').split('/cartridge/templates/resources/').pop()?.replace('.properties', ''), fsPath: Uri.file(file.fsPath).toString() })) }; } } })); scriptLanguageClient.info('Properties list =>'); const orderedCartridgesWithPropertiesFiltered = orderedCartridgesWithProperties.filter(Boolean); if (orderedCartridgesWithPropertiesFiltered.length) { scriptLanguageClient.sendNotification('cartridges.properties', { list: orderedCartridgesWithPropertiesFiltered }); } orderedCartridges.forEach(cartridge => { if (cartridge.fsPath) { const watcher = workspace.createFileSystemWatcher( new RelativePattern(cartridge.fsPath, 'cartridge/templates/resources/*.properties')); disposes.push(watcher); ['Change', 'Create', 'Delete'].forEach(action => { disposes.push(watcher['onDid' + action](uri => { if (uri.scheme === 'file') { scriptLanguageClient.sendNotification('cartridges.properties.modification', { action, template: uri.fsPath.split(sep).join('/').split('/cartridge/templates/resources/').pop()?.replace('.properties', ''), cartridge: cartridge, uri: uri.toString() }); } })); }); } }); scriptLanguageClient.info('Configuration done'); }).catch(err => { window.showErrorMessage(JSON.stringify(err)); scriptLanguageClient.error('init error:' + JSON.stringify(err)); return Promise.reject(err); }); return { start() { scriptLanguageClient.info('Starting client...'); const clientDispose = scriptLanguageClient.start(); return Disposable.create(() => { disposes.forEach(d => d.dispose()); clientDispose.dispose(); }); } } } else if (!isOrderedCartridgesWarnShown) { isOrderedCartridgesWarnShown = true; window.showInformationMessage('Prophet: Cartridges not detected, related features will be disabled. Consider specifying cartridge path (copy-paste from BM) in your dw.json as \'cartridgesPath\' property, please.'); } } }
the_stack
import { mount, VueWrapper } from '@vue/test-utils'; import { ComponentPublicInstance, ref } from 'vue'; import DSplitter from '../src/splitter'; import DSplitterPane from '../src/components/splitter-pane'; // 因为 jest 不支持 ResizeObserver,需要 mock 实现 window.ResizeObserver = window.ResizeObserver || jest.fn().mockImplementation(() => ({ disconnect: jest.fn(), observe: jest.fn(), unobserve: jest.fn(), })); describe('splitter', () => { describe('basic', () => { const testComponent = { components: { DSplitter, DSplitterPane, }, template: ` <d-splitter :orientation="orientation" :splitBarSize="splitBarSize" style="height: 500px; border: 1px solid #E3E5E9;"> <template v-slot:DSplitterPane> <d-splitter-pane :size="size" :minSize="minSize" :maxSize="maxSize" :collapsible="collapsible" :collapsed="collapsed" @sizeChange="sizeChange" > <div class="pane-content"> <h2>左侧面板</h2> <div>左侧内容区域,宽度 30%,最小宽度 20%</div> </div> </d-splitter-pane> <d-splitter-pane size="50px"> <div class="pane-content"> <h2>中间面板</h2> <div>中间内容区域</div> </div> </d-splitter-pane> <d-splitter-pane> <div class="pane-content"> <h2>右侧面板</h2> <div>右侧内容区域</div> </div> </d-splitter-pane> </template> </d-splitter> `, setup() { const orientation = ref('horizontal'); const collapsible = ref(true); const collapsed = ref(false); const splitBarSize = ref('2px'); const size = ref('30%'); const minSize = ref('20%'); const maxSize = ref('60%'); const sizeChange = (paneSize: number) => { console.log(paneSize); }; return { orientation, collapsible, collapsed, splitBarSize, size, minSize, maxSize, sizeChange, }; }, }; let wrapper: VueWrapper<ComponentPublicInstance>; let splitterElement: HTMLElement; beforeEach(() => { wrapper = mount(testComponent); splitterElement = wrapper.vm.$el; }); it('should create testComponent', () => { expect(wrapper.vm).toBeTruthy(); }); it('should create splitter container', () => { expect(splitterElement).toBeTruthy(); expect(wrapper.classes()).toContain('devui-splitter-horizontal'); }); it('should render splitter-bar', () => { const handles = wrapper.findAll('.devui-splitter-bar'); expect(handles.length).toBe(2); }); it('should collapse left pane when collapseButton clicked', async () => { const handleButton = wrapper.find('.prev.devui-collapse'); handleButton.trigger('click'); await wrapper.vm.$nextTick(); const pane = wrapper.find('.devui-splitter-pane').element; // jsdom 不支持 clientWidth 属性,需要 mock Object.defineProperty(pane, 'clientWidth', { get: jest.fn().mockImplementation(() => 0), set: jest.fn().mockImplementation(() => ({})), }); expect(pane.clientWidth).toBe(0); }); it('should add collapsed class when collapseButton clicked', async () => { const handleButton = wrapper.find('.prev.devui-collapse'); handleButton.trigger('click'); await wrapper.vm.$nextTick(); expect(handleButton.classes()).toContain('collapsed'); }); it('should change collapse state', () => { wrapper = mount( Object.assign(testComponent, { setup() { const orientation = ref('horizontal'); const collapsible = ref(false); const collapsed = ref(false); const splitBarSize = ref('2px'); const size = ref('30%'); const minSize = ref('20%'); const maxSize = ref('60%'); const sizeChange = (paneSize: number) => { console.log(paneSize); }; return { orientation, collapsible, collapsed, splitBarSize, size, minSize, maxSize, sizeChange, }; }, }) ); expect(wrapper.find('.prev').classes()).not.toContain('devui-collapse'); }); it('should be collapsed', () => { wrapper = mount( Object.assign(testComponent, { setup() { const orientation = ref('horizontal'); const collapsible = ref(true); const collapsed = ref(true); const splitBarSize = ref('2px'); const size = ref('30%'); const minSize = ref('20%'); const maxSize = ref('60%'); const sizeChange = (paneSize: number) => { console.log(paneSize); }; return { orientation, collapsible, collapsed, splitBarSize, size, minSize, maxSize, sizeChange, }; }, }) ); expect(wrapper.find('.prev.devui-collapse').classes()).toContain( 'collapsed' ); }); it('should change splitterBar size', async () => { const element = wrapper.find('.devui-splitter-bar').element; // jsdom 不支持 clientWidth 属性,需要 mock Object.defineProperty(element, 'clientWidth', { get: jest.fn().mockImplementation(() => 2), set: jest.fn().mockImplementation(() => ({})), }); expect(wrapper.find('.devui-splitter-bar').element.clientWidth).toBe(2); }); it('should change splitter direction', () => { wrapper = mount( Object.assign(testComponent, { setup() { const orientation = ref('vertical'); const collapsible = ref(true); const collapsed = ref(true); const splitBarSize = ref('2px'); const size = ref('30%'); const minSize = ref('20%'); const maxSize = ref('60%'); const sizeChange = (paneSize: number) => { console.log(paneSize); }; return { orientation, collapsible, collapsed, splitBarSize, size, minSize, maxSize, sizeChange, }; }, }) ); expect(wrapper.classes()).toContain('devui-splitter-vertical'); }); it('should change pane size', async () => { wrapper = mount( Object.assign(testComponent, { setup() { const orientation = ref('vertical'); const collapsible = ref(true); const collapsed = ref(true); const splitBarSize = ref('2px'); const size = ref('40%'); const minSize = ref('20%'); const maxSize = ref('60%'); const sizeChange = (paneSize: number) => { console.log(paneSize); }; return { orientation, collapsible, collapsed, splitBarSize, size, minSize, maxSize, sizeChange, }; }, }) ); await wrapper.vm.$nextTick(); const computedStyle = getComputedStyle( wrapper.find('.devui-splitter-pane').element ); expect(computedStyle.flexBasis).toContain('40%'); }); it('should change pane size', () => { wrapper = mount( Object.assign(testComponent, { setup() { const orientation = ref('vertical'); const collapsible = ref(true); const collapsed = ref(true); const splitBarSize = ref('2px'); const size = ref(undefined); const minSize = ref('20%'); const maxSize = ref('60%'); const sizeChange = (paneSize: number) => { console.log(paneSize); }; return { orientation, collapsible, collapsed, splitBarSize, size, minSize, maxSize, sizeChange, }; }, }) ); expect(wrapper.find('.devui-splitter-pane').classes()).not.toContain( 'devui-splitter-pane-fixed' ); }); }); describe('vertical', () => { const testComponent = { components: { DSplitter, DSplitterPane, }, template: ` <d-splitter :orientation="orientation" style="height: 500px; border: 1px solid #E3E5E9;"> <d-splitter-pane> <div class="pane-content"> <h2>上面板</h2> <div>内容区域</div> </div> </d-splitter-pane> <d-splitter-pane :size="size" :minSize="minSize" :maxSize="maxSize"> <div class="pane-content"> <h2>下面板</h2> <div>内容区域</div> </div> </d-splitter-pane> <d-splitter-pane [size]="'100px'" [resizable]="false"> <div class="pane-content"> <h2>下面板</h2> <div>内容区域</div> </div> </d-splitter-pane> </d-splitter> `, setup() { const orientation = ref('vertical'); const size = ref('100px'); const minSize = ref('50px'); const maxSize = ref('200px'); return { orientation, size, minSize, maxSize, }; }, }; let wrapper: VueWrapper<ComponentPublicInstance>; beforeEach(() => { wrapper = mount(testComponent); }); it('should create vertical container', () => { expect(wrapper.vm.$el).toBeTruthy(); expect(wrapper.classes()).toContain('devui-splitter-vertical'); }); }); });
the_stack
import {supportsCssVariables} from '../../mdc-ripple/util'; import {emitEvent} from '../../../testing/dom/events'; import {createMockFoundation} from '../../../testing/helpers/foundation'; import {setUpMdcTestEnvironment} from '../../../testing/helpers/setup'; import {strings, numbers} from '../constants'; import {MDCDialog, MDCDialogFoundation, util} from '../index'; function getFixture() { const wrapper = document.createElement('div'); wrapper.innerHTML = ` <div> <button class="open-dialog-button">click</button> <div id="test-dialog" class="mdc-dialog" role="alertdialog" aria-labelledby="test-dialog-label" aria-describedby="test-dialog-description"> <div class="mdc-dialog__container"> <div class="mdc-dialog__surface"> <h2 class="mdc-dialog__title"> Use Google's location service? </h2> <section class="mdc-dialog__content"> Let Google help apps determine location. </section> <div class="mdc-dialog__actions"> <button class="mdc-button mdc-dialog__button" data-mdc-dialog-action="cancel" type="button"> <span class="mdc-button__label">Cancel</span> </button> <button class="mdc-button mdc-dialog__button" data-mdc-dialog-action="no" type="button"> <span class="mdc-button__label">No</span> </button> <button class="mdc-button mdc-dialog__button" data-mdc-dialog-action="yes" type="button" ${strings.INITIAL_FOCUS_ATTRIBUTE}> <span class="mdc-button__label">Yes</span> </button> </div> </div> </div> <div class="mdc-dialog__scrim"></div> </div> </div>`; const el = wrapper.firstElementChild as HTMLElement; wrapper.removeChild(el); return el; } function setupTest(fixture = getFixture()) { const root = fixture.querySelector('.mdc-dialog') as HTMLElement; const component = new MDCDialog(root); const title = fixture.querySelector('.mdc-dialog__title') as HTMLElement; const content = fixture.querySelector('.mdc-dialog__content') as HTMLElement; const actions = fixture.querySelector('.mdc-dialog__actions') as HTMLElement; const yesButton = fixture.querySelector('[data-mdc-dialog-action="yes"]') as HTMLElement; const noButton = fixture.querySelector('[data-mdc-dialog-action="no"]') as HTMLElement; const cancelButton = fixture.querySelector('[data-mdc-dialog-action="cancel"]') as HTMLElement; return { root, component, title, content, actions, yesButton, noButton, cancelButton }; } function setupTestWithMocks() { const root = getFixture(); const mockFoundation = createMockFoundation(MDCDialogFoundation); const mockFocusTrapInstance = jasmine.createSpyObj('focusTrap', ['trapFocus', 'releaseFocus']); const component = new MDCDialog(root, mockFoundation, () => mockFocusTrapInstance); return {root, component, mockFoundation, mockFocusTrapInstance}; } describe('MDCDialog', () => { setUpMdcTestEnvironment(); it('attachTo returns a component instance', () => { expect(MDCDialog.attachTo( getFixture().querySelector('.mdc-dialog') as HTMLElement)) .toEqual(jasmine.any(MDCDialog)); }); it('attachTo throws an error when container element is missing', () => { const fixture = getFixture(); const container = fixture.querySelector('.mdc-dialog__container') as HTMLElement; container.parentElement!.removeChild(container); expect( () => MDCDialog.attachTo( fixture.querySelector('.mdc-dialog') as HTMLElement)) .toThrow(); }); it('#initialSyncWithDOM registers click handler on the root element', () => { const {root, component, mockFoundation} = setupTestWithMocks(); emitEvent(root, 'click'); expect(mockFoundation.handleClick).toHaveBeenCalledWith(jasmine.any(Event)); expect(mockFoundation.handleClick).toHaveBeenCalledTimes(1); component.destroy(); }); it('#initialSyncWithDOM registers keydown handler on the root element', () => { const {root, component, mockFoundation} = setupTestWithMocks(); emitEvent(root, 'keydown'); expect(mockFoundation.handleKeydown) .toHaveBeenCalledWith(jasmine.any(Event)); expect(mockFoundation.handleKeydown).toHaveBeenCalledTimes(1); component.destroy(); }); it('#destroy deregisters click handler on the root element', () => { const {root, component, mockFoundation} = setupTestWithMocks(); component.destroy(); emitEvent(root, 'click'); expect(mockFoundation.handleClick) .not.toHaveBeenCalledWith(jasmine.any(Event)); }); it('#destroy deregisters keydown handler on the root element', () => { const {root, component, mockFoundation} = setupTestWithMocks(); component.destroy(); emitEvent(root, 'keydown'); expect(mockFoundation.handleKeydown) .not.toHaveBeenCalledWith(jasmine.any(Event)); }); it(`${strings.OPENING_EVENT} registers document keydown handler and ${ strings.CLOSING_EVENT} deregisters it`, () => { const {root, mockFoundation} = setupTestWithMocks(); emitEvent(root, strings.OPENING_EVENT); emitEvent(document, 'keydown'); expect(mockFoundation.handleDocumentKeydown) .toHaveBeenCalledWith(jasmine.any(Event)); expect(mockFoundation.handleDocumentKeydown).toHaveBeenCalledTimes(1); emitEvent(root, strings.CLOSING_EVENT); emitEvent(document, 'keydown'); expect(mockFoundation.handleDocumentKeydown) .toHaveBeenCalledWith(jasmine.any(Event)); expect(mockFoundation.handleDocumentKeydown).toHaveBeenCalledTimes(1); }); it('#initialize attaches ripple elements to all footer buttons', function() { if (!supportsCssVariables(window, true)) { return; } const {yesButton, noButton, cancelButton} = setupTest(); jasmine.clock().tick(1); expect(yesButton.classList.contains('mdc-ripple-upgraded')).toBe(true); expect(noButton.classList.contains('mdc-ripple-upgraded')).toBe(true); expect(cancelButton.classList.contains('mdc-ripple-upgraded')).toBe(true); }); it('#destroy cleans up all ripples on footer buttons', function() { if (!supportsCssVariables(window, true)) { return; } const {component, yesButton, noButton, cancelButton} = setupTest(); jasmine.clock().tick(1); component.destroy(); jasmine.clock().tick(1); expect(yesButton.classList.contains('mdc-ripple-upgraded')).toBe(false); expect(noButton.classList.contains('mdc-ripple-upgraded')).toBe(false); expect(cancelButton.classList.contains('mdc-ripple-upgraded')).toBe(false); }); it('#open forwards to MDCDialogFoundation#open', () => { const {component, mockFoundation} = setupTestWithMocks(); component.open(); expect(mockFoundation.open).toHaveBeenCalled(); }); it('#close forwards to MDCDialogFoundation#close', () => { const {component, mockFoundation} = setupTestWithMocks(); const action = 'action'; component.close(action); expect(mockFoundation.close).toHaveBeenCalledWith(action); component.close(); expect(mockFoundation.close).toHaveBeenCalledWith(''); }); it('get isOpen forwards to MDCDialogFoundation#isOpen', () => { const {component, mockFoundation} = setupTestWithMocks(); component.isOpen; expect(mockFoundation.isOpen).toHaveBeenCalled(); }); it('get escapeKeyAction forwards to MDCDialogFoundation#getEscapeKeyAction', () => { const {component, mockFoundation} = setupTestWithMocks(); component.escapeKeyAction; expect(mockFoundation.getEscapeKeyAction).toHaveBeenCalled(); }); it('set escapeKeyAction forwards to MDCDialogFoundation#setEscapeKeyAction', () => { const {component, mockFoundation} = setupTestWithMocks(); component.escapeKeyAction = 'action'; expect(mockFoundation.setEscapeKeyAction).toHaveBeenCalledWith('action'); }); it('get scrimClickAction forwards to MDCDialogFoundation#getScrimClickAction', () => { const {component, mockFoundation} = setupTestWithMocks(); component.scrimClickAction; expect(mockFoundation.getScrimClickAction).toHaveBeenCalled(); }); it('set scrimClickAction forwards to MDCDialogFoundation#setScrimClickAction', () => { const {component, mockFoundation} = setupTestWithMocks(); component.scrimClickAction = 'action'; expect(mockFoundation.setScrimClickAction) .toHaveBeenCalledWith('action'); }); it('get autoStackButtons forwards to MDCDialogFoundation#getAutoStackButtons', () => { const {component, mockFoundation} = setupTestWithMocks(); component.autoStackButtons; expect(mockFoundation.getAutoStackButtons).toHaveBeenCalled(); }); it('set autoStackButtons forwards to MDCDialogFoundation#setAutoStackButtons', () => { const {component, mockFoundation} = setupTestWithMocks(); component.autoStackButtons = false; expect(mockFoundation.setAutoStackButtons).toHaveBeenCalledWith(false); }); it('autoStackButtons adds scrollable class', () => { const fixture = getFixture(); const root = fixture.querySelector('.mdc-dialog') as HTMLElement; const content = root.querySelector('.mdc-dialog__content') as HTMLElement; // Simulate a scrollable content area content.innerHTML = new Array(100).join(`<p>${content.textContent}</p>`); content.style.height = '50px'; content.style.overflow = 'auto'; document.body.appendChild(fixture); try { const component = new MDCDialog(root); component.autoStackButtons = false; component.open(); jasmine.clock().tick(1); jasmine.clock().tick(1); expect(root.classList.contains('mdc-dialog--scrollable')).toBe(true); } finally { document.body.removeChild(fixture); } }); it('adapter#addClass adds a class to the root element', () => { const {root, component} = setupTest(); (component.getDefaultFoundation() as any).adapter.addClass('foo'); expect(root.classList.contains('foo')).toBe(true); }); it('adapter#removeClass removes a class from the root element', () => { const {root, component} = setupTest(); root.classList.add('foo'); (component.getDefaultFoundation() as any).adapter.removeClass('foo'); expect(root.classList.contains('foo')).toBe(false); }); it('adapter#hasClass returns whether a class exists on the root element', () => { const {root, component} = setupTest(); root.classList.add('foo'); expect( (component.getDefaultFoundation() as any).adapter.hasClass('foo')) .toBe(true); expect((component.getDefaultFoundation() as any) .adapter.hasClass('does-not-exist')) .toBe(false); }); it('adapter#addBodyClass adds a class to the body', () => { const {component} = setupTest(); (component.getDefaultFoundation() as any) .adapter.addBodyClass('mdc-dialog--scroll-lock'); expect((document.querySelector('body') as HTMLElement) .classList.contains('mdc-dialog--scroll-lock')) .toBe(true); }); it('adapter#removeBodyClass removes a class from the body', () => { const {component} = setupTest(); const body = document.querySelector('body') as HTMLElement; body.classList.add('mdc-dialog--scroll-lock'); (component.getDefaultFoundation() as any) .adapter.removeBodyClass('mdc-dialog--scroll-lock'); expect(body.classList.contains('mdc-dialog--scroll-lock')).toBe(false); }); it('adapter#eventTargetMatches returns whether or not the target matches the selector', () => { const {component} = setupTest(); const target = document.createElement('div'); target.classList.add('existent-class'); const {adapter: adapter} = component.getDefaultFoundation() as any; expect(adapter.eventTargetMatches(target, '.existent-class')).toBe(true); expect(adapter.eventTargetMatches(target, '.non-existent-class')) .toBe(false); expect(adapter.eventTargetMatches(null, '.existent-class')).toBe(false); }); it(`adapter#notifyOpening emits ${strings.OPENING_EVENT}`, () => { const {component} = setupTest(); const handler = jasmine.createSpy('notifyOpeningHandler'); component.listen(strings.OPENING_EVENT, handler); (component.getDefaultFoundation() as any).adapter.notifyOpening(); component.unlisten(strings.OPENING_EVENT, handler); expect(handler).toHaveBeenCalledWith(jasmine.anything()); }); it(`adapter#notifyOpened emits ${strings.OPENED_EVENT}`, () => { const {component} = setupTest(); const handler = jasmine.createSpy('notifyOpenedHandler'); component.listen(strings.OPENED_EVENT, handler); (component.getDefaultFoundation() as any).adapter.notifyOpened(); component.unlisten(strings.OPENED_EVENT, handler); expect(handler).toHaveBeenCalledWith(jasmine.anything()); }); it(`adapter#notifyClosing emits ${ strings .CLOSING_EVENT} without action if passed action is empty string`, () => { const {component} = setupTest(); const handler = jasmine.createSpy('notifyClosingHandler'); component.listen(strings.CLOSING_EVENT, handler); (component.getDefaultFoundation() as any).adapter.notifyClosing(''); component.unlisten(strings.CLOSING_EVENT, handler); expect(handler).toHaveBeenCalledWith( jasmine.objectContaining({detail: {}})); }); it(`adapter#notifyClosing emits ${strings.CLOSING_EVENT} with action`, () => { const {component} = setupTest(); const action = 'action'; const handler = jasmine.createSpy('notifyClosingHandler'); component.listen(strings.CLOSING_EVENT, handler); (component.getDefaultFoundation() as any).adapter.notifyClosing(action); component.unlisten(strings.CLOSING_EVENT, handler); expect(handler).toHaveBeenCalledWith( jasmine.objectContaining({detail: {action}})); }); it(`adapter#notifyClosed emits ${ strings.CLOSED_EVENT} without action if passed action is empty string`, () => { const {component} = setupTest(); const handler = jasmine.createSpy('notifyClosedHandler'); component.listen(strings.CLOSED_EVENT, handler); (component.getDefaultFoundation() as any).adapter.notifyClosed(''); component.unlisten(strings.CLOSED_EVENT, handler); expect(handler).toHaveBeenCalledWith( jasmine.objectContaining({detail: {}})); }); it(`adapter#notifyClosed emits ${strings.CLOSED_EVENT} with action`, () => { const {component} = setupTest(); const action = 'action'; const handler = jasmine.createSpy('notifyClosedHandler'); component.listen(strings.CLOSED_EVENT, handler); (component.getDefaultFoundation() as any).adapter.notifyClosed(action); component.unlisten(strings.CLOSED_EVENT, handler); expect(handler).toHaveBeenCalledWith( jasmine.objectContaining({detail: {action}})); }); it('adapter#trapFocus calls trapFocus() on a properly configured focus trap instance', () => { const {component, mockFocusTrapInstance} = setupTestWithMocks(); component.initialize(); (component.getDefaultFoundation() as any).adapter.trapFocus(); expect(mockFocusTrapInstance.trapFocus).toHaveBeenCalled(); }); it('adapter#releaseFocus calls releaseFocus() on a properly configured focus trap instance', () => { const {component, mockFocusTrapInstance} = setupTestWithMocks(); component.initialize(); (component.getDefaultFoundation() as any).adapter.releaseFocus(); expect(mockFocusTrapInstance.releaseFocus).toHaveBeenCalled(); }); it('adapter#isContentScrollable returns false when there is no content element', () => { const {component, content} = setupTest(); content.parentElement!.removeChild(content); const isContentScrollable = (component.getDefaultFoundation() as any) .adapter.isContentScrollable(); expect(isContentScrollable).toBe(false); }); it('adapter#isContentScrollable returns result of util.isScrollable', () => { const {component, content} = setupTest(); expect((component.getDefaultFoundation() as any) .adapter.isContentScrollable()) .toBe(util.isScrollable(content)); }); it('adapter#areButtonsStacked returns result of util.areTopsMisaligned', () => { const {component, yesButton, noButton, cancelButton} = setupTest(); expect((component.getDefaultFoundation() as any) .adapter.areButtonsStacked()) .toBe(util.areTopsMisaligned([yesButton, noButton, cancelButton])); }); it('adapter#getActionFromEvent returns an empty string when no event target is present', () => { const {component} = setupTest(); const action = (component.getDefaultFoundation() as any) .adapter.getActionFromEvent({}); expect(action).toEqual(''); }); it('adapter#getActionFromEvent returns attribute value on event target', () => { const {component, yesButton} = setupTest(); const action = (component.getDefaultFoundation() as any) .adapter.getActionFromEvent({target: yesButton}); expect(action).toEqual('yes'); }); it('adapter#getActionFromEvent returns attribute value on parent of event target', () => { const {component, yesButton} = setupTest(); const childEl = document.createElement('span'); yesButton.appendChild(childEl); const action = (component.getDefaultFoundation() as any) .adapter.getActionFromEvent({target: childEl}); expect(action).toEqual('yes'); }); it('adapter#getActionFromEvent returns null when attribute is not present', () => { const {component, title} = setupTest(); const action = (component.getDefaultFoundation() as any) .adapter.getActionFromEvent({target: title}); expect(action).toBe(null); }); it(`adapter#clickDefaultButton invokes click() on button matching ${ strings.BUTTON_DEFAULT_ATTRIBUTE}`, () => { const fixture = getFixture(); const yesButton = fixture.querySelector( '[data-mdc-dialog-action="yes"]') as HTMLElement; yesButton.setAttribute(strings.BUTTON_DEFAULT_ATTRIBUTE, 'true'); const {component} = setupTest(fixture); yesButton.click = jasmine.createSpy('click'); (component.getDefaultFoundation() as any).adapter.clickDefaultButton(); expect(yesButton.click).toHaveBeenCalled(); }); it(`adapter#clickDefaultButton does nothing if nothing matches ${ strings.BUTTON_DEFAULT_ATTRIBUTE}`, () => { const {component, yesButton, noButton} = setupTest(); yesButton.click = jasmine.createSpy('click'); noButton.click = jasmine.createSpy('click'); expect( () => (component.getDefaultFoundation() as any) .adapter.clickDefaultButton) .not.toThrow(); expect(yesButton.click).not.toHaveBeenCalled(); expect(noButton.click).not.toHaveBeenCalled(); }); it('adapter#reverseButtons reverses the order of children under the actions element', () => { const {component, actions, yesButton, noButton, cancelButton} = setupTest(); (component.getDefaultFoundation() as any).adapter.reverseButtons(); expect([ yesButton, noButton, cancelButton ]).toEqual([].slice.call(actions.children)); }); it('#layout proxies to foundation', () => { const {component} = setupTest(); (component as any).foundation.layout = jasmine.createSpy('component.foundation.layout'); component.layout(); expect((component as any).foundation.layout).toHaveBeenCalled(); }); it(`Button with ${strings.INITIAL_FOCUS_ATTRIBUTE} will be focused when the dialog is opened, with multiple initial focus buttons in DOM`, () => { const {root: root1, component: component1, yesButton: yesButton1} = setupTest(); const {root: root2, component: component2, yesButton: yesButton2} = setupTest(); expect(yesButton1.hasAttribute(strings.INITIAL_FOCUS_ATTRIBUTE)).toBe(true); expect(yesButton2.hasAttribute(strings.INITIAL_FOCUS_ATTRIBUTE)).toBe(true); try { document.body.appendChild(root1) document.body.appendChild(root2) component1.open() jasmine.clock().tick(numbers.DIALOG_ANIMATION_OPEN_TIME_MS + 10); expect(document.activeElement).toEqual(yesButton1); component1.close() jasmine.clock().tick(numbers.DIALOG_ANIMATION_CLOSE_TIME_MS); component2.open() jasmine.clock().tick(numbers.DIALOG_ANIMATION_OPEN_TIME_MS + 10); expect(document.activeElement).toEqual(yesButton2); component2.close() jasmine.clock().tick(numbers.DIALOG_ANIMATION_CLOSE_TIME_MS); } finally { document.body.removeChild(root1) document.body.removeChild(root2) } }); });
the_stack
import { EventEmitter } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { QuestionSummary } from 'domain/question/question-summary-object.model'; import { QuestionObjectFactory } from 'domain/question/QuestionObjectFactory'; import { MisconceptionObjectFactory } from 'domain/skill/MisconceptionObjectFactory'; import { ShortSkillSummary } from 'domain/skill/short-skill-summary.model'; import { SkillDifficulty } from 'domain/skill/skill-difficulty.model'; import { SkillObjectFactory } from 'domain/skill/SkillObjectFactory'; import { importAllAngularServices } from 'tests/unit-test-utils.ajs'; /** * @fileoverview Unit test for Questions List Component. */ class MockNgbModalRef { componentInstance = { skillSummaries: null, skillsInSameTopicCount: null, categorizedSkills: null, allowSkillsFromOtherTopics: null, untriagedSkillSummaries: null }; } describe('QuestionsListComponent', () => { let ctrl = null; let $rootScope = null; let $scope = null; let $q = null; let $uibModal = null; let $timeout = null; let ngbModal: NgbModal; let WindowDimensionsService = null; let QuestionsListService = null; let AlertsService = null; let SkillBackendApiService = null; let skillObjectFactory: SkillObjectFactory; let misconceptionObjectFactory: MisconceptionObjectFactory; let QuestionObjectFactory: QuestionObjectFactory; let EditableQuestionBackendApiService = null; let QuestionUndoRedoService = null; let QuestionValidationService = null; let SkillEditorRoutingService = null; let ContextService = null; let question = null; let questionStateData = null; let skill = null; beforeEach(angular.mock.module('oppia')); importAllAngularServices(); beforeEach(() => { ngbModal = TestBed.inject(NgbModal); skillObjectFactory = TestBed.inject(SkillObjectFactory); misconceptionObjectFactory = TestBed.inject(MisconceptionObjectFactory); }); beforeEach(angular.mock.inject(function($injector, $componentController) { $rootScope = $injector.get('$rootScope'); $scope = $rootScope.$new(); $q = $injector.get('$q'); $uibModal = $injector.get('$uibModal'); $timeout = $injector.get('$timeout'); WindowDimensionsService = $injector.get('WindowDimensionsService'); QuestionsListService = $injector.get('QuestionsListService'); SkillEditorRoutingService = $injector.get('SkillEditorRoutingService'); SkillBackendApiService = $injector.get('SkillBackendApiService'); AlertsService = $injector.get('AlertsService'); QuestionObjectFactory = $injector.get('QuestionObjectFactory'); EditableQuestionBackendApiService = $injector .get('EditableQuestionBackendApiService'); QuestionUndoRedoService = $injector.get('QuestionUndoRedoService'); ContextService = $injector.get('ContextService'); QuestionValidationService = $injector.get('QuestionValidationService'); ctrl = $componentController('questionsList', { $scope: $scope, NgbModal: ngbModal }, { getSelectedSkillId: () => {}, getSkillIds: () => {}, getSkillIdToRubricsObject: () => {}, selectSkillModalIsShown: () => {}, canEditQuestion: () => {}, getAllSkillSummaries: () => {}, getGroupedSkillSummaries: () => {} }); question = QuestionObjectFactory.createFromBackendDict({ id: '1', question_state_data: { content: { html: 'Question 1', content_id: 'content_1' }, interaction: { answer_groups: [{ outcome: { dest: 'outcome 1', feedback: { content_id: 'content_5', html: '' }, labelled_as_correct: true, param_changes: [], refresher_exploration_id: null, missing_prerequisite_skill_id: null, }, rule_specs: [], training_data: null, tagged_skill_misconception_id: null }], confirmed_unclassified_answers: [], customization_args: { placeholder: { value: { content_id: 'ca_placeholder_0', unicode_str: '' } }, rows: { value: 1 } }, default_outcome: { dest: null, feedback: { html: 'Correct Answer', content_id: 'content_2' }, param_changes: [], labelled_as_correct: true, missing_prerequisite_skill_id: null, refresher_exploration_id: null }, hints: [{ hint_content: { html: 'Hint 1', content_id: 'content_3' } }], solution: { correct_answer: 'This is the correct answer', answer_is_exclusive: false, explanation: { html: 'Solution explanation', content_id: 'content_4' } }, id: 'TextInput' }, param_changes: [], recorded_voiceovers: { voiceovers_mapping: {} }, written_translations: { translations_mapping: {} }, classifier_model_id: null, solicit_answer_details: false, card_is_checkpoint: false, linked_skill_id: null, next_content_id_index: null, }, inapplicable_skill_misconception_ids: null, language_code: 'en', linked_skill_ids: [], question_state_data_schema_version: 44, version: 45 }); questionStateData = question.getStateData(); skill = skillObjectFactory.createFromBackendDict({ id: 'skillId1', description: 'test description 1', misconceptions: [{ id: '2', name: 'test name', notes: 'test notes', feedback: 'test feedback', must_be_addressed: true }], rubrics: [], skill_contents: { explanation: { html: 'test explanation', content_id: 'explanation', }, worked_examples: [], recorded_voiceovers: { voiceovers_mapping: {} } }, language_code: 'en', version: 3, prerequisite_skill_ids: [], all_questions_merged: null, next_misconception_id: null, superseding_skill_id: null }); spyOn(ctrl, 'getSelectedSkillId').and.returnValue('skillId1'); spyOn(ctrl, 'getSkillIds').and.returnValue(['skillId1', 'skillId2']); })); it('should set component properties on initialization', () => { spyOn(WindowDimensionsService, 'isWindowNarrow').and.returnValue(true); expect(ctrl.showDifficultyChoices).toBe(undefined); expect(ctrl.difficultyCardIsShown).toBe(undefined); expect(ctrl.associatedSkillSummaries).toEqual(undefined); expect(ctrl.selectedSkillId).toBe(undefined); expect(ctrl.editorIsOpen).toBe(undefined); expect(ctrl.deletedQuestionIds).toEqual(undefined); expect(ctrl.questionEditorIsShown).toBe(undefined); expect(ctrl.questionIsBeingUpdated).toBe(undefined); ctrl.$onInit(); expect(ctrl.showDifficultyChoices).toBe(false); expect(ctrl.difficultyCardIsShown).toBe(false); expect(ctrl.associatedSkillSummaries).toEqual([]); expect(ctrl.selectedSkillId).toBe('skillId1'); expect(ctrl.editorIsOpen).toBe(false); expect(ctrl.deletedQuestionIds).toEqual([]); expect(ctrl.questionEditorIsShown).toBe(false); expect(ctrl.questionIsBeingUpdated).toBe(false); ctrl.$onDestroy(); }); it('should subscribe to question summaries init event on' + ' component initialization', () => { spyOn(QuestionsListService.onQuestionSummariesInitialized, 'subscribe'); ctrl.$onInit(); expect(QuestionsListService.onQuestionSummariesInitialized.subscribe) .toHaveBeenCalled(); }); it('should reset history and fetch question summaries on' + ' initialization', () => { let resetHistoryAndFetch = true; spyOn(QuestionsListService, 'getQuestionSummariesAsync'); expect(ctrl.skillIds).toEqual(undefined); ctrl.$onInit(); expect(ctrl.skillIds).toEqual(['skillId1', 'skillId2']); expect(QuestionsListService.getQuestionSummariesAsync).toHaveBeenCalledWith( 'skillId1', resetHistoryAndFetch, resetHistoryAndFetch ); }); it('should not reset history and fetch question summaries when question' + ' summaries are initialized', () => { let resetHistoryAndFetch = false; let questionSummariesInitializedEmitter = new EventEmitter(); spyOnProperty(QuestionsListService, 'onQuestionSummariesInitialized') .and.returnValue(questionSummariesInitializedEmitter); spyOn(QuestionsListService, 'getQuestionSummariesAsync'); ctrl.$onInit(); questionSummariesInitializedEmitter.emit(); expect(QuestionsListService.getQuestionSummariesAsync).toHaveBeenCalledWith( 'skillId1', resetHistoryAndFetch, resetHistoryAndFetch ); }); it('should fetch misconception ids for selected skill on' + ' initialization', () => { spyOn(SkillBackendApiService, 'fetchSkillAsync').and.returnValue($q.resolve( { skill: skill } )); expect(ctrl.misconceptionIdsForSelectedSkill).toEqual(undefined); ctrl.$onInit(); $scope.$apply(); expect(ctrl.misconceptionIdsForSelectedSkill).toEqual(['2']); }); it('should start creating question on navigating to question editor', () => { spyOn(SkillEditorRoutingService, 'navigateToQuestionEditor') .and.returnValue(true); spyOn(ctrl, 'createQuestion').and.stub(); ctrl.$onInit(); expect(ctrl.createQuestion).toHaveBeenCalled(); }); it('should get selected skill id when a question is created', () => { // When modal is not shown, then newQuestionSkillIds get the values of // skillIds. spyOn(ctrl, 'selectSkillModalIsShown').and.returnValues(true, false); ctrl.skillIds = ['skillId2']; expect(ctrl.newQuestionSkillIds).toEqual(undefined); ctrl.createQuestion(); expect(ctrl.newQuestionSkillIds).toEqual(['skillId1']); ctrl.createQuestion(); expect(ctrl.newQuestionSkillIds).toEqual(['skillId2']); }); it('should populate misconceptions when a question is created', () => { const skill = skillObjectFactory.createFromBackendDict({ id: 'skillId1', description: 'test description 1', misconceptions: [{ id: '2', name: 'test name', notes: 'test notes', feedback: 'test feedback', must_be_addressed: true }], rubrics: [], skill_contents: { explanation: { html: 'test explanation', content_id: 'explanation', }, worked_examples: [], recorded_voiceovers: { voiceovers_mapping: {} } }, language_code: 'en', version: 3, prerequisite_skill_ids: [], all_questions_merged: null, next_misconception_id: null, superseding_skill_id: null }); spyOn(SkillBackendApiService, 'fetchMultiSkillsAsync').and.returnValue( $q.resolve([skill]) ); ctrl.linkedSkillsWithDifficulty = [ SkillDifficulty.create('skillId1', '', 1) ]; expect(ctrl.misconceptionsBySkill).toEqual(undefined); ctrl.initiateQuestionCreation(); $scope.$apply(); expect(ctrl.misconceptionsBySkill).toEqual({ skillId1: [ misconceptionObjectFactory.createFromBackendDict({ id: '2', name: 'test name', notes: 'test notes', feedback: 'test feedback', must_be_addressed: true }) ] }); }); it('should warning message if fetching skills fails', () => { spyOn(AlertsService, 'addWarning'); spyOn(SkillBackendApiService, 'fetchMultiSkillsAsync').and.returnValue( $q.reject('Error occurred.') ); ctrl.populateMisconceptions(); $scope.$apply(); expect(AlertsService.addWarning).toHaveBeenCalled(); }); it('should show the index of a question', () => { spyOn(QuestionsListService, 'getCurrentPageNumber').and.returnValue(5); // Question index = NUM_QUESTION_PER_PAGE (10) * current page number (5) + // index + 1 = 10 * 5 + 1 + 1 = 52. expect(ctrl.getQuestionIndex(1)).toBe(52); }); it('should fetch question summaries on moving to next page', () => { ctrl.selectedSkillId = 'skillId1'; spyOn(QuestionsListService, 'incrementPageNumber'); spyOn(QuestionsListService, 'getQuestionSummariesAsync'); ctrl.goToNextPage(); expect(QuestionsListService.incrementPageNumber).toHaveBeenCalled(); expect(QuestionsListService.getQuestionSummariesAsync).toHaveBeenCalledWith( 'skillId1', true, false ); }); it('should fetch question summaries on moving to previous page', () => { ctrl.selectedSkillId = 'skillId1'; spyOn(QuestionsListService, 'decrementPageNumber'); spyOn(QuestionsListService, 'getQuestionSummariesAsync'); ctrl.goToPreviousPage(); expect(QuestionsListService.decrementPageNumber).toHaveBeenCalled(); expect(QuestionsListService.getQuestionSummariesAsync).toHaveBeenCalledWith( 'skillId1', false, false ); }); it('should check if warning is to be shown for unaddressed skill' + ' misconceptions', () => { // The selected skill id is skillId1. ctrl.misconceptionIdsForSelectedSkill = [1, 2]; expect(ctrl.showUnaddressedSkillMisconceptionWarning([ 'skillId1-1', 'skillId1-2', ])).toBe(true); expect(ctrl.showUnaddressedSkillMisconceptionWarning([ 'skillId1-1', 'skillId2-2', ])).toBe(false); }); it('should get skill editor\'s URL', () => { expect(ctrl.getSkillEditorUrl('skillId1')).toBe('/skill_editor/skillId1'); }); it('should check if current page is the last one', () => { spyOn(QuestionsListService, 'isLastQuestionBatch').and.returnValue(true); expect(ctrl.isLastPage()).toBe(true); }); it('should not save and publish question if there are' + ' validation errors', () => { ctrl.question = question; spyOn(AlertsService, 'addWarning'); spyOn(ctrl.question, 'getValidationErrorMessage').and.returnValue('Error'); spyOn(ctrl.question, 'getUnaddressedMisconceptionNames') .and.returnValue(['misconception1', 'misconception2']); ctrl.saveAndPublishQuestion('Commit'); expect(AlertsService.addWarning).toHaveBeenCalledWith('Error'); }); it('should create new question in the backend if there are no validation' + ' error on saving and publishing a question when question is not already' + ' being updated', () => { ctrl.question = question; ctrl.questionIsBeingUpdated = false; ctrl.skillLinkageModificationsArray = ['1', '2', 1]; spyOn(ctrl.question, 'getValidationErrorMessage').and.returnValue(''); spyOn(ctrl.question, 'getUnaddressedMisconceptionNames') .and.returnValue([]); spyOn(EditableQuestionBackendApiService, 'createQuestionAsync') .and.returnValue($q.resolve({ questionId: 'qId' })); spyOn(EditableQuestionBackendApiService, 'editQuestionSkillLinksAsync'); ctrl.saveAndPublishQuestion('Commit'); $scope.$apply(); expect(EditableQuestionBackendApiService.editQuestionSkillLinksAsync) .toHaveBeenCalledWith('qId', ['1', '2', 1]); }); it('should save question when another question is being updated', () => { ctrl.question = question; ctrl.questionIsBeingUpdated = true; spyOn(ctrl.question, 'getValidationErrorMessage').and.returnValue(''); spyOn(ctrl.question, 'getUnaddressedMisconceptionNames') .and.returnValue([]); spyOn(QuestionUndoRedoService, 'hasChanges').and.returnValue(true); spyOn(EditableQuestionBackendApiService, 'updateQuestionAsync') .and.returnValue($q.resolve()); spyOn(QuestionUndoRedoService, 'clearChanges'); spyOn(QuestionsListService, 'getQuestionSummariesAsync'); ctrl.saveAndPublishQuestion('Commit'); $scope.$apply(); expect(QuestionUndoRedoService.clearChanges).toHaveBeenCalled(); expect(QuestionsListService.getQuestionSummariesAsync) .toHaveBeenCalledWith('skillId1', true, true); }); it('should show error if saving question fails when another question' + ' is being updated', () => { ctrl.question = question; ctrl.questionIsBeingUpdated = true; spyOn(ctrl.question, 'getValidationErrorMessage').and.returnValue(''); spyOn(ctrl.question, 'getUnaddressedMisconceptionNames') .and.returnValue([]); spyOn(QuestionUndoRedoService, 'hasChanges').and.returnValue(true); spyOn(EditableQuestionBackendApiService, 'updateQuestionAsync') .and.returnValue($q.reject()); spyOn(QuestionUndoRedoService, 'clearChanges'); spyOn(QuestionsListService, 'getQuestionSummariesAsync'); spyOn(AlertsService, 'addWarning'); ctrl.saveAndPublishQuestion('Commit'); $scope.$apply(); expect(QuestionUndoRedoService.clearChanges).not.toHaveBeenCalled(); expect(QuestionsListService.getQuestionSummariesAsync) .not.toHaveBeenCalled(); expect(AlertsService.addWarning).toHaveBeenCalledWith( 'There was an error saving the question.'); }); it('should display warning if commit message is not given while saving' + ' a question', () => { ctrl.question = question; ctrl.questionIsBeingUpdated = true; spyOn(ctrl.question, 'getValidationErrorMessage').and.returnValue(''); spyOn(ctrl.question, 'getUnaddressedMisconceptionNames') .and.returnValue([]); spyOn(QuestionUndoRedoService, 'hasChanges').and.returnValue(true); spyOn(AlertsService, 'addWarning'); ctrl.saveAndPublishQuestion(); $scope.$apply(); expect(AlertsService.addWarning) .toHaveBeenCalledWith('Please provide a valid commit message.'); }); it('should show \'confirm question modal exit\' modal when user ' + 'clicks cancel', () => { spyOn($uibModal, 'open').and.returnValue({ result: $q.resolve() }); ctrl.cancel(); $scope.$apply(); expect($uibModal.open).toHaveBeenCalled(); }); it('should reset image save destination when user clicks confirm on' + ' \'confirm question modal exit\' modal', () => { spyOn($uibModal, 'open').and.returnValue({ result: $q.resolve('confirm') }); spyOn(ContextService, 'resetImageSaveDestination'); ctrl.cancel(); $scope.$apply(); expect(ContextService.resetImageSaveDestination).toHaveBeenCalled(); }); it('should close \'confirm question modal exit\' modal when user clicks' + ' cancel', () => { spyOn($uibModal, 'open').and.returnValue({ result: $q.reject('close') }); ctrl.cancel(); $scope.$apply(); expect($uibModal.open).toHaveBeenCalled(); }); it('should update skill difficulty when user selects a difficulty', () => { let skill = SkillDifficulty.create('skillId1', '', 0.9); ctrl.newQuestionSkillIds = ['skillId1']; ctrl.linkedSkillsWithDifficulty = []; ctrl.skillLinkageModificationsArray = []; ctrl.updateSkillWithDifficulty(skill, 0); expect(ctrl.linkedSkillsWithDifficulty[0]).toBe(skill); expect(ctrl.newQuestionSkillDifficulties).toEqual([0.9]); expect(ctrl.skillLinkageModificationsArray).toEqual([ { id: 'skillId1', task: 'update_difficulty', difficulty: 0.9 } ]); ctrl.newQuestionSkillIds = []; ctrl.linkedSkillsWithDifficulty = []; ctrl.skillLinkageModificationsArray = []; ctrl.newQuestionSkillDifficulties = []; ctrl.updateSkillWithDifficulty(skill, 0); expect(ctrl.newQuestionSkillIds).toEqual( ['skillId1']); expect(ctrl.newQuestionSkillDifficulties).toEqual([0.9]); expect(ctrl.skillLinkageModificationsArray).toEqual([ { id: 'skillId1', task: 'update_difficulty', difficulty: 0.9 } ]); }); describe('when user clicks on edit question', () => { let questionSummaryForOneSkill = QuestionSummary .createFromBackendDict({ id: 'qId', interaction_id: '', misconception_ids: [], question_content: '' }); let skillDescription = 'Skill Description'; let difficulty: 0.9; it('should return null if editor is already opened', () => { spyOn(ctrl, 'canEditQuestion'); ctrl.editorIsOpen = true; expect(ctrl.editQuestion()).toBe(undefined); expect(ctrl.canEditQuestion).not.toHaveBeenCalled(); }); it('should warning if user does not have rights to delete a' + ' question', () => { spyOn(ctrl, 'canEditQuestion').and.returnValue(false); spyOn(AlertsService, 'addWarning'); ctrl.editQuestion(); expect(AlertsService.addWarning).toHaveBeenCalledWith( 'User does not have enough rights to delete the question'); }); it('should fetch question data from backend and set new ' + 'question\'s properties', () => { ctrl.editorIsOpen = false; spyOn(ctrl, 'canEditQuestion').and.returnValue(true); spyOn(ctrl, 'selectSkillModalIsShown').and.returnValue(true); spyOn(EditableQuestionBackendApiService, 'fetchQuestionAsync') .and.returnValue($q.resolve({ associated_skill_dicts: [{ id: 'skillId1', misconceptions: [{ id: 'misconception1', feedback: '', must_be_addressed: false, notes: '', name: 'MIsconception 1' }], description: '' }], questionObject: question })); ctrl.editQuestion( questionSummaryForOneSkill, skillDescription, difficulty); $scope.$apply(); expect(ctrl.question).toEqual(question); expect(ctrl.questionId).toBe('1'); expect(ctrl.questionStateData).toEqual(questionStateData); }); it('should display warning if fetching from backend fails', () => { ctrl.editorIsOpen = false; ctrl.skillIds = ['skillId1']; spyOn(ctrl, 'canEditQuestion').and.returnValue(true); spyOn(ctrl, 'selectSkillModalIsShown').and.returnValue(false); spyOn(EditableQuestionBackendApiService, 'fetchQuestionAsync') .and.returnValue($q.reject({ error: 'Failed to fetch question.' })); spyOn(AlertsService, 'addWarning'); ctrl.editQuestion( questionSummaryForOneSkill, skillDescription, difficulty); $scope.$apply(); expect(AlertsService.addWarning).toHaveBeenCalledWith( 'Failed to fetch question.' ); }); }); it('should save image destination to local storage if question editor is' + ' opened while a question is already being created', () => { ctrl.newQuestionIsBeingCreated = true; spyOn(ContextService, 'setImageSaveDestinationToLocalStorage'); ctrl.openQuestionEditor(); expect(ContextService.setImageSaveDestinationToLocalStorage) .toHaveBeenCalled(); }); describe('when deleting question from skill', () => { let questionId = 'qId'; let skillDescription = 'Skill Description'; it('should display warning when user does not have rights to delete' + ' a question', () => { spyOn(ctrl, 'canEditQuestion').and.returnValue(false); spyOn(AlertsService, 'addWarning'); ctrl.deleteQuestionFromSkill(questionId, skillDescription); expect(AlertsService.addWarning).toHaveBeenCalledWith( 'User does not have enough rights to delete the question'); }); it('should delete question when user is in the skill editor', () => { ctrl.selectedSkillId = 'skillId1'; ctrl.deletedQuestionIds = []; spyOn(ctrl, 'canEditQuestion').and.returnValue(true); spyOn(AlertsService, 'addSuccessMessage'); spyOn(ctrl, 'getAllSkillSummaries').and.returnValue([]); spyOn(EditableQuestionBackendApiService, 'editQuestionSkillLinksAsync') .and.returnValue($q.resolve()); ctrl.deleteQuestionFromSkill(questionId, skillDescription); $scope.$apply(); expect(AlertsService.addSuccessMessage).toHaveBeenCalledWith( 'Deleted Question' ); }); it('should delete question when user is not in the skill editor', () => { ctrl.selectedSkillId = 'skillId1'; ctrl.deletedQuestionIds = []; spyOn(ctrl, 'canEditQuestion').and.returnValue(true); spyOn(AlertsService, 'addSuccessMessage'); spyOn(ctrl, 'getAllSkillSummaries').and.returnValue([ ShortSkillSummary.createFromBackendDict({ skill_id: '1', skill_description: 'Skill Description' }) ]); spyOn(EditableQuestionBackendApiService, 'editQuestionSkillLinksAsync') .and.returnValue($q.resolve()); ctrl.deleteQuestionFromSkill(questionId, skillDescription); $scope.$apply(); expect(AlertsService.addSuccessMessage).toHaveBeenCalledWith( 'Deleted Question' ); }); }); it('should not remove skill if it is the only one', () => { ctrl.associatedSkillSummaries = ['summary']; spyOn(AlertsService, 'addInfoMessage'); ctrl.removeSkill(); expect(AlertsService.addInfoMessage).toHaveBeenCalledWith( 'A question should be linked to at least one skill.'); }); it('should remove skill linked to a question', () => { ctrl.associatedSkillSummaries = [ ShortSkillSummary.createFromBackendDict({ skill_id: '1', skill_description: 'Skill Description' }), ShortSkillSummary.createFromBackendDict({ skill_id: '2', skill_description: 'Skill Description' }) ]; ctrl.skillLinkageModificationsArray = []; ctrl.removeSkill('1'); expect(ctrl.associatedSkillSummaries).toEqual([ ShortSkillSummary.createFromBackendDict({ skill_id: '2', skill_description: 'Skill Description' }) ]); expect(ctrl.skillLinkageModificationsArray).toEqual([ { id: '1', task: 'remove' } ]); }); it('should check that question is not savable if there are no' + ' changes', () => { ctrl.skillLinkageModificationsArray = []; ctrl.isSkillDifficultyChanged = false; spyOn(QuestionUndoRedoService, 'hasChanges').and.returnValue(false); expect(ctrl.isQuestionSavable()).toBe(false); }); it('should check if question is savable', () => { ctrl.questionIsBeingUpdated = false; ctrl.newQuestionSkillDifficulties = [0.9]; spyOn(QuestionUndoRedoService, 'hasChanges').and.returnValue(true); spyOn(QuestionValidationService, 'isQuestionValid') .and.returnValues(true, false); expect(ctrl.isQuestionSavable()).toBe(true); ctrl.questionIsBeingUpdated = true; expect(ctrl.isQuestionSavable()).toBe(false); }); it('should show solution if interaction can have solution', () => { ctrl.question = question; spyOn(ctrl.question, 'getStateData').and.returnValue({ interaction: { id: 'TextInput' } }); expect(ctrl.showSolutionCheckpoint()).toBe(true); }); it('should show info message if skills is already linked to question', () => { var skillSummaryDict = { id: 'skillId1', description: 'description1', language_code: 'en', version: 1, misconception_count: 3, worked_examples_count: 3, skill_model_created_on: 1593138898626.193, skill_model_last_updated: 1593138898626.193 }; ctrl.associatedSkillSummaries = [ ShortSkillSummary.createFromBackendDict({ skill_id: 'skillId1', skill_description: 'Skill Description' }), ShortSkillSummary.createFromBackendDict({ skill_id: 'skillId2', skill_description: 'Skill Description' }) ]; spyOn(ctrl, 'getGroupedSkillSummaries').and.returnValue({ current: [], others: [skillSummaryDict] }); spyOn(ngbModal, 'open').and.returnValue( { componentInstance: new MockNgbModalRef(), result: $q.resolve(skillSummaryDict) } as NgbModalRef ); spyOn(AlertsService, 'addInfoMessage'); ctrl.addSkill(); $scope.$apply(); expect(AlertsService.addInfoMessage).toHaveBeenCalledWith( 'Skill already linked to question' ); }); it('should link skill if it is not already linked to question', () => { var skillSummaryDict = { id: 'skillId1', description: 'description1', language_code: 'en', version: 1, misconception_count: 3, worked_examples_count: 3, skill_model_created_on: 1593138898626.193, skill_model_last_updated: 1593138898626.193 }; ctrl.associatedSkillSummaries = [ ShortSkillSummary.createFromBackendDict({ skill_id: 'skillId2', skill_description: 'Skill Description' }), ShortSkillSummary.createFromBackendDict({ skill_id: 'skillId3', skill_description: 'Skill Description' }) ]; spyOn(ctrl, 'getGroupedSkillSummaries').and.returnValue({ current: [], others: [skillSummaryDict] }); spyOn(ngbModal, 'open').and.returnValue( { componentInstance: new MockNgbModalRef(), result: $q.resolve(skillSummaryDict) } as NgbModalRef ); ctrl.addSkill(); $scope.$apply(); expect(ctrl.associatedSkillSummaries).toEqual( [ ShortSkillSummary.createFromBackendDict({ skill_id: 'skillId2', skill_description: 'Skill Description' }), ShortSkillSummary.createFromBackendDict({ skill_id: 'skillId3', skill_description: 'Skill Description' }), ShortSkillSummary.createFromBackendDict({ skill_id: 'skillId1', skill_description: 'description1' }) ] ); expect(ctrl.skillLinkageModificationsArray).toEqual([{ id: 'skillId1', task: 'add', difficulty: 0.3 }]); }); it('should close modal when user clicks on cancel', () => { var skillSummaryDict = { id: 'skillId1', description: 'description1', language_code: 'en', version: 1, misconception_count: 3, worked_examples_count: 3, skill_model_created_on: 1593138898626.193, skill_model_last_updated: 1593138898626.193 }; ctrl.associatedSkillSummaries = [ ShortSkillSummary.createFromBackendDict({ skill_id: 'skillId2', skill_description: 'Skill Description' }), ShortSkillSummary.createFromBackendDict({ skill_id: 'skillId3', skill_description: 'Skill Description' }) ]; spyOn(ctrl, 'getGroupedSkillSummaries').and.returnValue({ current: [], others: [skillSummaryDict] }); spyOn(ngbModal, 'open').and.returnValue( { componentInstance: new MockNgbModalRef(), result: $q.reject(skillSummaryDict) } as NgbModalRef ); spyOn(AlertsService, 'addInfoMessage'); ctrl.addSkill(); $scope.$apply(); expect(ngbModal.open).toHaveBeenCalled(); }); it('should save and publish question after updating linked skill', () => { spyOn(EditableQuestionBackendApiService, 'editQuestionSkillLinksAsync') .and.returnValue($q.resolve()); spyOn(QuestionsListService, 'getQuestionSummariesAsync'); spyOn(ctrl, 'saveAndPublishQuestion'); ctrl.updateSkillLinkageAndQuestions('commit'); $scope.$apply(); $timeout.flush(500); expect(QuestionsListService.getQuestionSummariesAsync).toHaveBeenCalled(); expect(ctrl.editorIsOpen).toBe(false); expect(ctrl.saveAndPublishQuestion).toHaveBeenCalledWith('commit'); }); it('should update skill linkage correctly', () => { ctrl.skillLinkageModificationsArray = [ { id: 'skillId1', task: 'update_difficulty', difficulty: 0.9 } ]; spyOn(EditableQuestionBackendApiService, 'editQuestionSkillLinksAsync') .and.returnValue($q.resolve()); ctrl.updateSkillLinkage(); $scope.$apply(); $timeout.flush(500); expect(ctrl.skillLinkageModificationsArray).toEqual([]); }); it('should open question editor save modal if question' + ' is being updated when user click on \'SAVE\' button', () => { ctrl.questionIsBeingUpdated = true; spyOn($uibModal, 'open').and.returnValue({ result: $q.resolve('commit') }); spyOn(ctrl, 'updateSkillLinkageAndQuestions'); spyOn(ctrl, 'saveAndPublishQuestion'); // If skillLinkageModificationsArray is present. ctrl.skillLinkageModificationsArray = ['1', '2']; ctrl.saveQuestion(); $scope.$apply(); expect(ctrl.updateSkillLinkageAndQuestions).toHaveBeenCalledWith('commit'); // If skillLinkageModificationsArray is not present. ctrl.skillLinkageModificationsArray = []; ctrl.saveQuestion(); $scope.$apply(); expect(ctrl.saveAndPublishQuestion).toHaveBeenCalledWith('commit'); }); it('should create new question if user clicks on \'SAVE\' and if question' + ' is not being updates', () => { ctrl.questionIsBeingUpdated = false; spyOn(SkillEditorRoutingService, 'creatingNewQuestion'); spyOn(ctrl, 'saveAndPublishQuestion'); ctrl.saveQuestion(); expect(ctrl.saveAndPublishQuestion).toHaveBeenCalled(); expect(SkillEditorRoutingService.creatingNewQuestion).toHaveBeenCalled(); }); it('should close question editor save modal if user clicks cancel', () => { ctrl.questionIsBeingUpdated = true; spyOn(ctrl, 'saveAndPublishQuestion'); ctrl.skillLinkageModificationsArray = ['1', '2']; spyOn($uibModal, 'open').and.returnValue({ result: $q.reject() }); ctrl.saveQuestion(); $scope.$apply(); expect(ctrl.saveAndPublishQuestion).not.toHaveBeenCalled(); }); it('should get cached question summaries for one skill', () => { let summary = QuestionSummary .createFromBackendDict({ id: 'qId', interaction_id: '', misconception_ids: [], question_content: '' }); spyOn(QuestionsListService, 'getCachedQuestionSummaries').and.returnValue( summary); expect(ctrl.getQuestionSummariesForOneSkill()).toEqual(summary); }); it('should not toggle difficulty card if window is not narrow', () => { spyOn(WindowDimensionsService, 'isWindowNarrow').and.returnValue(false); ctrl.difficultyCardIsShown = true; ctrl.toggleDifficultyCard(); expect(ctrl.difficultyCardIsShown).toBe(true); }); it('should toggle difficulty card if window is narrow', () => { spyOn(WindowDimensionsService, 'isWindowNarrow').and.returnValue(true); ctrl.difficultyCardIsShown = true; ctrl.toggleDifficultyCard(); expect(ctrl.difficultyCardIsShown).toBe(false); }); it('should get current page number', () => { spyOn(QuestionsListService, 'getCurrentPageNumber').and.returnValue(5); expect(ctrl.getCurrentPageNumber()).toBe(5); }); });
the_stack
import * as core from '@serverless-devs/core'; import promiseRetry from 'promise-retry'; import _ from 'lodash'; import path from 'path'; import fse from 'fs-extra'; import { MOCK_PROJECT_YAML_PATH, MOCK_PROJECT_PATH, DEFAULT_CLIENT_TIMEOUT, INPUTS, REGION, ACCESS, SERVICE_CONFIG, SERVICE_NAME, FUNCTION_NAME, FUNCTION_CONFIG, OSS_TRIGGER_CONFIG, OSS_BUCKET_NAME, OSS_TRIGGER_NAME, MNS_TRIGGER_NAME, MNS_TOPIC_NAME, MNS_TRIGGER_CONFIG, HTTP_TRIGGER_NAME, HTTP_TRIGGER_CONFIG, ROLE_NAME, } from './mock-data'; import FcComponent from '../src/index'; import { handlerCredentials, setupIntegrationTestEnv, cleanupIntegrationTestEnv, getFcClient, deleteFcResource, createOssBucket, removeBucket, genStateIdOfService, generateProjectName, generateLogstoreName, transformMountpointFromRemoteToLocal, removeNas, removeSls, // removeVpc, removeRam, createMnsTopic, deleteMnsTopic, } from './test-utils'; import { NasConfig } from '../src/lib/interface/nas'; import { LogConfig } from '../src/lib/interface/sls'; const retryOptions = { retries: 2, factor: 2, minTimeout: 1 * 1000, randomize: true, }; describe('Integration::deploy', () => { let fcClient: any; beforeAll(async () => { const { accountId, accessKeyId, accessKeySecret } = handlerCredentials(); await setupIntegrationTestEnv(ACCESS, accountId, accessKeyId, accessKeySecret, MOCK_PROJECT_PATH, MOCK_PROJECT_YAML_PATH); fcClient = getFcClient(REGION, DEFAULT_CLIENT_TIMEOUT); }); afterAll(async () => { await cleanupIntegrationTestEnv(ACCESS, MOCK_PROJECT_PATH); }); afterEach(async () => { await fse.remove(path.join(MOCK_PROJECT_PATH, '.s')); }); it('deploy service role', async () => { const roleConfig = { name: ROLE_NAME, policies: [ 'AliyunOSSFullAccess', { name: ROLE_NAME, description: 'fc integration test', statement: [{ Effect: 'Allow', Action: 'log:ListProject', Resource: '*', }] } ] }; try { const inputs = _.cloneDeep(INPUTS); inputs.props = { region: REGION, service: { ...SERVICE_CONFIG, role: roleConfig, }, }; await new FcComponent(inputs).deploy(inputs); const { role } = (await fcClient.getService(SERVICE_NAME)).data; expect(role).toMatch(new RegExp(`role/${ROLE_NAME}`)); } finally { await deleteFcResource('Integration::deploy/deploy service with http trigger', fcClient, { serviceName: SERVICE_NAME }); try { await removeRam(ACCESS, MOCK_PROJECT_YAML_PATH, roleConfig); } catch(e) { console.log('remove ram error'); } } }); it('deploy service with mns/oss trigger', async () => { try { await createOssBucket(REGION, OSS_BUCKET_NAME); await createMnsTopic(REGION, MNS_TOPIC_NAME); const inputs = _.cloneDeep(INPUTS); inputs.props = { region: REGION, service: SERVICE_CONFIG, function: FUNCTION_CONFIG, triggers: [OSS_TRIGGER_CONFIG, MNS_TRIGGER_CONFIG], }; const res = await new FcComponent(inputs).deploy(inputs); expect(res).toMatchObject({ region: REGION, service: { name: SERVICE_NAME }, function: { name: FUNCTION_NAME, runtime: 'nodejs12', handler: 'index.handler', memorySize: 128, timeout: 30, }, triggers: [ { type: 'oss', name: OSS_TRIGGER_NAME }, { type: 'mns_topic', name: MNS_TRIGGER_NAME }, ], }); } finally { const resourceName = { serviceName: SERVICE_NAME, functionName: FUNCTION_NAME, triggerNames: [OSS_TRIGGER_NAME, MNS_TRIGGER_NAME], }; await deleteFcResource('Integration::deploy/deploy service with trigger', fcClient, resourceName); await removeBucket(REGION, OSS_BUCKET_NAME); await deleteMnsTopic(REGION, MNS_TOPIC_NAME); } }); it('deploy service with http trigger', async () => { try { const inputs = _.cloneDeep(INPUTS); inputs.props = { region: REGION, service: SERVICE_CONFIG, function: FUNCTION_CONFIG, triggers: [HTTP_TRIGGER_CONFIG], }; const res = await new FcComponent(inputs).deploy(inputs); expect(res).toMatchObject({ region: REGION, service: { name: SERVICE_NAME }, function: { name: FUNCTION_NAME, runtime: 'nodejs12', handler: 'index.handler', memorySize: 128, timeout: 30, }, triggers: [{ type: 'http', name: HTTP_TRIGGER_NAME }], }); } finally { const resourceName = { serviceName: SERVICE_NAME, functionName: FUNCTION_NAME, triggerNames: [HTTP_TRIGGER_NAME], }; await deleteFcResource('Integration::deploy/deploy service with http trigger', fcClient, resourceName); } }); it('deploy service with auto,and update service', async() => { let nasConfig: any; let vpcConfig: any; let resolvedNasConfig: NasConfig; let logConfig: LogConfig; try { const inputs = _.cloneDeep(INPUTS); inputs.props = { region: REGION, service: { ...SERVICE_CONFIG, tracingConfig: 'Enable', logConfig: 'auto', nasConfig: 'auto', vpcConfig: 'auto', }, }; const fcComponent = await new FcComponent(inputs); await promiseRetry(async (retry: any, times: number) => { try { await fcComponent.deploy(inputs); } catch (ex) { console.log('deploy service with auto, retry ', times); retry(ex); } }, retryOptions); const serviceConfig = (await fcClient.getService(SERVICE_NAME)).data; const state = await core.getState(genStateIdOfService(SERVICE_NAME, REGION)); expect(state).toHaveProperty('statefulConfig'); expect(state).toHaveProperty('statefulAutoConfig'); const statefulAutoConfig = state?.statefulAutoConfig; expect(statefulAutoConfig).toHaveProperty('role'); expect(statefulAutoConfig).toHaveProperty('vpcConfig'); expect(statefulAutoConfig).toHaveProperty('logConfig'); expect(statefulAutoConfig).toHaveProperty('nasConfig'); const role: string = statefulAutoConfig.role; expect(role).toEqual(`acs:ram::${fcClient.accountid}:role/aliyunfcdefaultrole`); logConfig = statefulAutoConfig.logConfig; expect(logConfig).toMatchObject({ project: generateProjectName(fcClient.accountid, REGION), logstore: generateLogstoreName(SERVICE_NAME, REGION, fcClient.accountid), enableRequestMetrics: true, enableInstanceMetrics: true, }); nasConfig = statefulAutoConfig.nasConfig; resolvedNasConfig = { userId: nasConfig.userId, groupId: nasConfig.groupId, mountPoints: nasConfig.mountPoints.map((item) => transformMountpointFromRemoteToLocal(item)), }; vpcConfig = statefulAutoConfig.vpcConfig; delete vpcConfig.role; expect(serviceConfig).toMatchObject({ serviceName: SERVICE_NAME, vpcConfig, nasConfig, role, logConfig, }); const inputs2 = _.cloneDeep(INPUTS); inputs2.props = { region: REGION, service: { ...SERVICE_CONFIG, vpcConfig, nasConfig: resolvedNasConfig, logConfig: { project: logConfig.project, logstore: logConfig.logstore, }, }, }; await promiseRetry(async (retry: any, times: number) => { try { await new FcComponent(inputs2).deploy(inputs2); } catch (ex) { console.log('update service, retry ', times); retry(ex); } }, retryOptions); const serviceConfig2 = (await fcClient.getService(SERVICE_NAME)).data; expect(serviceConfig2).toMatchObject({ serviceName: SERVICE_NAME, vpcConfig, nasConfig, role, logConfig: { project: logConfig.project, logstore: logConfig.logstore, enableRequestMetrics: false, enableInstanceMetrics: false, }, }); const inputs3 = _.cloneDeep(INPUTS); inputs3.props = { region: REGION, service: { ...SERVICE_CONFIG, }, }; await promiseRetry(async (retry: any, times: number) => { try { await new FcComponent(inputs3).deploy(inputs3); } catch (ex) { console.log('update service2, retry ', times); retry(ex); } }, retryOptions); const serviceConfig3 = (await fcClient.getService(SERVICE_NAME)).data; expect(serviceConfig3.role).toBe(''); expect(serviceConfig3.tracingConfig.type).toBeNull(); expect(serviceConfig3.logConfig).toMatchObject({ project: '', logstore: '', enableRequestMetrics: false, enableInstanceMetrics: false, // logBeginRule: null, }); expect(serviceConfig3.vpcConfig).toStrictEqual({ vpcId: '', vSwitchIds: [], securityGroupId: '', role: '', }); expect(serviceConfig3.nasConfig).toStrictEqual({ userId: -1, groupId: -1, mountPoints: [], }); } finally { try { await removeNas(ACCESS, MOCK_PROJECT_YAML_PATH, REGION, SERVICE_NAME, resolvedNasConfig); } catch (e) { console.log(e); } // try { // await removeVpc(ACCESS, MOCK_PROJECT_YAML_PATH, REGION, vpcConfig); // } catch (e) { // console.log(e); // } try { await removeSls(REGION, logConfig); } catch (e) { console.log(e); } await deleteFcResource('Integration::deploy/deploy service with auto', fcClient, { serviceName: SERVICE_NAME }); } }); });
the_stack
import * as ts from 'typescript'; import * as Lint from 'tslint'; import { isTypeParameter, getVariableDeclarationKind, VariableDeclarationKind, getPropertyName, isTypeFlagSet, isExpressionValueUsed, isUnionType, isThisParameter, isTypePredicateNode, isValidNumericLiteral, isIntersectionType, getIIFE, } from 'tsutils'; type FunctionExpressionLike = ts.ArrowFunction | ts.FunctionExpression; const CHECK_RETURN_TYPE_OPTION = 'check-return-type'; const FAIL_MESSAGE = `type annotation is redundant`; interface IOptions { checkReturnType: boolean; } export class Rule extends Lint.Rules.TypedRule { public applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] { return this.applyWithFunction( sourceFile, walk, { checkReturnType: this.ruleArguments.indexOf(CHECK_RETURN_TYPE_OPTION) !== -1, }, program.getTypeChecker(), ); } } const formatFlags = ts.TypeFormatFlags.UseStructuralFallback | ts.TypeFormatFlags.UseFullyQualifiedType | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope | ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.WriteClassExpressionAsTypeLiteral | ts.TypeFormatFlags.WriteArrowStyleSignature; function walk(ctx: Lint.WalkContext<IOptions>, checker: ts.TypeChecker) { return ts.forEachChild(ctx.sourceFile, function cb(node): void { switch (node.kind) { case ts.SyntaxKind.ArrowFunction: case ts.SyntaxKind.FunctionExpression: checkFunction(<FunctionExpressionLike>node); break; case ts.SyntaxKind.MethodDeclaration: if (node.parent!.kind === ts.SyntaxKind.ObjectLiteralExpression) checkObjectLiteralMethod(<ts.MethodDeclaration>node); break; case ts.SyntaxKind.VariableDeclarationList: // TODO add an option where to put the type annotation for functions (variable or function) checkVariables(<ts.VariableDeclarationList>node); } return ts.forEachChild(node, cb); }); function checkFunction(node: FunctionExpressionLike) { // TODO use getContextuallyTypedParameterType if (!functionHasTypeDeclarations(node)) return; const iife = getIIFE(node); if (iife !== undefined) return checkIife(node, iife); const type = getContextualTypeOfFunction(node); if (type === undefined) return; checkContextSensitiveFunctionOrMethod(node, type); } function checkObjectLiteralMethod(node: ts.MethodDeclaration) { if (!functionHasTypeDeclarations(node)) return; const type = getContextualTypeOfObjectLiteralMethod(node); if (type === undefined) return; checkContextSensitiveFunctionOrMethod(node, type); } function checkContextSensitiveFunctionOrMethod(node: ts.FunctionLikeDeclaration, contextualType: ts.Type) { const parameters = parametersExceptThis(node.parameters); const sig = getMatchingSignature(contextualType, parameters); if (sig === undefined) return; const [signature, checkReturn] = sig; if (ctx.options.checkReturnType && checkReturn && node.type !== undefined && !signatureHasGenericOrTypePredicateReturn(signature) && typesAreEqual(checker.getTypeFromTypeNode(node.type), signature.getReturnType())) fail(node.type); let restParameterContext = false; let contextualParameterType: ts.Type; for (let i = 0; i < parameters.length; ++i) { if (!restParameterContext) { const context = signature.parameters[i]; // wotan-disable-next-line no-useless-predicate if (context === undefined || context.valueDeclaration === undefined) break; if (isTypeParameter(checker.getTypeAtLocation(context.valueDeclaration))) continue; contextualParameterType = checker.getTypeOfSymbolAtLocation(context, node); if ((<ts.ParameterDeclaration>context.valueDeclaration).dotDotDotToken !== undefined) { const indexType = contextualParameterType.getNumberIndexType(); if (indexType === undefined) break; contextualParameterType = indexType; restParameterContext = true; } } const parameter = parameters[i]; if (parameter.type === undefined) continue; let declaredType: ts.Type; if (parameter.dotDotDotToken !== undefined) { if (!restParameterContext) break; declaredType = checker.getTypeFromTypeNode(parameter.type); const indexType = declaredType.getNumberIndexType(); if (indexType === undefined) break; declaredType = indexType; } else { declaredType = checker.getTypeFromTypeNode(parameter.type); } if (compareParameterTypes( contextualParameterType!, declaredType, parameter.questionToken !== undefined || parameter.initializer !== undefined, )) fail(parameter.type); } } function checkIife(func: FunctionExpressionLike, iife: ts.CallExpression) { if (ctx.options.checkReturnType && func.type !== undefined && func.name === undefined && ( !isExpressionValueUsed(iife) || !containsTypeWithFlag(checker.getTypeFromTypeNode(func.type), ts.TypeFlags.Literal) && checker.getContextualType(iife) !== undefined )) fail(func.type); const parameters = parametersExceptThis(func.parameters); const args = iife.arguments; const len = Math.min(parameters.length, args.length); outer: for (let i = 0; i < len; ++i) { const parameter = parameters[i]; if (parameter.type === undefined) continue; const declaredType = checker.getTypeFromTypeNode(parameter.type); const contextualType = checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(args[i])); if (parameter.dotDotDotToken !== undefined) { const indexType = declaredType.getNumberIndexType(); if (indexType === undefined || !typesAreEqual(indexType, contextualType)) break; for (let j = i + 1; j < args.length; ++j) if (!typesAreEqual(contextualType, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(args[j])))) break outer; // TODO build UnionType fail(parameter.type); } else if (compareParameterTypes( contextualType, declaredType, parameter.questionToken !== undefined || parameter.initializer !== undefined, )) { fail(parameter.type); } } } function checkVariables(list: ts.VariableDeclarationList) { const isConst = getVariableDeclarationKind(list) === VariableDeclarationKind.Const; for (const variable of list.declarations) { if (variable.type === undefined || variable.initializer === undefined) continue; let inferred = checker.getTypeAtLocation(variable.initializer); if (!isConst) inferred = checker.getBaseTypeOfLiteralType(inferred); const declared = checker.getTypeFromTypeNode(variable.type); if (typesAreEqual(declared, inferred) || isConst && typesAreEqual(declared, checker.getBaseTypeOfLiteralType(inferred))) fail(variable.type); } } function fail(type: ts.TypeNode) { ctx.addFailure(type.pos - 1, type.end, FAIL_MESSAGE, Lint.Replacement.deleteFromTo(type.pos - 1, type.end)); } // TODO this could use a little more effort function typesAreEqual(a: ts.Type, b: ts.Type): boolean { return a === b || checker.typeToString(a, undefined, formatFlags) === checker.typeToString(b, undefined, formatFlags); } function getContextualTypeOfFunction(func: FunctionExpressionLike): ts.Type | undefined { const type = checker.getContextualType(func); return type && checker.getApparentType(type); } function getContextualTypeOfObjectLiteralMethod(method: ts.MethodDeclaration): ts.Type | undefined { let type = checker.getContextualType(<ts.ObjectLiteralExpression>method.parent); if (type === undefined) return; type = checker.getApparentType(type); if (!isTypeFlagSet(type, ts.TypeFlags.StructuredType)) return; const t = checker.getTypeAtLocation(method); const symbol = t.symbol && type.getProperties().find((s) => s.escapedName === t.symbol!.escapedName); return symbol !== undefined ? checker.getTypeOfSymbolAtLocation(symbol, method.name) : isNumericPropertyName(method.name) && type.getNumberIndexType() || type.getStringIndexType(); } function signatureHasGenericOrTypePredicateReturn(signature: ts.Signature): boolean { if (signature.declaration === undefined) return false; if (signature.declaration.type !== undefined && isTypePredicateNode(signature.declaration.type)) return true; const original = checker.getSignatureFromDeclaration(<ts.SignatureDeclaration>signature.declaration); return original !== undefined && isTypeParameter(original.getReturnType()); } function removeOptionalityFromType(type: ts.Type): ts.Type { if (!containsTypeWithFlag(type, ts.TypeFlags.Undefined)) return type; const allowsNull = containsTypeWithFlag(type, ts.TypeFlags.Null); type = checker.getNonNullableType(type); return allowsNull ? checker.getNullableType(type, ts.TypeFlags.Null) : type; } function compareParameterTypes(context: ts.Type, declared: ts.Type, optional: boolean): boolean { if (optional) declared = removeOptionalityFromType(declared); return typesAreEqual(declared, context) || optional && typesAreEqual(checker.getNullableType(declared, ts.TypeFlags.Undefined), context); } function isNumericPropertyName(name: ts.PropertyName) { const str = getPropertyName(name); if (str !== undefined) return isValidNumericLiteral(str) && String(+str) === str; return isAssignableToNumber(checker.getTypeAtLocation((<ts.ComputedPropertyName>name).expression)); // TODO use isTypeAssignableTo } function isAssignableToNumber(type: ts.Type) { let typeParametersSeen: Set<ts.Type> | undefined; return (function check(t): boolean { if (isTypeParameter(t) && t.symbol !== undefined && t.symbol.declarations !== undefined) { if (typeParametersSeen === undefined) { typeParametersSeen = new Set([t]); } else if (!typeParametersSeen.has(t)) { typeParametersSeen.add(t); } else { return false; } const declaration = <ts.TypeParameterDeclaration>t.symbol.declarations[0]; if (declaration.constraint === undefined) return true; return check(checker.getTypeFromTypeNode(declaration.constraint)); } if (isUnionType(t)) return t.types.every(check); if (isIntersectionType(t)) return t.types.some(check); return isTypeFlagSet(t, ts.TypeFlags.NumberLike | ts.TypeFlags.Any); })(type); } function getMatchingSignature(type: ts.Type, parameters: ReadonlyArray<ts.ParameterDeclaration>): [ts.Signature, boolean] | undefined { const minArguments = getMinArguments(parameters); const signatures = getSignaturesOfType(type).filter( (s) => s.declaration !== undefined && getNumParameters(<ReadonlyArray<ts.ParameterDeclaration>>s.declaration.parameters) >= minArguments, ); switch (signatures.length) { case 0: return; case 1: return [signatures[0], true]; default: { const str = checker.signatureToString(signatures[0], undefined, formatFlags); const withoutReturn = removeSignatureReturn(str); let returnUsable = true; for (let i = 1; i < signatures.length; ++i) { // check if all signatures are the same const sig = checker.signatureToString(signatures[i], undefined, formatFlags); if (str !== sig) { if (withoutReturn !== removeSignatureReturn(sig)) return; returnUsable = false; } } return [signatures[0], returnUsable]; } } } } function removeSignatureReturn(str: string): string { const sourceFile = ts.createSourceFile('tmp.ts', `type T=${str}`, ts.ScriptTarget.ESNext); const signature = <ts.FunctionOrConstructorTypeNode>(<ts.TypeAliasDeclaration>sourceFile.statements[0]).type; return sourceFile.text.substring(7, signature.parameters.end + 1); } function getSignaturesOfType(type: ts.Type): ReadonlyArray<ts.Signature> { if (isUnionType(type)) { const signatures = []; for (const t of type.types) signatures.push(...getSignaturesOfType(t)); return signatures; } if (isIntersectionType(type)) { let signatures; for (const t of type.types) { const sig = getSignaturesOfType(t); if (sig.length !== 0) { if (signatures !== undefined) return []; // if more than one type of the intersection has call signatures, none of them is useful for inference signatures = sig; } } return signatures === undefined ? [] : signatures; } return type.getCallSignatures(); } function getNumParameters(parameters: ReadonlyArray<ts.ParameterDeclaration>): number { if (parameters.length === 0) return 0; if (parameters[parameters.length - 1].dotDotDotToken !== undefined) return Infinity; return parametersExceptThis(parameters).length; } function getMinArguments(parameters: ReadonlyArray<ts.ParameterDeclaration>): number { let minArguments = parameters.length; for (; minArguments > 0; --minArguments) { const parameter = parameters[minArguments - 1]; if (parameter.questionToken === undefined && parameter.initializer === undefined && parameter.dotDotDotToken === undefined) break; } return minArguments; } function containsTypeWithFlag(type: ts.Type, flag: ts.TypeFlags): boolean { return isUnionType(type) ? type.types.some((t) => isTypeFlagSet(t, flag)) : isTypeFlagSet(type, flag); } function parametersExceptThis(parameters: ReadonlyArray<ts.ParameterDeclaration>) { return parameters.length !== 0 && isThisParameter(parameters[0]) ? parameters.slice(1) : parameters; } function functionHasTypeDeclarations(func: ts.FunctionLikeDeclaration): boolean { return func.type !== undefined || parametersExceptThis(func.parameters).some((p) => p.type !== undefined); }
the_stack
import { IdentityTypes, RequestLogicTypes, SignatureTypes } from '@requestnetwork/types'; import Utils from '@requestnetwork/utils'; import AcceptAction from '../../../src/actions/accept'; import Version from '../../../src/version'; const CURRENT_VERSION = Version.currentVersion; import * as TestData from '../utils/test-data-generator'; /* eslint-disable @typescript-eslint/no-unused-expressions */ describe('actions/accept', () => { describe('format', () => { it('can formatAccept without extensionsData', async () => { const actionAccept = await AcceptAction.format( { requestId: TestData.requestIdMock, }, TestData.payerRaw.identity, TestData.fakeSignatureProvider, ); // 'action is wrong' expect(actionAccept.data.name).toBe(RequestLogicTypes.ACTION_NAME.ACCEPT); // 'requestId is wrong' expect(actionAccept.data.parameters.requestId).toBe(TestData.requestIdMock); // 'extensionsData is wrong' expect(actionAccept.data.parameters.extensionsData).toBeUndefined(); }); it('can formatAccept with extensionsData', async () => { const actionAccept = await AcceptAction.format( { extensionsData: TestData.oneExtension, requestId: TestData.requestIdMock, }, TestData.payerRaw.identity, TestData.fakeSignatureProvider, ); // 'action is wrong' expect(actionAccept.data.name).toBe(RequestLogicTypes.ACTION_NAME.ACCEPT); // 'requestId is wrong' expect(actionAccept.data.parameters.requestId).toBe(TestData.requestIdMock); // 'extensionsData is wrong' expect(actionAccept.data.parameters.extensionsData).toEqual(TestData.oneExtension); }); }); describe('applyActionToRequest', () => { it('can apply accept by payer', async () => { const actionAccept = await AcceptAction.format( { requestId: TestData.requestIdMock }, TestData.payerRaw.identity, TestData.fakeSignatureProvider, ); const request = AcceptAction.applyActionToRequest( actionAccept, 2, Utils.deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' expect(request.requestId).toBe(TestData.requestIdMock); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'state is wrong' expect(request.state).toBe(RequestLogicTypes.STATE.ACCEPTED); // 'expectedAmount is wrong' expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'extensions is wrong' expect(request.extensions).toEqual({}); // 'request should have property creator' expect(request).toHaveProperty('creator'); // 'request.creator.type is wrong' expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.creator.value is wrong' expect(request.creator.value).toBe(TestData.payeeRaw.address); // 'request should have property payee' expect(request).toHaveProperty('payee'); if (request.payee) { // 'request.payee.type is wrong' expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payee.value is wrong' expect(request.payee.value).toBe(TestData.payeeRaw.address); } // 'request should have property payer' expect(request).toHaveProperty('payer'); if (request.payer) { // 'request.payer.type is wrong' expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payer.value is wrong' expect(request.payer.value).toBe(TestData.payerRaw.address); } // 'request.events is wrong' expect(request.events[1]).toEqual({ actionSigner: TestData.payerRaw.identity, name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { extensionsDataLength: 0 }, timestamp: 2, }); }); it('cannot apply accept by payee', async () => { const actionAccept = await AcceptAction.format( { requestId: TestData.requestIdMock }, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ); // 'should throw' expect(() => { AcceptAction.applyActionToRequest( actionAccept, 1, Utils.deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('Signer must be the payer'); }); it('cannot apply accept by third party', async () => { const actionAccept = await AcceptAction.format( { requestId: TestData.requestIdMock }, TestData.otherIdRaw.identity, TestData.fakeSignatureProvider, ); expect(() => AcceptAction.applyActionToRequest( actionAccept, 1, Utils.deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('Signer must be the payer'); }); it('cannot apply accept if no requestId', () => { const action = { data: { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: {}, version: CURRENT_VERSION, }, signature: { method: SignatureTypes.METHOD.ECDSA, value: '0xdd44c2d34cba689921c60043a78e189b4aa35d5940723bf98b9bb9083385de316333204ce3bbeced32afe2ea203b76153d523d924c4dca4a1d9fc466e0160f071c', }, }; expect(() => AcceptAction.applyActionToRequest( action, 1, Utils.deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('requestId must be given'); }); it('cannot apply accept if no payer in state', () => { const requestContextNoPayer = { creator: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, events: [ { actionSigner: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { expectedAmount: '123400000000000000', extensionsDataLength: 0, isSignedRequest: false, }, timestamp: 1, }, ], expectedAmount: TestData.arbitraryExpectedAmount, extensions: {}, extensionsData: [], payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, requestId: TestData.requestIdMock, state: RequestLogicTypes.STATE.CREATED, timestamp: 1544426030, version: CURRENT_VERSION, }; const action = { data: { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { requestId: TestData.requestIdMock, }, version: CURRENT_VERSION, }, signature: { method: SignatureTypes.METHOD.ECDSA, value: '0xdd44c2d34cba689921c60043a78e189b4aa35d5940723bf98b9bb9083385de316333204ce3bbeced32afe2ea203b76153d523d924c4dca4a1d9fc466e0160f071c', }, }; expect(() => AcceptAction.applyActionToRequest(action, 2, requestContextNoPayer), ).toThrowError('the request must have a payer'); }); it('cannot apply accept if state === CANCELED in state', () => { const action = { data: { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { requestId: TestData.requestIdMock, }, version: CURRENT_VERSION, }, signature: { method: SignatureTypes.METHOD.ECDSA, value: '0xdd44c2d34cba689921c60043a78e189b4aa35d5940723bf98b9bb9083385de316333204ce3bbeced32afe2ea203b76153d523d924c4dca4a1d9fc466e0160f071c', }, }; expect(() => AcceptAction.applyActionToRequest( action, 1, Utils.deepCopy(TestData.requestCanceledNoExtension), ), ).toThrowError('the request state must be created'); }); it('cannot apply accept if state === ACCEPTED in state', () => { const action = { data: { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { requestId: TestData.requestIdMock, }, version: CURRENT_VERSION, }, signature: { method: SignatureTypes.METHOD.ECDSA, value: '0xdd44c2d34cba689921c60043a78e189b4aa35d5940723bf98b9bb9083385de316333204ce3bbeced32afe2ea203b76153d523d924c4dca4a1d9fc466e0160f071c', }, }; expect(() => AcceptAction.applyActionToRequest( action, 2, Utils.deepCopy(TestData.requestCanceledNoExtension), ), ).toThrowError('the request state must be created'); }); it('can apply accept with extensionsData and no extensionsData before', async () => { const newExtensionsData = [{ id: 'extension1', value: 'whatever' }]; const actionAccept = await AcceptAction.format( { extensionsData: newExtensionsData, requestId: TestData.requestIdMock, }, TestData.payerRaw.identity, TestData.fakeSignatureProvider, ); const request = AcceptAction.applyActionToRequest( actionAccept, 2, Utils.deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' expect(request.requestId).toBe(TestData.requestIdMock); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'state is wrong' expect(request.state).toBe(RequestLogicTypes.STATE.ACCEPTED); // 'expectedAmount is wrong' expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'request.extensionsData is wrong' expect(request.extensionsData).toEqual(newExtensionsData); // 'request should have property creator' expect(request).toHaveProperty('creator'); // 'request.creator.type is wrong' expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.creator.value is wrong' expect(request.creator.value).toBe(TestData.payeeRaw.address); // 'request should have property payee' expect(request).toHaveProperty('payee'); if (request.payee) { // 'request.payee.type is wrong' expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payee.value is wrong' expect(request.payee.value).toBe(TestData.payeeRaw.address); } // 'request should have property payer' expect(request).toHaveProperty('payer'); if (request.payer) { // 'request.payer.type is wrong' expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payer.value is wrong' expect(request.payer.value).toBe(TestData.payerRaw.address); } // 'request.events is wrong' expect(request.events[1]).toEqual({ actionSigner: TestData.payerRaw.identity, name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { extensionsDataLength: 1 }, timestamp: 2, }); }); it('can apply accept with extensionsData and extensionsData before', async () => { const newExtensionsData = [{ id: 'extension1', value: 'whatever' }]; const actionAccept = await AcceptAction.format( { extensionsData: newExtensionsData, requestId: TestData.requestIdMock, }, TestData.payerRaw.identity, TestData.fakeSignatureProvider, ); const request = AcceptAction.applyActionToRequest( actionAccept, 2, Utils.deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' expect(request.requestId).toBe(TestData.requestIdMock); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'state is wrong' expect(request.state).toBe(RequestLogicTypes.STATE.ACCEPTED); // 'expectedAmount is wrong' expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'request.extensionsData is wrong' expect(request.extensionsData).toEqual(TestData.oneExtension.concat(newExtensionsData)); // 'request should have property creator' expect(request).toHaveProperty('creator'); // 'request.creator.type is wrong' expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.creator.value is wrong' expect(request.creator.value).toBe(TestData.payeeRaw.address); // 'request.events is wrong' expect(request.events[1]).toEqual({ actionSigner: TestData.payerRaw.identity, name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { extensionsDataLength: 1 }, timestamp: 2, }); // 'request should have property payee' expect(request).toHaveProperty('payee'); if (request.payee) { // 'request.payee.type is wrong' expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payee.value is wrong' expect(request.payee.value).toBe(TestData.payeeRaw.address); } // 'request should have property payer' expect(request).toHaveProperty('payer'); if (request.payer) { // 'request.payer.type is wrong' expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payer.value is wrong' expect(request.payer.value).toBe(TestData.payerRaw.address); } // 'request.events is wrong' expect(request.events[1]).toEqual({ actionSigner: TestData.payerRaw.identity, name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { extensionsDataLength: 1 }, timestamp: 2, }); }); it('can apply accept without extensionsData and extensionsData before', async () => { const actionAccept = await AcceptAction.format( { requestId: TestData.requestIdMock, }, TestData.payerRaw.identity, TestData.fakeSignatureProvider, ); const request = AcceptAction.applyActionToRequest( actionAccept, 2, Utils.deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' expect(request.requestId).toBe(TestData.requestIdMock); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'state is wrong' expect(request.state).toBe(RequestLogicTypes.STATE.ACCEPTED); // 'expectedAmount is wrong' expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'request.extensionsData is wrong' expect(request.extensionsData).toEqual(TestData.oneExtension); // 'request should have property creator' expect(request).toHaveProperty('creator'); // 'request.creator.type is wrong' expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.creator.value is wrong' expect(request.creator.value).toBe(TestData.payeeRaw.address); // 'request should have property payee' expect(request).toHaveProperty('payee'); if (request.payee) { // 'request.payee.type is wrong' expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payee.value is wrong' expect(request.payee.value).toBe(TestData.payeeRaw.address); } // 'request should have property payer' expect(request).toHaveProperty('payer'); if (request.payer) { // 'request.payer.type is wrong' expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payer.value is wrong' expect(request.payer.value).toBe(TestData.payerRaw.address); } }); }); });
the_stack
import Util from './util' export default class Curve25519 { gf0: Int32Array gf1: Int32Array D: Int32Array D2: Int32Array I: Int32Array _9: Uint8Array _121665: Int32Array constructor() { this.gf0 = this.gf() this.gf1 = this.gf([1]) this._9 = new Uint8Array(32) this._9[0] = 9 this._121665 = this.gf([0xdb41, 1]) this.D = this.gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]) this.D2 = this.gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]) this.I = this.gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]) } gf(init?: number[]): Int32Array { const r = new Int32Array(16) if (init) { for (let i = 0; i < init.length; i++) { r[i] = init[i] } } return r } A(o: Int32Array, a: Int32Array, b: Int32Array): void { for (let i = 0; i < 16; i++) { o[i] = a[i] + b[i] } } Z(o: Int32Array, a: Int32Array, b: Int32Array): void { for (let i = 0; i < 16; i++) { o[i] = a[i] - b[i] } } // Avoid loops for better performance M(o: Int32Array, a: Int32Array, b: Int32Array): void { let v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0 const b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15] v = a[0] t0 += v * b0 t1 += v * b1 t2 += v * b2 t3 += v * b3 t4 += v * b4 t5 += v * b5 t6 += v * b6 t7 += v * b7 t8 += v * b8 t9 += v * b9 t10 += v * b10 t11 += v * b11 t12 += v * b12 t13 += v * b13 t14 += v * b14 t15 += v * b15 v = a[1] t1 += v * b0 t2 += v * b1 t3 += v * b2 t4 += v * b3 t5 += v * b4 t6 += v * b5 t7 += v * b6 t8 += v * b7 t9 += v * b8 t10 += v * b9 t11 += v * b10 t12 += v * b11 t13 += v * b12 t14 += v * b13 t15 += v * b14 t16 += v * b15 v = a[2] t2 += v * b0 t3 += v * b1 t4 += v * b2 t5 += v * b3 t6 += v * b4 t7 += v * b5 t8 += v * b6 t9 += v * b7 t10 += v * b8 t11 += v * b9 t12 += v * b10 t13 += v * b11 t14 += v * b12 t15 += v * b13 t16 += v * b14 t17 += v * b15 v = a[3] t3 += v * b0 t4 += v * b1 t5 += v * b2 t6 += v * b3 t7 += v * b4 t8 += v * b5 t9 += v * b6 t10 += v * b7 t11 += v * b8 t12 += v * b9 t13 += v * b10 t14 += v * b11 t15 += v * b12 t16 += v * b13 t17 += v * b14 t18 += v * b15 v = a[4] t4 += v * b0 t5 += v * b1 t6 += v * b2 t7 += v * b3 t8 += v * b4 t9 += v * b5 t10 += v * b6 t11 += v * b7 t12 += v * b8 t13 += v * b9 t14 += v * b10 t15 += v * b11 t16 += v * b12 t17 += v * b13 t18 += v * b14 t19 += v * b15 v = a[5] t5 += v * b0 t6 += v * b1 t7 += v * b2 t8 += v * b3 t9 += v * b4 t10 += v * b5 t11 += v * b6 t12 += v * b7 t13 += v * b8 t14 += v * b9 t15 += v * b10 t16 += v * b11 t17 += v * b12 t18 += v * b13 t19 += v * b14 t20 += v * b15 v = a[6] t6 += v * b0 t7 += v * b1 t8 += v * b2 t9 += v * b3 t10 += v * b4 t11 += v * b5 t12 += v * b6 t13 += v * b7 t14 += v * b8 t15 += v * b9 t16 += v * b10 t17 += v * b11 t18 += v * b12 t19 += v * b13 t20 += v * b14 t21 += v * b15 v = a[7] t7 += v * b0 t8 += v * b1 t9 += v * b2 t10 += v * b3 t11 += v * b4 t12 += v * b5 t13 += v * b6 t14 += v * b7 t15 += v * b8 t16 += v * b9 t17 += v * b10 t18 += v * b11 t19 += v * b12 t20 += v * b13 t21 += v * b14 t22 += v * b15 v = a[8] t8 += v * b0 t9 += v * b1 t10 += v * b2 t11 += v * b3 t12 += v * b4 t13 += v * b5 t14 += v * b6 t15 += v * b7 t16 += v * b8 t17 += v * b9 t18 += v * b10 t19 += v * b11 t20 += v * b12 t21 += v * b13 t22 += v * b14 t23 += v * b15 v = a[9] t9 += v * b0 t10 += v * b1 t11 += v * b2 t12 += v * b3 t13 += v * b4 t14 += v * b5 t15 += v * b6 t16 += v * b7 t17 += v * b8 t18 += v * b9 t19 += v * b10 t20 += v * b11 t21 += v * b12 t22 += v * b13 t23 += v * b14 t24 += v * b15 v = a[10] t10 += v * b0 t11 += v * b1 t12 += v * b2 t13 += v * b3 t14 += v * b4 t15 += v * b5 t16 += v * b6 t17 += v * b7 t18 += v * b8 t19 += v * b9 t20 += v * b10 t21 += v * b11 t22 += v * b12 t23 += v * b13 t24 += v * b14 t25 += v * b15 v = a[11] t11 += v * b0 t12 += v * b1 t13 += v * b2 t14 += v * b3 t15 += v * b4 t16 += v * b5 t17 += v * b6 t18 += v * b7 t19 += v * b8 t20 += v * b9 t21 += v * b10 t22 += v * b11 t23 += v * b12 t24 += v * b13 t25 += v * b14 t26 += v * b15 v = a[12] t12 += v * b0 t13 += v * b1 t14 += v * b2 t15 += v * b3 t16 += v * b4 t17 += v * b5 t18 += v * b6 t19 += v * b7 t20 += v * b8 t21 += v * b9 t22 += v * b10 t23 += v * b11 t24 += v * b12 t25 += v * b13 t26 += v * b14 t27 += v * b15 v = a[13] t13 += v * b0 t14 += v * b1 t15 += v * b2 t16 += v * b3 t17 += v * b4 t18 += v * b5 t19 += v * b6 t20 += v * b7 t21 += v * b8 t22 += v * b9 t23 += v * b10 t24 += v * b11 t25 += v * b12 t26 += v * b13 t27 += v * b14 t28 += v * b15 v = a[14] t14 += v * b0 t15 += v * b1 t16 += v * b2 t17 += v * b3 t18 += v * b4 t19 += v * b5 t20 += v * b6 t21 += v * b7 t22 += v * b8 t23 += v * b9 t24 += v * b10 t25 += v * b11 t26 += v * b12 t27 += v * b13 t28 += v * b14 t29 += v * b15 v = a[15] t15 += v * b0 t16 += v * b1 t17 += v * b2 t18 += v * b3 t19 += v * b4 t20 += v * b5 t21 += v * b6 t22 += v * b7 t23 += v * b8 t24 += v * b9 t25 += v * b10 t26 += v * b11 t27 += v * b12 t28 += v * b13 t29 += v * b14 t30 += v * b15 t0 += 38 * t16 t1 += 38 * t17 t2 += 38 * t18 t3 += 38 * t19 t4 += 38 * t20 t5 += 38 * t21 t6 += 38 * t22 t7 += 38 * t23 t8 += 38 * t24 t9 += 38 * t25 t10 += 38 * t26 t11 += 38 * t27 t12 += 38 * t28 t13 += 38 * t29 t14 += 38 * t30 c = 1 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536 t0 += c - 1 + 37 * (c - 1) c = 1 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536 t0 += c - 1 + 37 * (c - 1) o[0] = t0 o[1] = t1 o[2] = t2 o[3] = t3 o[4] = t4 o[5] = t5 o[6] = t6 o[7] = t7 o[8] = t8 o[9] = t9 o[10] = t10 o[11] = t11 o[12] = t12 o[13] = t13 o[14] = t14 o[15] = t15 } S(o: Int32Array, a: Int32Array): void { this.M(o, a, a) } add(p: Int32Array[], q: Int32Array[]): void { const a = this.gf(), b = this.gf(), c = this.gf(), d = this.gf(), e = this.gf(), f = this.gf(), g = this.gf(), h = this.gf(), t = this.gf() this.Z(a, p[1], p[0]) this.Z(t, q[1], q[0]) this.M(a, a, t) this.A(b, p[0], p[1]) this.A(t, q[0], q[1]) this.M(b, b, t) this.M(c, p[3], q[3]) this.M(c, c, this.D2) this.M(d, p[2], q[2]) this.A(d, d, d) this.Z(e, b, a) this.Z(f, d, c) this.A(g, d, c) this.A(h, b, a) this.M(p[0], e, f) this.M(p[1], h, g) this.M(p[2], g, f) this.M(p[3], e, h) } set25519(r: Int32Array, a: Int32Array): void { for (let i = 0; i < 16; i++) { r[i] = a[i] } } car25519(o: Int32Array): void { let i, v, c = 1 for (i = 0; i < 16; i++) { v = o[i] + c + 65535 c = Math.floor(v / 65536) o[i] = v - c * 65536 } o[0] += c - 1 + 37 * (c - 1) } // b is 0 or 1 sel25519(p: Int32Array, q: Int32Array, b: number): void { let i, t const c = ~(b - 1) for (i = 0; i < 16; i++) { t = c & (p[i] ^ q[i]) p[i] ^= t q[i] ^= t } } inv25519(o: Int32Array, i: Int32Array): void { let a const c = this.gf() for (a = 0; a < 16; a++) { c[a] = i[a] } for (a = 253; a >= 0; a--) { this.S(c, c) if (a !== 2 && a !== 4) { this.M(c, c, i) } } for (a = 0; a < 16; a++) { o[a] = c[a] } } neq25519(a: Int32Array, b: Int32Array): boolean { const c = new Uint8Array(32), d = new Uint8Array(32) this.pack25519(c, a) this.pack25519(d, b) return !Util.compare(c, d) } par25519(a: Int32Array): number { const d = new Uint8Array(32) this.pack25519(d, a) return d[0] & 1 } pow2523(o: Int32Array, i: Int32Array): void { let a const c = this.gf() for (a = 0; a < 16; a++) { c[a] = i[a] } for (a = 250; a >= 0; a--) { this.S(c, c) if (a !== 1) this.M(c, c, i) } for (a = 0; a < 16; a++) { o[a] = c[a] } } cswap(p: Int32Array[], q: Int32Array[], b: number): void { for (let i = 0; i < 4; i++) { this.sel25519(p[i], q[i], b) } } pack25519(o: Uint8Array, n: Int32Array): void { let i const m = this.gf() const t = this.gf() for (i = 0; i < 16; i++) { t[i] = n[i] } this.car25519(t) this.car25519(t) this.car25519(t) for (let j = 0; j < 2; j++) { m[0] = t[0] - 0xffed for (i = 1; i < 15; i++) { m[i] = t[i] - 0xffff - ((m[i - 1] >>> 16) & 1) m[i - 1] &= 0xffff } m[15] = t[15] - 0x7fff - ((m[14] >>> 16) & 1) const b = (m[15] >>> 16) & 1 m[14] &= 0xffff this.sel25519(t, m, 1 - b) } for (i = 0; i < 16; i++) { o[2 * i] = t[i] & 0xff o[2 * i + 1] = t[i] >>> 8 } } unpack25519(o: Int32Array, n: Uint8Array): void { for (let i = 0; i < 16; i++) { o[i] = n[2 * i] + (n[2 * i + 1] << 8) } o[15] &= 0x7fff } unpackNeg(r: Int32Array[], p: Uint8Array): number { const t = this.gf(), chk = this.gf(), num = this.gf(), den = this.gf(), den2 = this.gf(), den4 = this.gf(), den6 = this.gf() this.set25519(r[2], this.gf1) this.unpack25519(r[1], p) this.S(num, r[1]) this.M(den, num, this.D) this.Z(num, num, r[2]) this.A(den, r[2], den) this.S(den2, den) this.S(den4, den2) this.M(den6, den4, den2) this.M(t, den6, num) this.M(t, t, den) this.pow2523(t, t) this.M(t, t, num) this.M(t, t, den) this.M(t, t, den) this.M(r[0], t, den) this.S(chk, r[0]) this.M(chk, chk, den) if (this.neq25519(chk, num)) { this.M(r[0], r[0], this.I) } this.S(chk, r[0]) this.M(chk, chk, den) if (this.neq25519(chk, num)) { return -1 } if (this.par25519(r[0]) === (p[31] >>> 7)) { this.Z(r[0], this.gf0, r[0]) } this.M(r[3], r[0], r[1]) return 0 } /** * Internal scalar mult function * @param {Uint8Array} q Result * @param {Uint8Array} s Secret key * @param {Uint8Array} p Public key */ cryptoScalarmult(q: Uint8Array, s: Uint8Array, p: Uint8Array): void { const x = new Int32Array(80) let r, i const a = this.gf(), b = this.gf(), c = this.gf(), d = this.gf(), e = this.gf(), f = this.gf() this.unpack25519(x, p) for (i = 0; i < 16; i++) { b[i] = x[i] d[i] = a[i] = c[i] = 0 } a[0] = d[0] = 1 for (i = 254; i >= 0; --i) { r = (s[i >>> 3] >>> (i & 7)) & 1 this.sel25519(a, b, r) this.sel25519(c, d, r) this.A(e, a, c) this.Z(a, a, c) this.A(c, b, d) this.Z(b, b, d) this.S(d, e) this.S(f, a) this.M(a, c, a) this.M(c, b, e) this.A(e, a, c) this.Z(a, a, c) this.S(b, a) this.Z(c, d, f) this.M(a, c, this._121665) this.A(a, a, d) this.M(c, c, a) this.M(a, d, f) this.M(d, b, x) this.S(b, e) this.sel25519(a, b, r) this.sel25519(c, d, r) } for (i = 0; i < 16; i++) { x[i + 16] = a[i] x[i + 32] = c[i] x[i + 48] = b[i] x[i + 64] = d[i] } const x32 = x.subarray(32) const x16 = x.subarray(16) this.inv25519(x32, x32) this.M(x16, x16, x32) this.pack25519(q, x16) } /** * Generate the common key as the produkt of sk1 * pk2 * @param {Uint8Array} sk A 32 byte secret key of pair 1 * @param {Uint8Array} pk A 32 byte public key of pair 2 * @return {Uint8Array} sk * pk */ scalarMult(sk: Uint8Array, pk: Uint8Array) { const q = new Uint8Array(32) this.cryptoScalarmult(q, sk, pk) return q } /** * Generate a curve 25519 keypair * @param {Uint8Array} seed A 32 byte cryptographic secure random array. This is basically the secret key * @param {Object} Returns sk (Secret key) and pk (Public key) as 32 byte typed arrays */ generateKeys(seed: Uint8Array): { sk: Uint8Array, pk: Uint8Array } { const sk = seed.slice() const pk = new Uint8Array(32) if (sk.length !== 32) { throw new Error('Invalid secret key size, expected 32 bytes') } sk[0] &= 0xf8 sk[31] &= 0x7f sk[31] |= 0x40 this.cryptoScalarmult(pk, sk, this._9) return { sk, pk, } } }
the_stack
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {Component, Input, ViewChild} from '@angular/core'; import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import {MatAutocompleteHarness} from '@angular/material/autocomplete/testing'; import {MatCheckboxHarness} from '@angular/material/checkbox/testing'; import {MatInputHarness} from '@angular/material/input/testing'; import {By} from '@angular/platform-browser'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {FlowArgsFormModule} from '@app/components/flow_args_form/module'; import {ApiModule} from '@app/lib/api/module'; import {initTestEnvironment} from '@app/testing'; import {firstValueFrom, ReplaySubject, Subject} from 'rxjs'; import {ArtifactCollectorFlowArgs, CollectBrowserHistoryArgs, CollectBrowserHistoryArgsBrowser, GlobComponentExplanation, PipeEndFilter, PipeTypeFilter} from '../../lib/api/api_interfaces'; import {FlowDescriptor, OperatingSystem, SourceType} from '../../lib/models/flow'; import {newArtifactDescriptorMap, newClient} from '../../lib/models/model_test_util'; import {ExplainGlobExpressionService} from '../../lib/service/explain_glob_expression_service/explain_glob_expression_service'; import {deepFreeze} from '../../lib/type_utils'; import {ClientPageGlobalStore} from '../../store/client_page_global_store'; import {ClientPageGlobalStoreMock, mockClientPageGlobalStore} from '../../store/client_page_global_store_test_util'; import {ConfigGlobalStore} from '../../store/config_global_store'; import {injectMockStore, STORE_PROVIDERS} from '../../store/store_test_providers'; import {FlowArgsForm} from './flow_args_form'; initTestEnvironment(); const TEST_FLOW_DESCRIPTORS = deepFreeze({ ArtifactCollectorFlow: { name: 'ArtifactCollectorFlow', friendlyName: 'Collect artifact', category: 'Collector', defaultArgs: { artifactList: [], }, }, CollectBrowserHistory: { name: 'CollectBrowserHistory', friendlyName: 'Browser History', category: 'Browser', defaultArgs: { browsers: [CollectBrowserHistoryArgsBrowser.CHROME], }, }, CollectSingleFile: { name: 'CollectSingleFile', friendlyName: 'Collect Single File', category: 'Filesystem', defaultArgs: { path: '/foo', maxSizeBytes: 1024, }, }, CollectMultipleFiles: { name: 'CollectMultipleFiles', friendlyName: 'Collect Multiple Files', category: 'Filesystem', defaultArgs: { pathExpressions: [], }, }, ListNamedPipes: { name: 'ListNamedPipesFlow', friendlyName: 'List named pipes', category: 'Processes', defaultArgs: { pipeNameRegex: '', procExeRegex: '', pipeTypeFilter: PipeTypeFilter.ANY_TYPE, pipeEndFilter: PipeEndFilter.ANY_END, }, }, ListProcesses: { name: 'ListProcesses', friendlyName: 'List processes', category: 'Processes', defaultArgs: { filenameRegex: '/(default)foo)/', pids: [12222234, 456], connectionStates: [], fetchBinaries: false, }, }, Netstat: { name: 'Netstat', friendlyName: 'List active network connections on a system.', category: 'Network', defaultArgs: { listeningOnly: false, }, }, TimelineFlow: { name: 'TimelineFlow', friendlyName: 'Collect path timeline', category: 'Filesystem', defaultArgs: { root: '/', }, } }); @Component({ template: '<flow-args-form [flowDescriptor]="flowDescriptor"></flow-args-form>', }) class TestHostComponent { @Input() flowDescriptor?: FlowDescriptor; @ViewChild(FlowArgsForm) flowArgsForm!: FlowArgsForm; } function setUp() { return TestBed .configureTestingModule({ imports: [ NoopAnimationsModule, ApiModule, FlowArgsFormModule, ], declarations: [ TestHostComponent, ], providers: [ ...STORE_PROVIDERS, ], }) .compileComponents(); } describe('FlowArgsForm Component', () => { beforeEach(setUp); it('is empty initially', () => { const fixture = TestBed.createComponent(TestHostComponent); fixture.detectChanges(); expect(fixture.nativeElement.innerText.trim()).toEqual(''); }); it('renders sub-form correctly', () => { const fixture = TestBed.createComponent(TestHostComponent); fixture.detectChanges(); fixture.componentInstance.flowDescriptor = TEST_FLOW_DESCRIPTORS.CollectBrowserHistory; fixture.detectChanges(); expect(fixture.nativeElement.innerText).toContain('Chrome'); }); it('emits form value changes', (done) => { const fixture = TestBed.createComponent(TestHostComponent); fixture.detectChanges(); let counter = 0; fixture.componentInstance.flowArgsForm.flowArgValues$.subscribe((value) => { const args = value as CollectBrowserHistoryArgs; if (counter === 0) { expect((args.browsers ?? []).indexOf(CollectBrowserHistoryArgsBrowser.CHROME)) .not.toBe(-1); counter++; } else { expect((args.browsers ?? []).indexOf(CollectBrowserHistoryArgsBrowser.CHROME)) .toBe(-1); done(); } }); fixture.componentInstance.flowDescriptor = TEST_FLOW_DESCRIPTORS.CollectBrowserHistory; fixture.detectChanges(); // This test assumes that the first label in the CollectBrowserHistoryForm // is Chrome, which is not ideal, but an effective workaround. const label = fixture.debugElement.query(By.css('label')).nativeElement; expect(label.innerText).toContain('Chrome'); label.click(); fixture.detectChanges(); }); it('is empty after flow unselection', () => { const fixture = TestBed.createComponent(TestHostComponent); fixture.detectChanges(); fixture.componentInstance.flowDescriptor = TEST_FLOW_DESCRIPTORS.CollectBrowserHistory; fixture.detectChanges(); fixture.componentInstance.flowDescriptor = undefined; fixture.detectChanges(); expect(fixture.nativeElement.innerText.trim()).toEqual(''); }); it('fallback form emits defaultArgs', (done) => { const fixture = TestBed.createComponent(TestHostComponent); fixture.componentInstance.flowDescriptor = { name: 'FlowWithoutForm', friendlyName: '---', category: 'Misc', defaultArgs: {foo: 42}, }; fixture.detectChanges(); fixture.componentInstance.flowArgsForm.flowArgValues$.subscribe(values => { expect(values).toEqual({foo: 42}); done(); }); }); it('emits valid:false when form input is invalid', (done) => { const fixture = TestBed.createComponent(TestHostComponent); fixture.detectChanges(); fixture.componentInstance.flowDescriptor = TEST_FLOW_DESCRIPTORS.CollectSingleFile; fixture.detectChanges(); const byteInput = fixture.debugElement.query(By.css('input[byteInput]')); byteInput.nativeElement.value = 'invalid'; byteInput.triggerEventHandler('change', {target: byteInput.nativeElement}); fixture.detectChanges(); fixture.componentInstance.flowArgsForm.valid$.subscribe((valid) => { expect(valid).toBeFalse(); done(); }); }); }); Object.values(TEST_FLOW_DESCRIPTORS).forEach(fd => { describe(`FlowArgForm ${fd.name}`, () => { beforeEach(setUp); it('renders a sub-form', () => { const fixture = TestBed.createComponent(TestHostComponent); fixture.detectChanges(); fixture.componentInstance.flowDescriptor = fd; fixture.detectChanges(); expect(fixture.nativeElement.innerText.trim()).toBeTruthy(); }); it('emits initial form values', (done) => { const fixture = TestBed.createComponent(TestHostComponent); fixture.detectChanges(); fixture.componentInstance.flowArgsForm.flowArgValues$.subscribe( values => { expect(values).toBeTruthy(); done(); }); fixture.componentInstance.flowDescriptor = fd; fixture.detectChanges(); }); }); }); describe(`FlowArgForm CollectSingleFile`, () => { beforeEach(setUp); it('explains the byte input size', () => { const fixture = TestBed.createComponent(TestHostComponent); fixture.detectChanges(); fixture.componentInstance.flowDescriptor = TEST_FLOW_DESCRIPTORS.CollectSingleFile; fixture.detectChanges(); // Verify that defaultFlowArgs are rendered properly as hint. let text = fixture.debugElement.nativeElement.innerText; expect(text).toContain('1,024 bytes'); const byteInput = fixture.debugElement.query(By.css('input[byteInput]')); byteInput.nativeElement.value = '2 kib'; byteInput.triggerEventHandler('change', {target: byteInput.nativeElement}); fixture.detectChanges(); text = fixture.debugElement.nativeElement.innerText; expect(text).toContain('2 kibibytes '); expect(text).toContain('2,048 bytes'); }); }); describe(`FlowArgForm CollectMultipleFiles`, () => { let clientPageGlobalStore: ClientPageGlobalStoreMock; let explainGlobExpressionService: Partial<ExplainGlobExpressionService>; let explanation$: Subject<ReadonlyArray<GlobComponentExplanation>>; beforeEach(() => { clientPageGlobalStore = mockClientPageGlobalStore(); explanation$ = new ReplaySubject(1); explainGlobExpressionService = { explanation$, explain: jasmine.createSpy('explain'), }; TestBed .configureTestingModule({ imports: [ NoopAnimationsModule, ApiModule, FlowArgsFormModule, ], declarations: [ TestHostComponent, ], providers: [ { provide: ClientPageGlobalStore, useFactory: () => clientPageGlobalStore }, ], }) // Override ALL providers, because each path expression input provides // its own ExplainGlobExpressionService. The above way only overrides // the root-level. .overrideProvider( ExplainGlobExpressionService, {useFactory: () => explainGlobExpressionService}) .compileComponents(); }); function prepareFixture() { const fixture = TestBed.createComponent(TestHostComponent); fixture.detectChanges(); clientPageGlobalStore.mockedObservables.selectedClient$.next(newClient({ clientId: 'C.1234', })); fixture.componentInstance.flowDescriptor = TEST_FLOW_DESCRIPTORS.CollectMultipleFiles; fixture.detectChanges(); return fixture; } it('calls the GlobalStore to explain GlobExpressions', fakeAsync(() => { const fixture = prepareFixture(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = '/home/{foo,bar}'; input.dispatchEvent(new Event('input')); tick(1000); fixture.detectChanges(); expect(explainGlobExpressionService.explain) .toHaveBeenCalledWith('C.1234', '/home/{foo,bar}'); })); it('shows the loaded GlobExpressionExplanation', () => { const fixture = prepareFixture(); explanation$.next([ {globExpression: '/home/'}, {globExpression: '{foo,bar}', examples: ['foo', 'bar']}, ]); fixture.detectChanges(); const text = fixture.debugElement.nativeElement.innerText; expect(text).toContain('/home/foo'); }); it('allows adding path expressions', (done) => { const fixture = prepareFixture(); let inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs.length).toEqual(1); const addButton = fixture.debugElement.query(By.css('#button-add-path-expression')); addButton.nativeElement.click(); fixture.detectChanges(); inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs.length).toEqual(2); inputs[0].nativeElement.value = '/0'; inputs[0].nativeElement.dispatchEvent(new Event('input')); inputs[1].nativeElement.value = '/1'; inputs[1].nativeElement.dispatchEvent(new Event('input')); fixture.detectChanges(); fixture.componentInstance.flowArgsForm.flowArgValues$.subscribe( (values) => { expect(values).toEqual({pathExpressions: ['/0', '/1']}); done(); }); }); it('allows removing path expressions', (done) => { const fixture = prepareFixture(); let inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs.length).toEqual(1); const addButton = fixture.debugElement.query(By.css('#button-add-path-expression')); addButton.nativeElement.click(); fixture.detectChanges(); inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs.length).toEqual(2); inputs[0].nativeElement.value = '/0'; inputs[0].nativeElement.dispatchEvent(new Event('input')); inputs[1].nativeElement.value = '/1'; inputs[1].nativeElement.dispatchEvent(new Event('input')); fixture.detectChanges(); const removeButtons = fixture.debugElement.queryAll(By.css('button[aria-label=\'Remove\']')); expect(removeButtons.length).toEqual(2); removeButtons[1].nativeElement.click(); fixture.detectChanges(); inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs.length).toEqual(1); fixture.componentInstance.flowArgsForm.flowArgValues$.subscribe( (values) => { expect(values).toEqual({pathExpressions: ['/0']}); done(); }); }); it('allows adding modification time expression', () => { const fixture = prepareFixture(); expect(fixture.debugElement.queryAll(By.css('time-range-condition'))) .toHaveSize(0); const conditionButton = fixture.debugElement.query(By.css('button[name=modificationTime]')); conditionButton.nativeElement.click(); fixture.detectChanges(); // The button should disappear after the click. expect( fixture.debugElement.queryAll(By.css('button[name=modificationTime]'))) .toHaveSize(0); expect(fixture.debugElement.queryAll(By.css('time-range-condition'))) .toHaveSize(1); }); it('allows removing modification time expression', () => { const fixture = prepareFixture(); const conditionButton = fixture.debugElement.query(By.css('button[name=modificationTime]')); conditionButton.nativeElement.click(); fixture.detectChanges(); // The form should now appear. expect(fixture.debugElement.queryAll(By.css('time-range-condition'))) .toHaveSize(1); const removeButton = fixture.debugElement.query(By.css('.header .remove button')); removeButton.nativeElement.click(); fixture.detectChanges(); // The form should now disappear. expect(fixture.debugElement.queryAll(By.css('time-range-condition'))) .toHaveSize(0); }); }); describe(`FlowArgForm ArtifactCollectorFlowForm`, () => { beforeEach(() => { TestBed .configureTestingModule({ imports: [ NoopAnimationsModule, ApiModule, FlowArgsFormModule, ], declarations: [ TestHostComponent, ], providers: [ ...STORE_PROVIDERS, ], }) .compileComponents(); }); function prepareFixture() { const fixture = TestBed.createComponent(TestHostComponent); fixture.detectChanges(); fixture.componentInstance.flowDescriptor = TEST_FLOW_DESCRIPTORS.ArtifactCollectorFlow; fixture.detectChanges(); return {fixture}; } it('shows initial artifact suggestions', fakeAsync(async () => { const {fixture} = prepareFixture(); injectMockStore(ConfigGlobalStore) .mockedObservables.artifactDescriptors$.next( newArtifactDescriptorMap([ { name: 'foo', sources: [ { type: SourceType.FILE, paths: ['/sample/path'], conditions: [], returnedTypes: [], supportedOs: new Set() }, ] }, {name: 'bar', doc: 'description123'}, {name: 'baz'}, ])); fixture.detectChanges(); const harnessLoader = TestbedHarnessEnvironment.loader(fixture); const autocompleteHarness = await harnessLoader.getHarness(MatAutocompleteHarness); await autocompleteHarness.focus(); const options = await autocompleteHarness.getOptions(); expect(options.length).toEqual(3); const texts = await Promise.all(options.map(o => o.getText())); expect(texts[0]).toContain('foo'); expect(texts[0]).toContain('/sample/path'); expect(texts[1]).toContain('bar'); expect(texts[1]).toContain('description123'); expect(texts[2]).toContain('baz'); })); it('filters artifact suggestions based on user input', async () => { const {fixture} = prepareFixture(); injectMockStore(ConfigGlobalStore) .mockedObservables.artifactDescriptors$.next(newArtifactDescriptorMap([ {name: 'foo'}, {name: 'baar'}, {name: 'baaz'}, ])); const harnessLoader = TestbedHarnessEnvironment.loader(fixture); const autocompleteHarness = await harnessLoader.getHarness(MatAutocompleteHarness); await autocompleteHarness.enterText('aa'); const options = await autocompleteHarness.getOptions(); expect(options.length).toEqual(2); const texts = await Promise.all(options.map(o => o.getText())); expect(texts[0]).toContain('baar'); expect(texts[1]).toContain('baaz'); }); it('searches artifact fields based on user input', async () => { const {fixture} = prepareFixture(); injectMockStore(ConfigGlobalStore) .mockedObservables.artifactDescriptors$.next(newArtifactDescriptorMap([ { name: 'foo', sources: [ { type: SourceType.FILE, paths: ['/sample/path'], conditions: [], returnedTypes: [], supportedOs: new Set() }, ] }, {name: 'bar'}, {name: 'baz'}, ])); const harnessLoader = TestbedHarnessEnvironment.loader(fixture); const autocompleteHarness = await harnessLoader.getHarness(MatAutocompleteHarness); await autocompleteHarness.enterText('SaMpLe'); const options = await autocompleteHarness.getOptions(); expect(options.length).toEqual(1); expect(await options[0].getText()).toContain('foo'); }); it('configures flow args with selected artifact suggestion', async () => { const {fixture} = prepareFixture(); injectMockStore(ConfigGlobalStore) .mockedObservables.artifactDescriptors$.next(newArtifactDescriptorMap([ {name: 'foo'}, {name: 'bar'}, {name: 'baz'}, ])); const harnessLoader = TestbedHarnessEnvironment.loader(fixture); const autocompleteHarness = await harnessLoader.getHarness(MatAutocompleteHarness); await autocompleteHarness.selectOption({text: /bar/}); const flowArgValues = await firstValueFrom( fixture.componentInstance.flowArgsForm.flowArgValues$) as ArtifactCollectorFlowArgs; expect(flowArgValues.artifactList).toEqual(['bar']); }); it('marks artifacts for different operating system as unavailable', async () => { const {fixture} = prepareFixture(); injectMockStore(ConfigGlobalStore) .mockedObservables.artifactDescriptors$.next( newArtifactDescriptorMap([ {name: 'foo', supportedOs: new Set([OperatingSystem.DARWIN])}, {name: 'bar', supportedOs: new Set([OperatingSystem.WINDOWS])}, { name: 'baz', supportedOs: new Set([OperatingSystem.DARWIN, OperatingSystem.LINUX]) }, ])); injectMockStore(ClientPageGlobalStore) .mockedObservables.selectedClient$.next( newClient({knowledgeBase: {os: 'Darwin'}})); fixture.detectChanges(); const harnessLoader = TestbedHarnessEnvironment.loader(fixture); const autocompleteHarness = await harnessLoader.getHarness(MatAutocompleteHarness); await autocompleteHarness.focus(); const options = await autocompleteHarness.getOptions(); // Unavailable artifacts should still be shown for discoverability. expect(options.length).toEqual(3); const elements = await Promise.all(options.map(o => o.host())); expect(await elements[0].hasClass('unavailable')).toBeFalse(); expect(await elements[1].hasClass('unavailable')).toBeTrue(); expect(await elements[2].hasClass('unavailable')).toBeFalse(); expect(await options[1].getText()).toContain('Windows'); }); it('previews sources for the selected artifact', async () => { const {fixture} = prepareFixture(); injectMockStore(ConfigGlobalStore) .mockedObservables.artifactDescriptors$.next(newArtifactDescriptorMap([ { name: 'foo', sources: [ { type: SourceType.ARTIFACT_GROUP, names: ['bar'], conditions: [], returnedTypes: [], supportedOs: new Set() }, ] }, { name: 'bar', sources: [ { type: SourceType.REGISTRY_KEY, keys: ['HKLM'], conditions: [], returnedTypes: [], supportedOs: new Set() }, ] }, ])); const harnessLoader = TestbedHarnessEnvironment.loader(fixture); const autocompleteHarness = await harnessLoader.getHarness(MatAutocompleteHarness); await autocompleteHarness.selectOption({text: /foo/}); const text = fixture.nativeElement.innerText; // Validate that foo's child artifact and all its sources are shown. expect(text).toContain('bar'); expect(text).toContain('Collects Windows Registry key'); expect(text).toContain('HKLM'); }); }); describe(`FlowArgForm ListProcesses`, () => { beforeEach(setUp); it('emits form input values', async () => { const fixture = TestBed.createComponent(TestHostComponent); fixture.detectChanges(); fixture.componentInstance.flowDescriptor = TEST_FLOW_DESCRIPTORS.ListProcesses; fixture.detectChanges(); await setInputValue( fixture, 'input[formControlName="filenameRegex"]', '/foo/'); await setInputValue(fixture, 'input[formControlName="pids"]', '123, 456'); const harnessLoader = TestbedHarnessEnvironment.loader(fixture); const autocompleteHarness = await harnessLoader.getHarness(MatAutocompleteHarness); await autocompleteHarness.selectOption({text: 'CLOSING'}); const checkboxHarness = await harnessLoader.getHarness(MatCheckboxHarness); await checkboxHarness.check(); const values = await firstValueFrom( fixture.componentInstance.flowArgsForm.flowArgValues$); expect(values).toEqual({ pids: [123, 456], filenameRegex: '/foo/', connectionStates: ['CLOSING'], fetchBinaries: true, }); }); it('flags non-numeric pids as invalid', async () => { const fixture = TestBed.createComponent(TestHostComponent); fixture.detectChanges(); fixture.componentInstance.flowDescriptor = TEST_FLOW_DESCRIPTORS.ListProcesses; fixture.detectChanges(); await setInputValue( fixture, 'input[formControlName="pids"]', '12notnumeric3'); const valid = await firstValueFrom(fixture.componentInstance.flowArgsForm.valid$); expect(valid).toBeFalse(); }); }); async function setInputValue( fixture: ComponentFixture<unknown>, query: string, value: string) { const harnessLoader = TestbedHarnessEnvironment.loader(fixture); const inputHarness = await harnessLoader.getHarness(MatInputHarness.with({selector: query})); await inputHarness.setValue(value); }
the_stack
import { NULL_ADDRESS } from '@celo/base/lib/address' import { BigNumber } from 'bignumber.js' import { keccak } from 'ethereumjs-util' import { EIP712Object, EIP712ObjectValue, EIP712Optional, EIP712Types, encodeData, encodeType, structHash, typeHash, zeroValue, } from './sign-typed-data-utils' // Compile-time check that Domain can be cast to type EIP712Object export const TEST_OPTIONAL_IS_EIP712: EIP712Object = ({} as unknown) as EIP712Optional<EIP712ObjectValue> interface EIP712TestCase { primaryType: string types: EIP712Types typeEncoding: string zero?: EIP712Object examples: Array<{ data: EIP712Object dataEncoding: Buffer }> } const TEST_TYPES: EIP712TestCase[] = [ { primaryType: 'Mail', types: { Mail: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'contents', type: 'string' }, ], }, typeEncoding: 'Mail(address from,address to,string contents)', zero: { from: NULL_ADDRESS, to: NULL_ADDRESS, contents: '', }, examples: [ { data: { from: '0x000000000000000000000000000000000000a1ce', to: '0x0000000000000000000000000000000000000b0b', contents: 'hello bob!', }, dataEncoding: Buffer.concat([ Buffer.from('000000000000000000000000000000000000000000000000000000000000a1ce', 'hex'), Buffer.from('0000000000000000000000000000000000000000000000000000000000000b0b', 'hex'), keccak('hello bob!'), ]), }, { data: { from: '0x000000000000000000000000000000000000a1ce', to: '0x0000000000000000000000000000000000000b0b', // Should be interpreted as a UTF-8 encoded string. Not hex encoded bytes. contents: '0xdeadbeef', }, dataEncoding: Buffer.concat([ Buffer.from('000000000000000000000000000000000000000000000000000000000000a1ce', 'hex'), Buffer.from('0000000000000000000000000000000000000000000000000000000000000b0b', 'hex'), keccak(Buffer.from('0xdeadbeef', 'utf8')), ]), }, ], }, { primaryType: 'Transaction', types: { Transaction: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'tx', type: 'Asset' }, ], Person: [ { name: 'wallet', type: 'address' }, { name: 'name', type: 'string' }, ], Asset: [ { name: 'token', type: 'address' }, { name: 'amount', type: 'uint256' }, ], }, typeEncoding: 'Transaction(Person from,Person to,Asset tx)Asset(address token,uint256 amount)Person(address wallet,string name)', zero: { from: { wallet: NULL_ADDRESS, name: '' }, to: { wallet: NULL_ADDRESS, name: '' }, tx: { token: NULL_ADDRESS, amount: 0 }, }, examples: [ { data: { from: { wallet: '0x000000000000000000000000000000000000a1ce', name: 'Alice' }, to: { name: 'Bob', wallet: '0x0000000000000000000000000000000000000b0b' }, tx: { token: '0x000000000000000000000000000000000000ce10', amount: new BigNumber('5e+18'), }, }, dataEncoding: Buffer.concat([ keccak( Buffer.concat([ keccak('Person(address wallet,string name)'), Buffer.from( '000000000000000000000000000000000000000000000000000000000000a1ce', 'hex' ), keccak('Alice'), ]) ), keccak( Buffer.concat([ keccak('Person(address wallet,string name)'), Buffer.from( '0000000000000000000000000000000000000000000000000000000000000b0b', 'hex' ), keccak('Bob'), ]) ), keccak( Buffer.concat([ keccak('Asset(address token,uint256 amount)'), Buffer.from( '000000000000000000000000000000000000000000000000000000000000ce10', 'hex' ), Buffer.from( '0000000000000000000000000000000000000000000000004563918244F40000', 'hex' ), ]) ), ]), }, ], }, { primaryType: 'Nested', types: { Bird: [ { name: 'species', type: 'string' }, { name: 'color', type: 'Color' }, { name: 'nest', type: 'Nested' }, ], Color: [ { name: 'red', type: 'uint8' }, { name: 'green', type: 'uint8' }, { name: 'blue', type: 'uint8' }, ], Nested: [ { name: 'nest', type: 'Nested' }, { name: 'eggs', type: 'Egg[][]' }, ], Egg: [ { name: 'bird', type: 'Bird' }, { name: 'age', type: 'uint256' }, ], // An orphaned type should have no effect on the encoding. Orphan: [], }, typeEncoding: 'Nested(Nested nest,Egg[][] eggs)Bird(string species,Color color,Nested nest)Color(uint8 red,uint8 green,uint8 blue)Egg(Bird bird,uint256 age)', // Although this recurive type definition can be encoded with EIP-712, no instance of it can. examples: [], }, { primaryType: 'GameBoard', types: { GameBoard: [{ name: 'grid', type: 'Tile[][]' }], Tile: [ { name: 'occupied', type: 'bool' }, { name: 'occupantId', type: 'uint8' }, ], }, typeEncoding: 'GameBoard(Tile[][] grid)Tile(bool occupied,uint8 occupantId)', zero: { grid: [], }, examples: [ { data: { grid: [ [ { occupied: true, occupantId: 5 }, { occupied: false, occupantId: 0 }, ], [ { occupied: true, occupantId: new BigNumber(160) }, { occupied: true, occupantId: 161 }, ], ], }, dataEncoding: Buffer.concat([ keccak( Buffer.concat([ keccak( Buffer.concat([ keccak( Buffer.concat([ keccak('Tile(bool occupied,uint8 occupantId)'), Buffer.from( '0000000000000000000000000000000000000000000000000000000000000001', 'hex' ), Buffer.from( '0000000000000000000000000000000000000000000000000000000000000005', 'hex' ), ]) ), keccak( Buffer.concat([ keccak('Tile(bool occupied,uint8 occupantId)'), Buffer.from( '0000000000000000000000000000000000000000000000000000000000000000', 'hex' ), Buffer.from( '0000000000000000000000000000000000000000000000000000000000000000', 'hex' ), ]) ), ]) ), keccak( Buffer.concat([ keccak( Buffer.concat([ keccak('Tile(bool occupied,uint8 occupantId)'), Buffer.from( '0000000000000000000000000000000000000000000000000000000000000001', 'hex' ), Buffer.from( '00000000000000000000000000000000000000000000000000000000000000a0', 'hex' ), ]) ), keccak( Buffer.concat([ keccak('Tile(bool occupied,uint8 occupantId)'), Buffer.from( '0000000000000000000000000000000000000000000000000000000000000001', 'hex' ), Buffer.from( '00000000000000000000000000000000000000000000000000000000000000a1', 'hex' ), ]) ), ]) ), ]) ), ]), }, ], }, ] describe('encodeType()', () => { for (const { primaryType, types, typeEncoding } of TEST_TYPES) { it(`should encode type ${primaryType} correctly`, () => { expect(encodeType(primaryType, types)).toEqual(typeEncoding) }) } }) describe('typeHash()', () => { for (const { primaryType, types, typeEncoding } of TEST_TYPES) { it(`should hash type ${primaryType} correctly`, () => { expect(typeHash(primaryType, types)).toEqual(keccak(typeEncoding)) }) } }) describe('encodeData()', () => { for (const { primaryType, types, examples } of TEST_TYPES) { if (examples.length > 0) { it(`should encode data ${primaryType} correctly`, () => { for (const { data, dataEncoding } of examples) { expect(encodeData(primaryType, data, types)).toEqual(dataEncoding) } }) } } }) describe('structHash()', () => { for (const { primaryType, types, examples } of TEST_TYPES) { if (examples.length > 0) { it(`should hash data ${primaryType} correctly`, () => { for (const { data, dataEncoding } of examples) { const expected = keccak(Buffer.concat([typeHash(primaryType, types), dataEncoding])) expect(structHash(primaryType, data, types)).toEqual(expected) } }) } } }) describe('zeroValue()', () => { for (const { primaryType, types, zero } of TEST_TYPES) { if (zero !== undefined) { it(`should return zero value for ${primaryType} correctly`, () => { expect(zeroValue(primaryType, types)).toEqual(zero) }) } } })
the_stack
import { visit, DocumentNode, ObjectTypeDefinitionNode, ObjectTypeExtensionNode, Kind, TypeDefinitionNode, TypeExtensionNode, EnumTypeDefinitionNode, EnumTypeExtensionNode, InputObjectTypeDefinitionNode, InputObjectTypeExtensionNode, GraphQLSchema, isScalarType, InterfaceTypeDefinitionNode, InterfaceTypeExtensionNode, } from 'graphql'; import { pascalCase } from 'change-case-all'; import { unique, withQuotes, buildBlock, pushUnique, concatByKey, uniqueByKey, createObject, collectUsedTypes, indent, } from './utils'; import { ModulesConfig } from './config'; import { BaseVisitor } from '@graphql-codegen/visitor-plugin-common'; type RegistryKeys = 'objects' | 'inputs' | 'interfaces' | 'scalars' | 'unions' | 'enums'; type Registry = Record<RegistryKeys, string[]>; const registryKeys: RegistryKeys[] = ['objects', 'inputs', 'interfaces', 'scalars', 'unions', 'enums']; const resolverKeys: Array<Extract<RegistryKeys, 'objects' | 'enums' | 'scalars'>> = ['scalars', 'objects', 'enums']; export function buildModule( name: string, doc: DocumentNode, { importNamespace, importPath, encapsulate, shouldDeclare, rootTypes, schema, baseVisitor, useGraphQLModules, }: { importNamespace: string; importPath: string; encapsulate: ModulesConfig['encapsulateModuleTypes']; shouldDeclare: boolean; rootTypes: string[]; baseVisitor: BaseVisitor; schema?: GraphQLSchema; useGraphQLModules: boolean; } ): string { const picks: Record<RegistryKeys, Record<string, string[]>> = createObject(registryKeys, () => ({})); const defined: Registry = createObject(registryKeys, () => []); const extended: Registry = createObject(registryKeys, () => []); // List of types used in objects, fields, arguments etc const usedTypes = collectUsedTypes(doc); visit(doc, { ObjectTypeDefinition(node) { collectTypeDefinition(node); }, ObjectTypeExtension(node) { collectTypeExtension(node); }, InputObjectTypeDefinition(node) { collectTypeDefinition(node); }, InputObjectTypeExtension(node) { collectTypeExtension(node); }, InterfaceTypeDefinition(node) { collectTypeDefinition(node); }, InterfaceTypeExtension(node) { collectTypeExtension(node); }, ScalarTypeDefinition(node) { collectTypeDefinition(node); }, UnionTypeDefinition(node) { collectTypeDefinition(node); }, UnionTypeExtension(node) { collectTypeExtension(node); }, EnumTypeDefinition(node) { collectTypeDefinition(node); }, EnumTypeExtension(node) { collectTypeExtension(node); }, }); // Defined and Extended types const visited: Registry = createObject(registryKeys, key => concatByKey(defined, extended, key)); // Types that are not defined or extended in a module, they come from other modules const external: Registry = createObject(registryKeys, key => uniqueByKey(extended, defined, key)); // // // // Prints // // // // An actual output const imports = [`import * as ${importNamespace} from "${importPath}";`]; if (useGraphQLModules) { imports.push(`import * as gm from "graphql-modules";`); } let content = [ printDefinedFields(), printDefinedEnumValues(), printDefinedInputFields(), printSchemaTypes(usedTypes), printScalars(visited), printResolveSignaturesPerType(visited), printResolversType(visited), useGraphQLModules ? printResolveMiddlewareMap() : undefined, ] .filter(Boolean) .join('\n\n'); if (encapsulate === 'namespace') { content = `${shouldDeclare ? 'declare' : 'export'} namespace ${baseVisitor.convertName(name, { suffix: 'Module', useTypesPrefix: false, useTypesSuffix: false, })} {\n` + (shouldDeclare ? `${indent(2)(imports.join('\n'))}\n` : '') + indent(2)(content) + '\n}'; } return [...(!shouldDeclare ? imports : []), content].filter(Boolean).join('\n'); /** * A dictionary of fields to pick from an object */ function printDefinedFields() { return buildBlock({ name: `interface DefinedFields`, lines: [...visited.objects, ...visited.interfaces].map( typeName => `${typeName}: ${printPicks(typeName, { ...picks.objects, ...picks.interfaces, })};` ), }); } /** * A dictionary of values to pick from an enum */ function printDefinedEnumValues() { return buildBlock({ name: `interface DefinedEnumValues`, lines: visited.enums.map(typeName => `${typeName}: ${printPicks(typeName, picks.enums)};`), }); } function encapsulateTypeName(typeName: string): string { if (encapsulate === 'prefix') { return `${pascalCase(name)}_${typeName}`; } return typeName; } /** * A dictionary of fields to pick from an input */ function printDefinedInputFields() { return buildBlock({ name: `interface DefinedInputFields`, lines: visited.inputs.map(typeName => `${typeName}: ${printPicks(typeName, picks.inputs)};`), }); } /** * Prints signatures of schema types with picks */ function printSchemaTypes(types: string[]) { return types .filter(type => !visited.scalars.includes(type)) .map(printExportType) .join('\n'); } function printResolveSignaturesPerType(registry: Registry) { return [ [...registry.objects, ...registry.interfaces] .map(name => printResolverType( name, 'DefinedFields', !rootTypes.includes(name) && defined.objects.includes(name) ? ` | '__isTypeOf'` : '' ) ) .join('\n'), ].join('\n'); } function printScalars(registry: Registry) { if (!registry.scalars.length) { return ''; } return [ `export type ${encapsulateTypeName('Scalars')} = Pick<${importNamespace}.Scalars, ${registry.scalars .map(withQuotes) .join(' | ')}>;`, ...registry.scalars.map(scalar => { const convertedName = baseVisitor.convertName(scalar, { suffix: 'ScalarConfig', }); return `export type ${encapsulateTypeName(convertedName)} = ${importNamespace}.${convertedName};`; }), ].join('\n'); } /** * Aggregation of type resolver signatures */ function printResolversType(registry: Registry) { const lines: string[] = []; for (const kind in registry) { const k = kind as RegistryKeys; if (registry.hasOwnProperty(k) && resolverKeys.includes(k as any)) { const types = registry[k]; types.forEach(typeName => { if (k === 'enums') { return; } else if (k === 'scalars') { lines.push(`${typeName}?: ${encapsulateTypeName(importNamespace)}.Resolvers['${typeName}'];`); } else { lines.push(`${typeName}?: ${encapsulateTypeName(typeName)}Resolvers;`); } }); } } return buildBlock({ name: `export interface ${encapsulateTypeName('Resolvers')}`, lines, }); } /** * Signature for a map of resolve middlewares */ function printResolveMiddlewareMap() { const wildcardField = printResolveMiddlewareRecord(withQuotes('*')); const blocks: string[] = [buildBlock({ name: `${withQuotes('*')}?:`, lines: [wildcardField] })]; // Type.Field for (const typeName in picks.objects) { if (picks.objects.hasOwnProperty(typeName)) { const fields = picks.objects[typeName]; const lines = [wildcardField].concat(fields.map(field => printResolveMiddlewareRecord(field))); blocks.push( buildBlock({ name: `${typeName}?:`, lines, }) ); } } return buildBlock({ name: `export interface ${encapsulateTypeName('MiddlewareMap')}`, lines: blocks, }); } function printResolveMiddlewareRecord(path: string): string { return `${path}?: gm.Middleware[];`; } function printResolverType(typeName: string, picksTypeName: string, extraKeys = '') { return `export type ${encapsulateTypeName( `${typeName}Resolvers` )} = Pick<${importNamespace}.${baseVisitor.convertName(typeName, { suffix: 'Resolvers', })}, ${picksTypeName}['${typeName}']${extraKeys}>;`; } function printPicks(typeName: string, records: Record<string, string[]>): string { return records[typeName].filter(unique).map(withQuotes).join(' | '); } function printTypeBody(typeName: string): string { const coreType = `${importNamespace}.${baseVisitor.convertName(typeName, { useTypesSuffix: true, useTypesPrefix: true, })}`; if (external.enums.includes(typeName) || external.objects.includes(typeName)) { if (schema && isScalarType(schema.getType(typeName))) { return `${importNamespace}.Scalars['${typeName}']`; } return coreType; } if (defined.enums.includes(typeName) && picks.enums[typeName]) { return `DefinedEnumValues['${typeName}']`; } if (defined.objects.includes(typeName) && picks.objects[typeName]) { return `Pick<${coreType}, DefinedFields['${typeName}']>`; } if (defined.interfaces.includes(typeName) && picks.interfaces[typeName]) { return `Pick<${coreType}, DefinedFields['${typeName}']>`; } if (defined.inputs.includes(typeName) && picks.inputs[typeName]) { return `Pick<${coreType}, DefinedInputFields['${typeName}']>`; } return coreType; } function printExportType(typeName: string): string { return `export type ${encapsulateTypeName(typeName)} = ${printTypeBody(typeName)};`; } // // // // Utils // // // function collectFields( node: | ObjectTypeDefinitionNode | ObjectTypeExtensionNode | InterfaceTypeDefinitionNode | InterfaceTypeExtensionNode | InputObjectTypeDefinitionNode | InputObjectTypeExtensionNode, picksObj: Record<string, string[]> ) { const name = node.name.value; if (node.fields) { if (!picksObj[name]) { picksObj[name] = []; } node.fields.forEach(field => { picksObj[name].push(field.name.value); }); } } function collectValuesFromEnum(node: EnumTypeDefinitionNode | EnumTypeExtensionNode) { const name = node.name.value; if (node.values) { if (!picks.enums[name]) { picks.enums[name] = []; } node.values.forEach(field => { picks.enums[name].push(field.name.value); }); } } function collectTypeDefinition(node: TypeDefinitionNode) { const name = node.name.value; switch (node.kind) { case Kind.OBJECT_TYPE_DEFINITION: { defined.objects.push(name); collectFields(node, picks.objects); break; } case Kind.ENUM_TYPE_DEFINITION: { defined.enums.push(name); collectValuesFromEnum(node); break; } case Kind.INPUT_OBJECT_TYPE_DEFINITION: { defined.inputs.push(name); collectFields(node, picks.inputs); break; } case Kind.SCALAR_TYPE_DEFINITION: { defined.scalars.push(name); break; } case Kind.INTERFACE_TYPE_DEFINITION: { defined.interfaces.push(name); collectFields(node, picks.interfaces); break; } case Kind.UNION_TYPE_DEFINITION: { defined.unions.push(name); break; } } } function collectTypeExtension(node: TypeExtensionNode) { const name = node.name.value; switch (node.kind) { case Kind.OBJECT_TYPE_EXTENSION: { collectFields(node, picks.objects); // Do not include root types as extensions // so we can use them in DefinedFields if (rootTypes.includes(name)) { pushUnique(defined.objects, name); return; } pushUnique(extended.objects, name); break; } case Kind.ENUM_TYPE_EXTENSION: { collectValuesFromEnum(node); pushUnique(extended.enums, name); break; } case Kind.INPUT_OBJECT_TYPE_EXTENSION: { collectFields(node, picks.inputs); pushUnique(extended.inputs, name); break; } case Kind.INTERFACE_TYPE_EXTENSION: { collectFields(node, picks.interfaces); pushUnique(extended.interfaces, name); break; } case Kind.UNION_TYPE_EXTENSION: { pushUnique(extended.unions, name); break; } } } }
the_stack
import { IAgentContext, IAgentPlugin, IResolver, IDIDManager, IKeyManager, IPluginMethodMap, VerifiableCredential, VerifiablePresentation, IDataStore, IKey, IIdentifier, } from '@veramo/core' import { createVerifiableCredentialJwt, createVerifiablePresentationJwt, CredentialPayload, normalizeCredential, normalizePresentation, PresentationPayload, } from 'did-jwt-vc' import { schema } from './' import Debug from 'debug' const debug = Debug('veramo:w3c:action-handler') /** * The type of encoding to be used for the Verifiable Credential or Presentation to be generated. * * Only `jwt` is supported at the moment. * * @public */ export type EncodingFormat = 'jwt' // | "json" | "json-ld" /** * Encapsulates the parameters required to create a * {@link https://www.w3.org/TR/vc-data-model/#presentations | W3C Verifiable Presentation} * * @public */ export interface ICreateVerifiablePresentationArgs { /** * The json payload of the Presentation according to the * {@link https://www.w3.org/TR/vc-data-model/#presentations | canonical model}. * * The signer of the Presentation is chosen based on the `holder` property * of the `presentation` * * '@context', 'type' and 'issuanceDate' will be added automatically if omitted */ presentation: Partial<PresentationPayload> /** * If this parameter is true, the resulting VerifiablePresentation is sent to the * {@link @veramo/core#IDataStore | storage plugin} to be saved */ save?: boolean /** * The desired format for the VerifiablePresentation to be created. * Currently, only JWT is supported */ proofFormat: EncodingFormat /** * Remove payload members during JWT-JSON transformation. Defaults to `true`. * See https://www.w3.org/TR/vc-data-model/#jwt-encoding */ removeOriginalFields?: boolean } /** * Encapsulates the parameters required to create a * {@link https://www.w3.org/TR/vc-data-model/#credentials | W3C Verifiable Credential} * * @public */ export interface ICreateVerifiableCredentialArgs { /** * The json payload of the Credential according to the * {@link https://www.w3.org/TR/vc-data-model/#credentials | canonical model} * * The signer of the Credential is chosen based on the `issuer.id` property * of the `credential` * * '@context', 'type' and 'issuanceDate' will be added automatically if omitted */ credential: Partial<CredentialPayload> /** * If this parameter is true, the resulting VerifiablePresentation is sent to the * {@link @veramo/core#IDataStore | storage plugin} to be saved */ save?: boolean /** * The desired format for the VerifiablePresentation to be created. * Currently, only JWT is supported */ proofFormat: EncodingFormat /** * Remove payload members during JWT-JSON transformation. Defaults to `true`. * See https://www.w3.org/TR/vc-data-model/#jwt-encoding */ removeOriginalFields?: boolean } /** * The interface definition for a plugin that can generate Verifiable Credentials and Presentations * * @remarks Please see {@link https://www.w3.org/TR/vc-data-model | W3C Verifiable Credentials data model} * * @public */ export interface ICredentialIssuer extends IPluginMethodMap { /** * Creates a Verifiable Presentation. * The payload, signer and format are chosen based on the `args` parameter. * * @param args - Arguments necessary to create the Presentation. * @param context - This reserved param is automatically added and handled by the framework, *do not override* * * @returns - a promise that resolves to the {@link @veramo/core#VerifiablePresentation} that was requested or rejects with an error * if there was a problem with the input or while getting the key to sign * * @remarks Please see {@link https://www.w3.org/TR/vc-data-model/#presentations | Verifiable Presentation data model } */ createVerifiablePresentation( args: ICreateVerifiablePresentationArgs, context: IContext, ): Promise<VerifiablePresentation> /** * Creates a Verifiable Credential. * The payload, signer and format are chosen based on the `args` parameter. * * @param args - Arguments necessary to create the Presentation. * @param context - This reserved param is automatically added and handled by the framework, *do not override* * * @returns - a promise that resolves to the {@link @veramo/core#VerifiableCredential} that was requested or rejects with an error * if there was a problem with the input or while getting the key to sign * * @remarks Please see {@link https://www.w3.org/TR/vc-data-model/#credentials | Verifiable Credential data model} */ createVerifiableCredential( args: ICreateVerifiableCredentialArgs, context: IContext, ): Promise<VerifiableCredential> } /** * Represents the requirements that this plugin has. * The agent that is using this plugin is expected to provide these methods. * * This interface can be used for static type checks, to make sure your application is properly initialized. */ export type IContext = IAgentContext< IResolver & Pick<IDIDManager, 'didManagerGet'> & Pick<IDataStore, 'dataStoreSaveVerifiablePresentation' | 'dataStoreSaveVerifiableCredential'> & Pick<IKeyManager, 'keyManagerSign'> > /** * A Veramo plugin that implements the {@link ICredentialIssuer} methods. * * @public */ export class CredentialIssuer implements IAgentPlugin { readonly methods: ICredentialIssuer readonly schema = schema.ICredentialIssuer constructor() { this.methods = { createVerifiablePresentation: this.createVerifiablePresentation, createVerifiableCredential: this.createVerifiableCredential, } } /** {@inheritdoc ICredentialIssuer.createVerifiablePresentation} */ async createVerifiablePresentation( args: ICreateVerifiablePresentationArgs, context: IContext, ): Promise<VerifiablePresentation> { const presentation: Partial<PresentationPayload> = { ...args?.presentation, '@context': args?.presentation['@context'] || ['https://www.w3.org/2018/credentials/v1'], //FIXME: make sure 'VerifiablePresentation' is the first element in this array: type: args?.presentation?.type || ['VerifiablePresentation'], issuanceDate: args?.presentation?.issuanceDate || new Date().toISOString(), } if (!presentation.holder || typeof presentation.holder === 'undefined') { throw new Error('invalid_argument: args.presentation.holder must not be empty') } let identifier: IIdentifier try { identifier = await context.agent.didManagerGet({ did: presentation.holder }) } catch (e) { throw new Error('invalid_argument: args.presentation.holder must be a DID managed by this agent') } try { //FIXME: `args` should allow picking a key or key type const key = identifier.keys.find((k) => k.type === 'Secp256k1' || k.type === 'Ed25519') if (!key) throw Error('No signing key for ' + identifier.did) //FIXME: Throw an `unsupported_format` error if the `args.proofFormat` is not `jwt` debug('Signing VP with', identifier.did) let alg = 'ES256K' if (key.type === 'Ed25519') { alg = 'EdDSA' } const signer = wrapSigner(context, key, alg) const jwt = await createVerifiablePresentationJwt( presentation as PresentationPayload, { did: identifier.did, signer, alg }, { removeOriginalFields: args.removeOriginalFields }, ) //FIXME: flagging this as a potential privacy leak. debug(jwt) const verifiablePresentation = normalizePresentation(jwt) if (args.save) { await context.agent.dataStoreSaveVerifiablePresentation({ verifiablePresentation }) } return verifiablePresentation } catch (error) { debug(error) return Promise.reject(error) } } /** {@inheritdoc ICredentialIssuer.createVerifiableCredential} */ async createVerifiableCredential( args: ICreateVerifiableCredentialArgs, context: IContext, ): Promise<VerifiableCredential> { const credential: Partial<CredentialPayload> = { ...args?.credential, '@context': args?.credential?.['@context'] || ['https://www.w3.org/2018/credentials/v1'], //FIXME: make sure 'VerifiableCredential' is the first element in this array: type: args?.credential?.type || ['VerifiableCredential'], issuanceDate: args?.credential?.issuanceDate || new Date().toISOString(), } //FIXME: if the identifier is not found, the error message should reflect that. const issuer = typeof credential.issuer === 'string' ? credential.issuer : credential?.issuer?.id if (!issuer || typeof issuer === 'undefined') { throw new Error('invalid_argument: args.credential.issuer must not be empty') } let identifier: IIdentifier try { identifier = await context.agent.didManagerGet({ did: issuer }) } catch (e) { throw new Error(`invalid_argument: args.credential.issuer must be a DID managed by this agent. ${e}`) } try { //FIXME: `args` should allow picking a key or key type const key = identifier.keys.find((k) => k.type === 'Secp256k1' || k.type === 'Ed25519') if (!key) throw Error('No signing key for ' + identifier.did) //FIXME: Throw an `unsupported_format` error if the `args.proofFormat` is not `jwt` debug('Signing VC with', identifier.did) let alg = 'ES256K' if (key.type === 'Ed25519') { alg = 'EdDSA' } const signer = wrapSigner(context, key, alg) const jwt = await createVerifiableCredentialJwt( credential as CredentialPayload, { did: identifier.did, signer, alg }, { removeOriginalFields: args.removeOriginalFields }, ) //FIXME: flagging this as a potential privacy leak. debug(jwt) const verifiableCredential = normalizeCredential(jwt) if (args.save) { await context.agent.dataStoreSaveVerifiableCredential({ verifiableCredential }) } return verifiableCredential } catch (error) { debug(error) return Promise.reject(error) } } } function wrapSigner( context: IAgentContext<Pick<IKeyManager, 'keyManagerSign'>>, key: IKey, algorithm?: string, ) { return async (data: string | Uint8Array) => { const result = await context.agent.keyManagerSign({ keyRef: key.kid, data: <string>data, algorithm }) return result } }
the_stack
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. /// <reference path="../../Core.d.ts" /> import _BaseCoreUtils = require('../../Core/_BaseCoreUtils'); import _BaseUtils = require("../../Core/_BaseUtils"); import _Base = require('../../Core/_Base'); import _Global = require('../../Core/_Global'); import _WriteProfilerMark = require('../../Core/_WriteProfilerMark'); import _Log = require('../../Core/_Log'); import _ErrorFromName = require("../../Core/_ErrorFromName"); import _Events = require("../../Core/_Events"); import Promise = require('../../Promise'); import _Signal = require('../../_Signal'); import _ElementUtilities = require('../../Utilities/_ElementUtilities'); "use strict"; // We will style the _ElementResizeInstrument element to have the same height and width as it's nearest positioned ancestor. var styleText = 'display: block;' + 'position:absolute;' + 'top: 0;' + 'left: 0;' + 'height: 100%;' + 'width: 100%;' + 'overflow: hidden;' + 'pointer-events: none;' + 'z-index: -1;'; var className = "win-resizeinstrument"; var objData = "about:blank"; var eventNames = { /** * Fires when the _ElementResizeInstrument has detected a size change in the monitored ancestor element. **/ resize: "resize", /** * Fires when the internal <object> element has finished loading and we have added our own "resize" listener to its contentWindow. * Used by unit tests. **/ _ready: "_ready", } // Name of the <object> contentWindow event we listen to. var contentWindowResizeEvent = "resize"; // Determine if the browser environment is IE or Edge. // "msHightContrastAdjust" is availble in IE10+ var isMS: boolean = ("msHighContrastAdjust" in document.documentElement.style); /** * Creates a hidden <object> instrumentation element that is used to automatically generate and handle "resize" events whenever the nearest * positioned ancestor element has its size changed. Add the instrumented element to the DOM of the element you want to generate-and-handle * "resize" events for. The computed style.position of the ancestor element must be positioned and therefore may not be "static". **/ export class _ElementResizeInstrument { static EventNames = eventNames; private _disposed: boolean; private _elementLoadPromise: Promise<any>; private _elementLoaded: boolean; private _running: boolean; private _pendingResizeAnimationFrameId: number; private _objectWindowResizeHandlerBound: () => void; constructor() { this._disposed = false; this._elementLoaded = false; this._running = false; this._objectWindowResizeHandlerBound = this._objectWindowResizeHandler.bind(this); var objEl = <HTMLObjectElement>_Global.document.createElement("OBJECT"); objEl.setAttribute('style', styleText); if (isMS) { // <object> element shows an outline visual that can't be styled away in MS browsers. // Using visibility hidden everywhere will stop some browsers from sending resize events, // but we can use is in MS browsers to achieve the visual we want without losing resize events. objEl.style.visibility = "hidden"; } else { // Some browsers like iOS and Safari will never load the <object> element's content window // if the <object> element is in the DOM before its data property was set. // IE and Edge on the other hand are the exact opposite and won't ever load unless you append the // element to the DOM before the data property was set. We expect a later call to addedToDom() will // set the data property after the element is in the DOM for IE and Edge. objEl.data = objData; } objEl.type = 'text/html'; objEl['winControl'] = this; _ElementUtilities.addClass(objEl, className); _ElementUtilities.addClass(objEl, "win-disposable"); this._element = objEl; this._elementLoadPromise = new Promise((c) => { objEl.onload = () => { if (!this._disposed) { this._elementLoaded = true; this._objWindow.addEventListener(contentWindowResizeEvent, this._objectWindowResizeHandlerBound); c(); } } }); } /** * A hidden HTMLObjectElement used to detect size changes in its nearest positioned ancestor element. **/ private _element: HTMLObjectElement; get element() { return this._element; } // Getter for the <object>'s contentWindow. private get _objWindow(): Window { // Property may be undefined if the element hasn't loaded yet. // Property may be undefined in Safari if the element has been removed from the DOM. // https://bugs.webkit.org/show_bug.cgi?id=149251 // Return the contentWindow if it exists, else null. // If the <object> element hasn't loaded yet, some browsers will throw an exception if you try to read the contentDocument property. return this._elementLoaded && this._element.contentDocument && this._element.contentDocument.defaultView || null; } addedToDom() { // _ElementResizeInstrument should block on firing any events until the Object element has loaded and the _ElementResizeInstrument addedToDom() API has been called. // The former is required in order to allow us to get a handle to hook the resize event of the <object> element's content window. // The latter is for cross browser consistency. Some browsers will load the <object> element sync or async as soon as its added to the DOM. // Other browsers will not load the element until it is added to the DOM and the data property has been set on the <object>. If the element // hasn't already loaded when addedToDom is called, we can set the data property to kickstart the loading process. The function is only expected to be called once. if (!this._disposed) { var objEl = this.element; if (!_Global.document.body.contains(objEl)) { // In IE and Edge the <object> needs to be in the DOM before we set the data property or else the element will get into state where it can never be loaded. throw new _ErrorFromName("WinJS.UI._ElementResizeInstrument", "ElementResizeInstrument initialization failed"); } else { if (_Log.log && _ElementUtilities._getComputedStyle(objEl.parentElement).position === "static") { // Notify if the parentElement is not positioned. It is expected that the _ElementResizeInstrument will // be an immediate child of the element it wants to monitor for size changes. _Log.log("_ElementResizeInstrument can only detect size changes that are made to it's nearest positioned ancestor. " + "Its parent element is not currently positioned.") } if (!this._elementLoaded && isMS) { // If we're in the DOM and the element hasn't loaded yet, some browsers require setting the data property first, // in order to trigger the <object> load event. We MUST only do this after the element has been added to the DOM, // otherwise IE10, IE11 & Edge will NEVER fire the load event no matter what else is done to the <object> element // or its properties. objEl.data = "about:blank"; } this._elementLoadPromise.then(() => { // Once the element has loaded and addedToDom has been called, we can fire our private "_ready" event. this._running = true; this.dispatchEvent(eventNames._ready, null); // The _ElementResizeInstrument uses an <object> element and its contentWindow to detect resize events in whichever element the // _ElementResizeInstrument is appended to. Some browsers will fire an async "resize" event for the <object> element automatically when // it gets added to the DOM, others won't. In both cases it is up to the _ElementResizeHandler to make sure that exactly one async "resize" // is always fired in all browsers. // If we don't see a resize event from the <object> contentWindow within 50ms, assume this environment won't fire one and dispatch our own. var initialResizeTimeout = Promise.timeout(50); var handleInitialResize = () => { this.removeEventListener(eventNames.resize, handleInitialResize); initialResizeTimeout.cancel(); }; this.addEventListener(eventNames.resize, handleInitialResize); initialResizeTimeout .then(() => { this._objectWindowResizeHandler(); }); }); } } } dispose(): void { if (!this._disposed) { this._disposed = true; // Cancel loading state this._elementLoadPromise.cancel(); // Unhook loaded state if (this._objWindow) { // If we had already loaded and can still get a reference to the contentWindow, // unhook our listener from the <object>'s contentWindow to reduce any future noise. this._objWindow.removeEventListener.call(this._objWindow, contentWindowResizeEvent, this._objectWindowResizeHandlerBound); } // Turn off running state this._running = false; } } /** * Adds an event listener to the control. * @param type The type (name) of the event. * @param listener The listener to invoke when the event gets raised. * @param useCapture If true, initiates capture, otherwise false. **/ addEventListener(type: string, listener: Function, useCapture?: boolean): void { // Implementation will be provided by _Events.eventMixin } /** * Raises an event of the specified type and with the specified additional properties. * @param type The type (name) of the event. * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. * @returns true if preventDefault was called on the event. **/ dispatchEvent(type: string, eventProperties: any): boolean { // Implementation will be provided by _Events.eventMixin return false; } /** * Removes an event listener from the control. * @param type The type (name) of the event. * @param listener The listener to remove. * @param useCapture true if capture is to be initiated, otherwise false. **/ removeEventListener(type: string, listener: Function, useCapture?: boolean): void { // Implementation will be provided by _Events.eventMixin } private _objectWindowResizeHandler(): void { if (this._running) { this._batchResizeEvents(() => { this._fireResizeEvent(); }); } } private _batchResizeEvents(handleResizeFn: () => void): void { // Use requestAnimationFrame to batch consecutive resize events. if (this._pendingResizeAnimationFrameId) { _BaseUtils._cancelAnimationFrame(this._pendingResizeAnimationFrameId); } this._pendingResizeAnimationFrameId = _BaseUtils._requestAnimationFrame(() => { handleResizeFn(); }); } private _fireResizeEvent(): void { if (!this._disposed) { this.dispatchEvent(eventNames.resize, null); } } } // addEventListener, removeEventListener, dispatchEvent _Base.Class.mix(_ElementResizeInstrument, _Events.eventMixin);
the_stack
* This is an autogenerated file created by the Stencil compiler. * It contains typing information for all components that exist in this project. */ import { HTMLStencilElement, JSXBase } from "@stencil/core/internal"; import { VitamixId } from "@vtmn/icons/dist/vitamix/font/vitamix"; export namespace Components { interface VtmnBadge { /** * The value in the badge * @type {number} * @defaultValue 0 */ "value"?: number; /** * The variant of the badge. * @type {string} * @defaultValue 'default' */ "variant"?: 'default' | 'brand' | 'reversed' | 'accent'; } interface VtmnButton { /** * Icon to display when it is a button with icon only * @type {VitamixId} * @defaultValue undefined */ "iconAlone": VitamixId; /** * Icon to display on the left hand side of button * @type {VitamixId} * @defaultValue undefined */ "iconLeft": VitamixId; /** * Icon to display on the right hand side of button * @type {VitamixId} * @defaultValue undefined */ "iconRight": VitamixId; /** * The size of the button. * @defaultValue 'medium' */ "size": 'small' | 'medium' | 'large' | 'stretched'; /** * The variant of the button. * @defaultValue 'primary' */ "variant": | 'primary' | 'primary-reversed' | 'secondary' | 'tertiary' | 'ghost' | 'ghost-reversed' | 'conversion'; } interface VtmnCheckbox { /** * The checked state of the checkbox. * @defaultValue false */ "checked": boolean; /** * The disabled state of the checkbox. * @defaultValue false */ "disabled": boolean; /** * The id of the checkbox and its label. */ "identifier": string; /** * The text of the checkbox. */ "labelText": string; /** * The name of the checkbox. */ "name": string; /** * The value of the checkbox. */ "value": string; } interface VtmnLink { /** * The hypertext link * @type {string} * @defaultValue '#' */ "href": string; /** * The size of the link * @type {string} * @defaultValue 'medium' */ "size"?: 'small' | 'medium' | 'large'; /** * Whether the link is standalone * @type {boolean} * @defaultValue false */ "standalone"?: boolean; /** * The target of the link * @type {string} * @defaultValue '_self' */ "target"?: string; /** * Whether the link has an icon * @type {boolean} * @defaultValue false */ "withIcon": boolean; } interface VtmnLoader { /** * The size of the loader. * @type {string} * @defaultValue 'medium' */ "size": 'small' | 'medium' | 'large'; } interface VtmnRadioButton { /** * The checked state of the radio. * @defaultValue false */ "checked": boolean; /** * The disabled state of the radio. * @defaultValue false */ "disabled": boolean; /** * The id of the radio and its label. */ "identifier": string; /** * The text of the radio. */ "labelText": string; /** * The name of the radio. */ "name": string; /** * The value of the radio. */ "value": string; } interface VtmnTextInput { /** * The disabled state of the text-input. */ "disabled": boolean; /** * The error variant state of the text-input. */ "error": boolean; /** * The helper text of the text input. */ "helperText": string; /** * The icon to be displayed */ "icon": string; /** * The id of the text input. */ "identifier": string; /** * The label text of the text input. */ "labelText": string; /** * Is the text-input multiline or not. */ "multiline": boolean; /** * The placeholder of the text input. */ "placeholder": string; /** * The valid variant state of the text-input. */ "valid": boolean; } interface VtmnToggle { /** * The checked state of the toggle. * @defaultValue false */ "checked": boolean; /** * The disabled state of the toggle. * @defaultValue false */ "disabled": boolean; /** * The id of the toggle and its label. */ "identifier": string; /** * The text of the toggle. */ "labelText": string; /** * The size of the toggle. */ "size": 'small' | 'medium'; } } declare global { interface HTMLVtmnBadgeElement extends Components.VtmnBadge, HTMLStencilElement { } var HTMLVtmnBadgeElement: { prototype: HTMLVtmnBadgeElement; new (): HTMLVtmnBadgeElement; }; interface HTMLVtmnButtonElement extends Components.VtmnButton, HTMLStencilElement { } var HTMLVtmnButtonElement: { prototype: HTMLVtmnButtonElement; new (): HTMLVtmnButtonElement; }; interface HTMLVtmnCheckboxElement extends Components.VtmnCheckbox, HTMLStencilElement { } var HTMLVtmnCheckboxElement: { prototype: HTMLVtmnCheckboxElement; new (): HTMLVtmnCheckboxElement; }; interface HTMLVtmnLinkElement extends Components.VtmnLink, HTMLStencilElement { } var HTMLVtmnLinkElement: { prototype: HTMLVtmnLinkElement; new (): HTMLVtmnLinkElement; }; interface HTMLVtmnLoaderElement extends Components.VtmnLoader, HTMLStencilElement { } var HTMLVtmnLoaderElement: { prototype: HTMLVtmnLoaderElement; new (): HTMLVtmnLoaderElement; }; interface HTMLVtmnRadioButtonElement extends Components.VtmnRadioButton, HTMLStencilElement { } var HTMLVtmnRadioButtonElement: { prototype: HTMLVtmnRadioButtonElement; new (): HTMLVtmnRadioButtonElement; }; interface HTMLVtmnTextInputElement extends Components.VtmnTextInput, HTMLStencilElement { } var HTMLVtmnTextInputElement: { prototype: HTMLVtmnTextInputElement; new (): HTMLVtmnTextInputElement; }; interface HTMLVtmnToggleElement extends Components.VtmnToggle, HTMLStencilElement { } var HTMLVtmnToggleElement: { prototype: HTMLVtmnToggleElement; new (): HTMLVtmnToggleElement; }; interface HTMLElementTagNameMap { "vtmn-badge": HTMLVtmnBadgeElement; "vtmn-button": HTMLVtmnButtonElement; "vtmn-checkbox": HTMLVtmnCheckboxElement; "vtmn-link": HTMLVtmnLinkElement; "vtmn-loader": HTMLVtmnLoaderElement; "vtmn-radio-button": HTMLVtmnRadioButtonElement; "vtmn-text-input": HTMLVtmnTextInputElement; "vtmn-toggle": HTMLVtmnToggleElement; } } declare namespace LocalJSX { interface VtmnBadge { /** * The value in the badge * @type {number} * @defaultValue 0 */ "value"?: number; /** * The variant of the badge. * @type {string} * @defaultValue 'default' */ "variant"?: 'default' | 'brand' | 'reversed' | 'accent'; } interface VtmnButton { /** * Icon to display when it is a button with icon only * @type {VitamixId} * @defaultValue undefined */ "iconAlone"?: VitamixId; /** * Icon to display on the left hand side of button * @type {VitamixId} * @defaultValue undefined */ "iconLeft"?: VitamixId; /** * Icon to display on the right hand side of button * @type {VitamixId} * @defaultValue undefined */ "iconRight"?: VitamixId; /** * The size of the button. * @defaultValue 'medium' */ "size"?: 'small' | 'medium' | 'large' | 'stretched'; /** * The variant of the button. * @defaultValue 'primary' */ "variant"?: | 'primary' | 'primary-reversed' | 'secondary' | 'tertiary' | 'ghost' | 'ghost-reversed' | 'conversion'; } interface VtmnCheckbox { /** * The checked state of the checkbox. * @defaultValue false */ "checked"?: boolean; /** * The disabled state of the checkbox. * @defaultValue false */ "disabled"?: boolean; /** * The id of the checkbox and its label. */ "identifier": string; /** * The text of the checkbox. */ "labelText"?: string; /** * The name of the checkbox. */ "name"?: string; /** * The value of the checkbox. */ "value"?: string; } interface VtmnLink { /** * The hypertext link * @type {string} * @defaultValue '#' */ "href"?: string; /** * The size of the link * @type {string} * @defaultValue 'medium' */ "size"?: 'small' | 'medium' | 'large'; /** * Whether the link is standalone * @type {boolean} * @defaultValue false */ "standalone"?: boolean; /** * The target of the link * @type {string} * @defaultValue '_self' */ "target"?: string; /** * Whether the link has an icon * @type {boolean} * @defaultValue false */ "withIcon"?: boolean; } interface VtmnLoader { /** * The size of the loader. * @type {string} * @defaultValue 'medium' */ "size"?: 'small' | 'medium' | 'large'; } interface VtmnRadioButton { /** * The checked state of the radio. * @defaultValue false */ "checked"?: boolean; /** * The disabled state of the radio. * @defaultValue false */ "disabled"?: boolean; /** * The id of the radio and its label. */ "identifier": string; /** * The text of the radio. */ "labelText"?: string; /** * The name of the radio. */ "name"?: string; /** * The value of the radio. */ "value"?: string; } interface VtmnTextInput { /** * The disabled state of the text-input. */ "disabled"?: boolean; /** * The error variant state of the text-input. */ "error"?: boolean; /** * The helper text of the text input. */ "helperText": string; /** * The icon to be displayed */ "icon"?: string; /** * The id of the text input. */ "identifier": string; /** * The label text of the text input. */ "labelText": string; /** * Is the text-input multiline or not. */ "multiline"?: boolean; /** * The placeholder of the text input. */ "placeholder": string; /** * The valid variant state of the text-input. */ "valid"?: boolean; } interface VtmnToggle { /** * The checked state of the toggle. * @defaultValue false */ "checked"?: boolean; /** * The disabled state of the toggle. * @defaultValue false */ "disabled"?: boolean; /** * The id of the toggle and its label. */ "identifier": string; /** * The text of the toggle. */ "labelText"?: string; /** * The size of the toggle. */ "size"?: 'small' | 'medium'; } interface IntrinsicElements { "vtmn-badge": VtmnBadge; "vtmn-button": VtmnButton; "vtmn-checkbox": VtmnCheckbox; "vtmn-link": VtmnLink; "vtmn-loader": VtmnLoader; "vtmn-radio-button": VtmnRadioButton; "vtmn-text-input": VtmnTextInput; "vtmn-toggle": VtmnToggle; } } export { LocalJSX as JSX }; declare module "@stencil/core" { export namespace JSX { interface IntrinsicElements { "vtmn-badge": LocalJSX.VtmnBadge & JSXBase.HTMLAttributes<HTMLVtmnBadgeElement>; "vtmn-button": LocalJSX.VtmnButton & JSXBase.HTMLAttributes<HTMLVtmnButtonElement>; "vtmn-checkbox": LocalJSX.VtmnCheckbox & JSXBase.HTMLAttributes<HTMLVtmnCheckboxElement>; "vtmn-link": LocalJSX.VtmnLink & JSXBase.HTMLAttributes<HTMLVtmnLinkElement>; "vtmn-loader": LocalJSX.VtmnLoader & JSXBase.HTMLAttributes<HTMLVtmnLoaderElement>; "vtmn-radio-button": LocalJSX.VtmnRadioButton & JSXBase.HTMLAttributes<HTMLVtmnRadioButtonElement>; "vtmn-text-input": LocalJSX.VtmnTextInput & JSXBase.HTMLAttributes<HTMLVtmnTextInputElement>; "vtmn-toggle": LocalJSX.VtmnToggle & JSXBase.HTMLAttributes<HTMLVtmnToggleElement>; } } }
the_stack
import React from 'react'; import { Surface } from 'recharts'; import { findAllByType, findChildByType, getPresentationAttributes, isChildrenEqual, validateWidthHeight, } from 'recharts/lib/util/ReactUtils'; import { intersectionArea, intersectionAreaPath, normalizeSolution, scaleSolution, venn, } from '@upsetjs/venn.js'; import { Tooltip } from '../../Tooltip'; import VennArea from './VennArea'; import VennIntersection from './VennIntersection'; import { ICirclesObj, IVennChartProps, IVennChartState, IVennDataItem, IVennPayloadItem, ICirclesObjItem, } from './interface/VennChart'; import fire from '@semcore/utils/lib/fire'; import assignProps from '@semcore/utils/lib/assignProps'; import { sstyled } from '@semcore/core'; // eslint-disable-next-line import/no-extraneous-dependencies import cn from 'classnames'; import styles from './style/venn-tooltip-label.shadow.css'; import chartStyles from '../../style/chart.shadow.css'; export default class VennChart extends React.PureComponent<IVennChartProps, IVennChartState> { static displayName = 'VennChart'; static defaultProps = { padding: 2, orientation: Math.PI / 2, orientationOrder: (c1, c2) => c2.radius - c1.radius, minAreaRadius: 6, tooltipLabelIntersectionSizeFormatter: (v) => v, }; static getActualData(props) { const { data, children } = props; const circleItems = findAllByType(children, VennArea); // Mapping data to children to define actual sets const actualSets = circleItems.reduce((acc, circle) => { if (circle.props.hidden) { return acc; } const { name } = circle.props; const circleDataItem = data.find((item) => item.name === name); if (!circleDataItem || circleDataItem.sets.length > 1) { return acc; } return [...acc, ...circleDataItem.sets]; }, []); // filtering data by actual sets return data.filter((item) => item.sets.every((set) => actualSets.includes(set))); } static getDerivedStateFromProps(props: IVennChartProps, state: IVennChartState) { const { children, data } = props; const { activeNode, isTooltipActive } = state; if (data !== state.data || !isChildrenEqual(children, state.children)) { const actualData = VennChart.getActualData(props); return { data, children, actualData, activeNode, isTooltipActive, }; } return null; } private circles: ICirclesObj; private circlesLayout: ICirclesObjItem[]; constructor(props) { super(props); const { data, children } = props; this.state = { data, children, actualData: VennChart.getActualData(props), activeNode: null, isTooltipActive: false, }; } handleMouseEnter = (nodeProps) => (e) => { const { children } = this.state; const tooltip = findChildByType(children, Tooltip); this.setState({ activeNode: nodeProps, isTooltipActive: !!tooltip }, () => fire(this, 'onMouseEnter', e, this.generatePayload()), ); }; handleMouseLeave = (e) => { this.setState({ activeNode: null, isTooltipActive: false }, () => { fire(this, 'onMouseLeave', e, this.generatePayload()); }); }; handleClick = (e) => { fire(this, 'onClick', e, this.generatePayload()); }; dataToCirclesLayoutObj = (): ICirclesObj => { const { actualData } = this.state; const { width, height, padding, orientation, orientationOrder, minAreaRadius } = this.props; if (actualData.length === 0) { this.circles = {}; return null; } const circles = venn(actualData); const normalisedCircles = normalizeSolution(circles, orientation, orientationOrder); const scaledCircles = scaleSolution(normalisedCircles, width, height, padding); Object.keys(scaledCircles).forEach((key) => { const circleRadius = scaledCircles[key].radius; scaledCircles[key].radius = Math.max(minAreaRadius, circleRadius); //@ts-ignore scaledCircles[key].data = getElementDataByKey(actualData, key); }); //@ts-ignore this.circles = scaledCircles; }; getCirclesLayout() { const { children } = this.state; // tslint:disable-next-line:no-this-assignment const { circles } = this; const circleItems = findAllByType(children, VennArea); this.circlesLayout = Object.keys(circles).map((circle) => { const circleName = circles[circle].data.name; const circleNode = circleItems.find(({ props }) => circleName === props.name); return { name: circleName, node: circleNode, ...circles[circle], }; }); } renderCircle = (circleProps) => { const { activeNode } = this.state; const { x, y, radius, data, name, node } = circleProps; const isNodeActive = activeNode && name === activeNode.name; const nodeProps = { ...node.props, cx: x, cy: y, r: radius, key: `venn-area-${name}`, size: data.size, active: isNodeActive, data, }; const nodeHandlers = { onMouseEnter: this.handleMouseEnter(nodeProps), onMouseLeave: this.handleMouseLeave, onClick: this.handleClick, }; return React.cloneElement(node, assignProps(nodeProps, nodeHandlers)); }; renderCircles() { return this.circlesLayout.map(this.renderCircle); } getIntersectionsLayout() { const { actualData } = this.state; const circlesWithIntersections = actualData.filter((item) => item.sets.length > 1); return circlesWithIntersections.map((intersection) => { const { sets, name, size } = intersection; const circleNodes = sets.map((set) => this.circlesLayout.find((circle) => circle.data.sets[0] === set), ); const path: string = intersectionAreaPath(circleNodes); return { d: path, circles: circleNodes, name, size, sets, }; }); } renderIntersection = (intersectionProps) => { const { sets } = intersectionProps; const { activeNode } = this.state; const isNodeActive = activeNode && activeNode.sets && stringArrayIsEqual(sets, activeNode.sets); const nodeHandlers = { onMouseEnter: this.handleMouseEnter(intersectionProps), onMouseLeave: this.handleMouseLeave, onClick: this.handleClick, }; const nodeProps = { active: isNodeActive, key: `venn-intersection-${sets.join('-')}`, ...assignProps(intersectionProps, nodeHandlers), }; return <VennIntersection {...nodeProps} />; }; renderIntersections() { const intersections = this.getIntersectionsLayout(); return intersections.map(this.renderIntersection); } getAreaTooltipCoordinate(activeNode) { if (!activeNode || !activeNode.cx || !activeNode.cy) { return null; } return { x: (activeNode.cx as number) + (activeNode.r as number), y: (activeNode.cy as number) + (activeNode.r as number) / 2, }; } getIntersectionTooltipCoordinate(activeNode) { if (!activeNode || !activeNode.circles) { return null; } const stats = {}; intersectionArea(activeNode.circles, stats); // @ts-ignore const { innerPoints } = stats; return innerPoints.reduce( (acc, { x, y }) => { if (x > acc.x) { acc.x = x; } if (y > acc.y) { acc.y = y; } return acc; }, { x: 0, y: 0 }, ); } generatePayload(): IVennPayloadItem[] { const { data } = this.props; const { activeNode } = this.state; if (!activeNode) { return []; } return activeNode.name ? [ { payload: activeNode.data, name: activeNode.name, value: activeNode.size, fill: activeNode.fill, data, }, ] : activeNode.circles.map((circle) => ({ payload: circle.data, // @ts-ignore name: circle.name, value: circle.data.size, // @ts-ignore fill: circle.node.props.fill, data, })); } renderTooltip() { const { children } = this.props; const tooltipItem = findChildByType(children, Tooltip); if (!tooltipItem) { return null; } const { width, height } = this.props; const { isTooltipActive, activeNode } = this.state; const viewBox = { x: 0, y: 0, width, height }; const coordinate = this.getAreaTooltipCoordinate(activeNode) || this.getIntersectionTooltipCoordinate(activeNode); const payload = isTooltipActive ? this.generatePayload() : []; return React.cloneElement(tooltipItem, { label: 'Overlap', labelFormatter: this.formatTooltipLabel, ...tooltipItem.props, viewBox, active: isTooltipActive, coordinate, payload, }); } formatTooltipLabel = (label, payload) => { const { tooltipLabelIntersectionSizeFormatter } = this.props; if (!payload || payload.length < 2) { return null; } const totalValue = payload.reduce((acc, item) => acc + item.payload.size, 0); const sets = payload.reduce((acc, item) => { return acc.concat(item.payload.sets); }, []); const { size } = payload[0].data.find((dataItem) => sets.every((set) => dataItem.sets.includes(set)), ); const percent = size / (totalValue / 100); const finalPercentage = percent < 1 ? '< 1' : percent.toFixed(0); const STooltipLabel = 'span'; const STooltipLabelTitle = 'span'; const STooltipLabelPercentage = 'span'; const STooltipLabelValue = 'span'; return sstyled(styles)( <STooltipLabel> <STooltipLabelTitle>{label}</STooltipLabelTitle> <STooltipLabelPercentage>{finalPercentage}%</STooltipLabelPercentage> <STooltipLabelValue>{tooltipLabelIntersectionSizeFormatter(size)}</STooltipLabelValue> </STooltipLabel>, ); }; render() { if (!validateWidthHeight(this)) { return null; } this.dataToCirclesLayoutObj(); // elegant crutch 🤷‍ this.getCirclesLayout(); const { className, width, height, style, ...other } = this.props; const attrs = getPresentationAttributes(other); const SChart = 'div'; return sstyled(chartStyles)( <SChart className={cn('recharts-wrapper', className)} style={{ position: 'relative', cursor: 'default', width, height, ...style }} > <Surface {...attrs} width={width} height={height}> {this.renderCircles()} {this.renderIntersections()} </Surface> {this.renderTooltip()} </SChart>, ); } } function stringArrayIsEqual(arr1: string[], arr2: string[]) { if (arr1.length !== arr2.length) { return false; } return arr1.every((item) => arr2.includes(item)); } function getElementDataByKey(data: IVennDataItem[], key: string) { return data.find((el) => { return el.sets.length === 1 && el.sets[0] === key; }); }
the_stack
import { relative } from 'path' import traverse, { NodePath, Visitor } from '@babel/traverse' import * as t from '@babel/types' import { PseudoStyles, StaticConfigParsed, TamaguiInternalConfig, getSplitStyles, mediaQueryConfig, normalizeStyleObject, proxyThemeVariables, pseudos, rnw, stylePropsTransform, } from '@tamagui/core-node' import { difference, pick } from 'lodash' import type { ViewStyle } from 'react-native' import { FAILED_EVAL } from '../constants' import { ExtractedAttr, ExtractedAttrAttr, ExtractedAttrStyle, ExtractorParseProps, Ternary, } from '../types' import { createEvaluator, createSafeEvaluator } from './createEvaluator' import { evaluateAstNode } from './evaluateAstNode' import { attrStr, findComponentName, isInsideTamagui, isPresent, objToStr } from './extractHelpers' import { findTopmostFunction } from './findTopmostFunction' import { getStaticBindingsForScope } from './getStaticBindingsForScope' import { literalToAst } from './literalToAst' import { loadTamagui } from './loadTamagui' import { logLines } from './logLines' import { normalizeTernaries } from './normalizeTernaries' import { removeUnusedHooks } from './removeUnusedHooks' import { timer } from './timer' import { validAccessibilityAttributes, validHTMLAttributes } from './validHTMLAttributes' const UNTOUCHED_PROPS = { key: true, style: true, className: true, } const INLINE_EXTRACTABLE = { ref: 'ref', key: 'key', onPress: 'onClick', onHoverIn: 'onMouseEnter', onHoverOut: 'onMouseLeave', onPressIn: 'onMouseDown', onPressOut: 'onMouseUp', } const isAttr = (x: ExtractedAttr): x is ExtractedAttrAttr => x.type === 'attr' const validHooks = { useMedia: true, useTheme: true, } export type Extractor = ReturnType<typeof createExtractor> const createTernary = (x: Ternary) => x export function createExtractor() { if (!process.env.TAMAGUI_TARGET) { console.log('⚠️ Please set process.env.TAMAGUI_TARGET to either "web" or "native"') process.exit(1) } const shouldAddDebugProp = // really basic disable this for next.js because it messes with ssr !process.env.npm_package_dependencies_next && process.env.TAMAGUI_TARGET !== 'native' && process.env.IDENTIFY_TAGS !== 'false' && (process.env.NODE_ENV === 'development' || process.env.DEBUG || process.env.IDENTIFY_TAGS) let loadedTamaguiConfig: TamaguiInternalConfig let hasLogged = false return { getTamagui() { return loadedTamaguiConfig }, parse: ( fileOrPath: NodePath<t.Program> | t.File, { config = 'tamagui.config.ts', importsWhitelist = ['constants.js'], evaluateVars = true, shouldPrintDebug = false, sourcePath = '', onExtractTag, getFlattenedNode, disable, disableExtraction, disableExtractInlineMedia, disableExtractVariables, disableDebugAttr, prefixLogs, excludeProps, target, ...props }: ExtractorParseProps ) => { if (disable) { return null } if (sourcePath === '') { throw new Error(`Must provide a source file name`) } if (!Array.isArray(props.components)) { throw new Error(`Must provide components array with list of Tamagui component modules`) } const isTargetingHTML = target === 'html' const ogDebug = shouldPrintDebug const tm = timer() // we require it after parse because we need to set some global/env stuff before importing // otherwise we'd import `rnw` and cause it to evaluate react-native-web which causes errors const { components, tamaguiConfig } = loadTamagui({ config, components: props.components || ['tamagui'], }) if (shouldPrintDebug === 'verbose') { console.log('tamagui.config.ts:', { components, config }) } tm.mark('load-tamagui', shouldPrintDebug === 'verbose') loadedTamaguiConfig = tamaguiConfig as any const defaultTheme = proxyThemeVariables( tamaguiConfig.themes[Object.keys(tamaguiConfig.themes)[0]] ) const body = fileOrPath.type === 'Program' ? fileOrPath.get('body') : fileOrPath.program.body /** * Step 1: Determine if importing any statically extractable components */ const isInternalImport = (importStr: string) => { return isInsideTamagui(sourcePath) && importStr[0] === '.' } const validComponents: { [key: string]: any } = Object.keys(components) // check if uppercase to avoid hitting media query proxy before init .filter((key) => key[0].toUpperCase() === key[0] && !!components[key]?.staticConfig) .reduce((obj, name) => { obj[name] = components[name] return obj }, {}) if (shouldPrintDebug === 'verbose') { console.log('validComponents', Object.keys(validComponents)) } let doesUseValidImport = false let hasImportedTheme = false for (const bodyPath of body) { if (bodyPath.type !== 'ImportDeclaration') continue const node = ('node' in bodyPath ? bodyPath.node : bodyPath) as any const from = node.source.value const isValidImport = props.components.includes(from) || isInternalImport(from) if (isValidImport) { const isValidComponent = node.specifiers.some((specifier) => { const name = specifier.local.name return !!(validComponents[name] || validHooks[name]) }) if (shouldPrintDebug === 'verbose') { console.log('import from', from, { isValidComponent }) } if (isValidComponent) { doesUseValidImport = true break } } } if (shouldPrintDebug) { console.log(sourcePath, { doesUseValidImport }) } if (!doesUseValidImport) { return null } tm.mark('import-check', shouldPrintDebug === 'verbose') let couldntParse = false const modifiedComponents = new Set<NodePath<any>>() // only keeping a cache around per-file, reset it if it changes const bindingCache: Record<string, string | null> = {} const callTraverse = (a: Visitor<{}>) => { return fileOrPath.type === 'File' ? traverse(fileOrPath, a) : fileOrPath.traverse(a) } /** * Step 2: Statically extract from JSX < /> nodes */ let programPath: NodePath<t.Program> const res = { flattened: 0, optimized: 0, modified: 0, found: 0, } callTraverse({ Program: { enter(path) { programPath = path }, }, JSXElement(traversePath) { tm.mark('jsx-element', shouldPrintDebug === 'verbose') const node = traversePath.node.openingElement const ogAttributes = node.attributes const componentName = findComponentName(traversePath.scope) const closingElement = traversePath.node.closingElement // skip non-identifier opening elements (member expressions, etc.) if (t.isJSXMemberExpression(closingElement?.name) || !t.isJSXIdentifier(node.name)) { return } // validate its a proper import from tamagui (or internally inside tamagui) const binding = traversePath.scope.getBinding(node.name.name) if (binding) { if (!t.isImportDeclaration(binding.path.parent)) { return } const source = binding.path.parent.source if (!props.components.includes(source.value) && !isInternalImport(source.value)) { return } if (!validComponents[binding.identifier.name]) { return } } const component = validComponents[node.name.name] as { staticConfig?: StaticConfigParsed } if (!component || !component.staticConfig) { return } const originalNodeName = node.name.name // found a valid tag res.found++ const filePath = `./${relative(process.cwd(), sourcePath)}` const lineNumbers = node.loc ? node.loc.start.line + (node.loc.start.line !== node.loc.end.line ? `-${node.loc.end.line}` : '') : '' const tagId = [componentName, `${node.name.name}`, `${filePath}:${lineNumbers}`].filter( Boolean ) // debug just one const debugPropValue = node.attributes .filter<t.JSXAttribute>( // @ts-ignore (n) => t.isJSXAttribute(n) && t.isJSXIdentifier(n.name) && n.name.name === 'debug' ) .map((n) => { if (n.value === null) return true if (t.isStringLiteral(n.value)) return n.value.value as 'verbose' return false })[0] if (debugPropValue) { shouldPrintDebug = debugPropValue } try { node.attributes.find( (n) => t.isJSXAttribute(n) && t.isJSXIdentifier(n.name) && n.name.name === 'debug' && n.value === null ) if (shouldPrintDebug) { console.log('\n') console.log('\x1b[33m%s\x1b[0m', `${tagId[0]} | ${tagId[2]} -------------------`) console.log('\x1b[1m', '\x1b[32m', `<${originalNodeName} />`) } // add data-is if (shouldAddDebugProp && !disableDebugAttr) { res.modified++ node.attributes.unshift( t.jsxAttribute(t.jsxIdentifier('data-is'), t.stringLiteral(tagId.join(' '))) ) } const shouldLog = !hasLogged if (shouldLog) { const prefix = ' |' console.log( prefixLogs || prefix, ' total · optimized · flattened ' ) hasLogged = true } if (disableExtraction) { return } const { staticConfig } = component const isTextView = staticConfig.isText || false const validStyles = staticConfig?.validStyles ?? {} function isValidStyleKey(name: string) { return !!( !!validStyles[name] || !!pseudos[name] || staticConfig.variants?.[name] || tamaguiConfig.shorthands[name] || (name[0] === '$' ? !!mediaQueryConfig[name.slice(1)] : false) ) } // find tag="a" tag="main" etc dom indicators let tagName = staticConfig.defaultProps?.tag ?? (isTextView ? 'span' : 'div') traversePath .get('openingElement') .get('attributes') .forEach((path) => { const attr = path.node if (t.isJSXSpreadAttribute(attr)) return if (attr.name.name !== 'tag') return const val = attr.value if (!t.isStringLiteral(val)) return tagName = val.value }) const flatNode = getFlattenedNode({ isTextView, tag: tagName }) const inlineProps = new Set([ ...(props.inlineProps || []), ...(staticConfig.inlineProps || []), ]) const deoptProps = new Set([ // always de-opt animation 'animation', ...(props.deoptProps || []), ...(staticConfig.deoptProps || []), ]) const inlineWhenUnflattened = new Set([...(staticConfig.inlineWhenUnflattened || [])]) // Generate scope object at this level const staticNamespace = getStaticBindingsForScope( traversePath.scope, importsWhitelist, sourcePath, bindingCache, shouldPrintDebug ) const attemptEval = !evaluateVars ? evaluateAstNode : createEvaluator({ // @ts-ignore tamaguiConfig, staticNamespace, sourcePath, traversePath, shouldPrintDebug, }) const attemptEvalSafe = createSafeEvaluator(attemptEval) if (shouldPrintDebug) { console.log(' staticNamespace', Object.keys(staticNamespace).join(', ')) } // // SPREADS SETUP // // TODO restore // const hasDeopt = (obj: Object) => { // return Object.keys(obj).some(isDeoptedProp) // } // flatten any easily evaluatable spreads const flattenedAttrs: (t.JSXAttribute | t.JSXSpreadAttribute)[] = [] traversePath .get('openingElement') .get('attributes') .forEach((path) => { const attr = path.node if (!t.isJSXSpreadAttribute(attr)) { flattenedAttrs.push(attr) return } let arg: any try { arg = attemptEval(attr.argument) } catch (e: any) { if (shouldPrintDebug) { console.log(' couldnt parse spread', e.message) } flattenedAttrs.push(attr) return } if (arg !== undefined) { try { if (typeof arg !== 'object' || arg == null) { if (shouldPrintDebug) { console.log(' non object or null arg', arg) } flattenedAttrs.push(attr) } else { for (const k in arg) { const value = arg[k] // this is a null prop: if (!value && typeof value === 'object') { console.log('shouldnt we handle this?', k, value, arg) continue } flattenedAttrs.push( t.jsxAttribute( t.jsxIdentifier(k), t.jsxExpressionContainer(literalToAst(value)) ) ) } } } catch (err) { console.warn('cant parse spread, caught err', err) couldntParse = true } } }) if (couldntParse) { return } tm.mark('jsx-element-flattened', shouldPrintDebug === 'verbose') // set flattened node.attributes = flattenedAttrs // add in NON-STYLE default props if (staticConfig.defaultProps) { for (const key in staticConfig.defaultProps) { if (isValidStyleKey(key)) { continue } const serialize = require('babel-literal-to-ast') const val = staticConfig.defaultProps[key] try { const serializedDefaultProp = serialize(val) node.attributes.unshift( t.jsxAttribute( t.jsxIdentifier(key), typeof val === 'string' ? t.stringLiteral(val) : t.jsxExpressionContainer(serializedDefaultProp) ) ) } catch (err) { console.warn( `⚠️ Error evaluating default prop for component ${node.name.name}, prop ${key}\n error: ${err}\n value:`, val, '\n defaultProps:', staticConfig.defaultProps ) } } } let attrs: ExtractedAttr[] = [] let shouldDeopt = false const inlined = new Map<string, any>() let hasSetOptimized = false const inlineWhenUnflattenedOGVals = {} // RUN first pass // normalize all conditionals so we can evaluate away easier later // at the same time lets normalize shorthand media queries into spreads: // that way we can parse them with the same logic later on // // {...media.sm && { color: x ? 'red' : 'blue' }} // => {...media.sm && x && { color: 'red' }} // => {...media.sm && !x && { color: 'blue' }} // // $sm={{ color: 'red' }} // => {...media.sm && { color: 'red' }} // // $sm={{ color: x ? 'red' : 'blue' }} // => {...media.sm && x && { color: 'red' }} // => {...media.sm && !x && { color: 'blue' }} attrs = traversePath .get('openingElement') .get('attributes') .flatMap((path) => { try { const res = evaluateAttribute(path) tm.mark('jsx-element-evaluate-attr', shouldPrintDebug === 'verbose') if (!res) { path.remove() } return res } catch (err: any) { if (shouldPrintDebug) { console.log('Error extracting attribute', err.message, err.stack) console.log('node', path.node) } return { type: 'attr', value: path.node, } as const } }) .flat(4) .filter(isPresent) if (shouldPrintDebug) { console.log(' - attrs (before):\n', logLines(attrs.map(attrStr).join(', '))) } // START function evaluateAttribute function evaluateAttribute( path: NodePath<t.JSXAttribute | t.JSXSpreadAttribute> ): ExtractedAttr | ExtractedAttr[] | null { const attribute = path.node const attr: ExtractedAttr = { type: 'attr', value: attribute } // ...spreads if (t.isJSXSpreadAttribute(attribute)) { const arg = attribute.argument const conditional = t.isConditionalExpression(arg) ? // <YStack {...isSmall ? { color: 'red } : { color: 'blue }} ([arg.test, arg.consequent, arg.alternate] as const) : t.isLogicalExpression(arg) && arg.operator === '&&' ? // <YStack {...isSmall && { color: 'red }} ([arg.left, arg.right, null] as const) : null if (conditional) { const [test, alt, cons] = conditional if (!test) throw new Error(`no test`) if ([alt, cons].some((side) => side && !isExtractable(side))) { if (shouldPrintDebug) { console.log('not extractable', alt, cons) } return attr } // split into individual ternaries per object property return [ ...(createTernariesFromObjectProperties(test, alt) || []), ...((cons && createTernariesFromObjectProperties(t.unaryExpression('!', test), cons)) || []), ].map((ternary) => ({ type: 'ternary', value: ternary, })) } } // END ...spreads // directly keep these // couldn't evaluate spread, undefined name, or name is not string if ( t.isJSXSpreadAttribute(attribute) || !attribute.name || typeof attribute.name.name !== 'string' ) { if (shouldPrintDebug) { console.log(' ! inlining, spread attr') } inlined.set(`${Math.random()}`, 'spread') return attr } const name = attribute.name.name if (excludeProps?.has(name)) { if (shouldPrintDebug) { console.log(' excluding prop', name) } return null } if (inlineProps.has(name)) { inlined.set(name, name) if (shouldPrintDebug) { console.log(' ! inlining, inline prop', name) } return attr } // can still optimize the object... see hoverStyle on native if (deoptProps.has(name)) { shouldDeopt = true inlined.set(name, name) if (shouldPrintDebug) { console.log(' ! inlining, deopted prop', name) } return attr } // pass className, key, and style props through untouched if (UNTOUCHED_PROPS[name]) { return attr } if (INLINE_EXTRACTABLE[name]) { inlined.set(name, INLINE_EXTRACTABLE[name]) return attr } if (name.startsWith('data-')) { return attr } // shorthand media queries if (name[0] === '$' && t.isJSXExpressionContainer(attribute?.value)) { // allow disabling this extraction if (disableExtractInlineMedia) { return attr } const shortname = name.slice(1) if (mediaQueryConfig[shortname]) { const expression = attribute.value.expression if (!t.isJSXEmptyExpression(expression)) { const ternaries = createTernariesFromObjectProperties( t.stringLiteral(shortname), expression, { inlineMediaQuery: shortname, } ) if (ternaries) { return ternaries.map((value) => ({ type: 'ternary', value, })) } } } } const [value, valuePath] = (() => { if (t.isJSXExpressionContainer(attribute?.value)) { return [attribute.value.expression!, path.get('value')!] as const } else { return [attribute.value!, path.get('value')!] as const } })() const remove = () => { Array.isArray(valuePath) ? valuePath.map((p) => p.remove()) : valuePath.remove() } if (name === 'ref') { if (shouldPrintDebug) { console.log(' ! inlining, ref', name) } inlined.set('ref', 'ref') return attr } if (name === 'tag') { return { type: 'attr', value: path.node, } } // native shouldn't extract variables if (disableExtractVariables) { if (value) { if (value.type === 'StringLiteral' && value.value[0] === '$') { if (shouldPrintDebug) { console.log(` ! inlining, native disable extract: ${name} =`, value.value) } inlined.set(name, true) return attr } } } if (name === 'theme') { inlined.set('theme', attr.value) return attr } // if value can be evaluated, extract it and filter it out const styleValue = attemptEvalSafe(value) // never flatten if a prop isn't a valid static attribute // only post prop-mapping if (!isValidStyleKey(name)) { let keys = [name] let out: any = null if (staticConfig.propMapper) { // for now passing empty props {}, a bit odd, need to at least document // for now we don't expose custom components so just noting behavior out = staticConfig.propMapper( name, styleValue, defaultTheme, staticConfig.defaultProps, { resolveVariablesAs: 'auto' } ) if (out) { if (!Array.isArray(out)) { console.warn(`Error expected array but got`, out) couldntParse = true shouldDeopt = true } else { out = Object.fromEntries(out) } } if (out) { if (isTargetingHTML) { // translate to DOM-compat out = rnw.createDOMProps(isTextView ? 'span' : 'div', out) // remove className - we dont use rnw styling delete out.className } keys = Object.keys(out) } } let didInline = false const attributes = keys.map((key) => { const val = out[key] if (isValidStyleKey(key)) { return { type: 'style', value: { [name]: styleValue }, name, attr: path.node, } as const } if (validHTMLAttributes[key]) { return attr } if (shouldPrintDebug) { console.log(' ! inlining, non-static', key) } didInline = true inlined.set(key, val) return val }) // weird logic whats going on here if (didInline) { if (shouldPrintDebug) { console.log(' bailing flattening due to attributes', attributes) } // bail return attr } // return evaluated attributes return attributes } // FAILED = dynamic or ternary, keep going if (styleValue !== FAILED_EVAL) { if (inlineWhenUnflattened.has(name)) { // preserve original value for restoration inlineWhenUnflattenedOGVals[name] = { styleValue, attr } } if (isValidStyleKey(name)) { if (shouldPrintDebug) { console.log(` style: ${name} =`, styleValue) } if (!(name in staticConfig.defaultProps)) { if (!hasSetOptimized) { res.optimized++ hasSetOptimized = true } } return { type: 'style', value: { [name]: styleValue }, name, attr: path.node, } } else { inlined.set(name, true) return attr } } // ternaries! // binary ternary, we can eventually make this smarter but step 1 // basically for the common use case of: // opacity={(conditional ? 0 : 1) * scale} if (t.isBinaryExpression(value)) { if (shouldPrintDebug) { console.log(` binary expression ${name} = `, value) } const { operator, left, right } = value // if one side is a ternary, and the other side is evaluatable, we can maybe extract const lVal = attemptEvalSafe(left) const rVal = attemptEvalSafe(right) if (shouldPrintDebug) { console.log(` evalBinaryExpression lVal ${String(lVal)}, rVal ${String(rVal)}`) } if (lVal !== FAILED_EVAL && t.isConditionalExpression(right)) { const ternary = addBinaryConditional(operator, left, right) if (ternary) return ternary } if (rVal !== FAILED_EVAL && t.isConditionalExpression(left)) { const ternary = addBinaryConditional(operator, right, left) if (ternary) return ternary } if (shouldPrintDebug) { console.log(` evalBinaryExpression cant extract`) } inlined.set(name, true) return attr } const staticConditional = getStaticConditional(value) if (staticConditional) { if (shouldPrintDebug === 'verbose') { console.log(` static conditional ${name}`, value) } return { type: 'ternary', value: staticConditional } } const staticLogical = getStaticLogical(value) if (staticLogical) { if (shouldPrintDebug === 'verbose') { console.log(` static ternary ${name} = `, value) } return { type: 'ternary', value: staticLogical } } // if we've made it this far, the prop stays inline inlined.set(name, true) if (shouldPrintDebug) { console.log(` ! inline no match ${name}`, value) } // // RETURN ATTR // return attr // attr helpers: function addBinaryConditional( operator: any, staticExpr: any, cond: t.ConditionalExpression ): ExtractedAttr | null { if (getStaticConditional(cond)) { const alt = attemptEval(t.binaryExpression(operator, staticExpr, cond.alternate)) const cons = attemptEval( t.binaryExpression(operator, staticExpr, cond.consequent) ) if (shouldPrintDebug) { console.log(' binaryConditional', cond.test, cons, alt) } return { type: 'ternary', value: { test: cond.test, remove, alternate: { [name]: alt }, consequent: { [name]: cons }, }, } } return null } function getStaticConditional(value: t.Node): Ternary | null { if (t.isConditionalExpression(value)) { try { const aVal = attemptEval(value.alternate) const cVal = attemptEval(value.consequent) if (shouldPrintDebug) { const type = value.test.type console.log(' static ternary', type, cVal, aVal) } return { test: value.test, remove, consequent: { [name]: cVal }, alternate: { [name]: aVal }, } } catch (err: any) { if (shouldPrintDebug) { console.log(' cant eval ternary', err.message) } } } return null } function getStaticLogical(value: t.Node): Ternary | null { if (t.isLogicalExpression(value)) { if (value.operator === '&&') { try { const val = attemptEval(value.right) if (shouldPrintDebug) { console.log(' staticLogical', value.left, name, val) } return { test: value.left, remove, consequent: { [name]: val }, alternate: null, } } catch (err) { if (shouldPrintDebug) { console.log(' cant static eval logical', err) } } } } return null } } // END function evaluateAttribute function isExtractable(obj: t.Node): obj is t.ObjectExpression { return ( t.isObjectExpression(obj) && obj.properties.every((prop) => { if (!t.isObjectProperty(prop)) { console.log('not object prop', prop) return false } const propName = prop.key['name'] if (!isValidStyleKey(propName) && propName !== 'tag') { if (shouldPrintDebug) { console.log(' not a valid style prop!', propName) } return false } return true }) ) } // side = { // color: 'red', // background: x ? 'red' : 'green', // $gtSm: { color: 'green' } // } // => Ternary<test, { color: 'red' }, null> // => Ternary<test && x, { background: 'red' }, null> // => Ternary<test && !x, { background: 'green' }, null> // => Ternary<test && '$gtSm', { color: 'green' }, null> function createTernariesFromObjectProperties( test: t.Expression, side: t.Expression | null, ternaryPartial: Partial<Ternary> = {} ): null | Ternary[] { if (!side) { return null } if (!isExtractable(side)) { throw new Error('not extractable') } return side.properties.flatMap((property) => { if (!t.isObjectProperty(property)) { throw new Error('expected object property') } // handle media queries inside spread/conditional objects if (t.isIdentifier(property.key)) { const key = property.key.name const mediaQueryKey = key.slice(1) const isMediaQuery = key[0] === '$' && mediaQueryConfig[mediaQueryKey] if (isMediaQuery) { if (t.isExpression(property.value)) { const ternaries = createTernariesFromObjectProperties( t.stringLiteral(mediaQueryKey), property.value, { inlineMediaQuery: mediaQueryKey, } ) if (ternaries) { return ternaries.map((value) => ({ ...ternaryPartial, ...value, // ensure media query test stays on left side (see getMediaQueryTernary) test: t.logicalExpression('&&', value.test, test), })) } else { console.log('⚠️ no ternaries?', property) } } else { console.log('⚠️ not expression', property) } } } // this could be a recurse here if we want to get fancy if (t.isConditionalExpression(property.value)) { // merge up into the parent conditional, split into two const [truthy, falsy] = [ t.objectExpression([t.objectProperty(property.key, property.value.consequent)]), t.objectExpression([t.objectProperty(property.key, property.value.alternate)]), ].map((x) => attemptEval(x)) return [ createTernary({ remove() {}, ...ternaryPartial, test: t.logicalExpression('&&', test, property.value.test), consequent: truthy, alternate: null, }), createTernary({ ...ternaryPartial, test: t.logicalExpression( '&&', test, t.unaryExpression('!', property.value.test) ), consequent: falsy, alternate: null, remove() {}, }), ] } const obj = t.objectExpression([t.objectProperty(property.key, property.value)]) const consequent = attemptEval(obj) return createTernary({ remove() {}, ...ternaryPartial, test, consequent, alternate: null, }) }) } // now update to new values node.attributes = attrs.filter(isAttr).map((x) => x.value) if (couldntParse || shouldDeopt) { if (shouldPrintDebug) { console.log(` avoid optimizing:`, { couldntParse, shouldDeopt }) } node.attributes = ogAttributes return } // before deopt, can still optimize const parentFn = findTopmostFunction(traversePath) if (parentFn) { modifiedComponents.add(parentFn) } // combine ternaries let ternaries: Ternary[] = [] attrs = attrs .reduce<(ExtractedAttr | ExtractedAttr[])[]>((out, cur) => { const next = attrs[attrs.indexOf(cur) + 1] if (cur.type === 'ternary') { ternaries.push(cur.value) } if ((!next || next.type !== 'ternary') && ternaries.length) { // finish, process const normalized = normalizeTernaries(ternaries).map( ({ alternate, consequent, ...rest }) => { return { type: 'ternary' as const, value: { ...rest, alternate: alternate || null, consequent: consequent || null, }, } } ) try { return [...out, ...normalized] } finally { if (shouldPrintDebug) { console.log( ` normalizeTernaries (${ternaries.length} => ${normalized.length})` ) } ternaries = [] } } if (cur.type === 'ternary') { return out } out.push(cur) return out }, []) .flat() // flatten logic! // fairly simple check to see if all children are text const hasSpread = node.attributes.some((x) => t.isJSXSpreadAttribute(x)) const hasOnlyStringChildren = !hasSpread && (node.selfClosing || (traversePath.node.children && traversePath.node.children.every((x) => x.type === 'JSXText'))) let themeVal = inlined.get('theme') inlined.delete('theme') const allOtherPropsExtractable = [...inlined].every(([k, v]) => INLINE_EXTRACTABLE[k]) const shouldWrapThme = allOtherPropsExtractable && !!themeVal const canFlattenProps = inlined.size === 0 || shouldWrapThme || allOtherPropsExtractable let shouldFlatten = !shouldDeopt && canFlattenProps && !hasSpread && staticConfig.neverFlatten !== true && (staticConfig.neverFlatten === 'jsx' ? hasOnlyStringChildren : true) if (shouldPrintDebug) { // prettier-ignore console.log(' - flatten?', objToStr({ hasSpread, shouldDeopt, shouldFlatten, canFlattenProps, shouldWrapThme, allOtherPropsExtractable, hasOnlyStringChildren })) } // wrap theme around children on flatten if (shouldFlatten && shouldWrapThme) { if (shouldPrintDebug) { console.log(' - wrapping theme', allOtherPropsExtractable, themeVal) } // remove theme attribute from flattened node attrs = attrs.filter((x) => x.type === 'attr' && t.isJSXAttribute(x.value) && x.value.name.name === 'theme' ? false : true ) // add import if (!hasImportedTheme) { hasImportedTheme = true programPath.node.body.push( t.importDeclaration( [t.importSpecifier(t.identifier('_TamaguiTheme'), t.identifier('Theme'))], t.stringLiteral('@tamagui/core') ) ) } traversePath.replaceWith( t.jsxElement( t.jsxOpeningElement(t.jsxIdentifier('_TamaguiTheme'), [ t.jsxAttribute(t.jsxIdentifier('name'), themeVal.value), ]), t.jsxClosingElement(t.jsxIdentifier('_TamaguiTheme')), [traversePath.node] ) ) } // only if we flatten, ensure the default styles are there if (shouldFlatten && staticConfig.defaultProps) { const defaultStyleAttrs = Object.keys(staticConfig.defaultProps).flatMap((key) => { if (!isValidStyleKey(key)) { return [] } const value = staticConfig.defaultProps[key] const name = tamaguiConfig.shorthands[key] || key if (value === undefined) { console.warn( `⚠️ Error evaluating default style for component, prop ${key} ${value}` ) shouldDeopt = true return } const attr: ExtractedAttrStyle = { type: 'style', name, value: { [name]: value }, } return attr }) as ExtractedAttr[] if (defaultStyleAttrs.length) { attrs = [...defaultStyleAttrs, ...attrs] } } if (shouldDeopt) { node.attributes = ogAttributes return } // insert overrides - this inserts null props for things that are set in classNames // only when not flattening, so the downstream component can skip applying those styles const ensureOverridden = {} if (!shouldFlatten) { for (const cur of attrs) { if (cur.type === 'style') { // TODO need to loop over initial props not just style props for (const key in cur.value) { const shouldEnsureOverridden = !!staticConfig.ensureOverriddenProp?.[key] const isSetInAttrsAlready = attrs.some( (x) => x.type === 'attr' && x.value.type === 'JSXAttribute' && x.value.name.name === key ) if (!isSetInAttrsAlready) { const isVariant = !!staticConfig.variants?.[cur.name || ''] if (isVariant || shouldEnsureOverridden) { ensureOverridden[key] = true } } } } } } if (shouldPrintDebug) { console.log(' - attrs (flattened): \n', logLines(attrs.map(attrStr).join(', '))) console.log(' - ensureOverriden:', Object.keys(ensureOverridden).join(', ')) } // expand shorthands, de-opt variables attrs = attrs.reduce<ExtractedAttr[]>((acc, cur) => { if (!cur) return acc if (cur.type === 'attr' && !t.isJSXSpreadAttribute(cur.value)) { if (shouldFlatten) { if (cur.value.name.name === 'tag') { // remove tag="" return acc } } } if (cur.type !== 'style') { acc.push(cur) return acc } let key = Object.keys(cur.value)[0] const value = cur.value[key] const fullKey = tamaguiConfig.shorthands[key] // expand shorthands if (fullKey) { cur.value = { [fullKey]: value } key = fullKey } // finally we have all styles + expansions, lets see if we need to skip // any and keep them as attrs if (disableExtractVariables) { if (value[0] === '$') { if (shouldPrintDebug) { console.log(` keeping variable inline: ${key} =`, value) } acc.push({ type: 'attr', value: t.jsxAttribute( t.jsxIdentifier(key), t.jsxExpressionContainer(t.stringLiteral(value)) ), }) return acc } } acc.push(cur) return acc }, []) tm.mark('jsx-element-expanded', shouldPrintDebug === 'verbose') if (shouldPrintDebug) { console.log(' - attrs (expanded): \n', logLines(attrs.map(attrStr).join(', '))) } // merge styles, leave undefined values let prev: ExtractedAttr | null = null function mergeStyles(prev: ViewStyle & PseudoStyles, next: ViewStyle & PseudoStyles) { normalizeStyleObject(next) for (const key in next) { // merge pseudos if (pseudos[key]) { prev[key] = prev[key] || {} if (shouldPrintDebug) { if (!next[key] || !prev[key]) { console.log('warn: missing', key, prev, next) } } Object.assign(prev[key], next[key]) } else { prev[key] = next[key] } } } attrs = attrs.reduce<ExtractedAttr[]>((acc, cur) => { if (cur.type === 'style') { const key = Object.keys(cur.value)[0] const value = cur.value[key] const shouldKeepOriginalAttr = // !isStyleAndAttr[key] && !shouldFlatten && // de-opt transform styles so it merges properly if not flattened // we handle this later on // (stylePropsTransform[key] || // de-opt if non-style !validStyles[key] && !pseudos[key] && !key.startsWith('data-') if (shouldKeepOriginalAttr) { if (shouldPrintDebug) { console.log(' - keeping as non-style', key) } prev = cur acc.push({ type: 'attr', value: t.jsxAttribute( t.jsxIdentifier(key), t.jsxExpressionContainer( typeof value === 'string' ? t.stringLiteral(value) : literalToAst(value) ) ), }) acc.push(cur) return acc } if (ensureOverridden[key]) { acc.push({ type: 'attr', value: cur.attr || t.jsxAttribute( t.jsxIdentifier(key), t.jsxExpressionContainer(t.nullLiteral()) ), }) } if (prev?.type === 'style') { mergeStyles(prev.value, cur.value) return acc } } prev = cur acc.push(cur) return acc }, []) const state = { noClassNames: true, focus: false, hover: false, mounted: true, // TODO match logic in createComponent press: false, pressIn: false, } // evaluates all static attributes into a simple object const completeStaticProps = Object.keys(attrs).reduce((acc, index) => { const cur = attrs[index] as ExtractedAttr if (cur.type === 'style') { normalizeStyleObject(cur.value) Object.assign(acc, cur.value) } if (cur.type === 'attr') { if (t.isJSXSpreadAttribute(cur.value)) { return acc } if (!t.isJSXIdentifier(cur.value.name)) { return acc } const key = cur.value.name.name // undefined = boolean true const value = attemptEvalSafe(cur.value.value || t.booleanLiteral(true)) if (value === FAILED_EVAL) { return acc } acc[key] = value } return acc }, {}) const completeProps = { ...staticConfig.defaultProps, ...completeStaticProps, } if (shouldPrintDebug) { console.log(' - attrs (combined 🔀): \n', logLines(attrs.map(attrStr).join(', '))) console.log(' - defaultProps: \n', logLines(objToStr(staticConfig.defaultProps))) console.log(' - completeProps: \n', logLines(objToStr(completeProps))) } // post process const getStyles = (props: Object | null, debugName = '') => { if (!props || !Object.keys(props).length) { if (shouldPrintDebug) console.log(' getStyles() no props') return {} } if (excludeProps && !!excludeProps.size) { for (const key in props) { if (excludeProps.has(key)) { if (shouldPrintDebug) console.log(' delete excluded', key) delete props[key] } } } try { const out = getSplitStyles(props, staticConfig, defaultTheme, { ...state, fallbackProps: completeProps, }) const outStyle = { ...out.style, ...out.pseudos, } omitInvalidStyles(outStyle) if (shouldPrintDebug) { // prettier-ignore console.log(` getStyles ${debugName} (props):\n`, logLines(objToStr(props))) // prettier-ignore console.log(` getStyles ${debugName} (out.viewProps):\n`, logLines(objToStr(out.viewProps))) // prettier-ignore console.log(` getStyles ${debugName} (out.style):\n`, logLines(objToStr(outStyle || {}), true)) } return outStyle } catch (err: any) { console.log('error', err.message, err.stack) return {} } } function omitInvalidStyles(style: any) { if (staticConfig.validStyles) { for (const key in style) { if ( stylePropsTransform[key] || (!staticConfig.validStyles[key] && !pseudos[key] && !/(hoverStyle|focusStyle|pressStyle)$/.test(key)) ) { if (shouldPrintDebug) console.log(' delete invalid style', key) delete style[key] } } } } // used to ensure we pass the entire prop bundle to getStyles const completeStyles = getStyles(completeProps, 'completeStyles') if (!completeStyles) { throw new Error(`Impossible, no styles`) } // any extra styles added in postprocess should be added to first group as they wont be overriden const addInitialStyleKeys = shouldFlatten ? difference(Object.keys(completeStyles), Object.keys(completeStaticProps)) : [] if (addInitialStyleKeys.length) { const toAdd = pick(completeStyles, ...addInitialStyleKeys) const firstGroup = attrs.find((x) => x.type === 'style') if (shouldPrintDebug) { console.log(' toAdd', objToStr(toAdd)) } if (!firstGroup) { attrs.unshift({ type: 'style', value: toAdd }) } else { // because were adding fully processed, remove any unprocessed from first group omitInvalidStyles(firstGroup.value) Object.assign(firstGroup.value, toAdd) } } if (shouldPrintDebug) { // prettier-ignore console.log(' -- addInitialStyleKeys', addInitialStyleKeys.join(', '), { shouldFlatten }) // prettier-ignore console.log(' -- completeStaticProps:\n', logLines(objToStr(completeStaticProps))) // prettier-ignore console.log(' -- completeStyles:\n', logLines(objToStr(completeStyles))) } let getStyleError: any = null // fix up ternaries, combine final style values for (const attr of attrs) { try { if (shouldPrintDebug) console.log(' *', attrStr(attr)) switch (attr.type) { case 'ternary': const a = getStyles(attr.value.alternate, 'ternary.alternate') const c = getStyles(attr.value.consequent, 'ternary.consequent') if (a) attr.value.alternate = a if (c) attr.value.consequent = c if (shouldPrintDebug) console.log(' => tern ', attrStr(attr)) continue case 'style': // prettier-ignore if (shouldPrintDebug) console.log(' * styles in', logLines(objToStr(attr.value))) // expand variants and such // get the keys we need const styles = getStyles(attr.value, 'style') // prettier-ignore if (shouldPrintDebug) console.log(' * styles out', logLines(objToStr(styles))) if (styles) { // but actually resolve them to the full object // TODO media/psuedo merging attr.value = Object.fromEntries( Object.keys(styles).map((k) => [k, completeStyles[k]]) ) } continue } } catch (err) { // any error de-opt getStyleError = err } } tm.mark('jsx-element-styles', shouldPrintDebug === 'verbose') if (getStyleError) { console.log(' ⚠️ postprocessing error, deopt', getStyleError) node.attributes = ogAttributes return node } // final lazy extra loop: const existingStyleKeys = new Set() for (let i = attrs.length - 1; i >= 0; i--) { const attr = attrs[i] // if flattening map inline props to proper flattened names if (shouldFlatten && canFlattenProps) { if (attr.type === 'attr') { if (t.isJSXAttribute(attr.value)) { if (t.isJSXIdentifier(attr.value.name)) { const name = attr.value.name.name if (INLINE_EXTRACTABLE[name]) { // map to HTML only name attr.value.name.name = INLINE_EXTRACTABLE[name] } } } } } // remove duplicate styles // so if you have: // style({ color: 'red' }), ...someProps, style({ color: 'green' }) // this will mutate: // style({}), ...someProps, style({ color: 'green' }) if (attr.type === 'style') { for (const key in attr.value) { if (existingStyleKeys.has(key)) { if (shouldPrintDebug) { console.log(' >> delete existing', key) } delete attr.value[key] } else { existingStyleKeys.add(key) } } } } // inlineWhenUnflattened if (!shouldFlatten) { if (Object.keys(inlineWhenUnflattenedOGVals).length) { for (const [index, attr] of attrs.entries()) { if (attr.type === 'style') { for (const key in attr.value) { const val = inlineWhenUnflattenedOGVals[key] if (val) { // delete the style delete attr.value[key] // and insert it before attrs.splice(index - 1, 0, val.attr) } } } } } } if (shouldFlatten) { // DO FLATTEN if (shouldPrintDebug) { console.log(' [✅] flattening', originalNodeName, flatNode) } node.name.name = flatNode res.flattened++ if (closingElement) { closingElement.name.name = flatNode } } if (shouldPrintDebug) { // prettier-ignore console.log(` ❊❊ inline props (${inlined.size}):`, shouldDeopt ? ' deopted' : '', hasSpread ? ' has spread' : '', staticConfig.neverFlatten ? 'neverFlatten' : '') console.log(' - attrs (end):\n', logLines(attrs.map(attrStr).join(', '))) } onExtractTag({ attrs, node, lineNumbers, filePath, attemptEval, jsxPath: traversePath, originalNodeName, isFlattened: shouldFlatten, programPath, }) } catch (err) { throw err } finally { if (debugPropValue) { shouldPrintDebug = ogDebug } } }, }) tm.mark('jsx-done', shouldPrintDebug === 'verbose') /** * Step 3: Remove dead code from removed media query / theme hooks */ if (modifiedComponents.size) { const all = Array.from(modifiedComponents) if (shouldPrintDebug) { console.log(' [🪝] hook check', all.length) } for (const comp of all) { removeUnusedHooks(comp, shouldPrintDebug) } } tm.done(shouldPrintDebug === 'verbose') return res }, } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormPrice_Level { interface Header extends DevKit.Controls.IHeader { /** Reason for the status of the price list. */ StatusCode: DevKit.Controls.OptionSet; } interface tab_CategoryTab_Sections { CategorySection: DevKit.Controls.Section; } interface tab_General_Sections { Description: DevKit.Controls.Section; price_level_information: DevKit.Controls.Section; } interface tab_Price_List_Items_Sections { pricelistbyproduct: DevKit.Controls.Section; } interface tab_ResourceCategoryMarkupTab_Sections { ResourceCategoryMarkupSection: DevKit.Controls.Section; } interface tab_ResourceCategoryTab_Sections { ResourceCategorySection: DevKit.Controls.Section; } interface tab_TERRITORYRELATIONSHIP_TAB_Sections { service_settings: DevKit.Controls.Section; Territories: DevKit.Controls.Section; } interface tab_CategoryTab extends DevKit.Controls.ITab { Section: tab_CategoryTab_Sections; } interface tab_General extends DevKit.Controls.ITab { Section: tab_General_Sections; } interface tab_Price_List_Items extends DevKit.Controls.ITab { Section: tab_Price_List_Items_Sections; } interface tab_ResourceCategoryMarkupTab extends DevKit.Controls.ITab { Section: tab_ResourceCategoryMarkupTab_Sections; } interface tab_ResourceCategoryTab extends DevKit.Controls.ITab { Section: tab_ResourceCategoryTab_Sections; } interface tab_TERRITORYRELATIONSHIP_TAB extends DevKit.Controls.ITab { Section: tab_TERRITORYRELATIONSHIP_TAB_Sections; } interface Tabs { CategoryTab: tab_CategoryTab; General: tab_General; Price_List_Items: tab_Price_List_Items; ResourceCategoryMarkupTab: tab_ResourceCategoryMarkupTab; ResourceCategoryTab: tab_ResourceCategoryTab; TERRITORYRELATIONSHIP_TAB: tab_TERRITORYRELATIONSHIP_TAB; } interface Body { Tab: Tabs; /** Date on which the price list becomes effective. */ BeginDate: DevKit.Controls.Date; /** Description of the price list. */ Description: DevKit.Controls.String; /** Date that is the last day the price list is valid. */ EndDate: DevKit.Controls.Date; msdyn_BreakHoursBillable: DevKit.Controls.Boolean; /** Shows the price level that this price level was copied from. */ msdyn_CopiedFromPriceLevel: DevKit.Controls.Lookup; /** Select the context for this price level i.e whether it is sales prices, cost prices or purchase prices */ msdyn_Module: DevKit.Controls.OptionSet; /** Select the default unit of role based time on this price list */ msdyn_TimeUnit: DevKit.Controls.Lookup; /** Name of the price list. */ Name: DevKit.Controls.String; /** Unique identifier of the currency associated with the price level. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_pricelevel_msdyn_agreement_PriceList: DevKit.Controls.NavigationItem, nav_msdyn_pricelevel_msdyn_agreementbookingproduct_PriceList: DevKit.Controls.NavigationItem, nav_msdyn_pricelevel_msdyn_agreementbookingservice_PriceList: DevKit.Controls.NavigationItem, nav_msdyn_pricelevel_msdyn_agreementinvoiceproduct_PriceList: DevKit.Controls.NavigationItem, nav_msdyn_pricelevel_msdyn_fieldservicepricelistitem_PriceList: DevKit.Controls.NavigationItem, nav_msdyn_pricelevel_msdyn_resourcecategorymarkuppricelevel_PriceList: DevKit.Controls.NavigationItem, nav_msdyn_pricelevel_msdyn_resourcecategorypricelevel_PriceList: DevKit.Controls.NavigationItem, nav_msdyn_pricelevel_msdyn_rma_PriceList: DevKit.Controls.NavigationItem, nav_msdyn_pricelevel_msdyn_rmaproduct_PriceList: DevKit.Controls.NavigationItem, nav_msdyn_pricelevel_msdyn_transactioncategorypricelevel_PriceList: DevKit.Controls.NavigationItem, nav_msdyn_pricelevel_msdyn_workorder_PriceList: DevKit.Controls.NavigationItem, nav_msdyn_pricelevel_msdyn_workorderproduct_PriceList: DevKit.Controls.NavigationItem, nav_msdyn_pricelevel_msdyn_workorderservice_PriceList: DevKit.Controls.NavigationItem, nav_msdyn_pricelevel_msdyn_workordertype_PriceList: DevKit.Controls.NavigationItem, nav_msdyn_pricelevel_pricelevel_CopiedFromPriceLevel: DevKit.Controls.NavigationItem, navItems: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } interface Grid { ResourceCategoryGrid: DevKit.Controls.Grid; ResourceCategoryMarkupGrid: DevKit.Controls.Grid; CategoryGrid: DevKit.Controls.Grid; pricelistitemsgrid: DevKit.Controls.Grid; RelatedTerritoriesGrid: DevKit.Controls.Grid; } } class FormPrice_Level extends DevKit.IForm { /** * DynamicsCrm.DevKit form Price_Level * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Price_Level */ Body: DevKit.FormPrice_Level.Body; /** The Header section of form Price_Level */ Header: DevKit.FormPrice_Level.Header; /** The Navigation of form Price_Level */ Navigation: DevKit.FormPrice_Level.Navigation; /** The Grid of form Price_Level */ Grid: DevKit.FormPrice_Level.Grid; } namespace FormPrice_List_Quick_Create_5x5 { interface tab_tab_1_Sections { tab_1_column_1_section_1: DevKit.Controls.Section; tab_1_column_2_section_1: DevKit.Controls.Section; tab_1_column_3_section_1: DevKit.Controls.Section; } interface tab_tab_1 extends DevKit.Controls.ITab { Section: tab_tab_1_Sections; } interface Tabs { tab_1: tab_tab_1; } interface Body { Tab: Tabs; /** Date on which the price list becomes effective. */ BeginDate: DevKit.Controls.Date; /** Description of the price list. */ Description: DevKit.Controls.String; /** Date that is the last day the price list is valid. */ EndDate: DevKit.Controls.Date; /** Name of the price list. */ Name: DevKit.Controls.String; /** Unique identifier of the currency associated with the price level. */ TransactionCurrencyId: DevKit.Controls.Lookup; } } class FormPrice_List_Quick_Create_5x5 extends DevKit.IForm { /** * DynamicsCrm.DevKit form Price_List_Quick_Create_5x5 * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Price_List_Quick_Create_5x5 */ Body: DevKit.FormPrice_List_Quick_Create_5x5.Body; } class PriceLevelApi { /** * DynamicsCrm.DevKit PriceLevelApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Date on which the price list becomes effective. */ BeginDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Unique identifier of the user who created the price list. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the pricelevel. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Description of the price list. */ Description: DevKit.WebApi.StringValue; /** Date that is the last day the price list is valid. */ EndDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Freight terms for the price list. */ FreightTermsCode: DevKit.WebApi.OptionSetValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who last modified the price list. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the pricelevel. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; msdyn_BreakHoursBillable: DevKit.WebApi.BooleanValue; /** Shows the price level that this price level was copied from. */ msdyn_CopiedFromPriceLevel: DevKit.WebApi.LookupValue; /** Select the entity for this price level. */ msdyn_Entity: DevKit.WebApi.OptionSetValue; /** Select the context for this price level i.e whether it is sales prices, cost prices or purchase prices */ msdyn_Module: DevKit.WebApi.OptionSetValue; /** Select the default unit of role based time on this price list */ msdyn_TimeUnit: DevKit.WebApi.LookupValue; /** Name of the price list. */ Name: DevKit.WebApi.StringValue; /** Unique identifier for the organization */ OrganizationId: DevKit.WebApi.LookupValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Payment terms to use with the price list. */ PaymentMethodCode: DevKit.WebApi.OptionSetValue; /** Unique identifier of the price list. */ PriceLevelId: DevKit.WebApi.GuidValue; /** Method of shipment for products in the price list. */ ShippingMethodCode: DevKit.WebApi.OptionSetValue; /** Status of the price list. */ StateCode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the price list. */ StatusCode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the price level. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace PriceLevel { enum FreightTermsCode { /** 1 */ Default_Value } enum msdyn_Entity { /** 192350001 */ Customer, /** 192350000 */ Organization, /** 192350003 */ Project, /** 192350002 */ Sales_document } enum msdyn_Module { /** 192350000 */ Cost, /** 192350001 */ Purchase, /** 192350002 */ Sales } enum PaymentMethodCode { /** 1 */ Default_Value } enum ShippingMethodCode { /** 1 */ Default_Value } enum StateCode { /** 0 */ Active, /** 1 */ Inactive } enum StatusCode { /** 100001 */ Active, /** 100002 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Price Level','Price List Quick Create 5x5'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
// clang-format off import 'chrome://settings/settings.js'; import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js'; import {keyEventOn} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import { EDIT_STARTUP_URL_EVENT,SettingsStartupUrlDialogElement,SettingsStartupUrlEntryElement, SettingsStartupUrlsPageElement, StartupUrlsPageBrowserProxy, StartupUrlsPageBrowserProxyImpl} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {TestBrowserProxy} from 'chrome://webui-test/test_browser_proxy.js'; // clang-format on class TestStartupUrlsPageBrowserProxy extends TestBrowserProxy implements StartupUrlsPageBrowserProxy { private urlIsValid_: boolean = true; constructor() { super([ 'addStartupPage', 'editStartupPage', 'loadStartupPages', 'removeStartupPage', 'useCurrentPages', 'validateStartupPage', ]); } setUrlValidity(isValid: boolean) { this.urlIsValid_ = isValid; } addStartupPage(url: string) { this.methodCalled('addStartupPage', url); return Promise.resolve(this.urlIsValid_); } editStartupPage(modelIndex: number, url: string) { this.methodCalled('editStartupPage', [modelIndex, url]); return Promise.resolve(this.urlIsValid_); } loadStartupPages() { this.methodCalled('loadStartupPages'); } removeStartupPage(modelIndex: number) { this.methodCalled('removeStartupPage', modelIndex); } useCurrentPages() { this.methodCalled('useCurrentPages'); } validateStartupPage(url: string) { this.methodCalled('validateStartupPage', url); return Promise.resolve(this.urlIsValid_); } } suite('StartupUrlDialog', function() { let dialog: SettingsStartupUrlDialogElement; let browserProxy: TestStartupUrlsPageBrowserProxy; /** * Triggers an 'input' event on the given text input field, which triggers * validation to occur. */ function pressSpace(element: HTMLElement) { // The actual key code is irrelevant for these tests. keyEventOn(element, 'input', 32 /* space key code */); } setup(function() { browserProxy = new TestStartupUrlsPageBrowserProxy(); StartupUrlsPageBrowserProxyImpl.setInstance(browserProxy); document.body.innerHTML = ''; dialog = document.createElement('settings-startup-url-dialog'); }); teardown(function() { dialog.remove(); }); test('Initialization_Add', function() { document.body.appendChild(dialog); flush(); assertTrue(dialog.$.dialog.open); // Assert that the "Add" button is disabled. const actionButton = dialog.$.actionButton; assertTrue(!!actionButton); assertTrue(actionButton.disabled); // Assert that the text field is empty. const inputElement = dialog.$.url; assertTrue(!!inputElement); assertEquals('', inputElement.value); }); test('Initialization_Edit', function() { dialog.model = createSampleUrlEntry(); document.body.appendChild(dialog); assertTrue(dialog.$.dialog.open); // Assert that the "Edit" button is enabled. const actionButton = dialog.$.actionButton; assertTrue(!!actionButton); assertFalse(actionButton.disabled); // Assert that the text field is pre-populated. const inputElement = dialog.$.url; assertTrue(!!inputElement); assertEquals(dialog.model.url, inputElement.value); }); // Test that validation occurs as the user is typing, and that the action // button is updated accordingly. test('Validation', async function() { document.body.appendChild(dialog); const actionButton = dialog.$.actionButton; assertTrue(actionButton.disabled); const inputElement = dialog.$.url; const expectedUrl = 'dummy-foo.com'; inputElement.value = expectedUrl; browserProxy.setUrlValidity(false); pressSpace(inputElement); const url = await browserProxy.whenCalled('validateStartupPage'); assertEquals(expectedUrl, url); assertTrue(actionButton.disabled); assertTrue(!!inputElement.invalid); browserProxy.setUrlValidity(true); browserProxy.resetResolver('validateStartupPage'); pressSpace(inputElement); await browserProxy.whenCalled('validateStartupPage'); assertFalse(actionButton.disabled); assertFalse(!!inputElement.invalid); }); /** * Tests that the appropriate browser proxy method is called when the action * button is tapped. */ async function testProxyCalled(proxyMethodName: string) { const actionButton = dialog.$.actionButton; actionButton.disabled = false; // Test that the dialog remains open if the user somehow manages to submit // an invalid URL. browserProxy.setUrlValidity(false); actionButton.click(); await browserProxy.whenCalled(proxyMethodName); assertTrue(dialog.$.dialog.open); // Test that dialog is closed if the user submits a valid URL. browserProxy.setUrlValidity(true); browserProxy.resetResolver(proxyMethodName); actionButton.click(); await browserProxy.whenCalled(proxyMethodName); assertFalse(dialog.$.dialog.open); } test('AddStartupPage', async function() { document.body.appendChild(dialog); await testProxyCalled('addStartupPage'); }); test('EditStartupPage', async function() { dialog.model = createSampleUrlEntry(); document.body.appendChild(dialog); await testProxyCalled('editStartupPage'); }); test('Enter key submits', async function() { document.body.appendChild(dialog); // Input a URL and force validation. const inputElement = dialog.$.url; inputElement.value = 'foo.com'; pressSpace(inputElement); await browserProxy.whenCalled('validateStartupPage'); keyEventOn(inputElement, 'keypress', 13, undefined, 'Enter'); await browserProxy.whenCalled('addStartupPage'); }); }); suite('StartupUrlsPage', function() { let page: SettingsStartupUrlsPageElement; let browserProxy: TestStartupUrlsPageBrowserProxy; setup(function() { browserProxy = new TestStartupUrlsPageBrowserProxy(); StartupUrlsPageBrowserProxyImpl.setInstance(browserProxy); document.body.innerHTML = ''; page = document.createElement('settings-startup-urls-page'); page.prefs = { session: { restore_on_startup: { type: chrome.settingsPrivate.PrefType.NUMBER, value: 5, }, }, }; document.body.appendChild(page); flush(); }); teardown(function() { page.remove(); }); // Test that the page is requesting information from the browser. test('Initialization', async function() { await browserProxy.whenCalled('loadStartupPages'); }); test('UseCurrentPages', async function() { const useCurrentPagesButton = page.shadowRoot!.querySelector<HTMLElement>('#useCurrentPages > a'); assertTrue(!!useCurrentPagesButton); useCurrentPagesButton!.click(); await browserProxy.whenCalled('useCurrentPages'); }); test('AddPage_OpensDialog', async function() { const addPageButton = page.shadowRoot!.querySelector<HTMLElement>('#addPage > a'); assertTrue(!!addPageButton); assertFalse( !!page.shadowRoot!.querySelector('settings-startup-url-dialog')); addPageButton!.click(); flush(); assertTrue(!!page.shadowRoot!.querySelector('settings-startup-url-dialog')); }); test('EditPage_OpensDialog', function() { assertFalse( !!page.shadowRoot!.querySelector('settings-startup-url-dialog')); page.dispatchEvent(new CustomEvent(EDIT_STARTUP_URL_EVENT, { bubbles: true, composed: true, detail: {model: createSampleUrlEntry(), anchor: null} })); flush(); assertTrue(!!page.shadowRoot!.querySelector('settings-startup-url-dialog')); }); test('StartupPagesChanges_CloseOpenEditDialog', function() { const entry1 = { modelIndex: 2, title: 'Test page 1', tooltip: 'test tooltip', url: 'chrome://bar', }; const entry2 = { modelIndex: 2, title: 'Test page 2', tooltip: 'test tooltip', url: 'chrome://foo', }; webUIListenerCallback('update-startup-pages', [entry1, entry2]); page.dispatchEvent(new CustomEvent(EDIT_STARTUP_URL_EVENT, { bubbles: true, composed: true, detail: {model: entry2, anchor: null} })); flush(); assertTrue(!!page.shadowRoot!.querySelector('settings-startup-url-dialog')); webUIListenerCallback('update-startup-pages', [entry1]); flush(); assertFalse( !!page.shadowRoot!.querySelector('settings-startup-url-dialog')); }); test('StartupPages_WhenExtensionControlled', function() { assertFalse(!!page.get('prefs.session.startup_urls.controlledBy')); assertFalse( !!page.shadowRoot!.querySelector('extension-controlled-indicator')); assertTrue(!!page.shadowRoot!.querySelector('#addPage')); assertTrue(!!page.shadowRoot!.querySelector('#useCurrentPages')); page.set('prefs.session.startup_urls', { controlledBy: chrome.settingsPrivate.ControlledBy.EXTENSION, controlledByName: 'Totally Real Extension', enforcement: chrome.settingsPrivate.Enforcement.ENFORCED, extensionId: 'mefmhpjnkplhdhmfmblilkgpkbjebmij', type: chrome.settingsPrivate.PrefType.NUMBER, value: 5, }); flush(); assertTrue( !!page.shadowRoot!.querySelector('extension-controlled-indicator')); assertFalse(!!page.shadowRoot!.querySelector('#addPage')); assertFalse(!!page.shadowRoot!.querySelector('#useCurrentPages')); }); }); /** @return {!StartupPageInfo} */ function createSampleUrlEntry() { return { modelIndex: 2, title: 'Test page', tooltip: 'test tooltip', url: 'chrome://foo', }; } suite('StartupUrlEntry', function() { let element: SettingsStartupUrlEntryElement; let browserProxy: TestStartupUrlsPageBrowserProxy; setup(function() { browserProxy = new TestStartupUrlsPageBrowserProxy(); StartupUrlsPageBrowserProxyImpl.setInstance(browserProxy); document.body.innerHTML = ''; element = document.createElement('settings-startup-url-entry'); element.model = createSampleUrlEntry(); document.body.appendChild(element); flush(); }); teardown(function() { element.remove(); }); test('MenuOptions_Remove', async function() { element.editable = true; flush(); // Bring up the popup menu. assertFalse(!!element.shadowRoot!.querySelector('cr-action-menu')); element.shadowRoot!.querySelector<HTMLElement>('#dots')!.click(); flush(); assertTrue(!!element.shadowRoot!.querySelector('cr-action-menu')); const removeButton = element.shadowRoot!.querySelector<HTMLElement>('#remove'); removeButton!.click(); const modelIndex = await browserProxy.whenCalled('removeStartupPage'); assertEquals(element.model.modelIndex, modelIndex); }); test('Editable', function() { assertFalse(!!element.editable); assertFalse(!!element.shadowRoot!.querySelector('#dots')); element.editable = true; flush(); assertTrue(!!element.shadowRoot!.querySelector('#dots')); }); });
the_stack
/*global Observer: false*/ /*global TurbulenzEngine: false*/ "use strict"; class TextureInstance { static version = 1; name : string; texture : Texture; reference : Reference; textureChangedObserver : Observer; // // setTexture // setTexture(texture) { this.texture = texture; if (this.textureChangedObserver) { this.textureChangedObserver.notify(this); } } // // getTexture // getTexture(): Texture { return this.texture; } // // subscribeTextureChanged // subscribeTextureChanged(observerFunction) { if (!this.textureChangedObserver) { this.textureChangedObserver = Observer.create(); } this.textureChangedObserver.subscribe(observerFunction); } // // usubscribeTextureChanged // unsubscribeTextureChanged(observerFunction) { this.textureChangedObserver.unsubscribe(observerFunction); } // // destroy // destroy() { if (this.texture.name !== "default") { this.texture.destroy(); } delete this.texture; delete this.textureChangedObserver; } // // TextureInstance.create // static create(name: string, texture: Texture) : TextureInstance { var textureInstance = new TextureInstance(); textureInstance.name = name; textureInstance.texture = texture; textureInstance.reference = Reference.create(textureInstance); return textureInstance; } } interface TextureManagerDelayedTexture { nomipmaps: boolean; onload: { (texture: Texture): void; }; } interface TextureManagerArchive { textures: { [path: string]: Texture; }; } /** @class Texture manager @private @since TurbulenzEngine 0.1.0 */ class TextureManager { static version = 1; textureInstances: { [idx: string]: TextureInstance; }; loadingTexture: { [idx: string]: boolean; }; loadedTextureObservers: { [idx: string]: Observer; }; delayedTextures: { [idx: string]: TextureManagerDelayedTexture; }; numLoadingTextures: number; archivesLoaded: { [path: string]: TextureManagerArchive; }; loadingArchives: { [path: string]: TextureManagerArchive; }; loadedArchiveObservers: { [path: string]: Observer; }; numLoadingArchives: number; internalTexture: { [path: string]: boolean; }; pathRemapping: { [path: string]: string; }; pathPrefix: string; graphicsDevice: GraphicsDevice; requestHandler: RequestHandler; defaultTexture: Texture; errorCallback: { (msg?: string): void; }; onTextureInstanceDestroyed: { (textureInstance: TextureInstance): void; }; // TODO: This is so we can dynamically override methods on the // instance and get at the originals. There must be a better way // of doing this. prototype: any; /** Adds external texture @memberOf TextureManager.prototype @public @function @name add @param {string} name Name of the texture @param {Texture} texture Texture */ add(name, texture, internal?: boolean) { var textureInstance = this.textureInstances[name]; if (!textureInstance) { this.textureInstances[name] = TextureInstance.create(name, texture); this.textureInstances[name].reference.subscribeDestroyed(this.onTextureInstanceDestroyed); } else { textureInstance.setTexture(texture); } if (internal) { this.internalTexture[name] = true; this.textureInstances[name].reference.add(); } } /** Get texture created from a given file or with the given name @memberOf TextureManager.prototype @public @function @name get @param {string} path Path or name of the texture @return {Texture} object, returns the default texture if the texture is not yet loaded or the file didn't exist */ get(path) : Texture { var instance = this.textureInstances[path]; if (!instance) { return this.defaultTexture; } return instance.getTexture(); } // // getInstanceFn // getInstance(path): TextureInstance { return this.textureInstances[path]; } /** Creates texture from an image file @memberOf TextureManager.prototype @public @function @name load @param {string} path Path to the image file @param {boolean} nomipmaps True to disable mipmaps @param {function()} onTextureLoaded function to call once the texture is loaded @return {Texture} object, returns the default Texture if the file at given path is not yet loaded */ load(path, nomipmaps?, onTextureLoaded?): Texture { var that = this; if (path === undefined) { this.errorCallback("Invalid texture path passed to TextureManager.Load"); } var textureInstance = this.textureInstances[path]; if (!textureInstance || (textureInstance.texture === this.defaultTexture && path !== "default")) { if (!textureInstance) { this.add(path, this.defaultTexture, false); } if (!(path in this.loadingTexture)) { if (0 === this.numLoadingArchives) { this.loadingTexture[path] = true; this.numLoadingTextures += 1; var mipmaps = true; if (nomipmaps) { mipmaps = false; } var loadedObserver = Observer.create(); this.loadedTextureObservers[path] = loadedObserver; if (onTextureLoaded) { loadedObserver.subscribe(onTextureLoaded); } var textureLoaded = function textureLoadedFn(texture, status) { if (status === 200 && texture) { that.add(path, texture, false); } loadedObserver.notify(texture); delete that.loadedTextureObservers[path]; //Missing textures are left with the previous, usually default, texture. delete that.loadingTexture[path]; that.numLoadingTextures -= 1; }; var textureRequest = function textureRequestFn(url, onload /*, callContext */) { var texture = that.graphicsDevice.createTexture({ src : url, mipmaps : mipmaps, onload : onload }); if (!texture) { that.errorCallback("Texture '" + url + "' not created."); } }; this.requestHandler.request({ src: ((this.pathRemapping && this.pathRemapping[path]) || (this.pathPrefix + path)), requestFn: textureRequest, onload: textureLoaded }); } else { this.delayedTextures[path] = { nomipmaps: nomipmaps, onload: onTextureLoaded }; return this.get(path); } } else if (onTextureLoaded) { this.loadedTextureObservers[path].subscribe(onTextureLoaded); } return this.get(path); } else { var texture = this.get(path); if (onTextureLoaded) { // the callback should always be called asynchronously TurbulenzEngine.setTimeout(function textureAlreadyLoadedFn() { onTextureLoaded(texture); }, 0); } return texture; } } /** Alias one texture to another name @memberOf TextureManager.prototype @public @function @name map @param {string} dst Name of the alias @param {string} src Name of the texture to be aliased */ map(dst, src) { if (!this.textureInstances[dst]) { this.textureInstances[dst] = TextureInstance.create(dst, this.textureInstances[src].getTexture()); this.textureInstances[dst].reference.subscribeDestroyed(this.onTextureInstanceDestroyed); } else { this.textureInstances[dst].setTexture(this.textureInstances[src].getTexture()); } this.internalTexture[dst] = true; } /** Removes a texture from the manager @memberOf TextureManager.prototype @public @function @name remove @param {string} path Path or name of the texture */ remove(path) { if (!this.internalTexture[path]) { if (path in this.textureInstances) { this.textureInstances[path].reference.unsubscribeDestroyed(this.onTextureInstanceDestroyed); delete this.textureInstances[path]; } } } /** Loads a textures archive @memberOf TextureManager.prototype @public @function @name loadArchive @param {string} path Path to the archive file @param {boolean} nomipmaps True to disable mipmaps */ loadArchive(path, nomipmaps, onTextureLoaded, onArchiveLoaded) { var that = this; var archive = this.archivesLoaded[path]; if (!archive) { if (!(path in this.loadingArchives)) { var mipmaps = true; if (nomipmaps) { mipmaps = false; } this.loadingArchives[path] = { textures: {} }; this.numLoadingArchives += 1; var observer = Observer.create(); this.loadedArchiveObservers[path] = observer; if (onArchiveLoaded) { observer.subscribe(onArchiveLoaded); } var textureArchiveLoaded = function textureArchiveLoadedFn(success, status) { var loadedArchive; if (status === 200 && success) { loadedArchive = { textures: that.loadingArchives[path].textures }; that.archivesLoaded[path] = loadedArchive; } observer.notify(loadedArchive); delete that.loadedArchiveObservers[path]; delete that.loadingArchives[path]; that.numLoadingArchives -= 1; if (0 === that.numLoadingArchives) { var name; for (name in that.delayedTextures) { if (that.delayedTextures.hasOwnProperty(name)) { var delayedTexture = that.delayedTextures[name]; that.load(name, delayedTexture.nomipmaps, delayedTexture.onload); } } that.delayedTextures = {}; } }; var requestTextureArchive = function requestTextureArchiveFn(url, onload) { var ontextureload = function ontextureloadFn(texture) { var name = texture.name; if (!(name in that.textureInstances) || that.textureInstances[name].texture === that.defaultTexture) { that.add(name, texture, false); that.loadingArchives[path].textures[name] = texture; } if (onTextureLoaded) { onTextureLoaded(texture); } delete that.delayedTextures[name]; if (path in that.loadingTexture) { delete that.loadingTexture[path]; that.numLoadingTextures -= 1; } }; if (!that.graphicsDevice.loadTexturesArchive({ src: url, mipmaps: mipmaps, ontextureload: ontextureload, onload: onload })) { that.errorCallback("Archive '" + path + "' not loaded."); } }; that.requestHandler.request({ src: ((that.pathRemapping && that.pathRemapping[path]) || (that.pathPrefix + path)), requestFn: requestTextureArchive, onload: textureArchiveLoaded }); } else if (onTextureLoaded) { this.loadedArchiveObservers[path].subscribe(function textureArchiveLoadedFn() { var archive = that.archivesLoaded[path]; var texturesInArchive = archive.textures; var t; for (t in texturesInArchive) { if (texturesInArchive.hasOwnProperty(t)) { // the texture has already been loaded so we call onload manaually onTextureLoaded(texturesInArchive[t]); } } if (onArchiveLoaded) { onArchiveLoaded(archive); } }); } } else { if (onTextureLoaded) { var texturesInArchive = archive.textures; var numTexturesLoading = 0; var textureAlreadyLoadedWrapper = function textureAlreadyLoadedWrapper(texture) { return function textureAlreadyLoadedFn() { onTextureLoaded(texture); numTexturesLoading -= 1; if (numTexturesLoading === 0 && onArchiveLoaded) { onArchiveLoaded(archive); } }; }; var t; for (t in texturesInArchive) { if (texturesInArchive.hasOwnProperty(t)) { numTexturesLoading += 1; // the callback should always be called asynchronously TurbulenzEngine.setTimeout(textureAlreadyLoadedWrapper(texturesInArchive[t]), 0); } } } } } /** Check if an archive is not pending @memberOf TextureManager.prototype @public @function @name isArchiveLoaded @param {string} path Path or name of the archive @return {boolean} */ isArchiveLoaded(path): boolean { return path in this.archivesLoaded; } /** Removes a textures archive and all the textures it references. @memberOf TextureManager.prototype @public @function @name removeArchive @param {string} path Path of the archive file */ removeArchive(path) { if (path in this.archivesLoaded) { var archiveTextures = this.archivesLoaded[path].textures; var texture; for (texture in archiveTextures) { if (archiveTextures.hasOwnProperty(texture)) { this.remove(texture); } } delete this.archivesLoaded[path]; } } /** Get object containing all loaded textures @memberOf TextureManager.prototype @public @function @name getAll @return {object} */ getAll(): { [path: string]: TextureInstance; } { return this.textureInstances; } /** Get number of textures pending @memberOf TextureManager.prototype @public @function @name getNumLoadingTextures @return {number} */ getNumPendingTextures(): number { return (this.numLoadingTextures + this.numLoadingArchives); } /** Check if a texture is not pending @memberOf TextureManager.prototype @public @function @name isTextureLoaded @param {string} path Path or name of the texture @return {boolean} */ isTextureLoaded(path): boolean { return (!(path in this.loadingTexture) && !(path in this.delayedTextures)); } /** Check if a texture is missing @memberOf TextureManager.prototype @public @function @name isTextureMissing @param {string} path Path or name of the texture @return {boolean} */ isTextureMissing(path): boolean { return !(path in this.textureInstances); } /** Set path remapping dictionary @memberOf TextureManager.prototype @public @function @name setPathRemapping @param {string} prm Path remapping dictionary @param {string} assetUrl Asset prefix for all assets loaded */ setPathRemapping(prm, assetUrl) { this.pathRemapping = prm; this.pathPrefix = assetUrl; } addProceduralTexture(params) { var name = params.name; var procTexture = this.graphicsDevice.createTexture(params); if (!procTexture) { this.errorCallback("Failed to create '" + name + "' texture."); } else { this.add(name, procTexture, true); } } destroy() { if (this.textureInstances) { var p; for (p in this.textureInstances) { if (this.textureInstances.hasOwnProperty(p)) { var textureInstance = this.textureInstances[p]; if (textureInstance) { textureInstance.destroy(); } } } this.textureInstances = null; } if (this.defaultTexture) { this.defaultTexture.destroy(); this.defaultTexture = null; } this.loadingTexture = null; this.loadedTextureObservers = null; this.delayedTextures = null; this.numLoadingTextures = 0; this.archivesLoaded = null; this.loadingArchives = null; this.loadedArchiveObservers = null; this.numLoadingArchives = 0; this.internalTexture = null; this.pathRemapping = null; this.pathPrefix = null; this.requestHandler = null; this.graphicsDevice = null; } /** @constructs Constructs a TextureManager object. @param {GraphicsDevice} graphicsDevice Graphics device @param {Texture} dt Default texture @param {Element} log Logging element @return {TextureManager} object, null if failed */ static create(graphicsDevice: GraphicsDevice, requestHandler: RequestHandler, dt: Texture, errorCallback, log?: HTMLElement) : TextureManager { var textureManager = new TextureManager(); if (!errorCallback) { errorCallback = function (/* e */) {}; } var defaultTextureName = "default"; var defaultTexture; if (dt) { defaultTexture = dt; } else { defaultTexture = graphicsDevice.createTexture({ name : defaultTextureName, width : 2, height : 2, depth : 1, format : 'R8G8B8A8', cubemap : false, mipmaps : true, dynamic : false, data : [255, 20, 147, 255, 255, 0, 0, 255, 255, 255, 255, 255, 255, 20, 147, 255] }); if (!defaultTexture) { errorCallback("Default texture not created."); } } textureManager.textureInstances = {}; textureManager.loadingTexture = {}; textureManager.loadedTextureObservers = {}; textureManager.delayedTextures = {}; textureManager.numLoadingTextures = 0; textureManager.archivesLoaded = {}; textureManager.loadingArchives = {}; textureManager.loadedArchiveObservers = {}; textureManager.numLoadingArchives = 0; textureManager.internalTexture = {}; textureManager.pathRemapping = null; textureManager.pathPrefix = ""; textureManager.graphicsDevice = graphicsDevice; textureManager.requestHandler = requestHandler; textureManager.defaultTexture = defaultTexture; textureManager.errorCallback = errorCallback; // // onTextureInstanceDestroyed callback // var onTextureInstanceDestroyed = function onTextureInstanceDestroyedFn(textureInstance) { textureInstance.reference.unsubscribeDestroyed(onTextureInstanceDestroyed); delete textureManager.textureInstances[textureInstance.name]; }; textureManager.onTextureInstanceDestroyed = onTextureInstanceDestroyed; if (log) { textureManager.add = function addTextureLogFn(name, tex) { log.innerHTML += "TextureManager.add:&nbsp;'" + name + "'"; return TextureManager.prototype.add.call(textureManager, name, tex); }; textureManager.load = function loadTextureLogFn(path, nomipmaps?) { log.innerHTML += "TextureManager.load:&nbsp;'" + path + "'"; return TextureManager.prototype.load.call(textureManager, path, nomipmaps); }; textureManager.loadArchive = function loadArchiveLogFn(path, nomipmaps) { log.innerHTML += "TextureManager.loadArchive:&nbsp;'" + path + "'"; return TextureManager.prototype.loadArchive.call (textureManager, path, nomipmaps); }; textureManager.isArchiveLoaded = function isArchiveLoadedLogFn(path) { log.innerHTML += "TextureManager.isArchiveLoaded:&nbsp;'" + path + "'"; return TextureManager.prototype.isArchiveLoaded.call (textureManager, path); }; textureManager.removeArchive = function removeArchiveLogFn(path) { log.innerHTML += "TextureManager.removeArchive:&nbsp;'" + path + "'"; return TextureManager.prototype.removeArchive.call (textureManager, path); }; textureManager.map = function mapTextureLogFn(dst, src) { log.innerHTML += "TextureManager.map:&nbsp;'" + src + "' -> '" + dst + "'"; TextureManager.prototype.map.call(textureManager, dst, src); }; textureManager.get = function getTextureLogFn(path) { log.innerHTML += "TextureManager.get:&nbsp;'" + path + "'"; return TextureManager.prototype.get.call(textureManager, path); }; textureManager.getInstance = function getTextureInstanceLogFn(path) { log.innerHTML += "TextureManager.getInstance:&nbsp;'" + path + "'"; return TextureManager.prototype.getInstance.call (textureManager, path); }; textureManager.remove = function removeTextureLogFn(path) { log.innerHTML += "TextureManager.remove:&nbsp;'" + path + "'"; TextureManager.prototype.remove.call(textureManager, path); }; } // Add procedural textures textureManager.add(defaultTextureName, defaultTexture, true); textureManager.addProceduralTexture({ name : "white", width : 2, height : 2, depth : 1, format : 'R8G8B8A8', cubemap : false, mipmaps : true, dynamic : false, data : [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255] }); textureManager.addProceduralTexture({ name : "black", width : 2, height : 2, depth : 1, format : 'R8G8B8A8', cubemap : false, mipmaps : true, dynamic : false, data : [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255] }); textureManager.addProceduralTexture({ name : "flat", width : 2, height : 2, depth : 1, format : 'R8G8B8A8', cubemap : false, mipmaps : true, dynamic : false, data : [128, 128, 255, 255, 128, 128, 255, 255, 128, 128, 255, 255, 128, 128, 255, 255] }); var abs = Math.abs; var x, y; var quadraticData = []; for (y = 0; y < 4; y += 1) { for (x = 0; x < 32; x += 1) { var s = ((x + 0.5) * (2.0 / 32.0) - 1.0); s = abs(s) - (1.0 / 32.0); var value = (1.0 - (s * 2.0) + (s * s)); if (value <= 0) { quadraticData.push(0); } else if (value >= 1) { quadraticData.push(255); } else { quadraticData.push(value * 255); } } } textureManager.addProceduralTexture({ name : "quadratic", width : 32, height : 4, depth : 1, format : 'L8', cubemap : false, mipmaps : true, dynamic : false, data : quadraticData }); quadraticData = null; var nofalloffData = []; for (y = 0; y < 4; y += 1) { nofalloffData.push(0); for (x = 1; x < 31; x += 1) { nofalloffData.push(255); } nofalloffData.push(0); } textureManager.addProceduralTexture({ name : "nofalloff", width : 32, height : 4, depth : 1, format : 'L8', cubemap : false, mipmaps : true, dynamic : false, data : nofalloffData }); nofalloffData = null; return textureManager; } }
the_stack
// This file contains common part of defintions for rx.d.ts and rx.lite.d.ts // Do not include the file separately. declare namespace __LiteMolRx { export module internals { function isEqual(left: any, right: any): boolean; function addRef<T>(xs: Observable<T>, r: { getDisposable(): IDisposable; }): Observable<T>; // Priority Queue for Scheduling export class PriorityQueue<TTime> { constructor(capacity: number); length: number; isHigherPriority(left: number, right: number): boolean; percolate(index: number): void; heapify(index: number): void; peek(): ScheduledItem<TTime>; removeAt(index: number): void; dequeue(): ScheduledItem<TTime>; enqueue(item: ScheduledItem<TTime>): void; remove(item: ScheduledItem<TTime>): boolean; static count: number; } export class ScheduledItem<TTime> { constructor(scheduler: IScheduler, state: any, action: (scheduler: IScheduler, state: any) => IDisposable, dueTime: TTime, comparer?: (x: TTime, y: TTime) => number); scheduler: IScheduler; state: TTime; action: (scheduler: IScheduler, state: any) => IDisposable; dueTime: TTime; comparer: (x: TTime, y: TTime) => number; disposable: SingleAssignmentDisposable; invoke(): void; compareTo(other: ScheduledItem<TTime>): number; isCancelled(): boolean; invokeCore(): IDisposable; } } export module config { export var Promise: { new <T>(resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): IPromise<T>; }; } export module helpers { function noop(): void; function notDefined(value: any): boolean; function identity<T>(value: T): T; function defaultNow(): number; function defaultComparer(left: any, right: any): boolean; function defaultSubComparer(left: any, right: any): number; function defaultKeySerializer(key: any): string; function defaultError(err: any): void; function isPromise(p: any): boolean; function asArray<T>(...args: T[]): T[]; function not(value: any): boolean; function isFunction(value: any): boolean; } export interface IDisposable { dispose(): void; } export class CompositeDisposable implements IDisposable { constructor(...disposables: IDisposable[]); constructor(disposables: IDisposable[]); isDisposed: boolean; length: number; dispose(): void; add(item: IDisposable): void; remove(item: IDisposable): boolean; toArray(): IDisposable[]; } export class Disposable implements IDisposable { constructor(action: () => void); static create(action: () => void): IDisposable; static empty: IDisposable; dispose(): void; } // Single assignment export class SingleAssignmentDisposable implements IDisposable { constructor(); isDisposed: boolean; current: IDisposable; dispose(): void; getDisposable(): IDisposable; setDisposable(value: IDisposable): void; } // SerialDisposable it's an alias of SingleAssignmentDisposable export class SerialDisposable extends SingleAssignmentDisposable { constructor(); } export class RefCountDisposable implements IDisposable { constructor(disposable: IDisposable); dispose(): void; isDisposed: boolean; getDisposable(): IDisposable; } export interface IScheduler { now(): number; isScheduler(value: any): boolean; schedule(action: () => void): IDisposable; scheduleWithState<TState>(state: TState, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; scheduleWithAbsolute(dueTime: number, action: () => void): IDisposable; scheduleWithAbsoluteAndState<TState>(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; scheduleWithRelative(dueTime: number, action: () => void): IDisposable; scheduleWithRelativeAndState<TState>(state: TState, dueTime: number, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; scheduleRecursive(action: (action: () => void) => void): IDisposable; scheduleRecursiveWithState<TState>(state: TState, action: (state: TState, action: (state: TState) => void) => void): IDisposable; scheduleRecursiveWithAbsolute(dueTime: number, action: (action: (dueTime: number) => void) => void): IDisposable; scheduleRecursiveWithAbsoluteAndState<TState>(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) => void) => void): IDisposable; scheduleRecursiveWithRelative(dueTime: number, action: (action: (dueTime: number) => void) => void): IDisposable; scheduleRecursiveWithRelativeAndState<TState>(state: TState, dueTime: number, action: (state: TState, action: (state: TState, dueTime: number) => void) => void): IDisposable; schedulePeriodic(period: number, action: () => void): IDisposable; schedulePeriodicWithState<TState>(state: TState, period: number, action: (state: TState) => TState): IDisposable; } export interface Scheduler extends IScheduler { } export interface SchedulerStatic { new ( now: () => number, schedule: (state: any, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable, scheduleRelative: (state: any, dueTime: number, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable, scheduleAbsolute: (state: any, dueTime: number, action: (scheduler: IScheduler, state: any) => IDisposable) => IDisposable): Scheduler; normalize(timeSpan: number): number; immediate: IScheduler; currentThread: ICurrentThreadScheduler; default: IScheduler; // alias for Scheduler.timeout timeout: IScheduler; } export var Scheduler: SchedulerStatic; // Current Thread IScheduler interface ICurrentThreadScheduler extends IScheduler { scheduleRequired(): boolean; } // Notifications export class Notification<T> { accept(observer: IObserver<T>): void; accept<TResult>(onNext: (value: T) => TResult, onError?: (exception: any) => TResult, onCompleted?: () => TResult): TResult; toObservable(scheduler?: IScheduler): Observable<T>; hasValue: boolean; equals(other: Notification<T>): boolean; kind: string; value: T; exception: any; static createOnNext<T>(value: T): Notification<T>; static createOnError<T>(exception: any): Notification<T>; static createOnCompleted<T>(): Notification<T>; } /** * Promise A+ */ export interface IPromise<T> { then<R>(onFulfilled: (value: T) => IPromise<R>, onRejected: (reason: any) => IPromise<R>): IPromise<R>; then<R>(onFulfilled: (value: T) => IPromise<R>, onRejected?: (reason: any) => R): IPromise<R>; then<R>(onFulfilled: (value: T) => R, onRejected: (reason: any) => IPromise<R>): IPromise<R>; then<R>(onFulfilled?: (value: T) => R, onRejected?: (reason: any) => R): IPromise<R>; } // Observer export interface IObserver<T> { onNext(value: T): void; onError(exception: any): void; onCompleted(): void; } export interface Observer<T> extends IObserver<T> { toNotifier(): (notification: Notification<T>) => void; asObserver(): Observer<T>; } interface ObserverStatic { create<T>(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observer<T>; fromNotifier<T>(handler: (notification: Notification<T>, thisArg?: any) => void): Observer<T>; } export var Observer: ObserverStatic; export interface IObservable<T> { subscribe(observer: Observer<T>): IDisposable; subscribe(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): IDisposable; subscribeOnNext(onNext: (value: T) => void, thisArg?: any): IDisposable; subscribeOnError(onError: (exception: any) => void, thisArg?: any): IDisposable; subscribeOnCompleted(onCompleted: () => void, thisArg?: any): IDisposable; } export interface Observable<T> extends IObservable<T> { forEach(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): IDisposable; // alias for subscribe toArray(): Observable<T[]>; catch(handler: (exception: any) => Observable<T>): Observable<T>; catchException(handler: (exception: any) => Observable<T>): Observable<T>; // alias for catch catch(handler: (exception: any) => IPromise<T>): Observable<T>; catchException(handler: (exception: any) => IPromise<T>): Observable<T>; // alias for catch catch(second: Observable<T>): Observable<T>; catchException(second: Observable<T>): Observable<T>; // alias for catch combineLatest<T2, TResult>(second: Observable<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>; combineLatest<T2, TResult>(second: IPromise<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>; combineLatest<T2, T3, TResult>(second: Observable<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; combineLatest<T2, T3, TResult>(second: Observable<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; combineLatest<T2, T3, TResult>(second: IPromise<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; combineLatest<T2, T3, TResult>(second: IPromise<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; combineLatest<T2, T3, T4, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T2, T3, T4, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T2, T3, T4, TResult>(second: Observable<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T2, T3, T4, TResult>(second: Observable<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T2, T3, T4, TResult>(second: IPromise<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T2, T3, T4, TResult>(second: IPromise<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T2, T3, T4, TResult>(second: IPromise<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T2, T3, T4, TResult>(second: IPromise<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T2, T3, T4, T5, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, fifth: Observable<T5>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable<TResult>; combineLatest<TOther, TResult>(souces: Observable<TOther>[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable<TResult>; combineLatest<TOther, TResult>(souces: IPromise<TOther>[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable<TResult>; withLatestFrom<T2, TResult>(second: Observable<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>; withLatestFrom<T2, TResult>(second: IPromise<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>; withLatestFrom<T2, T3, TResult>(second: Observable<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; withLatestFrom<T2, T3, TResult>(second: Observable<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; withLatestFrom<T2, T3, TResult>(second: IPromise<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; withLatestFrom<T2, T3, TResult>(second: IPromise<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; withLatestFrom<T2, T3, T4, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T2, T3, T4, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T2, T3, T4, TResult>(second: Observable<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T2, T3, T4, TResult>(second: Observable<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T2, T3, T4, TResult>(second: IPromise<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T2, T3, T4, TResult>(second: IPromise<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T2, T3, T4, TResult>(second: IPromise<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T2, T3, T4, TResult>(second: IPromise<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T2, T3, T4, T5, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, fifth: Observable<T5>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable<TResult>; withLatestFrom<TOther, TResult>(souces: Observable<TOther>[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable<TResult>; withLatestFrom<TOther, TResult>(souces: IPromise<TOther>[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable<TResult>; concat(...sources: Observable<T>[]): Observable<T>; concat(...sources: IPromise<T>[]): Observable<T>; concat(sources: Observable<T>[]): Observable<T>; concat(sources: IPromise<T>[]): Observable<T>; concatAll(): T; concatObservable(): T; // alias for concatAll concatMap<T2, R>(selector: (value: T, index: number) => Observable<T2>, resultSelector: (value1: T, value2: T2, index: number) => R): Observable<R>; // alias for selectConcat concatMap<T2, R>(selector: (value: T, index: number) => IPromise<T2>, resultSelector: (value1: T, value2: T2, index: number) => R): Observable<R>; // alias for selectConcat concatMap<R>(selector: (value: T, index: number) => Observable<R>): Observable<R>; // alias for selectConcat concatMap<R>(selector: (value: T, index: number) => IPromise<R>): Observable<R>; // alias for selectConcat concatMap<R>(sequence: Observable<R>): Observable<R>; // alias for selectConcat merge(maxConcurrent: number): T; merge(other: Observable<T>): Observable<T>; merge(other: IPromise<T>): Observable<T>; mergeAll(): T; mergeObservable(): T; // alias for mergeAll skipUntil<T2>(other: Observable<T2>): Observable<T>; skipUntil<T2>(other: IPromise<T2>): Observable<T>; switch(): T; switchLatest(): T; // alias for switch takeUntil<T2>(other: Observable<T2>): Observable<T>; takeUntil<T2>(other: IPromise<T2>): Observable<T>; zip<T2, TResult>(second: Observable<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>; zip<T2, TResult>(second: IPromise<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>; zip<T2, T3, TResult>(second: Observable<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; zip<T2, T3, TResult>(second: Observable<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; zip<T2, T3, TResult>(second: IPromise<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; zip<T2, T3, TResult>(second: IPromise<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; zip<T2, T3, T4, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; zip<T2, T3, T4, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; zip<T2, T3, T4, TResult>(second: Observable<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; zip<T2, T3, T4, TResult>(second: Observable<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; zip<T2, T3, T4, TResult>(second: IPromise<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; zip<T2, T3, T4, TResult>(second: IPromise<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; zip<T2, T3, T4, TResult>(second: IPromise<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; zip<T2, T3, T4, TResult>(second: IPromise<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; zip<T2, T3, T4, T5, TResult>(second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, fifth: Observable<T5>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable<TResult>; zip<TOther, TResult>(second: Observable<TOther>[], resultSelector: (left: T, ...right: TOther[]) => TResult): Observable<TResult>; zip<TOther, TResult>(second: IPromise<TOther>[], resultSelector: (left: T, ...right: TOther[]) => TResult): Observable<TResult>; asObservable(): Observable<T>; dematerialize<TOrigin>(): Observable<TOrigin>; distinctUntilChanged(skipParameter: boolean, comparer: (x: T, y: T) => boolean): Observable<T>; distinctUntilChanged<TValue>(keySelector?: (value: T) => TValue, comparer?: (x: TValue, y: TValue) => boolean): Observable<T>; do(observer: Observer<T>): Observable<T>; doAction(observer: Observer<T>): Observable<T>; // alias for do tap(observer: Observer<T>): Observable<T>; // alias for do do(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observable<T>; doAction(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observable<T>; // alias for do tap(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observable<T>; // alias for do doOnNext(onNext: (value: T) => void, thisArg?: any): Observable<T>; doOnError(onError: (exception: any) => void, thisArg?: any): Observable<T>; doOnCompleted(onCompleted: () => void, thisArg?: any): Observable<T>; tapOnNext(onNext: (value: T) => void, thisArg?: any): Observable<T>; tapOnError(onError: (exception: any) => void, thisArg?: any): Observable<T>; tapOnCompleted(onCompleted: () => void, thisArg?: any): Observable<T>; finally(action: () => void): Observable<T>; finallyAction(action: () => void): Observable<T>; // alias for finally ignoreElements(): Observable<T>; materialize(): Observable<Notification<T>>; repeat(repeatCount?: number): Observable<T>; retry(retryCount?: number): Observable<T>; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(function (acc, x) { return acc + x; }, 0); * @param accumulator An accumulator function to be invoked on each element. * @param seed The initial accumulator value. * @returns An observable sequence containing the accumulated values. */ scan<TAcc>(accumulator: (acc: TAcc, value: T, index?: number, source?: Observable<TAcc>) => TAcc, seed: TAcc): Observable<TAcc>; scan(accumulator: (acc: T, value: T, index?: number, source?: Observable<T>) => T): Observable<T>; skipLast(count: number): Observable<T>; startWith(...values: T[]): Observable<T>; startWith(scheduler: IScheduler, ...values: T[]): Observable<T>; takeLast(count: number): Observable<T>; takeLastBuffer(count: number): Observable<T[]>; select<TResult>(selector: (value: T, index: number, source: Observable<T>) => TResult, thisArg?: any): Observable<TResult>; map<TResult>(selector: (value: T, index: number, source: Observable<T>) => TResult, thisArg?: any): Observable<TResult>; // alias for select pluck<TResult>(prop: string): Observable<TResult>; selectMany<TOther, TResult>(selector: (value: T) => Observable<TOther>, resultSelector: (item: T, other: TOther) => TResult): Observable<TResult>; selectMany<TOther, TResult>(selector: (value: T) => IPromise<TOther>, resultSelector: (item: T, other: TOther) => TResult): Observable<TResult>; selectMany<TResult>(selector: (value: T) => Observable<TResult>): Observable<TResult>; selectMany<TResult>(selector: (value: T) => IPromise<TResult>): Observable<TResult>; selectMany<TResult>(other: Observable<TResult>): Observable<TResult>; selectMany<TResult>(other: IPromise<TResult>): Observable<TResult>; selectMany<TResult>(selector: (value: T) => TResult[]): Observable<TResult>; // alias for selectMany flatMap<TOther, TResult>(selector: (value: T) => Observable<TOther>, resultSelector: (item: T, other: TOther) => TResult): Observable<TResult>; // alias for selectMany flatMap<TOther, TResult>(selector: (value: T) => IPromise<TOther>, resultSelector: (item: T, other: TOther) => TResult): Observable<TResult>; // alias for selectMany flatMap<TResult>(selector: (value: T) => Observable<TResult>): Observable<TResult>; // alias for selectMany flatMap<TResult>(selector: (value: T) => IPromise<TResult>): Observable<TResult>; // alias for selectMany flatMap<TResult>(other: Observable<TResult>): Observable<TResult>; // alias for selectMany flatMap<TResult>(other: IPromise<TResult>): Observable<TResult>; // alias for selectMany flatMap<TResult>(selector: (value: T) => TResult[]): Observable<TResult>; // alias for selectMany /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ selectManyObserver<T2, T3, T4>(onNext: (value: T, index: number) => Observable<T2>, onError: (exception: any) => Observable<T3>, onCompleted: () => Observable<T4>, thisArg?: any): Observable<T2 | T3 | T4>; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ flatMapObserver<T2, T3, T4>(onNext: (value: T, index: number) => Observable<T2>, onError: (exception: any) => Observable<T3>, onCompleted: () => Observable<T4>, thisArg?: any): Observable<T2 | T3 | T4>; selectConcat<T2, R>(selector: (value: T, index: number) => Observable<T2>, resultSelector: (value1: T, value2: T2, index: number) => R): Observable<R>; selectConcat<T2, R>(selector: (value: T, index: number) => IPromise<T2>, resultSelector: (value1: T, value2: T2, index: number) => R): Observable<R>; selectConcat<R>(selector: (value: T, index: number) => Observable<R>): Observable<R>; selectConcat<R>(selector: (value: T, index: number) => IPromise<R>): Observable<R>; selectConcat<R>(sequence: Observable<R>): Observable<R>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param [thisArg] Object to use as this when executing callback. * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ selectSwitch<TResult>(selector: (value: T, index: number, source: Observable<T>) => Observable<TResult>, thisArg?: any): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param [thisArg] Object to use as this when executing callback. * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ flatMapLatest<TResult>(selector: (value: T, index: number, source: Observable<T>) => Observable<TResult>, thisArg?: any): Observable<TResult>; // alias for selectSwitch /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param [thisArg] Object to use as this when executing callback. * @since 2.2.28 * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ switchMap<TResult>(selector: (value: T, index: number, source: Observable<T>) => TResult, thisArg?: any): Observable<TResult>; // alias for selectSwitch skip(count: number): Observable<T>; skipWhile(predicate: (value: T, index: number, source: Observable<T>) => boolean, thisArg?: any): Observable<T>; take(count: number, scheduler?: IScheduler): Observable<T>; takeWhile(predicate: (value: T, index: number, source: Observable<T>) => boolean, thisArg?: any): Observable<T>; where(predicate: (value: T, index: number, source: Observable<T>) => boolean, thisArg?: any): Observable<T>; filter(predicate: (value: T, index: number, source: Observable<T>) => boolean, thisArg?: any): Observable<T>; // alias for where /** * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * @param promiseCtor The constructor of the promise. * @returns An ES6 compatible promise with the last value from the observable sequence. */ toPromise<TPromise extends IPromise<T>>(promiseCtor: { new (resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): TPromise; }): TPromise; /** * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns An ES6 compatible promise with the last value from the observable sequence. */ toPromise(promiseCtor?: { new (resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): IPromise<T>; }): IPromise<T>; // Experimental Flattening /** * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * Can be applied on `Observable<Observable<R>>` or `Observable<IPromise<R>>`. * @since 2.2.28 * @returns A exclusive observable with only the results that happen when subscribed. */ exclusive<R>(): Observable<R>; /** * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * Can be applied on `Observable<Observable<I>>` or `Observable<IPromise<I>>`. * @since 2.2.28 * @param selector Selector to invoke for every item in the current subscription. * @param [thisArg] An optional context to invoke with the selector parameter. * @returns {An exclusive observable with only the results that happen when subscribed. */ exclusiveMap<I, R>(selector: (value: I, index: number, source: Observable<I>) => R, thisArg?: any): Observable<R>; } interface ObservableStatic { create<T>(subscribe: (observer: Observer<T>) => IDisposable): Observable<T>; create<T>(subscribe: (observer: Observer<T>) => () => void): Observable<T>; create<T>(subscribe: (observer: Observer<T>) => void): Observable<T>; createWithDisposable<T>(subscribe: (observer: Observer<T>) => IDisposable): Observable<T>; defer<T>(observableFactory: () => Observable<T>): Observable<T>; defer<T>(observableFactory: () => IPromise<T>): Observable<T>; empty<T>(scheduler?: IScheduler): Observable<T>; /** * This method creates a new Observable sequence from an array object. * @param array An array-like or iterable object to convert to an Observable sequence. * @param mapFn Map function to call on every element of the array. * @param [thisArg] The context to use calling the mapFn if provided. * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ from<T, TResult>(array: T[], mapFn: (value: T, index: number) => TResult, thisArg?: any, scheduler?: IScheduler): Observable<TResult>; /** * This method creates a new Observable sequence from an array object. * @param array An array-like or iterable object to convert to an Observable sequence. * @param [mapFn] Map function to call on every element of the array. * @param [thisArg] The context to use calling the mapFn if provided. * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ from<T>(array: T[], mapFn?: (value: T, index: number) => T, thisArg?: any, scheduler?: IScheduler): Observable<T>; /** * This method creates a new Observable sequence from an array-like object. * @param array An array-like or iterable object to convert to an Observable sequence. * @param mapFn Map function to call on every element of the array. * @param [thisArg] The context to use calling the mapFn if provided. * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ from<T, TResult>(array: { length: number;[index: number]: T; }, mapFn: (value: T, index: number) => TResult, thisArg?: any, scheduler?: IScheduler): Observable<TResult>; /** * This method creates a new Observable sequence from an array-like object. * @param array An array-like or iterable object to convert to an Observable sequence. * @param [mapFn] Map function to call on every element of the array. * @param [thisArg] The context to use calling the mapFn if provided. * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ from<T>(array: { length: number;[index: number]: T; }, mapFn?: (value: T, index: number) => T, thisArg?: any, scheduler?: IScheduler): Observable<T>; /** * This method creates a new Observable sequence from an array-like or iterable object. * @param array An array-like or iterable object to convert to an Observable sequence. * @param [mapFn] Map function to call on every element of the array. * @param [thisArg] The context to use calling the mapFn if provided. * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ from<T>(iterable: any, mapFn?: (value: any, index: number) => T, thisArg?: any, scheduler?: IScheduler): Observable<T>; fromArray<T>(array: T[], scheduler?: IScheduler): Observable<T>; fromArray<T>(array: { length: number;[index: number]: T; }, scheduler?: IScheduler): Observable<T>; generate<TState, TResult>(initialState: TState, condition: (state: TState) => boolean, iterate: (state: TState) => TState, resultSelector: (state: TState) => TResult, scheduler?: IScheduler): Observable<TResult>; never<T>(): Observable<T>; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * * @example * var res = Rx.Observable.of(1, 2, 3); * @since 2.2.28 * @returns The observable sequence whose elements are pulled from the given arguments. */ of<T>(...values: T[]): Observable<T>; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.ofWithScheduler(Rx.Scheduler.timeout, 1, 2, 3); * @since 2.2.28 * @param [scheduler] A scheduler to use for scheduling the arguments. * @returns The observable sequence whose elements are pulled from the given arguments. */ ofWithScheduler<T>(scheduler?: IScheduler, ...values: T[]): Observable<T>; range(start: number, count: number, scheduler?: IScheduler): Observable<number>; repeat<T>(value: T, repeatCount?: number, scheduler?: IScheduler): Observable<T>; return<T>(value: T, scheduler?: IScheduler): Observable<T>; /** * @since 2.2.28 */ just<T>(value: T, scheduler?: IScheduler): Observable<T>; // alias for return returnValue<T>(value: T, scheduler?: IScheduler): Observable<T>; // alias for return throw<T>(exception: Error, scheduler?: IScheduler): Observable<T>; throw<T>(exception: any, scheduler?: IScheduler): Observable<T>; throwException<T>(exception: Error, scheduler?: IScheduler): Observable<T>; // alias for throw throwException<T>(exception: any, scheduler?: IScheduler): Observable<T>; // alias for throw throwError<T>(error: Error, scheduler?: IScheduler): Observable<T>; // alias for throw throwError<T>(error: any, scheduler?: IScheduler): Observable<T>; // alias for throw catch<T>(sources: Observable<T>[]): Observable<T>; catch<T>(sources: IPromise<T>[]): Observable<T>; catchException<T>(sources: Observable<T>[]): Observable<T>; // alias for catch catchException<T>(sources: IPromise<T>[]): Observable<T>; // alias for catch catchError<T>(sources: Observable<T>[]): Observable<T>; // alias for catch catchError<T>(sources: IPromise<T>[]): Observable<T>; // alias for catch catch<T>(...sources: Observable<T>[]): Observable<T>; catch<T>(...sources: IPromise<T>[]): Observable<T>; catchException<T>(...sources: Observable<T>[]): Observable<T>; // alias for catch catchException<T>(...sources: IPromise<T>[]): Observable<T>; // alias for catch catchError<T>(...sources: Observable<T>[]): Observable<T>; // alias for catch catchError<T>(...sources: IPromise<T>[]): Observable<T>; // alias for catch combineLatest<T, T2>(first: Observable<T>, second: Observable<T2>): Observable<[T, T2]>; combineLatest<T, T2, TResult>(first: Observable<T>, second: Observable<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>; combineLatest<T, T2, TResult>(first: IPromise<T>, second: Observable<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>; combineLatest<T, T2, TResult>(first: Observable<T>, second: IPromise<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>; combineLatest<T, T2, TResult>(first: IPromise<T>, second: IPromise<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>; combineLatest<T, T2, T3>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>): Observable<[T, T2, T3]>; combineLatest<T, T2, T3, TResult>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; combineLatest<T, T2, T3, TResult>(first: Observable<T>, second: Observable<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; combineLatest<T, T2, T3, TResult>(first: Observable<T>, second: IPromise<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; combineLatest<T, T2, T3, TResult>(first: Observable<T>, second: IPromise<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; combineLatest<T, T2, T3, TResult>(first: IPromise<T>, second: Observable<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; combineLatest<T, T2, T3, TResult>(first: IPromise<T>, second: Observable<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; combineLatest<T, T2, T3, TResult>(first: IPromise<T>, second: IPromise<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; combineLatest<T, T2, T3, TResult>(first: IPromise<T>, second: IPromise<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>): Observable<[T, T2, T3, T4]>; combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: Observable<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: Observable<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: IPromise<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: IPromise<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: IPromise<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: Observable<T>, second: IPromise<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: Observable<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: Observable<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: Observable<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: IPromise<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: IPromise<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: IPromise<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, TResult>(first: IPromise<T>, second: IPromise<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; combineLatest<T, T2, T3, T4, T5>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, fifth: Observable<T5>): Observable<[T, T2, T3, T4, T5]>; combineLatest<T, T2, T3, T4, T5, TResult>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, fifth: Observable<T5>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable<TResult>; combineLatest<T>(sources: Observable<T>[]): Observable<T[]>; combineLatest<TOther, TResult>(sources: Observable<TOther>[], resultSelector: (...otherValues: TOther[]) => TResult): Observable<TResult>; combineLatest<TOther, TResult>(sources: IPromise<TOther>[], resultSelector: (...otherValues: TOther[]) => TResult): Observable<TResult>; withLatestFrom<T, T2, TResult>(first: Observable<T>, second: Observable<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>; withLatestFrom<T, T2, TResult>(first: IPromise<T>, second: Observable<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>; withLatestFrom<T, T2, TResult>(first: Observable<T>, second: IPromise<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>; withLatestFrom<T, T2, TResult>(first: IPromise<T>, second: IPromise<T2>, resultSelector: (v1: T, v2: T2) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, TResult>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, TResult>(first: Observable<T>, second: Observable<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, TResult>(first: Observable<T>, second: IPromise<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, TResult>(first: Observable<T>, second: IPromise<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, TResult>(first: IPromise<T>, second: Observable<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, TResult>(first: IPromise<T>, second: Observable<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, TResult>(first: IPromise<T>, second: IPromise<T2>, third: Observable<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, TResult>(first: IPromise<T>, second: IPromise<T2>, third: IPromise<T3>, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: Observable<T>, second: Observable<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: Observable<T>, second: Observable<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: Observable<T>, second: IPromise<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: Observable<T>, second: IPromise<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: Observable<T>, second: IPromise<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: Observable<T>, second: IPromise<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: IPromise<T>, second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: IPromise<T>, second: Observable<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: IPromise<T>, second: Observable<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: IPromise<T>, second: Observable<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: IPromise<T>, second: IPromise<T2>, third: Observable<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: IPromise<T>, second: IPromise<T2>, third: Observable<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: IPromise<T>, second: IPromise<T2>, third: IPromise<T3>, fourth: Observable<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, TResult>(first: IPromise<T>, second: IPromise<T2>, third: IPromise<T3>, fourth: IPromise<T4>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable<TResult>; withLatestFrom<T, T2, T3, T4, T5, TResult>(first: Observable<T>, second: Observable<T2>, third: Observable<T3>, fourth: Observable<T4>, fifth: Observable<T5>, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable<TResult>; withLatestFrom<TOther, TResult>(souces: Observable<TOther>[], resultSelector: (...otherValues: TOther[]) => TResult): Observable<TResult>; withLatestFrom<TOther, TResult>(souces: IPromise<TOther>[], resultSelector: (...otherValues: TOther[]) => TResult): Observable<TResult>; concat<T>(...sources: Observable<T>[]): Observable<T>; concat<T>(...sources: IPromise<T>[]): Observable<T>; concat<T>(sources: Observable<T>[]): Observable<T>; concat<T>(sources: IPromise<T>[]): Observable<T>; merge<T>(...sources: Observable<T>[]): Observable<T>; merge<T>(...sources: IPromise<T>[]): Observable<T>; merge<T>(sources: Observable<T>[]): Observable<T>; merge<T>(sources: IPromise<T>[]): Observable<T>; merge<T>(scheduler: IScheduler, ...sources: Observable<T>[]): Observable<T>; merge<T>(scheduler: IScheduler, ...sources: IPromise<T>[]): Observable<T>; merge<T>(scheduler: IScheduler, sources: Observable<T>[]): Observable<T>; merge<T>(scheduler: IScheduler, sources: IPromise<T>[]): Observable<T>; pairs<T>(obj: { [key: string]: T }, scheduler?: IScheduler): Observable<[string, T]>; zip<T1, T2, TResult>(first: Observable<T1>, sources: Observable<T2>[], resultSelector: (item1: T1, ...right: T2[]) => TResult): Observable<TResult>; zip<T1, T2, TResult>(first: Observable<T1>, sources: IPromise<T2>[], resultSelector: (item1: T1, ...right: T2[]) => TResult): Observable<TResult>; zip<T1, T2, TResult>(source1: Observable<T1>, source2: Observable<T2>, resultSelector: (item1: T1, item2: T2) => TResult): Observable<TResult>; zip<T1, T2, TResult>(source1: Observable<T1>, source2: IPromise<T2>, resultSelector: (item1: T1, item2: T2) => TResult): Observable<TResult>; zip<T1, T2, T3, TResult>(source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable<TResult>; zip<T1, T2, T3, TResult>(source1: Observable<T1>, source2: Observable<T2>, source3: IPromise<T3>, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable<TResult>; zip<T1, T2, T3, TResult>(source1: Observable<T1>, source2: IPromise<T2>, source3: Observable<T3>, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable<TResult>; zip<T1, T2, T3, TResult>(source1: Observable<T1>, source2: IPromise<T2>, source3: IPromise<T3>, resultSelector: (item1: T1, item2: T2, item3: T3) => TResult): Observable<TResult>; zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>; zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: IPromise<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>; zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: Observable<T2>, source3: IPromise<T3>, source4: Observable<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>; zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: Observable<T2>, source3: IPromise<T3>, source4: IPromise<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>; zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: IPromise<T2>, source3: Observable<T3>, source4: Observable<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>; zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: IPromise<T2>, source3: Observable<T3>, source4: IPromise<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>; zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: IPromise<T2>, source3: IPromise<T3>, source4: Observable<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>; zip<T1, T2, T3, T4, TResult>(source1: Observable<T1>, source2: IPromise<T2>, source3: IPromise<T3>, source4: IPromise<T4>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4) => TResult): Observable<TResult>; zip<T1, T2, T3, T4, T5, TResult>(source1: Observable<T1>, source2: Observable<T2>, source3: Observable<T3>, source4: Observable<T4>, source5: Observable<T5>, resultSelector: (item1: T1, item2: T2, item3: T3, item4: T4, item5: T5) => TResult): Observable<TResult>; zipArray<T>(...sources: Observable<T>[]): Observable<T[]>; zipArray<T>(sources: Observable<T>[]): Observable<T[]>; /** * Converts a Promise to an Observable sequence * @param promise An ES6 Compliant promise. * @returns An Observable sequence which wraps the existing promise success and failure. */ fromPromise<T>(promise: IPromise<T>): Observable<T>; prototype: any; } export var Observable: ObservableStatic; interface ISubject<T> extends Observable<T>, Observer<T>, IDisposable { hasObservers(): boolean; } export interface Subject<T> extends ISubject<T> { } interface SubjectStatic { new <T>(): Subject<T>; create<T>(observer?: Observer<T>, observable?: Observable<T>): ISubject<T>; } export var Subject: SubjectStatic; export interface AsyncSubject<T> extends Subject<T> { } interface AsyncSubjectStatic { new <T>(): AsyncSubject<T>; } export var AsyncSubject: AsyncSubjectStatic; export interface TimeInterval<T> { value: T; interval: number; } export interface Timestamp<T> { value: T; timestamp: number; } export interface Observable<T> { delay(dueTime: Date, scheduler?: IScheduler): Observable<T>; delay(dueTime: number, scheduler?: IScheduler): Observable<T>; debounce(dueTime: number, scheduler?: IScheduler): Observable<T>; throttleWithTimeout(dueTime: number, scheduler?: IScheduler): Observable<T>; /** * @deprecated use #debounce or #throttleWithTimeout instead. */ throttle(dueTime: number, scheduler?: IScheduler): Observable<T>; timeInterval(scheduler?: IScheduler): Observable<TimeInterval<T>>; timestamp(scheduler?: IScheduler): Observable<Timestamp<T>>; sample(interval: number, scheduler?: IScheduler): Observable<T>; sample<TSample>(sampler: Observable<TSample>, scheduler?: IScheduler): Observable<T>; timeout(dueTime: Date, other?: Observable<T>, scheduler?: IScheduler): Observable<T>; timeout(dueTime: number, other?: Observable<T>, scheduler?: IScheduler): Observable<T>; } interface ObservableStatic { interval(period: number, scheduler?: IScheduler): Observable<number>; interval(dutTime: number, period: number, scheduler?: IScheduler): Observable<number>; timer(dueTime: number, period: number, scheduler?: IScheduler): Observable<number>; timer(dueTime: number, scheduler?: IScheduler): Observable<number>; } export interface BehaviorSubject<T> extends Subject<T> { getValue(): T; } interface BehaviorSubjectStatic { new <T>(initialValue: T): BehaviorSubject<T>; } export var BehaviorSubject: BehaviorSubjectStatic; export interface ReplaySubject<T> extends Subject<T> { } interface ReplaySubjectStatic { new <T>(bufferSize?: number, window?: number, scheduler?: IScheduler): ReplaySubject<T>; } export var ReplaySubject: ReplaySubjectStatic; interface ConnectableObservable<T> extends Observable<T> { connect(): IDisposable; refCount(): Observable<T>; } interface ConnectableObservableStatic { new <T>(): ConnectableObservable<T>; } export var ConnectableObservable: ConnectableObservableStatic; export interface Observable<T> { multicast(subject: Observable<T>): ConnectableObservable<T>; multicast<TResult>(subjectSelector: () => ISubject<T>, selector: (source: ConnectableObservable<T>) => Observable<T>): Observable<T>; publish(): ConnectableObservable<T>; publish<TResult>(selector: (source: ConnectableObservable<T>) => Observable<TResult>): Observable<TResult>; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); * * @returns An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ share(): Observable<T>; publishLast(): ConnectableObservable<T>; publishLast<TResult>(selector: (source: ConnectableObservable<T>) => Observable<TResult>): Observable<TResult>; publishValue(initialValue: T): ConnectableObservable<T>; publishValue<TResult>(selector: (source: ConnectableObservable<T>) => Observable<TResult>, initialValue: T): Observable<TResult>; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); * * @param initialValue Initial value received by observers upon subscription. * @returns An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ shareValue(initialValue: T): Observable<T>; replay(selector?: boolean, bufferSize?: number, window?: number, scheduler?: IScheduler): ConnectableObservable<T>; // hack to catch first omitted parameter replay(selector: (source: ConnectableObservable<T>) => Observable<T>, bufferSize?: number, window?: number, scheduler?: IScheduler): Observable<T>; shareReplay(bufferSize?: number, window?: number, scheduler?: IScheduler): Observable<T>; } } declare namespace LiteMolCIFTools { var VERSION: { number: string; date: string; }; } declare namespace LiteMolCIFTools.Utils { /** * A generic chunked array builder. * * When adding elements, the array growns by a specified number * of elements and no copying is done until ChunkedArray.compact * is called. */ interface ChunkedArray<T> { creator: (size: number) => any; elementSize: number; chunkSize: number; current: any; currentIndex: number; parts: any[]; elementCount: number; } namespace ChunkedArray { function is(x: any): x is ChunkedArray<any>; function add4<T>(array: ChunkedArray<T>, x: T, y: T, z: T, w: T): number; function add3<T>(array: ChunkedArray<T>, x: T, y: T, z: T): number; function add2<T>(array: ChunkedArray<T>, x: T, y: T): number; function add<T>(array: ChunkedArray<T>, x: T): number; function compact<T>(array: ChunkedArray<T>): T[]; function forVertex3D<T>(chunkVertexCount?: number): ChunkedArray<number>; function forIndexBuffer<T>(chunkIndexCount?: number): ChunkedArray<number>; function forTokenIndices<T>(chunkTokenCount?: number): ChunkedArray<number>; function forIndices<T>(chunkTokenCount?: number): ChunkedArray<number>; function forInt32<T>(chunkSize?: number): ChunkedArray<number>; function forFloat32<T>(chunkSize?: number): ChunkedArray<number>; function forArray<T>(chunkSize?: number): ChunkedArray<T>; function create<T>(creator: (size: number) => any, chunkElementCount: number, elementSize: number): ChunkedArray<T>; } } /** * Efficient integer and float parsers. * * For the purposes of parsing numbers from the mmCIF data representations, * up to 4 times faster than JS parseInt/parseFloat. */ declare namespace LiteMolCIFTools.Utils.FastNumberParsers { function parseIntSkipTrailingWhitespace(str: string, start: number, end: number): number; function parseInt(str: string, start: number, end: number): number; function parseFloatSkipTrailingWhitespace(str: string, start: number, end: number): number; function parseFloat(str: string, start: number, end: number): number; } declare namespace LiteMolCIFTools.Utils { interface StringWriter { chunkData: string[]; chunkOffset: number; chunkCapacity: number; data: string[]; } namespace StringWriter { function create(chunkCapacity?: number): StringWriter; function asString(writer: StringWriter): string; function writeTo(writer: StringWriter, stream: OutputStream): void; function newline(writer: StringWriter): void; function whitespace(writer: StringWriter, len: number): void; function write(writer: StringWriter, val: string): void; function writeSafe(writer: StringWriter, val: string): void; function writePadLeft(writer: StringWriter, val: string, totalWidth: number): void; function writePadRight(writer: StringWriter, val: string, totalWidth: number): void; function writeInteger(writer: StringWriter, val: number): void; function writeIntegerPadLeft(writer: StringWriter, val: number, totalWidth: number): void; function writeIntegerPadRight(writer: StringWriter, val: number, totalWidth: number): void; /** * @example writeFloat(123.2123, 100) -- 2 decim */ function writeFloat(writer: StringWriter, val: number, precisionMultiplier: number): void; function writeFloatPadLeft(writer: StringWriter, val: number, precisionMultiplier: number, totalWidth: number): void; function writeFloatPadRight(writer: StringWriter, val: number, precisionMultiplier: number, totalWidth: number): void; } } declare namespace LiteMolCIFTools { /** * Represents a "CIF FILE" with one or more data blocks. */ interface File { dataBlocks: DataBlock[]; toJSON(): any; } /** * Represents a single CIF data block that contains categories and possibly * additonal data such as save frames. * * Example: * data_HEADER * _category1.field1 * ... * ... * _categoryN.fieldN */ interface DataBlock { header: string; categories: Category[]; additionalData: { [name: string]: any; }; getCategory(name: string): Category | undefined; toJSON(): any; } /** * Represents that CIF category with multiple fields represented as columns. * * Example: * _category.field1 * _category.field2 * ... */ interface Category { name: string; rowCount: number; columnCount: number; columnNames: string[]; /** * If a field with the given name is not present, returns UndefinedColumn. * * Columns are accessed by their field name only, i.e. * _category.field is accessed by * category.getColumn('field') * * Note that column are created on demand and there is some computational * cost when creating a new column. Therefore, if you need to reuse a column, * it is a good idea to cache it. */ getColumn(name: string): Column; toJSON(): any; } const enum ValuePresence { Present = 0, NotSpecified = 1, Unknown = 2, } /** * A columns represents a single field of a CIF category. */ interface Column { isDefined: boolean; getString(row: number): string | null; getInteger(row: number): number; getFloat(row: number): number; getValuePresence(row: number): ValuePresence; areValuesEqual(rowA: number, rowB: number): boolean; stringEquals(row: number, value: string): boolean; } const UndefinedColumn: Column; /** * Helper functions for categoies. */ namespace Category { /** * Extracts a matrix from a category from a specified rowIndex. * * _category.matrix[1][1] v11 * .... * .... * _category.matrix[rows][cols] vRowsCols */ function getMatrix(category: Category, field: string, rows: number, cols: number, rowIndex: number): number[][]; /** * Extracts a vector from a category from a specified rowIndex. * * _category.matrix[1][1] v11 * .... * .... * _category.matrix[rows][cols] vRowsCols */ function getVector(category: Category, field: string, rows: number, cols: number, rowIndex: number): number[]; } } declare namespace LiteMolCIFTools { type ParserResult<T> = ParserSuccess<T> | ParserError; namespace ParserResult { function error<T>(message: string, line?: number): ParserResult<T>; function success<T>(result: T, warnings?: string[]): ParserResult<T>; } class ParserError { message: string; line: number; isError: true; toString(): string; constructor(message: string, line: number); } class ParserSuccess<T> { result: T; warnings: string[]; isError: false; constructor(result: T, warnings: string[]); } } declare namespace LiteMolCIFTools { interface FieldDesc<Data> { name: string; string?: (data: Data, i: number) => string | null; number?: (data: Data, i: number) => number; typedArray?: any; encoder?: Binary.Encoder; presence?: (data: Data, i: number) => ValuePresence; } interface CategoryDesc<Data> { name: string; fields: FieldDesc<Data>[]; } type CategoryInstance<Data> = { data: any; count: number; desc: CategoryDesc<Data>; }; type CategoryProvider = (ctx: any) => CategoryInstance<any> | undefined; type OutputStream = { writeString: (data: string) => boolean; writeBinary: (data: Uint8Array) => boolean; }; interface Writer<Context> { startDataBlock(header: string): void; writeCategory(category: CategoryProvider, contexts?: Context[]): void; encode(): void; flush(stream: OutputStream): void; } } declare namespace LiteMolCIFTools.Text { /** * Represents the input file. */ class File implements LiteMolCIFTools.File { /** * The input string. * * In JavaScript, the input must always* be a string as there is no support for streams. * So since we already have the string in memory, we won't store unnecessary copies of * substrings but rather represent individual elements as pairs of <start,end) indices * to the data string. * * * It can also be a typed array buffer, but the point still holds: we need to have the entire * input in memory. And most molecular file formats are text based. */ data: string; /** * Data blocks inside the file. If no data block is present, a "default" one is created. */ dataBlocks: DataBlock[]; toJSON(): { id: string; categories: { name: string; columns: string[]; rows: any[]; }[]; additionalData: { [name: string]: any; }; }[]; constructor(data: string); } /** * Represents a single data block. */ class DataBlock implements LiteMolCIFTools.DataBlock { private categoryMap; private categoryList; /** * The input mmCIF string (same as file.data) */ data: string; /** * Header of the data block. */ header: string; /** * Categories of the block. * block.categories._atom_site / ['_atom_site'] */ readonly categories: Category[]; /** * Additional data such as save frames for mmCIF file. */ additionalData: { [name: string]: any; }; /** * Gets a category by its name. */ getCategory(name: string): Category | undefined; /** * Adds a category. */ addCategory(category: Category): void; toJSON(): { id: string; categories: { name: string; columns: string[]; rows: any[]; }[]; additionalData: { [name: string]: any; }; }; constructor(data: string, header: string); } /** * Represents a single CIF category. */ class Category implements LiteMolCIFTools.Category { private data; private columnIndices; private columnNameList; /** * Name of the category. */ name: string; /** * The array of columns. */ readonly columnNames: string[]; /** * Number of columns in the category. */ columnCount: number; /** * Number of rows in the category. */ rowCount: number; /** * Pairs of (start at index 2 * i, end at index 2 * i + 1) indices to the data string. * The "end" character is not included (for it's iterated as for (i = start; i < end; i++)). */ tokens: number[]; /** * Start index of the category in the input string. */ startIndex: number; /** * Start index of the category in the input string. */ endIndex: number; /** * Get a column object that makes accessing data easier. * @returns undefined if the column isn't present, the Column object otherwise. */ getColumn(name: string): LiteMolCIFTools.Column; constructor(data: string, name: string, startIndex: number, endIndex: number, columns: string[], tokens: number[], tokenCount: number); toJSON(): { name: string; columns: string[]; rows: any[]; }; } /** * Represents a single column of a CIF category. */ class Column implements LiteMolCIFTools.Column { private data; name: string; index: number; private tokens; private columnCount; private rowCount; private stringPool; isDefined: boolean; /** * Returns the string value at given row. */ getString(row: number): string | null; /** * Returns the integer value at given row. */ getInteger(row: number): number; /** * Returns the float value at given row. */ getFloat(row: number): number; /** * Returns true if the token has the specified string value. */ stringEquals(row: number, value: string): boolean; /** * Determines if values at the given rows are equal. */ areValuesEqual(rowA: number, rowB: number): boolean; /** * Returns true if the value is not defined (. or ? token). */ getValuePresence(row: number): ValuePresence; constructor(category: Category, data: string, name: string, index: number); } } declare namespace LiteMolCIFTools.Text { function parse(data: string): ParserResult<LiteMolCIFTools.File>; } declare namespace LiteMolCIFTools.Text { class Writer<Context> implements LiteMolCIFTools.Writer<Context> { private writer; private encoded; private dataBlockCreated; startDataBlock(header: string): void; writeCategory(category: CategoryProvider, contexts?: Context[]): void; encode(): void; flush(stream: OutputStream): void; constructor(); } } declare namespace LiteMolCIFTools.Binary.MessagePack { function decode(buffer: Uint8Array): any; } declare namespace LiteMolCIFTools.Binary.MessagePack { function encode(value: any): Uint8Array; } declare namespace LiteMolCIFTools.Binary.MessagePack { function utf8Write(data: Uint8Array, offset: number, str: string): void; function utf8Read(data: Uint8Array, offset: number, length: number): string; function utf8ByteCount(str: string): number; } declare namespace LiteMolCIFTools.Binary { /** * Fixed point, delta, RLE, integer packing adopted from https://github.com/rcsb/mmtf-javascript/ * by Alexander Rose <alexander.rose@weirdbyte.de>, MIT License, Copyright (c) 2016 */ function decode(data: EncodedData): any; } declare namespace LiteMolCIFTools.Binary { class File implements LiteMolCIFTools.File { dataBlocks: DataBlock[]; toJSON(): { id: string; categories: { name: string; columns: string[]; rows: any[]; }[]; additionalData: { [name: string]: any; }; }[]; constructor(data: EncodedFile); } class DataBlock implements LiteMolCIFTools.DataBlock { private categoryMap; private categoryList; header: string; additionalData: { [name: string]: any; }; readonly categories: Category[]; getCategory(name: string): Category | undefined; toJSON(): { id: string; categories: { name: string; columns: string[]; rows: any[]; }[]; additionalData: { [name: string]: any; }; }; constructor(data: EncodedDataBlock); } class Category implements LiteMolCIFTools.Category { private encodedColumns; private columnNameList; name: string; columnCount: number; rowCount: number; readonly columnNames: string[]; getColumn(name: string): LiteMolCIFTools.Column; toJSON(): { name: string; columns: string[]; rows: any[]; }; constructor(data: EncodedCategory); } } declare namespace LiteMolCIFTools.Binary { /** * Fixed point, delta, RLE, integer packing adopted from https://github.com/rcsb/mmtf-javascript/ * by Alexander Rose <alexander.rose@weirdbyte.de>, MIT License, Copyright (c) 2016 */ class Encoder { private providers; and(f: Encoder.Provider): Encoder; encode(data: any): EncodedData; constructor(providers: Encoder.Provider[]); } namespace Encoder { interface Result { encodings: Encoding[]; data: any; } type Provider = (data: any) => Result; function by(f: Provider): Encoder; function byteArray(data: Encoding.FloatArray | Encoding.IntArray): Result; function fixedPoint(factor: number): Provider; function intervalQuantizaiton(min: number, max: number, numSteps: number, arrayType?: new (size: number) => Encoding.IntArray): Provider; function runLength(data: Encoding.IntArray): Result; function delta(data: Int8Array | Int16Array | Int32Array): Result; /** * Packs Int32 array. The packing level is determined automatically to either 1-, 2-, or 4-byte words. */ function integerPacking(data: Int32Array): Result; function stringArray(data: string[]): Result; } } declare namespace LiteMolCIFTools.Binary { const VERSION = "0.3.0"; type Encoding = Encoding.ByteArray | Encoding.FixedPoint | Encoding.RunLength | Encoding.Delta | Encoding.IntervalQuantization | Encoding.IntegerPacking | Encoding.StringArray; interface EncodedFile { version: string; encoder: string; dataBlocks: EncodedDataBlock[]; } interface EncodedDataBlock { header: string; categories: EncodedCategory[]; } interface EncodedCategory { name: string; rowCount: number; columns: EncodedColumn[]; } interface EncodedColumn { name: string; data: EncodedData; /** * The mask represents the presence or absent of particular "CIF value". * If the mask is not set, every value is present. * * 0 = Value is present * 1 = . = value not specified * 2 = ? = value unknown */ mask?: EncodedData; } interface EncodedData { encoding: Encoding[]; data: Uint8Array; } namespace Encoding { const enum IntDataType { Int8 = 1, Int16 = 2, Int32 = 3, Uint8 = 4, Uint16 = 5, Uint32 = 6, } const enum FloatDataType { Float32 = 32, Float64 = 33, } type DataType = IntDataType | FloatDataType; type IntArray = Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array; type FloatArray = Float32Array | Float64Array; function getDataType(data: IntArray | FloatArray): DataType; function isSignedIntegerDataType(data: IntArray): boolean; interface ByteArray { kind: 'ByteArray'; type: DataType; } interface FixedPoint { kind: 'FixedPoint'; factor: number; srcType: FloatDataType; } interface IntervalQuantization { kind: 'IntervalQuantization'; min: number; max: number; numSteps: number; srcType: FloatDataType; } interface RunLength { kind: 'RunLength'; srcType: IntDataType; srcSize: number; } interface Delta { kind: 'Delta'; origin: number; srcType: IntDataType; } interface IntegerPacking { kind: 'IntegerPacking'; byteCount: number; isUnsigned: boolean; srcSize: number; } interface StringArray { kind: 'StringArray'; dataEncoding: Encoding[]; stringData: string; offsetEncoding: Encoding[]; offsets: Uint8Array; } } } declare namespace LiteMolCIFTools.Binary { function parse(data: ArrayBuffer): ParserResult<LiteMolCIFTools.File>; } declare namespace LiteMolCIFTools.Binary { class Writer<Context> implements LiteMolCIFTools.Writer<Context> { private data; private dataBlocks; private encodedData; startDataBlock(header: string): void; writeCategory(category: CategoryProvider, contexts?: Context[]): void; encode(): void; flush(stream: OutputStream): void; constructor(encoder: string); } } declare namespace LiteMol { const Promise: PromiseConstructor; } declare namespace LiteMol.Core { export import Rx = __LiteMolRx; export import Promise = LiteMol.Promise; namespace Formats { export import CIF = LiteMolCIFTools; } } declare namespace LiteMol.Core { var VERSION: { number: string; date: string; }; } declare namespace LiteMol.Core.Scheduler { const immediate: any; const clearImmediate: any; function immediatePromise(): Promise<void>; } declare namespace LiteMol.Core { function computation<A>(c: (ctx: Computation.Context) => Promise<A>): Computation<A>; class Computation<A> { private computation; run(ctx?: Computation.Context): Promise<A>; runWithContext(ctx?: Computation.Context): Computation.Running<A>; constructor(computation: (ctx: Computation.Context) => Promise<A>); } module Computation { let PRINT_CONSOLE_ERROR: boolean; function resolve<A>(a: A): Computation<A>; function reject<A>(reason: any): Computation<A>; function createContext(): Computation.Context; const Aborted = "Aborted"; const UpdateProgressDelta = 100; interface Progress { message: string; isIndeterminate: boolean; current: number; max: number; requestAbort?: () => void; } interface Context { progress: Rx.Observable<Progress>; requestAbort(): void; /** * Checks if the computation was aborted. If so, throws. * Otherwise, updates the progress. */ updateProgress(msg: string, abort?: boolean | (() => void), current?: number, max?: number): Promise<void>; } interface Running<A> { progress: Rx.Observable<Progress>; result: Promise<A>; } } } declare namespace LiteMol.Core.Utils { /** * An "object" based implementation of map that supports string and numeric keys * which should be ok for most use cases in LiteMol. * * The type limitation is on purpose to prevent using the type in places that are * not appropriate. */ interface FastMap<K extends string | number, V> { readonly size: number; set(key: K, v: V): void; get(key: K): V | undefined; delete(key: K): boolean; has(key: K): boolean; clear(): void; /** * Iterate over the collection. * Optional "context" object can be supplied that is passed to the callback. * * Enumerates only values that are not undefined. */ forEach<Context>(f: (value: V, key: K, ctx?: Context) => void, ctx?: Context): void; } /** * An "object" based implementation of set that supports string and numeric values * which should be ok for most use cases in LiteMol. * * The type limitation is on purpose to prevent using the type in places that are * not appropriate. */ interface FastSet<T extends string | number> { readonly size: number; add(key: T): boolean; delete(key: T): boolean; has(key: T): boolean; clear(): void; /** * Iterate over the collection. * Optional "context" object can be supplied that is passed to the callback. */ forEach<Context>(f: (key: T, ctx?: Context) => void, ctx?: Context): void; } namespace FastMap { /** * Creates an empty map. */ function create<K extends string | number, V>(): FastMap<K, V>; /** * Create a map from an array of the form [[key, value], ...] */ function ofArray<K extends string | number, V>(data: [K, V][]): FastMap<K, V>; /** * Create a map from an object of the form { key: value, ... } */ function ofObject<V>(data: { [key: string]: V; }): FastMap<string, V>; } namespace FastSet { /** * Create an empty set. */ function create<T extends string | number>(): FastSet<T>; /** * Create a set of an "array like" sequence. */ function ofArray<T extends string | number>(xs: ArrayLike<T>): FastSet<T>; } /** * An optimized set-like structure. */ interface Mask { size: number; has(i: number): boolean; } namespace Mask { function ofStructure(structure: Structure.Molecule.Model): Mask; function ofIndices(totalCount: number, indices: number[]): Mask; function ofFragments(seq: Structure.Query.FragmentSeq): Mask; } } declare namespace LiteMol.Core.Utils { export import FastNumberParsers = Core.Formats.CIF.Utils.FastNumberParsers; function extend<S, T, U>(object: S, source: T, guard?: U): S & T & U; function debounce<T>(func: () => T, wait: number): () => T; } declare namespace LiteMol.Core.Utils { type DataTable<Schema> = DataTable.Base<Schema> & DataTable.Columns<Schema>; module DataTable { type Definition<Schema> = { [T in keyof Schema]: ((size: number) => Schema[T][]) | undefined; }; type Columns<Schema> = { readonly [P in keyof Schema]: Schema[P][]; }; interface ColumnDescriptor<Schema> { name: keyof Schema; creator: (size: number) => any; } type TypedArrayContructor = Float32ArrayConstructor | Float64ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int8ArrayConstructor | Uint8ArrayConstructor; function typedColumn(t: TypedArrayContructor): (size: number) => number[]; function customColumn<T>(): (size: number) => T[]; const stringColumn: (size: number) => string[]; const stringNullColumn: (size: number) => (string | null)[]; interface Base<Schema> { count: number; indices: number[]; columns: ColumnDescriptor<Schema>[]; getBuilder(count: number): Builder<Schema>; getRawData(): any[][]; /** * Get a MUTABLE representation of a row. * Calling getRow() with differnt 'i' will change update old reference. */ getRow(i: number): Schema; } interface Builder<Schema> { count: number; columns: ColumnDescriptor<Schema>[]; addColumn<T>(name: keyof Schema, creator: (size: number) => T): T; addRawColumn<T>(name: keyof Schema, creator: (size: number) => T, data: T): T; getRawData(): any[][]; /** * This functions clones the table and defines all its column inside the constructor, hopefully making the JS engine * use internal class instead of dictionary representation. */ seal(): DataTable<Schema>; } function builder<Schema>(count: number): Builder<Schema>; function ofDefinition<Schema>(definition: Definition<Schema>, count: number): DataTable<Schema>; } } declare namespace LiteMol.Core.Utils { function integerSetToSortedTypedArray(set: FastSet<number>): number[]; /** * A a JS native array with the given size. */ function makeNativeIntArray(size: number): number[]; /** * A a JS native array with the given size. */ function makeNativeFloatArray(size: number): number[]; /** * A generic chunked array builder. * * When adding elements, the array growns by a specified number * of elements and no copying is done until ChunkedArray.compact * is called. */ interface ChunkedArray<T> { creator: (size: number) => any; elementSize: number; chunkSize: number; current: any; currentIndex: number; parts: any[]; elementCount: number; } namespace ChunkedArray { function is(x: any): x is ChunkedArray<any>; function add4<T>(array: ChunkedArray<T>, x: T, y: T, z: T, w: T): number; function add3<T>(array: ChunkedArray<T>, x: T, y: T, z: T): number; function add2<T>(array: ChunkedArray<T>, x: T, y: T): number; function add<T>(array: ChunkedArray<T>, x: T): number; function compact<T>(array: ChunkedArray<T>): T[]; function forVertex3D(chunkVertexCount?: number): ChunkedArray<number>; function forIndexBuffer(chunkIndexCount?: number): ChunkedArray<number>; function forTokenIndices(chunkTokenCount?: number): ChunkedArray<number>; function forIndices(chunkTokenCount?: number): ChunkedArray<number>; function forInt32(chunkSize?: number): ChunkedArray<number>; function forFloat32(chunkSize?: number): ChunkedArray<number>; function forArray<T>(chunkSize?: number): ChunkedArray<T>; function create<T>(creator: (size: number) => any, chunkElementCount: number, elementSize: number): ChunkedArray<T>; } /** * Static size array builder. */ interface ArrayBuilder<T> { currentIndex: number; elementCount: number; array: T[]; } namespace ArrayBuilder { function add3<T>(array: ArrayBuilder<T>, x: T, y: T, z: T): void; function add2<T>(array: ArrayBuilder<T>, x: T, y: T): void; function add<T>(array: ArrayBuilder<T>, x: T): void; function forVertex3D(count: number): ArrayBuilder<number>; function forIndexBuffer(count: number): ArrayBuilder<number>; function forTokenIndices(count: number): ArrayBuilder<number>; function forIndices(count: number): ArrayBuilder<number>; function forInt32(count: number): ArrayBuilder<number>; function forFloat32(count: number): ArrayBuilder<number>; function forArray<T>(count: number): ArrayBuilder<T>; function create<T>(creator: (size: number) => any, chunkElementCount: number, elementSize: number): ArrayBuilder<T>; } interface UniqueArray<T extends number | string> { _set: FastSet<T>; array: T[]; } function UniqueArray<T extends number | string>(): UniqueArray<T>; namespace UniqueArray { function add<T extends number | string>({ _set, array }: UniqueArray<T>, e: T): void; } } declare namespace LiteMol.Core.Utils { class PerformanceMonitor { private starts; private ends; static currentTime(): number; start(name: string): void; end(name: string): void; static format(t: number): string; formatTime(name: string): string; formatTimeSum(...names: string[]): string; time(name: string): number; timeSum(...names: string[]): number; } } declare namespace LiteMol.Core.Formats { interface FormatInfo { name: string; shortcuts: string[]; extensions: string[]; isBinary?: boolean; parse: (data: string | ArrayBuffer, params?: FormatInfo.Params) => Computation<ParserResult<any>>; } namespace FormatInfo { type Params = { id?: string; }; function is(o: any): o is FormatInfo; function fromShortcut(all: FormatInfo[], name: string): FormatInfo | undefined; function formatRegExp(info: FormatInfo): RegExp; function formatFileFilters(all: FormatInfo[]): string; function getFormat(filename: string, all: FormatInfo[]): FormatInfo | undefined; } type ParserResult<T> = ParserSuccess<T> | ParserError; namespace ParserResult { function error<T>(message: string, line?: number): ParserResult<T>; function success<T>(result: T, warnings?: string[]): ParserResult<T>; } class ParserError { message: string; line: number; isError: true; toString(): string; constructor(message: string, line: number); } class ParserSuccess<T> { result: T; warnings: string[]; isError: false; constructor(result: T, warnings: string[]); } /** * A helper for building a typed array of token indices. */ interface TokenIndexBuilder { tokensLenMinus2: number; count: number; tokens: Int32Array; } namespace TokenIndexBuilder { function addToken(builder: TokenIndexBuilder, start: number, end: number): void; function create(size: number): TokenIndexBuilder; } /** * This ensures there is only 1 instance of a short string. */ type ShortStringPool = { [key: string]: string; }; namespace ShortStringPool { function create(): ShortStringPool; function get(pool: ShortStringPool, str: string): string; } } declare namespace LiteMol.Core.Formats.Molecule.mmCIF { type StructConnType = 'covale' | 'covale_base' | 'covale_phosphate' | 'covale_sugar' | 'disulf' | 'hydrog' | 'metalc' | 'mismat' | 'modres' | 'saltbr'; function ofDataBlock(data: CIF.DataBlock): Structure.Molecule; } declare namespace LiteMol.Core.Formats.Molecule.PDB { type TokenRange = { start: number; end: number; }; type HelperData = { dot: TokenRange; question: TokenRange; numberTokens: Utils.FastMap<number, TokenRange>; data: string; }; class MoleculeData { header: Header; crystInfo: CrystStructureInfo | undefined; models: ModelsData; data: string; private makeEntities; toCifFile(): CIF.File; constructor(header: Header, crystInfo: CrystStructureInfo | undefined, models: ModelsData, data: string); } class Header { id: string; constructor(id: string); } class CrystStructureInfo { record: string; private getValue; toCifCategory(id: string): { cell: CIF.Category | undefined; symm: CIF.Category | undefined; }; constructor(record: string); } class SecondaryStructure { helixTokens: number[]; sheetTokens: number[]; toCifCategory(data: string): { helices: CIF.Category; sheets: CIF.Category; } | undefined; constructor(helixTokens: number[], sheetTokens: number[]); } class ModelData { idToken: TokenRange; atomTokens: number[]; atomCount: number; static COLUMNS: string[]; private writeToken; private writeTokenCond; private writeRange; private tokenEquals; private getEntityType; writeCifTokens(modelToken: TokenRange, cifTokens: Utils.ArrayBuilder<number>, helpers: HelperData): void; constructor(idToken: TokenRange, atomTokens: number[], atomCount: number); } class ModelsData { models: ModelData[]; toCifCategory(block: CIF.Text.DataBlock, helpers: HelperData): CIF.Text.Category; constructor(models: ModelData[]); } } declare namespace LiteMol.Core.Formats.Molecule.PDB { class Parser { private static tokenizeAtom; private static tokenize; static getDotRange(length: number): TokenRange; static getNumberRanges(length: number): Utils.FastMap<number, TokenRange>; static getQuestionmarkRange(length: number): TokenRange; static parse(id: string, data: string): ParserResult<CIF.File>; } function toCifFile(id: string, data: string): ParserResult<CIF.File>; } declare namespace LiteMol.Core.Formats.Molecule.SDF { function parse(data: string, id?: string): ParserResult<Structure.Molecule>; } declare namespace LiteMol.Core.Formats.Molecule { namespace SupportedFormats { const mmCIF: FormatInfo; const mmBCIF: FormatInfo; const PDB: FormatInfo; const SDF: FormatInfo; const All: FormatInfo[]; } } declare namespace LiteMol.Core.Formats.Density { interface Field3D { dimensions: number[]; length: number; getAt(idx: number): number; setAt(idx: number, v: number): void; get(i: number, j: number, k: number): number; set(i: number, j: number, k: number, v: number): void; fill(v: number): void; } /** * A field with the Z axis being the slowest and the X being the fastest. */ class Field3DZYX implements Field3D { data: number[]; dimensions: number[]; private nX; private nY; private len; readonly length: number; getAt(idx: number): number; setAt(idx: number, v: number): void; get(i: number, j: number, k: number): number; set(i: number, j: number, k: number, v: number): void; fill(v: number): void; constructor(data: number[], dimensions: number[]); } interface Spacegroup { number: number; size: number[]; angles: number[]; basis: { x: number[]; y: number[]; z: number[]; }; } /** * Represents electron density data. */ interface Data { name?: string; spacegroup: Spacegroup; box: { /** Origin of the data block in fractional coords. */ origin: number[]; /** Dimensions oft he data block in fractional coords. */ dimensions: number[]; /** X, Y, Z dimensions of the data matrix. */ sampleCount: number[]; }; /** * 3D volumetric data. */ data: Field3D; /** * Information about the min/max/mean/sigma values. */ valuesInfo: { min: number; max: number; mean: number; sigma: number; }; } function createSpacegroup(number: number, size: number[], angles: number[]): Spacegroup; } declare namespace LiteMol.Core.Formats.Density.CCP4 { function parse(buffer: ArrayBuffer): ParserResult<Data>; } declare namespace LiteMol.Core.Formats.Density.CIF { function parse(block: Formats.CIF.DataBlock): ParserResult<Data>; } declare namespace LiteMol.Core.Formats.Density { namespace SupportedFormats { const CCP4: FormatInfo; const All: FormatInfo[]; } } declare namespace LiteMol.Core.Geometry.LinearAlgebra { type Matrix4 = number[]; type Vector3 = number[]; type Vector4 = number[]; function Matrix4(): number[]; /** * Stores a 4x4 matrix in a column major (j * 4 + i indexing) format. */ namespace Matrix4 { function zero(): number[]; function identity(): number[]; function fromIdentity(mat: number[]): number[]; function ofRows(rows: number[][]): number[]; function areEqual(a: number[], b: number[], eps: number): boolean; function setValue(a: number[], i: number, j: number, value: number): void; function copy(out: number[], a: number[]): number[]; function clone(a: number[]): number[]; function invert(out: number[], a: number[]): number[] | null; function mul(out: number[], a: number[], b: number[]): number[]; function mul3(out: number[], a: number[], b: number[], c: number[]): number[]; function translate(out: number[], a: number[], v: number[]): number[]; function fromTranslation(out: number[], v: number[]): number[]; function rotate(out: number[], a: number[], rad: number, axis: number[]): number[] | null; function fromRotation(out: number[], rad: number, axis: number[]): number[]; function scale(out: number[], a: number[], v: number[]): number[]; function fromScaling(out: number[], v: number[]): number[]; function makeTable(m: number[]): string; function determinant(a: number[]): number; } function Vector3(x?: number, y?: number, z?: number): number[]; namespace Vector3 { function zero(): number[]; function clone(a: number[]): number[]; function fromObj(v: { x: number; y: number; z: number; }): number[]; function toObj(v: number[]): { x: number; y: number; z: number; }; function fromValues(x: number, y: number, z: number): number[]; function set(out: number[], x: number, y: number, z: number): number[]; function copy(out: number[], a: number[]): number[]; function add(out: number[], a: number[], b: number[]): number[]; function sub(out: number[], a: number[], b: number[]): number[]; function scale(out: number[], a: number[], b: number): number[]; function scaleAndAdd(out: number[], a: number[], b: number[], scale: number): number[]; function distance(a: number[], b: number[]): number; function squaredDistance(a: number[], b: number[]): number; function magnitude(a: number[]): number; function squaredMagnitude(a: number[]): number; function normalize(out: number[], a: number[]): number[]; function dot(a: number[], b: number[]): number; function cross(out: number[], a: number[], b: number[]): number[]; function lerp(out: number[], a: number[], b: number[], t: number): number[]; function transformMat4(out: number[], a: number[], m: number[]): number[]; function angle(a: number[], b: number[]): number; function makeRotation(mat: Matrix4, a: Vector3, b: Vector3): Matrix4; } function Vector4(x?: number, y?: number, z?: number, w?: number): number[]; namespace Vector4 { function zero(): number[]; function clone(a: number[]): number[]; function fromValues(x: number, y: number, z: number, w: number): number[]; function set(out: number[], x: number, y: number, z: number, w: number): number[]; function distance(a: number[], b: number[]): number; function squaredDistance(a: number[], b: number[]): number; function norm(a: number[]): number; function squaredNorm(a: number[]): number; function transform(out: number[], a: number[], m: number[]): number[]; } } declare namespace LiteMol.Core.Geometry { interface Surface { /** * Number of vertices. */ vertexCount: number; /** * Number of triangles. */ triangleCount: number; /** * Array of size 3 * vertexCount. Layout [x1, y1, z1, ...., xn, yn, zn] */ vertices: Float32Array; /** * 3 indexes for each triangle */ triangleIndices: Uint32Array; /** * Per vertex annotation. */ annotation?: number[]; /** * Array of size 3 * vertexCount. Layout [x1, y1, z1, ...., xn, yn, zn] * * Computed on demand. */ normals?: Float32Array; /** * Bounding sphere. */ boundingSphere?: { center: Geometry.LinearAlgebra.Vector3; radius: number; }; } namespace Surface { function computeNormalsImmediate(surface: Surface): void; function computeNormals(surface: Surface): Computation<Surface>; function laplacianSmooth(surface: Surface, iterCount?: number, vertexWeight?: number): Computation<Surface>; function computeBoundingSphere(surface: Surface): Computation<Surface>; function transformImmediate(surface: Surface, t: number[]): void; function transform(surface: Surface, t: number[]): Computation<Surface>; } } declare namespace LiteMol.Core.Geometry.Query3D { /** * Query context. Handles the actual querying. */ type QueryFunc<T> = (x: number, y: number, z: number, radius: number) => Result<T>; interface Result<T> { readonly count: number; readonly elements: T[]; readonly squaredDistances: number[]; } interface InputData<T> { elements: T[]; indices: Int32Array; bounds: Box3D; positions: number[]; } type LookupStructure<T> = () => QueryFunc<T>; /** * A helper to store boundary box. */ interface Box3D { min: number[]; max: number[]; } namespace Box3D { function createInfinite(): Box3D; } /** * Query context. Handles the actual querying. */ interface QueryContext<T> { structure: T; pivot: number[]; radius: number; radiusSq: number; buffer: QueryContext.Buffer; } namespace QueryContext { interface Buffer { sourceElements: any[]; count: number; elements: any[]; squaredDistances: number[]; } function add<T>(ctx: QueryContext<T>, distSq: number, index: number): void; /** * Query the tree and store the result to this.buffer. Overwrites the old result. */ function update<T>(ctx: QueryContext<T>, x: number, y: number, z: number, radius: number): void; function create<T>(structure: T, sourceElements: any[]): QueryContext<T>; } function createInputData<T>(elements: T[], f: (e: T, add: (x: number, y: number, z: number) => void) => void): InputData<T>; } declare namespace LiteMol.Core.Geometry.Query3D { function createSubdivisionTree<T>(data: InputData<T>, leafSize?: number): LookupStructure<T>; } declare namespace LiteMol.Core.Geometry.Query3D { function createSpatialHash<T>(data: InputData<T>): LookupStructure<T>; } declare namespace LiteMol.Core.Geometry.MarchingCubes { /** * The parameters required by the algorithm. */ interface MarchingCubesParameters { isoLevel: number; scalarField: Formats.Density.Field3D; bottomLeft?: number[]; topRight?: number[]; annotationField?: Formats.Density.Field3D; } function compute(parameters: MarchingCubesParameters): Computation<Surface>; } declare namespace LiteMol.Core.Geometry.MarchingCubes { class Index { i: number; j: number; k: number; constructor(i: number, j: number, k: number); } class IndexPair { a: Index; b: Index; constructor(a: Index, b: Index); } var EdgesXY: number[][]; var EdgesXZ: number[][]; var EdgesYZ: number[][]; var CubeVertices: Index[]; var CubeEdges: IndexPair[]; var EdgeIdInfo: { i: number; j: number; k: number; e: number; }[]; var EdgeTable: number[]; var TriTable: number[][]; } declare namespace LiteMol.Core.Geometry.MolecularSurface { interface MolecularIsoSurfaceParameters { exactBoundary?: boolean; boundaryDelta?: { dx: number; dy: number; dz: number; }; probeRadius?: number; atomRadius?: (i: number) => number; density?: number; interactive?: boolean; smoothingIterations?: number; } interface MolecularIsoField { data: Geometry.MarchingCubes.MarchingCubesParameters; bottomLeft: Geometry.LinearAlgebra.Vector3; topRight: Geometry.LinearAlgebra.Vector3; transform: number[]; inputParameters: MolecularSurfaceInputParameters; parameters: MolecularIsoSurfaceParameters; } interface MolecularIsoSurfaceGeometryData { surface: Surface; usedParameters: MolecularIsoSurfaceParameters; } function createMolecularIsoFieldAsync(parameters: MolecularSurfaceInputParameters): Computation<MolecularIsoField>; interface MolecularSurfaceInputParameters { positions: Core.Structure.PositionTable; atomIndices: number[]; parameters?: MolecularIsoSurfaceParameters; } function computeMolecularSurfaceAsync(parameters: MolecularSurfaceInputParameters): Computation<MolecularIsoSurfaceGeometryData>; } declare namespace LiteMol.Core.Structure { import DataTable = Utils.DataTable; interface Position { x: number; y: number; z: number; } interface Atom { id: number; name: string; authName: string; elementSymbol: string; altLoc: string | null; occupancy: number; tempFactor: number; residueIndex: number; chainIndex: number; entityIndex: number; rowIndex: number; } interface Residue { name: string; seqNumber: number; asymId: string; authName: string; authSeqNumber: number; authAsymId: string; insCode: string | null; entityId: string; isHet: number; atomStartIndex: number; atomEndIndex: number; chainIndex: number; entityIndex: number; secondaryStructureIndex: number; } interface Chain { asymId: string; authAsymId: string; entityId: string; atomStartIndex: number; atomEndIndex: number; residueStartIndex: number; residueEndIndex: number; entityIndex: number; sourceChainIndex: number; operatorIndex: number; } interface Entity { entityId: string; atomStartIndex: number; atomEndIndex: number; residueStartIndex: number; residueEndIndex: number; chainStartIndex: number; chainEndIndex: number; type: Entity.Type; } namespace Entity { type Type = 'polymer' | 'non-polymer' | 'water' | 'unknown'; } interface Bond { atomAIndex: number; atomBIndex: number; type: BondType; } interface ModifiedResidue { asymId: string; seqNumber: number; insCode: string | null; parent: string; details: string | null; } class ComponentBondInfoEntry { id: string; map: Utils.FastMap<string, Utils.FastMap<string, BondType>>; add(a: string, b: string, order: BondType, swap?: boolean): void; constructor(id: string); } class ComponentBondInfo { entries: Utils.FastMap<string, ComponentBondInfoEntry>; newEntry(id: string): ComponentBondInfoEntry; } /** * Identifier for a reside that is a part of the polymer. */ class PolyResidueIdentifier { asymId: string; seqNumber: number; insCode: string | null; constructor(asymId: string, seqNumber: number, insCode: string | null); static areEqual(a: PolyResidueIdentifier, index: number, bAsymId: string[], bSeqNumber: number[], bInsCode: string[]): boolean; static compare(a: PolyResidueIdentifier, b: PolyResidueIdentifier): 0 | 1 | -1; static compareResidue(a: PolyResidueIdentifier, index: number, bAsymId: string[], bSeqNumber: number[], bInsCode: string[]): 0 | 1 | -1; } const enum SecondaryStructureType { None = 0, Helix = 1, Turn = 2, Sheet = 3, AminoSeq = 4, Strand = 5 } class SecondaryStructureElement { type: SecondaryStructureType; startResidueId: PolyResidueIdentifier; endResidueId: PolyResidueIdentifier; info: any; startResidueIndex: number; endResidueIndex: number; readonly length: number; constructor(type: SecondaryStructureType, startResidueId: PolyResidueIdentifier, endResidueId: PolyResidueIdentifier, info?: any); } class SymmetryInfo { spacegroupName: string; cellSize: number[]; cellAngles: number[]; toFracTransform: number[]; isNonStandardCrytalFrame: boolean; constructor(spacegroupName: string, cellSize: number[], cellAngles: number[], toFracTransform: number[], isNonStandardCrytalFrame: boolean); } /** * Wraps _struct_conn mmCIF category. */ class StructConn { entries: StructConn.Entry[]; private _residuePairIndex; private _atomIndex; private static _resKey; private getResiduePairIndex; private getAtomIndex; private static _emptyEntry; getResidueEntries(residueAIndex: number, residueBIndex: number): ReadonlyArray<StructConn.Entry>; getAtomEntries(atomIndex: number): ReadonlyArray<StructConn.Entry>; constructor(entries: StructConn.Entry[]); } namespace StructConn { interface Entry { distance: number; bondType: BondType; partners: { residueIndex: number; atomIndex: number; symmetry: string; }[]; } } /** * Wraps an assembly operator. */ class AssemblyOperator { id: string; name: string; operator: number[]; constructor(id: string, name: string, operator: number[]); } /** * Wraps a single assembly gen entry. */ class AssemblyGenEntry { operators: string[][]; asymIds: string[]; constructor(operators: string[][], asymIds: string[]); } /** * Wraps an assembly generation template. */ class AssemblyGen { name: string; gens: AssemblyGenEntry[]; constructor(name: string); } /** * Information about the assemblies. */ class AssemblyInfo { operators: { [id: string]: AssemblyOperator; }; assemblies: AssemblyGen[]; constructor(operators: { [id: string]: AssemblyOperator; }, assemblies: AssemblyGen[]); } type PositionTable = DataTable<Position>; type AtomTable = DataTable<Atom>; type ResidueTable = DataTable<Residue>; type ChainTable = DataTable<Chain>; type EntityTable = DataTable<Entity>; type BondTable = DataTable<Bond>; type ModifiedResidueTable = DataTable<ModifiedResidue>; /** * Default Builders */ namespace Tables { const Positions: DataTable.Definition<Position>; const Atoms: DataTable.Definition<Atom>; const Residues: DataTable.Definition<Residue>; const Chains: DataTable.Definition<Chain>; const Entities: DataTable.Definition<Entity>; const Bonds: DataTable.Definition<Bond>; const ModifiedResidues: DataTable.Definition<ModifiedResidue>; } class Operator { matrix: number[]; id: string; isIdentity: boolean; apply(v: Geometry.LinearAlgebra.Vector3): void; static applyToModelUnsafe(matrix: number[], m: Molecule.Model): void; constructor(matrix: number[], id: string, isIdentity: boolean); } interface Molecule { readonly properties: Molecule.Properties; readonly id: string; readonly models: Molecule.Model[]; } namespace Molecule { function create(id: string, models: Model[], properties?: Properties): Molecule; interface Properties { experimentMethods?: string[]; } interface Bonds { readonly structConn?: StructConn; readonly input?: BondTable; readonly component?: ComponentBondInfo; } interface Model extends Model.Base { readonly queryContext: Query.Context; } namespace Model { function create(model: Base): Model; enum Source { File = 0, Computed = 1 } interface Base { readonly id: string; readonly modelId: string; readonly positions: PositionTable; readonly data: Data; readonly source: Source; readonly parent?: Model; readonly operators?: Operator[]; } interface Data { readonly atoms: AtomTable; readonly residues: ResidueTable; readonly chains: ChainTable; readonly entities: EntityTable; readonly bonds: Bonds; readonly secondaryStructure: SecondaryStructureElement[]; readonly modifiedResidues?: ModifiedResidueTable; readonly symmetryInfo?: SymmetryInfo; readonly assemblyInfo?: AssemblyInfo; } function withTransformedXYZ<T>(model: Model, ctx: T, transform: (ctx: T, x: number, y: number, z: number, out: Geometry.LinearAlgebra.Vector3) => void): Model; } } } declare namespace LiteMol.Core.Structure { const enum BondType { Unknown = 0, Single = 1, Double = 2, Triple = 3, Aromatic = 4, DisulfideBridge = 5, Metallic = 6, Ion = 7, Hydrogen = 8 } function isBondTypeCovalent(t: BondType): boolean; interface BondComputationParameters { maxHbondLength: number; forceCompute: boolean; } function computeBonds(model: Molecule.Model, atomIndices: number[], params?: Partial<BondComputationParameters>): Utils.DataTable<Bond>; } declare namespace LiteMol.Core.Structure { class Spacegroup { info: Structure.SymmetryInfo; private temp; private tempV; private space; private operators; readonly operatorCount: number; getOperatorMatrix(index: number, i: number, j: number, k: number, target: number[]): number[]; private getSpace; private static getOperator; private getOperators; constructor(info: Structure.SymmetryInfo); } namespace SpacegroupTables { var Transform: number[][]; var Operator: number[][]; var Group: number[][]; var Spacegroup: { [key: string]: number; }; } } declare namespace LiteMol.Core.Structure { function buildPivotGroupSymmetry(model: Molecule.Model, radius: number, pivotsQuery?: Query.Source): Molecule.Model; function buildSymmetryMates(model: Molecule.Model, radius: number): Molecule.Model; function buildAssembly(model: Molecule.Model, assembly: AssemblyGen): Molecule.Model; } declare namespace LiteMol.Core.Structure { /** * The query is a mapping from a context to a sequence of fragments. */ type Query = (ctx: Query.Context) => Query.FragmentSeq; namespace Query { function apply(q: Source, m: Molecule.Model): FragmentSeq; type Source = Query | string | Builder; /** * The context of a query. * * Stores: * - the mask of "active" atoms. * - kd-tree for fast geometry queries. * - the molecule itself. * */ class Context { readonly mask: Utils.Mask; private lazyLoopup3d; /** * Number of atoms in the current context. */ readonly atomCount: number; /** * Determine if the context contains all atoms of the input model. */ readonly isComplete: boolean; /** * The structure this context is based on. */ structure: Molecule.Model; /** * Get a 3d loopup structure for the atoms in the current context. */ readonly lookup3d: Geometry.Query3D.LookupStructure<number>; /** * Checks if an atom is included in the current context. */ hasAtom(index: number): boolean; /** * Checks if an atom from the range is included in the current context. */ hasRange(start: number, end: number): boolean; /** * Create a new context based on the provide structure. */ static ofStructure(structure: Molecule.Model): Context; /** * Create a new context from a sequence of fragments. */ static ofFragments(seq: FragmentSeq): Context; /** * Create a new context from a sequence of fragments. */ static ofAtomIndices(structure: Molecule.Model, atomIndices: number[]): Context; constructor(structure: Molecule.Model, mask: Utils.Mask); private makeLookup3d; } /** * The basic element of the query language. * Everything is represented as a fragment. */ class Fragment { /** * The index of the first atom of the generator. */ tag: number; /** * Indices of atoms. */ atomIndices: number[]; /** * The context the fragment belongs to. */ context: Context; private _hashCode; private _hashComputed; /** * The hash code of the fragment. */ readonly hashCode: number; /** * Id composed of <moleculeid>_<tag>. */ readonly id: string; /** * Number of atoms. */ readonly atomCount: number; /** * Determines if a fragment is HET based on the tag. */ readonly isHet: any; private _fingerprint; /** * A sorted list of residue identifiers. */ readonly fingerprint: string; private _authFingerprint; /** * A sorted list of residue identifiers. */ readonly authFingerprint: string; /** * Executes a query on the current fragment. */ find(what: Source): FragmentSeq; private _residueIndices; private _chainIndices; private _entityIndices; private computeIndices; /** * A sorted list of residue indices. */ readonly residueIndices: number[]; /** * A sorted list of chain indices. */ readonly chainIndices: number[]; /** * A sorted list of entity indices. */ readonly entityIndices: number[]; static areEqual(a: Fragment, b: Fragment): boolean; /** * Create a fragment from an integer set. * Assumes the set is in the given context's mask. */ static ofSet(context: Context, atomIndices: Utils.FastSet<number>): Fragment; /** * Create a fragment from an integer array. * Assumes the set is in the given context's mask. * Assumes the array is sorted. */ static ofArray(context: Context, tag: number, atomIndices: Int32Array | number[]): Fragment; /** * Create a fragment from a single index. * Assumes the index is in the given context's mask. */ static ofIndex(context: Context, index: number): Fragment; /** * Create a fragment from a <start,end) range. * Assumes the fragment is non-empty in the given context's mask. */ static ofIndexRange(context: Context, start: number, endExclusive: number): Fragment; /** * Create a fragment from an integer set. */ constructor(context: Context, tag: number, atomIndices: number[]); } /** * A sequence of fragments the queries operate on. */ class FragmentSeq { context: Context; fragments: Fragment[]; static empty(ctx: Context): FragmentSeq; readonly length: number; /** * Merges atom indices from all fragments. */ unionAtomIndices(): number[]; /** * Merges atom indices from all fragments into a single fragment. */ unionFragment(): Fragment; constructor(context: Context, fragments: Fragment[]); } /** * A builder that includes all fragments. */ class FragmentSeqBuilder { private ctx; private fragments; add(f: Fragment): void; getSeq(): FragmentSeq; constructor(ctx: Context); } /** * A builder that includes only unique fragments. */ class HashFragmentSeqBuilder { private ctx; private fragments; private byHash; add(f: Fragment): this; getSeq(): FragmentSeq; constructor(ctx: Context); } } } declare namespace LiteMol.Core.Structure.Query { interface Builder { compile(): Query; complement(): Builder; ambientResidues(radius: number): Builder; wholeResidues(): Builder; union(): Builder; inside(where: Source): Builder; intersectWith(where: Source): Builder; flatten(selector: (f: Fragment) => FragmentSeq): Builder; except(toRemove: Source): Builder; } namespace Builder { const BuilderPrototype: any; function registerModifier(name: string, f: Function): void; function build(compile: () => Query): Builder; function parse(query: string): Query; function toQuery(q: Source): Query; } interface EntityIdSchema { entityId?: string; type?: string; } interface AsymIdSchema extends EntityIdSchema { asymId?: string; authAsymId?: string; } interface ResidueIdSchema extends AsymIdSchema { name?: string; seqNumber?: number; authName?: string; authSeqNumber?: number; insCode?: string | null; } function allAtoms(): Builder; function atomsByElement(...elements: string[]): Builder; function atomsByName(...names: string[]): Builder; function atomsById(...ids: number[]): Builder; function residues(...ids: ResidueIdSchema[]): Builder; function chains(...ids: AsymIdSchema[]): Builder; function entities(...ids: EntityIdSchema[]): Builder; function notEntities(...ids: EntityIdSchema[]): Builder; function everything(): Builder; function entitiesFromIndices(indices: number[]): Builder; function chainsFromIndices(indices: number[]): Builder; function residuesFromIndices(indices: number[]): Builder; function atomsFromIndices(indices: number[]): Builder; function sequence(entityId: string | undefined, asymId: string | AsymIdSchema, startId: ResidueIdSchema, endId: ResidueIdSchema): Builder; function hetGroups(): Builder; function nonHetPolymer(): Builder; function polymerTrace(...atomNames: string[]): Builder; function cartoons(): Builder; function backbone(): Builder; function sidechain(): Builder; function atomsInBox(min: { x: number; y: number; z: number; }, max: { x: number; y: number; z: number; }): Builder; function or(...elements: Source[]): Builder; function complement(q: Source): Builder; function ambientResidues(q: Source, radius: number): Builder; function wholeResidues(q: Source): Builder; function union(q: Source): Builder; function inside(q: Source, where: Source): Builder; function intersectWith(what: Source, where: Source): Builder; function flatten(what: Source, selector: (f: Fragment) => FragmentSeq): Builder; function except(what: Source, toRemove: Source): Builder; /** * Shortcuts */ function residuesByName(...names: string[]): Builder; function residuesById(...ids: number[]): Builder; function chainsById(...ids: string[]): Builder; /** * Query compilation wrapper. */ namespace Compiler { function compileEverything(): (ctx: Context) => FragmentSeq; function compileAllAtoms(): (ctx: Context) => FragmentSeq; function compileAtoms(elements: string[] | number[], sel: (model: Structure.Molecule.Model) => string[] | number[]): (ctx: Context) => FragmentSeq; function compileAtomIndices(indices: number[]): (ctx: Context) => FragmentSeq; function compileFromIndices(complement: boolean, indices: number[], tableProvider: (molecule: Structure.Molecule.Model) => { atomStartIndex: number[]; atomEndIndex: number[]; } & Utils.DataTable<any>): Query; function compileAtomRanges(complement: boolean, ids: ResidueIdSchema[], tableProvider: (molecule: Structure.Molecule.Model) => { atomStartIndex: number[]; atomEndIndex: number[]; } & Utils.DataTable<any>): Query; function compileSequence(seqEntityId: string | undefined, seqAsymId: string | AsymIdSchema, start: ResidueIdSchema, end: ResidueIdSchema): Query; function compileHetGroups(): Query; function compileNonHetPolymer(): Query; function compileAtomsInBox(min: { x: number; y: number; z: number; }, max: { x: number; y: number; z: number; }): Query; function compileInside(what: Source, where: Source): Query; function compileIntersectWith(what: Source, where: Source): Query; function compileFilter(what: Source, filter: (f: Fragment) => boolean): Query; function compileComplement(what: Source): Query; function compileOr(queries: Source[]): Query; function compileUnion(what: Source): Query; function compilePolymerNames(names: string[], complement: boolean): Query; function compileAmbientResidues(where: Source, radius: number): (ctx: Context) => FragmentSeq; function compileWholeResidues(where: Source): (ctx: Context) => FragmentSeq; function compileFlatten(what: Source, selector: (f: Fragment) => FragmentSeq): (ctx: Context) => FragmentSeq; function compileExcept(what: Source, toRemove: Source): (ctx: Context) => FragmentSeq; } } declare namespace LiteMol.Core.Structure.Query.Algebraic { type Predicate = (ctx: Context, i: number) => boolean; type Selector = (ctx: Context, i: number) => any; const not: (a: Predicate) => Predicate; const and: (a: Predicate, b: Predicate) => Predicate; const or: (a: Predicate, b: Predicate) => Predicate; const backbone: Predicate; const sidechain: Predicate; const equal: (a: Selector, b: Selector) => Predicate; const notEqual: (a: Selector, b: Selector) => Predicate; const greater: (a: Selector, b: Selector) => Predicate; const lesser: (a: Selector, b: Selector) => Predicate; const greaterEqual: (a: Selector, b: Selector) => Predicate; const lesserEqual: (a: Selector, b: Selector) => Predicate; function inRange(s: Selector, a: number, b: number): Predicate; /** * Selectors */ function value(v: any): Selector; const residueSeqNumber: Selector; const residueName: Selector; const elementSymbol: Selector; const atomName: Selector; const entityType: Selector; /** * Query */ function query(p: Predicate): Builder; } declare module 'LiteMol-core' { import __Core = LiteMol.Core; export = __Core; }
the_stack
import { pascalCase } from 'pascal-case'; import * as cdk from '@aws-cdk/core'; import * as ec2 from '@aws-cdk/aws-ec2'; import * as c from '@aws-accelerator/common-config/src'; import { StackOutput } from '@aws-accelerator/common-outputs/src/stack-output'; import { TransitGatewayOutputFinder, TransitGatewayOutput } from '@aws-accelerator/common-outputs/src/transit-gateway'; import { VpnTunnelOptions } from '@aws-accelerator/custom-resource-ec2-vpn-tunnel-options'; import { VpnAttachments } from '@aws-accelerator/custom-resource-ec2-vpn-attachment'; import { AccountStacks } from '../../../common/account-stacks'; import { AddTagsToResourcesOutput, AddTagsToResource } from '../../../common/add-tags-to-resources-output'; import { FirewallPort, FirewallVpnConnection, CfnFirewallVpnConnectionOutput, FirewallPortOutputFinder, TgwVpnAttachment, CfnTgwVpnAttachmentsOutput, } from './outputs'; export interface FirewallStep2Props { accountStacks: AccountStacks; config: c.AcceleratorConfig; outputs: StackOutput[]; } /** * Creates the customer gateways for the EIPs of the firewall. * * The following outputs are necessary from previous steps: * - Firewall ports from step 1 of the firewall deployment * - Transit gateway in the firewallConfig.tgw-attach.account * * This step outputs the following: * - Firewall ports from step 1 with additional VPN connection info, if available */ export async function step2(props: FirewallStep2Props) { const { accountStacks, config, outputs } = props; for (const [accountKey, accountConfig] of config.getAccountConfigs()) { const firewallConfigs = accountConfig.deployments?.firewalls; if (!firewallConfigs || firewallConfigs.length === 0) { continue; } for (const firewallConfig of firewallConfigs) { if (!firewallConfig.deploy || c.FirewallAutoScaleConfigType.is(firewallConfig)) { console.log(`Deploy set to false for "${firewallConfig.name}"`); continue; } const firewallPorts: FirewallPort[] = []; if (c.FirewallEC2ConfigType.is(firewallConfig)) { // Find the firewall EIPs in the firewall account const firewallPortOutputs = FirewallPortOutputFinder.findAll({ outputs, accountKey, region: firewallConfig.region, }); firewallPorts.push(...firewallPortOutputs.flatMap(array => array)); if (firewallPorts.length === 0) { console.warn(`Cannot find firewall port outputs in account "${accountKey}"`); continue; } } const attachConfig = firewallConfig['tgw-attach']; if (!c.TransitGatewayAttachConfigType.is(attachConfig)) { continue; } const tgwAccountKey = attachConfig.account; const tgwName = attachConfig['associate-to-tgw']; const transitGateway = TransitGatewayOutputFinder.tryFindOneByName({ outputs, accountKey: tgwAccountKey, name: tgwName, }); if (!transitGateway) { console.warn(`Cannot find transit gateway "${tgwName}" in account "${tgwAccountKey}"`); continue; } const tgwAccountStack = accountStacks.tryGetOrCreateAccountStack(tgwAccountKey, firewallConfig.region); if (!tgwAccountStack) { console.warn(`Cannot find account stack ${tgwAccountKey}`); continue; } await createCustomerGateways({ scope: tgwAccountStack, firewallAccountKey: accountKey, firewallConfig, firewallPorts, transitGateway, attachConfig, }); } } } /** * Create customer gateway and VPN connections for the firewall EIPs of step 1 or customer provided ips from configuration file. */ async function createCustomerGateways(props: { scope: cdk.Construct; firewallAccountKey: string; firewallConfig: c.FirewallEC2ConfigType | c.FirewallCGWConfigType; transitGateway: TransitGatewayOutput; attachConfig: c.TransitGatewayAttachConfig; firewallPorts?: FirewallPort[]; }) { const { scope, firewallAccountKey, firewallConfig, firewallPorts, transitGateway, attachConfig } = props; // Keep track of the created VPN connection so we can use them in the next steps const vpnConnections: FirewallVpnConnection[] = []; const firewallCgwName = firewallConfig['fw-cgw-name']; const firewallCgwAsn = firewallConfig['fw-cgw-asn']; const firewallCgwRouting = firewallConfig['fw-cgw-routing'].toLowerCase(); const addTagsDependencies = []; const addTagsToResources: AddTagsToResource[] = []; const tgwAttachments: TgwVpnAttachment[] = []; if (c.FirewallEC2ConfigType.is(firewallConfig)) { for (const [index, port] of Object.entries(firewallPorts || [])) { if (port.firewallName !== firewallConfig.name) { continue; } let customerGateway; let vpnConnection; let vpnTunnelOptions; if (port.eipIpAddress && port.createCustomerGateway) { const prefix = `${firewallCgwName}_${port.subnetName}_az${pascalCase(port.az)}`; customerGateway = new ec2.CfnCustomerGateway(scope, `${prefix}_cgw`, { type: 'ipsec.1', ipAddress: port.eipIpAddress, bgpAsn: firewallCgwRouting === 'dynamic' ? firewallCgwAsn : 65000, }); vpnConnection = new ec2.CfnVPNConnection(scope, `${prefix}_vpn`, { type: 'ipsec.1', transitGatewayId: transitGateway.tgwId, customerGatewayId: customerGateway.ref, staticRoutesOnly: firewallCgwRouting === 'static' ? true : undefined, }); // Creating VPN connection route table association and propagation const attachments = new VpnAttachments(scope, `VpnAttachments${index}`, { vpnConnectionId: vpnConnection.ref, tgwId: transitGateway.tgwId, }); // Make sure to add the tags to the VPN attachments addTagsDependencies.push(attachments); addTagsToResources.push({ targetAccountIds: [cdk.Aws.ACCOUNT_ID], resourceId: attachments.getTransitGatewayAttachmentId(0), resourceType: 'tgw-attachment', tags: [ { key: 'Name', value: `${prefix}_att`, }, ], region: cdk.Aws.REGION, }); const associateConfig = attachConfig['tgw-rt-associate'] || []; const propagateConfig = attachConfig['tgw-rt-propagate'] || []; const tgwRouteAssociates = associateConfig.map(route => transitGateway.tgwRouteTableNameToIdMap[route]); const tgwRoutePropagates = propagateConfig.map(route => transitGateway.tgwRouteTableNameToIdMap[route]); for (const [routeIndex, route] of tgwRouteAssociates?.entries()) { new ec2.CfnTransitGatewayRouteTableAssociation(scope, `tgw_associate_${prefix}_${routeIndex}`, { transitGatewayAttachmentId: attachments.getTransitGatewayAttachmentId(0), // one vpn connection should only have one attachment transitGatewayRouteTableId: route, }); } for (const [routeIndex, route] of tgwRoutePropagates?.entries()) { new ec2.CfnTransitGatewayRouteTablePropagation(scope, `tgw_propagate_${prefix}_${routeIndex}`, { transitGatewayAttachmentId: attachments.getTransitGatewayAttachmentId(0), // one vpn connection should only have one attachment transitGatewayRouteTableId: route, }); } const options = new VpnTunnelOptions(scope, `VpnTunnelOptions${index}`, { vpnConnectionId: vpnConnection.ref, }); vpnTunnelOptions = { cgwTunnelInsideAddress1: options.getAttString('CgwInsideIpAddress1'), cgwTunnelOutsideAddress1: options.getAttString('CgwOutsideIpAddress1'), cgwBgpAsn1: firewallCgwRouting === 'dynamic' ? options.getAttString('CgwBgpAsn1') : undefined, vpnTunnelInsideAddress1: options.getAttString('VpnInsideIpAddress1'), vpnTunnelOutsideAddress1: options.getAttString('VpnOutsideIpAddress1'), vpnBgpAsn1: firewallCgwRouting === 'dynamic' ? options.getAttString('VpnBgpAsn1') : undefined, preSharedSecret1: options.getAttString('PreSharedKey1'), cgwTunnelInsideAddress2: options.getAttString('CgwInsideIpAddress2'), cgwTunnelOutsideAddress2: options.getAttString('CgwOutsideIpAddress2'), cgwBgpAsn2: firewallCgwRouting === 'dynamic' ? options.getAttString('CgwBgpAsn2') : undefined, vpnTunnelInsideAddress2: options.getAttString('VpnInsideIpAddress2'), vpnTunnelOutsideAddress2: options.getAttString('VpnOutsideIpAddress2'), vpnBgpAsn2: firewallCgwRouting === 'dynamic' ? options.getAttString('VpnBgpAsn2') : undefined, preSharedSecret2: options.getAttString('PreSharedKey2'), }; tgwAttachments.push({ subnet: port.subnetName, az: port.az, id: attachments.getTransitGatewayAttachmentId(0), }); } vpnConnections.push({ ...port, firewallAccountKey, transitGatewayId: transitGateway.tgwId, customerGatewayId: customerGateway?.ref, vpnConnectionId: vpnConnection?.ref, vpnTunnelOptions, }); } } else { for (const [index, fwIp] of Object.entries(firewallConfig['fw-ips'] || [])) { const prefix = `${firewallCgwName}_ip${index}`; const customerGateway = new ec2.CfnCustomerGateway(scope, `${prefix}_cgw`, { type: 'ipsec.1', ipAddress: fwIp, bgpAsn: firewallCgwRouting === 'dynamic' ? firewallCgwAsn : 65000, }); const vpnConnection = new ec2.CfnVPNConnection(scope, `${prefix}_vpn`, { type: 'ipsec.1', transitGatewayId: transitGateway.tgwId, customerGatewayId: customerGateway.ref, staticRoutesOnly: firewallCgwRouting === 'static' ? true : undefined, }); // Creating VPN connection route table association and propagation const attachments = new VpnAttachments(scope, `VpnAttachments-${prefix}_attach`, { vpnConnectionId: vpnConnection.ref, tgwId: transitGateway.tgwId, }); // Make sure to add the tags to the VPN attachments addTagsDependencies.push(attachments); addTagsToResources.push({ targetAccountIds: [cdk.Aws.ACCOUNT_ID], resourceId: attachments.getTransitGatewayAttachmentId(0), resourceType: 'tgw-attachment', tags: [ { key: 'Name', value: `${prefix}_att`, }, ], region: cdk.Aws.REGION, }); const associateConfig = attachConfig['tgw-rt-associate'] || []; const propagateConfig = attachConfig['tgw-rt-propagate'] || []; const tgwRouteAssociates = associateConfig.map(route => transitGateway.tgwRouteTableNameToIdMap[route]); const tgwRoutePropagates = propagateConfig.map(route => transitGateway.tgwRouteTableNameToIdMap[route]); for (const [routeIndex, route] of tgwRouteAssociates?.entries()) { new ec2.CfnTransitGatewayRouteTableAssociation(scope, `tgw_associate_${prefix}_${routeIndex}`, { transitGatewayAttachmentId: attachments.getTransitGatewayAttachmentId(0), // one vpn connection should only have one attachment transitGatewayRouteTableId: route, }); } for (const [routeIndex, route] of tgwRoutePropagates?.entries()) { new ec2.CfnTransitGatewayRouteTablePropagation(scope, `tgw_propagate_${prefix}_${routeIndex}`, { transitGatewayAttachmentId: attachments.getTransitGatewayAttachmentId(0), // one vpn connection should only have one attachment transitGatewayRouteTableId: route, }); } } } // Output the tags that need to be added to the VPN attachments if (addTagsToResources.length > 0) { new AddTagsToResourcesOutput(scope, `VpnAttachmentsTags${firewallConfig.name}`, { dependencies: addTagsDependencies, produceResources: () => addTagsToResources, }); } // Store the firewall VPN connections as outputs new CfnFirewallVpnConnectionOutput(scope, `FirewallVpnConnections${firewallConfig.name}`, vpnConnections); new CfnTgwVpnAttachmentsOutput(scope, `TgwVpnAttachments${firewallConfig.name}`, { name: firewallCgwName, attachments: tgwAttachments, }); }
the_stack
import { nbtStringifier } from '@variables/nbt/NBTs' import { rangeParser } from '@variables/parsers' import { ComponentClass } from './abstractClasses' import type { ENTITY_TYPES, GAMEMODES, Range, RootNBT, TextComponentObject, } from '@arguments' import type { CommandsRoot } from '@commands' import type { PredicateInstance } from '@resources' import type { LiteralUnion } from '../generalTypes' import type { ConditionClass } from './abstractClasses' import type { NotNBT } from './nbt/NBTs' type ScoreArgument = Record<string, Range> type AdvancementsArgument = Record<string, boolean | Record<string, boolean>> /** * If MustBeSingle is false, then anything is allowed. * If it is true, then you must provide limit=1 or limit=0. */ export type SelectorProperties<MustBeSingle extends boolean, MustBePlayer extends boolean> = { /** * Filter target selection based on their Euclidean distances from some point, * searching for the target's feet (a point at the bottom of the center of their hitbox). * * If the positional arguments `x`, `y` and `z` are left undefined, * radius is calculated relative to the position of the command's execution. * * Only unsigned values are allowed. */ distance?: Range, /** Filter target selection based on their scores in the specified objectives. */ scores?: ScoreArgument /** * Filter target selection to those who are on a given team. * * Allowed values are: * - `teamName`, to filter those who are in the given team. * - `!teamName`, to filter those who are not in the given team. * - `false`, to filter those who are teamless (in no team). * - `true`, ot filter those who have at least one team. */ team?: string | boolean /** * Filter target selection to those that have the given tag(s). * * Multiple values are allowed, when passed as an array. * * @example * * Selector(`@e`, { tag: 'alive' }) => `@e[tag=alive]` * * Selector(`@e`, { tag: ['alive', 'winner'] }) => `@e[tag=alive, tag=winner]` * */ tag?: string | string[] /** Filter target selection to all those with a given name. This cannot be a JSON text compound. */ name?: string /** * Specify the targets selection priority. * * - `nearest`: Sort by increasing distance. (Default for `@p`) * - `furthest`: Sort by decreasing distance. * - `random`: Sort randomly. (Default for `@r`) * - `arbitrary`: Do not sort. (Default for `@e`, `@a`) */ sort?: LiteralUnion<'nearest' | 'furthest' | 'random' | 'abitrary'> /** Filter target selection based on their experience levels. This naturally filters out all non-player targets. */ level?: Range /** Filter target selection to those who are in the specified game mode. */ gamemode?: LiteralUnion<GAMEMODES | `!${GAMEMODES}`> | `!${GAMEMODES}`[] // Selecting targets by vertical rotation /** * Filter target selection based on their vertical rotation, measured in degrees. * * Values range from `-90` (straight up) to `0` (at the horizon) to `+90` (straight down). */ x_rotation?: Range /** * Filter target selection based on their rotation in the horizontal XZ-plane, * measured clockwise in degrees from due south (or the positive Z direction). * * Values vary: * - from `-180` (facing due north, the -Z direction) * - to `-90` (facing due east, the +X direction) * - to `0` (facing due south, the +Z direction) * - to `+90` (facing due west, the -X direction) * - to `+180` (facing due north again). */ y_rotation?: Range /** Select all targets that match the specified advancement and value. */ advancements?: AdvancementsArgument /** Select all targets that match the specified predicate. */ predicate?: string | PredicateInstance | (PredicateInstance | string)[] /** Select all targets that have the specified NBT. */ nbt?: RootNBT | NotNBT /** * Define a position on the X-axis in the world the selector starts at, * for use with the `distance` argument or the volume arguments, `dx`, `dy` and `dz`. */ x?: number /** * Define a position on the Y-axis in the world the selector starts at, * for use with the `distance` argument or the volume arguments, `dx`, `dy` and `dz`. */ y?: number /** * Define a position on the Z-axis in the world the selector starts at, * for use with the `distance` argument or the volume arguments, `dx`, `dy` and `dz`. */ z?: number /** * Filter target selection based on their x-difference, from some point, * as measured from the closest corner of the entities' hitboxes */ dx?: number /** * Filter target selection based on their y-difference, from some point, * as measured from the closest corner of the entities' hitboxes */ dy?: number /** * Filter target selection based on their z-difference, from some point, * as measured from the closest corner of the entities' hitboxes */ dz?: number } & ( MustBeSingle extends true ? { limit: 0 | 1 } : { limit?: number } ) & ( MustBePlayer extends true ? { /** * Filter target selection to those of a specific entity type. * * Multiple values are allowed, when passed as an array. * * @example * * Selector(`@e`, { type: 'minecraft:cow' }) => `@e[type=!minecraft:cow]` * * Selector(`@e`, { type: ['!minecraft:cow', '!minecraft:skeleton'] }) => `@e[type=!minecraft:cow, type=!minecraft:skeleton]` */ type: 'minecraft:player' | 'minecraft:player'[] } : { /** * Filter target selection to those of a specific entity type. * * Multiple values are allowed, when passed as an array. * * @example * * Selector(`@e`, { type: 'minecraft:cow' }) => `@e[type=!minecraft:cow]` * * Selector(`@e`, { type: ['!minecraft:cow', '!minecraft:skeleton'] }) => `@e[type=!minecraft:cow, type=!minecraft:skeleton]` */ type?: LiteralUnion<ENTITY_TYPES> | LiteralUnion<ENTITY_TYPES>[] } ) // Returns the string representation of a score argument. `{ myScore: [0, null] } => {myScore=0..}`, `{ myScore: [-Infinity, 5] } => {myScore='..5'}`, 8 => '8' function parseScore(scores: ScoreArgument): string { return `{${Object.entries(scores).map(([scoreName, value]) => [scoreName, rangeParser(value)].join('=')).join(', ')}}` } // Returns the string representation of advancements function parseAdvancements(advancements: AdvancementsArgument): string { return `{${Object.entries(advancements).map(([advancementName, value]) => { if (typeof value === 'boolean') { return [advancementName, value].join('=') } return [advancementName, parseAdvancements(value)].join('=') }).join(', ')}}` } export class SelectorClass<IsSingle extends boolean = false, IsPlayer extends boolean = false> extends ComponentClass implements ConditionClass { protected commandsRoot: CommandsRoot target arguments: SelectorProperties<IsSingle, IsPlayer> constructor( commandsRoot: CommandsRoot, target: '@s' | '@p' | '@a' | '@e' | '@r', selectorArguments?: SelectorProperties<IsSingle, IsPlayer>, ) { super() this.commandsRoot = commandsRoot this.target = target this.arguments = selectorArguments ?? {} as SelectorProperties<IsSingle, IsPlayer> } // Custom actions // /** * List all scores of this entity. */ listScores = () => { this.commandsRoot.scoreboard.players.list(this.toString()) } _toMinecraftCondition(this: SelectorClass<IsSingle, IsPlayer>) { return { value: ['if', 'entity', this] } } toString() { if (!Object.keys(this.arguments).length) { return this.target } const result: (readonly [string, string])[] = [] if (this.arguments) { const args = { ...this.arguments } const modifiers = { // Parse scores scores: (scores: ScoreArgument) => result.push(['scores', parseScore(scores)]), nbt: (nbt: RootNBT) => result.push(['nbt', nbtStringifier(nbt)]), // Parse advancements advancements: (advancements: AdvancementsArgument) => result.push( ['advancements', parseAdvancements(advancements)], ), // Parse potentially multiple tags tag: (tag: string | string[]) => { const tags = Array.isArray(tag) ? tag : [tag] result.push(...tags.map((tag_) => ['tag', tag_] as const)) }, // Parse potentially multiple gamemodes gamemode: (gamemode: string | string[]) => { const gamemodes = Array.isArray(gamemode) ? gamemode : [gamemode] result.push(...gamemodes.map((gamemode_) => ['gamemode', gamemode_] as const)) }, // Parse potentially multiple predicates predicate: (predicate: string | string[]) => { const predicates = Array.isArray(predicate) ? predicate : [predicate] result.push(...predicates.map((pred) => ['predicate', pred] as const)) }, // Handle boolean values for teams team: (team: string | boolean) => { let teamRepr: string if (team === true) { teamRepr = '!' } else if (team === false) { teamRepr = '' } else { teamRepr = team } result.push(['team', teamRepr]) }, distance: (range_: Range) => result.push(['distance', rangeParser(range_)]), } as const for (const [baseName, modifier] of Object.entries(modifiers)) { const name = baseName as keyof typeof args const value = args[name] if (value !== undefined) { modifier(value as any) delete args[name] } } Object.entries(args).forEach(([key, value]) => { if (value !== undefined) { result.push([key, value.toString()]) } }) } return `${this.target}[${result.map(([key, value]) => `${key}=${value}`).join(', ')}]` } protected _toChatComponent(): TextComponentObject { return { selector: this.toString(), } } protected toJSON() { return this.toString() } } // Possible selector properties export type AnySelectorProperties = SelectorProperties<false, false> export type SingleSelectorProperties = SelectorProperties<true, false> export type SinglePlayerSelectorProperties = SelectorProperties<true, true> export type SelectorCreator = ( & ((target: '@s' | '@p' | '@r', selectorArguments?: Omit<AnySelectorProperties, 'limit' | 'type'>) => SelectorClass<true, true>) & ((target: '@a', selectorArguments: Omit<SingleSelectorProperties, 'type'>) => SelectorClass<true, true>) & ((target: '@a', selectorArguments?: Omit<AnySelectorProperties, 'type'>) => SelectorClass<false, true>) & ((target: '@e', selectorArguments: SinglePlayerSelectorProperties) => SelectorClass<true, true>) & ((target: '@e', selectorArguments: SingleSelectorProperties) => SelectorClass<true, false>) & ((target: '@e', selectorArguments?: AnySelectorProperties) => SelectorClass<false, false>) )
the_stack
interface Window { Viva? : any } module org.mwg.plugin.visualizer.taskRegistry { import Actions = org.mwg.task.Actions; import TaskContext = org.mwg.task.TaskContext; import Task = org.mwg.task.Task; import TaskResult = org.mwg.task.TaskResult; export const timeVar : string = "time"; export const worldVar : string = "world"; export const nodeIdVar : string = "nodeId"; const writeIdType = Actions.then(function(context : TaskContext) { let res : string = context.variable("string").get(0); let n : org.mwg.Node = context.variable("node").get(0); res += " _id=" + n.id() + "\n"; res += " _type=" + (n.nodeTypeName() || 'default') + "\n"; context.setGlobalVariable("string",res); context.continueTask(); }); const writeAtt = Actions.then(function(context : TaskContext) { let res : string = context.variable("string").get(0); let n : org.mwg.Node = context.variable("node").get(0); res += " " + context.result().get(0) + "="; if(typeof context.result().get(0) != "number") { var prop = n.get(context.result().get(0)); if(prop instanceof Float64Array || prop instanceof Int32Array) { res += "[" + prop + "]"; } else { res += prop; } } else { res += n.getByIndex(context.result().get(0)); } res += "\n"; context.setGlobalVariable("string",res); context.continueTask(); }); const writeIndexRel = Actions.then(function(context :TaskContext) { let n : org.mwg.Node = context.variable("node").get(0); let map : org.mwg.struct.LongLongArrayMap = n.get(context.result().get(0)); let index : number = 0; let res : String = context.variable("string").get(0); res += " " + context.result().get(0) + "=["; map.each(function (key:number, value:number) { res += (value + ""); if((index + 1) < map.size() ) { res += ","; } index++; }); res += "]\n"; context.setGlobalVariable("string",res); context.continueTask(); }); export const printNodeTask : Task = Actions .setTime(`{{${timeVar}}}`) .setWorld(`{{${worldVar}}}`) .inject("{\n") .asGlobalVar("string") .lookup(`{{${nodeIdVar}}}`) .asGlobalVar("node") .ifThen(function(context : TaskContext){return context.result().size() > 0}, writeIdType .subTasks([Actions.propertiesWithTypes(Type.BOOL), Actions.propertiesWithTypes(Type.INT), Actions.propertiesWithTypes(Type.DOUBLE), Actions.propertiesWithTypes(Type.LONG), Actions.propertiesWithTypes(Type.STRING), Actions.propertiesWithTypes(Type.RELATION), Actions.propertiesWithTypes(Type.INT_ARRAY), Actions.propertiesWithTypes(Type.LONG_ARRAY), Actions.propertiesWithTypes(Type.DOUBLE_ARRAY) ] ) .foreach(writeAtt) .fromVar("node") .propertiesWithTypes(Type.LONG_TO_LONG_ARRAY_MAP) .ifThen(function(context : TaskContext) { return context.result().size() > 0; },writeIndexRel) .fromVar("string")); function getRandomColor() { var letters = '789ABCD'.split(''); var color = "#"; for (var i = 0; i < 6; i++ ) { color += letters[Math.round(Math.random() * 6)]; } return color; } const addIndexedNode = Actions.then(function(context : TaskContext) { let node : org.mwg.Node = context.resultAsNodes().get(0); let graphVisu : GraphVisu = <GraphVisu> context.variable(graphVisuVar).get(0); let id : number = node.id(); let nodeType : string = node.nodeTypeName() || 'default'; graphVisu._graphVisu.addNode(id,{_type: nodeType}); if(graphVisu._mapTypeColor[nodeType] == null) { graphVisu._mapTypeColor[nodeType] = getRandomColor(); } context.continueTask(); }); const visitRel = Actions.then(function(context : TaskContext) { var alreadyVisit : TaskResult<number> = context.variable("alreadyVisit"); var srcNode : number = context.variable("currentNode").get(0).id(); var result : org.mwg.Node = context.resultAsNodes().get(0); var alreadyVisited : boolean = false; for(var i=0;i<alreadyVisit.size();i++) { alreadyVisited = alreadyVisited || (result.id() == alreadyVisit.get(i)) if(alreadyVisited) { break; } } let graphVisu : GraphVisu = <GraphVisu> context.variable(graphVisuVar).get(0); if(!alreadyVisited) { let nodeType : string = result.nodeTypeName() || 'default'; if(graphVisu._mapTypeColor[nodeType] == null) { graphVisu._mapTypeColor[nodeType] = getRandomColor(); } graphVisu._graphVisu.addNode(result.id(),{_type: nodeType}); let nextToVisit : TaskResult<org.mwg.Node> = context.variable("nextToVisit"); let alreadyAdded :boolean = false; for(let ntv=0;ntv<nextToVisit.size();ntv++) { alreadyAdded = alreadyAdded || (result.id() == nextToVisit.get(ntv).id()); if(alreadyAdded) { break; } } if(!alreadyAdded) { context.addToGlobalVariable("nextToVisit", result); } } graphVisu._graphVisu.addLink(srcNode,result.id()); context.continueTask(); }); const visitByIndex = Actions.then(function(context: TaskContext) { let node : org.mwg.Node = context.variable("currentNode").get(0); let hashReation : number = context.variable("relationName").get(0); node.relByIndex(hashReation, function(nodes: Array<org.mwg.Node>) { let alreadyVisit : TaskResult<number> = context.variable("alreadyVisit"); let srcNode : number = context.variable("currentNode").get(0).id(); for(let i=0;i<nodes.length;i++) { let result : org.mwg.Node = nodes[i]; let alreadyVisited : boolean = false; for(let i=0;i<alreadyVisit.size();i++) { alreadyVisited = alreadyVisited || (result.id() == alreadyVisit.get(i)) if(alreadyVisited) { break; } } let graphVisu : GraphVisu = <GraphVisu> context.variable(graphVisuVar).get(0); if(!alreadyVisited) { let nodeType : string = result.nodeTypeName() || 'default'; if(graphVisu._mapTypeColor[nodeType] == null) { graphVisu._mapTypeColor[nodeType] = getRandomColor(); } graphVisu._graphVisu.addNode(result.id(),{_type: nodeType}); let nextToVisit : TaskResult<org.mwg.Node> = context.variable("nextToVisit"); var alreadyAdded :boolean = false; for(let ntv=0;ntv<nextToVisit.size();ntv++) { alreadyAdded = alreadyAdded || (result.id() == nextToVisit.get(ntv).id()); if(alreadyAdded) { break; } } if(!alreadyAdded) { context.addToGlobalVariable("nextToVisit", result); } } graphVisu._graphVisu.addLink(srcNode,result.id()); } context.continueTask(); }); }); const visitRelIndex = Actions.then(function(context : TaskContext){ var alreadyVisit : TaskResult<number> = context.variable("alreadyVisit"); var srcNode : number = context.variable("currentNode").get(0).id(); var result : org.mwg.Node = context.resultAsNodes().get(0); var alreadyVisited : boolean = false; for(var i=0;i<alreadyVisit.size();i++) { alreadyVisited = alreadyVisited || (result.id() == alreadyVisit.get(i)); if(alreadyVisited) { break; } } let graphVisu : GraphVisu = <GraphVisu> context.variable(graphVisuVar).get(0); if(!alreadyVisited) { var nodeType : string = result.nodeTypeName() || 'default'; if(graphVisu._mapTypeColor[nodeType] == null) { graphVisu._mapTypeColor[nodeType] = getRandomColor(); } graphVisu._graphVisu.addNode(result.id(),{_type: nodeType}); var nextToVisit : TaskResult<org.mwg.Node> = context.variable("nextToVisit"); var alreadyAdded :boolean = false; for(var ntv=0;ntv<nextToVisit.size();ntv++) { alreadyAdded = alreadyAdded || (result.id() == nextToVisit.get(ntv).id()); if(alreadyAdded) { break; } } if(!alreadyAdded) { context.addToGlobalVariable("nextToVisit", result); } } graphVisu._graphVisu.addLink(srcNode,result.id()); context.continueTask(); }); export const depthVar : string = "depth"; export const graphVisuVar : string = "graphVisu"; export const drawGraphTask : Task = Actions .setTime(`{{${timeVar}}}`) .setWorld(`{{${worldVar}}}`) .indexesNames() .foreach( Actions .fromIndexAll("{{result}}") .asGlobalVar("toVisit") .foreach(addIndexedNode) .fromVar("toVisit") .loop("1",`{{${depthVar}}}`, Actions .defineVar("nextToVisit") .fromVar("toVisit") .foreach( Actions .asGlobalVar("currentNode") .then(function(context : TaskContext) { let node : org.mwg.Node = context.result().get(0); context.addToGlobalVariable("alreadyVisit",node.id()) context.continueTask(); }) .propertiesWithTypes(Type.RELATION) .foreach( Actions.asVar("relationName") .fromVar("currentNode") .traverse("{{relationName}}") .ifThenElse(function (context:TaskContext) : boolean { return context.result().size() > 0; }, Actions.foreach(visitRel), visitByIndex ) ) .fromVar("currentNode") .propertiesWithTypes(Type.LONG_TO_LONG_ARRAY_MAP) .foreach( Actions.asVar("relationName") .fromVar("currentNode") .traverseIndexAll("{{relationName}}") .foreach(visitRelIndex) ) ) .fromVar("nextToVisit") .asGlobalVar("toVisit") // .fromVar("nextToVisit") .clear() .asGlobalVar("nextToVisit") ) ); } module org.mwg.plugin { import timeVar = org.mwg.plugin.visualizer.taskRegistry.timeVar; import worldVar = org.mwg.plugin.visualizer.taskRegistry.worldVar; import nodeIdVar = org.mwg.plugin.visualizer.taskRegistry.nodeIdVar; import printNodeTask = org.mwg.plugin.visualizer.taskRegistry.printNodeTask; import depthVar = org.mwg.plugin.visualizer.taskRegistry.depthVar; import graphVisuVar = org.mwg.plugin.visualizer.taskRegistry.graphVisuVar; import drawGraphTask = org.mwg.plugin.visualizer.taskRegistry.drawGraphTask; import WSClient = org.mwg.plugin.WSClient; import Task = org.mwg.task.Task; import Actions = org.mwg.task.Actions; import TaskContext = org.mwg.task.TaskContext; import Type = org.mwg.Type; import TaskResult = org.mwg.task.TaskResult; import Graph = org.mwg.Graph; import HeapRelationship = org.mwg.core.chunk.heap.HeapRelationship; import CoreDeferCounterSync = org.mwg.core.utility.CoreDeferCounterSync; export const INIT_DEPTH = 10; export const INIT_TIME = 0; export const INIT_WORLD = 0; export var defaultGraphVisu : GraphVisu; export class GraphVisu { _graph : org.mwg.Graph; _graphVisu : any; _time : number = INIT_TIME; _world : number = INIT_WORLD; _depth : number = INIT_DEPTH; //todo delete _mapTypeColor : Object = new Object(); _previousSelect : number = -1; _previousColor : any; _renderer : any; _graphics : any; constructor(url : string) { this._graph = new org.mwg.GraphBuilder() .withStorage(new org.mwg.plugin.WSClient(url)) .build(); this._graphVisu = window.Viva.Graph.graph(); this._mapTypeColor['default'] = 0x009ee8ff; } } function printNodeDetails(nodeId: number, graphVisu : GraphVisu) { Actions .inject(nodeId) .asGlobalVar(nodeIdVar) .inject(graphVisu._time) .asGlobalVar(timeVar) .inject(graphVisu._world) .asGlobalVar(worldVar) .subTask(printNodeTask) .execute(graphVisu._graph, function(result : TaskResult<string>) { document.getElementById("nodeDetail").innerHTML = result.get(0) + "}"; }); } function selectNode(nodeID : number, graphVisu : GraphVisu) { if(nodeID != graphVisu._previousSelect) { printNodeDetails(nodeID, graphVisu); var selectedNodeUI = graphVisu._renderer.getGraphics().getNodeUI(nodeID); if(selectedNodeUI != null) { var currentColor = selectedNodeUI.color; selectedNodeUI.color = 0xFFA500ff; if (graphVisu._previousSelect != -1) { var previousSelected = graphVisu._renderer.getGraphics().getNodeUI(graphVisu._previousSelect); previousSelected.color = graphVisu._previousColor; } graphVisu._previousSelect = nodeID; graphVisu._previousColor = currentColor; } } } function connect(graphVisu : GraphVisu, idDiv : string) { graphVisu._graph.connect(function (succeed : boolean){ if(succeed) { graphVisu._graphics = window.Viva.Graph.View.webglGraphics(); graphVisu._graphics.node(function(node){ return window.Viva.Graph.View.webglSquare(12,graphVisu._mapTypeColor[node.data._type]); }); window.Viva.Graph.webglInputEvents(graphVisu._graphics,graphVisu._graphVisu) .click(function(selectedNode : any) { console.log("click"); selectNode(selectedNode.id,graphVisu); }); graphVisu._renderer = window.Viva.Graph.View.renderer(graphVisu._graphVisu, { layout: window.Viva.Graph.Layout.forceDirected(graphVisu._graphVisu, {}), container: document.getElementById(idDiv), graphics: graphVisu._graphics }); graphVisu._renderer.run(); // // setTimeout(function(){ // graphVisu._renderer.pause(); // },10000); drawGraph(graphVisu); } else { console.error("Problem during connection.") } }); } function drawGraph(graphVisu : GraphVisu) { graphVisu._graphVisu.clear(); Actions .inject(graphVisu._time) .asGlobalVar(timeVar) .inject(graphVisu._world) .asGlobalVar(worldVar) .inject(graphVisu._depth) .asGlobalVar(depthVar) .inject(graphVisu) .asGlobalVar(graphVisuVar) .subTask(drawGraphTask) .execute(graphVisu._graph,function() { if(graphVisu._previousSelect != -1) { let nodeId = graphVisu._previousSelect; graphVisu._previousSelect = -1; selectNode(nodeId,graphVisu); } }); } export function initVivaGraph(url: string, idDiv : string) { // let graphVisu = new GraphVisu(url); defaultGraphVisu = new GraphVisu(url); if(document.getElementById(idDiv) == null) { setTimeout(connect,5,defaultGraphVisu,idDiv) } else { connect(defaultGraphVisu,idDiv); } return defaultGraphVisu; } export function updateTime(time : number, graphVisu : GraphVisu) { graphVisu._time = time; drawGraph(graphVisu); } export function updateWorld(world : number, graphVisu : GraphVisu) { graphVisu._world = world; drawGraph(graphVisu); } export function updateDepth(depth : number, graphVisu : GraphVisu) { graphVisu._depth = depth; drawGraph(graphVisu); } }
the_stack
export interface CarbonPictogramProps extends Omit<React.SVGProps<SVGElement>, 'tabIndex'> { tabIndex?: string; } export type CarbonPictogram = (props: CarbonPictogramProps) => React.FunctionComponentElement<CarbonPictogramProps>; export const ActiveServer: CarbonPictogram; export const Advocate: CarbonPictogram; export const Agriculture: CarbonPictogram; export const AirConditioner: CarbonPictogram; export const Airplane: CarbonPictogram; export const Alarm: CarbonPictogram; export const AlchemyDataNews: CarbonPictogram; export const AlchemyLanguage: CarbonPictogram; export const AlchemyLanguageAlphabetAExpanded: CarbonPictogram; export const AlchemyVision: CarbonPictogram; export const Americas: CarbonPictogram; export const AmsterdamCanal: CarbonPictogram; export const AmsterdamFarm: CarbonPictogram; export const AmsterdamWindmill: CarbonPictogram; export const Analyze: CarbonPictogram; export const AnalyzesData: CarbonPictogram; export const Apartment: CarbonPictogram; export const Api: CarbonPictogram; export const AppDeveloper: CarbonPictogram; export const Apple: CarbonPictogram; export const Application: CarbonPictogram; export const Archive: CarbonPictogram; export const AsiaAustralia: CarbonPictogram; export const AugmentedReality: CarbonPictogram; export const Austin: CarbonPictogram; export const AutomateModularManagement: CarbonPictogram; export const Automobile: CarbonPictogram; export const Bag: CarbonPictogram; export const Bangalore: CarbonPictogram; export const Bee: CarbonPictogram; export const BeijingMunicipal: CarbonPictogram; export const BeijingTower: CarbonPictogram; export const BerlinBrandenburg: CarbonPictogram; export const BerlinCathedral: CarbonPictogram; export const BerlinTower: CarbonPictogram; export const Bicycle: CarbonPictogram; export const Blockchain: CarbonPictogram; export const Build: CarbonPictogram; export const Building: CarbonPictogram; export const Bulldozer: CarbonPictogram; export const Bus: CarbonPictogram; export const Cafe: CarbonPictogram; export const Calendar: CarbonPictogram; export const CalendarDate: CarbonPictogram; export const CalendarEvent: CarbonPictogram; export const Camera: CarbonPictogram; export const Capitol: CarbonPictogram; export const Care: CarbonPictogram; export const Cell: CarbonPictogram; export const ChartBar: CarbonPictogram; export const ChartBubbleLine: CarbonPictogram; export const ChartLine: CarbonPictogram; export const ChartScatterplot: CarbonPictogram; export const Cherries: CarbonPictogram; export const ChipCircuit: CarbonPictogram; export const ChipCredit: CarbonPictogram; export const ChipDebit: CarbonPictogram; export const CloudAnalytics: CarbonPictogram; export const CloudAssets: CarbonPictogram; export const CloudBuilderProfessionalServices: CarbonPictogram; export const CloudComputing: CarbonPictogram; export const CloudDataServices: CarbonPictogram; export const CloudDownload: CarbonPictogram; export const CloudEcosystem: CarbonPictogram; export const CloudGuidelines: CarbonPictogram; export const CloudManagedServices: CarbonPictogram; export const CloudOracle: CarbonPictogram; export const CloudPartners: CarbonPictogram; export const CloudPlanning: CarbonPictogram; export const CloudSap: CarbonPictogram; export const CloudServices: CarbonPictogram; export const CloudServicesPricing: CarbonPictogram; export const CloudStorage: CarbonPictogram; export const CloudStrategy: CarbonPictogram; export const CloudTutorials: CarbonPictogram; export const CloudUpload: CarbonPictogram; export const CloudVmware: CarbonPictogram; export const Cloudy: CarbonPictogram; export const CloudyDewy: CarbonPictogram; export const CloudyHazy: CarbonPictogram; export const CloudyHumid: CarbonPictogram; export const CloudyPartial: CarbonPictogram; export const CloudyWindy: CarbonPictogram; export const CoatHanger: CarbonPictogram; export const CognosAnalytics: CarbonPictogram; export const College: CarbonPictogram; export const ConceptExpansion: CarbonPictogram; export const ConceptInsights: CarbonPictogram; export const Connect: CarbonPictogram; export const Console: CarbonPictogram; export const ConsoleWireless: CarbonPictogram; export const Construct: CarbonPictogram; export const Conversation: CarbonPictogram; export const CopenhagenPlanetarium: CarbonPictogram; export const CopenhagenSnekkja: CarbonPictogram; export const CreditCard: CarbonPictogram; export const Crop: CarbonPictogram; export const CustomerService: CarbonPictogram; export const DataBackup: CarbonPictogram; export const DataInsights: CarbonPictogram; export const DataProcessing: CarbonPictogram; export const DataStorage: CarbonPictogram; export const Delete: CarbonPictogram; export const DeliverInsights: CarbonPictogram; export const DeliveryTruck: CarbonPictogram; export const DesignAndDevelopment_01: CarbonPictogram; export const DesignAndDevelopment_02: CarbonPictogram; export const Desktop: CarbonPictogram; export const Devops: CarbonPictogram; export const Dialogue: CarbonPictogram; export const Digital: CarbonPictogram; export const Dining: CarbonPictogram; export const Dna: CarbonPictogram; export const DoNot: CarbonPictogram; export const Docker: CarbonPictogram; export const Doctor: CarbonPictogram; export const DocumentConversion: CarbonPictogram; export const DoorHandle: CarbonPictogram; export const Download: CarbonPictogram; export const DownloadAlt: CarbonPictogram; export const DubaiPalmIslands: CarbonPictogram; export const DubaiSkyscraper: CarbonPictogram; export const DublinBrewery: CarbonPictogram; export const DublinCastle: CarbonPictogram; export const DuplicateFile: CarbonPictogram; export const Education: CarbonPictogram; export const Electric: CarbonPictogram; export const ElectricCharge: CarbonPictogram; export const Elevator: CarbonPictogram; export const Embed: CarbonPictogram; export const Engine: CarbonPictogram; export const EnterpriseDesignThinking: CarbonPictogram; export const EnterpriseDesignThinkingAlt: CarbonPictogram; export const Envelope: CarbonPictogram; export const ErlenmeyerFlask: CarbonPictogram; export const EscalatorDown: CarbonPictogram; export const EscalatorUp: CarbonPictogram; export const EuropeAfrica: CarbonPictogram; export const ExpandHorz: CarbonPictogram; export const ExpandUser: CarbonPictogram; export const ExpandVert: CarbonPictogram; export const Export: CarbonPictogram; export const ExportAlt: CarbonPictogram; export const Eye: CarbonPictogram; export const FaceDissatisfied: CarbonPictogram; export const FaceNeutral: CarbonPictogram; export const FaceSatisfied: CarbonPictogram; export const FaceVeryDissatisfied: CarbonPictogram; export const FaceVerySatisfied: CarbonPictogram; export const Factory: CarbonPictogram; export const Farm: CarbonPictogram; export const Faucet: CarbonPictogram; export const Feedback: CarbonPictogram; export const FileBackup: CarbonPictogram; export const FileTransfer: CarbonPictogram; export const FinancialConsultant: CarbonPictogram; export const FinancialGain: CarbonPictogram; export const FinancialNews: CarbonPictogram; export const FireAlarm: CarbonPictogram; export const FireExtinguisher: CarbonPictogram; export const Firewall: CarbonPictogram; export const FlowChart: CarbonPictogram; export const FlowChartDetail: CarbonPictogram; export const Fog: CarbonPictogram; export const Folder: CarbonPictogram; export const Forklift: CarbonPictogram; export const FreeTrial: CarbonPictogram; export const Fuel: CarbonPictogram; export const Gear: CarbonPictogram; export const GlobalBusinessServices: CarbonPictogram; export const GlobalFinanceEuro: CarbonPictogram; export const GlobalFinanceSterling: CarbonPictogram; export const GlobalNetwork: CarbonPictogram; export const GlobalTechnologyServices: CarbonPictogram; export const Globe: CarbonPictogram; export const GlobeLocations: CarbonPictogram; export const Group: CarbonPictogram; export const Hail: CarbonPictogram; export const HailHeavy: CarbonPictogram; export const HailMixed: CarbonPictogram; export const Handicap: CarbonPictogram; export const HandicapActive: CarbonPictogram; export const HardDrive: CarbonPictogram; export const HardDriveNetwork: CarbonPictogram; export const HardIceCream: CarbonPictogram; export const Hazy: CarbonPictogram; export const Headphones: CarbonPictogram; export const Heart: CarbonPictogram; export const HeartHealth: CarbonPictogram; export const HeatMap: CarbonPictogram; export const HighFive: CarbonPictogram; export const HomeFront: CarbonPictogram; export const HomeGarage: CarbonPictogram; export const HomeProfile: CarbonPictogram; export const Hospital: CarbonPictogram; export const Humid: CarbonPictogram; export const Hurricane: CarbonPictogram; export const HybridCloud: CarbonPictogram; export const HybridCloudServices: CarbonPictogram; export const IbmIx: CarbonPictogram; export const IbmZ: CarbonPictogram; export const Icon: CarbonPictogram; export const Idea: CarbonPictogram; export const Ideate: CarbonPictogram; export const Innovate: CarbonPictogram; export const Integration: CarbonPictogram; export const Intelligence: CarbonPictogram; export const Intercom: CarbonPictogram; export const IotMunich: CarbonPictogram; export const Java: CarbonPictogram; export const Javascript: CarbonPictogram; export const Justice: CarbonPictogram; export const KeyUsers: CarbonPictogram; export const KnowsDarkData: CarbonPictogram; export const Language: CarbonPictogram; export const LanguageTranslation: CarbonPictogram; export const LanguageTranslationAlphabetAExpanded: CarbonPictogram; export const Language_01: CarbonPictogram; export const Language_02: CarbonPictogram; export const Language_03: CarbonPictogram; export const Language_04: CarbonPictogram; export const Launch: CarbonPictogram; export const Lightning: CarbonPictogram; export const ListBullet: CarbonPictogram; export const ListCheckbox: CarbonPictogram; export const Location: CarbonPictogram; export const Lock: CarbonPictogram; export const LockAlt: CarbonPictogram; export const LockedNetwork: CarbonPictogram; export const LockedNetworkAlt: CarbonPictogram; export const London: CarbonPictogram; export const LondonBigBen: CarbonPictogram; export const LondonExpandedBase: CarbonPictogram; export const Lungs: CarbonPictogram; export const MachineLearning_01: CarbonPictogram; export const MachineLearning_02: CarbonPictogram; export const MachineLearning_03: CarbonPictogram; export const MachineLearning_04: CarbonPictogram; export const MachineLearning_05: CarbonPictogram; export const MachineLearning_06: CarbonPictogram; export const MadridCathedral: CarbonPictogram; export const MadridSkyscrapers: CarbonPictogram; export const MadridStatue: CarbonPictogram; export const Magnify: CarbonPictogram; export const Marketplace: CarbonPictogram; export const Mas: CarbonPictogram; export const Maximize: CarbonPictogram; export const Medical: CarbonPictogram; export const MedicalCharts: CarbonPictogram; export const MedicalStaff: CarbonPictogram; export const Melbourne: CarbonPictogram; export const Meter: CarbonPictogram; export const Microorganisms: CarbonPictogram; export const Microscope: CarbonPictogram; export const Minimize: CarbonPictogram; export const MobileAdd: CarbonPictogram; export const MobileChat: CarbonPictogram; export const MobileDevices: CarbonPictogram; export const MobilePhone: CarbonPictogram; export const MortarAndPestle: CarbonPictogram; export const Moscow: CarbonPictogram; export const Mqa: CarbonPictogram; export const Multitask: CarbonPictogram; export const Munich: CarbonPictogram; export const NaturalLanguageClassifier: CarbonPictogram; export const Network: CarbonPictogram; export const NetworkServices: CarbonPictogram; export const Networking_01: CarbonPictogram; export const Networking_02: CarbonPictogram; export const Networking_03: CarbonPictogram; export const Networking_04: CarbonPictogram; export const Networking_05: CarbonPictogram; export const Nice: CarbonPictogram; export const NightClear: CarbonPictogram; export const NycBrooklyn: CarbonPictogram; export const NycManhattan: CarbonPictogram; export const NycManhattanAlt: CarbonPictogram; export const Office: CarbonPictogram; export const OilPump: CarbonPictogram; export const OilRig: CarbonPictogram; export const Overcast: CarbonPictogram; export const PaperClip: CarbonPictogram; export const Parliament: CarbonPictogram; export const PartnerRelationship: CarbonPictogram; export const Path: CarbonPictogram; export const Pattern: CarbonPictogram; export const Perfume: CarbonPictogram; export const Person_01: CarbonPictogram; export const Person_02: CarbonPictogram; export const Person_03: CarbonPictogram; export const Person_04: CarbonPictogram; export const Person_05: CarbonPictogram; export const Person_06: CarbonPictogram; export const Person_07: CarbonPictogram; export const Person_08: CarbonPictogram; export const Person_09: CarbonPictogram; export const PersonalityInsights: CarbonPictogram; export const PetriCulture: CarbonPictogram; export const PillBottle_01: CarbonPictogram; export const Pills: CarbonPictogram; export const Podcast: CarbonPictogram; export const Police: CarbonPictogram; export const Power: CarbonPictogram; export const Presentation: CarbonPictogram; export const Presenter: CarbonPictogram; export const Price: CarbonPictogram; export const Printer: CarbonPictogram; export const PrivateNetwork: CarbonPictogram; export const PrivateNetworkAlt: CarbonPictogram; export const PrivateNetworkAlt_01: CarbonPictogram; export const PrivateNetwork_01: CarbonPictogram; export const Progress: CarbonPictogram; export const Puzzle: CarbonPictogram; export const Question: CarbonPictogram; export const QuestionAndAnswer: CarbonPictogram; export const Rainy: CarbonPictogram; export const RainyHeavy: CarbonPictogram; export const Rank: CarbonPictogram; export const Receipt: CarbonPictogram; export const Recycle: CarbonPictogram; export const Refinery: CarbonPictogram; export const Refresh: CarbonPictogram; export const RelationshipExtraction: CarbonPictogram; export const Renew: CarbonPictogram; export const RenewTeam: CarbonPictogram; export const Repeat: CarbonPictogram; export const Report: CarbonPictogram; export const Reset: CarbonPictogram; export const ResetHybridCloud: CarbonPictogram; export const ResetSettings: CarbonPictogram; export const RetrieveAndRank: CarbonPictogram; export const RichTextFormat: CarbonPictogram; export const Robot: CarbonPictogram; export const Robotics: CarbonPictogram; export const Rome: CarbonPictogram; export const SaasEnablement: CarbonPictogram; export const SanFrancisco: CarbonPictogram; export const SanFranciscoFog: CarbonPictogram; export const SaoPaulo: CarbonPictogram; export const SaoPauloExpandedBase: CarbonPictogram; export const Satellite: CarbonPictogram; export const SatelliteDish: CarbonPictogram; export const Scale: CarbonPictogram; export const Seattle: CarbonPictogram; export const SecureData: CarbonPictogram; export const SecureProfile: CarbonPictogram; export const Security: CarbonPictogram; export const SecurityShield: CarbonPictogram; export const ServerRack: CarbonPictogram; export const Servers: CarbonPictogram; export const Shop: CarbonPictogram; export const ShoppingCart: CarbonPictogram; export const Shower: CarbonPictogram; export const Singapore: CarbonPictogram; export const SingleSignOn: CarbonPictogram; export const Slider: CarbonPictogram; export const Sneaker: CarbonPictogram; export const Snow: CarbonPictogram; export const SoftIceCream: CarbonPictogram; export const SoftlayerEnablement: CarbonPictogram; export const Solve: CarbonPictogram; export const Spaceship: CarbonPictogram; export const Speech: CarbonPictogram; export const SpeechAlphabetAExpanded: CarbonPictogram; export const SpeechToText: CarbonPictogram; export const Speedometer: CarbonPictogram; export const StairsPlanView: CarbonPictogram; export const StationaryBicycle: CarbonPictogram; export const Steel: CarbonPictogram; export const SteeringWheel: CarbonPictogram; export const Stethoscope: CarbonPictogram; export const Strategy: CarbonPictogram; export const StrategyDirect: CarbonPictogram; export const StrategyMove: CarbonPictogram; export const StrategyPlay: CarbonPictogram; export const Streamline: CarbonPictogram; export const Sunny: CarbonPictogram; export const SunnyHazy: CarbonPictogram; export const SupportServices: CarbonPictogram; export const SwipeLeft: CarbonPictogram; export const SwipeRight: CarbonPictogram; export const Tags: CarbonPictogram; export const Target: CarbonPictogram; export const TargetArea: CarbonPictogram; export const TelAviv: CarbonPictogram; export const Telecom: CarbonPictogram; export const Telephone: CarbonPictogram; export const Television: CarbonPictogram; export const TemperatureHigh: CarbonPictogram; export const TemperatureLow: CarbonPictogram; export const Tennis: CarbonPictogram; export const TestTubes: CarbonPictogram; export const TextToSpeech: CarbonPictogram; export const Time: CarbonPictogram; export const TimeLapse: CarbonPictogram; export const Toggle: CarbonPictogram; export const TokyoCherryBlossom: CarbonPictogram; export const TokyoGates: CarbonPictogram; export const TokyoTemple: CarbonPictogram; export const TokyoVolcano: CarbonPictogram; export const ToneAnalyzer: CarbonPictogram; export const Tools: CarbonPictogram; export const Tornado: CarbonPictogram; export const Toronto: CarbonPictogram; export const Touch: CarbonPictogram; export const TouchGesture: CarbonPictogram; export const TouchId: CarbonPictogram; export const TouchScreen: CarbonPictogram; export const TouchSwipe: CarbonPictogram; export const Tractor: CarbonPictogram; export const TradeoffAnalytics: CarbonPictogram; export const Train: CarbonPictogram; export const Transform: CarbonPictogram; export const Trash: CarbonPictogram; export const University: CarbonPictogram; export const Unlock: CarbonPictogram; export const UnlockAlt: CarbonPictogram; export const Upload: CarbonPictogram; export const UploadAlt: CarbonPictogram; export const UserAnalytics: CarbonPictogram; export const UserInsights: CarbonPictogram; export const UserSearch: CarbonPictogram; export const Vancouver: CarbonPictogram; export const Video: CarbonPictogram; export const VideoAlt: CarbonPictogram; export const VideoChat: CarbonPictogram; export const VideoPlay: CarbonPictogram; export const Virus: CarbonPictogram; export const Vision: CarbonPictogram; export const VisualInsights: CarbonPictogram; export const VisualRecognition: CarbonPictogram; export const Warning: CarbonPictogram; export const WarningAlt: CarbonPictogram; export const Washer: CarbonPictogram; export const WashingtonDc: CarbonPictogram; export const WashingtonDcCapitol: CarbonPictogram; export const WashingtonDcMonument: CarbonPictogram; export const WatsonAvatar: CarbonPictogram; export const Weather: CarbonPictogram; export const WebDeveloper: CarbonPictogram; export const Webcast: CarbonPictogram; export const Wheat: CarbonPictogram; export const Wifi: CarbonPictogram; export const WindPower: CarbonPictogram; export const Windows: CarbonPictogram; export const Windy: CarbonPictogram; export const Wine: CarbonPictogram; export const WirelessHome: CarbonPictogram; export const WirelessModem: CarbonPictogram; export const WreckingBall: CarbonPictogram; export const Yoga_01: CarbonPictogram; export const Yoga_02: CarbonPictogram; export const Yoga_03: CarbonPictogram; export const Yoga_04: CarbonPictogram;
the_stack
declare namespace Mocha { class SuiteRunnable { private _beforeEach; private _beforeAll; private _afterEach; private _afterAll; private _timeout; private _enableTimeouts; private _slow; private _bail; private _retries; private _onlyTests; private _onlySuites; constructor(title: string, parentContext?: Context); ctx: Context; suites: Suite[]; tests: Test[]; pending: boolean; file?: string; root: boolean; delayed: boolean; parent: Suite | undefined; title: string; /** * Create a new `Suite` with the given `title` and parent `Suite`. When a suite * with the same title is already present, that suite is returned to provide * nicer reporter and more flexible meta-testing. * * @see https://mochajs.org/api/mocha#.exports.create */ static create(parent: Suite, title: string): Suite; /** * Return a clone of this `Suite`. * * @see https://mochajs.org/api/Mocha.Suite.html#clone */ clone(): Suite; /** * Get timeout `ms`. * * @see https://mochajs.org/api/Mocha.Suite.html#timeout */ timeout(): number; /** * Set timeout `ms` or short-hand such as "2s". * * @see https://mochajs.org/api/Mocha.Suite.html#timeout */ timeout(ms: string | number): this; /** * Get number of times to retry a failed test. * * @see https://mochajs.org/api/Mocha.Suite.html#retries */ retries(): number; /** * Set number of times to retry a failed test. * * @see https://mochajs.org/api/Mocha.Suite.html#retries */ retries(n: string | number): this; /** * Get whether timeouts are enabled. * * @see https://mochajs.org/api/Mocha.Suite.html#enableTimeouts */ enableTimeouts(): boolean; /** * Set whether timeouts are `enabled`. * * @see https://mochajs.org/api/Mocha.Suite.html#enableTimeouts */ enableTimeouts(enabled: boolean): this; /** * Get slow `ms`. * * @see https://mochajs.org/api/Mocha.Suite.html#slow */ slow(): number; /** * Set slow `ms` or short-hand such as "2s". * * @see https://mochajs.org/api/Mocha.Suite.html#slow */ slow(ms: string | number): this; /** * Get whether to bail after first error. * * @see https://mochajs.org/api/Mocha.Suite.html#bail */ bail(): boolean; /** * Set whether to bail after first error. * * @see https://mochajs.org/api/Mocha.Suite.html#bail */ bail(bail: boolean): this; /** * Check if this suite or its parent suite is marked as pending. * * @see https://mochajs.org/api/Mocha.Suite.html#isPending */ isPending(): boolean; /** * Run `fn(test[, done])` before running tests. * * @see https://mochajs.org/api/Mocha.Suite.html#beforeAll */ beforeAll(fn?: Func | AsyncFunc): this; /** * Run `fn(test[, done])` before running tests. * * @see https://mochajs.org/api/Mocha.Suite.html#beforeAll */ beforeAll(title: string, fn?: Func | AsyncFunc): this; /** * Run `fn(test[, done])` after running tests. * * @see https://mochajs.org/api/Mocha.Suite.html#afterAll */ afterAll(fn?: Func | AsyncFunc): this; /** * Run `fn(test[, done])` after running tests. * * @see https://mochajs.org/api/Mocha.Suite.html#afterAll */ afterAll(title: string, fn?: Func | AsyncFunc): this; /** * Run `fn(test[, done])` before each test case. * * @see https://mochajs.org/api/Mocha.Suite.html#beforeEach */ beforeEach(fn?: Func | AsyncFunc): this; /** * Run `fn(test[, done])` before each test case. * * @see https://mochajs.org/api/Mocha.Suite.html#beforeEach */ beforeEach(title: string, fn?: Func | AsyncFunc): this; /** * Run `fn(test[, done])` after each test case. * * @see https://mochajs.org/api/Mocha.Suite.html#afterEach */ afterEach(fn?: Func | AsyncFunc): this; /** * Run `fn(test[, done])` after each test case. * * @see https://mochajs.org/api/Mocha.Suite.html#afterEach */ afterEach(title: string, fn?: Func | AsyncFunc): this; /** * Add a test `suite`. * * @see https://mochajs.org/api/Mocha.Suite.html#addSuite */ addSuite(suite: Suite): this; /** * Add a `test` to this suite. * * @see https://mochajs.org/api/Mocha.Suite.html#addTest */ addTest(test: Test): this; /** * Return the full title generated by recursively concatenating the parent's * full title. * * @see https://mochajs.org/api/Mocha.Suite.html#.Suite#fullTitle */ fullTitle(): string; /** * Return the title path generated by recursively concatenating the parent's * title path. * * @see https://mochajs.org/api/Mocha.Suite.html#.Suite#titlePath */ titlePath(): string[]; /** * Return the total number of tests. * * @see https://mochajs.org/api/Mocha.Suite.html#.Suite#total */ total(): number; /** * Iterates through each suite recursively to find all tests. Applies a * function in the format `fn(test)`. * * @see https://mochajs.org/api/Mocha.Suite.html#eachTest */ eachTest(fn: (test: Test) => void): this; /** * This will run the root suite if we happen to be running in delayed mode. * * @see https://mochajs.org/api/Mocha.Suite.html#run */ run(): void; /** * Generic hook-creator. */ protected _createHook(title: string, fn?: Func | AsyncFunc): Hook; } /** * Initialize a new `Hook` with the given `title` and callback `fn` * * @see https://mochajs.org/api/Hook.html */ class Hook extends Runnable { private _error; type: "hook"; originalTitle?: string; // added by Runner /** * Get the test `err`. * * @see https://mochajs.org/api/Hook.html#error */ error(): any; /** * Set the test `err`. * * @see https://mochajs.org/api/Hook.html#error */ error(err: any): void; } /** * Initialize a new `Runnable` with the given `title` and callback `fn`. * * @see https://mochajs.org/api/Runnable.html */ class Runnable { private _slow; private _enableTimeouts; private _retries; private _currentRetry; private _timeout; private _timeoutError; constructor(title: string, fn?: Func | AsyncFunc); title: string; fn: Func | AsyncFunc | undefined; body: string; async: boolean; sync: boolean; timedOut: boolean; pending: boolean; duration?: number; parent?: Suite; state?: "failed" | "passed"; timer?: any; ctx?: Context; callback?: Done; allowUncaught?: boolean; file?: string; /** * Get test timeout. * * @see https://mochajs.org/api/Runnable.html#timeout */ timeout(): number; /** * Set test timeout. * * @see https://mochajs.org/api/Runnable.html#timeout */ timeout(ms: string | number): this; /** * Get test slowness threshold. * * @see https://mochajs.org/api/Runnable.html#slow */ slow(): number; /** * Set test slowness threshold. * * @see https://mochajs.org/api/Runnable.html#slow */ slow(ms: string | number): this; /** * Get whether timeouts are enabled. * * @see https://mochajs.org/api/Runnable.html#enableTimeouts */ enableTimeouts(): boolean; /** * Set whether timeouts are enabled. * * @see https://mochajs.org/api/Runnable.html#enableTimeouts */ enableTimeouts(enabled: boolean): this; /** * Halt and mark as pending. */ skip(): never; /** * Check if this runnable or its parent suite is marked as pending. * * @see https://mochajs.org/api/Runnable.html#isPending */ isPending(): boolean; /** * Return `true` if this Runnable has failed. */ isFailed(): boolean; /** * Return `true` if this Runnable has passed. */ isPassed(): boolean; /** * Set or get number of retries. * * @see https://mochajs.org/api/Runnable.html#retries */ retries(): number; /** * Set or get number of retries. * * @see https://mochajs.org/api/Runnable.html#retries */ retries(n: number): void; /** * Set or get current retry * * @see https://mochajs.org/api/Runnable.html#currentRetry */ protected currentRetry(): number; /** * Set or get current retry * * @see https://mochajs.org/api/Runnable.html#currentRetry */ protected currentRetry(n: number): void; /** * Return the full title generated by recursively concatenating the parent's full title. */ fullTitle(): string; /** * Return the title path generated by concatenating the parent's title path with the title. */ titlePath(): string[]; /** * Clear the timeout. * * @see https://mochajs.org/api/Runnable.html#clearTimeout */ clearTimeout(): void; /** * Inspect the runnable void of private properties. * * @see https://mochajs.org/api/Runnable.html#inspect */ inspect(): string; /** * Reset the timeout. * * @see https://mochajs.org/api/Runnable.html#resetTimeout */ resetTimeout(): void; /** * Get a list of whitelisted globals for this test run. * * @see https://mochajs.org/api/Runnable.html#globals */ globals(): string[]; /** * Set a list of whitelisted globals for this test run. * * @see https://mochajs.org/api/Runnable.html#globals */ globals(globals: ReadonlyArray<string>): void; /** * Run the test and invoke `fn(err)`. * * @see https://mochajs.org/api/Runnable.html#run */ run(fn: Done): void; } type Done = (err?: any) => void; /** * Callback function used for tests and hooks. */ type Func = (this: Context, done: Done) => void; /** * Async callback function used for tests and hooks. */ type AsyncFunc = (this: Context) => PromiseLike<any>; /** * Test context * * @see https://mochajs.org/api/module-Context.html#~Context */ class Context { private _runnable; test?: Runnable; currentTest?: Test; /** * Get the context `Runnable`. */ runnable(): Runnable; /** * Set the context `Runnable`. */ runnable(runnable: Runnable): this; /** * Get test timeout. */ timeout(): number; /** * Set test timeout. */ timeout(ms: string | number): this; /** * Get whether timeouts are enabled. */ enableTimeouts(): boolean; /** * Set whether timeouts are enabled. */ enableTimeouts(enabled: boolean): this; /** * Get test slowness threshold. */ slow(): number; /** * Set test slowness threshold. */ slow(ms: string | number): this; /** * Mark a test as skipped. */ skip(): never; /** * Get the number of allowed retries on failed tests. */ retries(): number; /** * Set the number of allowed retries on failed tests. */ retries(n: number): this; [key: string]: any; } }
the_stack
import { binaryBigIntAnnotation, BinaryBigIntType, buildFunction, callExtractedFunctionIfAvailable, collapsePath, ContainerAccessor, createTypeGuardFunction, embeddedAnnotation, EmbeddedOptions, excludedAnnotation, executeTemplates, extendTemplateLiteral, extractStateToFunctionAndCallIt, getIndexCheck, getNameExpression, getStaticDefaultCodeForProperty, hasDefaultValue, isNullable, isOptional, mongoIdAnnotation, ReflectionClass, ReflectionKind, resolveTypeMembers, RuntimeCode, sortSignatures, TemplateState, Type, TypeClass, TypeGuardRegistry, TypeIndexSignature, TypeLiteral, TypeObjectLiteral, TypeProperty, TypePropertySignature, TypeTemplateLiteral, TypeTuple, TypeUnion, uuidAnnotation } from '@deepkit/type'; import { seekElementSize } from './continuation'; import { BSONType, digitByteSize, isSerializable } from './utils'; function getNameComparator(name: string): string { //todo: support utf8 names const bufferCompare: string[] = []; for (let i = 0; i < name.length; i++) { bufferCompare.push(`state.parser.buffer[state.parser.offset + ${i}] === ${name.charCodeAt(i)}`); } bufferCompare.push(`state.parser.buffer[state.parser.offset + ${name.length}] === 0`); return bufferCompare.join(' && '); } function throwInvalidBsonType(type: Type, state: TemplateState) { state.setContext({ BSONType }); return state.throwCode(type, JSON.stringify('invalid BSON type'), `'bson type ' + BSONType[state.elementType]`); } export function deserializeBinary(type: Type, state: TemplateState) { const typeVar = state.setVariable('type', type); state.addCode(` if (state.elementType === ${BSONType.BINARY}) { ${state.setter} = state.parser.parseBinary(${typeVar}); } else { ${throwInvalidBsonType(type, state)} } `); } export function deserializeAny(type: Type, state: TemplateState) { state.addCode(` ${state.setter} = state.parser.parse(state.elementType); `); } export function deserializeNumber(type: Type, state: TemplateState) { const readBigInt = type.kind === ReflectionKind.bigint ? `state.parser.parseBinaryBigInt()` : `Number(state.parser.parseBinaryBigInt())`; state.addCode(` if (state.elementType === ${BSONType.INT}) { ${state.setter} = state.parser.parseInt(); } else if (state.elementType === ${BSONType.NULL} || state.elementType === ${BSONType.UNDEFINED}) { ${state.setter} = 0; } else if (state.elementType === ${BSONType.NUMBER}) { ${state.setter} = state.parser.parseNumber(); } else if (state.elementType === ${BSONType.LONG} || state.elementType === ${BSONType.TIMESTAMP}) { ${state.setter} = state.parser.parseLong(); } else if (state.elementType === ${BSONType.BOOLEAN}) { ${state.setter} = state.parser.parseBoolean() ? 1 : 0; } else if (state.elementType === ${BSONType.BINARY}) { ${state.setter} = ${readBigInt}; } else if (state.elementType === ${BSONType.STRING}) { ${state.setter} = Number(state.parser.parseString()); if (isNaN(${state.setter})) { ${throwInvalidBsonType(type, state)} } } else { ${throwInvalidBsonType(type, state)} } `); } export function deserializeBigInt(type: Type, state: TemplateState) { const binaryBigInt = binaryBigIntAnnotation.getFirst(type); const parseBigInt = binaryBigInt === BinaryBigIntType.signed ? 'parseSignedBinaryBigInt' : 'parseBinaryBigInt'; state.addCode(` if (state.elementType === ${BSONType.INT}) { ${state.setter} = BigInt(state.parser.parseInt()); } else if (state.elementType === ${BSONType.NULL} || state.elementType === ${BSONType.UNDEFINED}) { ${state.setter} = 0n; } else if (state.elementType === ${BSONType.NUMBER}) { ${state.setter} = BigInt(state.parser.parseNumber()); } else if (state.elementType === ${BSONType.LONG} || state.elementType === ${BSONType.TIMESTAMP}) { ${state.setter} = BigInt(state.parser.parseLong()); } else if (state.elementType === ${BSONType.BOOLEAN}) { ${state.setter} = BigInt(state.parser.parseBoolean() ? 1 : 0); } else if (state.elementType === ${BSONType.BINARY} && ${binaryBigInt} !== undefined) { ${state.setter} = state.parser.${parseBigInt}(); } else if (state.elementType === ${BSONType.STRING}) { ${state.setter} = BigInt(state.parser.parseString()); } else { ${throwInvalidBsonType(type, state)} } `); } export function deserializeString(type: Type, state: TemplateState) { const branches: string[] = []; if (uuidAnnotation.getFirst(type)) { branches.push(` } else if (state.elementType === ${BSONType.BINARY}) { ${state.setter} = state.parser.parseBinary(); `); } else if (mongoIdAnnotation.getFirst(type)) { branches.push(` } else if (state.elementType === ${BSONType.OID}) { ${state.setter} = state.parser.parseOid(); `); } state.addCode(` if (state.elementType === ${BSONType.STRING}) { ${state.setter} = state.parser.parseString(); } else if (state.elementType === ${BSONType.NULL} || state.elementType === ${BSONType.UNDEFINED}) { ${state.setter} = ''; } else if (state.elementType === ${BSONType.INT}) { ${state.setter} = '' + state.parser.parseInt(); } else if (state.elementType === ${BSONType.BOOLEAN}) { ${state.setter} = '' + state.parser.parseBoolean(); } else if (state.elementType === ${BSONType.NUMBER}) { ${state.setter} = '' + state.parser.parseNumber(); } else if (state.elementType === ${BSONType.LONG} || state.elementType === ${BSONType.TIMESTAMP}) { ${state.setter} = '' + state.parser.parseLong(); ${branches.join('\n')} } else { ${throwInvalidBsonType(type, state)} } ${executeTemplates(state.fork(state.setter, state.setter).forRegistry(state.registry.serializer.deserializeRegistry), type)} `); } export function deserializeLiteral(type: TypeLiteral, state: TemplateState) { state.addCode(` ${state.setter} = ${state.setVariable('literal', type.literal)}; seekElementSize(elementType, state.parser); `); } export function deserializeTemplateLiteral(type: TypeTemplateLiteral, state: TemplateState) { state.setContext({ extendTemplateLiteral: extendTemplateLiteral }); const typeVar = state.setVariable('type', type); state.addCode(` if (state.elementType === ${BSONType.STRING}) { ${state.setter} = state.parser.parseString(); if (!extendTemplateLiteral({kind: ${ReflectionKind.literal}, literal: ${state.setter}}, ${typeVar})) { ${state.throwCode(type, '', state.setter)} } } else { ${throwInvalidBsonType(type, state)} } `); } export function deserializeNull(type: Type, state: TemplateState) { state.addCode(` if (state.elementType === ${BSONType.NULL} || state.elementType === ${BSONType.UNDEFINED}) { ${state.setter} = null; } else { ${throwInvalidBsonType(type, state)} } `); } export function deserializeUndefined(type: Type, state: TemplateState) { state.addCode(` if (state.elementType === ${BSONType.NULL} || state.elementType === ${BSONType.UNDEFINED}) { ${state.setter} = undefined; } else { ${throwInvalidBsonType(type, state)} } `); } export function deserializeBoolean(type: Type, state: TemplateState) { state.addCode(` if (state.elementType === ${BSONType.BOOLEAN}) { ${state.setter} = state.parser.parseBoolean(); } else if (state.elementType === ${BSONType.NULL} || state.elementType === ${BSONType.UNDEFINED}) { ${state.setter} = false; } else if (state.elementType === ${BSONType.INT}) { ${state.setter} = state.parser.parseInt() ? true : false; } else if (state.elementType === ${BSONType.NUMBER}) { ${state.setter} = state.parser.parseNumber() ? true : false; } else if (state.elementType === ${BSONType.LONG} || state.elementType === ${BSONType.TIMESTAMP}) { ${state.setter} = state.parser.parseLong() ? true : false; } else { ${throwInvalidBsonType(type, state)} } `); } export function deserializeDate(type: Type, state: TemplateState) { state.addCode(` if (state.elementType === ${BSONType.DATE}) { ${state.setter} = state.parser.parseDate(); } else if (state.elementType === ${BSONType.INT}) { ${state.setter} = new Date(state.parser.parseInt()); } else if (state.elementType === ${BSONType.NUMBER}) { ${state.setter} = new Date(state.parser.parseNumber()); } else if (state.elementType === ${BSONType.LONG} || state.elementType === ${BSONType.TIMESTAMP}) { ${state.setter} = new Date(state.parser.parseLong()); } else if (state.elementType === ${BSONType.STRING}) { ${state.setter} = new Date(state.parser.parseString()); } else { ${throwInvalidBsonType(type, state)} } `); } export function deserializeRegExp(type: Type, state: TemplateState) { state.addCode(` if (state.elementType === ${BSONType.REGEXP}) { ${state.setter} = state.parser.parseRegExp(); } else { ${throwInvalidBsonType(type, state)} } `); } export function deserializeUnion(bsonTypeGuards: TypeGuardRegistry, type: TypeUnion, state: TemplateState) { const lines: string[] = []; //see handleUnion from deepkit/type for more information const typeGuards = bsonTypeGuards.getSortedTemplateRegistries(); for (const [specificality, typeGuard] of typeGuards) { for (const t of type.types) { const fn = createTypeGuardFunction(t, state.fork().forRegistry(typeGuard)); if (!fn) continue; const guard = state.setVariable('guard' + t.kind, fn); const looseCheck = specificality <= 0 ? `state.loosely && ` : ''; lines.push(`else if (${looseCheck}${guard}(${state.accessor || 'undefined'}, state, ${collapsePath(state.path)})) { //type = ${t.kind}, specificality=${specificality} ${executeTemplates(state.fork(state.setter, state.accessor).forPropertyName(state.propertyName), t)} }`); } } state.addCodeForSetter(` { if (!state.elementType) state.elementType = ${BSONType.OBJECT}; const oldElementType = state.elementType; if (false) { } ${lines.join(' ')} else { ${throwInvalidBsonType(type, state)} } state.elementType = oldElementType; } `); } export function bsonTypeGuardUnion(bsonTypeGuards: TypeGuardRegistry, type: TypeUnion, state: TemplateState) { const lines: string[] = []; //see serializeTypeUnion from deepkit/type for more information const typeGuards = bsonTypeGuards.getSortedTemplateRegistries(); for (const [specificality, typeGuard] of typeGuards) { for (const t of type.types) { const fn = createTypeGuardFunction(t, state.fork().forRegistry(typeGuard)); if (!fn) continue; const guard = state.setVariable('guard' + t.kind, fn); const looseCheck = specificality <= 0 ? `state.loosely && ` : ''; lines.push(`else if (${looseCheck}${guard}(${state.accessor || 'undefined'}, state)) { //type = ${t.kind}, specificality=${specificality} ${state.setter} = true; }`); } } state.addCodeForSetter(` { if (!state.elementType) state.elementType = ${BSONType.OBJECT}; const oldElementType = state.elementType; if (false) { } ${lines.join(' ')} state.elementType = oldElementType; } `); } export function deserializeTuple(type: TypeTuple, state: TemplateState) { const result = state.compilerContext.reserveName('result'); const v = state.compilerContext.reserveName('v'); const i = state.compilerContext.reserveName('i'); const length = state.compilerContext.reserveName('length'); state.setContext({ digitByteSize }); const lines: string[] = []; let restEndOffset = 0; let restStart = 0; let hasRest = false; //when there are types behind a rest (e.g. [string, ...number[], boolean]), then we have to iterate overall items first to determine when to use the boolean code. let hasTypedBehindRest = false; for (let i = 0; i < type.types.length; i++) { if (type.types[i].type.kind === ReflectionKind.rest) { hasRest = true; restStart = i; restEndOffset = type.types.length - (i + 1); } else if (hasRest) { hasTypedBehindRest = true; } } let j = 0; for (const member of type.types) { if (member.type.kind === ReflectionKind.rest) { const check = hasTypedBehindRest ? `${i} >= ${j} && ${i} < ${length} - ${restEndOffset}` : `${i} >= ${j}`; lines.push(` //tuple rest item ${j} else if (${check}) { ${executeTemplates(state.fork(v).extendPath(member.name || new RuntimeCode(i)), member.type.type)} if (${v} !== undefined || ${isOptional(member)}) { ${result}.push(${v}); } ${i}++; continue; } `); } else { const offsetRight = type.types.length - j; const check = hasRest && j >= restStart ? `${length} - ${i} === ${offsetRight}` : `${i} === ${j}`; lines.push(` //tuple item ${j} else if (${check}) { ${executeTemplates(state.fork(v).extendPath(member.name || new RuntimeCode(i)), member.type)} if (${v} !== undefined || ${isOptional(member)}) { ${result}.push(${v}); } ${i}++; continue; } `); } j++; } let readLength = ''; if (hasTypedBehindRest) { readLength = ` const lengthStart = state.parser.offset; while (state.parser.offset < end) { const elementType = state.elementType = state.parser.eatByte(); if (elementType === 0) break; //arrays are represented as objects, so we skip the key name state.parser.seek(digitByteSize(${length})); seekElementSize(elementType, state.parser); ${length}++; } state.parser.offset = lengthStart; `; } state.addCode(` if (state.elementType && state.elementType !== ${BSONType.ARRAY}) ${throwInvalidBsonType({ kind: ReflectionKind.array, type: type }, state)} { var ${result} = []; let ${length} = 0; const end = state.parser.eatUInt32() + state.parser.offset; const oldElementType = state.elementType; ${readLength} let ${i} = 0; while (state.parser.offset < end) { const elementType = state.elementType = state.parser.eatByte(); if (elementType === 0) break; //arrays are represented as objects, so we skip the key name state.parser.seek(digitByteSize(${i})); let ${v}; if (false) {} ${lines.join('\n')} ${i}++; //if no type match, seek seekElementSize(elementType, state.parser); } ${state.setter} = ${result}; state.elementType = oldElementType; } `); } export function bsonTypeGuardTuple(type: TypeTuple, state: TemplateState) { const valid = state.compilerContext.reserveName('valid'); const i = state.compilerContext.reserveName('i'); const length = state.compilerContext.reserveName('length'); state.setContext({ digitByteSize, seekElementSize }); const lines: string[] = []; let restEndOffset = 0; let restStart = 0; let hasRest = false; //when there are types behind a rest (e.g. [string, ...number[], boolean]), then we have to iterate overall items first to determine when to use the boolean code. let hasTypedBehindRest = false; for (let i = 0; i < type.types.length; i++) { if (type.types[i].type.kind === ReflectionKind.rest) { hasRest = true; restStart = i; restEndOffset = type.types.length - (i + 1); } else if (hasRest) { hasTypedBehindRest = true; } } let j = 0; for (const member of type.types) { if (member.type.kind === ReflectionKind.rest) { const check = hasTypedBehindRest ? `${i} >= ${j} && ${i} < ${length} - ${restEndOffset}` : `${i} >= ${j}`; lines.push(` //tuple rest item ${j} else if (${check}) { ${executeTemplates(state.fork(valid).extendPath(new RuntimeCode(i)), member.type.type)} if (!${valid}) { break; } ${i}++; seekElementSize(elementType, state.parser); continue; } `); } else { const offsetRight = type.types.length - j; const check = hasRest && j >= restStart ? `${length} - ${i} === ${offsetRight}` : `${i} === ${j}`; lines.push(` //tuple item ${j} else if (${check}) { ${executeTemplates(state.fork(valid).extendPath(new RuntimeCode(i)), member.type)} if (!${valid}) { break; } ${i}++; seekElementSize(elementType, state.parser); continue; } `); } j++; } let readLength = ''; if (hasTypedBehindRest) { readLength = ` const lengthStart = state.parser.offset; while (state.parser.offset < end) { const elementType = state.elementType = state.parser.eatByte(); if (elementType === 0) break; //arrays are represented as objects, so we skip the key name state.parser.seek(digitByteSize(${length})); seekElementSize(elementType, state.parser); ${length}++; } state.parser.offset = lengthStart; `; } state.addCode(` let ${valid} = state.elementType && state.elementType === ${BSONType.ARRAY}; if (${valid}){ let ${length} = 0; const start = state.parser.offset; const end = state.parser.eatUInt32() + state.parser.offset; const oldElementType = state.elementType; ${readLength} let ${i} = 0; while (state.parser.offset < end) { const elementType = state.elementType = state.parser.eatByte(); if (elementType === 0) break; //arrays are represented as objects, so we skip the key name state.parser.seek(digitByteSize(${i})); if (false) {} ${lines.join('\n')} //if no type match, seek ${i}++; seekElementSize(elementType, state.parser); } state.elementType = oldElementType; state.parser.offset = start; } ${state.setter} = ${valid}; `); } export function deserializeArray(elementType: Type, state: TemplateState) { const result = state.compilerContext.reserveName('result'); const v = state.compilerContext.reserveName('v'); const i = state.compilerContext.reserveName('i'); state.setContext({ digitByteSize }); state.addCode(` if (state.elementType && state.elementType !== ${BSONType.ARRAY}) ${throwInvalidBsonType({ kind: ReflectionKind.array, type: elementType }, state)} { var ${result} = []; const end = state.parser.eatUInt32() + state.parser.offset; const oldElementType = state.elementType; let ${i} = 0; while (state.parser.offset < end) { const elementType = state.elementType = state.parser.eatByte(); if (elementType === 0) break; //arrays are represented as objects, so we skip the key name state.parser.seek(digitByteSize(${i})); let ${v}; ${executeTemplates(state.fork(v, '').extendPath(new RuntimeCode(i)), elementType)} ${result}.push(${v}); ${i}++; } ${state.setter} = ${result}; state.elementType = oldElementType; } `); } /** * This array type guard goes through all array elements in order to determine the correct type. * This is only necessary when a union has at least 2 array members, otherwise a simple array check is enough. */ export function bsonTypeGuardArray(elementType: Type, state: TemplateState) { const v = state.compilerContext.reserveName('v'); const i = state.compilerContext.reserveName('i'); state.setContext({ digitByteSize, seekElementSize }); const typeGuardCode = executeTemplates(state.fork(v, '').extendPath(new RuntimeCode(i)), elementType); state.addCode(` ${state.setter} = state.elementType && state.elementType === ${BSONType.ARRAY}; if (${state.setter}) { const start = state.parser.offset; const oldElementType = state.elementType; const end = state.parser.eatUInt32() + state.parser.offset; let ${i} = 0; while (state.parser.offset < end) { const elementType = state.elementType = state.parser.eatByte(); if (elementType === 0) break; //arrays are represented as objects, so we skip the key name state.parser.seek(digitByteSize(${i})); let ${v}; ${typeGuardCode} if (!${v}) { ${state.setter} = false; break; } //since type guards don't eat, we seek automatically forward seekElementSize(elementType, state.parser); ${i}++; } state.parser.offset = start; state.elementType = oldElementType; } `); } export function getEmbeddedClassesForProperty(type: Type): { type: TypeClass, options: EmbeddedOptions }[] { if (type.kind === ReflectionKind.propertySignature || type.kind === ReflectionKind.property) type = type.type; const res: { type: TypeClass, options: EmbeddedOptions }[] = []; if (type.kind === ReflectionKind.union) { for (const t of type.types) { if (t.kind === ReflectionKind.class) { const embedded = embeddedAnnotation.getFirst(t); if (embedded) res.push({ options: embedded, type: t }); } } } else if (type.kind === ReflectionKind.class) { const embedded = embeddedAnnotation.getFirst(type); if (embedded) res.push({ options: embedded, type: type }); } return res; } export function deserializeObjectLiteral(type: TypeClass | TypeObjectLiteral, state: TemplateState) { //emdedded for the moment disabled. treat it as normal property. // const embedded = embeddedAnnotation.getFirst(type); // if (type.kind === ReflectionKind.class && embedded) { // const container = state.compilerContext.reserveName('container'); // // const embedded = deserializeEmbedded(type, state.fork(undefined, container).forRegistry(state.registry.serializer.deserializeRegistry)); // if (embedded) { // state.addCode(` // const ${container} = state.parser.parse(state.elementType); // console.log('container data', '${state.setter}', ${container}); // ${embedded} // `); // return; // } // } if (callExtractedFunctionIfAvailable(state, type)) return; const extract = extractStateToFunctionAndCallIt(state, type); state = extract.state; const lines: string[] = []; const signatures: TypeIndexSignature[] = []; const object = state.compilerContext.reserveName('object'); const resetDefaultSets: string[] = []; //run code for properties that had no value in the BSON. either set static values (literal, or null), or throw an error. const setDefaults: string[] = []; interface HandleEmbedded { type: TypeClass; valueSetVar: string; property: TypeProperty | TypePropertySignature; containerVar: string; } const handleEmbeddedClasses: HandleEmbedded[] = []; for (const member of resolveTypeMembers(type)) { if (member.kind === ReflectionKind.indexSignature) { if (excludedAnnotation.isExcluded(member.type, state.registry.serializer.name)) continue; signatures.push(member); } if (member.kind !== ReflectionKind.property && member.kind !== ReflectionKind.propertySignature) continue; if (!isSerializable(member.type)) continue; if (excludedAnnotation.isExcluded(member.type, state.registry.serializer.name)) continue; const nameInBson = String(state.namingStrategy.getPropertyName(member, state.registry.serializer.name)); const valueSetVar = state.compilerContext.reserveName('valueSetVar'); // //since Embedded<T> can have arbitrary prefix, we have to collect all fields first, and then after the loop, build everything together. // const embeddedClasses = getEmbeddedClassesForProperty(member); // //todo: // // 1. Embedded in a union need for each entry in the union (there can be multiple Embedded in one union) to collect all possible values. We collect them into own container // // then run the typeGuardObjectLiteral on it at the end of the loop, if the member was not already set. this works the same for non-union members as well, right? // // 2. we have to delay detecting the union, right? Otherwise `Embedded<T, {prefix: 'p'}> | string` will throw an error that it can't convert undefined to string, when // // ${member.name} is not provided. // // 3. we could also collect all values in a loop earlier? // if (embeddedClasses.length) { // for (const embedded of embeddedClasses) { // const constructorProperties = getConstructorProperties(embedded.type); // if (!constructorProperties.properties.length) throw new BSONError(`Can not embed class ${getClassName(embedded.type.classType)} since it has no constructor properties`); // // const containerVar = state.compilerContext.reserveName('container'); // const handleEmbedded: HandleEmbedded = { // type: embedded.type, containerVar, property: member, valueSetVar // }; // handleEmbeddedClasses.push(handleEmbedded); // // for (const property of constructorProperties.properties) { // const setter = getEmbeddedPropertyName(state.namingStrategy, property, embedded.options); // const accessor = getEmbeddedAccessor(embedded.type, constructorProperties.properties.length !== 1, nameInBson, state.namingStrategy, property, embedded.options); // //todo: handle explicit undefined and non-existing // lines.push(` // if (${getNameComparator(accessor)}) { // state.parser.offset += ${accessor.length} + 1; // ${executeTemplates(state.fork(new ContainerAccessor(containerVar, JSON.stringify(setter)), ''), property.type)}; // continue; // } // `); // } // } // } resetDefaultSets.push(`var ${valueSetVar} = false;`); const setter = new ContainerAccessor(object, JSON.stringify(member.name)); const staticDefault = getStaticDefaultCodeForProperty(member, setter, state); let throwInvalidTypeError = ''; if (!isOptional(member) && !hasDefaultValue(member)) { throwInvalidTypeError = state.fork().extendPath(member.name).throwCode(member.type as Type, '', `'undefined value'`); } setDefaults.push(`if (!${valueSetVar}) { ${staticDefault || throwInvalidTypeError} } `); let seekOnExplicitUndefined = ''; //handle explicitly set `undefined`, by jumping over the registered deserializers. if `null` is given and the property has no null type, we treat it as undefined. if (isOptional(member) || hasDefaultValue(member)) { const setUndefined = isOptional(member) ? `${setter} = undefined;` : hasDefaultValue(member) ? `` : `${setter} = undefined;`; const check = isNullable(member) ? `elementType === ${BSONType.UNDEFINED}` : `elementType === ${BSONType.UNDEFINED} || elementType === ${BSONType.NULL}`; seekOnExplicitUndefined = ` if (${check}) { ${setUndefined} seekElementSize(elementType, state.parser); continue; }`; } const setterTemplate = executeTemplates(state.fork(setter, '').extendPath(member.name), member.type); lines.push(` //property ${String(member.name)} (${member.type.kind}) else if (!${valueSetVar} && ${getNameComparator(nameInBson)}) { state.parser.offset += ${nameInBson.length} + 1; ${valueSetVar} = true; ${seekOnExplicitUndefined} ${setterTemplate} continue; } `); } if (signatures.length) { const i = state.compilerContext.reserveName('i'); const signatureLines: string[] = []; sortSignatures(signatures); for (const signature of signatures) { const check = isOptional(signature.type) ? `` : `elementType !== ${BSONType.UNDEFINED} &&`; signatureLines.push(`else if (${check} ${getIndexCheck(state, i, signature.index)}) { ${executeTemplates(state.fork(`${object}[${i}]`).extendPath(new RuntimeCode(i)).forPropertyName(new RuntimeCode(i)), signature.type)} continue; }`); } //the index signature type could be: string, number, symbol. //or a literal when it was constructed by a mapped type. lines.push(`else { let ${i} = state.parser.eatObjectPropertyName(); if (false) {} ${signatureLines.join(' ')} //if no index signature matches, we skip over it seekElementSize(elementType, state.parser); continue; }`); } state.setContext({ seekElementSize }); let initializeObject = `{}`; let createClassInstance = ``; if (type.kind === ReflectionKind.class && type.classType !== Object) { const reflection = ReflectionClass.from(type.classType); const constructor = reflection.getConstructorOrUndefined(); if (constructor && constructor.parameters.length) { const constructorArguments: string[] = []; for (const parameter of constructor.getParameters()) { const name = getNameExpression(parameter.getName(), state); constructorArguments.push(parameter.getVisibility() === undefined ? 'undefined' : `${object}[${name}]`); } createClassInstance = ` ${state.setter} = new ${state.compilerContext.reserveConst(type.classType, 'classType')}(${constructorArguments.join(', ')}); Object.assign(${state.setter}, ${object}); `; } else { initializeObject = `new ${state.compilerContext.reserveConst(type.classType, 'classType')}()`; } } const handleEmbeddedClassesLines: string[] = []; // for (const handle of handleEmbeddedClasses) { // // const constructorProperties = getConstructorProperties(handle.type); // const setter = new ContainerAccessor(object, JSON.stringify(handle.property.name)); // handleEmbeddedClassesLines.push(` // ${deserializeEmbedded(handle.type, state.fork(setter, handle.containerVar).forRegistry(state.registry.serializer.deserializeRegistry), handle.containerVar)} // if (${inAccessor(setter)}) { // ${handle.valueSetVar} = true; // } // `); // } state.addCode(` if (state.elementType && state.elementType !== ${BSONType.OBJECT}) ${throwInvalidBsonType(type, state)} var ${object} = ${initializeObject}; ${handleEmbeddedClasses.map(v => `const ${v.containerVar} = {};`).join('\n')} { const end = state.parser.eatUInt32() + state.parser.offset; ${resetDefaultSets.join('\n')} const oldElementType = state.elementType; while (state.parser.offset < end) { const elementType = state.elementType = state.parser.eatByte(); if (elementType === 0) break; if (false) {} ${lines.join('\n')} //jump over this property when not registered in schema while (state.parser.offset < end && state.parser.buffer[state.parser.offset++] != 0); //seek property value if (state.parser.offset >= end) break; seekElementSize(elementType, state.parser); } ${handleEmbeddedClassesLines.join('\n')} ${setDefaults.join('\n')} ${state.setter} = ${object}; ${createClassInstance} state.elementType = oldElementType; } `); extract.setFunction(buildFunction(state, type)); } export function bsonTypeGuardObjectLiteral(type: TypeClass | TypeObjectLiteral, state: TemplateState) { //emdedded for the moment disabled. treat it as normal property. // const embedded = embeddedAnnotation.getFirst(type); // if (type.kind === ReflectionKind.class && embedded && state.target === 'deserialize') { // const container = state.compilerContext.reserveName('container'); // const sub = state.fork(undefined, container).forRegistry(state.registry.serializer.typeGuards.getRegistry(1)); // typeGuardEmbedded(type, sub, embedded); // state.addCode(` // const ${container} = state.parser.read(state.elementType); // console.log('container data', '${state.setter}', ${container}); // ${sub.template} // `); // return; // } if (callExtractedFunctionIfAvailable(state, type)) return; const extract = extractStateToFunctionAndCallIt(state, type); state = extract.state; const lines: string[] = []; const signatures: TypeIndexSignature[] = []; const valid = state.compilerContext.reserveName('valid'); const resetDefaultSets: string[] = []; //run code for properties that had no value in the BSON. either set static values (literal, or null), or throw an error. const setDefaults: string[] = []; for (const member of resolveTypeMembers(type)) { if (member.kind === ReflectionKind.indexSignature) { if (excludedAnnotation.isExcluded(member.type, state.registry.serializer.name)) continue; signatures.push(member); } if (member.kind !== ReflectionKind.property && member.kind !== ReflectionKind.propertySignature) continue; if (!isSerializable(member.type)) continue; if (excludedAnnotation.isExcluded(member.type, state.registry.serializer.name)) continue; const nameInBson = String(state.namingStrategy.getPropertyName(member, state.registry.serializer.name)); const valueSetVar = state.compilerContext.reserveName('valueSetVar'); resetDefaultSets.push(`var ${valueSetVar} = false;`); let invalidType = ''; if (!isOptional(member) && !hasDefaultValue(member)) { invalidType = `${valid} = false`; } setDefaults.push(`if (!${valueSetVar}) { ${invalidType} } `); let seekOnExplicitUndefined = ''; //handle explicitly set `undefined`, by jumping over the registered deserializers. if `null` is given and the property has no null type, we treat it as undefined. if (isOptional(member) || hasDefaultValue(member)) { const check = isNullable(member) ? `elementType === ${BSONType.UNDEFINED}` : `elementType === ${BSONType.UNDEFINED} || elementType === ${BSONType.NULL}`; seekOnExplicitUndefined = ` if (${check}) { seekElementSize(elementType, state.parser); continue; }`; } const template = executeTemplates(state.fork(valid).extendPath(member.name), member.type); lines.push(` //property ${String(member.name)} (${member.type.kind}) else if (!${valueSetVar} && ${getNameComparator(nameInBson)}) { state.parser.offset += ${nameInBson.length} + 1; ${valueSetVar} = true; ${seekOnExplicitUndefined} ${template} if (!${valid}) break; //guards never eat/parse parser, so we jump over the value automatically seekElementSize(elementType, state.parser); continue; } `); } if (signatures.length) { const i = state.compilerContext.reserveName('i'); const signatureLines: string[] = []; sortSignatures(signatures); for (const signature of signatures) { signatureLines.push(`else if (${getIndexCheck(state, i, signature.index)}) { ${executeTemplates(state.fork(valid).extendPath(new RuntimeCode(i)).forPropertyName(new RuntimeCode(i)), signature.type)} if (!${valid}) break; //guards never eat/parse parser, so we jump over the value automatically seekElementSize(elementType, state.parser); continue; }`); } //the index signature type could be: string, number, symbol. //or a literal when it was constructed by a mapped type. lines.push(`else { let ${i} = state.parser.eatObjectPropertyName(); if (false) {} ${signatureLines.join(' ')} //if no index signature matches, we skip over it seekElementSize(elementType, state.parser); }`); } state.setContext({ seekElementSize }); state.addCode(` ${state.setter} = state.elementType && state.elementType === ${BSONType.OBJECT}; if (${state.setter}) { let ${valid} = true; const start = state.parser.offset; const end = state.parser.eatUInt32() + state.parser.offset; ${resetDefaultSets.join('\n')} const oldElementType = state.elementType; while (state.parser.offset < end) { const elementType = state.elementType = state.parser.eatByte(); if (elementType === 0) break; if (false) {} ${lines.join('\n')} //jump over this property when not registered in schema while (state.parser.offset < end && state.parser.buffer[state.parser.offset++] != 0); //seek property value if (state.parser.offset >= end) break; seekElementSize(elementType, state.parser); } ${setDefaults.join('\n')} state.elementType = oldElementType; state.parser.offset = start; ${state.setter} = ${valid}; } `); extract.setFunction(buildFunction(state, type)); } export function bsonTypeGuardForBsonTypes(types: BSONType[]): (type: Type, state: TemplateState) => void { return (type, state) => { state.addSetter(types.map(v => `state.elementType === ${v}`).join(' || ')); const decoratorTemplates = state.registry.getDecorator(type).slice(); decoratorTemplates.push(...state.registry.serializer.typeGuards.getRegistry(1).getDecorator(type)); if (decoratorTemplates.length) { const value = state.compilerContext.reserveName('value'); const decoratorState = state.fork(undefined, value); for (const template of decoratorTemplates) template(type, decoratorState); if (!decoratorState.template) return; state.addCode(` let ${value} = state.parser.read(state.elementType, ${decoratorState.compilerContext.reserveConst(type, 'type')}); ${decoratorState.template} `); } }; } export function bsonTypeGuardLiteral(type: TypeLiteral, state: TemplateState) { const literal = state.setVariable('literal', type.literal); state.addSetter(`state.parser.read(state.elementType) === ${literal}`); } export function bsonTypeGuardTemplateLiteral(type: TypeTemplateLiteral, state: TemplateState) { state.setContext({ extendTemplateLiteral: extendTemplateLiteral }); const typeVar = state.setVariable('type', type); state.addSetterAndReportErrorIfInvalid('type', 'Invalid literal', `state.elementType === ${BSONType.STRING} && extendTemplateLiteral({kind: ${ReflectionKind.literal}, literal: state.parser.read(state.elementType)}, ${typeVar})`); }
the_stack
import assert = require('assert'); import path = require('path'); import sinon = require('sinon'); import { TextDocument, TestItem, TestItemCollection, TextDocumentChangeEvent, workspace, Uri } from 'vscode'; import { GoTestExplorer } from '../../src/goTest/explore'; import { MockTestController, MockTestWorkspace } from '../mocks/MockTest'; import { forceDidOpenTextDocument, getSymbols_Regex, populateModulePathCache } from './goTest.utils'; import { MockExtensionContext } from '../mocks/MockContext'; import { MockMemento } from '../mocks/MockMemento'; import * as config from '../../src/config'; import { GoTestResolver } from '../../src/goTest/resolve'; import * as testUtils from '../../src/testUtils'; import { GoTest } from '../../src/goTest/utils'; type Files = Record<string, string | { contents: string; language: string }>; interface TestCase { workspace: string[]; files: Files; } function newExplorer<T extends GoTestExplorer>( folders: string[], files: Files, ctor: new (...args: ConstructorParameters<typeof GoTestExplorer>) => T ) { const ws = MockTestWorkspace.from(folders, files); const ctrl = new MockTestController(); const expl = new ctor(ws, ctrl, new MockMemento(), getSymbols_Regex); populateModulePathCache(ws); return { ctrl, expl, ws }; } function assertTestItems(items: TestItemCollection, expect: string[]) { const actual: string[] = []; function walk(items: TestItemCollection) { items.forEach((item) => { actual.push(item.id); walk(item.children); }); } walk(items); assert.deepStrictEqual(actual, expect); } async function forceResolve(resolver: GoTestResolver, item?: TestItem) { await resolver.resolve(item); const items: TestItem[] = []; (item?.children || resolver.items).forEach((x) => items.push(x)); await Promise.all(items.map((x) => forceResolve(resolver, x))); } suite('Go Test Explorer', () => { suite('Document opened', () => { class DUT extends GoTestExplorer { async _didOpen(doc: TextDocument) { await this.didOpenTextDocument(doc); } } interface TC extends TestCase { open: string; expect: string[]; } const cases: Record<string, TC> = { 'In workspace': { workspace: ['/src/proj'], files: { '/src/proj/go.mod': 'module test', '/src/proj/foo_test.go': 'package main\nfunc TestFoo(*testing.T) {}', '/src/proj/bar_test.go': 'package main\nfunc TestBar(*testing.T) {}', '/src/proj/baz/main_test.go': 'package main\nfunc TestBaz(*testing.T) {}' }, open: 'file:///src/proj/foo_test.go', expect: [ 'file:///src/proj?module', 'file:///src/proj/foo_test.go?file', 'file:///src/proj/foo_test.go?test#TestFoo' ] }, 'Outside workspace': { workspace: [], files: { '/src/proj/go.mod': 'module test', '/src/proj/foo_test.go': 'package main\nfunc TestFoo(*testing.T) {}' }, open: 'file:///src/proj/foo_test.go', expect: [ 'file:///src/proj?module', 'file:///src/proj/foo_test.go?file', 'file:///src/proj/foo_test.go?test#TestFoo' ] } }; for (const name in cases) { test(name, async () => { const { workspace, files, open, expect } = cases[name]; const { ctrl, expl, ws } = newExplorer(workspace, files, DUT); await expl._didOpen(ws.fs.files.get(open)); assertTestItems(ctrl.items, expect); }); } }); suite('Document edited', async () => { class DUT extends GoTestExplorer { async _didOpen(doc: TextDocument) { await this.didOpenTextDocument(doc); } async _didChange(e: TextDocumentChangeEvent) { await this.didChangeTextDocument(e); } } interface TC extends TestCase { open: string; changes: [string, string][]; expect: { before: string[]; after: string[]; }; } const cases: Record<string, TC> = { 'Add test': { workspace: ['/src/proj'], files: { '/src/proj/go.mod': 'module test', '/src/proj/foo_test.go': 'package main' }, open: 'file:///src/proj/foo_test.go', changes: [['file:///src/proj/foo_test.go', 'package main\nfunc TestFoo(*testing.T) {}']], expect: { before: ['file:///src/proj?module'], after: [ 'file:///src/proj?module', 'file:///src/proj/foo_test.go?file', 'file:///src/proj/foo_test.go?test#TestFoo' ] } }, 'Remove test': { workspace: ['/src/proj'], files: { '/src/proj/go.mod': 'module test', '/src/proj/foo_test.go': 'package main\nfunc TestFoo(*testing.T) {}' }, open: 'file:///src/proj/foo_test.go', changes: [['file:///src/proj/foo_test.go', 'package main']], expect: { before: [ 'file:///src/proj?module', 'file:///src/proj/foo_test.go?file', 'file:///src/proj/foo_test.go?test#TestFoo' ], after: ['file:///src/proj?module'] } } }; for (const name in cases) { test(name, async () => { const { workspace, files, open, changes, expect } = cases[name]; const { ctrl, expl, ws } = newExplorer(workspace, files, DUT); await expl._didOpen(ws.fs.files.get(open)); assertTestItems(ctrl.items, expect.before); for (const [file, contents] of changes) { const doc = ws.fs.files.get(file); doc.contents = contents; await expl._didChange({ document: doc, contentChanges: [] }); } assertTestItems(ctrl.items, expect.after); }); } }); suite('stretchr', () => { const fixtureDir = path.join(__dirname, '..', '..', '..', 'test', 'testdata', 'stretchrTestSuite'); const ctx = MockExtensionContext.new(); let document: TextDocument; let testExplorer: GoTestExplorer; suiteSetup(async () => { testExplorer = GoTestExplorer.setup(ctx); const uri = Uri.file(path.join(fixtureDir, 'suite_test.go')); document = await forceDidOpenTextDocument(workspace, testExplorer, uri); }); suiteTeardown(() => { ctx.teardown(); }); test('discovery', () => { const tests = testExplorer.resolver.find(document.uri).map((x) => x.id); assert.deepStrictEqual(tests.sort(), [ document.uri.with({ query: 'file' }).toString(), document.uri.with({ query: 'test', fragment: '(*ExampleTestSuite).TestExample' }).toString(), document.uri.with({ query: 'test', fragment: 'TestExampleTestSuite' }).toString() ]); }); }); suite('settings', () => { const sandbox = sinon.createSandbox(); // eslint-disable-next-line @typescript-eslint/no-explicit-any let goConfig: any; setup(() => { goConfig = Object.create(config.getGoConfig()); sandbox.stub(config, 'getGoConfig').returns(goConfig); }); teardown(() => { sandbox.restore(); }); suite('packageDisplayMode', () => { let resolver: GoTestResolver; setup(() => { const { expl } = newExplorer( ['/src/proj'], { '/src/proj/go.mod': 'module test', '/src/proj/pkg/main_test.go': 'package main\nfunc TestFoo(t *testing.T) {}', '/src/proj/pkg/sub/main_test.go': 'package main\nfunc TestBar(t *testing.T) {}' }, GoTestExplorer ); resolver = expl.resolver; }); test('flat', async () => { // Expect: // - module // - package pkg // - package pkg/sub sinon.stub(goConfig, 'get').withArgs('testExplorer.packageDisplayMode').returns('flat'); await forceResolve(resolver); const mod = resolver.items.get('file:///src/proj?module'); assert(mod, 'Module is missing or is not at the root'); const pkg = mod.children.get('file:///src/proj/pkg?package'); assert(pkg, 'Package pkg is missing or not a child of the module'); const sub = mod.children.get('file:///src/proj/pkg/sub?package'); assert(sub, 'Package pkg/sub is missing or not a child of the module'); }); test('nested', async () => { // Expect: // - module // - package pkg // - package pkg/sub sinon.stub(goConfig, 'get').withArgs('testExplorer.packageDisplayMode').returns('nested'); await forceResolve(resolver); const mod = resolver.items.get('file:///src/proj?module'); assert(mod, 'Module is missing or is not at the root'); const pkg = mod.children.get('file:///src/proj/pkg?package'); assert(pkg, 'Package pkg is missing or not a child of the module'); const sub = pkg.children.get('file:///src/proj/pkg/sub?package'); assert(sub, 'Package pkg/sub is missing or not a child of package pkg'); }); }); suite('alwaysRunBenchmarks', () => { let explorer: GoTestExplorer; let runStub: sinon.SinonStub<[testUtils.TestConfig], Promise<boolean>>; const expectedTests = [ 'file:///src/proj/pkg/main_test.go?file', 'file:///src/proj/pkg/main_test.go?test#TestFoo', 'file:///src/proj/pkg/main_test.go?benchmark#BenchmarkBar' ]; setup(() => { runStub = sandbox.stub(testUtils, 'goTest'); runStub.callsFake(() => Promise.resolve(true)); explorer = newExplorer( ['/src/proj'], { '/src/proj/go.mod': 'module test', '/src/proj/pkg/main_test.go': ` package main func TestFoo(t *testing.T) {} func BenchmarkBar(b *testing.B) {} ` }, GoTestExplorer ).expl; }); test('false', async () => { // Running the file should only run the test sinon.stub(goConfig, 'get').withArgs('testExplorer.alwaysRunBenchmarks').returns(false); await forceResolve(explorer.resolver); const tests = explorer.resolver.find(Uri.parse('file:///src/proj/pkg/main_test.go')); assert.deepStrictEqual( tests.map((x) => x.id), expectedTests ); await explorer.runner.run({ include: [tests[0]] }); assert.strictEqual(runStub.callCount, 1, 'Expected goTest to be called once'); assert.deepStrictEqual(runStub.lastCall.args[0].functions, ['TestFoo']); }); test('true', async () => { // Running the file should run the test and the benchmark sinon.stub(goConfig, 'get').withArgs('testExplorer.alwaysRunBenchmarks').returns(true); await forceResolve(explorer.resolver); const tests = explorer.resolver.find(Uri.parse('file:///src/proj/pkg/main_test.go')); assert.deepStrictEqual( tests.map((x) => x.id), expectedTests ); await explorer.runner.run({ include: [tests[0]] }); assert.strictEqual(runStub.callCount, 2, 'Expected goTest to be called twice'); assert.deepStrictEqual(runStub.firstCall.args[0].functions, ['TestFoo']); assert.deepStrictEqual(runStub.secondCall.args[0].functions, ['BenchmarkBar']); }); }); suite('showDynamicSubtestsInEditor', () => { let explorer: GoTestExplorer; let runStub: sinon.SinonStub<[testUtils.TestConfig], Promise<boolean>>; setup(() => { runStub = sandbox.stub(testUtils, 'goTest'); runStub.callsFake((cfg) => { // Trigger creation of dynamic subtest cfg.goTestOutputConsumer({ Test: 'TestFoo/Bar', Action: 'run' }); return Promise.resolve(true); }); explorer = newExplorer( ['/src/proj'], { '/src/proj/go.mod': 'module test', '/src/proj/main_test.go': 'package main\nfunc TestFoo(t *testing.T) {}' }, GoTestExplorer ).expl; }); test('false', async () => { // Dynamic subtests should have no location sinon.stub(goConfig, 'get').withArgs('testExplorer.showDynamicSubtestsInEditor').returns(false); await forceResolve(explorer.resolver); const test = explorer.resolver .find(Uri.parse('file:///src/proj/main_test.go')) .filter((x) => GoTest.parseId(x.id).name)[0]; assert(test, 'Could not find test'); await explorer.runner.run({ include: [test] }); assert.strictEqual(runStub.callCount, 1, 'Expected goTest to be called once'); const subTest = test.children.get('file:///src/proj/main_test.go?test#TestFoo%2FBar'); assert(subTest, 'Could not find subtest'); assert(!subTest.range, 'Subtest should not have a range'); }); test('true', async () => { // Dynamic subtests should have the same location as their parents sinon.stub(goConfig, 'get').withArgs('testExplorer.showDynamicSubtestsInEditor').returns(true); await forceResolve(explorer.resolver); const test = explorer.resolver .find(Uri.parse('file:///src/proj/main_test.go')) .filter((x) => GoTest.parseId(x.id).name)[0]; assert(test, 'Could not find test'); await explorer.runner.run({ include: [test] }); assert.strictEqual(runStub.callCount, 1, 'Expected goTest to be called once'); const subTest = test.children.get('file:///src/proj/main_test.go?test#TestFoo%2FBar'); assert(subTest, 'Could not find subtest'); assert.deepStrictEqual(subTest.range, test.range, 'Subtest range should match parent range'); }); }); }); });
the_stack
import * as path from 'path' import { Emitter, Disposable, CompositeDisposable, Grammar, Range } from 'atom' import { debounce } from 'lodash' import * as fs from 'fs' import { remote } from 'electron' import * as renderer from '../renderer' import { MarkdownItWorker } from '../markdown-it-helper' import { handlePromise, copyHtml, atomConfig, shellOpen } from '../util' import * as util from './util' import { WebviewHandler } from './webview-handler' import { saveAsPDF } from './pdf-export-util' import { loadUserMacros } from '../macros-util' import { WebContentsHandler } from './web-contents-handler' import { modalTextEditorView } from '../modal-text-editor-view' import { BrowserWindowHandler } from './browserwindow-handler' import { MarkdownPreviewController, MarkdownPreviewControllerEditor, MarkdownPreviewControllerFile, MarkdownPreviewControllerText, SerializedMPV, } from './controller' import { openPreviewPane } from './helpers' import * as clipboard from '../clipboard' import { pathToFileURL } from 'url' export type { SerializedMPV } export class MarkdownPreviewView { private static elementMap = new WeakMap<HTMLElement, MarkdownPreviewView>() // used for tests public get type() { return this.controller.type } public readonly element: HTMLElement protected emitter: Emitter<{ 'did-change-title': undefined 'did-change-markdown': undefined 'did-init': undefined 'did-destroy': undefined }> = new Emitter() protected disposables = new CompositeDisposable() protected controllerDisposables?: CompositeDisposable protected destroyed = false protected readonly handler: WebContentsHandler private loading: boolean = true private _initialRenderPromsie: Promise<void> constructor( private controller: MarkdownPreviewController, private renderLaTeX: boolean = atomConfig().mathConfig .enableLatexRenderingByDefault, handlerConstructor: new ( clientStyle: util.ClientStyle, x: () => Promise<void>, ) => WebContentsHandler = WebviewHandler, ) { this.disposables.add(this.emitter) const config = atomConfig() this.handler = new handlerConstructor(config.style, async () => { await this.handler.init({ userMacros: loadUserMacros(), mathJaxConfig: config.mathConfig, context: 'live-preview', }) await this.handler.setBasePath(this.getPath()) await this.handler.setNativeKeys( config.previewConfig.nativePageScrollKeys, ) this.emitter.emit('did-change-title') this.emitter.emit('did-init') }) this.disposables.add( atom.config.onDidChange('markdown-preview-plus.style', (val) => { handlePromise(this.handler.setClientStyle(val.newValue)) }), ) this.element = document.createElement('div') this.element.tabIndex = -1 this.element.classList.add('markdown-preview-plus') MarkdownPreviewView.elementMap.set(this.element, this) this.subscribeController() this._initialRenderPromsie = new Promise((resolve) => { this.disposables.add( this.emitter.on('did-init', () => { handlePromise( this.renderMarkdown().then(() => { this.loading = false resolve() }), ) }), ) }) if (this.handler.element) this.element.appendChild(this.handler.element) this.handler.registerViewEvents(this) this.disposables.add(this.handler.onDidDestroy(() => this.destroy())) this.handleEvents() } public static viewForElement(element: HTMLElement) { return MarkdownPreviewView.elementMap.get(element) } public serialize(): SerializedMPV { return this.controller.serialize() } public destroy() { if (this.destroyed) return this.destroyed = true this.emitter.emit('did-destroy') this.disposables.dispose() this.controller.destroy() this.handler.destroy() MarkdownPreviewView.elementMap.delete(this.element) this.element.remove() } public onDidDestroy(callback: () => void) { return this.emitter.on('did-destroy', callback) } public async runJS<T>(js: string) { return this.handler.runJS<T>(js) } public async initialRenderPromise() { await this._initialRenderPromsie } public onDidChangeTitle(callback: () => void): Disposable { return this.emitter.on('did-change-title', callback) } public onDidChangeMarkdown(callback: () => void): Disposable { return this.emitter.on('did-change-markdown', callback) } public toggleRenderLatex() { this.renderLaTeX = !this.renderLaTeX this.changeHandler() } public getTitle(): string { return this.controller.getTitle() } public getDefaultLocation(): 'left' | 'right' | 'bottom' | 'center' { return atomConfig().previewConfig.previewDock } public getIconName() { return 'markdown' } public getURI(): string { return this.controller.getURI() } public getPath(): string | undefined { return this.controller.getPath() } public getSaveDialogOptions() { let defaultPath = this.getPath() if (defaultPath === undefined) { const projectPath = atom.project.getPaths()[0] defaultPath = 'untitled.md' if (projectPath) { defaultPath = path.join(projectPath, defaultPath) } } defaultPath += '.' + atomConfig().saveConfig.defaultSaveFormat return { defaultPath } } public saveAs(filePath: string | undefined) { if (filePath === undefined) return if (this.loading) throw new Error('Preview is still loading') const { name, ext } = path.parse(filePath) const config = atomConfig() if (ext === '.pdf') { handlePromise( this.getMarkdownSource().then(async (mdSource) => { await saveAsPDF( mdSource, this.getPath(), this.getGrammar(), this.renderLaTeX, filePath, ) if (config.saveConfig.openOnSave.pdf) { return shellOpen(pathToFileURL(filePath).toString()) } else return }), ) } else { const style = config.style handlePromise( this.getHTMLToSave(filePath).then(async (html) => { const fullHtml = util.mkHtml( name, html, this.renderLaTeX, await this.handler.getTeXConfig(), style, ) fs.writeFileSync(filePath, fullHtml) if (config.saveConfig.openOnSave.html) { return atom.workspace.open(filePath) } else return undefined }), ) } } public openMainWindow(): void { const ctrl = this.createNewFromThis(WebviewHandler) handlePromise(openPreviewPane(ctrl)) util.destroy(this) } protected openNewWindow(): void { const ctrl = this.createNewFromThis(BrowserWindowHandler) atom.views.getView(atom.workspace).appendChild(ctrl.element) util.destroy(this) } protected createNewFromThis( handler: new ( clientStyle: util.ClientStyle, x: () => Promise<void>, ) => WebContentsHandler, ) { const curController = this.controller // this will get destroyed shortly, but we create it for consistency this.controller = new MarkdownPreviewControllerText( this.getMarkdownSource(), ) this.subscribeController() return new MarkdownPreviewView(curController, this.renderLaTeX, handler) } protected changeHandler = () => { handlePromise(this.renderMarkdown()) const pane = atom.workspace.paneForItem(this) if (pane !== undefined && pane !== atom.workspace.getActivePane()) { pane.activateItem(this) } } protected async getMarkdownSource(): Promise<string> { return this.controller.getMarkdownSource() } protected getGrammar(): Grammar | undefined { return this.controller.getGrammar() } protected async openSource(initialLine?: number) { const path = this.getPath() if (path === undefined) return undefined const ed = await atom.workspace.open(path, { initialLine, searchAllPanes: true, }) if (!atom.workspace.isTextEditor(ed)) return undefined if (this.controller.type !== 'editor') { this.controller.destroy() this.controller = new MarkdownPreviewControllerEditor(ed) this.subscribeController() } return ed } protected async syncPreview(line: number, flash: boolean) { return this.handler.sync(line, flash) } private handleEvents() { this.disposables.add( // atom events atom.grammars.onDidAddGrammar(() => debounce(() => { handlePromise(this.renderMarkdown()) }, 250), ), atom.grammars.onDidUpdateGrammar( debounce(() => { handlePromise(this.renderMarkdown()) }, 250), ), atom.commands.add(this.element, { 'core:move-up': () => this.handler.runJS('window.scrollBy({top:-30, behavior: "auto"})'), 'core:move-down': () => this.handler.runJS('window.scrollBy({top:30, behavior: "auto"})'), 'core:move-left': () => this.handler.runJS('window.scrollBy({left:-30, behavior: "auto"})'), 'core:move-right': () => this.handler.runJS('window.scrollBy({left:-30, behavior: "auto"})'), 'core:page-up': () => this.handler.runJS( 'window.scrollBy({top:-0.9*window.innerHeight, behavior: "auto"})', ), 'core:page-down': () => this.handler.runJS( 'window.scrollBy({top:0.9*window.innerHeight, behavior: "auto"})', ), 'core:move-to-top': () => this.handler.runJS( 'window.scrollBy({top:-document.body.scrollHeight, behavior: "smooth"})', ), 'core:move-to-bottom': () => this.handler.runJS( 'window.scrollBy({top:document.body.scrollHeight, behavior: "smooth"})', ), 'core:cancel': (evt) => { if (this.handler.hasSearch()) handlePromise(this.handler.stopSearch()) else evt.abortKeyBinding() }, 'core:copy': () => { handlePromise(this.copyToClipboard()) }, 'markdown-preview-plus:open-dev-tools': () => { handlePromise(this.handler.openDevTools()) }, 'markdown-preview-plus:new-window': () => { this.openNewWindow() }, 'markdown-preview-plus:print': () => { handlePromise(this.handler.print()) }, 'markdown-preview-plus:zoom-in': () => { handlePromise(this.handler.zoomIn()) }, 'markdown-preview-plus:zoom-out': () => { handlePromise(this.handler.zoomOut()) }, 'markdown-preview-plus:reset-zoom': () => { handlePromise(this.handler.resetZoom()) }, 'markdown-preview-plus:sync-source': (_event) => { handlePromise( this.handler.syncSource().then((line) => this.openSource(line)), ) }, 'markdown-preview-plus:search-selection-in-source': () => { handlePromise(this.searchSelectionInSource()) }, 'markdown-preview-plus:find-next': () => { handlePromise(this.handler.findNext()) }, 'markdown-preview-plus:find-in-preview': () => { const cw = remote.getCurrentWindow() const fw = remote.BrowserWindow.getFocusedWindow() if (fw !== cw) cw.focus() handlePromise( modalTextEditorView('Find in preview').then((text) => { if (fw && fw !== cw) fw.focus() if (!text) return undefined return this.handler.search(text) }), ) }, }), atom.config.onDidChange('markdown-preview-plus.markdownItConfig', () => { if (atomConfig().renderer === 'markdown-it') this.changeHandler() }), atom.config.onDidChange('markdown-preview-plus.pandocConfig', () => { if (atomConfig().renderer === 'pandoc') this.changeHandler() }), atom.config.onDidChange( 'markdown-preview-plus.mathConfig.latexRenderer', () => handlePromise(this.handler.reload()), ), atom.config.onDidChange( 'markdown-preview-plus.mathConfig.numberEquations', () => handlePromise(this.handler.reload()), ), atom.config.onDidChange( 'markdown-preview-plus.previewConfig.nativePageScrollKeys', ({ newValue }) => handlePromise(this.handler.setNativeKeys(newValue)), ), atom.config.onDidChange( 'markdown-preview-plus.renderer', this.changeHandler, ), atom.config.onDidChange( 'markdown-preview-plus.previewConfig.highlighter', this.changeHandler, ), // webview events this.handler.emitter.on('did-scroll-preview', ({ min, max }) => { this.controller.didScrollPreview(min, max) }), ) } private async renderMarkdown(): Promise<void> { return this.renderMarkdownText(await this.getMarkdownSource()) } private async getHTMLToSave(savePath: string) { const source = await this.getMarkdownSource() return renderer.render({ text: source, filePath: this.getPath(), grammar: this.getGrammar(), renderLaTeX: this.renderLaTeX, renderErrors: false, mode: 'save', savePath, }) } private async renderMarkdownText(text: string): Promise<void> { try { const domDocument = await renderer.render({ text, filePath: this.getPath(), grammar: this.getGrammar(), renderLaTeX: this.renderLaTeX, renderErrors: true, mode: 'normal', imageWatcher: this.handler.imageWatcher, }) if (this.destroyed) return const config = atomConfig() await this.handler.update( domDocument.documentElement!.outerHTML, this.renderLaTeX, config.previewConfig.diffMethod, util.buildLineMap( domDocument.querySelector('[data-pos]') ? domDocument : await MarkdownItWorker.getTokens(text, this.renderLaTeX), ), config.syncConfig.syncPreviewOnEditorScroll ? this.controller.getScrollSyncParams() : undefined, ) this.emitter.emit('did-change-markdown') } catch (error) { await this.showError(error as Error) } } private async showError(error: Error) { if (this.destroyed) { atom.notifications.addFatalError( 'Error reported on a destroyed Markdown Preview Plus view', { dismissable: true, stack: error.stack, detail: error.message, }, ) return } else if (this.loading) { atom.notifications.addFatalError( 'Error reported when Markdown Preview Plus view is loading', { dismissable: true, stack: error.stack, detail: error.message, }, ) return } else { return this.handler.error(error.message) } } private async copyToClipboard(): Promise<void> { const selection = await this.handler.getSelection() // Use stupid copy event handler if there is selected text inside this view if (selection !== undefined) { if (atom.config.get('markdown-preview-plus.richClipboard')) { await this.handler.runJS('document.execCommand("copy")') } else { clipboard.writePlain(selection) } } else { const src = await this.getMarkdownSource() await copyHtml(src, this.getPath(), this.renderLaTeX, atomConfig().style) } } private async searchSelectionInSource() { const text = await this.handler.getSelection() if (!text) return const editor = await this.openSource() if (!editor) return const rxs = text .replace(/[\/\\^$*+?.()|[\]{}]/g, '\\$&') .replace(/\n+$/, '') .replace(/\s+/g, '\\s+') const rx = new RegExp(rxs) let found = false editor.scanInBufferRange( rx, new Range( editor.getCursors()[0].getBufferPosition(), editor.getBuffer().getRange().end, ), (it) => { editor.scrollToBufferPosition(it.range.start) editor.setSelectedBufferRange(it.range) found = true it.stop() }, ) if (found) return editor.scan(rx, (it) => { editor.scrollToBufferPosition(it.range.start) editor.setSelectedBufferRange(it.range) it.stop() }) } private subscribeController() { if (this.controllerDisposables) { this.disposables.remove(this.controllerDisposables) this.controllerDisposables.dispose() } this.controllerDisposables = new CompositeDisposable() this.disposables.add(this.controllerDisposables) this.controllerDisposables.add( this.controller.onDidChange(this.changeHandler), this.controller.onDidChangePath((path) => { handlePromise(this.handler.setBasePath(path)) this.emitter.emit('did-change-title') }), this.controller.onDidDestroy(() => { if (atomConfig().previewConfig.closePreviewWithEditor) { util.destroy(this) } else { const path = this.controller.getPath() if (path) { this.controller = new MarkdownPreviewControllerFile(path) } else { this.controller = new MarkdownPreviewControllerText( this.controller.getMarkdownSource(), ) } this.subscribeController() } }), this.controller.onActivate((edPane) => { const pane = atom.workspace.paneForItem(this) if (!pane) return if (pane === edPane) return pane.activateItem(this) }), this.controller.onScrollSync(({ firstLine, lastLine }) => { handlePromise(this.handler.scrollSync(firstLine, lastLine)) }), this.controller.onSearch((text) => { handlePromise(this.handler.search(text)) }), this.controller.onSync(([pos, flash]) => { handlePromise(this.syncPreview(pos, flash)) }), ) } }
the_stack
import * as vscode from 'vscode'; import * as fs from 'fs'; import * as path from 'path'; import crypto from 'crypto'; import { IBucket, IObject, IResumableUploadRange, DataRetentionPolicy } from 'forge-server-utils'; import { IContext, promptBucket, promptObject, showErrorMessage } from '../common'; const RetentionPolicyKeys = ['transient', 'temporary', 'persistent']; const AllowedMimeTypes = { 'a': 'application/octet-stream', 'ai': 'application/postscript', 'aif': 'audio/x-aiff', 'aifc': 'audio/x-aiff', 'aiff': 'audio/x-aiff', 'au': 'audio/basic', 'avi': 'video/x-msvideo', 'bat': 'text/plain', 'bin': 'application/octet-stream', 'bmp': 'image/x-ms-bmp', 'c': 'text/plain', 'cdf': 'application/x-cdf', 'csh': 'application/x-csh', 'css': 'text/css', 'dll': 'application/octet-stream', 'doc': 'application/msword', 'dot': 'application/msword', 'dvi': 'application/x-dvi', 'eml': 'message/rfc822', 'eps': 'application/postscript', 'etx': 'text/x-setext', 'exe': 'application/octet-stream', 'gif': 'image/gif', 'gtar': 'application/x-gtar', 'h': 'text/plain', 'hdf': 'application/x-hdf', 'htm': 'text/html', 'html': 'text/html', 'jpe': 'image/jpeg', 'jpeg': 'image/jpeg', 'jpg': 'image/jpeg', 'js': 'application/x-javascript', 'ksh': 'text/plain', 'latex': 'application/x-latex', 'm1v': 'video/mpeg', 'man': 'application/x-troff-man', 'me': 'application/x-troff-me', 'mht': 'message/rfc822', 'mhtml': 'message/rfc822', 'mif': 'application/x-mif', 'mov': 'video/quicktime', 'movie': 'video/x-sgi-movie', 'mp2': 'audio/mpeg', 'mp3': 'audio/mpeg', 'mp4': 'video/mp4', 'mpa': 'video/mpeg', 'mpe': 'video/mpeg', 'mpeg': 'video/mpeg', 'mpg': 'video/mpeg', 'ms': 'application/x-troff-ms', 'nc': 'application/x-netcdf', 'nws': 'message/rfc822', 'o': 'application/octet-stream', 'obj': 'application/octet-stream', 'oda': 'application/oda', 'pbm': 'image/x-portable-bitmap', 'pdf': 'application/pdf', 'pfx': 'application/x-pkcs12', 'pgm': 'image/x-portable-graymap', 'png': 'image/png', 'pnm': 'image/x-portable-anymap', 'pot': 'application/vnd.ms-powerpoint', 'ppa': 'application/vnd.ms-powerpoint', 'ppm': 'image/x-portable-pixmap', 'pps': 'application/vnd.ms-powerpoint', 'ppt': 'application/vnd.ms-powerpoint', 'pptx': 'application/vnd.ms-powerpoint', 'ps': 'application/postscript', 'pwz': 'application/vnd.ms-powerpoint', 'py': 'text/x-python', 'pyc': 'application/x-python-code', 'pyo': 'application/x-python-code', 'qt': 'video/quicktime', 'ra': 'audio/x-pn-realaudio', 'ram': 'application/x-pn-realaudio', 'ras': 'image/x-cmu-raster', 'rdf': 'application/xml', 'rgb': 'image/x-rgb', 'roff': 'application/x-troff', 'rtx': 'text/richtext', 'sgm': 'text/x-sgml', 'sgml': 'text/x-sgml', 'sh': 'application/x-sh', 'shar': 'application/x-shar', 'snd': 'audio/basic', 'so': 'application/octet-stream', 'src': 'application/x-wais-source', 'swf': 'application/x-shockwave-flash', 't': 'application/x-troff', 'tar': 'application/x-tar', 'tcl': 'application/x-tcl', 'tex': 'application/x-tex', 'texi': 'application/x-texinfo', 'texinfo': 'application/x-texinfo', 'tif': 'image/tiff', 'tiff': 'image/tiff', 'tr': 'application/x-troff', 'tsv': 'text/tab-separated-values', 'txt': 'text/plain', 'ustar': 'application/x-ustar', 'vcf': 'text/x-vcard', 'wav': 'audio/x-wav', 'wiz': 'application/msword', 'wsdl': 'application/xml', 'xbm': 'image/x-xbitmap', 'xlb': 'application/vnd.ms-excel', 'xls': 'application/vnd.ms-excel', 'xlsx': 'application/vnd.ms-excel', 'xml': 'text/xml', 'xpdl': 'application/xml', 'xpm': 'image/x-xpixmap', 'xsl': 'application/xml', 'xwd': 'image/x-xwindowdump', 'zip': 'application/zip' }; const DeleteBatchSize = 8; function computeFileHash(bucketKey: string, objectKey: string, filename: string): Promise<string> { return new Promise(function(resolve, reject) { const stream = fs.createReadStream(filename); let hash = crypto.createHash('md5'); hash.update(bucketKey); hash.update(objectKey); stream.on('data', function(chunk) { hash.update(chunk); }); stream.on('end', function() { resolve(hash.digest('hex')); }); stream.on('error', function(err) { reject(err); }); }); } export async function createBucket(context: IContext) { const name = await vscode.window.showInputBox({ prompt: 'Enter unique bucket name' }); if (!name) { return; } const retention = await vscode.window.showQuickPick(RetentionPolicyKeys, { placeHolder: 'Select retention policy' }); if (!retention) { return; } try { await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Creating bucket: ${name}`, cancellable: false }, async (progress, token) => { const bucket = await context.dataManagementClient.createBucket(name, <DataRetentionPolicy>retention); }); vscode.window.showInformationMessage(`Bucket created: ${name}`); } catch (err) { showErrorMessage('Could not create bucket', err); } } export async function viewBucketDetails(bucket: IBucket | undefined, context: IContext) { try { if (!bucket) { bucket = await promptBucket(context); if (!bucket) { return; } } const { bucketKey } = bucket; await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Getting bucket details: ${bucketKey}`, cancellable: false }, async (progress, token) => { const bucketDetail = await context.dataManagementClient.getBucketDetails(bucketKey); const panel = vscode.window.createWebviewPanel( 'bucket-details', `Details: ${bucketKey}`, vscode.ViewColumn.One, { enableScripts: false, retainContextWhenHidden: true } ); panel.webview.html = context.templateEngine.render('bucket-details', { bucket: bucketDetail }); }); } catch(err) { showErrorMessage('Could not access bucket', err); } } export async function uploadObject(bucket: IBucket | undefined, context: IContext) { const chunkBytes = vscode.workspace.getConfiguration(undefined, null).get<number>('autodesk.forge.data.uploadChunkSize') || (2 << 20); async function _upload(name: string, uri: vscode.Uri, context: IContext, bucketKey: string, contentType?: string) { const filepath = uri.fsPath; const hash = await computeFileHash(bucketKey, name, filepath); const stateKey = `upload:${hash}`; let fd = -1; try { fd = fs.openSync(filepath, 'r'); const totalBytes = fs.statSync(filepath).size; const buff = Buffer.alloc(chunkBytes); let lastByte = 0; let cancelled = false; await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Uploading file: ${filepath}`, cancellable: true }, async (progress, token) => { token.onCancellationRequested(() => { cancelled = true; }); progress.report({ increment: 0 }); // Check if any parts of the file have already been uploaded let uploadSessionID = context.extensionContext.globalState.get<string>(stateKey); if (!uploadSessionID) { uploadSessionID = crypto.randomBytes(8).toString('hex'); context.extensionContext.globalState.update(stateKey, uploadSessionID); } let ranges: IResumableUploadRange[]; try { ranges = await context.dataManagementClient.getResumableUploadStatus(bucketKey, name, uploadSessionID); } catch (err) { ranges = []; } // Upload potential missing data before each successfully uploaded range for (const range of ranges) { if (cancelled) { return; } while (lastByte < range.start) { if (cancelled) { return; } const chunkSize = Math.min(range.start - lastByte, chunkBytes); fs.readSync(fd, buff, 0, chunkSize, lastByte); await context.dataManagementClient.uploadObjectResumable(bucketKey, name, buff.slice(0, chunkSize), lastByte, totalBytes, uploadSessionID, contentType); progress.report({ increment: 100 * chunkSize / totalBytes }); lastByte += chunkSize; } progress.report({ increment: 100 * (range.end + 1 - lastByte) / totalBytes }); lastByte = range.end + 1; } // Upload potential missing data after the last successfully uploaded range while (lastByte < totalBytes - 1) { if (cancelled) { return; } const chunkSize = Math.min(totalBytes - lastByte, chunkBytes); fs.readSync(fd, buff, 0, chunkSize, lastByte); await context.dataManagementClient.uploadObjectResumable(bucketKey, name, buff.slice(0, chunkSize), lastByte, totalBytes, uploadSessionID, contentType); progress.report({ increment: 100 * chunkSize / totalBytes }); lastByte += chunkSize; } }); if (cancelled) { vscode.window.showInformationMessage(`Upload cancelled: ${filepath}`); } else { // Clear the resumable upload session info context.extensionContext.globalState.update(stateKey, null); const res = await vscode.window.showInformationMessage(`Upload complete: ${filepath}`, 'Translate', 'Translate (Custom)'); if (res === 'Translate') { const obj = await context.dataManagementClient.getObjectDetails(bucketKey, name); vscode.commands.executeCommand('forge.translateObject', obj); } else if (res === 'Translate (Custom)') { const obj = await context.dataManagementClient.getObjectDetails(bucketKey, name); vscode.commands.executeCommand('forge.translateObjectCustom', obj); } } } catch (err) { showErrorMessage('Could not upload file', err); } finally { if (fd !== -1) { fs.closeSync(fd); fd = -1; } } } if (!bucket) { bucket = await promptBucket(context); if (!bucket) { return; } } const { bucketKey } = bucket; // Collect inputs const uris = await vscode.window.showOpenDialog({ canSelectFiles: true, canSelectFolders: false, canSelectMany: true }); if (!uris) { return; } if (uris.length === 1) { const name = await vscode.window.showInputBox({ prompt: 'Enter object name', value: path.basename(uris[0].fsPath) }); if (!name) { return; } // Warn users against uploading files without extension (which is needed by Model Derivative service) if (!path.extname(name)) { await vscode.window.showWarningMessage('Objects with no file extension in their name cannot be translated by Model Derivative service.'); } // Pick the content type for the uploaded file let contentType = vscode.workspace.getConfiguration(undefined, null).get<string>('autodesk.forge.data.defaultContentType'); if (!contentType) { contentType = await vscode.window.showQuickPick(Object.values(AllowedMimeTypes), { canPickMany: false, placeHolder: 'Select content type' }); } if (!contentType) { return; } await _upload(name, uris[0], context, bucketKey, contentType); } else { const uploads = uris.map(uri => _upload(path.basename(uri.fsPath), uri, context, bucketKey)); await Promise.all(uploads); } } export async function createEmptyObject(bucket: IBucket | undefined, context: IContext) { if (!bucket) { bucket = await promptBucket(context); if (!bucket) { return; } } const { bucketKey } = bucket; const name = await vscode.window.showInputBox({ prompt: 'Enter object name' }); if (!name) { return; } let contentType = vscode.workspace.getConfiguration(undefined, null).get<string>('autodesk.forge.data.defaultContentType'); if (!contentType) { contentType = await vscode.window.showQuickPick(Object.values(AllowedMimeTypes), { canPickMany: false, placeHolder: 'Select content type' }); } if (!contentType) { return; } try { const obj = await context.dataManagementClient.uploadObject(bucketKey, name, contentType, Buffer.from([])); vscode.window.showInformationMessage(`Object created: ${obj.objectId}`); } catch(err) { showErrorMessage('Could not create file', err); } } export async function downloadObject(object: IObject | undefined, context: IContext) { if (!object) { const bucket = await promptBucket(context); if (!bucket) { return; } object = await promptObject(context, bucket.bucketKey); if (!object) { return; } } const { objectKey, bucketKey } = object; const uri = await vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file(objectKey) }); if (!uri) { return; } try { await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Downloading file: ${uri.fsPath}`, cancellable: false }, async (progress, token) => { const arrayBuffer = await context.dataManagementClient.downloadObject(bucketKey, objectKey); fs.writeFileSync(uri.fsPath, Buffer.from(arrayBuffer), { encoding: 'binary' }); }); const action = await vscode.window.showInformationMessage(`Download complete: ${uri.fsPath}`, 'Open File'); if (action === 'Open File') { vscode.env.openExternal(uri); } } catch(err) { showErrorMessage('Could not download file', err); } } export async function viewObjectDetails(object: IObject | undefined, context: IContext) { try { if (!object) { const bucket = await promptBucket(context); if (!bucket) { return; } object = await promptObject(context, bucket.bucketKey); if (!object) { return; } } const panel = vscode.window.createWebviewPanel( 'object-details', 'Details: ' + object.objectKey, vscode.ViewColumn.One, { enableScripts: true, retainContextWhenHidden: true } ); panel.webview.html = context.templateEngine.render('object-details', { object }); } catch(err) { showErrorMessage('Could not access object', err); } } export async function copyObject(object: IObject | undefined, context: IContext) { try { if (!object) { const bucket = await promptBucket(context); if (!bucket) { return; } object = await promptObject(context, bucket.bucketKey); if (!object) { return; } } const newObjectKey = await vscode.window.showInputBox({ prompt: 'Enter new object name' }); if (!newObjectKey) { return; } const { bucketKey, objectKey } = object; await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Copying file: ${object.objectKey}`, cancellable: false }, async (progress, token) => { await context.dataManagementClient.copyObject(bucketKey, objectKey, newObjectKey); }); vscode.window.showInformationMessage(`Object copy created: ${newObjectKey}`); } catch(err) { showErrorMessage('Could not copy object', err); } } export async function renameObject(object: IObject | undefined, context: IContext) { try { if (!object) { const bucket = await promptBucket(context); if (!bucket) { return; } object = await promptObject(context, bucket.bucketKey); if (!object) { return; } } const newObjectKey = await vscode.window.showInputBox({ prompt: 'Enter new object name' }); if (!newObjectKey) { return; } const { bucketKey, objectKey } = object; await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Renaming file: ${object.objectKey}`, cancellable: false }, async (progress, token) => { await context.dataManagementClient.copyObject(bucketKey, objectKey, newObjectKey); await context.dataManagementClient.deleteObject(bucketKey, objectKey); }); vscode.window.showInformationMessage(` Object successfully renamed to ${newObjectKey}. Note that any derivatives created for the object's original name will not be accesible now but they still exist. You can either start another conversion job for this object with its new name, or rename the object back to ${object.objectKey} to regain access to the derivatives. `); } catch(err) { showErrorMessage('Could not rename object', err); } } export async function deleteObject(object: IObject | undefined, context: IContext) { try { if (!object) { const bucket = await promptBucket(context); if (!bucket) { return; } object = await promptObject(context, bucket.bucketKey); if (!object) { return; } } const { bucketKey, objectKey } = object; await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Deleting object: ${object.objectKey}`, cancellable: false }, async (progress, token) => { await context.dataManagementClient.deleteObject(bucketKey, objectKey); }); vscode.window.showInformationMessage(`Object deleted: ${object.objectKey}`); } catch(err) { showErrorMessage('Could not delete object', err); } } export async function deleteAllObjects(bucket: IBucket | undefined, context: IContext) { try { if (!bucket) { bucket = await promptBucket(context); if (!bucket) { return; } } const { bucketKey } = bucket; const objects = await context.dataManagementClient.listObjects(bucketKey); if (objects.length === 0) { vscode.window.showInformationMessage('No objects to delete'); return; } await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Deleting all objects in bucket: ${bucket.bucketKey}`, cancellable: true }, async (progress, token) => { let cancelled = false; token.onCancellationRequested(() => { cancelled = true; }); let batch = []; progress.report({ increment: 0 }); for (let i = 0, len = objects.length; i < len; i++) { if (cancelled) { break; } batch.push(context.dataManagementClient.deleteObject(bucketKey, objects[i].objectKey)); if (batch.length === DeleteBatchSize || i === len - 1) { await Promise.all(batch); progress.report({ increment: 100.0 * batch.length / len }); batch = []; } } }); vscode.window.showInformationMessage(`Objects deleted`); } catch(err) { showErrorMessage('Could not delete objects', err); } } export async function generateSignedUrl(object: IObject | undefined, context: IContext) { try { if (!object) { const bucket = await promptBucket(context); if (!bucket) { return; } object = await promptObject(context, bucket.bucketKey); if (!object) { return; } } const { objectKey, bucketKey } = object; const permissions = await vscode.window.showQuickPick(['read', 'write', 'readwrite'], { canPickMany: false, placeHolder: 'Select access permissions for the new URL' }); if (!permissions) { return; } const signedUrl = await context.dataManagementClient.createSignedUrl(bucketKey, objectKey, permissions); const action = await vscode.window.showInformationMessage(`Signed URL: ${signedUrl.signedUrl} (expires in ${signedUrl.expiration})`, 'Copy URL to Clipboard'); if (action === 'Copy URL to Clipboard') { vscode.env.clipboard.writeText(signedUrl.signedUrl); } } catch(err) { showErrorMessage('Could not generate signed URL', err); } } export async function deleteBucket(bucket: IBucket | undefined, context: IContext) { try { if (!bucket) { bucket = await promptBucket(context); if (!bucket) { return; } } const { bucketKey } = bucket; await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Deleting bucket: ${bucketKey}`, cancellable: false }, async (progress, token) => { await context.dataManagementClient.deleteBucket(bucketKey); }); vscode.window.showInformationMessage(`Bucket deleted: ${bucketKey}`); } catch(err) { showErrorMessage('Could not delete bucket', err); } }
the_stack
import { DataFrame } from '../core/frame'; import { Tensor } from '@tensorflow/tfjs-node'; import Series from '../core/series'; import { BaseUserConfig, TableUserConfig } from "table"; import Str from '../core/strings'; import Dt from '../core/datetime'; import { ParseConfig } from 'papaparse'; import { GroupBy } from '../core/groupby'; import { Plot } from "../plotting/plot"; export declare type DTYPES = "float32" | "int32" | "string" | "boolean" | "undefined"; export declare type ArrayType2D = Array<number[] | string[] | boolean[] | (number | string | boolean)[]>; export declare type ArrayType1D = Array<number | string | boolean | (number | string | boolean)>; export declare type ConfigsType = { tableDisplayConfig?: BaseUserConfig & TableUserConfig; tableMaxRow?: number; tableMaxColInConsole?: number; dtypeTestLim?: number; lowMemoryMode?: boolean; tfInstance?: any; }; export interface BaseDataOptionType { type?: number; index?: Array<string | number>; columns?: string[]; dtypes?: Array<string>; config?: ConfigsType; } export interface NdframeInputDataType { data: any; type?: number; index?: Array<string | number>; columns?: string[]; dtypes?: Array<string>; config?: ConfigsType; isSeries: boolean; } export interface LoadArrayDataType { data: ArrayType1D | ArrayType2D; index?: Array<string | number>; columns?: string[]; dtypes?: Array<string>; } export interface LoadObjectDataType { data: object | Array<object>; type?: number; index?: Array<string | number>; columns?: string[]; dtypes?: Array<string>; } export declare type AxisType = { index: Array<string | number>; columns: Array<string | number>; }; export interface NDframeInterface { config?: ConfigsType; $setDtypes(dtypes: Array<string>, infer: boolean): void; $setIndex(index: Array<string | number>): void; $resetIndex(): void; $setColumnNames(columns: string[]): void; get dtypes(): Array<string>; get ndim(): number; get axis(): AxisType; get index(): Array<string | number>; get columns(): string[]; get shape(): Array<number>; get values(): ArrayType1D | ArrayType2D; get tensor(): Tensor; get size(): number; to_csv(options?: CsvOutputOptionsNode): string | void; to_json(options?: { format?: "row" | "column"; filePath?: string; }): object | void; to_excel(options?: { filePath?: string; sheetName?: string; }): void; print(): void; } export declare type CsvOutputOptionsNode = { filePath?: string; sep?: string; header?: boolean; }; export type CsvOutputOptionsBrowser = { fileName?: string, sep?: string, header?: boolean, download?: boolean } export interface CsvInputOptions extends ParseConfig { } export interface SeriesInterface extends NDframeInterface { iloc(rows: Array<string | number>): Series; head(rows: number): Series; tail(rows: number): Series; sample(num: number, options?: { seed?: number; }): Promise<Series>; add(other: Series | number | Array<number>, options?: { inplace?: boolean; }): Series | void; sub(other: Series | number | Array<number>, options?: { inplace?: boolean; }): Series | void; mul(other: Series | number | Array<number>, options?: { inplace?: boolean; }): Series | void; div(other: Series | number | Array<number>, options?: { inplace?: boolean; }): Series | void; pow(other: Series | number | Array<number>, options?: { inplace?: boolean; }): Series | void; mod(other: Series | number | Array<number>, options?: { inplace?: boolean; }): Series | void; mean(): number; median(): number; mode(): any; min(): number; max(): number; sum(): number; count(): number; maximum(other: Series | number | Array<number>): Series; minimum(other: Series | number | Array<number>): Series; round(dp: number, options?: { inplace?: boolean; }): Series | void; std(): number; var(): number; isna(): Series; fillna(options?: { value: number | string | boolean, inplace?: boolean; }): Series | void; sort_values(options?: { ascending?: boolean, inplace?: boolean; }): Series | void; copy(): Series; describe(): Series; reset_index(options?: { inplace?: boolean; }): Series | void; set_index(options?: { index: Array<number | string | (number | string)>, inplace?: boolean; }): Series | void; map(callable: any, options?: { inplace?: boolean; }): Series | void; apply(callable: any, options?: { inplace?: boolean; }): Series | void; unique(): Series; nunique(): number; value_counts(): Series; abs(options?: { inplace?: boolean; }): Series | void; cumsum(options?: { inplace?: boolean; }): Series | void; cummin(options?: { inplace?: boolean; }): Series | void; cummax(options?: { inplace?: boolean; }): Series | void; cumprod(options?: { inplace?: boolean; }): Series | void; lt(other: Series | number | Array<number>): Series; gt(other: Series | number | Array<number>): Series; le(other: Series | number | Array<number>): Series; ge(other: Series | number | Array<number>): Series; ne(other: Series | number | Array<number>): Series; eq(other: Series | number | Array<number>): Series; replace(options?: { oldValue: string | number | boolean, newValue: string | number | boolean, inplace?: boolean; }): Series | void; dropna(options?: { inplace?: boolean; }): Series | void; argsort(): Series; argmax(): number; argmin(): number; get dtype(): string; drop_duplicates(options?: { keep?: "first" | "last"; inplace?: boolean; }): Series | void; astype(dtype: "float32" | "int32" | "string" | "boolean", options?: { inplace?: boolean; }): Series | void; get str(): Str; get dt(): Dt; append(values: string | number | boolean | Series | ArrayType1D, index: Array<number | string> | number | string, options?: { inplace?: boolean; }): Series | void; toString(): string; and(other: any): Series; or(other: any): Series; get_dummies(options?: { prefix?: string | Array<string>; prefixSeparator?: string | Array<string>; inplace?: boolean; }): DataFrame; plot(div: string): Plot } export interface DataFrameInterface extends NDframeInterface { [key: string]: any; drop(options: { columns?: string | Array<string>; index?: Array<string | number>; inplace?: boolean; }): DataFrame | void; loc(options: { rows?: Array<string | number>; columns?: Array<string>; }): DataFrame; iloc(options: { rows?: Array<string | number>; columns?: Array<string | number>; }): DataFrame; head(rows?: number): DataFrame; tail(rows?: number): DataFrame; sample(num: number, options?: { seed?: number; }): Promise<DataFrame>; add(other: DataFrame | Series | number | number[], options?: { axis?: 0 | 1; inplace?: boolean; }): DataFrame | void; sub(other: DataFrame | Series | number | number[], options?: { axis?: 0 | 1; inplace?: boolean; }): DataFrame | void; mul(other: DataFrame | Series | number | number[], options?: { axis?: 0 | 1; inplace?: boolean; }): DataFrame | void; div(other: DataFrame | Series | number | number[], options?: { axis?: 0 | 1; inplace?: boolean; }): DataFrame | void; pow(other: DataFrame | Series | number | number[], options?: { axis?: 0 | 1; inplace?: boolean; }): DataFrame | void; mod(other: DataFrame | Series | number | number[], options?: { axis?: 0 | 1; inplace?: boolean; }): DataFrame | void; mean(options?: { axis?: 0 | 1; }): Series; median(options?: { axis?: 0 | 1; }): Series; mode(options?: { axis?: 0 | 1; keep?: number; }): Series; min(options?: { axis?: 0 | 1; }): Series; max(options?: { axis?: 0 | 1; }): Series; std(options?: { axis?: 0 | 1; }): Series; var(options?: { axis?: 0 | 1; }): Series; sum(options?: { axis?: 0 | 1; }): Series; count(options?: { axis?: 0 | 1; }): Series; round(dp?: number, options?: { inplace: boolean; }): DataFrame | void; cumsum(options?: { axis?: 0 | 1; }): DataFrame | void; cummin(options?: { axis?: 0 | 1; }): DataFrame | void; cummax(options?: { axis?: 0 | 1; }): DataFrame | void; cumprod(options?: { axis?: 0 | 1; }): DataFrame | void; copy(): DataFrame; reset_index(options: { inplace?: boolean; }): DataFrame | void; set_index(options: { index: Array<number | string | (number | string)>; column?: string; drop?: boolean; inplace?: boolean; }): DataFrame | void; describe(): DataFrame; select_dtypes(include: Array<string>): DataFrame; abs(options?: { inplace?: boolean; }): DataFrame | void; query(options: { column?: string, is?: string, to?: any, condition?: Series | Array<boolean>, inplace?: boolean }): DataFrame | void addColumn(options: { column: string, values: Series | ArrayType1D, inplace?: boolean; }): DataFrame | void; column(column: string): Series; fillna(value: ArrayType1D, options?: { columns?: Array<string>; inplace?: boolean; }): DataFrame | void; isna(): DataFrame; dropna(axis?: 0 | 1, options?: { inplace?: boolean; }): DataFrame | void; apply(callable: any, options?: { axis?: 0 | 1; }): DataFrame | Series; apply_map(callable: any, options?: { inplace?: boolean; }): DataFrame | void; lt(other: DataFrame | Series | number, options?: { axis?: 0 | 1; }): DataFrame; gt(other: DataFrame | Series | number, options?: { axis?: 0 | 1; }): DataFrame; le(other: DataFrame | Series | number, options?: { axis?: 0 | 1; }): DataFrame; ge(other: DataFrame | Series | number, options?: { axis?: 0 | 1; }): DataFrame; ne(other: DataFrame | Series | number, options?: { axis?: 0 | 1; }): DataFrame; eq(other: DataFrame | Series | number, options?: { axis?: 0 | 1; }): DataFrame; replace(oldValue: number | string | boolean, newValue: number | string | boolean, options?: { columns?: Array<string>; inplace?: boolean; }): DataFrame | void; transpose(options?: { inplace?: boolean; }): DataFrame | void; get T(): DataFrame; get ctypes(): Series; astype(options?: { column: string, dtype: "float32" | "int32" | "string" | "boolean", inplace?: boolean; }): DataFrame | void; nunique(axis: 0 | 1): Series; rename(mapper: object, options?: { axis?: 0 | 1; inplace?: boolean; }): DataFrame | void; sort_index(options?: { inplace?: boolean; ascending?: boolean; }): DataFrame | void; sort_values(options?: { by: string, ascending?: boolean; inplace?: boolean; }): DataFrame | void; append(newValues: ArrayType1D | ArrayType2D | Series | DataFrame, index: Array<number | string> | number | string, options?: { inplace?: boolean; }): DataFrame | void; toString(): string; get_dummies(options?: { columns?: string | Array<string>; prefix?: string | Array<string>; prefixSeparator?: string | Array<string>; inplace?: boolean; }): DataFrame | void; groupby(column: string): GroupBy; plot(div: string): Plot } export interface DateTime { month(): Series; day(): Series; year(): Series; month_name(): Series; monthday(): Series; weekdays(): Series; hours(): Series; seconds(): Series; minutes(): Series; }
the_stack
import { mochaLocalRegistry, mochaTmpdir, Package, repoVersions, writePackage, } from "@adpt/testutils"; import { Constructor, repoDirs, yarn, } from "@adpt/utils"; import execa from "execa"; import * as fs from "fs-extra"; import * as os from "os"; import * as path from "path"; import should from "should"; import { packageDirs } from "../testlib"; import { callerModule, findMummy, findMummyUrn, mockRegistry_, MummyJson, MummyRegistry, reanimate, reanimateUrn, registerObject, } from "../../src/reanimate/reanimate"; import * as firstBaseReg from "./test_baseReg"; import * as firstInFunc from "./test_inFunc"; import * as firstLateExport from "./test_lateExport"; import { isLiving } from "./test_living"; import * as firstVictim from "./test_victim"; const currentAdaptVersion = repoVersions.core; const curMod = { victim: firstVictim, lateExport: firstLateExport, inFunc: firstInFunc, baseReg: firstBaseReg, }; type Mods = typeof curMod; type ModName = keyof Mods; //type ModExports<Mname extends ModName> = keyof Mods[Mname]; type CtorNames<T> = { [K in keyof T]: T[K] extends Constructor<any> ? K : never }[keyof T]; type ModCtorNames<Mname extends ModName> = CtorNames<Mods[Mname]>; function deleteModule(modName: ModName) { delete require.cache[curMod[modName].module.id]; } function requireModule(modName: ModName) { const current = curMod[modName]; curMod[modName] = require(`./test_${modName}`); // Ensure we actually got a new module should(curMod[modName]).not.equal(current); } describe("Reanimate basic tests", () => { let origRegistry: MummyRegistry | undefined; let firstMummyJ: MummyJson; before(() => { origRegistry = mockRegistry_(); }); after(() => { mockRegistry_(origRegistry); }); it("Should have registered on first import", async () => { mockRegistry_(origRegistry); firstMummyJ = findMummy(firstVictim.Victim); should(firstMummyJ).be.type("string"); const parsed = JSON.parse(firstMummyJ); should(parsed).eql({ name: "Victim", namespace: "", pkgName: "@adpt/core", pkgVersion: currentAdaptVersion, relFilePath: "../test/reanimate/test_victim.js", }); const obj = await reanimate(firstMummyJ); should(obj).equal(firstVictim.Victim); const mummyUrn = findMummyUrn(firstVictim.Victim); should(mummyUrn).equal( // tslint:disable-next-line:max-line-length `urn:Adapt:@adpt/core:${currentAdaptVersion}::../test/reanimate/test_victim.js:Victim`); const obj2 = await reanimateUrn(mummyUrn); should(obj2).equal(firstVictim.Victim); }); it("Should store and reanimate with new module and registry", async () => { mockRegistry_(null); // Pre-flight sanity check. Victim derives from Living let v = new curMod.victim.Victim(); should(isLiving(v)).be.True(); registerObject(curMod.victim.Victim, "Victim", curMod.victim.module); const mummified = findMummy(curMod.victim.Victim); should(mummified).be.type("string"); const parsed = JSON.parse(mummified); should(parsed).eql({ name: "Victim", namespace: "", pkgName: "@adpt/core", pkgVersion: currentAdaptVersion, relFilePath: "../test/reanimate/test_victim.js", }); // Clear out the registry and victim module mockRegistry_(null); deleteModule("victim"); const obj = await reanimate(mummified); // This Victim will be a different object from the original should(obj).not.equal(curMod.victim.Victim); // But if we re-require the victim module, we'll get the updated obj requireModule("victim"); should(obj).equal(curMod.victim.Victim); // And the reanimated object should still be an instance of Living v = new obj(); should(isLiving(v)).be.True(); should(v.constructor.name).equal("VictimInternal"); }); it("Should store and reanimate object registered before export", async () => { // Pre-flight sanity check. LateExport derives from Living let v = new curMod.lateExport.LateExport(); should(isLiving(v)).be.True(); should(v.constructor.name).equal("LateExportInternal"); // Clear everything deleteModule("lateExport"); mockRegistry_(null); requireModule("lateExport"); const firstMummyLate = findMummy(curMod.lateExport.LateExport); should(firstMummyLate).be.type("string"); const parsed = JSON.parse(firstMummyLate); should(parsed).eql({ // FIXME(mark): registerObject needs to delay searching module.exports // until after module.loaded === true. Then this should be: // name: "LateExport", namespace: "" name: "LateExportReg", namespace: "$adaptExports", pkgName: "@adpt/core", pkgVersion: currentAdaptVersion, relFilePath: "../test/reanimate/test_lateExport.js", }); const mummyUrn = findMummyUrn(curMod.lateExport.LateExport); should(mummyUrn).equal( // tslint:disable-next-line:max-line-length `urn:Adapt:@adpt/core:${currentAdaptVersion}:$adaptExports:../test/reanimate/test_lateExport.js:LateExportReg`); const firstObj = await reanimate(firstMummyLate); // The reanimated object should still be an instance of Living v = new firstObj(); should(isLiving(v)).be.True(); should(v.constructor.name).equal("LateExportInternal"); const firstObj2 = await reanimateUrn(mummyUrn); should(firstObj2).equal(firstObj); // Clear once more deleteModule("lateExport"); mockRegistry_(null); const obj = await reanimate(firstMummyLate); // This LateExport will be a different object from the original should(obj).not.equal(firstObj); should(obj).not.equal(curMod.lateExport.LateExport); // But if we re-require the module, we'll get the updated obj requireModule("lateExport"); should(obj).equal(curMod.lateExport.LateExport); // And the reanimated object should still be an instance of Living v = new obj(); should(isLiving(v)).be.True(); should(v.constructor.name).equal("LateExportInternal"); }); it("callerModule should return valid modules", () => { const files = [ "dist/src/reanimate/reanimate.js", "dist/test/reanimate/reanimate.spec.js", ]; for (let i = 0; i < files.length; i++) { const mod = callerModule(i); should(mod).be.type("object"); should(mod.filename).equal(path.join(packageDirs.root, files[i])); if (i === 1) { should(mod).equal(module); } } }); it("Should store and reanimate with module default", async () => { mockRegistry_(null); // modOrCallerNum is default paremeter curMod.inFunc.doRegister(); const mummy = findMummy(curMod.inFunc.InFunc); should(mummy).be.type("string"); const parsed = JSON.parse(mummy); should(parsed).eql({ name: "InFunc", namespace: "", pkgName: "@adpt/core", pkgVersion: currentAdaptVersion, relFilePath: "../test/reanimate/test_inFunc.js", }); // Clear out the registry and module mockRegistry_(null); deleteModule("inFunc"); const obj = await reanimate(mummy); // This will be a different object from the original should(obj).not.equal(curMod.inFunc.InFunc); // But if we re-require the module, we'll get the updated obj requireModule("inFunc"); should(obj).equal(curMod.inFunc.InFunc); // And the reanimated object should still be an instance of Living const v = new obj(); should(isLiving(v)).be.True(); should(v.constructor.name).equal("InFuncInternal"); }); }); async function basicTestConstructor<M extends ModName, R extends ModCtorNames<M>>( modName: M, regName: R, // Name of the constructor we expect to be registered newName: R = regName, // Name of the constructor to new to cause registration ) { const getCtor = (name: R): any => curMod[modName][name]; const regCtor = getCtor(regName); const newCtor = getCtor(newName); // Shouldn't have already registered should(() => findMummy(regCtor)).throwError(/Unable to look up JSON/); // Register on construct new newCtor(); const mummyJson = findMummy(regCtor); should(mummyJson).be.type("string"); const mummy = JSON.parse(mummyJson); should(mummy).eql({ name: regName, namespace: "", pkgName: "@adpt/core", pkgVersion: currentAdaptVersion, relFilePath: `../test/reanimate/test_${modName}.js`, }); let live = await reanimate(mummyJson); should(live).equal(regCtor); // Clear out the registry and module mockRegistry_(null); deleteModule(modName); live = await reanimate(mummyJson); // This will be a different object from the original should(live).not.equal(regCtor); // But if we re-require the module, we'll get the updated obj requireModule(modName); should(live).equal(getCtor(regName)); const b = new live(); should(b.constructor.name).equal(regName); } describe("registerConstructor", () => { it("Should store and reanimate constructor", async () => { await basicTestConstructor("baseReg", "BaseReg"); }); it("Should store and reanimate indirect register", async () => { await basicTestConstructor("baseReg", "BaseRegFunc"); }); it("Should store and reanimate nested constructor", async () => { await basicTestConstructor("baseReg", "BaseReg", "BaseRegNested" as "BaseReg"); }); it("Should store and reanimate derived class", async () => { await basicTestConstructor("baseReg", "Derived"); }); }); const mainIndexJs = ` const re = require("@usys/reanimate"); try { if (process.argv.length !== 3) { throw new Error("Usage: node index.js <MummyJson>|show1|show2|showlate"); } const mummy = process.argv[2]; if (mummy === "show1") { const o = require("@usys/oldlib"); console.log(re.findMummy(o.Victim)); process.exit(0); } if (mummy === "show2") { const v = require("@usys/victim"); console.log(re.findMummy(v.Victim)); process.exit(0); } if (mummy === "showlate") { const v = require("@usys/register-in-func"); // registerObject is only called on construction new v.LateVictim(true); console.log(re.findMummy(v.LateVictim)); process.exit(0); } re.reanimate(mummy) .then((alive) => { new alive(); console.log("SUCCESS"); }) .catch((err) => { console.log("FAILED\\n", err); process.exit(1); }); } catch (err) { console.log("FAILED\\n", err); process.exit(1); } `; const mainPackage: Package = { pkgJson: { name: "@usys/test_proj", dependencies: { "@usys/reanimate": "1.0.0", "@usys/victim": "2.0.0", "@usys/oldlib": "1.0.0", "@usys/register-in-func": "1.0.0", } }, files: { "index.js": mainIndexJs, }, }; function victimJs(version: string) { return ` const re = require("@usys/reanimate"); class Victim { constructor() { console.log("Created Victim version ${version}"); } } exports.Victim = Victim; re.registerObject(Victim, "Victim", module); `; } function victimPackage(version: string): Package { return { pkgJson: { name: "@usys/victim", version, dependencies: { "@usys/reanimate": "1.0.0" } }, files: { "index.js": victimJs(version) } }; } const registerInFunc = ` const re = require("@usys/reanimate"); // registerObject NOT called from module scope class LateVictimInternal { constructor(noPrint) { re.registerObject(LateVictimInternal, "Avictim", module); if (!noPrint) console.log("Created LateVictim"); } } exports.LateVictim = LateVictimInternal; `; const registerInFuncPackage: Package = { pkgJson: { name: "@usys/register-in-func", dependencies: { "@usys/reanimate": "1.0.0" } }, files: { "index.js": registerInFunc } }; const distSrc = path.join(packageDirs.dist, "src"); const reanimateIndexJs = ` const path = require("path"); global.getAdaptContext = () => ({ projectRoot: path.resolve("."), }); module.exports = require('./reanimate'); `; const reanimatePackage: Package = { pkgJson: { name: "@usys/reanimate", dependencies: { "@adpt/utils": repoVersions.utils, "callsites": "^3.1.0", "json-stable-stringify": "1.0.1", "read-pkg-up": "^7.0.1", "ts-custom-error": "^3.2.0", "urn-lib": "^1.2.0", }, }, files: { "index.js": reanimateIndexJs, }, copy: { "reanimate/index.js": path.join(distSrc, "reanimate", "reanimate.js"), "error.js": path.join(distSrc, "error.js"), "packageinfo.js": path.join(distSrc, "packageinfo.js"), } }; const oldlibIndexJs = ` const v = require("@usys/victim"); exports.Victim = v.Victim; `; const oldlibPackage: Package = { pkgJson: { name: "@usys/oldlib", dependencies: { "@usys/victim": "1.0.0", }, }, files: { "index.js": oldlibIndexJs, } }; async function createProject() { await writePackage(".", mainPackage); await writePackage("reanimate", reanimatePackage); await writePackage("oldlib", oldlibPackage); await writePackage("victim1", victimPackage("1.0.0")); await writePackage("victim2", victimPackage("2.0.0")); await writePackage("register-in-func", registerInFuncPackage); } async function showMummy(which: string): Promise<MummyJson> { // Get the mummy representation const res = await execa("node", ["index.js", "show" + which]); const mummyJson = res.stdout; should(mummyJson).not.match(/FAILED/); const mummy = JSON.parse(mummyJson); should(mummy).be.type("object"); should(mummy.relFilePath).equal("index.js"); return mummyJson; } function checkMummyVictim(which: string, mummyJson: MummyJson) { const mummy = JSON.parse(mummyJson); should(mummy).be.type("object"); should(mummy.name).equal("Victim"); should(mummy.pkgName).equal("@usys/victim"); should(mummy.pkgVersion).equal(which + ".0.0"); } describe("Reanimate in package tests", function () { let mummy1: string; let mummy2: string; this.timeout(10 * 1000); mochaTmpdir.all("adapt-reanimate-test"); before(createProject); const localRegistry = mochaLocalRegistry.all({ publishList: [ repoDirs.utils, "reanimate", "oldlib", "victim1", "victim2", "register-in-func", ] }); before(async function () { this.timeout(20 * 1000); await yarn.install(localRegistry.yarnProxyOpts); }); it("Should reanimate top level dependency from mummy", async () => { const mummyJson = await showMummy("2"); checkMummyVictim("2", mummyJson); mummy2 = mummyJson; // Reanimate the mummy and construct it const res = await execa("node", ["index.js", mummyJson]); should(res.stdout).match(/SUCCESS/); should(res.stdout).match(/Created Victim version 2.0.0/); }); it("Should reanimate sub dependency from mummy", async () => { const mummyJson = await showMummy("1"); checkMummyVictim("1", mummyJson); mummy1 = mummyJson; // Reanimate the mummy object and construct it const res = await execa("node", ["index.js", mummyJson]); should(res.stdout).match(/SUCCESS/); should(res.stdout).match(/Created Victim version 1.0.0/); }); it("Should reanimate non-module-level registerObject", async () => { const mummyJson = await showMummy("late"); const mummy = JSON.parse(mummyJson); should(mummy.name).equal("LateVictim"); should(mummy.pkgName).equal("@usys/register-in-func"); should(mummy.pkgVersion).equal("1.0.0"); // Reanimate the mummy object and construct it const res = await execa("node", ["index.js", mummyJson]); should(res.stdout).match(/SUCCESS/); should(res.stdout).match(/Created LateVictim/); }); it("Should reanimate with different root dir", async () => { if (!mummy1 || !mummy2) { throw new Error(`Previous tests did not run successfully`); } const oldTmp = process.cwd(); const newTmp = await fs.mkdtemp(path.join(os.tmpdir(), "adapt-reanimate")); // Make a new directory/project try { process.chdir(newTmp); await createProject(); await yarn.install(localRegistry.yarnProxyOpts); let res = await execa("node", ["index.js", mummy1]); should(res.stdout).match(/SUCCESS/); should(res.stdout).match(/Created Victim version 1.0.0/); res = await execa("node", ["index.js", mummy2]); should(res.stdout).match(/SUCCESS/); should(res.stdout).match(/Created Victim version 2.0.0/); } finally { process.chdir(oldTmp); await fs.remove(newTmp); } }); });
the_stack
import * as _ from 'lodash'; /* tslint:disable:indent quotemark max-line-length */ // The following line is important to keep in that format so it can be rendered into the page export const config: IDashboardConfig = /*return*/ { id: 'human_handoff', name: 'Hand-off to human', icon: 'question_answer', url: 'human_handoff', description: 'Monitor bot and hand-off to human conversations', preview: '/images/default.png', category: 'Bots - Advanced', html: ` <div> This dashboard displays the status for a bot-to-human handoff system. <br/> <br/> <h2>Features</h2> <ul> <li> <p>Displays total users including how many are talking with bot, human agent or waiting for an agent.</p> </li> <li> <p>Displays average time waiting (in secs) for human agent to connect and respond to user, including the shortest and longest times.</p> </li> <li> <p>Displays total number of transcripts with bot or with human agent.</p> </li> <li> <p>Displays timeline of conversations with bot and human.</p> </li> <li> <p>Displays list of active conversations with sentiment score.</p> <p>If there is a conversation of interest this can be selected to show the option to hand-off to human.</p> </li> </ul> <p> <span>Refer to the </span> <span> <a href="https://github.com/Azure/ibex-dashboard/blob/master/docs/bot-framework.md" target="_blank"> bot-framework </a> docs for setup instructions.</span> </p> </div> `, config: { connections: { 'bot-framework': { 'directLine': '', 'conversationsEndpoint': '', 'webchatEndpoint': '' } }, layout: { isDraggable: true, isResizable: true, rowHeight: 30, verticalCompact: false, cols: { lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }, breakpoints: { lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 } } }, dataSources: [ { id: 'timespan', type: 'Constant', params: { values: ['24 hours', '1 week', '1 month', '3 months'], selectedValue: '1 month' }, format: 'timespan' }, { id: 'ai', type: 'ApplicationInsights/Query', dependencies: { timespan: 'timespan', queryTimespan: 'timespan:queryTimespan', granularity: 'timespan:granularity' }, params: { table: 'customEvents', queries: { transcripts: { query: () => ` where name == 'Transcript' | extend conversationId=tostring(customDimensions.userConversationId), customerName=tostring(customDimensions.customerName), timestamp=todatetime(customDimensions.timestamp) | project conversationId, customerName, timestamp, customDimensions | order by timestamp desc | summarize transcripts_count=count(timestamp), transcripts=makelist(customDimensions) by customerName, conversationId | project conversationId, customerName, transcripts_count, transcripts`, calculated: (transcripts) => { const listTranscripts = transcripts.reduce( (destArray, currentValue) => { const transcriptsArray = JSON.parse(currentValue.transcripts); if (!Array.isArray(transcriptsArray)) { return destArray; } const lastMessage = transcriptsArray.find(x => x.from === 'Customer'); if (!lastMessage) { return destArray; } const lastSentimentScore = parseFloat(lastMessage.sentimentScore) || 0.5; const lastState = parseInt(transcriptsArray[0].state, 10); const value = { userId: lastMessage.customerId, conversationId: lastMessage.customerConversationId, username: lastMessage.customerName || 'Anon', timestamp: new Date(lastMessage.timestamp).toUTCString(), lastMessage: lastMessage.text || '', lastSentimentScore: lastSentimentScore, lastSentiment: lastSentimentScore < 0 ? 'error_outline' : lastSentimentScore < 0.2 ? 'sentiment_very_dissatisfied' : lastSentimentScore < 0.4 ? 'sentiment_dissatisfied' : lastSentimentScore < 0.6 ? 'sentiment_neutral' : lastSentimentScore < 0.8 ? 'sentiment_satisfied' : 'sentiment_very_satisfied', icon: lastState === 0 ? 'memory' : lastState === 2 ? 'perm_identity' : 'more_horiz', }; destArray.push(value); return destArray; }, []); return { 'transcripts-values': listTranscripts }; } }, transcriptsTimeWaiting: { query: () => ` where name == 'Transcript' | extend conversationId=tostring(customDimensions.userConversationId), customerId=tostring(customDimensions.customerId), state=toint(customDimensions.state) | where state==1 or state==2 | order by timestamp asc | summarize total=count(), times=makelist(timestamp) by conversationId, customerId, bin(state, 1) | project conversationId, customerId, state, startTime=times[0] | summarize result=count(state), startEndTimes=makelist(startTime) by conversationId, customerId | where result == 2 | project conversationId, customerId, timeTaken=todatetime(startEndTimes[1])-todatetime(startEndTimes[0])`, calculated: (results) => { const times = results.reduce( (acc, cur) => { // converts time hh:mm:ss format to value in seconds acc.push(cur.timeTaken.split(':').reverse().reduce((a, c, i) => a + c * Math.pow(60, i), 0)); return acc; }, []); const avgTimeWaiting = times.reduce((a, c) => a + c, 0) / times.length; const maxTimeWaiting = Math.max(...times); const minTimeWaiting = Math.min(...times); const timeFormat = (secs) => { const time = new Date(secs * 1000); let t = time.getSeconds() + 's'; if (time.getHours() > 0 && time.getMinutes() > 0) { t = time.getHours() + 'h ' + time.getMinutes() + 'm'; } else if (time.getMinutes() > 0) { t = time.getMinutes() + 'm'; } return t; }; return { 'transcriptsTimeWaiting-avg': isFinite(avgTimeWaiting) ? timeFormat(avgTimeWaiting) : '-', 'transcriptsTimeWaiting-longest': isFinite(avgTimeWaiting) ? timeFormat(maxTimeWaiting) : '-', 'transcriptsTimeWaiting-shortest': isFinite(avgTimeWaiting) ? timeFormat(minTimeWaiting) : '-', }; } }, timeline: { query: (dependencies) => { var { granularity } = dependencies; return `where name == 'Transcript' | extend customerName=tostring(customDimensions.customerName), text=tostring(customDimensions.text), state=toint(customDimensions.state), agentName=tostring(customDimensions.agentName), from=tostring(customDimensions.from) | extend timestamp=todatetime(customDimensions.timestamp) | extend states=pack_array('bot','waiting','agent','watching') | extend stateLabel=tostring(states[state]) | where state == 0 or state == 2 | project timestamp, from, text, customerName, agentName, state, stateLabel | summarize transcripts_count=count() by bin(timestamp, ${granularity}), state, stateLabel | order by timestamp asc`; }, calculated: (results, dependencies) => { const totalBot = results.reduce((a, c) => c.state === 0 ? a + c.transcripts_count : a, 0); const totalAgent = results.reduce((a, c) => c.state === 2 ? a + c.transcripts_count : a, 0); const totalMessages = totalBot + totalAgent; // Timeline const { timespan } = dependencies; const keys = results.reduce( (keyArray, currentValue) => { return keyArray.includes(currentValue.stateLabel) ? keyArray : [...keyArray, currentValue.stateLabel]; }, []); const timestampKey = 'time'; // NB: required key name for timeline component // group by timestamp const graphData = results.reduce( (a, c) => { if (!c.timestamp) { console.warn('Invalid date format:', c); return a; } const item = a.find(collection => collection[timestampKey] === c.timestamp); if (!item) { // new time collection let collection = { count: 0 }; collection[timestampKey] = c.timestamp; keys.forEach(key => { collection[key] = (key !== c.stateLabel) ? 0 : c.transcripts_count; }); a.push(collection); } else { // merge into time collection item.count += c.transcripts_count; item[c.stateLabel] += c.transcripts_count; } return a; }, []); return { 'timeline-graphData': graphData, 'timeline-recipients': keys, 'timeline-timeFormat': (timespan === '24 hours' ? 'hour' : 'date'), 'timeline-bot': totalBot, 'timeline-agent': totalAgent, 'timeline-total': totalMessages, }; } }, customerTranscripts: { query: () => ` where name == 'Transcript' | extend customerId=tostring(customDimensions.customerId) | extend state=toint(customDimensions.state) | extend timestamp=todatetime(customDimensions.timestamp) | project customerId, timestamp, state | order by timestamp desc | summarize transcripts_count=count(customerId), timestamps=makelist(timestamp) by customerId, state | project customerId, state, transcripts_count, timestamp=timestamps[0] | summarize count(customerId), totals=makelist(transcripts_count), states=makelist(state), timestamps=makelist(timestamp) by customerId | project customerId, state=toint(states[0]), transcripts_count=toint(totals[0]), timestamp=timestamps[0]`, calculated: (customerTranscripts) => { const bot = customerTranscripts.filter((customer) => customer.state === 0); const waiting = customerTranscripts.filter((customer) => customer.state === 1); const agent = customerTranscripts.filter((customer) => customer.state === 2); return { 'customerTranscripts-total': customerTranscripts.length, 'customerTranscripts-bot': bot.length, 'customerTranscripts-waiting': waiting.length, 'customerTranscripts-agent': agent.length, }; } } } } } ], filters: [ { type: 'TextFilter', title: 'Timespan', source: 'timespan', actions: { onChange: 'timespan:updateSelectedValue' }, first: true }, ], elements: [ { id: 'customerTranscripts', type: 'Scorecard', title: 'Users', size: { w: 6, h: 3 }, dependencies: { card_total_heading: '::Total Users', card_total_tooltip: '::Total users', card_total_value: 'ai:customerTranscripts-total', card_total_color: '::#666666', card_total_icon: '::account_circle', card_bot_heading: '::Bot', card_bot_tooltip: '::Total users talking to the bot', card_bot_value: 'ai:customerTranscripts-bot', card_bot_color: '::#00FF00', card_bot_icon: '::memory', card_agent_heading: '::Agent', card_agent_tooltip: '::Total users talking to a human agent', card_agent_value: 'ai:customerTranscripts-agent', card_agent_color: '::#0066FF', card_agent_icon: '::perm_identity', card_waiting_heading: '::Waiting', card_waiting_tooltip: '::Total users waiting for a human agent to respond', card_waiting_value: 'ai:customerTranscripts-waiting', card_waiting_color: '::#FF6600', card_waiting_icon: '::more_horiz', } }, { id: 'customerWaiting', type: 'Scorecard', title: 'Waiting Times', size: { w: 6, h: 3 }, dependencies: { card_average_heading: '::Average', card_average_tooltip: '::Average time for human agent to respond', card_average_value: 'ai:transcriptsTimeWaiting-avg', card_average_color: '::#333333', card_average_icon: '::av_timer', card_max_heading: '::Slowest', card_max_tooltip: '::Slowest time for human agent to respond', card_max_value: 'ai:transcriptsTimeWaiting-longest', card_max_color: '::#ff0000', card_max_icon: '::timer', card_min_heading: '::Fastest', card_min_tooltip: '::Fastest time for human agent to respond', card_min_value: 'ai:transcriptsTimeWaiting-shortest', card_min_color: '::#0066ff', card_min_icon: '::timer', } }, { id: 'timelineScores', type: 'Scorecard', title: 'Transcripts', size: { w: 2, h: 8 }, dependencies: { card_total_heading: '::Total Msgs', card_total_tooltip: '::Total messages', card_total_value: 'ai:timeline-total', card_total_color: '::#666666', card_total_icon: '::question_answer', card_bot_heading: '::Bot', card_bot_tooltip: '::Total messages with bot', card_bot_value: 'ai:timeline-bot', card_bot_color: '::#00FF00', card_bot_icon: '::memory', card_agent_heading: '::Agent', card_agent_tooltip: '::Total messages with a human', card_agent_value: 'ai:timeline-agent', card_agent_color: '::#0066FF', card_agent_icon: '::perm_identity' } }, { id: 'timeline', type: 'Area', title: 'Conversations with bot / human', subtitle: 'How many conversations required hand-off to human', size: { w: 10, h: 8 }, dependencies: { values: 'ai:timeline-graphData', lines: 'ai:timeline-recipients', timeFormat: 'ai:timeline-timeFormat' }, props: { isStacked: false, showLegend: true } }, { id: 'transcripts', type: 'Table', title: 'Recent Conversations', subtitle: 'Monitor bot communications', size: { w: 12, h: 19 }, dependencies: { values: 'ai:transcripts-values' }, props: { cols: [ { header: 'Timestamp', field: 'timestamp', type: 'time', format: 'MMM-DD HH:mm:ss', width: '100px' }, { header: 'Last Message', field: 'lastMessage' }, { header: 'Last Sentiment', field: 'lastSentiment', type: 'icon', tooltip: 'lastSentimentScore', tooltipPosition: 'right' }, { header: 'Username', field: 'username' }, { header: 'Status', field: 'icon', type: 'icon' }, { type: 'button', value: 'chat', click: 'openTranscriptsDialog' } ] }, actions: { openTranscriptsDialog: { action: 'dialog:transcriptsDialog', params: { title: 'args:username', conversationId: 'args:conversationId', queryspan: 'timespan:queryTimespan' } } } } ], dialogs: [ { id: 'transcriptsDialog', width: '60%', params: ['title', 'conversationId', 'queryspan'], dataSources: [ { id: 'transcriptsData', type: 'ApplicationInsights/Query', dependencies: { username: 'dialog_transcriptsDialog:title', conversationId: 'dialog_transcriptsDialog:conversationId', queryTimespan: 'dialog_transcriptsDialog:queryspan', secret: 'connection:bot-framework.directLine' }, params: { query: ({ conversationId }) => ` customEvents | where name == 'Transcript' | where customDimensions.customerConversationId == '${conversationId}' | extend timestamp=tostring(customDimensions.timestamp) | project timestamp, text=tostring(customDimensions.text), sentimentScore=todouble(customDimensions.sentimentScore), from=tostring(customDimensions.from), state=toint(customDimensions.state) | order by timestamp asc` }, calculated: (state, dependencies) => { let { values } = state || []; if (!values || values.length < 1) { return null; } const { secret } = dependencies; const { conversationId } = dependencies; let body, headers = {}; let disabled = values[values.length - 1].state !== 0 ? true : false; values.map(v => { const lastSentimentScore = v.sentimentScore || 0.5; v['sentiment'] = lastSentimentScore < 0 ? 'error_outline' : lastSentimentScore < 0.2 ? 'sentiment_very_dissatisfied' : lastSentimentScore < 0.4 ? 'sentiment_dissatisfied' : lastSentimentScore < 0.6 ? 'sentiment_neutral' : lastSentimentScore < 0.8 ? 'sentiment_satisfied' : 'sentiment_very_satisfied'; }); body = { 'conversationId': conversationId, }; headers = { 'Authorization': `Bearer ${secret}` }; return { values, headers, body, disabled }; } } ], elements: [ { id: 'transcripts-button', type: 'RequestButton', title: 'Transfer to Agent', size: { w: 2, h: 1 }, location: { x: 0, y: 0 }, dependencies: { body: 'transcriptsData:body', headers: 'transcriptsData:headers', disabled: 'transcriptsData:disabled', conversationsEndpoint: 'connection:bot-framework.conversationsEndpoint' }, props: { url: ({ conversationsEndpoint }) => `${conversationsEndpoint}`, method: 'POST', disableAfterFirstClick: true, icon: 'person', buttonProps: { iconBefore: false, primary: true } } }, { id: 'agent-button', type: 'RequestButton', title: 'Open Webchat', size: { w: 2, h: 1 }, location: { x: 2, y: 0 }, dependencies: { token: 'connection:bot-framework.directLine', webchatEndpoint: 'connection:bot-framework.webchatEndpoint', dependsOn: 'transcriptsData:disabled' }, props: { url: ({ token, webchatEndpoint }) => `${webchatEndpoint}/?s=${token}`, link: true, icon: 'open_in_new', buttonProps: { iconBefore: false, secondary: true } } }, { id: 'transcriptsData', type: 'Table', title: 'Transcripts', size: { w: 12, h: 11 }, location: { x: 0, y: 1 }, dependencies: { values: 'transcriptsData:values' }, props: { rowClassNameField: 'from', cols: [ { header: 'Timestamp', field: 'timestamp', type: 'time', format: 'MMM-DD HH:mm:ss', width: '50px' }, { header: 'Sentiment', field: 'sentiment', tooltip: 'sentimentScore', type: 'icon', width: '50px', tooltipPosition: 'right' }, { header: 'Text', field: 'text' } ] } } ] } ] };
the_stack