text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import React from 'react' import renderer, { act } from 'react-test-renderer' import { shallow, mount } from 'enzyme' import moment from 'moment' import ScheduleSelector, { preventScroll } from '../../src/lib/ScheduleSelector' const startDate = new Date('2018-01-01T00:00:00.000') const getTestSchedule = () => [ moment(startDate) .startOf('day') .add(12, 'h'), moment(startDate) .startOf('day') .add(1, 'd') .add(13, 'h') ] describe('ScheduleSelector', () => { beforeAll(() => { const fakeElement = document.createElement('div') document.elementFromPoint = jest.fn().mockReturnValue(fakeElement) document.removeEventListener = jest.fn() }) describe('snapshot tests', () => { it('renders correctly with default render logic', () => { const component = renderer.create( <ScheduleSelector selection={getTestSchedule()} startDate={startDate} numDays={5} onChange={() => undefined} /> ) const tree = component.toJSON() expect(tree).toMatchSnapshot() }) it('renders correctly with custom render props', () => { const customDateCellRenderer = (date, selected) => ( <div className={`${selected && 'selected'} test-date-cell-renderer`}>{+date}</div> ) const component = renderer.create( <ScheduleSelector selection={getTestSchedule()} startDate={startDate} numDays={5} onChange={() => undefined} renderDateCell={customDateCellRenderer} renderDateLabel={(date: Date) => <div>{+date}</div>} renderTimeLabel={(time: Date) => <div>{+time}</div>} /> ) const tree = component.toJSON() expect(tree).toMatchSnapshot() }) }) it('getTimeFromTouchEvent returns the time for that cell', () => { const component = shallow(<ScheduleSelector />) const mainSpy = jest.spyOn(component.instance(), 'getTimeFromTouchEvent') const mockCellTime = new Date() const mockEvent = { touches: [{ clientX: 1, clientY: 2 }] } const cellToDateSpy = jest.spyOn(component.instance().cellToDate, 'get').mockReturnValue(mockCellTime) component.instance().getTimeFromTouchEvent(mockEvent) expect(document.elementFromPoint).toHaveBeenCalledWith(mockEvent.touches[0].clientX, mockEvent.touches[0].clientY) expect(cellToDateSpy).toHaveBeenCalled() expect(mainSpy).toHaveReturnedWith(mockCellTime) mainSpy.mockRestore() cellToDateSpy.mockRestore() }) it('endSelection calls the onChange prop and resets selection state', () => { const changeSpy = jest.fn() const component = shallow(<ScheduleSelector onChange={changeSpy} />) const setStateSpy = jest.spyOn(component.instance(), 'setState') component.instance().endSelection() expect(changeSpy).toHaveBeenCalledWith(component.state('selectionDraft')) expect(setStateSpy).toHaveBeenCalledWith({ selectionType: null, selectionStart: null }) setStateSpy.mockRestore() }) describe('mouse handlers', () => { const spies = {} let component let anInstance beforeAll(() => { spies.onMouseDown = jest.spyOn(ScheduleSelector.prototype, 'handleSelectionStartEvent') spies.onMouseEnter = jest.spyOn(ScheduleSelector.prototype, 'handleMouseEnterEvent') spies.onMouseUp = jest.spyOn(ScheduleSelector.prototype, 'handleMouseUpEvent') component = shallow(<ScheduleSelector />) anInstance = component.find('.rgdp__grid-cell').first() }) test.each([['onMouseDown'], ['onMouseEnter'], ['onMouseUp']])('calls the handler for %s', name => { anInstance.prop(name)() expect(spies[name]).toHaveBeenCalled() spies[name].mockClear() }) afterAll(() => { Object.keys(spies).forEach(spyName => { spies[spyName].mockRestore() }) }) }) describe('touch handlers', () => { const spies = {} let component let anInstance const mockEvent = {} beforeAll(() => { spies.onTouchStart = jest.spyOn(ScheduleSelector.prototype, 'handleSelectionStartEvent') spies.onTouchMove = jest.spyOn(ScheduleSelector.prototype, 'handleTouchMoveEvent') spies.onTouchEnd = jest.spyOn(ScheduleSelector.prototype, 'handleTouchEndEvent') component = shallow(<ScheduleSelector />) anInstance = component.find('.rgdp__grid-cell').first() mockEvent.touches = [ { clientX: 1, clientY: 2 }, { clientX: 100, clientY: 200 } ] }) test.each([ ['onTouchStart', []], ['onTouchMove', [mockEvent]], ['onTouchEnd', []] ])('calls the handler for %s', (name, args) => { anInstance.prop(name)(...args) expect(spies[name]).toHaveBeenCalled() spies[name].mockClear() }) afterAll(() => { Object.keys(spies).forEach(spyName => { spies[spyName].mockRestore() }) }) }) it('handleTouchMoveEvent updates the availability draft', () => { const mockCellTime = new Date() const getTimeSpy = jest.spyOn(ScheduleSelector.prototype, 'getTimeFromTouchEvent').mockReturnValue(mockCellTime) const updateDraftSpy = jest.spyOn(ScheduleSelector.prototype, 'updateAvailabilityDraft') const component = shallow(<ScheduleSelector />) component.instance().handleTouchMoveEvent({}) expect(updateDraftSpy).toHaveBeenCalledWith(mockCellTime) getTimeSpy.mockRestore() updateDraftSpy.mockRestore() }) describe('updateAvailabilityDraft', () => { it.each([ ['add', 1], ['remove', 1], ['add', -1], ['remove', -1] ])( 'updateAvailabilityDraft handles addition and removals, for forward and reversed drags', (type, amount, done) => { const start = moment(startDate) .add(5, 'hours') .toDate() const end = moment(start) .add(amount, 'hours') .toDate() const outOfRangeOne = moment(start) .add(amount + 5, 'hours') .toDate() const setStateSpy = jest.spyOn(ScheduleSelector.prototype, 'setState') const component = shallow( <ScheduleSelector // Initialize the initial selection based on whether this test is adding or removing selection={type === 'remove' ? [start, end, outOfRangeOne] : [outOfRangeOne]} startDate={start} numDays={5} minTime={0} maxTime={23} /> ) component.setState( { selectionType: type, selectionStart: start }, () => { component.instance().updateAvailabilityDraft(end, () => { expect(setStateSpy).toHaveBeenLastCalledWith({ selectionDraft: expect.arrayContaining([]) }) setStateSpy.mockRestore() done() }) } ) } ) it('updateAvailabilityDraft handles a single cell click correctly', done => { const setStateSpy = jest.spyOn(ScheduleSelector.prototype, 'setState') const component = shallow(<ScheduleSelector />) const start = startDate component.setState( { selectionType: 'add', selectionStart: start }, () => { component.instance().updateAvailabilityDraft(null, () => { expect(setStateSpy).toHaveBeenCalledWith({ selectionDraft: expect.arrayContaining([]) }) setStateSpy.mockRestore() done() }) } ) }) }) describe('componentWillUnmount', () => { it('removes the mouseup event listener', () => { const component = shallow(<ScheduleSelector />) const endSelectionMethod = component.instance().endSelection component.unmount() expect(document.removeEventListener).toHaveBeenCalledWith('mouseup', endSelectionMethod) }) it('removes the touchmove event listeners from the date cells', () => { const component = shallow(<ScheduleSelector />) const mockDateCell = { removeEventListener: jest.fn() } component.instance().cellToDate.set(mockDateCell, new Date()) component.unmount() expect(mockDateCell.removeEventListener).toHaveBeenCalledWith('touchmove', expect.anything()) }) }) describe('handleTouchEndEvent', () => { const component = shallow(<ScheduleSelector />) const setStateSpy = jest.spyOn(component.instance(), 'setState') const updateDraftSpy = jest.spyOn(component.instance(), 'updateAvailabilityDraft').mockImplementation((a, b) => b()) const endSelectionSpy = jest.spyOn(component.instance(), 'endSelection').mockImplementation(jest.fn()) it('handles regular events correctly', () => { component.instance().handleTouchEndEvent() expect(setStateSpy).toHaveBeenLastCalledWith({ isTouchDragging: false }) expect(updateDraftSpy).toHaveBeenCalled() expect(endSelectionSpy).toHaveBeenCalled() setStateSpy.mockClear() updateDraftSpy.mockClear() endSelectionSpy.mockClear() }) it('handles single-touch-tap events correctly', done => { // Set touch dragging to true and make sure updateDraftSpy doesn't get called component.setState( { isTouchDragging: true }, () => { component.instance().handleTouchEndEvent() expect(updateDraftSpy).not.toHaveBeenCalled() expect(endSelectionSpy).toHaveBeenCalled() expect(setStateSpy).toHaveBeenLastCalledWith({ isTouchDragging: false }) setStateSpy.mockRestore() updateDraftSpy.mockRestore() endSelectionSpy.mockRestore() done() } ) }) }) describe('preventScroll', () => { it('prevents the event default', () => { const event = { preventDefault: jest.fn() } preventScroll(event) expect(event.preventDefault).toHaveBeenCalled() }) }) describe('minute-level resolution', () => { it('splits hours using the hourlyChunks prop', () => { // 15-minute resolution const component = shallow(<ScheduleSelector minTime={1} maxTime={2} hourlyChunks={4} />) expect(component.find('ScheduleSelector__TimeText')).toHaveLength(4) // 5-minute resolution const componentTwo = shallow(<ScheduleSelector minTime={1} maxTime={2} hourlyChunks={12} />) expect(componentTwo.find('ScheduleSelector__TimeText')).toHaveLength(12) }) it('formats the time column using the timeFormat prop', () => { // 15-minute resolution const component = shallow(<ScheduleSelector minTime={1} maxTime={2} timeFormat="h:mma" hourlyChunks={4} />) expect( component .find('ScheduleSelector__TimeText') .at(1) .render() .text() ).toEqual('1:15am') // 5-minute resolution const componentTwo = shallow(<ScheduleSelector minTime={1} maxTime={2} timeFormat="h:mma" hourlyChunks={12} />) expect( componentTwo .find('ScheduleSelector__TimeText') .at(1) .render() .text() ).toEqual('1:05am') }) }) })
the_stack
import CustomMedia from './interfaces/custom-media'; import Level from './interfaces/level'; import PlayerOptions from './interfaces/player-options'; import Source from './interfaces/source'; import DashMedia from './media/dash'; import FlvMedia from './media/flv'; import HlsMedia from './media/hls'; import HTML5Media from './media/html5'; import * as source from './utils/media'; /** * Media element. * * @description Class that creates the Media Component in the player. * `Media` is the visual/audio entity that results from playing a valid source (MP4, MP3, M3U8, MPD, etc.) * @class Media */ class Media { /** * The video/audio tag that contains media to be played. * * @type HTMLMediaElement * @memberof Media */ #element: HTMLMediaElement; /** * Object that instantiates class of current media. * * @type (HTML5Media|HlsMedia|DashMedia|any) * @memberof Media */ #media: HTML5Media | HlsMedia | DashMedia | any; /** * Collection of media sources available within the video/audio tag. * * @type Source[] * @memberof Media */ #files: Source[]; /** * Promise to be resolved once media starts playing to avoid race issues. * * @see [[Media.play]] * @see [[Media.pause]] * @private * @type Promise<void> * @memberof Media */ #promisePlay: Promise<void>; /** * Media options to be passed to Hls and/or Dash players. * * @private * @type PlayerOptions * @memberof Media */ #options: PlayerOptions; /** * Flag to indicate if `autoplay` attribute was set * * @private * @type boolean * @memberof Media */ #autoplay: boolean; /** * Flag that indicates if initial load has occurred. * * @type boolean * @memberof Media */ #mediaLoaded = false; /** * Collection of additional (non-native) media * * @type CustomMedia * @memberof Media */ #customMedia: CustomMedia = { media: {}, optionsKey: {}, rules: [], }; /** * Reference to current media being played * * @type Source * @memberof Media */ #currentSrc: Source; /** * Create an instance of Media. * * @param {HTMLMediaElement} element * @param {object} options * @param {boolean} autoplay * @param {CustomMedia} customMedia * @returns {Media} * @memberof Media */ constructor(element: HTMLMediaElement, options: PlayerOptions, autoplay = false, customMedia: CustomMedia) { this.#element = element; this.#options = options; this.#files = this._getMediaFiles(); this.#customMedia = customMedia; this.#autoplay = autoplay; return this; } /** * Check if player can play the current media type (MIME type). * * @param {string} mimeType A valid MIME type, that can include codecs. * @see [[Native.canPlayType]] * @returns {boolean} */ public canPlayType(mimeType: string): boolean { return this.#media.canPlayType(mimeType); } /** * Check media associated and process it according to its type. * * It requires to run with Promises to avoid racing errors between execution of the action * and the time the potential libraries are loaded completely. * It will loop the media list found until it reached the first element that can be played. * * If none of them can be played, automatically the method destroys the `Media` object. * * @see [[Native.load]] */ public async load(): Promise<void> { if (this.#mediaLoaded) { return; } this.#mediaLoaded = true; if (!this.#files.length) { throw new TypeError('Media not set'); } // Remove previous media if any is detected and it's different from current one if (this.#media && typeof this.#media.destroy === 'function') { const sameMedia = this.#files.length === 1 && this.#files[0].src === this.#media.media.src; if (!sameMedia) { this.#media.destroy(); } } // Loop until first playable source is found this.#files.some(media => { try { this.#media = this._invoke(media); } catch (e) { this.#media = new HTML5Media(this.#element, media); } return this.#media.canPlayType(media.type); }); try { if (this.#media === null) { throw new TypeError('Media cannot be played with any valid media type'); } await this.#media.promise; this.#media.load(); } catch (e) { // destroy media if (this.#media) { this.#media.destroy(); } throw e; } } /** * Wrapper for `play` method. * * It returns a Promise to avoid browser's race issues when attempting to pause media. * @see https://developers.google.com/web/updates/2017/06/play-request-was-interrupted * @see [[Native.play]] * @returns {Promise<void>} * @memberof Media */ public async play(): Promise<void> { if (!this.#mediaLoaded) { this.#mediaLoaded = true; await this.load(); this.#mediaLoaded = false; } else { await this.#media.promise; } this.#promisePlay = this.#media.play(); return this.#promisePlay; } /** * Wrapper for `pause` method. * * It checks if play Promise has been resolved in order to trigger pause * to avoid browser's race issues. * @see https://developers.google.com/web/updates/2017/06/play-request-was-interrupted * @see [[Native.pause]] * @memberof Media */ public async pause(): Promise<void> { if (this.#promisePlay !== undefined) { await this.#promisePlay; } this.#media.pause(); } /** * Invoke `destroy` method of current media type. * * Streaming that uses hls.js or dash.js libraries require to destroy their players and * their custom events. * @memberof Media */ public destroy(): void { if (this.#media) { this.#media.destroy(); } } /** * Set one or more media sources. * * @param {string|object|object[]} media * @see [[Native.src]] * @memberof Media */ set src(media) { if (typeof media === 'string') { this.#files.push({ src: media, type: source.predictType(media, this.#element), }); } else if (Array.isArray(media)) { this.#files = media; } else if (typeof media === 'object') { this.#files.push(media); } // Remove files without source this.#files = this.#files.filter(file => file.src); if (this.#files.length > 0) { // Save copy of original file to restore it when player is destroyed if (this.#element.src) { this.#element.setAttribute('data-op-file', this.#files[0].src); } this.#element.src = this.#files[0].src; this.#currentSrc = this.#files[0]; if (this.#media) { this.#media.src = this.#files[0]; } } else { this.#element.src = ''; } } /** * Get all media associated with element * * @see [[Native.src]] * @type Source[] * @memberof Media * @readonly */ get src(): Source[] { return this.#files; } /** * Get the current media being played. * * @type Source * @memberof Media * @readonly */ get current(): Source { return this.#currentSrc; } /** * Set the list of media associated with the current player. * * @param {Source[]} sources * @memberof Media */ set mediaFiles(sources: Source[]) { this.#files = sources; } /** * Get the list of media associated with the current player. * * @type Source[] * @memberof Media * @readonly */ get mediaFiles(): Source[] { return this.#files; } /** * * @see [[Native.volume]] * @memberof Media */ set volume(value: number) { if (this.#media) { this.#media.volume = value; } } /** * * @see [[Native.volume]] * @type number * @memberof Media * @readonly */ get volume(): number { return this.#media ? this.#media.volume : this.#element.volume; } /** * * @see [[Native.muted]] * @memberof Media */ set muted(value: boolean) { if (this.#media) { this.#media.muted = value; } } /** * * @see [[Native.muted]] * @type boolean * @memberof Media * @readonly */ get muted(): boolean { return this.#media ? this.#media.muted : this.#element.muted; } /** * * @see [[Native.playbackRate]] * @memberof Media */ set playbackRate(value) { if (this.#media) { this.#media.playbackRate = value; } } /** * * @see [[Native.playbackRate]] * @type number * @memberof Media * @readonly */ get playbackRate(): number { return this.#media ? this.#media.playbackRate : this.#element.playbackRate; } /** * * @see [[Native.defaultPlaybackRate]] * @memberof Media */ set defaultPlaybackRate(value) { if (this.#media) { this.#media.defaultPlaybackRate = value; } } /** * * @see [[Native.defaultPlaybackRate]] * @type number * @memberof Media * @readonly */ get defaultPlaybackRate(): number { return this.#media ? this.#media.defaultPlaybackRate : this.#element.defaultPlaybackRate; } /** * * @see [[Native.currentTime]] * @memberof Media */ set currentTime(value: number) { if (this.#media) { this.#media.currentTime = value; } } /** * * @see [[Native.currentTime]] * @type number * @memberof Media * @readonly */ get currentTime(): number { return this.#media ? this.#media.currentTime : this.#element.currentTime; } /** * * @see [[Native.duration]] * @type number * @memberof Media * @readonly */ get duration(): number { const duration = this.#media ? this.#media.duration : this.#element.duration; // To seek backwards in a live streaming (mobile devices) if (duration === Infinity && this.#element.seekable && this.#element.seekable.length) { return this.#element.seekable.end(0); } return duration; } /** * * @see [[Native.paused]] * @type boolean * @memberof Media * @readonly */ get paused(): boolean { return this.#media ? this.#media.paused : this.#element.paused; } /** * * @see [[Native.ended]] * @type boolean * @memberof Media * @readonly */ get ended(): boolean { return this.#media ? this.#media.ended : this.#element.ended; } /** * * @memberof Media */ set loaded(loaded: boolean) { this.#mediaLoaded = loaded; } /** * * @type boolean * @memberof Media */ get loaded(): boolean { return this.#mediaLoaded; } /** * * @memberof Media */ set level(value: number|string|Level) { if (this.#media) { this.#media.level = value; } } /** * * @memberof Media * @readonly */ get level(): number|string|Level { return this.#media ? this.#media.level : -1; } /** * * @memberof Media * @readonly */ get levels() { return this.#media ? this.#media.levels : []; } /** * * @memberof Media * @readonly */ get instance() { return this.#media ? this.#media.instance : null; } /** * Gather all media sources within the video/audio/iframe tags. * * It will be grouped inside the `mediaFiles` array. This method basically mimics * the native behavior when multiple sources are associated with an element, and * the browser takes care of selecting the most appropriate one. * @returns {Source[]} * @memberof Media */ private _getMediaFiles(): Source[] { const mediaFiles = []; const sourceTags = this.#element.querySelectorAll('source'); const nodeSource = this.#element.src; // Consider if node contains the `src` and `type` attributes if (nodeSource) { mediaFiles.push({ src: nodeSource, type: this.#element.getAttribute('type') || source.predictType(nodeSource, this.#element), }); } // test <source> types to see if they are usable for (let i = 0, total = sourceTags.length; i < total; i++) { const item = sourceTags[i]; const src = item.src; mediaFiles.push({ src, type: item.getAttribute('type') || source.predictType(src, this.#element), }); // If tag has the attribute `preload` set as `none`, the current media will // be the first one on the list of sources if (i === 0) { this.#currentSrc = mediaFiles[0]; } } if (!mediaFiles.length) { mediaFiles.push({ src: '', type: source.predictType('', this.#element), }); } return mediaFiles; } /** * Instantiate media object according to current media type. * * @param {Source} media * @returns {(HlsMedia|DashMedia|HTML5Media|any)} * @memberof Media */ private _invoke(media: Source): HlsMedia | DashMedia | HTML5Media | any { const playHLSNatively = this.#element.canPlayType('application/vnd.apple.mpegurl') || this.#element.canPlayType('application/x-mpegURL'); this.#currentSrc = media; let activeLevels = false; Object.keys(this.#options.controls.layers).forEach(layer => { if (this.#options.controls.layers[layer].indexOf('levels') > -1) { activeLevels = true; } }); if (Object.keys(this.#customMedia.media).length) { let customRef: any; this.#customMedia.rules.forEach((rule: any) => { const type = rule(media.src); if (type) { const customMedia = this.#customMedia.media[type] as any; const customOptions = this.#options[this.#customMedia.optionsKey[type]] || undefined; customRef = customMedia(this.#element, media, this.#autoplay, customOptions); } }); if (customRef) { customRef.create(); return customRef; } return new HTML5Media(this.#element, media); } if (source.isHlsSource(media)) { if (playHLSNatively && this.#options.forceNative && !activeLevels) { return new HTML5Media(this.#element, media); } const hlsOptions = this.#options && this.#options.hls ? this.#options.hls : undefined; return new HlsMedia(this.#element, media, this.#autoplay, hlsOptions); } if (source.isDashSource(media)) { const dashOptions = this.#options && this.#options.dash ? this.#options.dash : undefined; return new DashMedia(this.#element, media, dashOptions); } if (source.isFlvSource(media)) { const flvOptions = this.#options && this.#options.flv ? this.#options.flv : { debug: false, type: 'flv', url: media.src, }; return new FlvMedia(this.#element, media, flvOptions); } return new HTML5Media(this.#element, media); } } export default Media;
the_stack
declare const unsafeWindow: Window /** * Get some info about the script and TM. */ declare const GM_info: { downloadMode: string isIncognito: boolean script: GMInfoScript scriptHandler: string scriptMetaStr: string scriptSource: string scriptUpdateURL?: string scriptWillUpdate: boolean version: string } interface GMInfoScript { author: string blockers: string[] description: string description_i18n: GMInfoI18n downloadURL: string | null evilness: number excludes: string[] grant: string[] header: string homepage: string | null icon: string | null icon64: string | null includes: string[] lastModified: number matches: string[] name: string name_i18n: GMInfoI18n namespace: string options: GMInfoOptions position: number resources: GMInfoResources[] 'run-at': string supportURL?: string sync: GMInfoSync unwrap: boolean updateURL: string | null uuid: string version: string webRequest: string | null } interface GMInfoI18n { [index: string]: string } interface GMInfoOptions { awareOfChrome: boolean check_for_updates: boolean comment: string | null compat_arrayleft: boolean compat_foreach: boolean compat_forvarin: boolean compat_metadata: boolean compat_prototypes: boolean compat_uW_gmonkey: boolean compat_wrappedjsObject: boolean compatopts_for_requires: boolean noframes: boolean | null override: GMInfoOverride run_at: string } interface GMInfoOverride { merge_connects: boolean merge_excludes: boolean merge_includes: boolean merge_matches: boolean orig_connects: string[] orig_excludes: string[] orig_includes: string[] orig_matches: string[] orig_noframes: boolean | null orig_run_at: string use_blockers: string[] use_connects: string[] use_excludes: string[] use_includes: string[] use_matches: string[] } interface GMInfoResources { content: string meta: string name: string url: string } interface GMInfoSync { imported: boolean } /** * GM_openInTab * * @interface GMOpenInTabOptions */ interface GMOpenInTabOptions { /** * decides whether the new tab should be focused * * @type {boolean} * @memberof GMOpenInTabOptions */ active?: boolean /** * inserts the new tab after the current one * * @type {boolean} * @memberof GMOpenInTabOptions */ insert?: boolean /** * makes the browser re-focus the current tab on close. * * @type {boolean} * @memberof GMOpenInTabOptions */ setParent?: boolean } interface GMOpenInTabRetuens { close: () => void closed: boolean onclose: () => void } /** * GM_xmlhttpRequest * * @interface GMXMLHttpRequestOptions */ interface GMXMLHttpRequestOptions { /** * one of GET, HEAD, POST * * @type {('GET' | 'HEAD' | 'POST')} * @memberof GMXMLHttpRequestOptions */ method: 'GET' | 'HEAD' | 'POST' /** * the destination URL * * @type {string} * @memberof GMXMLHttpRequestOptions */ url: string /** * ie. user-agent, referer, ... (some special headers are not supported by Safari and Android browsers) * * @type {{ [index: string]: string | number }} * @memberof GMXMLHttpRequestOptions */ headers?: { [index: string]: string | number } /** * some string to send via a POST request * * @type {string} * @memberof GMXMLHttpRequestOptions */ data?: string /** * some string to send via a POST request * * @type {string} * @memberof GMXMLHttpRequestOptions */ body?: string /** * send the data string in binary mode * * @type {boolean} * @memberof GMXMLHttpRequestOptions */ binary?: boolean /** * a timeout in ms * * @type {number} * @memberof GMXMLHttpRequestOptions */ timeout?: number /** * a property which will be added to the response Object * * @type {*} * @memberof GMXMLHttpRequestOptions */ context?: any /** * one of arraybuffer, blob, json * * @type {XMLHttpRequestResponseType} * @memberof GMXMLHttpRequestOptions */ responseType?: XMLHttpRequestResponseType /** * a MIME type for the request * * @type {string} * @memberof GMXMLHttpRequestOptions */ overrideMimeType?: string /** * don't send cookies with the requests (please see the fetch notes) * * @type {boolean} * @memberof GMXMLHttpRequestOptions */ anonymous?: boolean /** * (beta) use a fetch instead of a xhr request * (at Chrome this causes xhr.abort, details.timeout and xhr.onprogress to not work and makes xhr.onreadystatechange receive only readyState 4 events) * * @type {boolean} * @memberof GMXMLHttpRequestOptions */ fetch?: boolean /** * a username for authentication * * @type {string} * @memberof GMXMLHttpRequestOptions */ username?: string /** * a password * * @type {string} * @memberof GMXMLHttpRequestOptions */ password?: string /** * callback to be executed if the request was aborted * * @memberof GMXMLHttpRequestOptions */ onabort?: (response: GMXMLHttpRequestResponse) => void /** * callback to be executed if the request ended up with an error * * @memberof GMXMLHttpRequestOptions */ onerror?: (response: GMXMLHttpRequestResponse) => void /** * callback to be executed if the request was loaded * * @memberof GMXMLHttpRequestOptions */ onload?: (response: GMXMLHttpRequestResponse) => void /** * callback to be executed if the request started to load * * @memberof GMXMLHttpRequestOptions */ onloadstart?: (response: GMXMLHttpRequestResponse) => void /** * callback to be executed if the request made some progress * * @memberof GMXMLHttpRequestOptions */ onprogress?: (response: GMXMLHttpRequestProgressResponse) => void /** * callback to be executed if the request's ready state changed * * @memberof GMXMLHttpRequestOptions */ onreadystatechange?: (response: GMXMLHttpRequestResponse) => void /** * callback to be executed if the request failed due to a timeout * * @memberof GMXMLHttpRequestOptions */ ontimeout?: ({ }) => void } interface GMXMLHttpRequestResponse { readonly context: any readonly finalUrl: string readonly readyState: number readonly response: ArrayBuffer | Blob | string | any readonly responseHeaders: string readonly responseText: string readonly responseXML: Document readonly status: number readonly statusText: string } interface GMXMLHttpRequestProgressResponse extends GMXMLHttpRequestResponse { readonly lengthComputable: boolean readonly loaded: number readonly total: number } interface GMXMLHttpRequestReturns { /** * function to be called to cancel this request * * @memberof GMXMLHttpRequestReturns */ abort(): void } /** * GM_download * * @interface GMDownloadOptions */ interface GMDownloadOptions { /** * the URL from where the data should be downloaded * * @type {string} * @memberof GMDownloadOptions */ url: string /** * the filename - for security reasons the file extension needs to be whitelisted at the Tampermonkey options page * * @type {string} * @memberof GMDownloadOptions */ name: string /** * see GM_xmlhttpRequest for more details * * @type {*} * @memberof GMDownloadOptions */ headers?: any /** * boolean value, show a saveAs dialog * * @type {boolean} * @memberof GMDownloadOptions */ saveAs?: boolean /** * callback to be executed if the download ended up with an error * * @memberof GMDownloadOptions */ onerror?: (error: GMDownloadError) => void /** * callback to be executed if the download finished * * @memberof GMDownloadOptions */ onload?: ({ }) => void /** * callback to be executed if the download made some progress * * @memberof GMDownloadOptions */ onprogress?: (response: GMXMLHttpRequestProgressResponse) => void /** * callback to be executed if the download failed due to a timeout * * @memberof GMDownloadOptions */ ontimeout?: ({ }) => void } /** * not_enabled - the download feature isn't enabled by the user * not_whitelisted - the requested file extension is not whitelisted * not_permitted - the user enabled the download feature, but did not give the downloads permission * not_supported - the download feature isn't supported by the browser/version * not_succeeded - the download wasn't started or failed, the details attribute may provide more information * * @interface GMDownloadError */ interface GMDownloadError { error: 'not_enabled' | 'not_whitelisted ' | 'not_permitted' | 'not_supported' | 'not_succeeded' details?: any } interface GMDownloadReturns { /** * function to be called to cancel this download * * @memberof GMDownloadReturns */ abort(): void } /** * GM_notification * * @interface GMNotificationOptions */ interface GMNotificationOptions { /** * the text of the notification (optional if highlight is set) * * @type {string} * @memberof GMNotificationOptions */ text?: string /** * the notificaton title * * @type {string} * @memberof GMNotificationOptions */ title?: string /** * the image * * @type {string} * @memberof GMNotificationOptions */ image?: string /** * a boolean flag whether to highlight the tab that sends the notfication * * @type {boolean} * @memberof GMNotificationOptions */ highlight?: boolean /** * the time after that the notification will be hidden(ms, 0 = disabled) * * @type {number} * @memberof GMNotificationOptions */ timeout?: number /** * called when the notification is closed(no matter if this was triggered by a timeout or a click) or the tab was highlighted * * @memberof GMNotificationOptions */ ondone?: (click: boolean) => void /** * called in case the user clicks the notification * * @memberof GMNotificationOptions */ onclick?: (click: boolean) => void } /** * GM_setClipboard * * @interface GMSetClipboardInfo */ interface GMSetClipboardInfo { type: string mimetype: string }
the_stack
import {Component, Prop} from "vue-property-decorator"; import DragAwareMixin from "./DragAwareMixin"; import {createDragImage} from "../ts/createDragImage"; import {dnd} from "../ts/DnD"; import scrollparent from './../js/scrollparent' import {cancelScrollAction, performEdgeScroll} from './../js/edgescroller' @Component({}) export default class DragMixin extends DragAwareMixin { @Prop({default: null, type: null}) type: string; @Prop({default: null, type: null}) data: any; @Prop({default: 0.7, type: Number}) dragImageOpacity: any; @Prop({default: false, type: Boolean}) disabled: boolean; @Prop({default: false, type: Boolean}) goBack: boolean; @Prop({required: false, type: String}) handle: string | undefined; @Prop({type: Number, default: 3}) delta: number; @Prop({type: Number, default: 0}) delay: number; @Prop({type: String, default: null}) dragClass: String; @Prop({type: Number, default: 0}) vibration: number; @Prop ({type: Number, default: 100}) scrollingEdgeSize: number; dragInitialised: boolean = false; dragStarted: boolean = false; ignoreNextClick: boolean = false; initialUserSelect = null; downEvent: TouchEvent | MouseEvent = null; startPosition = null; delayTimer = null; scrollContainer = null; onSelectStart (e) { e.stopPropagation(); e.preventDefault(); } performVibration () { // If browser can perform vibration and user has defined a vibration, perform it if (this.vibration > 0 && window.navigator && window.navigator.vibrate) { window.navigator.vibrate(this.vibration); } } onMouseDown (e: MouseEvent | TouchEvent) { let target: HTMLElement; let goodButton: boolean; if (e.type === 'mousedown') { const mouse = e as MouseEvent; target = e.target as HTMLElement; goodButton = mouse.buttons === 1; } else { const touch = e as TouchEvent; target = touch.touches[0].target as HTMLElement; goodButton = true; } if (this.disabled || this.downEvent !== null || !goodButton) { return; } // Check that the target element is eligible for starting a drag // Includes checking against the handle selector // or whether the element contains 'dnd-no-drag' class (which should disable dragging from that // sub-element of a draggable parent) const goodTarget = !target.matches('.dnd-no-drag, .dnd-no-drag *') && ( !this.handle || target.matches(this.handle + ', ' + this.handle + ' *') ); if (!goodTarget) { return; } this.scrollContainer = scrollparent(target); this.initialUserSelect = document.body.style.userSelect; document.documentElement.style.userSelect = 'none'; // Permet au drag de se poursuivre normalement même // quand on quitte un élémént avec overflow: hidden. this.dragStarted = false; this.downEvent = e; if (this.downEvent.type === 'mousedown') { const mouse = event as MouseEvent; this.startPosition = { x: mouse.clientX, y: mouse.clientY }; } else { const touch = event as TouchEvent; this.startPosition = { x: touch.touches[0].clientX, y: touch.touches[0].clientY }; } if (!!this.delay) { this.dragInitialised = false; clearTimeout(this.delayTimer); this.delayTimer = setTimeout(() => { this.dragInitialised = true; this.performVibration(); }, this.delay); } else { this.dragInitialised = true; this.performVibration(); } document.addEventListener('click', this.onMouseClick, true); document.addEventListener('mouseup', this.onMouseUp); document.addEventListener('touchend', this.onMouseUp); document.addEventListener('selectstart', this.onSelectStart); document.addEventListener('keyup', this.onKeyUp); setTimeout(() => { document.addEventListener('mousemove', this.onMouseMove); document.addEventListener('touchmove', this.onMouseMove, {passive: false}); document.addEventListener('easy-dnd-move', this.onEasyDnDMove); }, 0) // Prevents event from bubbling to ancestor drag components and initiate several drags at the same time e.stopPropagation(); // Prevents touchstart event to be converted to mousedown //e.preventDefault(); } // Prevent the user from accidentally causing a click event // if they have just attempted a drag event onMouseClick (e) { if (this.ignoreNextClick) { e.preventDefault(); e.stopPropagation && e.stopPropagation(); e.stopImmediatePropagation && e.stopImmediatePropagation(); this.ignoreNextClick = false; return false; } } onMouseMove (e: TouchEvent | MouseEvent) { // We ignore the mousemove event that follows touchend : if (this.downEvent === null) return; // On touch devices, we ignore fake mouse events and deal with touch events only. if (this.downEvent.type === 'touchstart' && e.type === 'mousemove') return; // Find out event target and pointer position : let target: Element; let x: number; let y: number; if (e.type === 'touchmove') { let touch = e as TouchEvent; x = touch.touches[0].clientX; y = touch.touches[0].clientY; target = document.elementFromPoint(x, y); if (!target) { // Mouse going off screen. Ignore event. return; } } else { let mouse = e as MouseEvent; x = mouse.clientX; y = mouse.clientY; target = mouse.target as Element; } // Distance between current event and start position : let dist = Math.sqrt(Math.pow(this.startPosition.x - x, 2) + Math.pow(this.startPosition.y - y, 2)); // If the drag has not begun yet and distance from initial point is greater than delta, we start the drag : if (!this.dragStarted && dist > this.delta) { // If they have dragged greater than the delta before the delay period has ended, // It means that they attempted to perform another action (such as scrolling) on the page if (!this.dragInitialised) { clearTimeout(this.delayTimer); } else { this.ignoreNextClick = true; this.dragStarted = true; dnd.startDrag(this, this.downEvent, this.startPosition.x, this.startPosition.y, this.type, this.data); document.documentElement.classList.add('drag-in-progress'); } } // Dispatch custom easy-dnd-move event : if (this.dragStarted) { // If cursor/touch is at edge of container, perform scroll if available // If this.dragTop is defined, it means they are dragging on top of another DropList/EasyDnd component // if dropTop is a DropList, use the scrollingEdgeSize of that container if it exists, otherwise use the scrollingEdgeSize of the Drag component const currEdgeSize = this.dragTop && this.dragTop.$props.scrollingEdgeSize !== undefined ? this.dragTop.$props.scrollingEdgeSize : this.scrollingEdgeSize; if (!!currEdgeSize) { const currScrollContainer = this.dragTop ? scrollparent(this.dragTop.$el) : this.scrollContainer; performEdgeScroll(e, currScrollContainer, x, y, currEdgeSize); } else { cancelScrollAction(); } let custom = new CustomEvent("easy-dnd-move", { bubbles: true, cancelable: true, detail: { x, y, native: e } }); target.dispatchEvent(custom); } // Prevent scroll on touch devices if they were performing a drag if (this.dragInitialised && e.cancelable) { e.preventDefault(); } } onEasyDnDMove (e) { dnd.mouseMove(e, null); } onMouseUp (e: MouseEvent | TouchEvent) { // On touch devices, we ignore fake mouse events and deal with touch events only. if (this.downEvent.type === 'touchstart' && e.type === 'mouseup') return; // This delay makes sure that when the click event that results from the mouseup is produced, the drag is // still in progress. So by checking the flag dnd.inProgress, one can tell apart true clicks from drag and // drop artefacts. setTimeout(() => { this.cancelDragActions(); if (this.dragStarted) { dnd.stopDrag(e); } this.finishDrag(); }, 0); } onKeyUp (e: KeyboardEvent) { // If ESC is pressed, cancel the drag if (e.key === 'Escape') { this.cancelDragActions(); setTimeout(() => { dnd.cancelDrag(e); this.finishDrag(); }, 0); } } cancelDragActions () { this.dragInitialised = false; clearTimeout(this.delayTimer); cancelScrollAction(); } finishDrag () { this.downEvent = null; this.scrollContainer = null; if (this.dragStarted) { document.documentElement.classList.remove('drag-in-progress'); } document.removeEventListener('click', this.onMouseClick, true); document.removeEventListener('mousemove', this.onMouseMove); document.removeEventListener('touchmove', this.onMouseMove); document.removeEventListener('easy-dnd-move', this.onEasyDnDMove); document.removeEventListener('mouseup', this.onMouseUp); document.removeEventListener('touchend', this.onMouseUp); document.removeEventListener('selectstart', this.onSelectStart); document.removeEventListener('keyup', this.onKeyUp); document.documentElement.style.userSelect = this.initialUserSelect; } dndDragStart (ev) { if (ev.source === this) { this.$emit('dragstart', ev); } } dndDragEnd (ev) { if (ev.source === this) { this.$emit('dragend', ev); } } created() { dnd.on('dragstart', this.dndDragStart); dnd.on('dragend', this.dndDragEnd); } mounted () { this.$el.addEventListener('mousedown', this.onMouseDown); this.$el.addEventListener('touchstart', this.onMouseDown); } beforeDestroy() { dnd.off('dragstart', this.dndDragStart); dnd.off('dragend', this.dndDragEnd); this.$el.removeEventListener('mousedown', this.onMouseDown); this.$el.removeEventListener('touchstart', this.onMouseDown); } get cssClasses() { let clazz = { 'dnd-drag': true } as any; if (!this.disabled) { return { ...clazz, 'drag-source': this.dragInProgress && this.dragSource === this, 'drag-mode-copy': this.currentDropMode === 'copy', 'drag-mode-cut': this.currentDropMode === 'cut', 'drag-mode-reordering': this.currentDropMode === 'reordering', 'drag-no-handle': !this.handle }; } else { return clazz; } } get currentDropMode() { if (this.dragInProgress && this.dragSource === this) { if (this.dragTop && this.dragTop['dropAllowed']) { if (this.dragTop['reordering']) return 'reordering'; else return this.dragTop['mode']; } else { return null; } } else { return null; } } createDragImage(selfTransform: string) { let image; if (this.$scopedSlots['drag-image']) { let el = this.$refs['drag-image'] as HTMLElement || document.createElement('div'); if (el.childElementCount !== 1) { image = createDragImage(el); } else { image = createDragImage(el.children.item(0) as HTMLElement); } } else { image = createDragImage(this.$el as HTMLElement); image.style.transform = selfTransform; } if (this.dragClass) { image.classList.add(this.dragClass) } image.classList.add('dnd-ghost') image['__opacity'] = this.dragImageOpacity; return image; } }
the_stack
import net from 'net' import { ExtendedSocket } from 'extendedsocket' import { Channel } from 'channel/channel' import { User } from 'user/user' import { UserInventory } from 'user/userinventory' import { UserSession } from 'user/usersession' import { ChannelManager } from 'channel/channelmanager' import { ChatMessageType } from 'packets/definitions' import { FavoritePacketType } from 'packets/definitions' import { OptionPacketType } from 'packets/definitions' import { UnlockCurrency } from 'gametypes/unlockitem' import { InFavoritePacket } from 'packets/in/favorite' import { InFavoriteSetCosmetics } from 'packets/in/favorite/setcosmetics' import { InFavoriteSetLoadout } from 'packets/in/favorite/setloadout' import { InLoginPacket } from 'packets/in/login' import { InOptionPacket } from 'packets/in/option' import { InOptionBuyMenu } from 'packets/in/option/buymenu' import { OutChatPacket } from 'packets/out/chat' import { OutFavoritePacket } from 'packets/out/favorite' import { OutInventoryPacket } from 'packets/out/inventory' import { OutOptionPacket } from 'packets/out/option' import { OutUserInfoPacket } from 'packets/out/userinfo' import { OutUserStartPacket } from 'packets/out/userstart' import { OutUnlockPacket } from 'packets/out/unlock' import { AboutMeHandler } from 'handlers/aboutmehandler' import { UserService } from 'services/userservice' import { ActiveConnections } from 'storage/activeconnections' import { GAME_LOGIN_BAD_PASSWORD, GAME_LOGIN_BAD_USERNAME, GAME_LOGIN_INVALID_USERINFO } from 'gamestrings' // TODO: move this to UserManager, make UserManager not static const aboutMeHandler = new AboutMeHandler() /** * handles the user logic */ export class UserManager { public static async OnSocketClosed(conn: ExtendedSocket): Promise<void> { const session: UserSession = conn.session if (session == null) { return } const curChannel: Channel = session.currentChannel if (curChannel != null) { curChannel.OnUserLeft(conn) } await UserService.Logout(session.user.id) } /** * called when we receive a login request packet * @param loginData the login packet's data * @param connection the login requester's connection * @param server the instance to the server */ public static async onLoginPacket( loginData: Buffer, connection: ExtendedSocket, holepunchPort: number ): Promise<boolean> { const loginPacket: InLoginPacket = new InLoginPacket(loginData) const loggedUserId = await UserService.Login( loginPacket.gameUsername, loginPacket.password ) if (loggedUserId === 0) { this.SendUserDialogBox(connection, GAME_LOGIN_BAD_USERNAME) console.warn( 'Could not create session for user %s', loginPacket.gameUsername ) return false } if (loggedUserId === -1) { this.SendUserDialogBox(connection, GAME_LOGIN_BAD_PASSWORD) console.warn( `Login attempt for user ${loginPacket.gameUsername} failed` ) return false } // clear plain password right away, we don't need it anymore loginPacket.password = null const user: User = await UserService.GetUserById(loggedUserId) if (user == null) { this.SendUserDialogBox(connection, GAME_LOGIN_INVALID_USERINFO) console.error(`Couldn't get user ID ${loggedUserId}'s information`) return false } const newSession: UserSession = new UserSession( user, connection.address() as net.AddressInfo ) connection.session = newSession console.log( `user ${user.username} logged in (uuid: ${connection.uuid})` ) ActiveConnections.Singleton().Add(connection) UserManager.sendUserInfoToSelf(user, connection, holepunchPort) await UserManager.sendInventory(newSession.user.id, connection) ChannelManager.sendChannelListTo(connection) return true } public static async onAboutmePacket( packetData: Buffer, connection: ExtendedSocket ): Promise<boolean> { return await aboutMeHandler.OnPacket(packetData, connection) } /** * listens for option packets * @param optionData the packet's data * @param conn the sender's connection */ public static async onOptionPacket( optionData: Buffer, conn: ExtendedSocket ): Promise<boolean> { if (conn.session == null) { console.warn( `connection ${conn.uuid} sent an option packet without a session` ) return false } const optPacket: InOptionPacket = new InOptionPacket(optionData) switch (optPacket.packetType) { case OptionPacketType.SetBuyMenu: return this.onOptionSetBuyMenu(optPacket, conn) } console.warn( 'UserManager::onOptionPacket: unknown packet type %i', optPacket.packetType ) return false } public static async onOptionSetBuyMenu( optPacket: InOptionPacket, conn: ExtendedSocket ): Promise<boolean> { const buyMenuData: InOptionBuyMenu = new InOptionBuyMenu(optPacket) const session: UserSession = conn.session if (session == null) { console.warn(`Could not get connection "${conn.uuid}"'s session`) return false } console.log(`Setting user ID ${session.user.id}'s buy menu`) await UserInventory.setBuyMenu(session.user.id, buyMenuData.buyMenu) return true } public static async onFavoritePacket( favoriteData: Buffer, sourceConn: ExtendedSocket ): Promise<boolean> { if (sourceConn.session == null) { console.warn( `connection ${sourceConn.uuid} sent a favorite packet without a session` ) return false } const favPacket: InFavoritePacket = new InFavoritePacket(favoriteData) switch (favPacket.packetType) { case FavoritePacketType.SetLoadout: return this.onFavoriteSetLoadout(favPacket, sourceConn) case FavoritePacketType.SetCosmetics: return this.onFavoriteSetCosmetics(favPacket, sourceConn) } console.warn( 'UserManager::onFavoritePacket: unknown packet type %i', favPacket.packetType ) return false } public static async onFavoriteSetLoadout( favPacket: InFavoritePacket, sourceConn: ExtendedSocket ): Promise<boolean> { const loadoutData: InFavoriteSetLoadout = new InFavoriteSetLoadout( favPacket ) const session: UserSession = sourceConn.session if (session == null) { console.warn( `Could not get connection "${sourceConn.uuid}"'s session` ) return false } const loadoutNum: number = loadoutData.loadout const slot: number = loadoutData.weaponSlot const itemId: number = loadoutData.itemId console.log( `Setting user ID ${session.user.id}'s new weapon ${itemId} to slot ${slot} in loadout ${loadoutNum}` ) await UserInventory.setLoadoutWeapon( session.user.id, loadoutNum, slot, itemId ) return true } public static async onFavoriteSetCosmetics( favPacket: InFavoritePacket, sourceConn: ExtendedSocket ): Promise<boolean> { const cosmeticsData: InFavoriteSetCosmetics = new InFavoriteSetCosmetics( favPacket ) const session: UserSession = sourceConn.session if (session == null) { console.warn( `Could not get connection "${sourceConn.uuid}"'s session` ) return false } const slot: number = cosmeticsData.slot const itemId: number = cosmeticsData.itemId console.debug( `Setting user ID ${session.user.id}'s new cosmetic ${itemId} to slot ${slot}` ) await UserInventory.setCosmeticSlot(session.user.id, slot, itemId) return true } /** * send an user's info to itself * @param user the target user's object * @param conn the target user's connection * @param holepunchPort the master server's UDP holepunching port */ private static sendUserInfoToSelf( user: User, conn: ExtendedSocket, holepunchPort: number ): void { conn.send( new OutUserStartPacket( user.id, user.username, user.playername, holepunchPort ) ) conn.send(OutUserInfoPacket.fullUserUpdate(user)) } /** * sends an user's inventory to itself * @param userId the target user's ID * @param conn the target user's connection */ private static async sendInventory( userId: number, conn: ExtendedSocket ): Promise<void> { const [inventory, cosmetics, loadouts, buyMenu] = await Promise.all([ UserInventory.getInventory(userId), UserInventory.getCosmetics(userId), UserInventory.getAllLoadouts(userId), UserInventory.getBuyMenu(userId) ]) if ( inventory == null || cosmetics == null || loadouts == null || buyMenu == null ) { return } conn.send(OutInventoryPacket.createInventory(inventory.items)) /* const defaultInvReply: Buffer = new OutInventoryPacket(conn).addInventory(inventory.getDefaultInventory()) conn.send(defaultInvReply)*/ /* const achievementReply: Buffer = Buffer.from([0x55, 0x12, 0x23, 0x00, 0x60, 0x04, 0x2C, 0x00, 0x02, 0x02, 0x40, 0x00, 0x00, 0x00, 0x03, 0xDE, 0x07, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0xD8, 0x07, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xDD, 0x07, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00]) conn.sendBuffer(achievementReply) const achievementReply2: Buffer = Buffer.from([0x55, 0x13, 0x2B, 0x00, 0x60, 0x04, 0x2D, 0x00, 0x02, 0x02, 0x40, 0x00, 0x00, 0x00, 0x04, 0x40, 0x1F, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x42, 0x1F, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x44, 0x1F, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x54, 0xC3, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00]) conn.sendBuffer(achievementReply2) const achievementReply3: Buffer = Buffer.from([0x55, 0x14, 0x2B, 0x00, 0x60, 0x04, 0x2E, 0x00, 0x02, 0x02, 0x40, 0x00, 0x00, 0x00, 0x04, 0x54, 0xC3, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x36, 0x21, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xE6, 0x07, 0x00, 0x00, 0x01, 0x00, 0x07, 0x00, 0xE4, 0x07, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00]) conn.sendBuffer(achievementReply3) */ conn.send(OutUnlockPacket.createUnlockInfo([], [])) conn.send( OutFavoritePacket.setCosmetics( cosmetics.ct_item, cosmetics.ter_item, cosmetics.head_item, cosmetics.glove_item, cosmetics.back_item, cosmetics.steps_item, cosmetics.card_item, cosmetics.spray_item ) ) conn.send(OutFavoritePacket.setLoadout(loadouts)) conn.send(OutOptionPacket.setBuyMenu(buyMenu)) } private static SendUserDialogBox(userConn: ExtendedSocket, msg: string) { const badDialogData: OutChatPacket = OutChatPacket.systemMessage( msg, ChatMessageType.DialogBox ) userConn.send(badDialogData) } }
the_stack
import { POP_UI_BASE } from "../../common/ui/pop_ui_base"; import BallItem, { EnumBallStatus } from "../item/BallItem"; import GameConst from "../GameConst"; import GameModel from "../model/GameModel"; import BrickItem from "../item/BrickItem"; import { RandomUtil } from "../../common/random/RandomUtil"; import { EventDispatch, Event_Name } from "../../common/event/EventDispatch"; import * as ui from "../../common/ui/pop_mgr"; import { AudioPlayer, AUDIO_CONFIG } from "../../common/audio/AudioPlayer"; import { gen_handler } from "../../common/util"; import { loader_mgr } from "../../common/loader/loader_mgr"; import { Tween, Ease } from "../../common/tween/Tween"; const { ccclass, property } = cc._decorator; @ccclass export default class GameView extends POP_UI_BASE { @property(cc.Node) bg: cc.Node = null; @property(cc.Node) node_top: cc.Node = null; @property(cc.Node) cannon_head: cc.Node = null; @property(cc.Node) node_physics: cc.Node = null; @property(cc.Label) lb_ball_count: cc.Label = null; @property(cc.Label) lb_ball_power: cc.Label = null; @property(cc.Node) guide_hand: cc.Node = null; @property(cc.Node) node_freeze: cc.Node = null; @property(cc.Label) lb_score: cc.Label = null; @property(cc.Node) node_power_progress: cc.Node = null; @property([cc.Node]) power_txts: cc.Node[] = []; @property(cc.ParticleSystem) particleSystem: cc.ParticleSystem = null; @property([cc.Prefab]) balls_ins: cc.Prefab[] = []; @property([cc.Prefab]) bricks_ins: cc.Prefab[] = []; @property(cc.Node) node_star_img: cc.Node = null; @property(cc.Prefab) star_ins: cc.Prefab = null; private _star_pool: cc.Node[] = []; private _star_num = 0; private balls_pool: cc.Node[][] = []; private bricks_pool: cc.Node[][] = []; private balls_in_game: BallItem[] = []; private bricks_in_game: BrickItem[] = []; private _updateDt: number = 0; private _brick_speed: number = 1; private _moved_length = 0; private _moved_level = 0; private _power_type = 0; private _isGameOver = false; onLoad() { this.bg.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this); cc.director.getPhysicsManager().enabled = true; // cc.director.getPhysicsManager().debugDrawFlags = 1; for (let i = 0, len = this.balls_ins.length; i < len;) { this.balls_pool[i++] = []; } for (let i = 0, len = this.bricks_ins.length; i < len;) { this.bricks_pool[i++] = []; } cc.director.getPhysicsManager().enabledAccumulator = true; } private onTouchMove(param: cc.Event.EventTouch) { const deltaX = param.getDeltaX(); const deltaY = param.getDeltaY(); const deltaR = Math.sqrt(deltaX * deltaX + deltaY * deltaY) * 0.3; const sign = Math.sign(deltaX); // 2.1.0 后改 rotation --> -angle let angle = -this.cannon_head.angle + deltaR * sign; angle = Math.abs(angle) >= 85 ? Math.sign(angle) * 85 : angle; this.cannon_head.angle = -angle; } update(dt) { if (this._isGameOver) { return; } //power type if (this._power_type > 0) { this.node_power_progress.width -= 1.5; if (this.node_power_progress.active && this.node_power_progress.width <= 0) { this.updateGamePowerType(0); } switch (this._power_type) { case 3: { this._brick_speed = 0; break; } } } this._updateDt++; this._moved_length += this._brick_speed; //fire ball if (this._updateDt % GameModel.ins().fireBallDt === 0 || this._power_type === 2) { this.balls_in_game.some((item) => { if ((item.ball_status === EnumBallStatus.onReady) && (item.ball_type === 0 || this._power_type === 2)) { item.power_scale = this._power_type === 1 ? 2 : 1; item.fireBall(-this.cannon_head.angle); return true; } return false; }) } //add bricks const brick_radius = GameConst.ins().brick_radius; const ball_power = GameModel.ins().ball_power; const new_level = Math.floor(this._moved_length / 4 / brick_radius); if (new_level > this._moved_level) { this._moved_level++; let balls_in_game_length = this.balls_in_game.length / (this._power_type === 2 ? 2 : 1); const maxHp = Math.ceil(balls_in_game_length * ball_power * 0.5 + this._moved_level * ball_power * 1.2); const brick_type_percent = GameConst.ins().brick_type_percent; let big_j = -999; let item_i = -999, item_j = -999; if (this._moved_level % 12 === 0) { //big big_j = RandomUtil.ins().randomNum(-2, 3); this.createBrick(-brick_radius + big_j * brick_radius * 2 + GameConst.ins().brick_init_x, brick_radius + GameConst.ins().brick_init_y, RandomUtil.ins().randomNum(maxHp * 3, maxHp * 6), RandomUtil.ins().randomNum(14, 16), 10); } if (this._moved_level % 11 === 0) { //道具 item_i = RandomUtil.ins().randomNum(0, 1); item_j = RandomUtil.ins().randomNum(-3, 3); } for (let i = 0; i < 2; i++) { for (let j = -3; j < 4; j++) { if (j === big_j || j === big_j - 1) { //big } else { let hp = (i === item_i && j === item_j) ? RandomUtil.ins().randomNum(ball_power, Math.ceil(maxHp / 2)) : RandomUtil.ins().randomNum(-Math.round(maxHp / (this._moved_level % 5 + 1)), maxHp); let brick_type = (i === item_i && j === item_j) ? RandomUtil.ins().randomNum(11, 13) : (brick_type_percent[RandomUtil.ins().randomNum(0, brick_type_percent.length - 1)]); if (hp >= ball_power) { this.createBrick(j * brick_radius * 2 + GameConst.ins().brick_init_x, i * brick_radius * 2 + GameConst.ins().brick_init_y, hp, brick_type, Math.ceil(hp * 10 / maxHp)); } } } } } //update bricks let brick_min_y = 9999; for (let index = 0, len = this.bricks_in_game.length; index < len; index++) { const element = this.bricks_in_game[index]; if (element && element.node) { const brick = element.node; if (element.hp <= 0 || !brick.active) { //remove if (this._updateDt % 60 === 0) { element.reset(); this.bricks_in_game.splice(index, 1); this.bricks_pool[element.brick_type].push(brick); index--; } } else { //update pos brick.y -= this._brick_speed; if (brick.y - element.brick_radius_mul * brick_radius <= GameConst.ins().ball_init_y) { this.gameOver(); return; } if (brick.y < brick_min_y) { brick_min_y = brick.y; } } } } this._brick_speed = (brick_min_y > GameConst.ins().ball_init_y + brick_radius * 7) ? 1 : ((brick_min_y > GameConst.ins().ball_init_y + brick_radius * 5) ? 0.9 : 0.6); } // 创建小球 private createBall(x = GameConst.ins().ball_init_x, y = GameConst.ins().ball_init_y, status = EnumBallStatus.onReady, ball_type = 0) { let ball = this.balls_pool[ball_type].shift(); if (!ball) { ball = cc.instantiate(this.balls_ins[ball_type]); this.node_physics.addChild(ball); } const item = ball.getComponent(BallItem); item.init(x, y, status); ball.active = true; this.balls_in_game.unshift(item); this.lb_ball_count.string = `${this.balls_in_game.length / 2}`; if (ball_type === 0) { this.createBall(GameConst.ins().ball_init_x, GameConst.ins().ball_init_y, EnumBallStatus.onReady, 1); } } //创建砖块 private createBrick(x = GameConst.ins().brick_init_x, y = GameConst.ins().brick_init_y, hp = 1, brick_type = 0, colors_num = 1) { if (brick_type === 7 && this.balls_in_game.length > 200) { brick_type = 0; } let brick = this.bricks_pool[brick_type].shift(); if (!brick) { brick = cc.instantiate(this.bricks_ins[brick_type]); this.node_physics.addChild(brick); } const item = brick.getComponent(BrickItem); brick.active = true; brick.x = x; brick.y = y; item.init(colors_num, hp); this.bricks_in_game.push(item); } private resetGame() { this.node_physics.active = true; this.cannon_head.angle = 10 - Math.random() * 20; cc.director.getPhysicsManager().enabled = true; this._updateDt = 0; this._moved_length = 0; this._moved_level = 0; this._isGameOver = false; this.updateGamePowerType(0); GameModel.ins().reset(); const ball_init_count = GameModel.ins().ball_init_count; for (let index = 0; index < ball_init_count; index++) { this.createBall(); } const brick_radius = GameConst.ins().brick_radius; for (let i = 0; i < 2; i++) { for (let j = -3; j < 4; j++) { let hp = (i + 1) * GameModel.ins().ball_power + (ball_init_count - 4); hp = hp < 0 ? 1 : hp; this.createBrick(j * brick_radius * 2 + GameConst.ins().brick_init_x, i * brick_radius * 2 + GameConst.ins().brick_init_y, hp); } } this._star_num = GameModel.ins().ball_power; this.lb_ball_power.string = `${this._star_num}`; } private clearGame() { this.node_physics.active = false; cc.director.getPhysicsManager().enabled = false; this.balls_in_game.forEach((value) => { value.reset(); this.balls_pool[value.ball_type].push(value.node); }) this.balls_in_game = []; this.bricks_in_game.forEach((value) => { value.reset(); this.bricks_pool[value.brick_type].push(value.node); }) this.bricks_in_game = []; GameModel.ins().reset(); } private updateScore(old?: number, newValue?: number) { const score = GameModel.ins().score; this.lb_score.string = `${score}`; } private updateBallPower(old?: number, newValue?: number) { const ball_power = GameModel.ins().ball_power; // this.lb_ball_power.string = `${ball_power}`; } //星星特效 private updateStarNumGetEffect(x: number, y: number, count: number) { const targetPos = this.node_top.convertToNodeSpaceAR(this.node_star_img.convertToWorldSpaceAR(cc.v2(0, 0))); for (let index = 0; index < count; index++) { let star_item = this._star_pool.shift(); if (!star_item) { star_item = cc.instantiate(this.star_ins); this.node_top.addChild(star_item); } star_item.x = x; star_item.y = y; star_item.angle = 0; star_item.active = true; Tween.get(star_item).to({ angle: 720, x: targetPos.x, y: targetPos.y }, 800 + 100 * index, Ease.getBackInOut(1.2)).call(() => { star_item.active = false; this._star_pool.push(star_item); Tween.get(this.node_star_img).to({ scale: 1.2 }, 300).to({ scale: 1 }, 300, Ease.backInOut).call(() => { this._star_num += 1; this.lb_ball_power.string = `${this._star_num}`; }) }) } } //砖块消除特效 private _brick_img_pool: cc.Node[] = []; private playBrickDeleteEffect(x: number, y: number, color: cc.Color) { const theme_cfg = GameConst.ins().theme_config[0]; if (theme_cfg) { loader_mgr.get_inst().loadAsset('texture/plist/customize', gen_handler((res: cc.SpriteAtlas) => { const spriteFrame = res.getSpriteFrame(theme_cfg.theme); if (spriteFrame) { for (let index = 0; index < 9; index++) { const i = index % 3 - 1.5; const j = Math.floor(index / 3) - 1.5; const targetPosX = x + i * (100 + 150 * Math.random()); const targetPosY = y + j * (100 + 150 * Math.random()); let img = this._brick_img_pool.shift(); if (!img) { img = new cc.Node(); img.addComponent(cc.Sprite); this.node_physics.addChild(img); } img.active = true; img.angle = 0; img.getComponent(cc.Sprite).spriteFrame = spriteFrame; img.color = color; const size = Math.random() * 50 + 50; img.width = img.height = size; img.x = x; img.y = y; Tween.get(img).to({ x: targetPosX, y: targetPosY, width: size / 3, height: size / 3, angle: 1000 * Math.random() }, Math.random() * 500 + 500).call(() => { img.active = false; this._brick_img_pool.push(img); }) } } else { } }), cc.SpriteAtlas); } } //道具效果 private updateGamePowerType(power = 0) { if (power > 0) { if (this._power_type === 0) { this.node_power_progress.active = true; this.node_power_progress.width = 640; this._power_type = power; switch (power) { case 2: { this.cannon_head.scale = 2; break; } case 3: { this.node_freeze.active = true; break; } } this.lb_ball_count.node.color = this.node_power_progress.color = [cc.Color.WHITE, cc.Color.RED, cc.Color.YELLOW, cc.Color.GRAY][power] || cc.Color.WHITE; const power_txt = this.power_txts[power]; if (power_txt) { power_txt.active = true; power_txt.stopAllActions(); power_txt.opacity = 0; const moveY = 100; power_txt.runAction(cc.sequence(cc.fadeIn(1), cc.moveBy(0.5, 0, moveY), cc.delayTime(0.5), cc.fadeOut(1), cc.callFunc(() => { if (power_txt) { power_txt.y -= moveY; power_txt.active = false; } }))) } AudioPlayer.ins().play_sound(AUDIO_CONFIG.Audio_levelup); } } else { this.node_freeze.active = this.node_power_progress.active = false; this.node_power_progress.width = 640; this.lb_ball_count.node.color = cc.Color.WHITE; this.cannon_head.scale = 1; switch (this._power_type) { case 1: { break; } case 2: { break; } } this._power_type = power; } } private gameRelive() { GameModel.ins().revive_times++; this.bricks_in_game.forEach((value) => { value.reset(); this.bricks_pool[value.brick_type].push(value.node); }) this.bricks_in_game = []; this._isGameOver = false; cc.director.getPhysicsManager().enabled = true; AudioPlayer.ins().play_music(AUDIO_CONFIG.Audio_Bgm); } private gameOver() { this._isGameOver = true; cc.director.getPhysicsManager().enabled = false; ui.pop_mgr.get_inst().show(ui.UI_CONFIG.result); } on_show() { super.on_show(); EventDispatch.ins().add(Event_Name.GAME_CREATE_BALL, this.createBall, this); EventDispatch.ins().add(Event_Name.GAME_RELIVE, this.gameRelive, this); EventDispatch.ins().add(Event_Name.GAME_ON_TOUCH_MOVE, this.onTouchMove, this); EventDispatch.ins().add(Event_Name.GAME_POWER_TYPE_CHANGED, this.updateGamePowerType, this); EventDispatch.ins().add(Event_Name.GAME_SCORE_CHANGED, this.updateScore, this, true); EventDispatch.ins().add(Event_Name.GAME_BALL_POWER_CHANGED, this.updateBallPower, this, true); EventDispatch.ins().add(Event_Name.GAME_PLAY_BRICK_REMOVE_EFFECT, this.playBrickDeleteEffect, this); EventDispatch.ins().add(Event_Name.GAME_STAR_GET_EFFECT, this.updateStarNumGetEffect, this); AudioPlayer.ins().play_music(AUDIO_CONFIG.Audio_Bgm); const duration = 0.5; this.guide_hand.active = true; this.guide_hand.stopAllActions(); this.guide_hand.runAction(cc.sequence(cc.repeat(cc.sequence(cc.moveBy(duration, 100, 0), cc.moveBy(duration, -100, 0), cc.moveBy(duration, -100, 0), cc.moveBy(duration, 100, 0)), 5), cc.callFunc(() => { if (this.guide_hand) this.guide_hand.active = false; }))); this.btn_close.node.active = false; setTimeout(() => { this.btn_close.node.active = true; }, 5000); this.resetGame(); } onCloseBtnTouch() { super.onCloseBtnTouch(); } on_hide() { EventDispatch.ins().remove(Event_Name.GAME_CREATE_BALL, this.createBall); EventDispatch.ins().remove(Event_Name.GAME_RELIVE, this.gameRelive); EventDispatch.ins().remove(Event_Name.GAME_ON_TOUCH_MOVE, this.onTouchMove); EventDispatch.ins().remove(Event_Name.GAME_POWER_TYPE_CHANGED, this.updateGamePowerType); EventDispatch.ins().remove(Event_Name.GAME_SCORE_CHANGED, this.updateScore); EventDispatch.ins().remove(Event_Name.GAME_PLAY_BRICK_REMOVE_EFFECT, this.playBrickDeleteEffect); EventDispatch.ins().remove(Event_Name.GAME_STAR_GET_EFFECT, this.updateStarNumGetEffect); AudioPlayer.ins().stop_music(); this.guide_hand.stopAllActions(); this.clearGame(); super.on_hide(); } } // https://github.com/baiyuwubing/firing_balls // qq 交流群 859642112
the_stack
import { Reader, IReaderHooks, ParseError } from "./Common/Reader"; import { ExpressionParser, IExpressionParserHooks } from "./Common/ExpressionParser"; import { NodeManager } from "./Common/NodeManager"; import { IParser } from "./Common/IParser"; import { AnyType, VoidType, UnresolvedType, LambdaType } from "../One/Ast/AstTypes"; import { Expression, TemplateString, TemplateStringPart, NewExpression, Identifier, CastExpression, NullLiteral, BooleanLiteral, BinaryExpression, UnaryExpression, UnresolvedCallExpression, PropertyAccessExpression, InstanceOfExpression, RegexLiteral, AwaitExpression, ParenthesizedExpression, UnresolvedNewExpression } from "../One/Ast/Expressions"; import { VariableDeclaration, Statement, UnsetStatement, IfStatement, WhileStatement, ForeachStatement, ForStatement, ReturnStatement, ThrowStatement, BreakStatement, ExpressionStatement, ForeachVariable, ForVariable, DoStatement, ContinueStatement, TryStatement, CatchVariable, Block } from "../One/Ast/Statements"; import { Class, Method, MethodParameter, Field, Visibility, SourceFile, Property, Constructor, Interface, EnumMember, Enum, IMethodBase, Import, SourcePath, ExportScopeRef, Package, Lambda, UnresolvedImport, GlobalFunction } from "../One/Ast/Types"; import { IType } from "../One/Ast/Interfaces"; class TypeAndInit { constructor( public type: IType, public init: Expression) { } } class MethodSignature { constructor( public params: MethodParameter[], public fields: Field[], public body: Block, public returns: IType, public superCallArgs: Expression[]) { } } export class TypeScriptParser2 implements IParser, IExpressionParserHooks, IReaderHooks { context: string[] = []; reader: Reader; expressionParser: ExpressionParser; nodeManager: NodeManager; exportScope: ExportScopeRef; missingReturnTypeIsVoid = false; allowDollarIds = false; // TODO: hack to support templates constructor(source: string, public path: SourcePath = null) { this.reader = new Reader(source); this.reader.hooks = this; this.nodeManager = new NodeManager(this.reader); this.expressionParser = this.createExpressionParser(this.reader, this.nodeManager); this.exportScope = this.path !== null ? new ExportScopeRef(this.path.pkg.name, this.path.path !== null ? this.path.path.replace(/\.ts$/, "") : null) : null; } createExpressionParser(reader: Reader, nodeManager: NodeManager = null): ExpressionParser { const expressionParser = new ExpressionParser(reader, this, nodeManager); expressionParser.stringLiteralType = new UnresolvedType("TsString", []); expressionParser.numericLiteralType = new UnresolvedType("TsNumber", []); return expressionParser; } errorCallback(error: ParseError): void { throw new Error(`[TypeScriptParser] ${error.message} at ${error.cursor.line}:${error.cursor.column} (context: ${this.context.join("/")})\n${this.reader.linePreview(error.cursor)}`); } infixPrehook(left: Expression): Expression { if (left instanceof PropertyAccessExpression && this.reader.peekRegex("<[A-Za-z0-9_<>]*?>\\(") !== null) { const typeArgs = this.parseTypeArgs(); this.reader.expectToken("("); const args = this.expressionParser.parseCallArguments(); return new UnresolvedCallExpression(left, typeArgs, args); } else if (this.reader.readToken("instanceof")) { const type = this.parseType(); return new InstanceOfExpression(left, type); } else if (left instanceof Identifier && this.reader.readToken("=>")) { const block = this.parseLambdaBlock(); return new Lambda([new MethodParameter(left.text, null, null, null)], block); } return null; } parseLambdaParams(): MethodParameter[] { if (!this.reader.readToken("(")) return null; const params: MethodParameter[] = []; if (!this.reader.readToken(")")) { do { const paramName = this.reader.expectIdentifier(); const type = this.reader.readToken(":") ? this.parseType() : null; params.push(new MethodParameter(paramName, type, null, null)); } while (this.reader.readToken(",")); this.reader.expectToken(")"); } return params; } parseType(): IType { if (this.reader.readToken("{")) { this.reader.expectToken("["); this.reader.readIdentifier(); this.reader.expectToken(":"); this.reader.expectToken("string"); this.reader.expectToken("]"); this.reader.expectToken(":"); const mapValueType = this.parseType(); this.reader.readToken(";"); this.reader.expectToken("}"); return new UnresolvedType("TsMap", [mapValueType]); } if (this.reader.peekToken("(")) { const params = this.parseLambdaParams(); this.reader.expectToken("=>"); const returnType = this.parseType(); return new LambdaType(params, returnType); } const typeName = this.reader.expectIdentifier(); const startPos = this.reader.prevTokenOffset; let type: IType; if (typeName === "string") { type = new UnresolvedType("TsString", []); } else if (typeName === "boolean") { type = new UnresolvedType("TsBoolean", []); } else if (typeName === "number") { type = new UnresolvedType("TsNumber", []); } else if (typeName === "any") { type = AnyType.instance; } else if (typeName === "void") { type = VoidType.instance; } else { const typeArguments = this.parseTypeArgs(); type = new UnresolvedType(typeName, typeArguments); } this.nodeManager.addNode(type, startPos); while (this.reader.readToken("[]")) { type = new UnresolvedType("TsArray", [type]); this.nodeManager.addNode(type, startPos); } return type; } parseExpression(): Expression { return this.expressionParser.parse(); } unaryPrehook(): Expression { if (this.reader.readToken("null")) { return new NullLiteral(); } else if (this.reader.readToken("true")) { return new BooleanLiteral(true); } else if (this.reader.readToken("false")) { return new BooleanLiteral(false); } else if (this.reader.readToken("`")) { const parts: TemplateStringPart[] = []; let litPart = ""; while (true) { if (this.reader.readExactly("`")) { if (litPart !== "") { parts.push(TemplateStringPart.Literal(litPart)); litPart = ""; } break; } else if (this.reader.readExactly("${")) { if (litPart !== "") { parts.push(TemplateStringPart.Literal(litPart)); litPart = ""; } const expr = this.parseExpression(); parts.push(TemplateStringPart.Expression(expr)); this.reader.expectToken("}"); } else if (this.allowDollarIds && this.reader.readExactly("$")) { if (litPart !== "") { parts.push(TemplateStringPart.Literal(litPart)); litPart = ""; } const id = this.reader.readIdentifier(); parts.push(TemplateStringPart.Expression(new Identifier(id))); } else if (this.reader.readExactly("\\")) { const chr = this.reader.readChar(); if (chr === "n") litPart += "\n"; else if (chr === "r") litPart += "\r"; else if (chr === "t") litPart += "\t"; else if (chr === "`") litPart += "`"; else if (chr === "$") litPart += "$"; else if (chr === "\\") litPart += "\\"; else this.reader.fail("invalid escape", this.reader.offset - 1); } else { const chr = this.reader.readChar(); const chrCode = chr.charCodeAt(0); if (!(32 <= chrCode && chrCode <= 126) || chr === "`" || chr === "\\") this.reader.fail(`not allowed character (code=${chrCode})`, this.reader.offset - 1); litPart += chr; } } return new TemplateString(parts); } else if (this.reader.readToken("new")) { const type = this.parseType(); if (type instanceof UnresolvedType) { this.reader.expectToken("("); const args = this.expressionParser.parseCallArguments(); return new UnresolvedNewExpression(type, args); } else throw new Error(`[TypeScriptParser2] Expected UnresolvedType here!`); } else if (this.reader.readToken("<")) { const newType = this.parseType(); this.reader.expectToken(">"); const expression = this.parseExpression(); return new CastExpression(newType, expression); } else if (this.reader.readToken("/")) { let pattern = ""; while (true) { const chr = this.reader.readChar(); if (chr === "\\") { const chr2 = this.reader.readChar(); pattern += chr2 === "/" ? "/" : "\\" + chr2; } else if (chr === "/") { break; } else pattern += chr; } const modifiers = this.reader.readModifiers(["g", "i"]); return new RegexLiteral(pattern, modifiers.includes("i"), modifiers.includes("g")); } else if (this.reader.readToken("typeof")) { const expr = this.expressionParser.parse(this.expressionParser.prefixPrecedence); this.reader.expectToken("==="); const check = this.reader.expectString(); let tsType: string = null; if (check === "string") tsType = "TsString"; else if (check === "boolean") tsType = "TsBoolean"; else if (check === "object") tsType = "Object"; else if (check === "function") // TODO: ??? tsType = "Function"; else if (check === "undefined") // TODO: ??? tsType = "Object"; // ignore for now else this.reader.fail("unexpected typeof comparison"); return new InstanceOfExpression(expr, new UnresolvedType(tsType, [])); } else if (this.reader.peekRegex("\\([A-Za-z0-9_]+\\s*[:,]|\\(\\)") !== null) { const params = this.parseLambdaParams(); this.reader.expectToken("=>"); const block = this.parseLambdaBlock(); return new Lambda(params, block); } else if (this.reader.readToken("await")) { const expression = this.parseExpression(); return new AwaitExpression(expression); } const mapLiteral = this.expressionParser.parseMapLiteral(); if (mapLiteral != null) return mapLiteral; const arrayLiteral = this.expressionParser.parseArrayLiteral(); if (arrayLiteral != null) return arrayLiteral; return null; } parseLambdaBlock(): Block { const block = this.parseBlock(); if (block !== null) return block; let returnExpr = this.parseExpression(); if (returnExpr instanceof ParenthesizedExpression) returnExpr = returnExpr.expression; return new Block([new ReturnStatement(returnExpr)]); } parseTypeAndInit(): TypeAndInit { const type = this.reader.readToken(":") ? this.parseType() : null; const init = this.reader.readToken("=") ? this.parseExpression() : null; if (type === null && init === null) this.reader.fail(`expected type declaration or initializer`); return new TypeAndInit(type, init); } expectBlockOrStatement(): Block { const block = this.parseBlock(); if (block !== null) return block; const stmts: Statement[] = []; const stmt = this.expectStatement(); if (stmt !== null) stmts.push(stmt); return new Block(stmts); } expectStatement(): Statement { let statement: Statement = null; const leadingTrivia = this.reader.readLeadingTrivia(); const startPos = this.reader.offset; let requiresClosing = true; const varDeclMatches = this.reader.readRegex("(const|let|var)\\b"); if (varDeclMatches !== null) { const name = this.reader.expectIdentifier("expected variable name"); const typeAndInit = this.parseTypeAndInit(); statement = new VariableDeclaration(name, typeAndInit.type, typeAndInit.init); } else if (this.reader.readToken("delete")) { statement = new UnsetStatement(this.parseExpression()); } else if (this.reader.readToken("if")) { requiresClosing = false; this.reader.expectToken("("); const condition = this.parseExpression(); this.reader.expectToken(")"); const then = this.expectBlockOrStatement(); const else_ = this.reader.readToken("else") ? this.expectBlockOrStatement() : null; statement = new IfStatement(condition, then, else_); } else if (this.reader.readToken("while")) { requiresClosing = false; this.reader.expectToken("("); const condition = this.parseExpression(); this.reader.expectToken(")"); const body = this.expectBlockOrStatement(); statement = new WhileStatement(condition, body); } else if (this.reader.readToken("do")) { requiresClosing = false; const body = this.expectBlockOrStatement(); this.reader.expectToken("while"); this.reader.expectToken("("); const condition = this.parseExpression(); this.reader.expectToken(")"); statement = new DoStatement(condition, body); } else if (this.reader.readToken("for")) { requiresClosing = false; this.reader.expectToken("("); const varDeclMod = this.reader.readAnyOf(["const", "let", "var"]); const itemVarName = varDeclMod === null ? null : this.reader.expectIdentifier(); if (itemVarName !== null && this.reader.readToken("of")) { const items = this.parseExpression(); this.reader.expectToken(")"); const body = this.expectBlockOrStatement(); statement = new ForeachStatement(new ForeachVariable(itemVarName), items, body); } else { let forVar: ForVariable = null; if (itemVarName !== null) { const typeAndInit = this.parseTypeAndInit(); forVar = new ForVariable(itemVarName, typeAndInit.type, typeAndInit.init); } this.reader.expectToken(";"); const condition = this.parseExpression(); this.reader.expectToken(";"); const incrementor = this.parseExpression(); this.reader.expectToken(")"); const body = this.expectBlockOrStatement(); statement = new ForStatement(forVar, condition, incrementor, body); } } else if (this.reader.readToken("try")) { const block = this.expectBlock("try body is missing"); let catchVar: CatchVariable = null; let catchBody: Block = null; if (this.reader.readToken("catch")) { this.reader.expectToken("("); catchVar = new CatchVariable(this.reader.expectIdentifier(), null); this.reader.expectToken(")"); catchBody = this.expectBlock("catch body is missing"); } const finallyBody = this.reader.readToken("finally") ? this.expectBlock() : null; return new TryStatement(block, catchVar, catchBody, finallyBody); } else if (this.reader.readToken("return")) { const expr = this.reader.peekToken(";") ? null : this.parseExpression(); statement = new ReturnStatement(expr); } else if (this.reader.readToken("throw")) { const expr = this.parseExpression(); statement = new ThrowStatement(expr); } else if (this.reader.readToken("break")) { statement = new BreakStatement(); } else if (this.reader.readToken("continue")) { statement = new ContinueStatement(); } else if (this.reader.readToken("debugger;")) { return null; } else { const expr = this.parseExpression(); statement = new ExpressionStatement(expr); const isBinarySet = expr instanceof BinaryExpression && ["=", "+=", "-="].includes(expr.operator); const isUnarySet = expr instanceof UnaryExpression && ["++", "--"].includes(expr.operator); if (!(expr instanceof UnresolvedCallExpression || isBinarySet || isUnarySet || expr instanceof AwaitExpression)) this.reader.fail("this expression is not allowed as statement"); } if (statement === null) this.reader.fail("unknown statement"); statement.leadingTrivia = leadingTrivia; this.nodeManager.addNode(statement, startPos); const statementLastLine = this.reader.wsLineCounter; if (!this.reader.readToken(";") && requiresClosing && this.reader.wsLineCounter === statementLastLine) this.reader.fail("statement is not closed", this.reader.wsOffset); return statement; } parseBlock(): Block { if (!this.reader.readToken("{")) return null; const startPos = this.reader.prevTokenOffset; const statements: Statement[] = []; if (!this.reader.readToken("}")) { do { const statement = this.expectStatement(); if (statement !== null) statements.push(statement); } while(!this.reader.readToken("}")); } const block = new Block(statements); this.nodeManager.addNode(block, startPos); return block; } expectBlock(errorMsg: string = null): Block { const block = this.parseBlock(); if (block === null) this.reader.fail(errorMsg || "expected block here"); return block; } parseTypeArgs(): IType[] { const typeArguments: IType[] = []; if (this.reader.readToken("<")) { do { const generics = this.parseType(); typeArguments.push(generics); } while(this.reader.readToken(",")); this.reader.expectToken(">"); } return typeArguments; } parseGenericsArgs(): string[] { const typeArguments: string[] = []; if (this.reader.readToken("<")) { do { const generics = this.reader.expectIdentifier(); typeArguments.push(generics); } while(this.reader.readToken(",")); this.reader.expectToken(">"); } return typeArguments; } parseExprStmtFromString(expression: string): ExpressionStatement { const expr = this.createExpressionParser(new Reader(expression)).parse(); return new ExpressionStatement(expr); } parseMethodSignature(isConstructor: boolean, declarationOnly: boolean): MethodSignature { const params: MethodParameter[] = []; const fields: Field[] = []; if (!this.reader.readToken(")")) { do { const leadingTrivia = this.reader.readLeadingTrivia(); const paramStart = this.reader.offset; const isPublic = this.reader.readToken("public"); if (isPublic && !isConstructor) this.reader.fail("public modifier is only allowed in constructor definition"); const paramName = this.reader.expectIdentifier(); this.context.push(`arg:${paramName}`); const typeAndInit = this.parseTypeAndInit(); const param = new MethodParameter(paramName, typeAndInit.type, typeAndInit.init, leadingTrivia); params.push(param); // init should be used as only the constructor's method parameter, but not again as a field initializer too // (otherwise it would called twice if cloned or cause AST error is just referenced from two separate places) if (isPublic) { const field = new Field(paramName, typeAndInit.type, null, Visibility.Public, false, param, param.leadingTrivia); fields.push(field); param.fieldDecl = field; } this.nodeManager.addNode(param, paramStart); this.context.pop(); } while (this.reader.readToken(",")); this.reader.expectToken(")"); } let returns: IType = null; if (!isConstructor) // in case of constructor, "returns" won't be used returns = this.reader.readToken(":") ? this.parseType() : this.missingReturnTypeIsVoid ? VoidType.instance : null; let body: Block = null; let superCallArgs: Expression[] = null; if (declarationOnly) { this.reader.expectToken(";"); } else { body = this.expectBlock("method body is missing"); const firstStmt = body.statements.length > 0 ? body.statements[0] : null; if (firstStmt instanceof ExpressionStatement && firstStmt.expression instanceof UnresolvedCallExpression && firstStmt.expression.func instanceof Identifier && firstStmt.expression.func.text === "super") { superCallArgs = firstStmt.expression.args; body.statements.shift(); } } return new MethodSignature(params, fields, body, returns, superCallArgs); } parseIdentifierOrString() { return this.reader.readString() || this.reader.expectIdentifier(); } parseInterface(leadingTrivia: string, isExported: boolean) { if (!this.reader.readToken("interface")) return null; const intfStart = this.reader.prevTokenOffset; const intfName = this.reader.expectIdentifier("expected identifier after 'interface' keyword"); this.context.push(`I:${intfName}`); const intfTypeArgs = this.parseGenericsArgs(); const baseInterfaces: IType[] = []; if (this.reader.readToken("extends")) { do { baseInterfaces.push(this.parseType()); } while (this.reader.readToken(",")) } const methods: Method[] = []; const fields: Field[] = []; this.reader.expectToken("{"); while(!this.reader.readToken("}")) { const memberLeadingTrivia = this.reader.readLeadingTrivia(); const memberStart = this.reader.offset; const memberName = this.parseIdentifierOrString(); if (this.reader.readToken(":")) { this.context.push(`F:${memberName}`); const fieldType = this.parseType(); this.reader.expectToken(";"); const field = new Field(memberName, fieldType, null, Visibility.Public, false, null, memberLeadingTrivia); fields.push(field); this.nodeManager.addNode(field, memberStart); this.context.pop(); } else { this.context.push(`M:${memberName}`); const methodTypeArgs = this.parseGenericsArgs(); this.reader.expectToken("("); // method const sig = this.parseMethodSignature(/* isConstructor = */ false, /* declarationOnly = */ true); const method = new Method(memberName, methodTypeArgs, sig.params, sig.body, Visibility.Public, false, sig.returns, false, memberLeadingTrivia); methods.push(method); this.nodeManager.addNode(method, memberStart); this.context.pop(); } } const intf = new Interface(intfName, intfTypeArgs, baseInterfaces, fields, methods, isExported, leadingTrivia); this.nodeManager.addNode(intf, intfStart); this.context.pop(); return intf; } parseSpecifiedType() { const typeName = this.reader.readIdentifier(); const typeArgs = this.parseTypeArgs(); return new UnresolvedType(typeName, typeArgs); } parseClass(leadingTrivia: string, isExported: boolean, declarationOnly: boolean) { const clsModifiers = this.reader.readModifiers(["abstract"]); if (!this.reader.readToken("class")) return null; const clsStart = this.reader.prevTokenOffset; const clsName = this.reader.expectIdentifier("expected identifier after 'class' keyword"); this.context.push(`C:${clsName}`); const typeArgs = this.parseGenericsArgs(); const baseClass = this.reader.readToken("extends") ? this.parseSpecifiedType() : null; const baseInterfaces: IType[] = []; if (this.reader.readToken("implements")) { do { baseInterfaces.push(this.parseSpecifiedType()); } while (this.reader.readToken(",")) } let constructor: Constructor = null; const fields: Field[] = []; const methods: Method[] = []; const properties: Property[] = []; this.reader.expectToken("{"); while(!this.reader.readToken("}")) { const memberLeadingTrivia = this.reader.readLeadingTrivia(); const memberStart = this.reader.offset; const modifiers = this.reader.readModifiers(["static", "public", "protected", "private", "readonly", "async", "abstract"]); const isStatic = modifiers.includes("static"); const isAsync = modifiers.includes("async"); const isAbstract = modifiers.includes("abstract"); const visibility = modifiers.includes("private") ? Visibility.Private : modifiers.includes("protected") ? Visibility.Protected : Visibility.Public; const memberName = this.parseIdentifierOrString(); const methodTypeArgs = this.parseGenericsArgs(); if (this.reader.readToken("(")) { // method const isConstructor = memberName === "constructor"; let member: IMethodBase; const sig = this.parseMethodSignature(isConstructor, declarationOnly || isAbstract); if (isConstructor) { member = constructor = new Constructor(sig.params, sig.body, sig.superCallArgs, memberLeadingTrivia); for (const field of sig.fields) fields.push(field); } else { const method = new Method(memberName, methodTypeArgs, sig.params, sig.body, visibility, isStatic, sig.returns, isAsync, memberLeadingTrivia); methods.push(method); member = method; } this.nodeManager.addNode(member, memberStart); } else if (memberName === "get" || memberName === "set") { // property const propName = this.reader.expectIdentifier(); let prop = properties.find(x => x.name === propName) || null; let propType: IType = null; let getter: Block = null; let setter: Block = null; if (memberName === "get") { // get propName(): propType { return ... } this.context.push(`P[G]:${propName}`); this.reader.expectToken("()", "expected '()' after property getter name"); propType = this.reader.readToken(":") ? this.parseType() : null; if (declarationOnly) { if (propType === null) this.reader.fail("Type is missing for property in declare class"); this.reader.expectToken(";"); } else { getter = this.expectBlock("property getter body is missing"); if (prop !== null) prop.getter = getter; } } else if (memberName === "set") { // set propName(value: propType) { ... } this.context.push(`P[S]:${propName}`); this.reader.expectToken("(", "expected '(' after property setter name"); this.reader.expectIdentifier(); propType = this.reader.readToken(":") ? this.parseType() : null; this.reader.expectToken(")"); if (declarationOnly) { if (propType === null) this.reader.fail("Type is missing for property in declare class"); this.reader.expectToken(";"); } else { setter = this.expectBlock("property setter body is missing"); if (prop !== null) prop.setter = setter; } } if (!prop) { prop = new Property(propName, propType, getter, setter, visibility, isStatic, memberLeadingTrivia); properties.push(prop); this.nodeManager.addNode(prop, memberStart); } this.context.pop(); } else { this.context.push(`F:${memberName}`); const typeAndInit = this.parseTypeAndInit(); this.reader.expectToken(";"); const field = new Field(memberName, typeAndInit.type, typeAndInit.init, visibility, isStatic, null, memberLeadingTrivia); fields.push(field); this.nodeManager.addNode(field, memberStart); this.context.pop(); } } const cls = new Class(clsName, typeArgs, baseClass, baseInterfaces, fields, properties, constructor, methods, isExported, leadingTrivia); this.nodeManager.addNode(cls, clsStart); this.context.pop(); return cls; } parseEnum(leadingTrivia: string, isExported: boolean) { if (!this.reader.readToken("enum")) return null; const enumStart = this.reader.prevTokenOffset; const name = this.reader.expectIdentifier("expected identifier after 'enum' keyword"); this.context.push(`E:${name}`); const members: EnumMember[] = []; this.reader.expectToken("{"); if (!this.reader.readToken("}")) { do { if (this.reader.peekToken("}")) break; // eg. "enum { A, B, }" (but multiline) const enumMember = new EnumMember(this.reader.expectIdentifier()); members.push(enumMember); this.nodeManager.addNode(enumMember, this.reader.prevTokenOffset); // TODO: generated code compatibility this.reader.readToken(`= "${enumMember.name}"`); } while(this.reader.readToken(",")); this.reader.expectToken("}"); } const enumObj = new Enum(name, members, isExported, leadingTrivia); this.nodeManager.addNode(enumObj, enumStart); this.context.pop(); return enumObj; } static calculateRelativePath(currFile: string, relPath: string) { if (!relPath.startsWith(".")) throw new Error(`relPath must start with '.', but got '${relPath}'`); const curr = currFile.split(/\//g); curr.pop(); // filename does not matter for (const part of relPath.split(/\//g)) { if (part === "") throw new Error(`relPath should not contain multiple '/' next to each other (relPath='${relPath}')`); if (part === ".") { // "./" == stay in current directory continue; } else if (part === "..") { // "../" == parent directory if (curr.length === 0) throw new Error(`relPath goes out of root (curr='${currFile}', relPath='${relPath}')`); curr.pop(); } else curr.push(part); } return curr.join("/"); } static calculateImportScope(currScope: ExportScopeRef, importFile: string) { if (importFile.startsWith(".")) // relative return new ExportScopeRef(currScope.packageName, this.calculateRelativePath(currScope.scopeName, importFile)); else { const path = importFile.split(/\//g); const pkgName = path.shift(); return new ExportScopeRef(pkgName, path.length === 0 ? Package.INDEX : path.join('/')); } } readIdentifier() { const rawId = this.reader.readIdentifier(); return rawId.replace(/_+$/, ""); } parseImport(leadingTrivia: string) { if (!this.reader.readToken("import")) return null; const importStart = this.reader.prevTokenOffset; let importAllAlias: string = null; let importParts: UnresolvedImport[] = []; if (this.reader.readToken("*")) { this.reader.expectToken("as"); importAllAlias = this.reader.expectIdentifier(); } else { this.reader.expectToken("{"); do { if (this.reader.peekToken("}")) break; const imp = this.reader.expectIdentifier(); if (this.reader.readToken("as")) this.reader.fail("This is not yet supported"); importParts.push(new UnresolvedImport(imp)); this.nodeManager.addNode(imp, this.reader.prevTokenOffset); } while(this.reader.readToken(",")); this.reader.expectToken("}"); } this.reader.expectToken("from"); const moduleName = this.reader.expectString(); this.reader.expectToken(";"); const importScope = this.exportScope !== null ? TypeScriptParser2.calculateImportScope(this.exportScope, moduleName) : null; const imports: Import[] = []; if (importParts.length > 0) imports.push(new Import(importScope, false, importParts, null, leadingTrivia)); if (importAllAlias !== null) imports.push(new Import(importScope, true, null, importAllAlias, leadingTrivia)); //this.nodeManager.addNode(imports, importStart); return imports; } parseSourceFile() { const imports: Import[] = []; const enums: Enum[] = []; const intfs: Interface[] = []; const classes: Class[] = []; const funcs: GlobalFunction[] = []; while (true) { const leadingTrivia = this.reader.readLeadingTrivia(); if (this.reader.eof) break; const imps = this.parseImport(leadingTrivia); if (imps !== null) { for (const imp of imps) imports.push(imp); continue; } const modifiers = this.reader.readModifiers(["export", "declare"]); const isExported = modifiers.includes("export"); const isDeclaration = modifiers.includes("declare"); const cls = this.parseClass(leadingTrivia, isExported, isDeclaration); if (cls !== null) { classes.push(cls); continue; } const enumObj = this.parseEnum(leadingTrivia, isExported); if (enumObj !== null) { enums.push(enumObj); continue; } const intf = this.parseInterface(leadingTrivia, isExported); if (intf !== null) { intfs.push(intf); continue; } if (this.reader.readToken("function")) { const funcName = this.readIdentifier(); this.reader.expectToken("("); const sig = this.parseMethodSignature(false, isDeclaration); funcs.push(new GlobalFunction(funcName, sig.params, sig.body, sig.returns, isExported, leadingTrivia)); continue; } break; } this.reader.skipWhitespace(); const stmts: Statement[] = []; while (true) { const leadingTrivia = this.reader.readLeadingTrivia(); if (this.reader.eof) break; const stmt = this.expectStatement(); if (stmt === null) continue; stmt.leadingTrivia = leadingTrivia; stmts.push(stmt); } return new SourceFile(imports, intfs, classes, enums, funcs, new Block(stmts), this.path, this.exportScope); } parse() { return this.parseSourceFile(); } static parseFile(source: string, path: SourcePath = null): SourceFile { return new TypeScriptParser2(source, path).parseSourceFile(); } }
the_stack
"use strict" import { ColorRange, LocalStorageCustomConfigs, stateObjectReplacer, stateObjectReviver } from "../codeCharta.model" import { CustomConfigItemGroup } from "../ui/customConfigs/customConfigs.component" import { CustomConfig, CustomConfigMapSelectionMode, CustomConfigsDownloadFile, ExportCustomConfig } from "../model/customConfig/customConfig.api.model" import { CustomConfigFileStateConnector } from "../ui/customConfigs/customConfigFileStateConnector" import { FileNameHelper } from "./fileNameHelper" import { FileDownloader } from "./fileDownloader" import { setState } from "../state/store/state.actions" import { setColorRange } from "../state/store/dynamicSettings/colorRange/colorRange.actions" import { setMargin } from "../state/store/dynamicSettings/margin/margin.actions" import { setCamera } from "../state/store/appSettings/camera/camera.actions" import { Vector3 } from "three" import { setCameraTarget } from "../state/store/appSettings/cameraTarget/cameraTarget.actions" import { StoreService } from "../state/store.service" import { ThreeCameraService } from "../ui/codeMap/threeViewer/threeCameraService" import { ThreeOrbitControlsService } from "../ui/codeMap/threeViewer/threeOrbitControlsService" import { CodeChartaStorage } from "./codeChartaStorage" export const CUSTOM_CONFIG_FILE_EXTENSION = ".cc.config.json" const CUSTOM_CONFIGS_LOCAL_STORAGE_VERSION = "1.0.0" const CUSTOM_CONFIGS_DOWNLOAD_FILE_VERSION = "1.0.0" export const CUSTOM_CONFIGS_LOCAL_STORAGE_ELEMENT = "CodeCharta::customConfigs" export class CustomConfigHelper { private static customConfigs: Map<string, CustomConfig> = CustomConfigHelper.loadCustomConfigs() private static storage: Storage static getStorage() { if (CustomConfigHelper.storage === undefined) { CustomConfigHelper.storage = new CodeChartaStorage() } return CustomConfigHelper.storage } static getCustomConfigItemGroups(customConfigFileStateConnector: CustomConfigFileStateConnector): Map<string, CustomConfigItemGroup> { const customConfigItemGroups: Map<string, CustomConfigItemGroup> = new Map() for (const customConfig of CustomConfigHelper.customConfigs.values()) { const groupKey = `${customConfig.assignedMaps.join("_")}_${customConfig.mapSelectionMode}` if (!customConfigItemGroups.has(groupKey)) { customConfigItemGroups.set(groupKey, { mapNames: customConfig.assignedMaps.join(" "), mapSelectionMode: customConfig.mapSelectionMode, hasApplicableItems: false, customConfigItems: [] }) } const customConfigItemApplicable = CustomConfigHelper.isCustomConfigApplicable(customConfigFileStateConnector, customConfig) customConfigItemGroups.get(groupKey).customConfigItems.push({ id: customConfig.id, name: customConfig.name, mapNames: customConfig.assignedMaps.join(" "), mapSelectionMode: customConfig.mapSelectionMode, isApplicable: customConfigItemApplicable }) if (customConfigItemApplicable) { customConfigItemGroups.get(groupKey).hasApplicableItems = true } } return customConfigItemGroups } private static isCustomConfigApplicable(customConfigFileStateConnector: CustomConfigFileStateConnector, customConfig: CustomConfig) { // Configs are applicable if their mapChecksums (and mode) are matching, therefore, map names must not be checked. return ( customConfigFileStateConnector.getChecksumOfAssignedMaps() === customConfig.mapChecksum && customConfigFileStateConnector.getMapSelectionMode() === customConfig.mapSelectionMode ) } static setCustomConfigsToLocalStorage() { const newLocalStorageElement: LocalStorageCustomConfigs = { version: CUSTOM_CONFIGS_LOCAL_STORAGE_VERSION, customConfigs: [...CustomConfigHelper.customConfigs] } CustomConfigHelper.getStorage().setItem( CUSTOM_CONFIGS_LOCAL_STORAGE_ELEMENT, JSON.stringify(newLocalStorageElement, stateObjectReplacer) ) } private static loadCustomConfigs() { const ccLocalStorage: LocalStorageCustomConfigs = JSON.parse( CustomConfigHelper.getStorage().getItem(CUSTOM_CONFIGS_LOCAL_STORAGE_ELEMENT), stateObjectReviver ) return new Map(ccLocalStorage?.customConfigs) } static addCustomConfigs(newCustomConfigs: CustomConfig[]) { for (const newCustomConfig of newCustomConfigs) { CustomConfigHelper.customConfigs.set(newCustomConfig.id, newCustomConfig) } CustomConfigHelper.setCustomConfigsToLocalStorage() } static addCustomConfig(newCustomConfig: CustomConfig) { CustomConfigHelper.customConfigs.set(newCustomConfig.id, newCustomConfig) CustomConfigHelper.setCustomConfigsToLocalStorage() } static getCustomConfigSettings(configId: string): CustomConfig | undefined { return CustomConfigHelper.customConfigs.get(configId) } static hasCustomConfigByName(mapSelectionMode: CustomConfigMapSelectionMode, selectedMaps: string[], configName: string): boolean { for (const customConfig of CustomConfigHelper.customConfigs.values()) { if ( customConfig.name === configName && customConfig.mapSelectionMode === mapSelectionMode && customConfig.assignedMaps.join("") === selectedMaps.join("") ) { return true } } return false } static getCustomConfigByName( mapSelectionMode: CustomConfigMapSelectionMode, selectedMaps: string[], configName: string ): CustomConfig | null { for (const customConfig of CustomConfigHelper.customConfigs.values()) { if ( customConfig.name === configName && customConfig.mapSelectionMode === mapSelectionMode && customConfig.assignedMaps.join("") === selectedMaps.join("") ) { return customConfig } } return null } static getCustomConfigs(): Map<string, CustomConfig> { return CustomConfigHelper.customConfigs } static importCustomConfigs(content: string) { const importedCustomConfigsFile: CustomConfigsDownloadFile = JSON.parse(content, stateObjectReviver) for (const exportedConfig of importedCustomConfigsFile.customConfigs.values()) { const alreadyExistingConfig = CustomConfigHelper.getCustomConfigSettings(exportedConfig.id) // Check for a duplicate Config by matching checksums if (alreadyExistingConfig) { continue } // Prevent different Configs with the same name if ( CustomConfigHelper.hasCustomConfigByName(exportedConfig.mapSelectionMode, exportedConfig.assignedMaps, exportedConfig.name) ) { exportedConfig.name += ` (${FileNameHelper.getFormattedTimestamp(new Date(exportedConfig.creationTime))})` } const importedCustomConfig: CustomConfig = { id: exportedConfig.id, name: exportedConfig.name, creationTime: exportedConfig.creationTime, assignedMaps: exportedConfig.assignedMaps, customConfigVersion: exportedConfig.customConfigVersion, mapChecksum: exportedConfig.mapChecksum, mapSelectionMode: exportedConfig.mapSelectionMode, stateSettings: exportedConfig.stateSettings } CustomConfigHelper.addCustomConfig(importedCustomConfig) } } static downloadCustomConfigs( customConfigs: Map<string, ExportCustomConfig>, customConfigFileStateConnector: CustomConfigFileStateConnector ) { const customConfigsDownloadFile: CustomConfigsDownloadFile = { downloadApiVersion: CUSTOM_CONFIGS_DOWNLOAD_FILE_VERSION, timestamp: Date.now(), customConfigs } let fileName = FileNameHelper.getNewTimestamp() + CUSTOM_CONFIG_FILE_EXTENSION if ( !customConfigFileStateConnector.isDeltaMode() && customConfigFileStateConnector.getAmountOfUploadedFiles() === 1 && customConfigFileStateConnector.isEachFileSelected() ) { // If only one map is uploaded/present in SINGLE mode, prefix the .cc.config.json file with its name. fileName = `${FileNameHelper.withoutCCJsonExtension(customConfigFileStateConnector.getJointMapName())}_${fileName}` } FileDownloader.downloadData(JSON.stringify(customConfigsDownloadFile, stateObjectReplacer), fileName) } static createExportCustomConfigFromConfig(customConfig: CustomConfig): ExportCustomConfig { return { ...customConfig } } static getCustomConfigsAmountByMapAndMode(mapNames: string, mapSelectionMode: CustomConfigMapSelectionMode): number { let count = 0 for (const config of CustomConfigHelper.customConfigs.values()) { if (config.assignedMaps.join(" ") === mapNames && config.mapSelectionMode === mapSelectionMode) { count++ } } return count } static getConfigNameSuggestionByFileState(customConfigFileStateConnector: CustomConfigFileStateConnector): string { const suggestedConfigName = customConfigFileStateConnector.getJointMapName() if (!suggestedConfigName) { return "" } const customConfigNumberSuffix = CustomConfigHelper.getCustomConfigsAmountByMapAndMode( customConfigFileStateConnector.getJointMapName(), customConfigFileStateConnector.getMapSelectionMode() ) + 1 return `${suggestedConfigName} #${customConfigNumberSuffix}` } static deleteCustomConfigs(customConfigs: CustomConfig[]) { for (const customConfig of customConfigs) { CustomConfigHelper.customConfigs.delete(customConfig.id) } CustomConfigHelper.setCustomConfigsToLocalStorage() } static deleteCustomConfig(configId: string) { CustomConfigHelper.customConfigs.delete(configId) CustomConfigHelper.setCustomConfigsToLocalStorage() } static sortCustomConfigDropDownGroupList(a: CustomConfigItemGroup, b: CustomConfigItemGroup) { if (!b.hasApplicableItems) { if (a.hasApplicableItems || a.mapSelectionMode < b.mapSelectionMode) { return -1 } if (a.mapSelectionMode === b.mapSelectionMode) { return 0 } } return 1 } static applyCustomConfig( configId: string, storeService: StoreService, threeCameraService: ThreeCameraService, threeOrbitControlsService: ThreeOrbitControlsService ) { const customConfig = this.getCustomConfigSettings(configId) // TODO: Setting state from loaded CustomConfig not working at the moment // due to issues of the event architecture. // TODO: Check if state properties differ // Create new partial State (updates) for changed values only storeService.dispatch(setState(customConfig.stateSettings)) // Should we fire another event "ResettingStateFinishedEvent" // We could add a listener then to reset the camera storeService.dispatch(setColorRange(customConfig.stateSettings.dynamicSettings.colorRange as ColorRange)) storeService.dispatch(setMargin(customConfig.stateSettings.dynamicSettings.margin)) // TODO: remove this dirty timeout and set camera settings properly // This timeout is a chance that CustomConfigs for a small map can be restored and applied completely (even the camera positions) setTimeout(() => { threeCameraService.setPosition() threeOrbitControlsService.setControlTarget() storeService.dispatch(setCamera(customConfig.stateSettings.appSettings.camera as Vector3)) storeService.dispatch(setCameraTarget(customConfig.stateSettings.appSettings.cameraTarget as Vector3)) }, 100) } }
the_stack
module android.app { import DialogInterface = android.content.DialogInterface; import Drawable = android.graphics.drawable.Drawable; import Bundle = android.os.Bundle; import Handler = android.os.Handler; import Message = android.os.Message; import Log = android.util.Log; import TypedValue = android.util.TypedValue; import Gravity = android.view.Gravity; import KeyEvent = android.view.KeyEvent; import LayoutInflater = android.view.LayoutInflater; import MotionEvent = android.view.MotionEvent; import View = android.view.View; import ViewGroup = android.view.ViewGroup; import LayoutParams = android.view.ViewGroup.LayoutParams; import Window = android.view.Window; import WindowManager = android.view.WindowManager; import WeakReference = java.lang.ref.WeakReference; import Activity = android.app.Activity; import Application = android.app.Application; import Context = android.content.Context; import Runnable = java.lang.Runnable; /** * Base class for Dialogs. * * <p>Note: Activities provide a facility to manage the creation, saving and * restoring of dialogs. See {@link Activity#onCreateDialog(int)}, * {@link Activity#onPrepareDialog(int, Dialog)}, * {@link Activity#showDialog(int)}, and {@link Activity#dismissDialog(int)}. If * these methods are used, {@link #getOwnerActivity()} will return the Activity * that managed this dialog. * * <p>Often you will want to have a Dialog display on top of the current * input method, because there is no reason for it to accept text. You can * do this by setting the {@link WindowManager.LayoutParams#FLAG_ALT_FOCUSABLE_IM * WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM} window flag (assuming * your Dialog takes input focus, as it the default) with the following code: * * <pre> * getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, * WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);</pre> * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about creating dialogs, read the * <a href="{@docRoot}guide/topics/ui/dialogs.html">Dialogs</a> developer guide.</p> * </div> */ export class Dialog implements DialogInterface, Window.Callback, KeyEvent.Callback { private static TAG:string = "Dialog"; //private mOwnerActivity:Activity; mContext:Context; mWindowManager:WindowManager; mWindow:Window; mDecor:View; //private mActionBar:ActionBarImpl; /** * This field should be made private, so it is hidden from the SDK. * {@hide} */ protected mCancelable:boolean = true; private mCancelAndDismissTaken:string; private mCancelMessage:Message; private mDismissMessage:Message; private mShowMessage:Message; private mOnKeyListener:DialogInterface.OnKeyListener; private mCreated:boolean = false; private mShowing:boolean = false; private mCanceled:boolean = false; private mHandler:Handler = new Handler(); private static DISMISS:number = 0x43; private static CANCEL:number = 0x44; private static SHOW:number = 0x45; private mListenersHandler:Handler; //private mActionMode:ActionMode; private mDismissAction:Runnable = (()=> { const inner_this = this; class _Inner implements Runnable { run():void { inner_this.dismissDialog(); } } return new _Inner(); })(); /** * Create a Dialog window that uses the default dialog frame style. * * @param context The Context the Dialog is to run it. In particular, it * uses the window manager and theme in this context to * present its UI. */ constructor(context:Context, cancelable?:boolean, cancelListener?:DialogInterface.OnCancelListener) { //if (createContextThemeWrapper) { // if (theme == 0) { // let outValue:TypedValue = new TypedValue(); // context.getTheme().resolveAttribute(com.android.internal.R.attr.dialogTheme, outValue, true); // theme = outValue.resourceId; // } // this.mContext = new ContextThemeWrapper(context, theme); //} else { this.mContext = context; //} this.mWindowManager = (<android.app.Activity>context).getWindowManager(); let w:Window = new Window(context); w.setFloating(true); w.setDimAmount(0.7); w.setBackgroundColor(android.graphics.Color.TRANSPARENT); this.mWindow = w; let dm = context.getResources().getDisplayMetrics(); let decor = w.getDecorView(); decor.setMinimumWidth(dm.density * 280); decor.setMinimumHeight(dm.density * 20); const onMeasure = decor.onMeasure; decor.onMeasure = (widthMeasureSpec:number, heightMeasureSpec:number)=>{ onMeasure.call(decor, widthMeasureSpec, heightMeasureSpec); let width = decor.getMeasuredWidth(); if(width > 360 * dm.density){//max 360dp let widthSpec = View.MeasureSpec.makeMeasureSpec(360 * dm.density, View.MeasureSpec.EXACTLY); onMeasure.call(decor, widthSpec, heightMeasureSpec); } } let wp = w.getAttributes(); wp.flags |= WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH; wp.height = wp.width = ViewGroup.LayoutParams.WRAP_CONTENT; wp.leftMargin = wp.rightMargin = wp.topMargin = wp.bottomMargin = dm.density * 16; w.setWindowAnimations(android.R.anim.dialog_enter, android.R.anim.dialog_exit, null, null); w.setChildWindowManager(this.mWindowManager); w.setGravity(Gravity.CENTER); w.setCallback(this); this.mListenersHandler = new Dialog.ListenersHandler(this); this.mCancelable = cancelable; this.setOnCancelListener(cancelListener); } /** * Retrieve the Context this Dialog is running in. * * @return Context The Context used by the Dialog. */ getContext():Context { return this.mContext; } ///** // * Retrieve the {@link ActionBar} attached to this dialog, if present. // * // * @return The ActionBar attached to the dialog or null if no ActionBar is present. // */ //getActionBar():ActionBar { // return this.mActionBar; //} // ///** // * Sets the Activity that owns this dialog. An example use: This Dialog will // * use the suggested volume control stream of the Activity. // * // * @param activity The Activity that owns this dialog. // */ //setOwnerActivity(activity:Activity):void { // this.mOwnerActivity = activity; // this.getWindow().setVolumeControlStream(this.mOwnerActivity.getVolumeControlStream()); //} // ///** // * Returns the Activity that owns this Dialog. For example, if // * {@link Activity#showDialog(int)} is used to show this Dialog, that // * Activity will be the owner (by default). Depending on how this dialog was // * created, this may return null. // * // * @return The Activity that owns this Dialog. // */ //getOwnerActivity():Activity { // return this.mOwnerActivity; //} /** * @return Whether the dialog is currently showing. */ isShowing():boolean { return this.mShowing; } /** * Start the dialog and display it on screen. The window is placed in the * application layer and opaque. Note that you should not override this * method to do initialization when the dialog is shown, instead implement * that in {@link #onStart}. */ show():void { if (this.mShowing) { if (this.mDecor != null) { //if (this.mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) { // this.mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR); //} this.mDecor.setVisibility(View.VISIBLE); } return; } this.mCanceled = false; if (!this.mCreated) { this.dispatchOnCreate(null); } this.onStart(); this.mDecor = this.mWindow.getDecorView(); //if (this.mActionBar == null && this.mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) { //const info:ApplicationInfo = this.mContext.getApplicationInfo(); //this.mWindow.setDefaultIcon(info.icon); //this.mWindow.setDefaultLogo(info.logo); //this.mActionBar = new ActionBarImpl(this); //} //let l:WindowManager.LayoutParams = this.mWindow.getAttributes(); //if ((l.softInputMode & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) == 0) { // let nl:WindowManager.LayoutParams = new WindowManager.LayoutParams(); // nl.copyFrom(l); // nl.softInputMode |= WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; // l = nl; //} try { this.mWindowManager.addWindow(this.mWindow); this.mShowing = true; this.sendShowMessage(); } finally { } } /** * Hide the dialog, but do not dismiss it. */ hide():void { if (this.mDecor != null) { this.mDecor.setVisibility(View.GONE); } } /** * Dismiss this dialog, removing it from the screen. This method can be * invoked safely from any thread. Note that you should not override this * method to do cleanup when the dialog is dismissed, instead implement * that in {@link #onStop}. */ dismiss():void { //if (Looper.myLooper() == this.mHandler.getLooper()) { this.dismissDialog(); //} else { // this.mHandler.post(this.mDismissAction); //} } dismissDialog():void { if (this.mDecor == null || !this.mShowing) { return; } if (this.mWindow.isDestroyed()) { Log.e(Dialog.TAG, "Tried to dismissDialog() but the Dialog's window was already destroyed!"); return; } try { this.mWindowManager.removeWindow(this.mWindow); } finally { //if (this.mActionMode != null) { // this.mActionMode.finish(); //} this.mDecor = null; //this.mWindow.closeAllPanels(); this.onStop(); this.mShowing = false; this.sendDismissMessage(); } } private sendDismissMessage():void { if (this.mDismissMessage != null) { // Obtain a new message so this dialog can be re-used Message.obtain(this.mDismissMessage).sendToTarget(); } } private sendShowMessage():void { if (this.mShowMessage != null) { // Obtain a new message so this dialog can be re-used Message.obtain(this.mShowMessage).sendToTarget(); } } // internal method to make sure mcreated is set properly without requiring // users to call through to super in onCreate dispatchOnCreate(savedInstanceState:Bundle):void { if (!this.mCreated) { this.onCreate(savedInstanceState); this.mCreated = true; } } /** * Similar to {@link Activity#onCreate}, you should initialize your dialog * in this method, including calling {@link #setContentView}. * @param savedInstanceState If this dialog is being reinitalized after a * the hosting activity was previously shut down, holds the result from * the most recent call to {@link #onSaveInstanceState}, or null if this * is the first time. */ protected onCreate(savedInstanceState:Bundle):void { } /** * Called when the dialog is starting. */ protected onStart():void { //if (this.mActionBar != null) // this.mActionBar.setShowHideAnimationEnabled(true); } /** * Called to tell you that you're stopping. */ protected onStop():void { //if (this.mActionBar != null) // this.mActionBar.setShowHideAnimationEnabled(false); } private static DIALOG_SHOWING_TAG:string = "android:dialogShowing"; private static DIALOG_HIERARCHY_TAG:string = "android:dialogHierarchy"; ///** // * Saves the state of the dialog into a bundle. // * // * The default implementation saves the state of its view hierarchy, so you'll // * likely want to call through to super if you override this to save additional // * state. // * @return A bundle with the state of the dialog. // */ //onSaveInstanceState():Bundle { // let bundle:Bundle = new Bundle(); // bundle.putBoolean(Dialog.DIALOG_SHOWING_TAG, this.mShowing); // if (this.mCreated) { // bundle.putBundle(Dialog.DIALOG_HIERARCHY_TAG, this.mWindow.saveHierarchyState()); // } // return bundle; //} // ///** // * Restore the state of the dialog from a previously saved bundle. // * // * The default implementation restores the state of the dialog's view // * hierarchy that was saved in the default implementation of {@link #onSaveInstanceState()}, // * so be sure to call through to super when overriding unless you want to // * do all restoring of state yourself. // * @param savedInstanceState The state of the dialog previously saved by // * {@link #onSaveInstanceState()}. // */ //onRestoreInstanceState(savedInstanceState:Bundle):void { // const dialogHierarchyState:Bundle = savedInstanceState.getBundle(Dialog.DIALOG_HIERARCHY_TAG); // if (dialogHierarchyState == null) { // // dialog has never been shown, or onCreated, nothing to restore. // return; // } // this.dispatchOnCreate(savedInstanceState); // this.mWindow.restoreHierarchyState(dialogHierarchyState); // if (savedInstanceState.getBoolean(Dialog.DIALOG_SHOWING_TAG)) { // this.show(); // } //} /** * Retrieve the current Window for the activity. This can be used to * directly access parts of the Window API that are not available * through Activity/Screen. * * @return Window The current window, or null if the activity is not * visual. */ getWindow():Window { return this.mWindow; } /** * Call {@link android.view.Window#getCurrentFocus} on the * Window if this Activity to return the currently focused view. * * @return View The current View with focus or null. * * @see #getWindow * @see android.view.Window#getCurrentFocus */ getCurrentFocus():View { return this.mWindow != null ? this.mWindow.getCurrentFocus() : null; } /** * Finds a view that was identified by the id attribute from the XML that * was processed in {@link #onStart}. * * @param id the identifier of the view to find * @return The view if found or null otherwise. */ findViewById(id:string):View { return this.mWindow.findViewById(id); } ///** // * Set the screen content from a layout resource. The resource will be // * inflated, adding all top-level views to the screen. // * // * @param layoutResID Resource ID to be inflated. // */ //setContentView(layoutResID:number):void { // this.mWindow.setContentView(layoutResID); //} ///** // * Set the screen content to an explicit view. This view is placed // * directly into the screen's view hierarchy. It can itself be a complex // * view hierarhcy. // * // * @param view The desired content to display. // */ //setContentView(view:View):void { // this.mWindow.setContentView(view); //} /** * Set the screen content to an explicit view. This view is placed * directly into the screen's view hierarchy. It can itself be a complex * view hierarhcy. * * @param view The desired content to display. * @param params Layout parameters for the view. */ setContentView(view:View, params?:ViewGroup.LayoutParams):void { this.mWindow.setContentView(view, params); } /** * Add an additional content view to the screen. Added after any existing * ones in the screen -- existing views are NOT removed. * * @param view The desired content to display. * @param params Layout parameters for the view. */ addContentView(view:View, params:ViewGroup.LayoutParams):void { this.mWindow.addContentView(view, params); } /** * Set the title text for this dialog's window. * * @param title The new text to display in the title. */ setTitle(title:string):void { this.mWindow.setTitle(title); this.mWindow.getAttributes().setTitle(title); } ///** // * Set the title text for this dialog's window. The text is retrieved // * from the resources with the supplied identifier. // * // * @param titleId the title's text resource identifier // */ //setTitle(titleId:number):void { // this.setTitle(this.mContext.getText(titleId)); //} /** * A key was pressed down. * * <p>If the focused view didn't want this event, this method is called. * * <p>The default implementation consumed the KEYCODE_BACK to later * handle it in {@link #onKeyUp}. * * @see #onKeyUp * @see android.view.KeyEvent */ onKeyDown(keyCode:number, event:KeyEvent):boolean { if (keyCode == KeyEvent.KEYCODE_BACK) { event.startTracking(); return true; } return false; } /** * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle * the event). */ onKeyLongPress(keyCode:number, event:KeyEvent):boolean { return false; } /** * A key was released. * * <p>The default implementation handles KEYCODE_BACK to close the * dialog. * * @see #onKeyDown * @see KeyEvent */ onKeyUp(keyCode:number, event:KeyEvent):boolean { if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking() && !event.isCanceled()) { this.onBackPressed(); return true; } return false; } /** * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle * the event). */ onKeyMultiple(keyCode:number, repeatCount:number, event:KeyEvent):boolean { return false; } /** * Called when the dialog has detected the user's press of the back * key. The default implementation simply cancels the dialog (only if * it is cancelable), but you can override this to do whatever you want. */ onBackPressed():void { if (this.mCancelable) { this.cancel(); } } ///** // * Called when a key shortcut event is not handled by any of the views in the Dialog. // * Override this method to implement global key shortcuts for the Dialog. // * Key shortcuts can also be implemented by setting the // * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. // * // * @param keyCode The value in event.getKeyCode(). // * @param event Description of the key event. // * @return True if the key shortcut was handled. // */ //onKeyShortcut(keyCode:number, event:KeyEvent):boolean { // return false; //} /** * Called when a touch screen event was not handled by any of the views * under it. This is most useful to process touch events that happen outside * of your window bounds, where there is no view to receive it. * * @param event The touch screen event being processed. * @return Return true if you have consumed the event, false if you haven't. * The default implementation will cancel the dialog when a touch * happens outside of the window bounds. */ onTouchEvent(event:MotionEvent):boolean { if (this.mCancelable && this.mShowing && this.mWindow.shouldCloseOnTouch(this.mContext, event)) { this.cancel(); return true; } return false; } /** * Called when the trackball was moved and not handled by any of the * views inside of the activity. So, for example, if the trackball moves * while focus is on a button, you will receive a call here because * buttons do not normally do anything with trackball events. The call * here happens <em>before</em> trackball movements are converted to * DPAD key events, which then get sent back to the view hierarchy, and * will be processed at the point for things like focus navigation. * * @param event The trackball event being processed. * * @return Return true if you have consumed the event, false if you haven't. * The default implementation always returns false. */ onTrackballEvent(event:MotionEvent):boolean { return false; } /** * Called when a generic motion event was not handled by any of the * views inside of the dialog. * <p> * Generic motion events describe joystick movements, mouse hovers, track pad * touches, scroll wheel movements and other input events. The * {@link MotionEvent#getSource() source} of the motion event specifies * the class of input that was received. Implementations of this method * must examine the bits in the source before processing the event. * The following code example shows how this is done. * </p><p> * Generic motion events with source class * {@link android.view.InputDevice#SOURCE_CLASS_POINTER} * are delivered to the view under the pointer. All other generic motion events are * delivered to the focused view. * </p><p> * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to * handle this event. * </p> * * @param event The generic motion event being processed. * * @return Return true if you have consumed the event, false if you haven't. * The default implementation always returns false. */ onGenericMotionEvent(event:MotionEvent):boolean { return false; } onWindowAttributesChanged(params:WindowManager.LayoutParams):void { if (this.mDecor != null) { this.mWindowManager.updateWindowLayout(this.mWindow, params); } } onContentChanged():void { } onWindowFocusChanged(hasFocus:boolean):void { } onAttachedToWindow():void { } onDetachedFromWindow():void { } /** * Called to process key events. You can override this to intercept all * key events before they are dispatched to the window. Be sure to call * this implementation for key events that should be handled normally. * * @param event The key event. * * @return boolean Return true if this event was consumed. */ dispatchKeyEvent(event:KeyEvent):boolean { if ((this.mOnKeyListener != null) && (this.mOnKeyListener.onKey(this, event.getKeyCode(), event))) { return true; } if (this.mWindow.superDispatchKeyEvent(event)) { return true; } return event.dispatch(this, this.mDecor != null ? this.mDecor.getKeyDispatcherState() : null, this); } ///** // * Called to process a key shortcut event. // * You can override this to intercept all key shortcut events before they are // * dispatched to the window. Be sure to call this implementation for key shortcut // * events that should be handled normally. // * // * @param event The key shortcut event. // * @return True if this event was consumed. // */ //dispatchKeyShortcutEvent(event:KeyEvent):boolean { // if (this.mWindow.superDispatchKeyShortcutEvent(event)) { // return true; // } // return this.onKeyShortcut(event.getKeyCode(), event); //} /** * Called to process touch screen events. You can override this to * intercept all touch screen events before they are dispatched to the * window. Be sure to call this implementation for touch screen events * that should be handled normally. * * @param ev The touch screen event. * * @return boolean Return true if this event was consumed. */ dispatchTouchEvent(ev:MotionEvent):boolean { if (this.mWindow.superDispatchTouchEvent(ev)) { return true; } return this.onTouchEvent(ev); } ///** // * Called to process trackball events. You can override this to // * intercept all trackball events before they are dispatched to the // * window. Be sure to call this implementation for trackball events // * that should be handled normally. // * // * @param ev The trackball event. // * // * @return boolean Return true if this event was consumed. // */ //dispatchTrackballEvent(ev:MotionEvent):boolean { // if (this.mWindow.superDispatchTrackballEvent(ev)) { // return true; // } // return this.onTrackballEvent(ev); //} /** * Called to process generic motion events. You can override this to * intercept all generic motion events before they are dispatched to the * window. Be sure to call this implementation for generic motion events * that should be handled normally. * * @param ev The generic motion event. * * @return boolean Return true if this event was consumed. */ dispatchGenericMotionEvent(ev:MotionEvent):boolean { if (this.mWindow.superDispatchGenericMotionEvent(ev)) { return true; } return this.onGenericMotionEvent(ev); } //dispatchPopulateAccessibilityEvent(event:AccessibilityEvent):boolean { // event.setClassName(this.getClass().getName()); // event.setPackageName(this.mContext.getPackageName()); // let params:LayoutParams = this.getWindow().getAttributes(); // let isFullScreen:boolean = (params.width == LayoutParams.MATCH_PARENT) && (params.height == LayoutParams.MATCH_PARENT); // event.setFullScreen(isFullScreen); // return false; //} // ///** // * @see Activity#onCreatePanelView(int) // */ //onCreatePanelView(featureId:number):View { // return null; //} // ///** // * @see Activity#onCreatePanelMenu(int, Menu) // */ //onCreatePanelMenu(featureId:number, menu:Menu):boolean { // if (featureId == Window.FEATURE_OPTIONS_PANEL) { // return this.onCreateOptionsMenu(menu); // } // return false; //} // ///** // * @see Activity#onPreparePanel(int, View, Menu) // */ //onPreparePanel(featureId:number, view:View, menu:Menu):boolean { // if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) { // let goforit:boolean = this.onPrepareOptionsMenu(menu); // return goforit && menu.hasVisibleItems(); // } // return true; //} // ///** // * @see Activity#onMenuOpened(int, Menu) // */ //onMenuOpened(featureId:number, menu:Menu):boolean { // if (featureId == Window.FEATURE_ACTION_BAR) { // this.mActionBar.dispatchMenuVisibilityChanged(true); // } // return true; //} // ///** // * @see Activity#onMenuItemSelected(int, MenuItem) // */ //onMenuItemSelected(featureId:number, item:MenuItem):boolean { // return false; //} // ///** // * @see Activity#onPanelClosed(int, Menu) // */ //onPanelClosed(featureId:number, menu:Menu):void { // if (featureId == Window.FEATURE_ACTION_BAR) { // this.mActionBar.dispatchMenuVisibilityChanged(false); // } //} // ///** // * It is usually safe to proxy this call to the owner activity's // * {@link Activity#onCreateOptionsMenu(Menu)} if the client desires the same // * menu for this Dialog. // * // * @see Activity#onCreateOptionsMenu(Menu) // * @see #getOwnerActivity() // */ //onCreateOptionsMenu(menu:Menu):boolean { // return true; //} // ///** // * It is usually safe to proxy this call to the owner activity's // * {@link Activity#onPrepareOptionsMenu(Menu)} if the client desires the // * same menu for this Dialog. // * // * @see Activity#onPrepareOptionsMenu(Menu) // * @see #getOwnerActivity() // */ //onPrepareOptionsMenu(menu:Menu):boolean { // return true; //} // ///** // * @see Activity#onOptionsItemSelected(MenuItem) // */ //onOptionsItemSelected(item:MenuItem):boolean { // return false; //} // ///** // * @see Activity#onOptionsMenuClosed(Menu) // */ //onOptionsMenuClosed(menu:Menu):void { //} // ///** // * @see Activity#openOptionsMenu() // */ //openOptionsMenu():void { // this.mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null); //} // ///** // * @see Activity#closeOptionsMenu() // */ //closeOptionsMenu():void { // this.mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL); //} // ///** // * @see Activity#invalidateOptionsMenu() // */ //invalidateOptionsMenu():void { // this.mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL); //} // ///** // * @see Activity#onCreateContextMenu(ContextMenu, View, ContextMenuInfo) // */ //onCreateContextMenu(menu:ContextMenu, v:View, menuInfo:ContextMenuInfo):void { //} // ///** // * @see Activity#registerForContextMenu(View) // */ //registerForContextMenu(view:View):void { // view.setOnCreateContextMenuListener(this); //} // ///** // * @see Activity#unregisterForContextMenu(View) // */ //unregisterForContextMenu(view:View):void { // view.setOnCreateContextMenuListener(null); //} // ///** // * @see Activity#openContextMenu(View) // */ //openContextMenu(view:View):void { // view.showContextMenu(); //} // ///** // * @see Activity#onContextItemSelected(MenuItem) // */ //onContextItemSelected(item:MenuItem):boolean { // return false; //} // ///** // * @see Activity#onContextMenuClosed(Menu) // */ //onContextMenuClosed(menu:Menu):void { //} // ///** // * This hook is called when the user signals the desire to start a search. // */ //onSearchRequested():boolean { // const searchManager:SearchManager = <SearchManager> this.mContext.getSystemService(Context.SEARCH_SERVICE); // // associate search with owner activity // const appName:ComponentName = this.getAssociatedActivity(); // if (appName != null && searchManager.getSearchableInfo(appName) != null) { // searchManager.startSearch(null, false, appName, null, false); // this.dismiss(); // return true; // } else { // return false; // } //} // //onWindowStartingActionMode(callback:ActionMode.Callback):ActionMode { // if (this.mActionBar != null) { // return this.mActionBar.startActionMode(callback); // } // return null; //} // ///** // * {@inheritDoc} // * // * Note that if you override this method you should always call through // * to the superclass implementation by calling super.onActionModeStarted(mode). // */ //onActionModeStarted(mode:ActionMode):void { // this.mActionMode = mode; //} // ///** // * {@inheritDoc} // * // * Note that if you override this method you should always call through // * to the superclass implementation by calling super.onActionModeFinished(mode). // */ //onActionModeFinished(mode:ActionMode):void { // if (mode == this.mActionMode) { // this.mActionMode = null; // } //} // ///** // * @return The activity associated with this dialog, or null if there is no associated activity. // */ //private getAssociatedActivity():ComponentName { // let activity:Activity = this.mOwnerActivity; // let context:Context = this.getContext(); // while (activity == null && context != null) { // if (context instanceof Activity) { // // found it! // activity = <Activity> context; // } else { // context = (context instanceof ContextWrapper) ? // unwrap one level // (<ContextWrapper> context).getBaseContext() : // done // null; // } // } // return activity == null ? null : activity.getComponentName(); //} /** * Request that key events come to this dialog. Use this if your * dialog has no views with focus, but the dialog still wants * a chance to process key events. * * @param get true if the dialog should receive key events, false otherwise * @see android.view.Window#takeKeyEvents */ takeKeyEvents(get:boolean):void { this.mWindow.takeKeyEvents(get); } ///** // * Enable extended window features. This is a convenience for calling // * {@link android.view.Window#requestFeature getWindow().requestFeature()}. // * // * @param featureId The desired feature as defined in // * {@link android.view.Window}. // * @return Returns true if the requested feature is supported and now // * enabled. // * // * @see android.view.Window#requestFeature // */ //requestWindowFeature(featureId:number):boolean { // return this.getWindow().requestFeature(featureId); //} // ///** // * Convenience for calling // * {@link android.view.Window#setFeatureDrawableResource}. // */ //setFeatureDrawableResource(featureId:number, resId:number):void { // this.getWindow().setFeatureDrawableResource(featureId, resId); //} // ///** // * Convenience for calling // * {@link android.view.Window#setFeatureDrawableUri}. // */ //setFeatureDrawableUri(featureId:number, uri:Uri):void { // this.getWindow().setFeatureDrawableUri(featureId, uri); //} // ///** // * Convenience for calling // * {@link android.view.Window#setFeatureDrawable(int, Drawable)}. // */ //setFeatureDrawable(featureId:number, drawable:Drawable):void { // this.getWindow().setFeatureDrawable(featureId, drawable); //} // ///** // * Convenience for calling // * {@link android.view.Window#setFeatureDrawableAlpha}. // */ //setFeatureDrawableAlpha(featureId:number, alpha:number):void { // this.getWindow().setFeatureDrawableAlpha(featureId, alpha); //} getLayoutInflater():LayoutInflater { return this.getWindow().getLayoutInflater(); } /** * Sets whether this dialog is cancelable with the * {@link KeyEvent#KEYCODE_BACK BACK} key. */ setCancelable(flag:boolean):void { this.mCancelable = flag; } /** * Sets whether this dialog is canceled when touched outside the window's * bounds. If setting to true, the dialog is set to be cancelable if not * already set. * * @param cancel Whether the dialog should be canceled when touched outside * the window. */ setCanceledOnTouchOutside(cancel:boolean):void { if (cancel && !this.mCancelable) { this.mCancelable = true; } this.mWindow.setCloseOnTouchOutside(cancel); } /** * Cancel the dialog. This is essentially the same as calling {@link #dismiss()}, but it will * also call your {@link DialogInterface.OnCancelListener} (if registered). */ cancel():void { if (!this.mCanceled && this.mCancelMessage != null) { this.mCanceled = true; // Obtain a new message so this dialog can be re-used Message.obtain(this.mCancelMessage).sendToTarget(); } this.dismiss(); } /** * Set a listener to be invoked when the dialog is canceled. * * <p>This will only be invoked when the dialog is canceled. * Cancel events alone will not capture all ways that * the dialog might be dismissed. If the creator needs * to know when a dialog is dismissed in general, use * {@link #setOnDismissListener}.</p> * * @param listener The {@link DialogInterface.OnCancelListener} to use. */ setOnCancelListener(listener:DialogInterface.OnCancelListener):void { if (this.mCancelAndDismissTaken != null) { throw Error(`new IllegalStateException("OnCancelListener is already taken by " + this.mCancelAndDismissTaken + " and can not be replaced.")`); } if (listener != null) { this.mCancelMessage = this.mListenersHandler.obtainMessage(Dialog.CANCEL, listener); } else { this.mCancelMessage = null; } } /** * Set a message to be sent when the dialog is canceled. * @param msg The msg to send when the dialog is canceled. * @see #setOnCancelListener(android.content.DialogInterface.OnCancelListener) */ setCancelMessage(msg:Message):void { this.mCancelMessage = msg; } /** * Set a listener to be invoked when the dialog is dismissed. * @param listener The {@link DialogInterface.OnDismissListener} to use. */ setOnDismissListener(listener:DialogInterface.OnDismissListener):void { if (this.mCancelAndDismissTaken != null) { throw Error(`new IllegalStateException("OnDismissListener is already taken by " + this.mCancelAndDismissTaken + " and can not be replaced.")`); } if (listener != null) { this.mDismissMessage = this.mListenersHandler.obtainMessage(Dialog.DISMISS, listener); } else { this.mDismissMessage = null; } } /** * Sets a listener to be invoked when the dialog is shown. * @param listener The {@link DialogInterface.OnShowListener} to use. */ setOnShowListener(listener:DialogInterface.OnShowListener):void { if (listener != null) { this.mShowMessage = this.mListenersHandler.obtainMessage(Dialog.SHOW, listener); } else { this.mShowMessage = null; } } /** * Set a message to be sent when the dialog is dismissed. * @param msg The msg to send when the dialog is dismissed. */ setDismissMessage(msg:Message):void { this.mDismissMessage = msg; } /** @hide */ takeCancelAndDismissListeners(msg:string, cancel:DialogInterface.OnCancelListener, dismiss:DialogInterface.OnDismissListener):boolean { if (this.mCancelAndDismissTaken != null) { this.mCancelAndDismissTaken = null; } else if (this.mCancelMessage != null || this.mDismissMessage != null) { return false; } this.setOnCancelListener(cancel); this.setOnDismissListener(dismiss); this.mCancelAndDismissTaken = msg; return true; } ///** // * By default, this will use the owner Activity's suggested stream type. // * // * @see Activity#setVolumeControlStream(int) // * @see #setOwnerActivity(Activity) // */ //setVolumeControlStream(streamType:number):void { // this.getWindow().setVolumeControlStream(streamType); //} // ///** // * @see Activity#getVolumeControlStream() // */ //getVolumeControlStream():number { // return this.getWindow().getVolumeControlStream(); //} /** * Sets the callback that will be called if a key is dispatched to the dialog. */ setOnKeyListener(onKeyListener:DialogInterface.OnKeyListener):void { this.mOnKeyListener = onKeyListener; } } export module Dialog { export class ListenersHandler extends Handler { private mDialog:WeakReference<DialogInterface>; constructor(dialog:Dialog) { super(); this.mDialog = new WeakReference<DialogInterface>(dialog); } handleMessage(msg:Message):void { switch (msg.what) { case Dialog.DISMISS: (<DialogInterface.OnDismissListener> msg.obj).onDismiss(this.mDialog.get()); break; case Dialog.CANCEL: (<DialogInterface.OnCancelListener> msg.obj).onCancel(this.mDialog.get()); break; case Dialog.SHOW: (<DialogInterface.OnShowListener> msg.obj).onShow(this.mDialog.get()); break; } } } } }
the_stack
import app = require("./app"); import {autoFocus} from "./utils"; // import * as CodeMirror from "codemirror"; import {Element, Handler, RenderHandler, Renderer} from "./microReact"; declare var CodeMirror; let WebSocket = require('ws'); let uuid = require("uuid"); // ------------------ // Preamble // ------------------ enum CardState { NONE, GOOD, PENDING, CLOSED, ERROR, } enum ConnectionState { CONNECTED, DISCONNECTED, CONNECTING, } enum CardDisplay { QUERY, RESULT, BOTH, } enum ResultsDisplay { TABLE, GRAPH, INFO, MESSAGE, HISTORY, NONE, } export interface QueryMessage { type: string, query: string, id: string, } export interface CloseMessage { type: string, id: string, } export interface ResultMessage { type: string, id: string, timestamp?: number, fields: Array<string>, insert: Array<Array<any>>, remove: Array<Array<any>>, } interface Query { id: string, query: string, result: QueryResult, info: QueryInfo, message: string, } interface QueryResult { fields: Array<string>, values: Array<Array<any>>, } interface QueryInfo { id: string, raw: string, smil: string, weasl: string, } interface ReplCard { id: string, row: number, col: number, state: CardState, focused: boolean, query: Query, history: Array<ResultMessage>, display: CardDisplay, resultDisplay: ResultsDisplay, } interface ServerConnection { state: ConnectionState, queue: Array<QueryMessage | CloseMessage>, ws: any, timer: any, timeout: number, } interface Deck { columns: number, focused: ReplCard, cards: Array<ReplCard>, } interface Chat { visible: boolean, unread: number, messages: Array<{ id: string, user: string, message: string, time: number, }>, } interface Repl { init: boolean, user: { id: string, name?: string, username?: string, }, chat: Chat, system: { entities: Query, tags: Query, //queries?: Query, users: Query, messages: Query, }, decks: Array<Deck>, deck: Deck, promisedQueries: Array<Query>, modal: any, server: ServerConnection, } // ------------------ // Storage functions // ------------------ function saveCard(card: ReplCard) { localStorage.setItem("everepl-" + card.id, JSON.stringify(card)); } function loadCards(): Array<ReplCard> { let storedCards: Array<ReplCard> = []; for (let item in localStorage) { if (item.substr(0,7) === "everepl") { let storedReplCard = JSON.parse(localStorage[item]); storedCards.push(storedReplCard); } } // Reset card properties if (storedCards.length > 0) { storedCards.map((r) => r.focused = false); } return storedCards; } function deleteStoredCard(card: ReplCard) { localStorage.removeItem("everepl-" + card.id); } /* function saveCards() { let serialized = JSON.stringify(replCards.filter((r) => r.state !== CardState.NONE).map((r) => r.query)); let blob = new Blob([serialized], {type: "application/json"}); let url = URL.createObjectURL(blob); repl.blob = url; }*/ /* function saveTable() { let replCard = replCards.filter((r) => r.focused).pop(); if (replCard !== undefined) { // If the card has results, form the csv if (typeof replCard.result === 'object') { let result: any = replCard.result; let fields:string = result.fields.join(","); let rows: Array<string> = result.values.map((row) => { return row.join(","); }); let csv: string = fields + "\r\n" + rows.join("\r\n"); let blob = new Blob([csv], {type: "text/csv"}); let url = URL.createObjectURL(blob); repl.csv = url; } else { repl.csv = undefined; } } }*/ /* function loadCards(event:Event, elem) { let target = <HTMLInputElement>event.target; if(!target.files.length) return; if(target.files.length > 1) throw new Error("Cannot load multiple files at once"); let file = target.files[0]; let reader = new FileReader(); reader.onload = function(event:any) { let serialized = event.target.result; let queries = JSON.parse(serialized); let cards = queries.map((q) => { let card = newReplCard(); card.query = q; return card; }); replCards = cards; replCards.forEach((r,i) => r.ix = i); replCards.forEach((r) => submitReplCard(r)); rerender(); }; reader.readAsText(file); event.stopPropagation(); closeModals(); rerender(); }*/ // ------------------ // Server functions // ------------------ function connectToServer() { let host = location.host || "localhost:8081"; let wsAddress = `ws://${host}`; let ws: WebSocket = new WebSocket(wsAddress, []); repl.server.ws = ws; ws.onopen = function(e: Event) { repl.server.state = ConnectionState.CONNECTED; // Initialize the repl state if (repl.init === false) { objectToArray(repl.system).map(sendQuery); // Retrieve the object from storage let userID = localStorage.getItem('repl-user'); if (userID !== null) { repl.user = {id: userID}; } } // In the case of a reconnect, reset the timeout // and send queued messages repl.server.timeout = 0; while(repl.server.queue.length > 0) { let message = repl.server.queue.shift(); sendMessage(message); } rerender(); } ws.onerror = function(error) { repl.server.state = ConnectionState.DISCONNECTED; repl.init = false; objectToArray(repl.system).map((q: Query) => q.result = undefined); rerender(); } ws.onclose = function(error) { repl.server.state = ConnectionState.DISCONNECTED; repl.init = false; objectToArray(repl.system).map((q: Query) => q.result = undefined); /*repl.deck.cards.map((c) => { c.state = CardState.PENDING c.query.result = undefined; c.display = CardDisplay.QUERY; });*/ reconnect(); rerender(); } ws.onmessage = function(message) { //console.log("message") //console.log(message.data); let parsed = JSON.parse(message.data.replace(/\n/g,'\\\\n').replace(/\r/g,'\\\\r').replace(/\t/g,' ').replace(/\\\\"/g,'\\"')); // Update the result of the correct repl card let targetCard = repl.deck.cards.filter((r) => r.id === parsed.id).shift(); if (targetCard !== undefined) { if (parsed.type === "result") { let resultMsg: ResultMessage = parsed; resultMsg.timestamp = new Date().getTime(); if (resultMsg.fields.length > 0) { // If the card is pending, it was submitted manually, // so we replace the values with the inserts if (targetCard.state === CardState.PENDING) { targetCard.display = CardDisplay.BOTH; targetCard.resultDisplay = ResultsDisplay.TABLE; targetCard.query.result = undefined; } if (resultMsg.insert.length > 0 || resultMsg.remove.length > 0) { targetCard.history.push(resultMsg); } updateQueryResult(targetCard.query, resultMsg); } else { targetCard.resultDisplay = ResultsDisplay.NONE; } targetCard.state = CardState.GOOD; if (targetCard.resultDisplay === ResultsDisplay.MESSAGE) { targetCard.resultDisplay = ResultsDisplay.TABLE; } //saveReplCard(targetCard); } else if (parsed.type === "error") { targetCard.state = CardState.ERROR; targetCard.query.message = parsed.cause; targetCard.display = CardDisplay.BOTH; targetCard.resultDisplay = ResultsDisplay.MESSAGE; targetCard.query.info = undefined; targetCard.query.result = undefined; //saveReplCard(targetCard); } else if (parsed.type === "close") { /*let removeIx = repl.deck.cards.map((r) => r.id).indexOf(parsed.id); if (removeIx >= 0) { replCards[removeIx].state = CardState.CLOSED; }*/ rerender(); } else if (parsed.type === "query-info") { let info: QueryInfo = { id: parsed.id, raw: parsed.raw, smil: parsed.smil, weasl: parsed.weasl, }; targetCard.query.info = info; if (targetCard.resultDisplay === ResultsDisplay.NONE) { targetCard.resultDisplay = ResultsDisplay.INFO; } } else { return; } // If the query ID was not matched to a repl card, then it should // match a system query } else { let targetSystemQuery: Query = objectToArray(repl.system).filter((q) => q.id === parsed.id).shift(); if (targetSystemQuery !== undefined) { if (parsed.type === "result") { let resultMsg: ResultMessage = parsed; updateQueryResult(targetSystemQuery, resultMsg); // Update the repl based on these new system queries /* @NOTE Disabled for now if (repl.system.queries !== undefined && parsed.id === repl.system.queries.id && parsed.insert !== undefined) { parsed.insert.forEach((n) => { let replCard = getCard(n[1], n[2]); if (replCard === undefined) { replCard = newReplCard(n[1], n[2]); repl.deck.cards.push(replCard); } replCard.id = n[0]; replCard.query.id = replCard.id; replCard.query.query = n[4]; if (replCard.state === CardState.NONE) { submitCard(replCard); } }); }*/ } else { return; } // If we have an update to the user query, match it against the stored ID to validate if (targetSystemQuery.id === repl.system.users.id && repl.user !== undefined && repl.user.name === undefined) { // Check if the stored user is in the database let dbUsers = repl.system.users.result.values; let ix = dbUsers.map((u) => u[0]).indexOf(repl.user.id) if (ix >= 0) { repl.user = {id: dbUsers[ix][0], name: dbUsers[ix][1], username: dbUsers[ix][2] }; // We found a user! Ask for all the queries by that user /* @NOTE Disabled for now if (repl.system.queries === undefined) { repl.system.queries = newQuery(`(query [id row col display query] (fact id :tag "repl-card" :tag "system" :user "${repl.user.id}" :row row :col col :display display :query query))`); sendQuery(repl.system.queries); }*/ } // Decode a chat message and put it in the system } else if (targetSystemQuery.id === repl.system.messages.id) { let newMessages = parsed.insert.map((m) => {return {id: m[0], user: m[1], message: m[2], time: m[3]}; }); repl.chat.messages = repl.chat.messages.concat(newMessages); if (repl.chat.visible === false) { repl.chat.unread += newMessages.length; } } // Mark the repl as initialized if all the system queries have been populated if (repl.init === false && objectToArray(repl.system).every((q: Query) => q.result !== undefined)) { if (repl.system.users.result.values.length === 0) { let addUsers = `(query [] (insert-fact! "8abecbae-3984-11e6-ac61-9e71128cae77" :tag "repl-user" :tag "system" :name "Eve" :username "eve" :password "eve") (insert-fact! "9f546210-20aa-460f-ab7b-55800bec82f0" :tag "repl-user" :tag "system" :name "Corey" :username "corey" :password "corey") (insert-fact! "3037e028-3395-4d8c-a0a7-0e92368c9ec3" :tag "repl-user" :tag "system" :name "Eric" :username "eric" :password "eric") (insert-fact! "62741d3b-b94a-4417-9794-1e6f86e262b6" :tag "repl-user" :tag "system" :name "Josh" :username "josh" :password "josh") (insert-fact! "d4a6dc56-4b13-41d5-be48-c656541cfac1" :tag "repl-user" :tag "system" :name "Chris" :username "chris" :password "chris"))` sendAnonymousQuery(addUsers); } else { repl.init = true; // @NOTE temporary: submit all the repl cards for evaluation repl.deck.cards.filter((c) => c.query !== undefined && c.query.query !== "").map(submitCard); } } } } rerender(); }; } function reconnect() { if(repl.server.state === ConnectionState.CONNECTED) { clearTimeout(repl.server.timer); repl.server.timer = undefined; } else { repl.server.timer = setTimeout(connectToServer, repl.server.timeout * 1000); } if (repl.server.timeout < 32) { repl.server.timeout += repl.server.timeout > 0 ? repl.server.timeout : 1; } } function sendMessage(message): boolean { if (repl.server.ws.readyState === repl.server.ws.OPEN) { repl.server.ws.send(JSON.stringify(message)); return true; } else { repl.server.queue.push(message); return false; } } // ------------------ // Query functions // ------------------ function newQuery(queryString: string): Query { let query: Query = { id: uuid(), query: queryString, result: undefined, message: "", info: undefined, }; return query; } function sendQuery(query: Query): boolean { let queryMessage: QueryMessage = { type: "query", id: query.id, query: query.query, }; return sendMessage(queryMessage); } function sendClose(query: Query): boolean { let closeMessage: CloseMessage = { type: "close", id: query.id, } return sendMessage(closeMessage); } function sendAnonymousQuery(query: string) { let anonID = uuid(); let queryMessage: QueryMessage = { type: "query", id: anonID, query: query, }; let closeMessage: CloseMessage = { type: "close", id: anonID, } sendMessage(queryMessage); sendMessage(closeMessage); } // --------------------- // Card/Query functions // --------------------- function newReplCard(row?: number, col? :number): ReplCard { let id = uuid(); let replCard: ReplCard = { id: id, row: row === undefined ? 0 : row, col: col === undefined ? 0 : col, state: CardState.NONE, focused: false, query: { id: id, query: "", result: undefined, message: "", info: undefined, }, history: [], display: CardDisplay.QUERY, resultDisplay: ResultsDisplay.MESSAGE, } return replCard; } /* function deleteReplCard(replCard: ReplCard) { if (replCard.state !== CardState.NONE) { let closemessage = { type: "close", id: replCard.id, }; sendMessage(closemessage); replCard.state = CardState.PENDING; replCard.result = "Deleting card..."; } }*/ function getCard(row: number, col: number): ReplCard { return repl.deck.cards.filter((r) => r.row === row && r.col === col).shift(); } function submitCard(card: ReplCard) { let query = card.query; // If it does exist, remove the previous repl-card row and close the old query if (card.state !== CardState.NONE) { // Delete a row from the repl-card table let delQuery = `(query [] (fact-btu "${card.id}" :tick t) (remove-by-t! t))`; sendAnonymousQuery(delQuery); // Close the old query if (card.state === CardState.GOOD) { sendClose(card.query); } } // Insert a row in the repl-card table /* @NOTE Disable for now let rcQuery = `(query [] (insert-fact! "${card.id}" :tag "repl-card" :tag "system" :row ${card.row} :col ${card.col} :user "${repl.user.id}" :query "${card.query.query.replace(/"/g,'\\"')}" :display ${card.display}))`; sendAnonymousQuery(rcQuery);*/ saveCard(card); // Send the actual query let sent = sendQuery(card.query); let queryText = card.query.query; if(queryText.indexOf("insert-fact!") > -1 || queryText.indexOf("remove-by-t!") > -1 || queryText.indexOf("remove-fact!") > -1) { sendClose(card.query); } card.state = CardState.PENDING; if (card.query.result === undefined) { if (sent) { card.query.message = "Waiting for response..."; } else { card.query.message = "Message queued."; } } // Create a new card if we submitted the last one in the col let emptyCardsInCol = repl.deck.cards.filter((r) => r.col === card.col && r.state === CardState.NONE); if (emptyCardsInCol.length === 0) { addCardToColumn(repl.deck.focused.col); } rerender(); } function updateQueryResult(query: Query, message: ResultMessage) { if (query.result === undefined || query.result.fields.length !== message.fields.length) { query.result = { fields: message.fields, values: message.insert, }; } else { // Apply inserts query.result.values = query.result.values.concat(message.insert); // Apply removes message.remove.forEach((row) => { removeRow(row,query.result.values); }); } } function addColumn() { let nCard = newReplCard(0,++repl.deck.columns); repl.deck.cards.push(nCard); } function addCardToColumn(col: number): ReplCard { let row = repl.deck.cards.filter((r) => r.col === col).length; let nCard = newReplCard(row, col); repl.deck.cards.push(nCard); focusCard(nCard); return nCard; } function blurCard(replCard: ReplCard) { replCard.focused = false; let cm = getCodeMirrorInstance(replCard); if (cm !== undefined) { cm.getInputField().blur(); } } function deleteCard(card: ReplCard) { //console.log(card); // Delete a row from the repl-card table let delQuery = `(query [] (fact-btu "${card.id}" :tick t) (remove-by-t! t))`; sendAnonymousQuery(delQuery); // find the index in the deck let ix = repl.deck.cards.map((c) => c.id).indexOf(card.id); // remove the card from the deck repl.deck.cards.splice(ix,1); // Remove the card from local storage deleteStoredCard(card); // Renumber the cards repl.deck.cards.filter((r) => r.col === card.col && r.row > card.row).forEach((c,i) => c.row = i + card.row); // Add a card to the column if there are none left if (repl.deck.cards.filter((c) => c.col === card.col).length === 0) { repl.deck.cards.push(newReplCard(0, card.col)); } // send a remove to the server sendClose(card.query); } function focusCard(replCard: ReplCard) { if (replCard !== undefined) { if (repl.deck.focused.id !== replCard.id) { //blurCard(repl.deck.focused); } repl.deck.cards.forEach((r) => r.focused = false); replCard.focused = true; repl.deck.focused = replCard; // @HACK The timeout allows the CM instance time to render // otherwise, I couldn't focus it, because it didn't exist // when the call was made let cm = getCodeMirrorInstance(replCard); //console.log(cm); if (cm !== undefined) { cm.focus() } else { setTimeout(function() { cm = getCodeMirrorInstance(replCard); if (cm !== undefined) { cm.focus(); } }, 100); } } } function submitChatMessage(message: string) { let d = new Date(); let t = d.getTime(); let messageInsert = `(query [] (insert-fact! "${uuid()}" :tag "system" :tag "repl-chat" :message "${message}" :user "${repl.user.id}" :timestamp "${t}"))`; sendAnonymousQuery(messageInsert); } // ------------------ // Event handlers // ------------------ // Register some global event handlers on the window window.onkeydown = function(event) { let thisReplCard = repl.deck.focused; let modified = event.ctrlKey || event.metaKey; // Catch ctrl + arrow up or page up if (event.keyCode === 38 && modified || event.keyCode === 33) { // Set the focus to the previous repl card let previousReplCard = getReplCard(thisReplCard.row - 1, thisReplCard.col); focusCard(previousReplCard); // Catch ctrl + arrow down or page down } else if (event.keyCode === 40 && modified || event.keyCode === 34) { // Set the focus to the next repl card let nextReplCard = getReplCard(thisReplCard.row + 1, thisReplCard.col); //console.log(nextReplCard.query); focusCard(nextReplCard); // Catch ctrl + arrow left } else if (event.keyCode === 37 && modified) { let leftReplCard = getReplCard(thisReplCard.row, thisReplCard.col - 1); if (leftReplCard !== undefined) { focusCard(leftReplCard); } else { let rowsInPrevCol = repl.deck.cards.filter((r) => r.col === thisReplCard.col - 1).length - 1; leftReplCard = getReplCard(rowsInPrevCol, thisReplCard.col - 1); focusCard(leftReplCard); } // Catch ctrl + arrow right } else if (event.keyCode === 39 && modified) { let rightReplCard = getReplCard(thisReplCard.row, thisReplCard.col + 1); if (rightReplCard !== undefined) { focusCard(rightReplCard); } else { let rowsInNextCol = repl.deck.cards.filter((r) => r.col === thisReplCard.col + 1).length - 1; rightReplCard = getReplCard(rowsInNextCol, thisReplCard.col + 1); focusCard(rightReplCard); } // Catch ctrl + y } else if (event.keyCode === 89 && event.ctrlKey) { addColumn(); // Catch ctrl + e } else if (event.keyCode === 69 && modified) { addCardToColumn(repl.deck.focused.col); } else { return; } event.preventDefault(); rerender(); } window.onbeforeunload = function(event) { // Close all open queries before we close the window repl.deck.cards.filter((c) => c.state === CardState.GOOD).map((c) => sendClose(c.query)); // Close all system queries objectToArray(repl.system).map(sendClose); } function queryInputKeydown(event, elem) { let thisReplCard: ReplCard = elemToReplCard(elem); let modified = event.ctrlKey || event.metaKey; // Submit the query with ctrl + enter or ctrl + s if ((event.keyCode === 13 || event.keyCode === 83) && modified) { submitCard(thisReplCard); // Catch ctrl + delete to remove a card } else if (event.keyCode === 46 && modified) { deleteCard(thisReplCard); // Catch ctrl + home } else if (event.keyCode === 36 && modified) { //focusCard(replCards[0]); // Catch ctrl + end } else if (event.keyCode === 35 && modified) { //focusCard(replCards[replCards.length - 1]); // Catch ctrl + b } else if (event.keyCode === 66 && modified) { thisReplCard.query.query = "(query [e a v]\n\t(fact-btu e a v))"; // Catch ctrl + q } else if (event.keyCode === 81 && modified) { thisReplCard.query.query = "(query [] \n\t\n)"; let cm = getCodeMirrorInstance(thisReplCard); // @HACK Wait for CM to render setTimeout(function () {cm.getDoc().setCursor({line: 1, ch: 1});},10); } else { return; } event.preventDefault(); rerender(); } function queryInputBlur(event, elem) { /*let cm = getCodeMirrorInstance(elemToReplCard(elem)); cm.getDoc().setCursor({line: 0, ch: 0}); rerender();*/ } function queryInputFocus(event, elem) { let focusedCard = elemToReplCard(elem); focusCard(focusedCard); rerender(); } /*function queryInputBlur(event, elem) { let thisReplCard = replCards[elem.ix]; thisReplCard.focused = false; rerender(); }*/ function replCardClick(event, elem) { let clickedCard = elemToReplCard(elem); if (clickedCard !== undefined) { focusCard(clickedCard); } rerender(); } function inputKeydown(event, elem) { // Capture enter if (event.keyCode === 13) { let inputs: any = document.querySelectorAll(".login input"); let username = inputs[0].value; let password = inputs[1].value; inputs[0].value = ""; inputs[1].value = ""; login(username, password); } else { return; } event.preventDefault(); } function loginSubmitClick(event, elem) { let inputs: any = document.querySelectorAll(".login input"); let username = inputs[0].value; let password = inputs[1].value; login(username, password); } function login(username,password) { let users = repl.system.users.result.values; for (let user of users) { if (username === user[2] && password === user[3]) { repl.user = {id: user[0], name: user[1], username: user[2]}; // Put the user into local storage localStorage.setItem('repl-user', user[0]); break; } } if (repl.user !== undefined) { rerender(); } } /* function deleteAllCards(event, elem) { replCards.forEach(deleteReplCard); closeModals(); event.stopPropagation(); rerender(); }*/ /* function focusQueryBox(node, element) { if (element.focused) { node.focus(); } }*/ /* function toggleTheme(event, elem) { var theme = localStorage["eveReplTheme"]; if (theme === "dark") { localStorage["eveReplTheme"] = "light"; } else if(theme === "light") { localStorage["eveReplTheme"] = "dark"; } else { localStorage["eveReplTheme"] = "dark"; } rerender(); } */ /* function saveCardsClick(event, elem) { closeModals(); saveCards(); saveTable(); event.stopPropagation(); rerender(); }*/ /* function trashCardsClick(event, elem) { closeModals(); repl.delete = true; event.stopPropagation(); rerender(); }*/ /* function loadCardsClick(event, elem) { closeModals(); repl.load = true; event.stopPropagation(); rerender(); }*/ function deleteCardClick(event, elem) { let card = repl.deck.focused; deleteCard(card); rerender(); } function addColumnClick(event, elem) { addColumn(); rerender(); } function addCardClick(event, elem) { addCardToColumn(repl.deck.focused.col); rerender(); } function toggleChatClick(event, elem) { if (repl.chat.visible) { repl.chat.visible = false; } else { repl.chat.unread = 0; repl.chat.visible = true; } } function chatInputKeydown(event, elem) { if (event.keyCode === 13) { let message = event.target.value; submitChatMessage(message); event.target.value = ""; } } function queryInputChange(event, elem) { let card = elemToReplCard(elem); let cm = getCodeMirrorInstance(card); card.query.query = cm.getValue(); } function queryResultClick(event, elem) { if (event.button === 1) { let card = elemToReplCard(elem); card.display = card.display === CardDisplay.BOTH ? CardDisplay.RESULT : CardDisplay.BOTH; event.preventDefault(); rerender(); } } function queryInputClick(event, elem) { if (event.button === 1) { let card = elemToReplCard(elem); card.display = card.display === CardDisplay.BOTH ? CardDisplay.QUERY : CardDisplay.BOTH; // If we can't see the query results, close the query if (card.display === CardDisplay.QUERY) { //sendClose(card.query); // If we can see the query results, open the query } else { // @TODO } event.preventDefault(); rerender(); } } function resultSwitchClick(event, elem) { let card = elemToReplCard(elem); card.resultDisplay = elem.data; event.preventDefault(); rerender(); } function entityListClick(event, elem) { // Filter out results for only the current entity let result: QueryResult = { fields: ["Attribute", "Value"], values: repl.system.entities.result.values.filter((e) => e[0] === elem.text).map((e) => [e[1], e[2]]), }; // Generate the table let table = generateResultTable(result); repl.modal = {c: "modal", left: 110, top: event.y, children: [table]}; // Prevent click event from propagating to another layer event.stopImmediatePropagation(); rerender(); } function tagsListClick(event, elem) { // Filter out results for only the current entity let result: QueryResult = { fields: ["Members"], values: repl.system.tags.result.values.filter((e) => e[0] === elem.text).map((e) => [e[1]]), }; // Generate the table let table = generateResultTable(result); repl.modal = {c: "modal", left: 110, top: event.y, children: [{c: "height-constrained", children: [table]}]}; // Prevent click event from propagating to another layer event.stopImmediatePropagation(); rerender(); } function rootClick(event, elem) { // Causes the open modal to close repl.modal = undefined; rerender(); } // ------------------ // Element generation // ------------------ function generateReplCardElement(replCard: ReplCard) { let queryInput = { row: replCard.row, col: replCard.col, key: `${replCard.id}${replCard.focused}`, focused: replCard.focused, c: `query-input ${replCard.display === CardDisplay.RESULT ? "hidden" : ""} ${replCard.display === CardDisplay.QUERY ? "stretch" : ""}`, value: replCard.query.query, //contentEditable: true, //spellcheck: false, //text: replCard.query, keydown: queryInputKeydown, //blur: queryInputBlur, //focus: queryInputFocus, change: queryInputChange, mouseup: queryInputClick, matchBrackets: true, lineNumbers: false, }; let replCardElement = { id: replCard.id, row: replCard.row, col: replCard.col, c: `repl-card ${replCard.focused ? " focused" : ""}`, click: replCardClick, //mousedown: function(event) {event.preventDefault();}, children: [codeMirrorElement(queryInput), generateResultElement(replCard)], }; return replCardElement; } function generateResultElement(card: ReplCard) { // Set the css according to the card state let resultcss = `query-result ${card.display === CardDisplay.QUERY ? "hidden" : ""}`; let result = undefined; let replClass = "repl-card"; // Build the results switches let tableSwitch = {c: `button ${card.resultDisplay === ResultsDisplay.TABLE ? "" : "disabled "}ion-grid`, text: " Table", data: ResultsDisplay.TABLE, row: card.row, col: card.col, click: resultSwitchClick }; let graphSwitch = {c: `button ${card.resultDisplay === ResultsDisplay.GRAPH ? "" : "disabled "}ion-stats-bars`, data: ResultsDisplay.GRAPH, row: card.row, col: card.col, text: " Graph"}; let messageSwitch = {c: `button ${card.resultDisplay === ResultsDisplay.MESSAGE ? "" : "disabled "}ion-quote`, data: ResultsDisplay.MESSAGE, row: card.row, col: card.col, text: " Message"}; let historySwitch = {c: `button ${card.resultDisplay === ResultsDisplay.HISTORY ? "" : "disabled "}ion-quote`, data: ResultsDisplay.HISTORY, row: card.row, col: card.col, text: " History", click: resultSwitchClick}; let infoSwitch = {c: `button ${card.resultDisplay === ResultsDisplay.INFO ? "" : "disabled "}ion-help`, data: ResultsDisplay.INFO, row: card.row, col: card.col, text: " Info", click: resultSwitchClick}; let switches = []; // Format card based on state if (card.state === CardState.GOOD) { resultcss += " good"; if (card.query.result !== undefined) { switches.push(tableSwitch); } if (card.history.length > 0) { switches.push(historySwitch); } } else if (card.state === CardState.ERROR) { resultcss += " error"; switches.push(messageSwitch); } else if (card.state === CardState.PENDING) { resultcss += " pending"; switches.push(messageSwitch); } else if (card.state === CardState.CLOSED) { resultcss += " closed"; switches.push(messageSwitch); } // Pick the results to display if (card.resultDisplay === ResultsDisplay.GRAPH) { // @TODO result = {}; } else if (card.resultDisplay === ResultsDisplay.INFO) { result = {c: "debug", children: [ {t: "h1", text: "Raw"}, {c: "code", text: card.query.info.raw}, {t: "h1", text: "SMIL :)"}, {c: "code", text: card.query.info.smil}, {t: "h1", text: "WEASL"}, {c: "code", text: card.query.info.weasl}, ]}; } else if (card.resultDisplay === ResultsDisplay.MESSAGE) { result = {text: card.query.message}; } else if (card.resultDisplay === ResultsDisplay.TABLE) { result = generateResultTable(card.query.result); } else if (card.resultDisplay === ResultsDisplay.HISTORY) { let tables = card.history.map((h) => { let insertTable = h.insert.length > 0 ? generateResultTable({fields: h.fields, values: h.insert}) : false; let removeTable = h.remove.length > 0 ? generateResultTable({fields: h.fields, values: h.remove}) : false; let historyChildren = []; if(insertTable || removeTable) { historyChildren.push({t: "h1", text: `Received: ${formatDate(h.timestamp)} ${formatTime(h.timestamp)}`}); } if(insertTable) { historyChildren.push({t: "h2", text: "Insert"}, insertTable); } if(removeTable) { historyChildren.push({t: "h2", text: "Remove"}, removeTable); } return {c: "", children: historyChildren}; }); result = {c: "", children: tables}; } // Add the info switch if there is info to be had if (card.query.info !== undefined) { switches.push(infoSwitch); } // Build the results switch container let resultViewSwitch = { c: "results-switch", children: switches, }; let queryResult = { c: resultcss, row: card.row, col: card.col, children: [resultViewSwitch, result], mouseup: queryResultClick, }; return queryResult; } function generateResultTable(result: QueryResult): any { if (result === undefined) { return {}; } if (result.fields.length > 0) { let tableHeader = {c: "header", children: result.fields.map((f: string) => { return {c: "cell", text: f}; })}; let tableBody = result.values.map((r: Array<any>) => { return {c: "row", children: r.map((c: any) => { return {c: "cell", text: `${`${c}`.replace(/\\t/g,' ')}`}; })}; }); let tableRows = [tableHeader].concat(tableBody); return {c: "table", children: tableRows}; } } function generateCardRootElements() { let cardRoot = { id: "card-root", c: "card-root", children: [], } // Build each column and add it to the card root let i; for (i = 0; i <= repl.deck.columns; i++) { let column = { id: `card-column-${i}`, c: "card-column", ix: i, children: repl.deck.cards.filter((r) => r.col === i).sort((a,b) => a.row - b.row).map(generateReplCardElement), }; cardRoot.children.push(column); } return cardRoot; } function generateStatusBarElement() { let indicator = "connecting"; if (repl.server.state === ConnectionState.CONNECTED) { indicator = "connected"; } else if (repl.server.state === ConnectionState.DISCONNECTED) { indicator = "disconnected"; } // Build the proper elements of the status bar let eveLogo = {t: "img", c: "logo", src: "http://witheve.com/logo.png", width: 643/15, height: 1011/15}; let deleteButton = {c: "button", text: "Delete Card", click: deleteCardClick}; let addColumn = {c: "button", text: "Add Column", click: addColumnClick}; let addCard = {c: "button", text: "Add Card", click: addCardClick}; //let importCSV = {c: "button", text: "Import CSV", click: importCSVClick}; // Chat button let unread = repl.chat.unread > 0 ? {c: "unread", text: `${repl.chat.unread}`} : {}; let toggleChat = {c: "button", children: [{c: "inline", text: "Chat"}, unread], click: toggleChatClick}; let buttonList = formListElement([deleteButton, addColumn, addCard, toggleChat]); // Build the entities table let entities: Array<any> = repl.system.entities.result !== undefined ? unique(repl.system.entities.result.values.map((e) => e[0])).map((e) => { return {c: "info-link", text: e, click: entityListClick }; }) : []; let entitiesElement = {c: "info", children: [formListElement(entities)]}; let entitiesTable = {c: "info-table", children: [{t: "h2", text: "Entities"}, entitiesElement]}; // Build the tags table let tags: Array<any> = repl.system.tags.result !== undefined ? unique(repl.system.tags.result.values.map((e) => e[0])).map((e) => { return {c: "info-link", text: e, click: tagsListClick }; }) : []; let tagsElement = {c: "info", children: [formListElement(tags)]}; let tagsTable = {c: "info-table", children: [{t: "h2", text: "Tags"}, tagsElement]}; // Build the status bar let statusBar = { id: "status-bar", c: "status-bar", children: [eveLogo, buttonList, entitiesTable, tagsTable], }; return statusBar; } function generateChatElement() { let chat = {}; if (repl.chat.visible) { let messageElements = repl.chat.messages.map((m) => { let userIx = repl.system.users.result.values.map((u) => u[0]).indexOf(m.user); let userName = repl.system.users.result.values[userIx][1]; return {c: "chat-message-box", children: [ {c: `chat-user ${m.user === repl.user.id ? "me" : ""}`, text: `${userName}`}, {c: "chat-time", text: `${formatTime(m.time)}`}, {c: "chat-message", text: `${m.message}`}, ]}; }); let conversation = {c: "conversation", children: messageElements}; let submitChat = {c: "button", text: "Submit"}; let chatInput = {t: "input", c: "chat-input", keydown: chatInputKeydown}; chat = {c: "chat-bar", children: [conversation, chatInput]}; } return chat; } // ----------------- // Entry point // ----------------- // Create an initial repl card //let defaultCard = newReplCard(); let storedCards = loadCards(); if (storedCards.length === 0) { storedCards.push(newReplCard()); } let replCards: Deck = { columns: storedCards.map((c) => c.col).sort().pop(), cards: storedCards, focused: storedCards[0], } // Instantiate a repl instance let repl: Repl = { init: false, user: undefined, system: { entities: newQuery(`(query [entities attributes values] (fact-btu entities attributes values) (not (fact entities :tag "system")))`), // get all entities that are not system entities tags: newQuery(`(query [tag entity], (fact entity :tag tag) (not (fact entity :tag "system")))`), // get all tags that are not system tags users: newQuery(`(query [id name username password] (fact id :tag "repl-user" :name name :username username :password password))`), // get all users messages: newQuery(`(query [id user message time] (fact id :tag "repl-chat" :message message :user user :timestamp time))`), // get the chat history }, chat: { visible: false, unread: 0, messages: [], }, decks: [replCards], deck: replCards, promisedQueries: [], modal: undefined, server: { queue: [], state: ConnectionState.CONNECTING, ws: null, timer: undefined, timeout: 0, }, }; connectToServer(); app.renderRoots["repl"] = root; function root() { let replChildren; let eveLogo = {t: "img", c: "logo", src: "http://witheve.com/logo.png", width: 643/5, height: 1011/5}; // If the system is ready and there is a user, load the repl if (repl.init === true && repl.user !== undefined && repl.user.name !== undefined) { replChildren = [generateStatusBarElement(), generateChatElement(), generateCardRootElements(), repl.modal !== undefined ? repl.modal : {}]; // If the system is ready but there is no user, show a login page } else if (repl.init === true && repl.user === undefined) { let username = {t: "input", id: "repl-username-input", placeholder: "Username", keydown: inputKeydown}; let password = {t: "input", id: "repl-password-input", type: "password", placeholder: "Password", keydown: inputKeydown}; let submit = {c: "button", text: "Submit", click: loginSubmitClick}; let login = {c: "login", children: [eveLogo, username, password, submit]} replChildren = [login]; // If the system is disconnected, show a reconnect page } else if (repl.server.state === ConnectionState.DISCONNECTED) { replChildren = [{c: "login", children: [eveLogo, {text: "Disconnected from Eve server."}, {c: "button", text: "Reconnect", click: connectToServer}]}]; // If the system is not ready, display a loading page } else { replChildren = [{c: "login", children: [eveLogo, {text: "Loading Eve Database..."}]}]; } //replChildren = [generateStatusBarElement(), generateChatElement(), generateCardRootElements(), repl.modal !== undefined ? repl.modal : {}]; let root = { id: "repl", c: "repl", click: rootClick, children: replChildren, }; return root; } // ----------------- // Utility Functions // ----------------- function formatTime(timestamp: number): string { let d = new Date(0); d.setUTCMilliseconds(timestamp); let hrs = d.getHours() > 12 ? d.getHours() - 12 : d.getHours(); let mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes(); let ampm = d.getHours() < 12 ? "AM" : "PM"; let timeString = `${hrs}:${mins} ${ampm}` return timeString; } function formatDate(timestamp: number): string { let d = new Date(0); d.setUTCMilliseconds(timestamp); let day = d.getDate(); let month = d.getMonth(); let year = d.getFullYear(); let date = `${month}/${day}/${year}`; return date; } function removeRow(row: Array<any>, array: Array<Array<any>>) { let ix; for (let i = 0; i < array.length; i++) { let value = array[i]; if (arraysEqual(row,value)) { ix = i; break; } } // If we found the row, remove it from the values if (ix !== undefined) { array.splice(ix,1); } } function arraysEqual(a, b) { if (a === b) return true; if (a == null || b == null) return false; if (a.length !== b.length) return false; for (let i = 0; i < a.length; ++i) { if (a[i] !== b[i]) return false; } return true; } function unique(array: Array<any>): Array<any> { array = array.filter((e,i) => array.indexOf(e) === i); return array; } function formListElement(list: Array<any>) { let li = list.map((e) => {return {t: "li", children: [e]};}); return {t: "ul", children: li}; } function resultToObject(result): Object { // @TODO return {}; } function objectToArray(obj: Object): Array<any> { return Object.keys(obj).map(key => obj[key]); } function elemToReplCard(elem): ReplCard { if (elem.col !== undefined && elem.row !== undefined) { return repl.deck.cards.filter((r) => r.col === elem.col && r.row === elem.row).pop(); } return undefined; } function getReplCard(row: number, col: number): ReplCard { return repl.deck.cards.filter((r) => r.row === row && r.col === col).pop(); } function rerender() { app.dispatch("rerender", {}).commit(); } // Codemirror! function getCodeMirrorInstance(replCard: ReplCard): CodeMirror.Editor { let targets = document.querySelectorAll(".query-input"); for (let i = 0; i < targets.length; i++) { let target = targets[i]; if (target.parentElement["_id"] === replCard.id) { return target["cm"]; } } return undefined; } interface CMNode extends HTMLElement { cm: any } interface CMEvent extends Event { editor: CodeMirror.Editor value: string } export function codeMirrorElement(elem: CMElement): CMElement { elem.postRender = codeMirrorPostRender(elem.postRender); elem["cmChange"] = elem.change; elem["cmBlur"] = elem.blur; elem["cmFocus"] = elem.focus; elem.change = undefined; elem.blur = undefined; elem.focus = undefined; return elem; } interface CMElement extends Element { autoFocus?: boolean lineNumbers?: boolean, lineWrapping?: boolean, mode?: string, shortcuts?: {[shortcut:string]: Handler<any>} }; let _codeMirrorPostRenderMemo = {}; function handleCMEvent(handler:Handler<Event>, elem:CMElement):(cm:CodeMirror.Editor) => void { return (cm:CodeMirror.Editor) => { let evt = <CMEvent><any>(new CustomEvent("CMEvent")); evt.editor = cm; evt.value = cm.getDoc().getValue(); handler(evt, elem); } } function codeMirrorPostRender(postRender?: RenderHandler): RenderHandler { let key = postRender ? postRender.toString() : ""; if(_codeMirrorPostRenderMemo[key]) return _codeMirrorPostRenderMemo[key]; return _codeMirrorPostRenderMemo[key] = (node:CMNode, elem:CMElement) => { let cm = node.cm; if(!cm) { let extraKeys = {}; if(elem.shortcuts) { for(let shortcut in elem.shortcuts) extraKeys[shortcut] = handleCMEvent(elem.shortcuts[shortcut], elem); } cm = node.cm = CodeMirror(node, { lineWrapping: elem.lineWrapping !== false ? true : false, lineNumbers: elem.lineNumbers, mode: elem.mode || "clojure", matchBrackets: true, autoCloseBrackets: true, extraKeys }); if(elem["cmChange"]) cm.on("change", handleCMEvent(elem["cmChange"], elem)); if(elem["cmBlur"]) cm.on("blur", handleCMEvent(elem["cmBlur"], elem)); if(elem["cmFocus"]) cm.on("focus", handleCMEvent(elem["cmFocus"], elem)); if(elem.autoFocus) cm.focus(); } if(cm.getDoc().getValue() !== elem.value) { cm.setValue(elem.value || ""); if(elem["cursorPosition"] === "end") { cm.setCursor(100000); } } if(postRender) postRender(node, elem); } }
the_stack
import { CdmCorpusDefinition, CdmDataPartitionDefinition, CdmEntityDeclarationDefinition, CdmEntityDefinition, cdmIncrementalPartitionType, CdmLocalEntityDeclarationDefinition, CdmManifestDefinition, cdmObjectType, cdmStatusLevel, constants, copyOptions, enterScope, resolveContext, resolveOptions, } from '../../../../internal'; import { CdmFolder } from '../../../../Persistence'; import { DataPartition, EntityDeclarationDefinition, ManifestContent, KeyValPair, TraitReference } from '../../../../Persistence/CdmFolder/types'; import { testHelper } from '../../../testHelper'; import { createDocumentForEntity } from '../../../Cdm/CdmCollection/CdmCollectionHelperFunctions'; import { using } from 'using-statement'; describe('Persistence.CdmFolder.DataPartition', () => { /// <summary> /// The path between TestDataPath and TestName. /// </summary> const testsSubpath: string = 'Persistence/CdmFolder/DataPartition'; const doesWriteTestDebuggingFiles: boolean = false; /** * Testing for Manifest instance with local entity declaration having data partitions. */ it('TestLoadLocalEntityWithDataPartition', () => { const readFile: string = testHelper.getInputFileContent( testsSubpath, 'TestLoadLocalEntityWithDataPartition', 'entities.manifest.cdm.json'); const cdmManifest: CdmManifestDefinition = CdmFolder.ManifestPersistence.fromObject( new resolveContext(new CdmCorpusDefinition(), undefined), 'entities', 'testNamespace', '/', JSON.parse(readFile)); expect(cdmManifest.entities.length) .toBe(1); expect(cdmManifest.entities.allItems[0].getObjectType()) .toBe(cdmObjectType.localEntityDeclarationDef); const entity: CdmLocalEntityDeclarationDefinition = cdmManifest.entities.allItems[0] as CdmLocalEntityDeclarationDefinition; expect(entity.dataPartitions.length) .toBe(2); const relativePartition: CdmDataPartitionDefinition = entity.dataPartitions.allItems[0]; expect(relativePartition.name) .toBe('Sample data partition'); expect(relativePartition.location) .toBe('test/location'); expect(relativePartition.lastFileModifiedTime.toUTCString()) .toBe('Mon, 15 Sep 2008 23:53:23 GMT'); expect(relativePartition.exhibitsTraits.length) .toBe(1); expect(relativePartition.specializedSchema) .toBe('teststring'); const testList: string[] = relativePartition.arguments.get('test'); expect(testList.length) .toEqual(3); expect(testList[0]) .toEqual('something'); expect(testList[1]) .toEqual('somethingelse'); expect(testList[2]) .toEqual('anotherthing'); const keyList: string[] = relativePartition.arguments.get('KEY'); expect(keyList.length) .toEqual(1); expect(keyList[0]) .toEqual('VALUE'); expect(relativePartition.arguments.has('wrong')) .toBeFalsy(); const absolutePartition: CdmDataPartitionDefinition = entity.dataPartitions.allItems[1]; expect(absolutePartition.location) .toBe('local:/some/test/location'); }); /** * Manifest.DataPartitions.Arguments can be read in multiple forms, * but should always be serialized as {name: 'theName', value: 'theValue'}. */ it('TestDataPartitionArgumentsAreSerializedAppropriately', () => { const readFile: string = testHelper.getInputFileContent( testsSubpath, 'TestDataPartitionArgumentsAreSerializedAppropriately', 'entities.manifest.cdm.json'); const cdmManifest: CdmManifestDefinition = CdmFolder.ManifestPersistence.fromObject( new resolveContext(new CdmCorpusDefinition(), undefined), 'entities', 'testNamespace', '/', JSON.parse(readFile)); const obtainedCdmFolder: ManifestContent = CdmFolder.ManifestPersistence.toData(cdmManifest, undefined, undefined); if (doesWriteTestDebuggingFiles) { testHelper.writeActualOutputFileContent( testsSubpath, 'TestDataPartitionArgumentsAreSerializedAppropriately', 'savedManifest.manifest.cdm.json', JSON.stringify(obtainedCdmFolder)); } const expectedOutput: string = testHelper.getExpectedOutputFileContent( testsSubpath, 'TestDataPartitionArgumentsAreSerializedAppropriately', 'savedManifest.manifest.cdm.json'); const expectedManifest: object = JSON.parse(expectedOutput) as object; expect(testHelper.compareObjectsContent(obtainedCdmFolder, expectedManifest, true)) .toBeTruthy(); }); /** * Testing programmatically creating manifest with partitions and persisting */ it('TestProgrammaticallyCreatePartitions', async () => { const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestProgrammaticallyCreatePartitions', undefined, undefined, undefined, false); const manifest: CdmManifestDefinition = corpus.MakeObject<CdmManifestDefinition>(cdmObjectType.manifestDef, 'manifest'); const entity: CdmEntityDeclarationDefinition = manifest.entities.push('entity'); const relativePartition: CdmDataPartitionDefinition = corpus.MakeObject<CdmDataPartitionDefinition>(cdmObjectType.dataPartitionDef, 'relative partition'); relativePartition.location = 'relative/path'; relativePartition.arguments.set('test1', [ 'argument1' ]); relativePartition.arguments.set('test2', [ 'argument2', 'argument3' ]); const absolutePartition: CdmDataPartitionDefinition = corpus.MakeObject<CdmDataPartitionDefinition>(cdmObjectType.dataPartitionDef, 'absolute partition'); absolutePartition.location = 'local:/absolute/path'; // add an empty arguments list to test empty list should not be displayed in ToData json. absolutePartition.arguments.set('test', []); entity.dataPartitions.push(relativePartition); entity.dataPartitions.push(absolutePartition); const manifestData: ManifestContent = CdmFolder.ManifestPersistence.toData(manifest, new resolveOptions(), new copyOptions()); expect(manifestData.entities.length) .toBe(1); const entityData: EntityDeclarationDefinition = manifestData.entities[0]; const partitionsList: DataPartition[] = entityData.dataPartitions; expect(partitionsList.length) .toBe(2); const relativePartitionData: DataPartition = partitionsList[0]; const absolutePartitionData: DataPartition = partitionsList[1]; expect(relativePartitionData.location) .toBe(relativePartition.location); const argumentsList: KeyValPair[] = relativePartitionData.arguments; expect(argumentsList.length) .toBe(3); expect(argumentsList[0].name) .toBe('test1'); expect(argumentsList[0].value) .toBe('argument1'); expect(argumentsList[1].name) .toBe('test2'); expect(argumentsList[1].value) .toBe('argument2'); expect(argumentsList[2].name) .toBe('test2'); expect(argumentsList[2].value) .toBe('argument3'); expect(absolutePartitionData.location) .toBe(absolutePartition.location); // test if empty argument list is set to null expect(absolutePartitionData.arguments) .toBeUndefined(); }); /** * Testing loading manifest with local entity declaration having an incremental partition without incremental trait. */ it('TestFromIncrementalPartitionWithoutTrait', async (done) => { const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestFromIncrementalPartitionWithoutTrait'); let errorMessageVerified: boolean = false // not checking the CdmLogCode here as we want to check if this error message constructed correctly for the partition (it shares the same CdmLogCode with partition pattern) corpus.setEventCallback((level, message) => { if (message.indexOf('Failed to persist object \'DeletePartition\'. This object does not contain the trait \'is.partition.incremental\', so it should not be in the collection \'incrementalPartitions\'. | fromData') !== -1) { errorMessageVerified = true; } else { fail(new Error('Some unexpected failure - ' + message)); } }, cdmStatusLevel.warning); const manifest: CdmManifestDefinition = await corpus.fetchObjectAsync<CdmManifestDefinition>('local:/entities.manifest.cdm.json'); expect(manifest.entities.length) .toBe(1); expect(manifest.entities.allItems[0].objectType) .toBe(cdmObjectType.localEntityDeclarationDef); const entity: CdmLocalEntityDeclarationDefinition = manifest.entities.allItems[0] as CdmLocalEntityDeclarationDefinition; expect(entity.incrementalPartitions.length) .toBe(1); const incrementalPartition = entity.incrementalPartitions.allItems[0] expect(incrementalPartition.name) .toBe('UpsertPartition'); expect(incrementalPartition.exhibitsTraits.length) .toBe(1); expect(incrementalPartition.exhibitsTraits.allItems[0].fetchObjectDefinitionName()) .toBe(constants.INCREMENTAL_TRAIT_NAME); expect(errorMessageVerified) .toBeTruthy(); done(); }); /** * Testing loading manifest with local entity declaration having a data partition with incremental trait. */ it('TestFromDataPartitionWithIncrementalTrait', async (done) => { const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestFromDataPartitionWithIncrementalTrait'); let errorMessageVerified: boolean = false // not checking the CdmLogCode here as we want to check if this error message constructed correctly for the partition (it shares the same CdmLogCode with partition pattern) corpus.setEventCallback((level, message) => { if (message.indexOf('Failed to persist object \'UpsertPartition\'. This object contains the trait \'is.partition.incremental\', so it should not be in the collection \'dataPartitions\'. | fromData') !== -1) { errorMessageVerified = true; } else { fail(new Error('Some unexpected failure - ' + message)); } }, cdmStatusLevel.warning); const manifest: CdmManifestDefinition = await corpus.fetchObjectAsync<CdmManifestDefinition>('local:/entities.manifest.cdm.json'); expect(manifest.entities.length) .toBe(1); expect(manifest.entities.allItems[0].objectType) .toBe(cdmObjectType.localEntityDeclarationDef); const entity: CdmLocalEntityDeclarationDefinition = manifest.entities.allItems[0] as CdmLocalEntityDeclarationDefinition; expect(entity.dataPartitions.length) .toBe(1); expect(entity.dataPartitions.allItems[0].name) .toBe('TestingPartition'); expect(errorMessageVerified) .toBeTruthy(); done(); }); /* * Testing saving manifest with local entity declaration having an incremental partition without incremental trait. */ it('TestToIncrementalPartitionWithoutTrait', async (done) => { const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestToIncrementalPartitionWithoutTrait'); let errorMessageVerified: boolean = false // not checking the CdmLogCode here as we want to check if this error message constructed correctly for the partition (it shares the same CdmLogCode with partition pattern) corpus.setEventCallback((level, message) => { if (message.indexOf('Failed to persist object \'DeletePartition\'. This object does not contain the trait \'is.partition.incremental\', so it should not be in the collection \'incrementalPartitions\'. | toData') !== -1) { errorMessageVerified = true; } else { fail(new Error('Some unexpected failure - ' + message)); } }, cdmStatusLevel.warning); const manifest: CdmManifestDefinition = new CdmManifestDefinition(corpus.ctx, 'manifest'); corpus.storage.fetchRootFolder('local').documents.push(manifest); const entity: CdmEntityDefinition = new CdmEntityDefinition(corpus.ctx, 'entityName', undefined); createDocumentForEntity(corpus, entity); const localizedEntityDeclaration = manifest.entities.push(entity); const upsertIncrementalPartition = corpus.MakeObject<CdmDataPartitionDefinition>(cdmObjectType.dataPartitionDef, 'UpsertPartition', false); upsertIncrementalPartition.location = '/IncrementalData'; upsertIncrementalPartition.specializedSchema = 'csv'; upsertIncrementalPartition.exhibitsTraits.push(constants.INCREMENTAL_TRAIT_NAME, [['type', cdmIncrementalPartitionType[cdmIncrementalPartitionType.Upsert]]]); const deletePartition = corpus.MakeObject<CdmDataPartitionDefinition>(cdmObjectType.dataPartitionDef, 'DeletePartition', false); deletePartition.location = '/IncrementalData'; deletePartition.specializedSchema = 'csv'; localizedEntityDeclaration.incrementalPartitions.push(upsertIncrementalPartition); localizedEntityDeclaration.incrementalPartitions.push(deletePartition); using(enterScope('DataPartitionTest', corpus.ctx, 'TestToIncrementalPartitionWithoutTrait'), _ => { const manifestData = CdmFolder.ManifestPersistence.toData(manifest, undefined, undefined); expect(manifestData.entities.length) .toBe(1); const entityData: EntityDeclarationDefinition = manifestData.entities[0]; expect(entityData.incrementalPartitions.length) .toBe(1); const partitionData: DataPartition = entityData.incrementalPartitions[0]; expect(partitionData.name) .toBe('UpsertPartition'); expect(partitionData.exhibitsTraits.length) .toBe(1); expect((partitionData.exhibitsTraits[0] as TraitReference).traitReference) .toBe(constants.INCREMENTAL_TRAIT_NAME); }); expect(errorMessageVerified) .toBeTruthy(); done(); }); /* * Testing saving manifest with local entity declaration having a data partition with incremental trait. */ it('TestToDataPartitionWithIncrementalTrait', async (done) => { const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestToDataPartitionWithIncrementalTrait'); let errorMessageVerified: boolean = false // not checking the CdmLogCode here as we want to check if this error message constructed correctly for the partition (it shares the same CdmLogCode with partition pattern) corpus.setEventCallback((level, message) => { if (message.indexOf('Failed to persist object \'UpsertPartition\'. This object contains the trait \'is.partition.incremental\', so it should not be in the collection \'dataPartitions\'. | toData') !== -1) { errorMessageVerified = true; } else { fail(new Error('Some unexpected failure - ' + message)); } }, cdmStatusLevel.warning); const manifest: CdmManifestDefinition = new CdmManifestDefinition(corpus.ctx, 'manifest'); corpus.storage.fetchRootFolder('local').documents.push(manifest); const entity: CdmEntityDefinition = new CdmEntityDefinition(corpus.ctx, 'entityName', undefined); createDocumentForEntity(corpus, entity); const localizedEntityDeclaration = manifest.entities.push(entity); const upsertIncrementalPartition = corpus.MakeObject<CdmDataPartitionDefinition>(cdmObjectType.dataPartitionDef, 'UpsertPartition', false); upsertIncrementalPartition.location = '/IncrementalData'; upsertIncrementalPartition.specializedSchema = 'csv'; upsertIncrementalPartition.exhibitsTraits.push(constants.INCREMENTAL_TRAIT_NAME, [['type', cdmIncrementalPartitionType[cdmIncrementalPartitionType.Upsert]]]); const deletePartition = corpus.MakeObject<CdmDataPartitionDefinition>(cdmObjectType.dataPartitionDef, 'TestingPartition', false); deletePartition.location = '/testingData'; deletePartition.specializedSchema = 'csv'; localizedEntityDeclaration.dataPartitions.push(upsertIncrementalPartition); localizedEntityDeclaration.dataPartitions.push(deletePartition); using(enterScope('DataPartitionTest', corpus.ctx, 'TestToDataPartitionWithIncrementalTrait'), _ => { const manifestData = CdmFolder.ManifestPersistence.toData(manifest, undefined, undefined); expect(manifestData.entities.length) .toBe(1); const entityData: EntityDeclarationDefinition = manifestData.entities[0]; expect(entityData.dataPartitions.length) .toBe(1); const partitionData: DataPartition = entityData.dataPartitions[0]; expect(partitionData.name) .toBe('TestingPartition'); }); expect(errorMessageVerified) .toBeTruthy(); done(); }); });
the_stack
import * as eaw from 'eastasianwidth'; /* * FracturedJsonJs * FracturedJsonJs is a library for formatting JSON documents in a human-readable but fairly compact way. * * Copyright (c) 2021 Jesse Brooke * Project site: https://github.com/j-brooke/FracturedJsonJs * License: https://github.com/j-brooke/FracturedJsonJs/blob/main/LICENSE */ /* * Class that outputs JSON formatted in a compact, user-readable way. Any given container is formatted in one * of three ways: * * Arrays or objects will be written on a single line, if their contents aren't too complex and the * resulting line wouldn't be too long. * * Arrays can be written on multiple lines, with multiple items per line, as long as those items aren't * too complex. * * Otherwise, each object property or array item is written beginning on its own line, indented one step * deeper than its parent. */ export class Formatter { /** * Dictates what sort of line endings to use. */ get jsonEolStyle(): EolStyle { return this._jsonEolStyle; } set jsonEolStyle(value: EolStyle) { this._jsonEolStyle = value; } /** * Maximum length of a complex element on a single line. This includes only the data for the inlined element, * not indentation or leading property names. */ get maxInlineLength(): number { return this._maxInlineLength; } set maxInlineLength(value: number) { this._maxInlineLength = value; } /** * Maximum nesting level that can be displayed on a single line. A primitive type or an empty * array or object has a complexity of 0. An object or array has a complexity of 1 greater than * its most complex child. */ get maxInlineComplexity(): number { return this._maxInlineComplexity; } set maxInlineComplexity(value: number) { this._maxInlineComplexity = value; } /** * Maximum nesting level that can be arranged spanning multiple lines, with multiple items per line. */ get maxCompactArrayComplexity(): number { return this._maxCompactArrayComplexity; } set maxCompactArrayComplexity(value: number) { this._maxCompactArrayComplexity = value; } /** * If an inlined array or object contains other arrays or objects, setting NestedBracketPadding to true * will include spaces inside the outer brackets. (See also simpleBracketPadding) */ get nestedBracketPadding(): boolean { return this._nestedBracketPadding; } set nestedBracketPadding(value: boolean) { this._nestedBracketPadding = value; } /** * If an inlined array or object does NOT contain other arrays/objects, setting SimpleBracketPadding to true * will include spaces inside the brackets. (See also nestedBracketPadding) */ get simpleBracketPadding(): boolean { return this._simpleBracketPadding; } set simpleBracketPadding(value: boolean) { this._simpleBracketPadding = value; } /** * If true, includes a space after property colons. */ get colonPadding(): boolean { return this._colonPadding; } set colonPadding(value: boolean) { this._colonPadding = value; } /** * If true, includes a space after commas separating array items and object properties. */ get commaPadding(): boolean { return this._commaPadding; } set commaPadding(value: boolean) { this._commaPadding = value; } /** * Depth at which lists/objects are always fully expanded, regardless of other settings. * -1 = none; 0 = root node only; 1 = root node and its children. */ get alwaysExpandDepth(): number { return this._alwaysExpandDepth; } set alwaysExpandDepth(value: number) { this._alwaysExpandDepth = value; } /** * Number of spaces to use per indent level (unless UseTabToIndent is true) */ get indentSpaces(): number { return this._indentSpaces; } set indentSpaces(value: number) { this._indentSpaces = value; } /** * Uses a single tab per indent level, instead of spaces. */ get useTabToIndent(): boolean { return this._useTabToIndent; } set useTabToIndent(value: boolean) { this._useTabToIndent = value; } /** * Value from 0 to 100 indicating how similar collections of inline objects need to be to be formatted as * a table. A group of objects that don't have any property names in common has a similarity of zero. A * group of objects that all contain the exact same property names has a similarity of 100. Setting this * to a value &gt;100 disables table formatting with objects as rows. */ get tableObjectMinimumSimilarity(): number { return this._tableObjectMinimumSimilarity; } set tableObjectMinimumSimilarity(value: number) { this._tableObjectMinimumSimilarity = value; } /** * Value from 0 to 100 indicating how similar collections of inline arrays need to be to be formatted as * a table. Similarity for arrays refers to how similar they are in length; if they all have the same * length their similarity is 100. Setting this to a value &gt;100 disables table formatting with arrays as * rows. */ get tableArrayMinimumSimilarity(): number { return this._tableArrayMinimumSimilarity; } set tableArrayMinimumSimilarity(value: number) { this._tableArrayMinimumSimilarity = value; } /** * If true, property names of expanded objects are padded to the same size. */ get alignExpandedPropertyNames(): boolean { return this._alignExpandedPropertyNames; } set alignExpandedPropertyNames(value: boolean) { this._alignExpandedPropertyNames = value; } /** * If true, numbers won't be right-aligned with matching precision. */ get dontJustifyNumbers(): boolean { return this._dontJustifyNumbers; } set dontJustifyNumbers(value: boolean) { this._dontJustifyNumbers = value; } /** * String attached to the beginning of every line, before regular indentation. */ get prefixString(): string { return this._prefixString; } set prefixString(value: string) { this._prefixString = value; } /** * Function that returns the visual width of strings measured in characters. This is used to line * columns up when formatting objects/arrays as tables. You can use the static methods * StringWidthByCharacterCount, StringWidthWithEastAsian, or supply your own. */ get stringWidthFunc(): (s:string) => number { return this._stringWidthFunc; } set stringWidthFunc(value: (s:string) => number) { this._stringWidthFunc = value; } /** * Returns a JSON-formatted string that represents the given JavaScript value. * @param jsValue */ serialize(jsValue: any): string { this.initInternals(); return this._prefixString + this.formatElement(0, jsValue).Value; } /** * Returns the character count of the string (just like the String.length property). * See StringWidthFunc */ static StringWidthByCharacterCount(str: string): number { return str.length; } /** * Returns a width, where some East Asian symbols are treated as twice as wide as Latin symbols. * See StringWidthFunc */ static StringWidthWithEastAsian(str: string): number { return eaw.length(str); } private _jsonEolStyle: EolStyle = EolStyle.lf; private _maxInlineLength: number = 80; private _maxInlineComplexity: number = 2; private _maxCompactArrayComplexity: number = 1; private _nestedBracketPadding: boolean = true; private _simpleBracketPadding: boolean = false; private _colonPadding: boolean = true; private _commaPadding: boolean = true; private _alwaysExpandDepth: number = -1; private _indentSpaces: number = 4; private _useTabToIndent: boolean = false; private _tableObjectMinimumSimilarity: number = 75; private _tableArrayMinimumSimilarity: number = 75; private _alignExpandedPropertyNames: boolean = false; private _dontJustifyNumbers: boolean = false; private _prefixString: string = ""; private _stringWidthFunc: (s: string) => number = Formatter.StringWidthWithEastAsian; private _eolStr: string = ""; private _indentStr: string = ""; private _paddedCommaStr: string = ""; private _paddedColonStr: string = ""; private _indentCache: string[] = []; /** * Set up some intermediate fields for efficiency. * @private */ private initInternals() { this._eolStr = (this._jsonEolStyle === EolStyle.Crlf) ? "\r\n" : "\n"; this._indentStr = (this._useTabToIndent) ? "\t" : " ".repeat(this._indentSpaces); this._paddedCommaStr = (this._commaPadding) ? ", " : ","; this._paddedColonStr = (this._colonPadding) ? ": " : ":"; } private indent(buff: string[], depth: number) : string[] { if (!this._indentCache[depth]) this._indentCache[depth] = this._indentStr.repeat(depth); buff.push(this._prefixString, this._indentCache[depth]); return buff; } private combine(buff: string[]): string { return buff.join(''); } /** * Base of recursion. Nearly everything comes through here. * @param depth * @param element * @private */ private formatElement(depth: number, element: any): FormattedNode { let formattedItem : FormattedNode; if (Array.isArray(element)) formattedItem = this.formatArray(depth, element); else if (element===null) formattedItem = this.formatSimple(depth, element); else if (typeof(element)==="object") formattedItem = this.formatObject(depth, element); else formattedItem = this.formatSimple(depth, element); formattedItem.cleanup(); return formattedItem; } /** * Formats a JSON element other than an array or object. * @param depth * @param element * @private */ private formatSimple(depth: number, element: any): FormattedNode { const simpleNode = new FormattedNode(); simpleNode.Value = JSON.stringify(element); simpleNode.ValueLength = this._stringWidthFunc(simpleNode.Value); simpleNode.Complexity = 0; simpleNode.Depth = depth; simpleNode.Kind = JsonValueKind.Array; simpleNode.Format = Format.Inline; if (element===null) { simpleNode.Kind = JsonValueKind.Null; return simpleNode; } switch (typeof(element)) { case "boolean": simpleNode.Kind = JsonValueKind.Boolean; break; case "number": simpleNode.Kind = JsonValueKind.Number; break; case "undefined": simpleNode.Kind = JsonValueKind.Null; break; default: case "string": simpleNode.Kind = JsonValueKind.String; break; } return simpleNode; } private formatArray(depth: number, element: any[]): FormattedNode { // Recursively format all of this array's elements. const items = element.map(child => this.formatElement(depth+1, child)); if (items.length===0) return this.emptyArray(depth); const thisItem = new FormattedNode(); thisItem.Kind = JsonValueKind.Array; thisItem.Complexity = Math.max(...items.map(fn => fn.Complexity)) + 1; thisItem.Depth = depth; thisItem.Children = items; if (thisItem.Depth > this._alwaysExpandDepth) { if (this.formatArrayInline(thisItem)) { return thisItem; } } this.justifyParallelNumbers(thisItem.Children); if (thisItem.Depth > this._alwaysExpandDepth) { if (this.formatArrayMultilineCompact(thisItem)) { return thisItem; } } if (this.formatTableArrayObject(thisItem)) return thisItem; if (this.formatTableArrayArray(thisItem)) return thisItem; this.formatArrayExpanded(thisItem); return thisItem; } private formatObject(depth: number, element: object): FormattedNode { // Recursively format all of this object's property values. const items: FormattedNode[] = []; for (const childKvp of Object.entries(element)) { const elem = this.formatElement(depth+1, childKvp[1]); elem.Name = JSON.stringify(childKvp[0]); elem.NameLength = this._stringWidthFunc(elem.Name); items.push(elem); } if (items.length===0) return this.emptyObject(depth); const thisItem = new FormattedNode(); thisItem.Kind = JsonValueKind.Object; thisItem.Complexity = Math.max(...items.map(fn => fn.Complexity)) + 1; thisItem.Depth = depth; thisItem.Children = items; if (thisItem.Depth > this._alwaysExpandDepth) { if (this.formatObjectInline(thisItem)) { return thisItem; } } if (this.formatTableObjectObject(thisItem)) return thisItem; if (this.formatTableObjectArray(thisItem)) return thisItem; this.formatObjectExpanded(thisItem, false); return thisItem; } private emptyArray(depth: number): FormattedNode { const arr = new FormattedNode(); arr.Value = "[]"; arr.ValueLength = 2; arr.Complexity = 0; arr.Depth = depth; arr.Kind = JsonValueKind.Array; arr.Format = Format.Inline; return arr; } /** * Try to format this array in a single line, if possible. * @param thisItem * @private */ private formatArrayInline(thisItem: FormattedNode): boolean { if (thisItem.Complexity > this._maxInlineComplexity) return false; if (thisItem.Children.some(fn => fn.Format !== Format.Inline)) return false; const useBracketPadding = (thisItem.Complexity >= 2)? this._nestedBracketPadding : this._simpleBracketPadding; const lineLength = 2 + (useBracketPadding? 2 : 0) + (thisItem.Children.length -1) * this._paddedCommaStr.length + thisItem.Children.map(fn => fn.ValueLength).reduce((acc,item) => acc+item); if (lineLength > this._maxInlineLength) return false; const buff : string[] = []; buff.push('['); if (useBracketPadding) buff.push(' '); let firstElem = true; for (const child of thisItem.Children) { if (!firstElem) buff.push(this._paddedCommaStr); buff.push(child.Value); firstElem = false; } if (useBracketPadding) buff.push(' '); buff.push(']'); thisItem.Value = this.combine(buff); thisItem.ValueLength = lineLength; thisItem.Format = Format.Inline; return true; } /** * Try to format this array, spanning multiple lines, but with several items per line, if possible. * @param thisItem * @private */ private formatArrayMultilineCompact(thisItem: FormattedNode): boolean { if (thisItem.Complexity > this._maxCompactArrayComplexity) return false; if (thisItem.Children.some(fn => fn.Format !== Format.Inline)) return false; const buff : string[] = []; buff.push('[', this._eolStr); this.indent(buff, thisItem.Depth + 1); let lineLengthSoFar = 0; let childIndex = 0; while (childIndex < thisItem.Children.length) { const notLastItem = childIndex < thisItem.Children.length-1; const itemLength = thisItem.Children[childIndex].ValueLength; const segmentLength = itemLength + ((notLastItem) ? this._paddedCommaStr.length : 0); if (lineLengthSoFar + segmentLength > this._maxInlineLength && lineLengthSoFar > 0) { buff.push(this._eolStr); this.indent(buff, thisItem.Depth+1); lineLengthSoFar = 0; } buff.push(thisItem.Children[childIndex].Value); if (notLastItem) buff.push(this._paddedCommaStr); childIndex += 1; lineLengthSoFar += segmentLength; } buff.push(this._eolStr); this.indent(buff, thisItem.Depth); buff.push(']'); thisItem.Value = this.combine(buff); thisItem.Format = Format.MultilineCompact; return true; } /** * Format this array with one child object per line, and those objects padded to line up nicely. * @param thisItem * @private */ private formatTableArrayObject(thisItem: FormattedNode): boolean { if (this._tableObjectMinimumSimilarity > 100.5) return false; // Gather stats about our children's property order and width, if they're eligible objects. const colStats = this.getPropertyStats(thisItem); if (!colStats) return false; // Reformat our immediate children using the width info we've computed. Their children aren't // recomputed, so this part isn't recursive. for (const child of thisItem.Children) this.formatObjectTableRow(child, colStats); return this.formatArrayExpanded(thisItem); } /** * Format this array with one child array per line, and those arrays padded to line up nicely. * @param thisItem * @private */ private formatTableArrayArray(thisItem: FormattedNode): boolean { if (this._tableArrayMinimumSimilarity > 100.5) return false; // Gather stats about our children's item widths, if they're eligible arrays. const columnStats = this.getArrayStats(thisItem); if (!columnStats) return false; // Reformat our immediate children using the width info we've computed. Their children aren't // recomputed, so this part isn't recursive. for (const child of thisItem.Children) this.formatArrayTableRow(child, columnStats); return this.formatArrayExpanded(thisItem); } /** * Format this array in a single line, with padding to line up with siblings. * @param thisItem * @param columnStatsArray * @private */ private formatArrayTableRow(thisItem: FormattedNode, columnStatsArray: ColumnStats[]) { const buff: string[] = []; buff.push("[ "); // Write the elements that actually exist in this array. for (let index=0; index<thisItem.Children.length; ++index) { if (index) buff.push(this._paddedCommaStr); const columnStats = columnStatsArray[index]; buff.push(columnStats.formatValue(thisItem.Children[index].Value, thisItem.Children[index].ValueLength, this._dontJustifyNumbers)); } // Write padding for elements that exist in siblings but not this array. for (let index=thisItem.Children.length; index < columnStatsArray.length; ++index) { const padSize = columnStatsArray[index].MaxValueSize + ((index===0)? 0 : this._paddedCommaStr.length); buff.push(' '.repeat(padSize)); } buff.push(" ]"); thisItem.Value = this.combine(buff); thisItem.Format = Format.InlineTabular; } /** * Write this array with each element starting on its own line. (They might be multiple lines themselves.) * @param thisItem * @private */ private formatArrayExpanded(thisItem: FormattedNode): boolean { const buff : string[] = []; buff.push('[', this._eolStr); let firstElem = true; for (const child of thisItem.Children) { if (!firstElem) buff.push(',', this._eolStr); this.indent(buff, child.Depth).push(child.Value); firstElem = false; } buff.push(this._eolStr); this.indent(buff, thisItem.Depth).push(']'); thisItem.Value = this.combine(buff); thisItem.Format = Format.Expanded; return true; } private emptyObject(depth: number) { const obj = new FormattedNode(); obj.Value = "{}"; obj.ValueLength = 2; obj.Complexity = 0; obj.Depth = depth; obj.Kind = JsonValueKind.Object; obj.Format = Format.Inline; return obj; } /** * Format this object as a single line, if possible. * @param thisItem * @private */ private formatObjectInline(thisItem: FormattedNode): boolean { if (thisItem.Complexity > this._maxInlineComplexity) return false; if (thisItem.Children.some(fn => fn.Format !== Format.Inline)) return false; const useBracketPadding = (thisItem.Complexity >= 2)? this._nestedBracketPadding : this._simpleBracketPadding; const lineLength = 2 + (useBracketPadding? 2 : 0) + thisItem.Children.length * this._paddedColonStr.length + (thisItem.Children.length -1) * this._paddedCommaStr.length + thisItem.Children.map(fn => fn.NameLength).reduce((acc,item) => acc+item) + thisItem.Children.map(fn => fn.ValueLength).reduce((acc,item) => acc+item); if (lineLength > this._maxInlineLength) return false; const buff: string[] = []; buff.push('{'); if (useBracketPadding) buff.push(' '); let firstElem = true; for (const prop of thisItem.Children) { if (!firstElem) buff.push(this._paddedCommaStr); buff.push(prop.Name, this._paddedColonStr, prop.Value); firstElem = false; } if (useBracketPadding) buff.push(' '); buff.push('}'); thisItem.Value = this.combine(buff); thisItem.ValueLength = lineLength; thisItem.Format = Format.Inline; return true; } /** * Format this object with one child object per line, and those objects padded to line up nicely. * @param thisItem * @private */ private formatTableObjectObject(thisItem: FormattedNode): boolean { if (this._tableObjectMinimumSimilarity > 100.5) return false; // Gather stats about our children's property order and width, if they're eligible objects. const propStats = this.getPropertyStats(thisItem); if (!propStats) return false; // Reformat our immediate children using the width info we've computed. Their children aren't // recomputed, so this part isn't recursive. for (const child of thisItem.Children) this.formatObjectTableRow(child, propStats); return this.formatObjectExpanded(thisItem, true); } /** * Format this object with one child array per line, and those arrays padded to line up nicely. * @param thisItem * @private */ private formatTableObjectArray(thisItem: FormattedNode): boolean { if (this._tableArrayMinimumSimilarity > 100.5) return false; // Gather stats about our children's widths, if they're eligible arrays. const columnStats = this.getArrayStats(thisItem); if (!columnStats) return false; // Reformat our immediate children using the width info we've computed. Their children aren't // recomputed, so this part isn't recursive. for (const child of thisItem.Children) this.formatArrayTableRow(child, columnStats); return this.formatObjectExpanded(thisItem, true); } /** * Format this object in a single line, with padding to line up with siblings. * @param thisItem * @param columnStatsArray * @private */ private formatObjectTableRow(thisItem: FormattedNode, columnStatsArray: ColumnStats[]) { // Bundle up each property name, value, quotes, colons, etc., or equivalent empty space. let highestNonBlankIndex: number = -1; const propSegmentStrings: string[] = []; for (let colIndex=0; colIndex < columnStatsArray.length; ++colIndex) { const buff: string[] = []; const columnStats = columnStatsArray[colIndex]; const filteredPropNodes = thisItem.Children.filter(fn => fn.Name === columnStats.PropName); if (filteredPropNodes.length===0) { // This object doesn't have this particular property. Pad it out. const skipLength = columnStats.PropNameLength + this._paddedColonStr.length + columnStats.MaxValueSize; buff.push(' '.repeat(skipLength)); } else { const propNode: FormattedNode = filteredPropNodes[0]; buff.push(columnStats.PropName, this._paddedColonStr); buff.push(columnStats.formatValue(propNode.Value, propNode.ValueLength, this._dontJustifyNumbers)); highestNonBlankIndex = colIndex; } propSegmentStrings[colIndex] = this.combine(buff); } const buff:string[] = []; buff.push("{ "); // Put them all together with commas in the right places. let firstElem = true; let needsComma = false; for (let segmentIndex=0; segmentIndex<propSegmentStrings.length; ++segmentIndex) { if (needsComma && segmentIndex <= highestNonBlankIndex) buff.push(this._paddedCommaStr); else if (!firstElem) buff.push(' '.repeat(this._paddedCommaStr.length)); buff.push(propSegmentStrings[segmentIndex]); needsComma = (propSegmentStrings[segmentIndex].trim().length!==0); firstElem = false; } buff.push(" }"); thisItem.Value = this.combine(buff); thisItem.Format = Format.InlineTabular; } /** * Write this object with each element starting on its own line. (They might be multiple lines * themselves.) * @param thisItem * @param forceExpandPropNames * @private */ private formatObjectExpanded(thisItem: FormattedNode, forceExpandPropNames: boolean): boolean { const maxPropNameLength = Math.max(...thisItem.Children.map(fn => fn.NameLength)); const buff : string[] = []; buff.push('{', this._eolStr); let firstItem = true; for (const prop of thisItem.Children) { if (!firstItem) buff.push(',', this._eolStr); this.indent(buff, prop.Depth).push(prop.Name); if (this._alignExpandedPropertyNames || forceExpandPropNames) buff.push(' '.repeat(maxPropNameLength - prop.NameLength)); buff.push(this._paddedColonStr, prop.Value); firstItem = false; } buff.push(this._eolStr); this.indent(buff, thisItem.Depth).push('}'); thisItem.Value = this.combine(buff); thisItem.Format = Format.Expanded; return true; } /** * If the given nodes are all numbers and not too big or small, format them to the same precision and width. * @param itemList * @private */ private justifyParallelNumbers(itemList: FormattedNode[]) { if (itemList.length < 2 || this._dontJustifyNumbers) return; const columnStats = new ColumnStats(); for (const propNode of itemList) columnStats.update(propNode, 0); if (!columnStats.IsQualifiedNumeric) return; for (const propNode of itemList) { propNode.Value = columnStats.formatValue(propNode.Value, propNode.ValueLength, this._dontJustifyNumbers); propNode.ValueLength = columnStats.MaxValueSize; } } /** * Check if this node's object children can be formatted as a table, and if so, return stats about * their properties, such as max width. Returns null if they're not eligible. * @param thisItem * @private */ private getPropertyStats(thisItem: FormattedNode): ColumnStats[] | null { if (thisItem.Children.length < 2) return null; // Record every property across all objects, count them, tabulate their order, and find the longest. const props: {[key:string] : ColumnStats} = {}; for (const child of thisItem.Children) { if (child.Kind !== JsonValueKind.Object || child.Format !== Format.Inline) return null; for (let index=0; index<child.Children.length; ++index) { const propNode = child.Children[index]; let propStats = props[propNode.Name]; if (!propStats) { propStats = new ColumnStats(); propStats.PropName = propNode.Name; propStats.PropNameLength = propNode.NameLength; props[propStats.PropName] = propStats; } propStats.update(propNode, index); } } // Decide the order of the properties by sorting by the average index. It's a crude metric, // but it should handle the occasional missing property well enough. const orderedProps = Object.values(props) .sort((a,b) => (a.OrderSum/a.Count) - (b.OrderSum/b.Count)); const totalPropCount = orderedProps.map(cs => cs.Count).reduce((acc,item) => acc+item); // Calculate a score based on how many of all possible properties are present. If the score is too // low, these objects are too different to try to line up as a table. const score = 100 * totalPropCount / (orderedProps.length * thisItem.Children.length); if (score < this._tableObjectMinimumSimilarity) return null; // If the formatted lines would be too long, bail out. const lineLength = 4 // outer brackets & spaces + orderedProps.map(cs => cs.PropNameLength).reduce((acc,item) => acc+item) // prop names + this._paddedColonStr.length * orderedProps.length // colons + orderedProps.map(cs => cs.MaxValueSize).reduce((acc,item) => acc+item) // values + this._paddedCommaStr.length * (orderedProps.length-1); // commas if (lineLength > this._maxInlineLength) return null; return orderedProps; } /** * Check if this node's array children can be formatted as a table, and if so, gather stats like max width. * Returns null if they're not eligible. * @param thisItem * @private */ private getArrayStats(thisItem: FormattedNode): ColumnStats[] | null { if (thisItem.Children.length < 2) return null; const valid = thisItem.Children.every(fn => fn.Kind===JsonValueKind.Array && fn.Format===Format.Inline); if (!valid) return null; const numberOfColumns = Math.max(...thisItem.Children.map(fn => fn.Children.length)); const colStatsArray: ColumnStats[] = []; for (let i=0; i<numberOfColumns; ++i) colStatsArray[i] = new ColumnStats(); for (const rowNode of thisItem.Children) { for (let index=0; index<rowNode.Children.length; ++index) colStatsArray[index].update(rowNode.Children[index], index); } // Calculate a score based on how rectangular the arrays are. If they differ too much in length, // it probably doesn't make sense to format them together. const totalElemCount = thisItem.Children.map(fn => fn.Children.length).reduce((acc,item) => acc+item); const similarity = 100 * totalElemCount / (thisItem.Children.length * numberOfColumns); if (similarity < this._tableArrayMinimumSimilarity) return null; // If the formatted lines would be too long, bail out. const lineLength = 4 + colStatsArray.map(cs => cs.MaxValueSize).reduce((acc,item) => acc+item) + (colStatsArray.length -1) * this._paddedCommaStr.length; if (lineLength > this._maxInlineLength) return null; return colStatsArray; } } export enum EolStyle { Crlf, lf, } enum JsonValueKind { Undefined, Object, Array, String, Number, Boolean, Null, } /** * Used in figuring out how to format properties/array items as columns in a table format. */ class ColumnStats { PropName: string = ""; PropNameLength: number = 0; OrderSum: number = 0; Count: number = 0; MaxValueSize: number = 0; IsQualifiedNumeric: boolean = true; CharsBeforeDec: number = 0; CharsAfterDec: number = 0; /** * Add stats about this FormattedNode to this PropertyStats. * @param propNode * @param index */ update(propNode: FormattedNode, index: number) { this.OrderSum += index; this.Count += 1; this.MaxValueSize = Math.max(this.MaxValueSize, propNode.ValueLength); this.IsQualifiedNumeric = this.IsQualifiedNumeric && (propNode.Kind === JsonValueKind.Number); if (!this.IsQualifiedNumeric) return; const normalizedNum = Number(propNode.Value).toString(); this.IsQualifiedNumeric = this.IsQualifiedNumeric && !(normalizedNum.includes("e") || normalizedNum.includes("E")); if (!this.IsQualifiedNumeric) return; const decIndex = normalizedNum.indexOf("."); if (decIndex < 0) { this.CharsBeforeDec = Math.max(this.CharsBeforeDec, normalizedNum.length); } else { this.CharsBeforeDec = Math.max(this.CharsBeforeDec, decIndex); this.CharsAfterDec = Math.max(this.CharsAfterDec, normalizedNum.length - decIndex - 1); } } formatValue(value: string, valueLength: number, dontJustify: boolean): string { if (this.IsQualifiedNumeric && !dontJustify) { const adjustedVal = Number(value).toFixed(this.CharsAfterDec); const totalLength = this.CharsBeforeDec + this.CharsAfterDec + ((this.CharsAfterDec>0)? 1 : 0); return adjustedVal.padStart(totalLength); } return value.padEnd(this.MaxValueSize - (valueLength-value.length)); } } enum Format { Inline, InlineTabular, MultilineCompact, Expanded, } /** * Data about a JSON element and how we've formatted it. */ class FormattedNode { Name: string = ""; NameLength: number = 0; Value: string = ""; ValueLength: number = 0; Complexity: number = 0; Depth: number = 0; Kind: JsonValueKind = JsonValueKind.Undefined; Format: Format = Format.Inline; Children: FormattedNode[] = []; withName(name: string): FormattedNode { this.Name = name; return this; } cleanup() { if (this.Format !== Format.Inline) this.Children = []; for (const child of this.Children) child.Children = []; } }
the_stack
import { workspace as Workspace, Uri, WorkspaceConfiguration, ConfigurationTarget } from 'vscode'; import { Is } from './node-utils'; import { DirectoryItem, ModeItem } from './shared/settings'; // Defines settings locally to the client or deprecated settings that are converted to // shared settings export type ValidateItem = { language: string; autoFix?: boolean; }; export namespace ValidateItem { export function is(item: any): item is ValidateItem { const candidate = item as ValidateItem; return candidate && Is.string(candidate.language) && (Is.boolean(candidate.autoFix) || candidate.autoFix === void 0); } } export type LegacyDirectoryItem = { directory: string; changeProcessCWD: boolean; }; export namespace LegacyDirectoryItem { export function is(item: any): item is LegacyDirectoryItem { const candidate = item as LegacyDirectoryItem; return candidate && Is.string(candidate.directory) && Is.boolean(candidate.changeProcessCWD); } } export type PatternItem = { pattern: string; '!cwd'?: boolean; }; export namespace PatternItem { export function is(item: any): item is PatternItem { const candidate = item as PatternItem; return candidate && Is.string(candidate.pattern) && (Is.boolean(candidate['!cwd']) || candidate['!cwd'] === undefined); } } // ----- Settings migration code type InspectData<T> = { globalValue?: T; workspaceValue?: T; workspaceFolderValue?: T }; type MigrationElement<T> = { changed: boolean; value: T | undefined; }; type MigrationData<T> = { global: MigrationElement<T>; workspace: MigrationElement<T>; workspaceFolder: MigrationElement<T>; }; interface CodeActionsOnSaveMap { 'source.fixAll'?: boolean; 'source.fixAll.eslint'?: boolean; [key: string]: boolean | undefined; } export type CodeActionsOnSave = CodeActionsOnSaveMap | string[] | null; namespace CodeActionsOnSave { export function isExplicitlyDisabled(setting: CodeActionsOnSave | undefined): boolean { if (setting === undefined || setting === null || Array.isArray(setting)) { return false; } return setting['source.fixAll.eslint'] === false; } export function getSourceFixAll(setting: CodeActionsOnSave): boolean | undefined { if (setting === null) { return undefined; } if (Array.isArray(setting)) { return setting.includes('source.fixAll') ? true : undefined; } else { return setting['source.fixAll']; } } export function getSourceFixAllESLint(setting: CodeActionsOnSave): boolean | undefined { if (setting === null) { return undefined; } else if (Array.isArray(setting)) { return setting.includes('source.fixAll.eslint') ? true : undefined; } else { return setting['source.fixAll.eslint']; } } export function setSourceFixAllESLint(setting: CodeActionsOnSave, value: boolean | undefined): void { // If the setting is mistyped do nothing. if (setting === null) { return; } else if (Array.isArray(setting)) { const index = setting.indexOf('source.fixAll.eslint'); if (value === true) { if (index === -1) { setting.push('source.fixAll.eslint'); } } else { if (index >= 0) { setting.splice(index, 1); } } } else { setting['source.fixAll.eslint'] = value; } } } type LanguageSettings = { 'editor.codeActionsOnSave'?: CodeActionsOnSave; }; namespace MigrationData { export function create<T>(inspect: InspectData<T> | undefined): MigrationData<T> { return inspect === undefined ? { global: { value: undefined, changed: false }, workspace: { value: undefined, changed: false }, workspaceFolder: { value: undefined, changed: false } } : { global: { value: inspect.globalValue, changed: false }, workspace: { value: inspect.workspaceValue, changed: false }, workspaceFolder: { value: inspect.workspaceFolderValue, changed: false } }; } export function needsUpdate(data: MigrationData<any>): boolean { return data.global.changed || data.workspace.changed || data.workspaceFolder.changed; } } export class Migration { private workspaceConfig: WorkspaceConfiguration; private eslintConfig: WorkspaceConfiguration; private editorConfig: WorkspaceConfiguration; private codeActionOnSave: MigrationData<CodeActionsOnSave>; private languageSpecificSettings: Map<string, MigrationData<CodeActionsOnSave>>; private autoFixOnSave: MigrationData<boolean>; private validate: MigrationData<(ValidateItem | string)[]>; private workingDirectories: MigrationData<(string | DirectoryItem)[]>; private didChangeConfiguration: (() => void) | undefined; constructor(resource: Uri) { this.workspaceConfig = Workspace.getConfiguration(undefined, resource); this.eslintConfig = Workspace.getConfiguration('eslint', resource); this.editorConfig = Workspace.getConfiguration('editor', resource); this.codeActionOnSave = MigrationData.create(this.editorConfig.inspect<CodeActionsOnSave>('codeActionsOnSave')); this.autoFixOnSave = MigrationData.create(this.eslintConfig.inspect<boolean>('autoFixOnSave')); this.validate = MigrationData.create(this.eslintConfig.inspect<(ValidateItem | string)[]>('validate')); this.workingDirectories = MigrationData.create(this.eslintConfig.inspect<(string | DirectoryItem)[]>('workingDirectories')); this.languageSpecificSettings = new Map(); } public record(): void { const fixAll = this.recordAutoFixOnSave(); this.recordValidate(fixAll); this.recordWorkingDirectories(); } public captureDidChangeSetting(func: () => void): void { this.didChangeConfiguration = func; } private recordAutoFixOnSave(): [boolean, boolean, boolean] { function record(this: void, elem: MigrationElement<boolean>, setting: MigrationElement<CodeActionsOnSave>): boolean { // if it is explicitly set to false don't convert anything anymore if (CodeActionsOnSave.isExplicitlyDisabled(setting.value)) { return false; } if (!Is.objectLiteral(setting.value) && !Array.isArray(setting.value)) { setting.value = Object.create(null) as {}; } const autoFix: boolean = !!elem.value; const sourceFixAll: boolean = !!CodeActionsOnSave.getSourceFixAll(setting.value); let result: boolean; if (autoFix !== sourceFixAll && autoFix && CodeActionsOnSave.getSourceFixAllESLint(setting.value) === undefined) { CodeActionsOnSave.setSourceFixAllESLint(setting.value, elem.value); setting.changed = true; result = !!CodeActionsOnSave.getSourceFixAllESLint(setting.value); } else { result = !!CodeActionsOnSave.getSourceFixAll(setting.value); } /* For now we don't rewrite the settings to allow users to go back to an older version elem.value = undefined; elem.changed = true; */ return result; } return [ record(this.autoFixOnSave.global, this.codeActionOnSave.global), record(this.autoFixOnSave.workspace, this.codeActionOnSave.workspace), record(this.autoFixOnSave.workspaceFolder, this.codeActionOnSave.workspaceFolder) ]; } private recordValidate(fixAll: [boolean, boolean, boolean]): void { function record(this: void, elem: MigrationElement<(ValidateItem | string)[]>, settingAccessor: (language: string) => MigrationElement<CodeActionsOnSave>, fixAll: boolean): void { if (elem.value === undefined) { return; } for (let i = 0; i < elem.value.length; i++) { const item = elem.value[i]; if (typeof item === 'string') { continue; } if (fixAll && item.autoFix === false && typeof item.language === 'string') { const setting = settingAccessor(item.language); if (!Is.objectLiteral(setting.value) && !Array.isArray(setting.value)) { setting.value = Object.create(null) as {}; } if (CodeActionsOnSave.getSourceFixAllESLint(setting.value!) !== false) { CodeActionsOnSave.setSourceFixAllESLint(setting.value!, false); setting.changed = true; } } /* For now we don't rewrite the settings to allow users to go back to an older version if (item.language !== undefined) { elem.value[i] = item.language; elem.changed = true; } */ } } const languageSpecificSettings = this.languageSpecificSettings; const workspaceConfig = this.workspaceConfig; function getCodeActionsOnSave(language: string): MigrationData<CodeActionsOnSave> { let result: MigrationData<CodeActionsOnSave> | undefined = languageSpecificSettings.get(language); if (result !== undefined) { return result; } const value: InspectData<LanguageSettings> | undefined = workspaceConfig.inspect(`[${language}]`); if (value === undefined) { return MigrationData.create(undefined); } const globalValue = value.globalValue?.['editor.codeActionsOnSave']; const workspaceFolderValue = value.workspaceFolderValue?.['editor.codeActionsOnSave']; const workspaceValue = value.workspaceValue?.['editor.codeActionsOnSave']; result = MigrationData.create<CodeActionsOnSave>({ globalValue, workspaceFolderValue, workspaceValue }); languageSpecificSettings.set(language, result); return result; } record(this.validate.global, (language) => getCodeActionsOnSave(language).global, fixAll[0]); record(this.validate.workspace, (language) => getCodeActionsOnSave(language).workspace, fixAll[1] ? fixAll[1] : fixAll[0]); record(this.validate.workspaceFolder, (language) => getCodeActionsOnSave(language).workspaceFolder, fixAll[2] ? fixAll[2] : (fixAll[1] ? fixAll[1] : fixAll[0])); } private recordWorkingDirectories(): void { function record(this: void, elem: MigrationElement<(string | DirectoryItem | LegacyDirectoryItem | PatternItem | ModeItem)[]>): void { if (elem.value === undefined || !Array.isArray(elem.value)) { return; } for (let i = 0; i < elem.value.length; i++) { const item = elem.value[i]; if (typeof item === 'string' || ModeItem.is(item) || PatternItem.is(item)) { continue; } if (DirectoryItem.is(item) && item['!cwd'] !== undefined) { continue; } /* For now we don't rewrite the settings to allow users to go back to an older version if (LegacyDirectoryItem.is(item)) { const legacy: LegacyDirectoryItem = item; if (legacy.changeProcessCWD === false) { (item as DirectoryItem)['!cwd'] = true; elem.changed = true; } } if (DirectoryItem.is(item) && item['!cwd'] === undefined) { elem.value[i] = item.directory; elem.changed = true; } */ } } record(this.workingDirectories.global); record(this.workingDirectories.workspace); record(this.workingDirectories.workspaceFolder); } public needsUpdate(): boolean { if (MigrationData.needsUpdate(this.autoFixOnSave) || MigrationData.needsUpdate(this.validate) || MigrationData.needsUpdate(this.codeActionOnSave) || MigrationData.needsUpdate(this.workingDirectories) ) { return true; } for (const value of this.languageSpecificSettings.values()) { if (MigrationData.needsUpdate(value)) { return true; } } return false; } public async update(): Promise<void> { async function _update<T>(config: WorkspaceConfiguration, section: string, newValue: MigrationElement<T>, target: ConfigurationTarget): Promise<void> { if (!newValue.changed) { return; } await config.update(section, newValue.value, target); } async function _updateLanguageSetting(config: WorkspaceConfiguration, section: string, settings: LanguageSettings | undefined, newValue: MigrationElement<CodeActionsOnSave>, target: ConfigurationTarget): Promise<void> { if (!newValue.changed) { return; } if (settings === undefined) { settings = Object.create(null) as object; } if (settings['editor.codeActionsOnSave'] === undefined) { settings['editor.codeActionsOnSave'] = {}; } settings['editor.codeActionsOnSave'] = newValue.value; await config.update(section, settings, target); } try { await _update(this.editorConfig, 'codeActionsOnSave', this.codeActionOnSave.global, ConfigurationTarget.Global); await _update(this.editorConfig, 'codeActionsOnSave', this.codeActionOnSave.workspace, ConfigurationTarget.Workspace); await _update(this.editorConfig, 'codeActionsOnSave', this.codeActionOnSave.workspaceFolder, ConfigurationTarget.WorkspaceFolder); await _update(this.eslintConfig, 'autoFixOnSave', this.autoFixOnSave.global, ConfigurationTarget.Global); await _update(this.eslintConfig, 'autoFixOnSave', this.autoFixOnSave.workspace, ConfigurationTarget.Workspace); await _update(this.eslintConfig, 'autoFixOnSave', this.autoFixOnSave.workspaceFolder, ConfigurationTarget.WorkspaceFolder); await _update(this.eslintConfig, 'validate', this.validate.global, ConfigurationTarget.Global); await _update(this.eslintConfig, 'validate', this.validate.workspace, ConfigurationTarget.Workspace); await _update(this.eslintConfig, 'validate', this.validate.workspaceFolder, ConfigurationTarget.WorkspaceFolder); await _update(this.eslintConfig, 'workingDirectories', this.workingDirectories.global, ConfigurationTarget.Global); await _update(this.eslintConfig, 'workingDirectories', this.workingDirectories.workspace, ConfigurationTarget.Workspace); await _update(this.eslintConfig, 'workingDirectories', this.workingDirectories.workspaceFolder, ConfigurationTarget.WorkspaceFolder); for (const language of this.languageSpecificSettings.keys()) { const value = this.languageSpecificSettings.get(language)!; if (MigrationData.needsUpdate(value)) { const section = `[${language}]`; const current = this.workspaceConfig.inspect<LanguageSettings>(section); await _updateLanguageSetting(this.workspaceConfig, section, current?.globalValue, value.global, ConfigurationTarget.Global); await _updateLanguageSetting(this.workspaceConfig, section, current?.workspaceValue, value.workspace, ConfigurationTarget.Workspace); await _updateLanguageSetting(this.workspaceConfig, section, current?.workspaceFolderValue, value.workspaceFolder, ConfigurationTarget.WorkspaceFolder); } } } finally { if (this.didChangeConfiguration) { this.didChangeConfiguration(); this.didChangeConfiguration = undefined; } } } }
the_stack
import MarkdownIt from "markdown-it/lib"; import StateBlock, { ParentType, } from "markdown-it/lib/rules_block/state_block"; import { isSpace } from "markdown-it/lib/common/utils"; type BlockquoteExtOptions = { followingCharRegex: RegExp; markup: string; name: string; }; // TODO unfortunately, we cannot reliably extend blockquote since it is hardcoded to search for `>` characters // In addition, we cannot just call "blockquote" inside spoiler, because it does a lookahead for `>` characters and leaves our `!`s behind, potentially causing parsing issues // The official advice is to just "copy paste then edit" "extended" rules... // see https://github.com/markdown-it/markdown-it/blob/master/docs/development.md#general-considerations-for-plugins // see also https://github.com/markdown-it/markdown-it/issues/46#issuecomment-73125248 function blockquoteExt( options: BlockquoteExtOptions, state: StateBlock, startLine: number, endLine: number, silent: boolean ): boolean { // NOTE: we're keeping the source as close to upstream as possible, so ignore errors like this // eslint-disable-next-line no-var var adjustTab, ch, i, initial, l, lastLineEmpty, lines: [number, number], nextLine, offset, oldBMarks, oldBSCount, oldIndent, oldParentType: ParentType, oldSCount, oldTShift, spaceAfterMarker, terminate, terminatorRules, token, wasOutdented, oldLineMax = state.lineMax, pos = state.bMarks[startLine] + state.tShift[startLine], max = state.eMarks[startLine]; // if it's indented more than 3 spaces, it should be a code block if (state.sCount[startLine] - state.blkIndent >= 4) { return false; } // check the block quote marker if ( state.src.charCodeAt(pos) !== 0x3e /* > */ || !options.followingCharRegex.test(state.src[pos + 1]) ) { return false; } pos += options.markup.length; // we know that it's going to be a valid blockquote, // so no point trying to find the end of it in silent mode if (silent) { return true; } // skip spaces after ">" and re-calculate offset initial = offset = state.sCount[startLine] + pos - (state.bMarks[startLine] + state.tShift[startLine]); // skip one optional space after '>' if (state.src.charCodeAt(pos) === 0x20 /* space */) { // ' > test ' // ^ -- position start of line here: pos++; initial++; offset++; adjustTab = false; spaceAfterMarker = true; } else if (state.src.charCodeAt(pos) === 0x09 /* tab */) { spaceAfterMarker = true; if ((state.bsCount[startLine] + offset) % 4 === 3) { // ' >\t test ' // ^ -- position start of line here (tab has width===1) pos++; initial++; offset++; adjustTab = false; } else { // ' >\t test ' // ^ -- position start of line here + shift bsCount slightly // to make extra space appear adjustTab = true; } } else { spaceAfterMarker = false; } oldBMarks = [state.bMarks[startLine]]; state.bMarks[startLine] = pos; while (pos < max) { ch = state.src.charCodeAt(pos); if (isSpace(ch)) { if (ch === 0x09) { offset += 4 - ((offset + state.bsCount[startLine] + (adjustTab ? 1 : 0)) % 4); } else { offset++; } } else { break; } pos++; } oldBSCount = [state.bsCount[startLine]]; state.bsCount[startLine] = state.sCount[startLine] + 1 + (spaceAfterMarker ? 1 : 0); lastLineEmpty = pos >= max; oldSCount = [state.sCount[startLine]]; state.sCount[startLine] = offset - initial; oldTShift = [state.tShift[startLine]]; state.tShift[startLine] = pos - state.bMarks[startLine]; terminatorRules = state.md.block.ruler.getRules("spoiler"); oldParentType = state.parentType; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore TODO adding a new parent type here... state.parentType = "spoiler"; wasOutdented = false; // Search the end of the block // // Block ends with either: // 1. an empty line outside: // ``` // > test // // ``` // 2. an empty line inside: // ``` // > // test // ``` // 3. another tag: // ``` // > test // - - - // ``` for (nextLine = startLine + 1; nextLine < endLine; nextLine++) { // check if it's outdented, i.e. it's inside list item and indented // less than said list item: // // ``` // 1. anything // > current blockquote // 2. checking this line // ``` if (state.sCount[nextLine] < state.blkIndent) wasOutdented = true; pos = state.bMarks[nextLine] + state.tShift[nextLine]; max = state.eMarks[nextLine]; if (pos >= max) { // Case 1: line is not inside the blockquote, and this line is empty. break; } pos += options.markup.length; if ( state.src.charCodeAt(pos - options.markup.length) === 0x3e /* > */ && options.followingCharRegex.test( state.src[pos - options.markup.length + 1] ) && !wasOutdented ) { // This line is inside the blockquote. // skip spaces after ">" and re-calculate offset initial = offset = state.sCount[nextLine] + pos - (state.bMarks[nextLine] + state.tShift[nextLine]); // skip one optional space after '>' if (state.src.charCodeAt(pos) === 0x20 /* space */) { // ' > test ' // ^ -- position start of line here: pos++; initial++; offset++; adjustTab = false; spaceAfterMarker = true; } else if (state.src.charCodeAt(pos) === 0x09 /* tab */) { spaceAfterMarker = true; if ((state.bsCount[nextLine] + offset) % 4 === 3) { // ' >\t test ' // ^ -- position start of line here (tab has width===1) pos++; initial++; offset++; adjustTab = false; } else { // ' >\t test ' // ^ -- position start of line here + shift bsCount slightly // to make extra space appear adjustTab = true; } } else { spaceAfterMarker = false; } oldBMarks.push(state.bMarks[nextLine]); state.bMarks[nextLine] = pos; while (pos < max) { ch = state.src.charCodeAt(pos); if (isSpace(ch)) { if (ch === 0x09) { offset += 4 - ((offset + state.bsCount[nextLine] + (adjustTab ? 1 : 0)) % 4); } else { offset++; } } else { break; } pos++; } lastLineEmpty = pos >= max; oldBSCount.push(state.bsCount[nextLine]); state.bsCount[nextLine] = state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0); oldSCount.push(state.sCount[nextLine]); state.sCount[nextLine] = offset - initial; oldTShift.push(state.tShift[nextLine]); state.tShift[nextLine] = pos - state.bMarks[nextLine]; continue; } // Case 2: line is not inside the blockquote, and the last line was empty. if (lastLineEmpty) { break; } // Case 3: another tag found. terminate = false; for (i = 0, l = terminatorRules.length; i < l; i++) { if (terminatorRules[i](state, nextLine, endLine, true)) { terminate = true; break; } } if (terminate) { // Quirk to enforce "hard termination mode" for paragraphs; // normally if you call `tokenize(state, startLine, nextLine)`, // paragraphs will look below nextLine for paragraph continuation, // but if blockquote is terminated by another tag, they shouldn't state.lineMax = nextLine; if (state.blkIndent !== 0) { // state.blkIndent was non-zero, we now set it to zero, // so we need to re-calculate all offsets to appear as // if indent wasn't changed oldBMarks.push(state.bMarks[nextLine]); oldBSCount.push(state.bsCount[nextLine]); oldTShift.push(state.tShift[nextLine]); oldSCount.push(state.sCount[nextLine]); state.sCount[nextLine] -= state.blkIndent; } break; } oldBMarks.push(state.bMarks[nextLine]); oldBSCount.push(state.bsCount[nextLine]); oldTShift.push(state.tShift[nextLine]); oldSCount.push(state.sCount[nextLine]); // A negative indentation means that this is a paragraph continuation // state.sCount[nextLine] = -1; } oldIndent = state.blkIndent; state.blkIndent = 0; token = state.push(options.name + "_open", options.name, 1); token.markup = options.markup; token.map = lines = [startLine, 0]; state.md.block.tokenize(state, startLine, nextLine); token = state.push(options.name + "_close", options.name, -1); token.markup = options.markup; state.lineMax = oldLineMax; state.parentType = oldParentType; lines[1] = state.line; // Restore original tShift; this might not be necessary since the parser // has already been here, but just to make sure we can do that. for (i = 0; i < oldTShift.length; i++) { state.bMarks[i + startLine] = oldBMarks[i]; state.tShift[i + startLine] = oldTShift[i]; state.sCount[i + startLine] = oldSCount[i]; state.bsCount[i + startLine] = oldBSCount[i]; } state.blkIndent = oldIndent; return true; } function spoilerFn( state: StateBlock, startLine: number, endLine: number, silent: boolean ) { return blockquoteExt( { followingCharRegex: /!/, markup: ">!", name: "spoiler", }, state, startLine, endLine, silent ); } function blockquoteFn( state: StateBlock, startLine: number, endLine: number, silent: boolean ) { return blockquoteExt( { followingCharRegex: /[^!]/, markup: ">", name: "blockquote", }, state, startLine, endLine, silent ); } /** * Parses out spoiler `>!` blocks * @param md */ export function spoiler(md: MarkdownIt): void { // TODO necessary? // find all blockquote chain rules and update to be part of the spoiler chain as well // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore TODO no public way to iterate over all rules; maybe there's a better way? (md.block.ruler.__rules__ as { alt: string[] }[]).forEach((r) => { const bqIndex = r.alt.indexOf("blockquote"); if (bqIndex > -1) { // add in "spoiler" right before the "blockquote" entry r.alt.splice(bqIndex, 0, "spoiler"); } }); md.block.ruler.before("blockquote", "spoiler", spoilerFn, { // TODO stole this from blockquote, dunno what it does... alt: ["paragraph", "reference", "spoiler", "blockquote", "list"], }); md.block.ruler.at("blockquote", blockquoteFn, { alt: ["paragraph", "reference", "spoiler", "blockquote", "list"], }); }
the_stack
import { setOfSupportedSchemes, supportedSchemes } from 'common-utils/uriHelper.js'; import { WorkspaceConfigForDocument } from 'server/api'; import { CodeAction, CodeActionKind, Command, Diagnostic, DiagnosticCollection, DiagnosticSeverity, Disposable, ExtensionContext, languages as vsCodeSupportedLanguages, Position, Range, TextDocument, Uri, window, workspace, } from 'vscode'; import * as VSCodeLangClient from 'vscode-languageclient/node'; import { ForkOptions, LanguageClient, LanguageClientOptions, Trace, ServerOptions, TransportKind } from 'vscode-languageclient/node'; import { diagnosticSource } from '../constants'; import * as Settings from '../settings'; import { Inspect, inspectConfigKeys, sectionCSpell } from '../settings'; import * as LanguageIds from '../settings/languageIds'; import { Maybe } from '../util'; import { createBroadcaster } from '../util/broadcaster'; import { findConicalDocumentScope } from '../util/documentUri'; import { logErrors, silenceErrors } from '../util/errors'; import { createServerApi, FieldExistsInTarget, GetConfigurationForDocumentResult, IsSpellCheckEnabledResult, OnSpellCheckDocumentStep, requestCodeAction, ServerApi, WorkspaceConfigForDocumentRequest, WorkspaceConfigForDocumentResponse, } from './server'; // The debug options for the server const debugExecArgv = ['--nolazy', '--inspect=60048']; const diagnosticCollectionName = diagnosticSource; export interface ServerResponseIsSpellCheckEnabled extends Partial<IsSpellCheckEnabledResult> {} export interface ServerResponseIsSpellCheckEnabledForFile extends ServerResponseIsSpellCheckEnabled { uri: Uri; } interface TextDocumentInfo { uri?: Uri; languageId?: string; } const traceMode: Trace = Trace.Off; export class CSpellClient implements Disposable { readonly client: LanguageClient; readonly import: Set<string> = new Set(); readonly languageIds: Set<string>; readonly allowedSchemas: Set<string>; private serverApi: ServerApi; private disposables: Set<Disposable> = new Set(); private broadcasterOnSpellCheckDocument = createBroadcaster<OnSpellCheckDocumentStep>(); /** * @param: {string} module -- absolute path to the server module. */ constructor(context: ExtensionContext, languageIds: string[]) { // The server is implemented in node const module = context.asAbsolutePath('packages/_server/dist/main.js'); const enabledLanguageIds = Settings.getScopedSettingFromVSConfig('enabledLanguageIds', Settings.Scopes.Workspace); this.allowedSchemas = new Set( Settings.getScopedSettingFromVSConfig('allowedSchemas', Settings.Scopes.Workspace) || supportedSchemes ); setOfSupportedSchemes.clear(); this.allowedSchemas.forEach((schema) => setOfSupportedSchemes.add(schema)); this.languageIds = new Set(languageIds.concat(enabledLanguageIds || []).concat(LanguageIds.languageIds)); const uniqueLangIds = [...this.languageIds]; const documentSelector = [...this.allowedSchemas] .map((scheme) => uniqueLangIds.map((language) => ({ language, scheme }))) .reduce((a, b) => a.concat(b)); // Options to control the language client const clientOptions: LanguageClientOptions = { documentSelector, diagnosticCollectionName, synchronize: { // Synchronize the setting section 'spellChecker' to the server configurationSection: [sectionCSpell, 'search'], }, middleware: { handleDiagnostics(uri, diagnostics, next) { // console.error(`${new Date().toISOString()} Client handleDiagnostics: ${uri.toString()}`); next(uri, diagnostics); }, }, }; if (traceMode !== Trace.Off) { clientOptions.traceOutputChannel = window.createOutputChannel('Trace CSpell'); } const execArgv = this.calcServerArgs(); const options: ForkOptions = { execArgv }; // The debug options for the server const debugOptions: ForkOptions = { execArgv: [...execArgv, ...debugExecArgv] }; // If the extension is launched in debug mode the debug server options are use // Otherwise the run options are used const serverOptions: ServerOptions = { run: { module, transport: TransportKind.ipc, options }, debug: { module, transport: TransportKind.ipc, options: debugOptions }, }; // Create the language client and start the client. this.client = new LanguageClient('cspell', 'Code Spell Checker', serverOptions, clientOptions); this.client.registerProposedFeatures(); setTimeout(() => { this.client.trace = traceMode; if (traceMode !== Trace.Off) { this.client.traceOutputChannel.show(); } }, 1000); this.serverApi = createServerApi(this.client); this.initWhenReady().catch((e) => console.error(e)); } public needsStart(): boolean { return this.client.needsStart(); } public needsStop(): boolean { return this.client.needsStop(); } public start(): Disposable { return this.exposeDisposable(this.client.start()); } public async isSpellCheckEnabled(document: TextDocument): Promise<ServerResponseIsSpellCheckEnabledForFile> { const { uri, languageId = '' } = document; if (!uri || !languageId) { return { uri }; } const response = await this.serverApi.isSpellCheckEnabled({ uri: uri.toString(), languageId }); return { ...response, uri }; } readonly getConfigurationForDocument = this.factoryGetConfigurationForDocument(); private async _getConfigurationForDocument( document: TextDocument | TextDocumentInfo | undefined ): Promise<GetConfigurationForDocumentResult> { const { uri, languageId } = document || {}; const workspaceConfig = calculateWorkspaceConfigForDocument(uri); if (!uri) { return this.serverApi.getConfigurationForDocument({ workspaceConfig }); } return this.serverApi.getConfigurationForDocument({ uri: uri.toString(), languageId, workspaceConfig }); } private cacheGetConfigurationForDocument = new Map<string | undefined, Promise<GetConfigurationForDocumentResult>>(); private factoryGetConfigurationForDocument(): ( document: TextDocument | TextDocumentInfo | undefined ) => Promise<GetConfigurationForDocumentResult> { return (document: TextDocument | TextDocumentInfo | undefined) => { const key = document?.uri?.toString(); const found = this.cacheGetConfigurationForDocument.get(key); if (found) return found; const result = this._getConfigurationForDocument(document); this.cacheGetConfigurationForDocument.set(key, result); return result; }; } public notifySettingsChanged(): Promise<void> { this.cacheGetConfigurationForDocument.clear(); setTimeout(() => this.cacheGetConfigurationForDocument.clear(), 250); return silenceErrors( this.whenReady(() => this.serverApi.notifyConfigChange()), 'notifySettingsChanged' ); } public registerConfiguration(path: string): Promise<void> { return logErrors( this.whenReady(() => this.serverApi.registerConfigurationFile(path)), 'registerConfiguration' ); } get diagnostics(): Maybe<DiagnosticCollection> { return (this.client && this.client.diagnostics) || undefined; } public triggerSettingsRefresh(): Promise<void> { return this.notifySettingsChanged(); } public async whenReady<R>(fn: () => R): Promise<R> { await this.client.onReady(); return fn(); } public static create(context: ExtensionContext): Promise<CSpellClient> { return Promise.resolve(vsCodeSupportedLanguages.getLanguages().then((langIds) => new CSpellClient(context, langIds))); } /** * @param d - internal disposable to register * @returns the disposable to hand out. */ private exposeDisposable(d: Disposable): Disposable { this.registerDisposable(d); return new Disposable(() => this.disposeOf(d)); } private registerDisposable(...disposables: Disposable[]) { for (const d of disposables) { this.disposables.add(d); } } private disposeOf(d: Disposable) { if (!this.disposables.has(d)) return; this.disposables.delete(d); d.dispose(); } public dispose(): void { const toDispose = [...this.disposables]; this.disposables.clear(); Disposable.from(...toDispose).dispose(); } private calcServerArgs(): string[] { const args: string[] = []; return args; } public onSpellCheckDocumentNotification(fn: (p: OnSpellCheckDocumentStep) => void): Disposable { return this.broadcasterOnSpellCheckDocument.listen(fn); } public async requestSpellingSuggestions(doc: TextDocument, range: Range, diagnostics: Diagnostic[]): Promise<CodeAction[]> { const params: VSCodeLangClient.CodeActionParams = { textDocument: VSCodeLangClient.TextDocumentIdentifier.create(doc.uri.toString()), range: mapRangeToLangClient(range), context: VSCodeLangClient.CodeActionContext.create(diagnostics.map(mapDiagnosticToLangClient)), }; const r = await requestCodeAction(this.client, params); if (!r) return []; const actions = r.filter(isCodeAction).map(mapCodeAction); return actions; } private async initWhenReady() { await this.client.onReady(); this.registerHandleNotificationsFromServer(); this.registerHandleOnWorkspaceConfigForDocumentRequest(); } private registerHandleOnWorkspaceConfigForDocumentRequest() { this.registerDisposable(this.serverApi.onWorkspaceConfigForDocumentRequest(handleOnWorkspaceConfigForDocumentRequest)); } private registerHandleNotificationsFromServer() { this.registerDisposable(this.serverApi.onSpellCheckDocument((p) => this.broadcasterOnSpellCheckDocument.send(p))); } } function handleOnWorkspaceConfigForDocumentRequest(req: WorkspaceConfigForDocumentRequest): WorkspaceConfigForDocumentResponse { const { uri } = req; const docUri = Uri.parse(uri); return calculateWorkspaceConfigForDocument(docUri); } function calculateWorkspaceConfigForDocument(docUri: Uri | undefined): WorkspaceConfigForDocument { const scope = findConicalDocumentScope(docUri); const cfg = inspectConfigKeys(scope, ['words', 'userWords', 'ignoreWords']); const workspaceFile = workspace.workspaceFile?.toString(); const workspaceFolder = scope && workspace.getWorkspaceFolder(scope)?.uri.toString(); const allowFolder = workspaceFile !== undefined; const tUserWords = toConfigTarget(cfg.userWords, allowFolder); const tWords = toConfigTarget(cfg.words, allowFolder); const tIgnoreWords = toConfigTarget(cfg.ignoreWords, allowFolder); tWords.user = tUserWords.user; const resp: WorkspaceConfigForDocumentResponse = { uri: docUri?.toString(), workspaceFile, workspaceFolder, words: tWords, ignoreWords: tIgnoreWords, }; // console.log('handleOnWorkspaceConfigForDocumentRequest Req: %o Res: %o cfg: %o', req, resp, cfg); return resp; } function toConfigTarget<T>(ins: Inspect<T> | undefined, allowFolder: boolean): FieldExistsInTarget { if (!ins) return {}; const { globalValue, workspaceValue, workspaceFolderValue } = ins; return { user: globalValue !== undefined || undefined, workspace: workspaceValue !== undefined || undefined, folder: allowFolder && (workspaceFolderValue !== undefined || undefined), }; } function isCodeAction(c: VSCodeLangClient.Command | VSCodeLangClient.CodeAction): c is VSCodeLangClient.CodeAction { return VSCodeLangClient.CodeAction.is(c); } function mapCodeAction(c: VSCodeLangClient.CodeAction): CodeAction { const kind = (c.kind !== undefined && CodeActionKind.Empty.append(c.kind)) || undefined; const action = new CodeAction(c.title, kind); action.command = c.command && mapCommand(c.command); return action; } function mapCommand(c: VSCodeLangClient.Command): Command { return c; } type MapDiagnosticSeverity = { [key in DiagnosticSeverity]: VSCodeLangClient.DiagnosticSeverity; }; const diagSeverityMap: MapDiagnosticSeverity = { [DiagnosticSeverity.Error]: VSCodeLangClient.DiagnosticSeverity.Error, [DiagnosticSeverity.Warning]: VSCodeLangClient.DiagnosticSeverity.Warning, [DiagnosticSeverity.Information]: VSCodeLangClient.DiagnosticSeverity.Information, [DiagnosticSeverity.Hint]: VSCodeLangClient.DiagnosticSeverity.Hint, }; function mapDiagnosticToLangClient(d: Diagnostic): VSCodeLangClient.Diagnostic { const diag = VSCodeLangClient.Diagnostic.create( mapRangeToLangClient(d.range), d.message, diagSeverityMap[d.severity], undefined, d.source ); return diag; } function mapRangeToLangClient(r: Range): VSCodeLangClient.Range { const { start, end } = r; return VSCodeLangClient.Range.create(mapPositionToLangClient(start), mapPositionToLangClient(end)); } function mapPositionToLangClient(p: Position): VSCodeLangClient.Position { const { line, character } = p; return VSCodeLangClient.Position.create(line, character); }
the_stack
import './DashboardItems.scss' import { Link } from 'lib/components/Link' import { useActions, useValues, BindLogic } from 'kea' import { Dropdown, Menu, Alert, Skeleton } from 'antd' import { combineUrl, router } from 'kea-router' import { deleteWithUndo, Loading } from 'lib/utils' import React, { RefObject, useEffect, useState } from 'react' import { ActionsLineGraph } from 'scenes/trends/viz/ActionsLineGraph' import { ActionsTable } from 'scenes/trends/viz/ActionsTable' import { ActionsPie } from 'scenes/trends/viz/ActionsPie' import { Paths } from 'scenes/paths/Paths' import { EllipsisOutlined, SaveOutlined } from '@ant-design/icons' import { dashboardColorNames, dashboardColors } from 'lib/colors' import { useLongPress } from 'lib/hooks/useLongPress' import { usePrevious } from 'lib/hooks/usePrevious' import { dashboardsModel } from '~/models/dashboardsModel' import { RetentionContainer } from 'scenes/retention/RetentionContainer' import { SaveModal } from 'scenes/insights/SaveModal' import { insightsModel } from '~/models/insightsModel' import { InsightModel, DashboardMode, DashboardType, ChartDisplayType, InsightType, FilterType, InsightLogicProps, InsightShortId, } from '~/types' import { ActionsHorizontalBar } from 'scenes/trends/viz' import { eventUsageLogic } from 'lib/utils/eventUsageLogic' import { Funnel } from 'scenes/funnels/Funnel' import { Tooltip } from 'lib/components/Tooltip' import { InsightEmptyState, FunnelInvalidExclusionState, FunnelSingleStepState, InsightErrorState, InsightTimeoutState, } from 'scenes/insights/EmptyStates' import { funnelLogic } from 'scenes/funnels/funnelLogic' import { insightLogic } from 'scenes/insights/insightLogic' import { featureFlagLogic } from 'lib/logic/featureFlagLogic' import { FEATURE_FLAGS } from 'lib/constants' import { LinkButton } from 'lib/components/LinkButton' import { DiveIcon } from 'lib/components/icons' import { teamLogic } from '../teamLogic' import { dayjs } from 'lib/dayjs' import { urls } from 'scenes/urls' interface DashboardItemProps { item: InsightModel dashboardId?: number receivedErrorFromAPI?: boolean updateItemColor?: (insightId: number, itemClassName: string) => void setDiveDashboard?: (insightId: number, diveDashboard: number | null) => void loadDashboardItems?: () => void isDraggingRef?: RefObject<boolean> isReloading?: boolean reload?: () => void dashboardMode: DashboardMode | null isOnEditMode: boolean setEditMode?: () => void index: number layout?: any footer?: JSX.Element onClick?: () => void moveDashboardItem?: (it: InsightModel, dashboardId: number) => void saveDashboardItem?: (it: InsightModel) => void duplicateDashboardItem?: (it: InsightModel, dashboardId?: number) => void isHighlighted?: boolean doNotLoad?: boolean } export type DisplayedType = ChartDisplayType | 'RetentionContainer' interface DisplayProps { className: string element: (props: any) => JSX.Element | null viewText: string } // const insightLink = ({ filters, short_id, dashboard, name }: InsightModel): string => export const displayMap: Record<DisplayedType, DisplayProps> = { ActionsLineGraph: { className: 'graph', element: ActionsLineGraph, viewText: 'View graph', }, ActionsLineGraphCumulative: { className: 'graph', element: ActionsLineGraph, viewText: 'View graph', }, ActionsBar: { className: 'bar', element: ActionsLineGraph, viewText: 'View graph', }, ActionsBarValue: { className: 'bar', element: ActionsHorizontalBar, viewText: 'View graph', }, ActionsTable: { className: 'table', element: ActionsTable, viewText: 'View table', }, ActionsPie: { className: 'pie', element: ActionsPie, viewText: 'View graph', }, FunnelViz: { className: 'funnel', element: Funnel, viewText: 'View funnel', }, RetentionContainer: { className: 'retention', element: RetentionContainer, viewText: 'View graph', }, PathsViz: { className: 'paths-viz', element: Paths, viewText: 'View graph', }, } export function getDisplayedType(filters: Partial<FilterType>): DisplayedType { return ( filters.insight === InsightType.RETENTION ? 'RetentionContainer' : filters.insight === InsightType.PATHS ? 'PathsViz' : filters.insight === InsightType.FUNNELS ? 'FunnelViz' : filters.display || 'ActionsLineGraph' ) as DisplayedType } const dashboardDiveLink = (dive_dashboard: number, dive_source_id: InsightShortId): string => { return combineUrl(`/dashboard/${dive_dashboard}`, { dive_source_id: dive_source_id }).url } export function DashboardItem({ item, dashboardId, receivedErrorFromAPI, updateItemColor, setDiveDashboard, loadDashboardItems, isDraggingRef, isReloading, reload, dashboardMode, isOnEditMode, setEditMode, index, layout, footer, onClick, moveDashboardItem, saveDashboardItem, duplicateDashboardItem, isHighlighted = false, doNotLoad = false, }: DashboardItemProps): JSX.Element { const [initialLoaded, setInitialLoaded] = useState(false) const [showSaveModal, setShowSaveModal] = useState(false) const { currentTeamId } = useValues(teamLogic) const { nameSortedDashboards } = useValues(dashboardsModel) const { renameInsight } = useActions(insightsModel) const { featureFlags } = useValues(featureFlagLogic) const _type = getDisplayedType(item.filters) const insightTypeDisplayName = item.filters.insight === InsightType.RETENTION ? 'Retention' : item.filters.insight === InsightType.PATHS ? 'Paths' : item.filters.insight === InsightType.FUNNELS ? 'Funnel' : item.filters.insight === InsightType.SESSIONS ? 'Sessions' : item.filters.insight === InsightType.STICKINESS ? 'Stickiness' : 'Trends' const className = displayMap[_type].className const Element = displayMap[_type].element const viewText = displayMap[_type].viewText const link = combineUrl(urls.insightView(item.short_id, item.filters), undefined, { fromDashboard: item.dashboard, }).url const color = item.color || 'white' const otherDashboards: DashboardType[] = nameSortedDashboards.filter((d: DashboardType) => d.id !== dashboardId) const getDashboard = (id: number): DashboardType | undefined => nameSortedDashboards.find((d) => d.id === id) const longPressProps = useLongPress(setEditMode, { ms: 500, touch: true, click: false, exclude: 'table, table *', }) const filters = { ...item.filters, from_dashboard: item.dashboard || undefined } const logicProps: InsightLogicProps = { dashboardItemId: item.short_id, filters: filters, cachedResults: (item as any).result, doNotLoad, } const { insightProps, showTimeoutMessage, showErrorMessage, insight, insightLoading, isLoading } = useValues( insightLogic(logicProps) ) const { loadResults } = useActions(insightLogic(logicProps)) const { reportDashboardItemRefreshed } = useActions(eventUsageLogic) const { areFiltersValid, isValidFunnel, areExclusionFiltersValid } = useValues(funnelLogic(insightProps)) const previousLoading = usePrevious(insightLoading) const diveDashboard = item.dive_dashboard ? getDashboard(item.dive_dashboard) : null // if a load is performed and returns that is not the initial load, we refresh dashboard item to update timestamp useEffect(() => { if (previousLoading && !insightLoading && !initialLoaded) { setInitialLoaded(true) } }, [insightLoading]) // Empty states that completely replace the graph const BlockingEmptyState = (() => { // Insight specific empty states - note order is important here if (item.filters.insight === InsightType.FUNNELS) { if (!areFiltersValid) { return <FunnelSingleStepState /> } if (!areExclusionFiltersValid) { return <FunnelInvalidExclusionState /> } if (!isValidFunnel && !(insightLoading || isLoading)) { return <InsightEmptyState /> } } // Insight agnostic empty states if (showErrorMessage || receivedErrorFromAPI) { return <InsightErrorState excludeDetail={true} /> } if (showTimeoutMessage) { return <InsightTimeoutState isLoading={isLoading} /> } return null })() // Empty states that can coexist with the graph (e.g. Loading) const CoexistingEmptyState = (() => { if (isLoading || insightLoading || isReloading) { return <Loading /> } return null })() const response = ( <div key={item.short_id} className={`dashboard-item ${item.color || 'white'} di-width-${layout?.w || 0} di-height-${ layout?.h || 0 } ph-no-capture`} {...longPressProps} data-attr={'dashboard-item-' + index} style={{ border: isHighlighted ? '1px solid var(--primary)' : undefined }} > {!BlockingEmptyState && CoexistingEmptyState} <div className={`dashboard-item-container ${className}`}> <div className="dashboard-item-header" style={{ cursor: isOnEditMode ? 'move' : 'inherit' }}> <div className="dashboard-item-title" data-attr="dashboard-item-title"> {dashboardMode === DashboardMode.Public ? ( item.name ) : ( <Link draggable={false} to={link} title={item.name} preventClick onClick={() => { if (!isDraggingRef?.current) { onClick ? onClick() : router.actions.push(link) } }} style={{ fontSize: 16, fontWeight: 500 }} > {item.name || `Untitled ${insightTypeDisplayName} Query`} </Link> )} </div> {dashboardMode !== DashboardMode.Public && ( <div className="dashboard-item-settings"> {saveDashboardItem && dashboardMode !== DashboardMode.Internal && (!item.saved && item.dashboard ? ( <Link to={'/dashboard/' + item.dashboard}> <small>View dashboard</small> </Link> ) : ( <Tooltip title="Save insight"> <SaveOutlined style={{ cursor: 'pointer', marginTop: -3, ...(item.saved ? { background: 'var(--primary)', color: 'white', } : {}), }} onClick={() => { if (item.saved) { return saveDashboardItem({ ...item, saved: false }) } if (item.name) { // If item already has a name we don't have to ask for it again return saveDashboardItem({ ...item, saved: true }) } setShowSaveModal(true) }} /> </Tooltip> ))} {dashboardMode !== DashboardMode.Internal && ( <> {featureFlags[FEATURE_FLAGS.DIVE_DASHBOARDS] && typeof item.dive_dashboard === 'number' && ( <Tooltip title={`Dive to ${diveDashboard?.name || 'connected dashboard'}`}> <LinkButton to={dashboardDiveLink(item.dive_dashboard, item.short_id)} icon={ <span role="img" aria-label="dive" className="anticon"> <DiveIcon /> </span> } data-attr="dive-btn-dive" className="dive-btn dive-btn-dive" > Dive </LinkButton> </Tooltip> )} <Dropdown overlayStyle={{ minWidth: 240, border: '1px solid var(--primary)' }} placement="bottomRight" trigger={['click']} overlay={ <Menu data-attr={'dashboard-item-' + index + '-dropdown-menu'} style={{ padding: '12px 4px' }} > <Menu.Item data-attr={'dashboard-item-' + index + '-dropdown-view'}> <Link to={link}>{viewText}</Link> </Menu.Item> <Menu.Item data-attr={'dashboard-item-' + index + '-dropdown-refresh'} onClick={() => { // On dashboards we use custom reloading logic, which updates a // global "loading 1 out of n" label, and loads 4 items at a time if (reload) { reload() } else { loadResults(true) } reportDashboardItemRefreshed(item) }} > <Tooltip placement="left" title={ <i> Last updated:{' '} {item.last_refresh ? dayjs(item.last_refresh).fromNow() : 'recently'} </i> } > Refresh </Tooltip> </Menu.Item> <Menu.Item data-attr={'dashboard-item-' + index + '-dropdown-rename'} onClick={() => renameInsight(item)} > Rename </Menu.Item> {updateItemColor && ( <Menu.SubMenu data-attr={'dashboard-item-' + index + '-dropdown-color'} key="colors" title="Set color" > {Object.entries(dashboardColorNames).map( ([itemClassName, itemColor], colorIndex) => ( <Menu.Item key={itemClassName} onClick={() => updateItemColor(item.id, itemClassName) } data-attr={ 'dashboard-item-' + index + '-dropdown-color-' + colorIndex } > <span style={{ background: dashboardColors[itemClassName], border: '1px solid #eee', display: 'inline-block', width: 13, height: 13, verticalAlign: 'middle', marginRight: 5, marginBottom: 1, }} /> {itemColor} </Menu.Item> ) )} </Menu.SubMenu> )} {featureFlags[FEATURE_FLAGS.DIVE_DASHBOARDS] && setDiveDashboard && ( <Menu.SubMenu data-attr={'dashboard-item-' + index + '-dive-dashboard'} key="dive" title={`Set dive dashboard`} > {otherDashboards.map((dashboard, diveIndex) => ( <Menu.Item data-attr={ 'dashboard-item-' + index + '-dive-dashboard-' + diveIndex } key={dashboard.id} onClick={() => setDiveDashboard(item.id, dashboard.id)} disabled={dashboard.id === item.dive_dashboard} > {dashboard.name} </Menu.Item> ))} <Menu.Item data-attr={ 'dashboard-item-' + index + '-dive-dashboard-remove' } key="remove" onClick={() => setDiveDashboard(item.id, null)} className="text-danger" > Remove </Menu.Item> </Menu.SubMenu> )} {duplicateDashboardItem && otherDashboards.length > 0 && ( <Menu.SubMenu data-attr={'dashboard-item-' + index + '-dropdown-copy'} key="copy" title="Copy to" > {otherDashboards.map((dashboard, copyIndex) => ( <Menu.Item data-attr={ 'dashboard-item-' + index + '-dropdown-copy-' + copyIndex } key={dashboard.id} onClick={() => duplicateDashboardItem(item, dashboard.id) } > <span style={{ background: dashboardColors[className], border: '1px solid #eee', display: 'inline-block', width: 13, height: 13, verticalAlign: 'middle', marginRight: 5, marginBottom: 1, }} /> {dashboard.name} </Menu.Item> ))} </Menu.SubMenu> )} {moveDashboardItem && (otherDashboards.length > 0 ? ( <Menu.SubMenu data-attr={'dashboard-item-' + index + '-dropdown-move'} key="move" title="Move to" > {otherDashboards.map((dashboard, moveIndex) => ( <Menu.Item data-attr={ 'dashboard-item-' + index + '-dropdown-move-' + moveIndex } key={dashboard.id} onClick={() => moveDashboardItem(item, dashboard.id) } > {dashboard.name} </Menu.Item> ))} </Menu.SubMenu> ) : null)} {duplicateDashboardItem && ( <Menu.Item data-attr={'dashboard-item-' + index + '-dropdown-duplicate'} onClick={() => duplicateDashboardItem(item)} > Duplicate </Menu.Item> )} <Menu.Item data-attr={'dashboard-item-' + index + '-dropdown-delete'} onClick={() => deleteWithUndo({ object: { id: item.id, name: item.name, }, endpoint: `projects/${currentTeamId}/insights`, callback: loadDashboardItems, }) } className="text-danger" > Delete </Menu.Item> </Menu> } > <span data-attr={'dashboard-item-' + index + '-dropdown'} style={{ cursor: 'pointer', marginTop: -3 }} > <EllipsisOutlined /> </span> </Dropdown> </> )} </div> )} </div> {item.description && ( <div style={{ padding: '0 16px', marginBottom: 16, fontSize: 12 }}>{item.description}</div> )} <div className={`dashboard-item-content ${_type}`} onClickCapture={onClick}> {!!BlockingEmptyState ? ( BlockingEmptyState ) : ( <Alert.ErrorBoundary message="Error rendering graph!"> {dashboardMode === DashboardMode.Public && !insight.result && !item.result ? ( <Skeleton /> ) : ( <Element dashboardItemId={item.short_id} cachedResults={item.result} filters={filters} color={color} theme={color === 'white' ? 'light' : 'dark'} inSharedMode={dashboardMode === DashboardMode.Public} /> )} </Alert.ErrorBoundary> )} </div> {footer} </div> {showSaveModal && saveDashboardItem && ( <SaveModal title="Save Chart" prompt="Name of Chart" textLabel="Name" textPlaceholder="DAUs Last 14 days" visible={true} onCancel={() => { setShowSaveModal(false) }} onSubmit={(text) => { saveDashboardItem({ ...item, name: text, saved: true }) setShowSaveModal(false) }} /> )} </div> ) return ( <BindLogic logic={insightLogic} props={insightProps}> {response} </BindLogic> ) }
the_stack
import * as crypto from "crypto"; import { EventEmitter } from "events"; import { addElement, AddressSpace, ContinuationPointManager, createExtObjArrayNode, ensureObjectIsSecure, ISessionBase, removeElement, UADynamicVariableArray, UAObject, UASessionDiagnosticsVariable, UASessionSecurityDiagnostics, DTSessionDiagnostics, DTSessionSecurityDiagnostics } from "node-opcua-address-space"; import { assert } from "node-opcua-assert"; import { randomGuid } from "node-opcua-basic-types"; import { SessionDiagnosticsDataType, SessionSecurityDiagnosticsDataType, SubscriptionDiagnosticsDataType } from "node-opcua-common"; import { QualifiedName, NodeClass } from "node-opcua-data-model"; import { checkDebugFlag, make_debugLog } from "node-opcua-debug"; import { makeNodeId, NodeId, NodeIdType, sameNodeId } from "node-opcua-nodeid"; import { ObjectRegistry } from "node-opcua-object-registry"; import { StatusCode, StatusCodes } from "node-opcua-status-code"; import { WatchDog } from "node-opcua-utils"; import { lowerFirstLetter } from "node-opcua-utils"; import { ISubscriber, IWatchdogData2 } from "node-opcua-utils"; import { IServerSession, ServerSecureChannelLayer } from "node-opcua-secure-channel"; import { ApplicationDescription, UserIdentityToken, CreateSubscriptionRequestOptions, EndpointDescription } from "node-opcua-types"; import { ServerSidePublishEngine } from "./server_publish_engine"; import { Subscription } from "./server_subscription"; import { SubscriptionState } from "./server_subscription"; import { ServerEngine } from "./server_engine"; const debugLog = make_debugLog(__filename); const doDebug = checkDebugFlag(__filename); const theWatchDog = new WatchDog(); const registeredNodeNameSpace = 9999; function compareSessionId( sessionDiagnostics1: SessionDiagnosticsDataType | SessionSecurityDiagnosticsDataType, sessionDiagnostics2: SessionDiagnosticsDataType | SessionSecurityDiagnosticsDataType ) { return sessionDiagnostics1.sessionId.toString() === sessionDiagnostics2.sessionId.toString(); } function on_channel_abort(this: ServerSession) { debugLog("ON CHANNEL ABORT ON SESSION!!!"); /** * @event channel_aborted */ this.emit("channel_aborted"); } interface SessionDiagnosticsDataTypeEx extends SessionDiagnosticsDataType { $session: any; } interface SessionSecurityDiagnosticsDataTypeEx extends SessionSecurityDiagnosticsDataType { $session: any; } /** * * A Server session object. * * **from OPCUA Spec 1.02:** * * * Sessions are created to be independent of the underlying communications connection. Therefore, if a communication * connection fails, the Session is not immediately affected. The exact mechanism to recover from an underlying * communication connection error depends on the SecureChannel mapping as described in Part 6. * * * Sessions are terminated by the Server automatically if the Client fails to issue a Service request on the Session * within the timeout period negotiated by the Server in the CreateSession Service response. This protects the Server * against Client failures and against situations where a failed underlying connection cannot be re-established. * * * Clients shall be prepared to submit requests in a timely manner to prevent the Session from closing automatically. * * * Clients may explicitly terminate Sessions using the CloseSession Service. * * * When a Session is terminated, all outstanding requests on the Session are aborted and BadSessionClosed StatusCodes * are returned to the Client. In addition, the Server deletes the entry for the Client from its * SessionDiagnosticsArray Variable and notifies any other Clients who were subscribed to this entry. * */ export class ServerSession extends EventEmitter implements ISubscriber, ISessionBase, IServerSession { public static registry = new ObjectRegistry(); public static maxPublishRequestInQueue = 100; public __status = ""; public parent: ServerEngine; public authenticationToken: NodeId; public nodeId: NodeId; public sessionName = ""; public publishEngine: ServerSidePublishEngine; public sessionObject: any; public readonly creationDate: Date; public sessionTimeout: number; public sessionDiagnostics?: UASessionDiagnosticsVariable<DTSessionDiagnostics>; public sessionSecurityDiagnostics?: UASessionSecurityDiagnostics<DTSessionSecurityDiagnostics>; public subscriptionDiagnosticsArray?: UADynamicVariableArray<SubscriptionDiagnosticsDataType>; public channel?: ServerSecureChannelLayer; public nonce?: Buffer; public userIdentityToken?: UserIdentityToken; public clientDescription?: ApplicationDescription; public channelId?: number | null; public continuationPointManager: ContinuationPointManager; // ISubscriber public _watchDog?: WatchDog; public _watchDogData?: IWatchdogData2; keepAlive: () => void = WatchDog.emptyKeepAlive; private _registeredNodesCounter: number; private _registeredNodes: any; private _registeredNodesInv: any; private _cumulatedSubscriptionCount: number; private _sessionDiagnostics?: SessionDiagnosticsDataTypeEx; private _sessionSecurityDiagnostics?: SessionSecurityDiagnosticsDataTypeEx; private channel_abort_event_handler: any; constructor(parent: ServerEngine, sessionTimeout: number) { super(); this.parent = parent; // SessionEngine ServerSession.registry.register(this); assert(isFinite(sessionTimeout)); assert(sessionTimeout >= 0, " sessionTimeout"); this.sessionTimeout = sessionTimeout; const authenticationTokenBuf = crypto.randomBytes(16); this.authenticationToken = new NodeId(NodeIdType.BYTESTRING, authenticationTokenBuf); // the sessionId const ownNamespaceIndex = 1; // addressSpace.getOwnNamespace().index; this.nodeId = new NodeId(NodeIdType.GUID, randomGuid(), ownNamespaceIndex); assert(this.authenticationToken instanceof NodeId); assert(this.nodeId instanceof NodeId); this._cumulatedSubscriptionCount = 0; this.publishEngine = new ServerSidePublishEngine({ maxPublishRequestInQueue: ServerSession.maxPublishRequestInQueue }); this.publishEngine.setMaxListeners(100); theWatchDog.addSubscriber(this, this.sessionTimeout); this.__status = "new"; /** * the continuation point manager for this session * @property continuationPointManager * @type {ContinuationPointManager} */ this.continuationPointManager = new ContinuationPointManager(); /** * @property creationDate * @type {Date} */ this.creationDate = new Date(); this._registeredNodesCounter = 0; this._registeredNodes = {}; this._registeredNodesInv = {}; } public getSessionId(): NodeId { return this.nodeId; } public endpoint?: EndpointDescription; public getEndpointDescription(): EndpointDescription { return this.endpoint!; } public dispose(): void { debugLog("ServerSession#dispose()"); assert(!this.sessionObject, " sessionObject has not been cleared !"); this.parent = null as any as ServerEngine; this.authenticationToken = NodeId.nullNodeId; if (this.publishEngine) { this.publishEngine.dispose(); (this as any).publishEngine = null; } this._sessionDiagnostics = undefined; this._registeredNodesCounter = 0; this._registeredNodes = null; this._registeredNodesInv = null; (this as any).continuationPointManager = null; this.removeAllListeners(); this.__status = "disposed"; ServerSession.registry.unregister(this); } public get clientConnectionTime(): Date { return this.creationDate; } public get clientLastContactTime(): number { return this._watchDogData!.lastSeen; } public get status(): string { return this.__status; } public set status(value: string) { if (value === "active") { this._createSessionObjectInAddressSpace(); } this.__status = value; } get addressSpace(): AddressSpace | null { if (this.parent && this.parent.addressSpace) { return this.parent.addressSpace!; } return null; } get currentPublishRequestInQueue(): number { return this.publishEngine ? this.publishEngine.pendingPublishRequestCount : 0; } public updateClientLastContactTime(): void { if (this._sessionDiagnostics && this._sessionDiagnostics.clientLastContactTime) { const currentTime = new Date(); // do not record all ticks as this may be overwhelming, if (currentTime.getTime() - 250 >= this._sessionDiagnostics.clientLastContactTime.getTime()) { this._sessionDiagnostics.clientLastContactTime = currentTime; } } } /** * @method onClientSeen * required for watch dog * @param currentTime {DateTime} * @private */ public onClientSeen(): void { this.updateClientLastContactTime(); if (this._sessionDiagnostics) { // see https://opcfoundation-onlineapplications.org/mantis/view.php?id=4111 assert(Object.prototype.hasOwnProperty.call(this._sessionDiagnostics, "currentMonitoredItemsCount")); assert(Object.prototype.hasOwnProperty.call(this._sessionDiagnostics, "currentSubscriptionsCount")); assert(Object.prototype.hasOwnProperty.call(this._sessionDiagnostics, "currentPublishRequestsInQueue")); // note : https://opcfoundation-onlineapplications.org/mantis/view.php?id=4111 // sessionDiagnostics extension object uses a different spelling // here with an S !!!! if (this._sessionDiagnostics.currentMonitoredItemsCount !== this.currentMonitoredItemCount) { this._sessionDiagnostics.currentMonitoredItemsCount = this.currentMonitoredItemCount; } if (this._sessionDiagnostics.currentSubscriptionsCount !== this.currentSubscriptionCount) { this._sessionDiagnostics.currentSubscriptionsCount = this.currentSubscriptionCount; } if (this._sessionDiagnostics.currentPublishRequestsInQueue !== this.currentPublishRequestInQueue) { this._sessionDiagnostics.currentPublishRequestsInQueue = this.currentPublishRequestInQueue; } } } public incrementTotalRequestCount(): void { if (this._sessionDiagnostics && this._sessionDiagnostics.totalRequestCount) { this._sessionDiagnostics.totalRequestCount.totalCount += 1; } } public incrementRequestTotalCounter(counterName: string): void { if (this._sessionDiagnostics) { const propName = lowerFirstLetter(counterName + "Count"); if (!Object.prototype.hasOwnProperty.call(this._sessionDiagnostics, propName)) { console.log(" cannot find", propName); // xx return; } else { // console.log(self._sessionDiagnostics.toString()); (this._sessionDiagnostics as any)[propName].totalCount += 1; } } } public incrementRequestErrorCounter(counterName: string): void { this.parent?.incrementRejectedRequestsCount(); if (this._sessionDiagnostics) { const propName = lowerFirstLetter(counterName + "Count"); if (!Object.prototype.hasOwnProperty.call(this._sessionDiagnostics, propName)) { console.log(" cannot find", propName); // xx return; } else { (this._sessionDiagnostics as any)[propName].errorCount += 1; } } } /** * returns rootFolder.objects.server.serverDiagnostics.sessionsDiagnosticsSummary.sessionDiagnosticsArray */ public getSessionDiagnosticsArray(): UADynamicVariableArray<SessionDiagnosticsDataType> { const server = this.addressSpace!.rootFolder.objects.server; return server.serverDiagnostics.sessionsDiagnosticsSummary.sessionDiagnosticsArray as any; } /** * returns rootFolder.objects.server.serverDiagnostics.sessionsDiagnosticsSummary.sessionSecurityDiagnosticsArray */ public getSessionSecurityDiagnosticsArray(): UADynamicVariableArray<SessionSecurityDiagnosticsDataType> { const server = this.addressSpace!.rootFolder.objects.server; return server.serverDiagnostics.sessionsDiagnosticsSummary.sessionSecurityDiagnosticsArray as any; } /** * number of active subscriptions */ public get currentSubscriptionCount(): number { return this.publishEngine ? this.publishEngine.subscriptionCount : 0; } /** * number of subscriptions ever created since this object is live */ public get cumulatedSubscriptionCount(): number { return this._cumulatedSubscriptionCount; } /** * number of monitored items */ public get currentMonitoredItemCount(): number { return this.publishEngine ? this.publishEngine.currentMonitoredItemCount : 0; } /** * retrieve an existing subscription by subscriptionId * @method getSubscription * @param subscriptionId {Number} * @return {Subscription} */ public getSubscription(subscriptionId: number): Subscription | null { const subscription = this.publishEngine.getSubscriptionById(subscriptionId); if (subscription && subscription.state === SubscriptionState.CLOSED) { // subscription is CLOSED but has not been notified yet // it should be considered as excluded return null; } assert( !subscription || subscription.state !== SubscriptionState.CLOSED, "CLOSED subscription shall not be managed by publish engine anymore" ); return subscription; } /** * @method deleteSubscription * @param subscriptionId {Number} * @return {StatusCode} */ public deleteSubscription(subscriptionId: number): StatusCode { const subscription = this.getSubscription(subscriptionId); if (!subscription) { return StatusCodes.BadSubscriptionIdInvalid; } // xx this.publishEngine.remove_subscription(subscription); subscription.terminate(); if (this.currentSubscriptionCount === 0) { const local_publishEngine = this.publishEngine; local_publishEngine.cancelPendingPublishRequest(); } return StatusCodes.Good; } /** * close a ServerSession, this will also delete the subscriptions if the flag is set. * * Spec extract: * * If a Client invokes the CloseSession Service then all Subscriptions associated with the Session are also deleted * if the deleteSubscriptions flag is set to TRUE. If a Server terminates a Session for any other reason, * Subscriptions associated with the Session, are not deleted. Each Subscription has its own lifetime to protect * against data loss in the case of a Session termination. In these cases, the Subscription can be reassigned to * another Client before its lifetime expires. * * @method close * @param deleteSubscriptions : should we delete subscription ? * @param [reason = "CloseSession"] the reason for closing the session * (shall be "Timeout", "Terminated" or "CloseSession") * */ public close(deleteSubscriptions: boolean, reason: string): void { debugLog(" closing session deleteSubscriptions = ", deleteSubscriptions); if (this.publishEngine) { this.publishEngine.onSessionClose(); } theWatchDog.removeSubscriber(this); // --------------- delete associated subscriptions --------------------- if (!deleteSubscriptions && this.currentSubscriptionCount !== 0) { // I don't know what to do yet if deleteSubscriptions is false console.log("TO DO : Closing session without deleting subscription not yet implemented"); // to do: Put subscriptions in safe place for future transfer if any } this._deleteSubscriptions(); assert(this.currentSubscriptionCount === 0); // Post-Conditions assert(this.currentSubscriptionCount === 0); this.status = "closed"; /** * @event session_closed * @param deleteSubscriptions {Boolean} * @param reason {String} */ this.emit("session_closed", this, deleteSubscriptions, reason); // ---------------- shut down publish engine if (this.publishEngine) { // remove subscription this.publishEngine.shutdown(); assert(this.publishEngine.subscriptionCount === 0); this.publishEngine.dispose(); this.publishEngine = null as any as ServerSidePublishEngine; } this._removeSessionObjectFromAddressSpace(); assert(!this.sessionDiagnostics, "ServerSession#_removeSessionObjectFromAddressSpace must be called"); assert(!this.sessionObject, "ServerSession#_removeSessionObjectFromAddressSpace must be called"); } public registerNode(nodeId: NodeId): NodeId { assert(nodeId instanceof NodeId); if (nodeId.namespace === 0 && nodeId.identifierType === NodeIdType.NUMERIC) { return nodeId; } const key = nodeId.toString(); const registeredNode = this._registeredNodes[key]; if (registeredNode) { // already registered return registeredNode; } const node = this.addressSpace!.findNode(nodeId); if (!node) { return nodeId; } this._registeredNodesCounter += 1; const aliasNodeId = makeNodeId(this._registeredNodesCounter, registeredNodeNameSpace); this._registeredNodes[key] = aliasNodeId; this._registeredNodesInv[aliasNodeId.toString()] = node; return aliasNodeId; } public unRegisterNode(aliasNodeId: NodeId): void { assert(aliasNodeId instanceof NodeId); if (aliasNodeId.namespace !== registeredNodeNameSpace) { return; // not a registered Node } const node = this._registeredNodesInv[aliasNodeId.toString()]; if (!node) { return; } this._registeredNodesInv[aliasNodeId.toString()] = null; this._registeredNodes[node.nodeId.toString()] = null; } public resolveRegisteredNode(aliasNodeId: NodeId): NodeId { if (aliasNodeId.namespace !== registeredNodeNameSpace) { return aliasNodeId; // not a registered Node } const node = this._registeredNodesInv[aliasNodeId.toString()]; if (!node) { return aliasNodeId; } return node.nodeId; } /** * true if the underlying channel has been closed or aborted... */ public get aborted(): boolean { if (!this.channel) { return true; } return this.channel.aborted; } public createSubscription(parameters: CreateSubscriptionRequestOptions): Subscription { const subscription = this.parent._createSubscriptionOnSession(this, parameters); assert(!Object.prototype.hasOwnProperty.call(parameters, "id")); this.assignSubscription(subscription); assert(subscription.$session === this); assert(subscription.sessionId instanceof NodeId); assert(sameNodeId(subscription.sessionId, this.nodeId)); return subscription; } public _attach_channel(channel: ServerSecureChannelLayer): void { assert(this.nonce && this.nonce instanceof Buffer); this.channel = channel; this.channelId = channel.channelId; const key = this.authenticationToken.toString(); assert(!Object.prototype.hasOwnProperty.call(channel.sessionTokens, key), "channel has already a session"); channel.sessionTokens[key] = this; // when channel is aborting this.channel_abort_event_handler = on_channel_abort.bind(this); channel.on("abort", this.channel_abort_event_handler); } public _detach_channel(): void { const channel = this.channel; if (!channel) { throw new Error("expecting a valid channel"); } assert(this.nonce && this.nonce instanceof Buffer); assert(this.authenticationToken); const key = this.authenticationToken.toString(); assert(Object.prototype.hasOwnProperty.call(channel.sessionTokens, key)); assert(this.channel); assert(typeof this.channel_abort_event_handler === "function"); channel.removeListener("abort", this.channel_abort_event_handler); delete channel.sessionTokens[key]; this.channel = undefined; this.channelId = undefined; } public _exposeSubscriptionDiagnostics(subscription: Subscription): void { debugLog("ServerSession#_exposeSubscriptionDiagnostics"); assert(subscription.$session === this); const subscriptionDiagnosticsArray = this._getSubscriptionDiagnosticsArray(); const subscriptionDiagnostics = subscription.subscriptionDiagnostics; assert(subscriptionDiagnostics.$subscription === subscription); if (subscriptionDiagnostics && subscriptionDiagnosticsArray) { // subscription.id,"on session", session.nodeId.toString()); addElement(subscriptionDiagnostics, subscriptionDiagnosticsArray); } } public _unexposeSubscriptionDiagnostics(subscription: Subscription): void { const subscriptionDiagnosticsArray = this._getSubscriptionDiagnosticsArray(); const subscriptionDiagnostics = subscription.subscriptionDiagnostics; assert(subscriptionDiagnostics instanceof SubscriptionDiagnosticsDataType); if (subscriptionDiagnostics && subscriptionDiagnosticsArray) { // console.log("GG => ServerSession **Unexposing** subscription diagnostics =>", // subscription.id,"on session", session.nodeId.toString()); removeElement(subscriptionDiagnosticsArray, subscriptionDiagnostics); } debugLog("ServerSession#_unexposeSubscriptionDiagnostics"); } /** * @method watchdogReset * used as a callback for the Watchdog * @private */ public watchdogReset(): void { debugLog("Session#watchdogReset: the server session has expired and must be removed from the server"); // the server session has expired and must be removed from the server this.emit("timeout"); } private _createSessionObjectInAddressSpace() { if (this.sessionObject) { return; } assert(!this.sessionObject, "ServerSession#_createSessionObjectInAddressSpace already called ?"); this.sessionObject = null; if (!this.addressSpace) { debugLog("ServerSession#_createSessionObjectInAddressSpace : no addressSpace"); return; // no addressSpace } const root = this.addressSpace.rootFolder; assert(root, "expecting a root object"); if (!root.objects) { debugLog("ServerSession#_createSessionObjectInAddressSpace : no object folder"); return false; } if (!root.objects.server) { debugLog("ServerSession#_createSessionObjectInAddressSpace : no server object"); return false; } // self.addressSpace.findNode(makeNodeId(ObjectIds.Server_ServerDiagnostics)); const serverDiagnosticsNode = root.objects.server.serverDiagnostics; if (!serverDiagnosticsNode || !serverDiagnosticsNode.sessionsDiagnosticsSummary) { debugLog("ServerSession#_createSessionObjectInAddressSpace :" + " no serverDiagnostics.sessionsDiagnosticsSummary"); return false; } const sessionDiagnosticsObjectType = this.addressSpace.findObjectType("SessionDiagnosticsObjectType"); const sessionDiagnosticsDataType = this.addressSpace.findDataType("SessionDiagnosticsDataType"); const sessionDiagnosticsVariableType = this.addressSpace.findVariableType("SessionDiagnosticsVariableType"); const sessionSecurityDiagnosticsDataType = this.addressSpace.findDataType("SessionSecurityDiagnosticsDataType"); const sessionSecurityDiagnosticsType = this.addressSpace.findVariableType("SessionSecurityDiagnosticsType"); const namespace = this.addressSpace.getOwnNamespace(); function createSessionDiagnosticsStuff(this: ServerSession) { if (sessionDiagnosticsDataType && sessionDiagnosticsVariableType) { // the extension object this._sessionDiagnostics = this.addressSpace!.constructExtensionObject( sessionDiagnosticsDataType, {} )! as SessionDiagnosticsDataTypeEx; this._sessionDiagnostics.$session = this; // install property getter on property that are unlikely to change if (this.parent.clientDescription) { this._sessionDiagnostics.clientDescription = this.parent.clientDescription; } Object.defineProperty(this._sessionDiagnostics, "clientConnectionTime", { get(this: any) { return this.$session.clientConnectionTime; } }); Object.defineProperty(this._sessionDiagnostics, "actualSessionTimeout", { get(this: SessionDiagnosticsDataTypeEx) { return this.$session?.sessionTimeout; } }); Object.defineProperty(this._sessionDiagnostics, "sessionId", { get(this: SessionDiagnosticsDataTypeEx) { return this.$session?.nodeId; } }); Object.defineProperty(this._sessionDiagnostics, "sessionName", { get(this: SessionDiagnosticsDataTypeEx) { return this.$session?.sessionName.toString(); } }); this.sessionDiagnostics = sessionDiagnosticsVariableType.instantiate({ browseName: new QualifiedName({ name: "SessionDiagnostics", namespaceIndex: 0 }), componentOf: this.sessionObject, extensionObject: this._sessionDiagnostics, minimumSamplingInterval: 2000 // 2 seconds }) as UASessionDiagnosticsVariable<DTSessionDiagnostics>; this._sessionDiagnostics = this.sessionDiagnostics.$extensionObject as SessionDiagnosticsDataTypeEx; assert(this._sessionDiagnostics.$session === this); const sessionDiagnosticsArray = this.getSessionDiagnosticsArray(); // add sessionDiagnostics into sessionDiagnosticsArray addElement<SessionDiagnosticsDataType>(this._sessionDiagnostics, sessionDiagnosticsArray); } } function createSessionSecurityDiagnosticsStuff(this: ServerSession) { if (sessionSecurityDiagnosticsDataType && sessionSecurityDiagnosticsType) { // the extension object this._sessionSecurityDiagnostics = this.addressSpace!.constructExtensionObject( sessionSecurityDiagnosticsDataType, {} )! as SessionSecurityDiagnosticsDataTypeEx; this._sessionSecurityDiagnostics.$session = this; /* sessionId: NodeId; clientUserIdOfSession: UAString; clientUserIdHistory: UAString[] | null; authenticationMechanism: UAString; encoding: UAString; transportProtocol: UAString; securityMode: MessageSecurityMode; securityPolicyUri: UAString; clientCertificate: ByteString; */ Object.defineProperty(this._sessionSecurityDiagnostics, "sessionId", { get(this: any) { return this.$session?.nodeId; } }); Object.defineProperty(this._sessionSecurityDiagnostics, "clientUserIdOfSession", { get(this: any) { return ""; // UAString // TO DO : implement } }); Object.defineProperty(this._sessionSecurityDiagnostics, "clientUserIdHistory", { get(this: any) { return []; // UAString[] | null } }); Object.defineProperty(this._sessionSecurityDiagnostics, "authenticationMechanism", { get(this: any) { return ""; } }); Object.defineProperty(this._sessionSecurityDiagnostics, "encoding", { get(this: any) { return ""; } }); Object.defineProperty(this._sessionSecurityDiagnostics, "transportProtocol", { get(this: any) { return "opc.tcp"; } }); Object.defineProperty(this._sessionSecurityDiagnostics, "securityMode", { get(this: any) { const session: ServerSession = this.$session; return session?.channel?.securityMode; } }); Object.defineProperty(this._sessionSecurityDiagnostics, "securityPolicyUri", { get(this: any) { const session: ServerSession = this.$session; return session?.channel?.securityPolicy; } }); Object.defineProperty(this._sessionSecurityDiagnostics, "clientCertificate", { get(this: any) { const session: ServerSession = this.$session; return session?.channel!.clientCertificate; } }); this.sessionSecurityDiagnostics = sessionSecurityDiagnosticsType.instantiate({ browseName: new QualifiedName({ name: "SessionSecurityDiagnostics", namespaceIndex: 0 }), componentOf: this.sessionObject, extensionObject: this._sessionSecurityDiagnostics, minimumSamplingInterval: 2000 // 2 seconds }) as UASessionSecurityDiagnostics<DTSessionSecurityDiagnostics>; ensureObjectIsSecure(this.sessionSecurityDiagnostics); this._sessionSecurityDiagnostics = this.sessionSecurityDiagnostics .$extensionObject as SessionSecurityDiagnosticsDataTypeEx; assert(this._sessionSecurityDiagnostics.$session === this); const sessionSecurityDiagnosticsArray = this.getSessionSecurityDiagnosticsArray(); // add sessionDiagnostics into sessionDiagnosticsArray const node = addElement<SessionSecurityDiagnosticsDataType>( this._sessionSecurityDiagnostics, sessionSecurityDiagnosticsArray ); ensureObjectIsSecure(node); } } function createSessionDiagnosticSummaryUAObject(this: ServerSession) { const references: any[] = []; if (sessionDiagnosticsObjectType) { references.push({ isForward: true, nodeId: sessionDiagnosticsObjectType, referenceType: "HasTypeDefinition" }); } this.sessionObject = namespace.createNode({ browseName: this.sessionName || "Session-" + this.nodeId.toString(), componentOf: serverDiagnosticsNode.sessionsDiagnosticsSummary, nodeClass: NodeClass.Object, nodeId: this.nodeId, references, typeDefinition: sessionDiagnosticsObjectType }) as UAObject; createSessionDiagnosticsStuff.call(this); createSessionSecurityDiagnosticsStuff.call(this); } function createSubscriptionDiagnosticsArray(this: ServerSession) { const subscriptionDiagnosticsArrayType = this.addressSpace!.findVariableType("SubscriptionDiagnosticsArrayType")!; assert(subscriptionDiagnosticsArrayType.nodeId.toString() === "ns=0;i=2171"); this.subscriptionDiagnosticsArray = createExtObjArrayNode<SubscriptionDiagnosticsDataType>(this.sessionObject, { browseName: { namespaceIndex: 0, name: "SubscriptionDiagnosticsArray" }, complexVariableType: "SubscriptionDiagnosticsArrayType", indexPropertyName: "subscriptionId", minimumSamplingInterval: 2000, // 2 seconds variableType: "SubscriptionDiagnosticsType" }); } createSessionDiagnosticSummaryUAObject.call(this); createSubscriptionDiagnosticsArray.call(this); return this.sessionObject; } /** * * @private */ private _removeSessionObjectFromAddressSpace() { // todo : dump session statistics in a file or somewhere for deeper diagnostic analysis on closed session if (!this.addressSpace) { return; } if (this.sessionDiagnostics) { const sessionDiagnosticsArray = this.getSessionDiagnosticsArray()!; removeElement(sessionDiagnosticsArray, this.sessionDiagnostics.$extensionObject); this.addressSpace.deleteNode(this.sessionDiagnostics); assert(this._sessionDiagnostics!.$session === this); this._sessionDiagnostics!.$session = null; this._sessionDiagnostics = undefined; this.sessionDiagnostics = undefined; } if (this.sessionSecurityDiagnostics) { const sessionSecurityDiagnosticsArray = this.getSessionSecurityDiagnosticsArray()!; removeElement(sessionSecurityDiagnosticsArray, this.sessionSecurityDiagnostics.$extensionObject); this.addressSpace.deleteNode(this.sessionSecurityDiagnostics); assert(this._sessionSecurityDiagnostics!.$session === this); this._sessionSecurityDiagnostics!.$session = null; this._sessionSecurityDiagnostics = undefined; this.sessionSecurityDiagnostics = undefined; } if (this.sessionObject) { this.addressSpace.deleteNode(this.sessionObject); this.sessionObject = null; } } /** * * @private */ private _getSubscriptionDiagnosticsArray() { if (!this.addressSpace) { if (doDebug) { console.warn("ServerSession#_getSubscriptionDiagnosticsArray : no addressSpace"); } return null; // no addressSpace } const subscriptionDiagnosticsArray = this.subscriptionDiagnosticsArray; if (!subscriptionDiagnosticsArray) { return null; // no subscriptionDiagnosticsArray } assert(subscriptionDiagnosticsArray.browseName.toString() === "SubscriptionDiagnosticsArray"); return subscriptionDiagnosticsArray; } private assignSubscription(subscription: Subscription) { assert(!subscription.$session); assert(this.nodeId instanceof NodeId); subscription.$session = this; subscription.sessionId = this.nodeId; this._cumulatedSubscriptionCount += 1; // Notify the owner that a new subscription has been created // @event new_subscription // @param {Subscription} subscription this.emit("new_subscription", subscription); // add subscription diagnostics to SubscriptionDiagnosticsArray this._exposeSubscriptionDiagnostics(subscription); subscription.once("terminated", () => { // Notify the owner that a new subscription has been terminated // @event subscription_terminated // @param {Subscription} subscription this.emit("subscription_terminated", subscription); }); } private _deleteSubscriptions() { assert(this.publishEngine); const subscriptions = this.publishEngine.subscriptions; for (const subscription of subscriptions) { this.deleteSubscription(subscription.id); } } }
the_stack
import * as path from "path"; import { assert, Id64Array, Id64String } from "@itwin/core-bentley"; import { BackgroundMapProps, ColorDef, Hilite, RenderMode, ViewFlags, ViewStateProps, } from "@itwin/core-common"; import { RenderSystem, TileAdmin } from "@itwin/core-frontend"; /** Dimensions of the Viewport for a TestConfig. */ export interface ViewSize { readonly width: number; readonly height: number; } /** Selectively overrides individual ViewFlags for a TestConfig. * @note renderMode can be a string "wireframe", "hiddenline", "solidfill", or "smoothshade" (case-insensitive). */ export type ViewFlagProps = Partial<Omit<ViewFlags, "renderMode">> & { renderMode?: string | RenderMode }; /** The types of saved views to include in a TestConfig. Case-insensitive in TestConfigProps; always lower-case in TestConfig. * local and internal mean exactly the same thing - include all persistent views from the iModel, including private ones. * external means to include external saved views from a *_ESV.json file * both means to include both types. */ export type SavedViewType = "both" | "external" | "internal" | "local"; /** The type(s) of tests specified by a TestConfig. * timing means to record and output timing for drawing to the screen. * readPixels means to record and output timing for drawing to an offscreen framebuffer for reading pixel data. * image means to save an image of the screen. * both means to do "timing" and "image". */ export type TestType = "timing" | "readPixels" | "image" | "both"; /** Specifies symbology overrides to apply to elements in a TestConfig. */ export interface ElementOverrideProps { /** The Id of the affected element, or "-default-" to apply to all elements not otherwise overridden. */ id: Id64String | "-default-"; /** The symbology overrides to apply. */ fsa: string; // A stringified FeatureAppearanceProps. Why is all the JSON double-stringified??? } /** JSON representation of a ViewState with some additional data used by external saved views in a *_ESV.json file and by TestConfigProps.viewString. */ export interface ViewStateSpecProps { _name: string; // eslint-disable-line @typescript-eslint/naming-convention _viewStatePropsString: string; // eslint-disable-line @typescript-eslint/naming-convention _overrideElements?: string; // eslint-disable-line @typescript-eslint/naming-convention _selectedElements?: string; // eslint-disable-line @typescript-eslint/naming-convention } /** Parsed in-memory representation of a ViewStateSpecProps. */ export interface ViewStateSpec { name: string; viewProps: ViewStateProps; elementOverrides?: ElementOverrideProps[]; selectedElements?: Id64String | Id64Array; } /** Overrides aspects of the Hilite.Settings used for emphasis or hilite in a TestConfig. */ export interface HiliteProps { visibleRatio?: number; hiddenRatio?: number; silhouette?: Hilite.Silhouette; red?: number; green?: number; blue?: number; } /** Specifies how to apply hypermodeling in a TestConfig. */ export interface HyperModelingProps { /** The Id of the [SectionDrawingLocation]($backend) element from which the section view and 2d section graphics are obtained. */ sectionDrawingLocationId: Id64String; /** If true, the spatial view associated with the section drawing location will be applied before the test is executed. * This essentially overrides the view defined by TestConfig's viewName, extViewName, and viewString properties. However, * the spatial view is applied before other properties like viewFlags, backgroundMap, etc, so those can still override aspects of * the view. * If not true, only the clip and 2d section graphics from the section drawing location are applied to the viewport. */ applySpatialView?: boolean; } /** JSON representation of a TestConfig. */ export interface TestConfigProps { /** The default output path. Not stored in the JSON file but supplied by the backend for the base config. Ignored if outputPath is defined. */ argOutputPath?: string; /** The dimensions of the viewport. * Default: 1000x1000. */ view?: ViewSize; /** The number of frames to draw while recording timings. Timings are averaged over these frames. * Default: 50 */ numRendersToTime?: number; /** The number of frames to draw without recording timings, to prime the system so that recorded timings are more consistent. * Default: 100 */ numRendersToSkip?: number; /** The name of the output .csv file to contain the recorded timing data. * Default: performanceResults.csv */ outputName?: string; /** The directory to contain output like the .csv file containing timing data, saved images, log files, etc. * Default: d:\output\performanceData\ */ outputPath?: string; /** The location of the iModel file(s) used by the test. * Default: "" */ iModelLocation?: string; /** The name of the iModel(s) to test. Can include wildcards. * Default: "*" */ iModelName?: string; /** The name of the iTwin from which to obtain iModels. Currently not supported. * Default: "iModel Testing" */ iModelHubProject?: string; /** The format in which to output the timing data. See DisplayPerfRpcImpl.saveCsv - only "original" is treated specially. * Default: "original". */ csvFormat?: string; /** Substrings to omit from generated file names. See removeOptsFromString. */ filenameOptsToIgnore?: string[] | string; /** The name of the view(s) to test. Can include wildcards. * Default: "*" */ viewName?: string; /** The name of an external saved view to test. Supersedes viewName if defined. */ extViewName?: string; /** The type of test(s) to run. */ testType?: TestType; /** The name (Code value) of a display style to apply to the view. */ displayStyle?: string; /** Overrides for selected ViewFlags to apply to the view. */ viewFlags?: ViewFlagProps; /** Selectively overrides how the background map is drawn. */ backgroundMap?: BackgroundMapProps; /** Selectively overrides options used to initialize the RenderSystem. */ renderOptions?: RenderSystem.Options; /** Selectively overrides options used to initialize the TileAdmin. */ tileProps?: TileAdmin.Props; hilite?: HiliteProps; emphasis?: HiliteProps; /** The type(s) of saved views to include. */ savedViewType?: SavedViewType; /** An object (not a string) describing a non-persistent view. Supersedes viewName if defined. */ viewString?: ViewStateSpecProps; /** Specifies hypermodeling settings applied to the view. */ hyperModeling?: HyperModelingProps; /** Specifies if EXT_disjoint_timer_query extension is used to collect GPU data */ useDisjointTimer?: boolean; /** Describes how to react to an otherwise uncaught exception during a test. * - "terminate" => log the exception and terminate immediately. * - undefined => log the exception and continue to next test. * Logged exceptions will include the string "DPTA_EXCEPTION" for easy grepping. */ onException?: "terminate"; } export const defaultHilite = new Hilite.Settings(); export const defaultEmphasis = new Hilite.Settings(ColorDef.black, 0, 0, Hilite.Silhouette.Thick); export const isWindows = window.navigator.userAgent.toLowerCase().includes("win"); /** Configures how one or more tests are run. A Test belongs to a TestSet and can test multiple iModels and views thereof. * A single base config is supplied by the backend. * Each TestSet can override aspects of that base config. * Each Test within a TestSet receives the TestSet's config and can override aspects of it. * Most properties have the same meanings as those in TestConfigProps. */ export class TestConfig { public readonly view: ViewSize; public readonly numRendersToTime: number; public readonly numRendersToSkip: number; public readonly outputName: string; public readonly outputPath: string; public iModelName: string; public readonly iTwin: string; public viewName: string; public readonly testType: TestType; public readonly csvFormat: string; public readonly renderOptions: RenderSystem.Options; public readonly savedViewType: SavedViewType; public readonly iModelLocation: string; public readonly useDisjointTimer: boolean; public readonly extViewName?: string; public readonly displayStyle?: string; public readonly viewFlags?: ViewFlagProps; public readonly tileProps?: TileAdmin.Props; public readonly hilite?: Hilite.Settings; public readonly emphasis?: Hilite.Settings; /** A string representation of a ViewState, produced from TestConfigProps.viewString. */ public readonly viewStateSpec?: ViewStateSpec; public readonly filenameOptsToIgnore?: string[] | string; public readonly backgroundMap?: BackgroundMapProps; public readonly hyperModeling?: HyperModelingProps; public readonly onException?: "terminate"; /** Construct a new TestConfig with properties initialized by following priority: * As defined by `props`; or * as defined by `prevConfig` if not defined by props; or * to default values if not defined by prevConfig or prevConfig is not supplied. */ public constructor(props: TestConfigProps, prevConfig?: TestConfig) { this.view = props.view ?? prevConfig?.view ?? { width: 1000, height: 1000 }; this.numRendersToTime = props.numRendersToTime ?? prevConfig?.numRendersToTime ?? 100; this.numRendersToSkip = props.numRendersToSkip ?? prevConfig?.numRendersToSkip ?? 50; this.outputName = props.outputName ?? prevConfig?.outputName ?? "performanceResults.csv"; this.outputPath = prevConfig?.outputPath ?? (isWindows ? "D:\\output\\performanceData\\" : "/Users/"); this.iModelLocation = prevConfig?.iModelLocation ?? ""; this.iModelName = props.iModelName ?? prevConfig?.iModelName ?? "*"; this.iTwin = props.iModelHubProject ?? prevConfig?.iTwin ?? "iModel Testing"; this.csvFormat = props.csvFormat ?? prevConfig?.csvFormat ?? "original"; this.viewName = props.viewName ?? prevConfig?.viewName ?? "*"; this.extViewName = props.extViewName; this.testType = props.testType ?? prevConfig?.testType ?? "timing"; this.savedViewType = (props.savedViewType?.toLowerCase() as SavedViewType) ?? prevConfig?.savedViewType ?? "both"; this.renderOptions = prevConfig?.renderOptions ? { ...prevConfig.renderOptions } : { useWebGL2: true, dpiAwareLOD: true }; this.filenameOptsToIgnore = props.filenameOptsToIgnore ?? prevConfig?.filenameOptsToIgnore; this.displayStyle = props.displayStyle ?? prevConfig?.displayStyle; this.hyperModeling = props.hyperModeling ?? prevConfig?.hyperModeling; this.useDisjointTimer = props.useDisjointTimer ?? prevConfig?.useDisjointTimer ?? true; this.onException = props.onException ?? prevConfig?.onException; if (prevConfig) { if (prevConfig.viewStateSpec) { // Don't preserve selected elements or appearance overrides. this.viewStateSpec = { name: prevConfig.viewStateSpec.name, viewProps: prevConfig.viewStateSpec.viewProps }; } this.hilite = prevConfig.hilite; this.emphasis = prevConfig.emphasis; if (prevConfig.backgroundMap) this.backgroundMap = { ...prevConfig.backgroundMap }; if (prevConfig.tileProps) this.tileProps = { ...prevConfig.tileProps }; if (prevConfig.viewFlags) this.viewFlags = { ...prevConfig.viewFlags }; } else if (props.argOutputPath) { this.outputPath = props.argOutputPath; } if (props.iModelLocation) this.iModelLocation = combineFilePaths(props.iModelLocation, this.iModelLocation); if (props.outputPath) this.outputPath = combineFilePaths(props.outputPath, this.outputPath); if (props.viewString) { this.viewStateSpec = { name: props.viewString._name, viewProps: JSON.parse(props.viewString._viewStatePropsString), }; if (props.viewString._overrideElements) this.viewStateSpec.elementOverrides = JSON.parse(props.viewString._overrideElements); if (props.viewString._selectedElements) this.viewStateSpec.selectedElements = JSON.parse(props.viewString._selectedElements); } if (props.renderOptions) { const options = merge(this.renderOptions, props.renderOptions); assert(options !== undefined); this.renderOptions = options; } this.tileProps = merge(this.tileProps, props.tileProps); this.backgroundMap = merge(this.backgroundMap, props.backgroundMap); this.viewFlags = merge(this.viewFlags, props.viewFlags); if (props.hilite) this.hilite = hiliteSettings(this.hilite ?? defaultHilite, props.hilite); if (props.emphasis) this.emphasis = hiliteSettings(this.emphasis ?? defaultEmphasis, props.emphasis); } /** Returns true if IModelApp must be restarted when transitioning from this config to the specified config. */ public requiresRestart(newConfig: TestConfig): boolean { if (!areObjectsEqual(this.renderOptions, newConfig.renderOptions)) return true; if (!this.tileProps || !newConfig.tileProps) return undefined !== this.tileProps || undefined !== newConfig.tileProps; return !areObjectsEqual(this.tileProps, newConfig.tileProps); } } /** Maintains a stack of TestConfigs such that entries pushed on the stack inherit properties from the entry currently on the top of the stack. */ export class TestConfigStack { private readonly _stack: TestConfig[] = []; public constructor(base: TestConfig) { this._stack.push(base); } public get top(): TestConfig { assert(this._stack.length > 0); return this._stack[this._stack.length - 1]; } // Push to the top of the stack and return true if the new config requires restarting IModelApp. public push(props: TestConfigProps): boolean { const config = new TestConfig(props, this.top); const requiresRestart = this.top.requiresRestart(config); this._stack.push(config); return requiresRestart; } public pop(): void { assert(this._stack.length > 1); // never pop the base of the stack. this._stack.pop(); } } /** Override properties of settings with those defined by props. */ function hiliteSettings(settings: Hilite.Settings, props: HiliteProps): Hilite.Settings { const colors = settings.color.colors; const color = ColorDef.from(props?.red ?? colors.r, props?.green ?? colors.g, props?.blue ?? colors.b, 0); return new Hilite.Settings(color, props.visibleRatio ?? settings.visibleRatio, props.hiddenRatio ?? settings.hiddenRatio, props.silhouette ?? settings.silhouette); } /** Merge two objects of type T such that any property defined by second overrides the value supplied for that property by first. * The inputs are not modified - a new object is returned if two objects are supplied. */ function merge<T extends object>(first: T | undefined, second: T | undefined): T | undefined { if (!first) return second; else if (!second) return first; else return { ...first, ...second }; } /** Combine two file paths. e.g., combineFilePaths("images/img.png", "/usr/tmp") returns "/usr/tmp/images/img.png". * If isWindows & additionalPath begins with a drive letter, initialPath is ignored. * If !isWindows & additionalPath begins with "/", initialPath is ignored. */ function combineFilePaths(additionalPath: string, initialPath: string): string { if (initialPath.length === 0 || (isWindows && additionalPath[1] === ":") || (!isWindows && additionalPath[0] === "/")) return additionalPath; return path.join(initialPath, additionalPath); } /** Compare two values for equality, recursing into arrays and object fields. */ function areEqual(a: any, b: any): boolean { if (typeof a !== typeof b) return false; if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) if (!areEqual(a[i], b[i])) return false; return true; } if (typeof a === "object") return areObjectsEqual(a, b as object); return a === b; } /** Compare the fields of each object for equality. */ function areObjectsEqual(a: object, b: object): boolean { if (Object.keys(a).length !== Object.keys(b).length) return false; const ob = b as { [key: string]: any }; for (const [key, value] of Object.entries(a)) if (!areEqual(value, ob[key])) return false; return true; }
the_stack
import React, { useEffect, useState } from 'react' import Grid from '@material-ui/core/Grid' import Button from '@material-ui/core/Button' import Checkbox from '@material-ui/core/Checkbox' import Table from '@material-ui/core/Table' import TableBody from '@material-ui/core/TableBody' import TableContainer from '@material-ui/core/TableContainer' import TableHead from '@material-ui/core/TableHead' import TableRow from '@material-ui/core/TableRow' import TableCell from '@material-ui/core/TableCell' import TableSortLabel from '@material-ui/core/TableSortLabel' import Paper from '@material-ui/core/Paper' import TablePagination from '@material-ui/core/TablePagination' import { useDispatch } from '../../../store' import { useAuthState } from '../../../user/state/AuthState' import { AVATAR_PAGE_LIMIT } from '../../state/AvatarState' import styles from './Avatars.module.scss' import AddToContentPackModal from '../ContentPack/AddToContentPackModal' import { useAvatarState } from '../../state/AvatarState' import AvatarSelectMenu from '../../../user/components/UserMenu/menus/AvatarSelectMenu' import { AuthService } from '../../../user/state/AuthService' import { AvatarService } from '../../state/AvatarService' if (!global.setImmediate) { global.setImmediate = setTimeout as any } interface Props { locationState?: any } const Avatars = (props: Props) => { const adminAvatarState = useAvatarState() const dispatch = useDispatch() const authState = useAuthState() const user = authState.user const adminAvatars = adminAvatarState.avatars.avatars const adminAvatarCount = adminAvatarState.avatars.total const headCell = [ { id: 'sid', numeric: false, disablePadding: true, label: 'ID' }, { id: 'name', numeric: false, disablePadding: false, label: 'Name' }, { id: 'key', numeric: false, disablePadding: false, label: 'Key' }, { id: 'addToContentPack', numeric: false, disablePadding: false, label: 'Add to Content Pack' } ] function descendingComparator<T>(a: T, b: T, orderBy: keyof T) { if (b[orderBy] < a[orderBy]) { return -1 } if (b[orderBy] > a[orderBy]) { return 1 } return 0 } type Order = 'asc' | 'desc' function getComparator<Key extends keyof any>( order: Order, orderBy: Key ): (a: { [key in Key]: number | string }, b: { [key in Key]: number | string }) => number { return order === 'desc' ? (a, b) => descendingComparator(a, b, orderBy) : (a, b) => -descendingComparator(a, b, orderBy) } function stableSort<T>(array: T[], comparator: (a: T, b: T) => number) { const stabilizedThis = array.map((el, index) => [el, index] as [T, number]) stabilizedThis.sort((a, b) => { const order = comparator(a[0], b[0]) if (order !== 0) return order return a[1] - b[1] }) const returned = stabilizedThis.map((el) => el[0]) return returned } interface EnhancedTableProps { object: string numSelected: number onRequestSort: (event: React.MouseEvent<unknown>, property) => void onSelectAllClick: (event: React.ChangeEvent<HTMLInputElement>) => void order: Order orderBy: string rowCount: number } function EnhancedTableHead(props: EnhancedTableProps) { const { object, order, orderBy, onRequestSort } = props const createSortHandler = (property) => (event: React.MouseEvent<unknown>) => { onRequestSort(event, property) } return ( <TableHead className={styles.thead}> <TableRow className={styles.trow}> {headCell.map((headCell) => ( <TableCell className={styles.tcell} key={headCell.id} align="right" padding={headCell.disablePadding ? 'none' : 'normal'} sortDirection={orderBy === headCell.id ? order : false} > <TableSortLabel active={orderBy === headCell.id} direction={orderBy === headCell.id ? order : 'asc'} onClick={createSortHandler(headCell.id)} > {headCell.label} </TableSortLabel> </TableCell> ))} </TableRow> </TableHead> ) } const [order, setOrder] = useState<Order>('asc') const [orderBy, setOrderBy] = useState<any>('name') const [selected, setSelected] = useState<string[]>([]) const [page, setPage] = useState(0) const [rowsPerPage, setRowsPerPage] = useState(AVATAR_PAGE_LIMIT) const [refetch, setRefetch] = useState(false) const [addToContentPackModalOpen, setAddToContentPackModalOpen] = useState(false) const [selectedAvatars, setSelectedAvatars] = useState([]) const [avatarSelectMenuOpen, setAvatarSelectMenuOpen] = useState(false) const [dimensions, setDimensions] = useState({ height: window.innerHeight, width: window.innerWidth }) const handleRequestSort = (event: React.MouseEvent<unknown>, property) => { const isAsc = orderBy === property && order === 'asc' setOrder(isAsc ? 'desc' : 'asc') setOrderBy(property) } const handleSelectAllClick = (event: React.ChangeEvent<HTMLInputElement>) => { if (event.target.checked) { const newSelecteds = adminAvatars.value.map((n) => n.name) setSelected(newSelecteds) return } setSelected([]) } const handlePageChange = (event: unknown, newPage: number) => { const incDec = page < newPage ? 'increment' : 'decrement' AvatarService.fetchAdminAvatars(incDec) setPage(newPage) } const handleRowsPerPageChange = (event: React.ChangeEvent<HTMLInputElement>) => { setRowsPerPage(parseInt(event.target.value, 10)) setPage(0) } const handleCheck = (e: any, row: any) => { const existingAvatarIndex = selectedAvatars.findIndex((avatar) => avatar.id === row.id) if (e.target.checked === true) { if (existingAvatarIndex >= 0) setSelectedAvatars(selectedAvatars.splice(existingAvatarIndex, 1, row)) else setSelectedAvatars(selectedAvatars.concat(row)) } else setSelectedAvatars(selectedAvatars.splice(existingAvatarIndex, 1)) } const fetchTick = () => { setTimeout(() => { setRefetch(true) fetchTick() }, 5000) } const closeAvatarSelectModal = () => { setAvatarSelectMenuOpen(false) } // useEffect(() => { // fetchTick() // }, []) useEffect(() => { if (user?.id.value != null && (adminAvatarState.avatars.updateNeeded.value === true || refetch === true)) { AvatarService.fetchAdminAvatars() } setRefetch(false) }, [authState.user?.id?.value, adminAvatarState.avatars.updateNeeded.value, refetch]) useEffect(() => { window.addEventListener('resize', handleWindowResize) return () => { window.removeEventListener('resize', handleWindowResize) } }, []) const handleWindowResize = () => { setDimensions({ height: window.innerHeight, width: window.innerWidth }) } const uploadAvatarModel = (model: any, thumbnail: any, avatarName?: string, isPublicAvatar?: boolean): any => { AuthService.uploadAvatarModel(model, thumbnail, avatarName, isPublicAvatar) } return ( <div> <Paper className={styles.adminRoot}> <Grid container spacing={3} className={styles.marginBottom}> <Grid item xs={6}> <Button className={styles['open-modal']} type="button" variant="contained" color="primary" onClick={() => setAvatarSelectMenuOpen(true)} > Upload Avatar </Button> </Grid> <Grid item xs={6}> <Button className={styles['open-modal']} type="button" variant="contained" color="primary" onClick={() => setAddToContentPackModalOpen(true)} > {dimensions.width <= 768 ? '+ Pack' : 'Add to Content Pack'} </Button> </Grid> </Grid> <TableContainer className={styles.tableContainer}> <Table stickyHeader aria-labelledby="tableTitle" size={'medium'} aria-label="enhanced table"> <EnhancedTableHead object={'avatars'} numSelected={selected.length} order={order} orderBy={orderBy} onSelectAllClick={handleSelectAllClick} onRequestSort={handleRequestSort} rowCount={adminAvatarCount.value || 0} /> <TableBody> {stableSort(adminAvatars.value, getComparator(order, orderBy)).map((row, index) => { return ( <TableRow hover className={styles.trowHover} style={{ color: 'black !important' }} // onClick={(event) => handleLocationClick(event, row.id.toString())} tabIndex={-1} key={row.id} > <TableCell className={styles.tcell} component="th" id={row.id.toString()} align="right" scope="row" padding="none" > {row.sid} </TableCell> <TableCell className={styles.tcell} align="right"> {row.name} </TableCell> <TableCell className={styles.tcell} align="right"> {row.key} </TableCell> <TableCell className={styles.tcell} align="right"> {user.userRole.value === 'admin' && ( <Checkbox className={styles.checkbox} onChange={(e) => handleCheck(e, row)} name="stereoscopic" color="primary" /> )} </TableCell> </TableRow> ) })} </TableBody> </Table> </TableContainer> <div className={styles.tableFooter}> <TablePagination rowsPerPageOptions={[AVATAR_PAGE_LIMIT]} component="div" count={adminAvatarCount.value} rowsPerPage={rowsPerPage} page={page} onPageChange={handlePageChange} onRowsPerPageChange={handleRowsPerPageChange} className={styles.tablePagination} /> </div> <AddToContentPackModal open={addToContentPackModalOpen} avatars={selectedAvatars} handleClose={() => setAddToContentPackModalOpen(false)} /> {avatarSelectMenuOpen && ( <AvatarSelectMenu changeActiveMenu={() => setAvatarSelectMenuOpen(false)} uploadAvatarModel={uploadAvatarModel} isPublicAvatar={true} /> )} </Paper> </div> ) } export default Avatars
the_stack
import { MomentInput, MomentFormatSpecification, Moment } from 'moment'; export type MomentConstructor1 = (inp?: MomentInput, format?: MomentFormatSpecification, strict?: boolean) => Moment; export type MomentConstructor2 = (inp?: MomentInput, format?: MomentFormatSpecification, language?: string, strict?: boolean) => Moment; export type MomentConstructor = MomentConstructor1 | MomentConstructor2; export type IdType = string | number; export type SubgroupType = IdType; export type DateType = Date | number | string; export type DirectionType = 'from' | 'to'; export type HeightWidthType = IdType; export type TimelineItemType = 'box' | 'point' | 'range' | 'background'; export type TimelineAlignType = 'auto' | 'center' | 'left' | 'right'; export type TimelineTimeAxisScaleType = 'millisecond' | 'second' | 'minute' | 'hour' | 'weekday' | 'day' | 'week' | 'month' | 'year'; export type TimelineEventPropertiesResultWhatType = 'item' | 'background' | 'axis' | 'group-label' | 'custom-time' | 'current-time'; export type TimelineEvents = 'currentTimeTick' | 'click' | 'contextmenu' | 'doubleClick' | 'drop' | 'mouseOver' | 'mouseDown' | 'mouseUp' | 'mouseMove' | 'groupDragged' | 'changed' | 'rangechange' | 'rangechanged' | 'select' | 'itemover' | 'itemout' | 'timechange' | 'timechanged'; export type Graph2dStyleType = 'line' | 'bar' | 'points'; export type Graph2dBarChartAlign = 'left' | 'center' | 'right'; export type Graph2dDrawPointsStyle = 'square' | 'circle'; export type LegendPositionType = 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'; export type ParametrizationInterpolationType = 'centripetal' | 'chordal' | 'uniform' | 'disabled'; export type TopBottomEnumType = 'top' | 'bottom'; export type RightLeftEnumType = 'right' | 'left'; export interface LegendPositionOptions { visible?: boolean | undefined; position?: LegendPositionType | undefined; } export interface LegendOptions { enabled?: boolean | undefined; icons?: boolean | undefined; iconSize?: number | undefined; iconSpacing?: number | undefined; left?: LegendPositionOptions | undefined; right?: LegendPositionOptions | undefined; } export interface DataItem { className?: string | undefined; content: string; end?: DateType | undefined; group?: any; id?: IdType | undefined; start: DateType; style?: string | undefined; subgroup?: SubgroupType | undefined; title?: string | undefined; type?: string | undefined; editable?: boolean | undefined; } export interface PointItem extends DataItem { x: string; y: number; } export interface SubGroupStackOptions { [name: string]: boolean; } export interface DataGroup { className?: string | undefined; content: string; id: IdType; options?: DataGroupOptions | undefined; style?: string | undefined; subgroupOrder?: string | (() => void) | undefined; title?: string | undefined; nestedGroups?: IdType[] | undefined; subgroupStack?: SubGroupStackOptions | boolean | undefined; visible?: boolean | undefined; showNested?: boolean | undefined; } export interface DataGroupOptions { drawPoints?: Graph2dDrawPointsOption | (() => void) | undefined; // TODO excludeFromLegend?: boolean | undefined; interpolation?: boolean | InterpolationOptions | undefined; shaded?: Graph2dShadedOption | undefined; style?: string | undefined; yAxisOrientation?: RightLeftEnumType | undefined; } export interface InterpolationOptions { parametrization: ParametrizationInterpolationType; } export interface TimelineEditableOption { add?: boolean | undefined; remove?: boolean | undefined; updateGroup?: boolean | undefined; updateTime?: boolean | undefined; overrideItems?: boolean | undefined; } export type TimelineFormatLabelsFunction = (date: Date, scale: string, step: number) => string; export interface TimelineFormatLabelsOption { millisecond?: string | undefined; second?: string | undefined; minute?: string | undefined; hour?: string | undefined; weekday?: string | undefined; day?: string | undefined; week?: string | undefined; month?: string | undefined; year?: string | undefined; } export interface TimelineFormatOption { minorLabels?: TimelineFormatLabelsOption | TimelineFormatLabelsFunction | undefined; majorLabels?: TimelineFormatLabelsOption | TimelineFormatLabelsFunction | undefined; } export interface TimelineGroupEditableOption { add?: boolean | undefined; remove?: boolean | undefined; order?: boolean | undefined; } export interface TimelineHiddenDateOption { start: DateType; end: DateType; repeat?: 'daily' | 'weekly' | 'monthly' | 'yearly' | undefined; } export interface TimelineItemsAlwaysDraggableOption { item?: boolean | undefined; range?: boolean | undefined; } export interface TimelineMarginItem { horizontal?: number | undefined; vertical?: number | undefined; } export type TimelineMarginItemType = number | TimelineMarginItem; export interface TimelineMarginOption { axis?: number | undefined; item?: TimelineMarginItemType | undefined; } export interface TimelineOrientationOption { axis?: string | undefined; item?: string | undefined; } export interface TimelineTimeAxisOption { scale?: TimelineTimeAxisScaleType | undefined; step?: number | undefined; } export interface TimelineRollingModeOption { follow?: boolean | undefined; offset?: number | undefined; } export interface TimelineTooltipOption { followMouse?: boolean | undefined; overflowMethod?: 'cap' | 'flip' | undefined; } export type TimelineOptionsConfigureFunction = (option: string, path: string[]) => boolean; export type TimelineOptionsConfigureType = boolean | TimelineOptionsConfigureFunction; export type TimelineOptionsDataAttributesType = boolean | string | string[]; export type TimelineOptionsEditableType = boolean | TimelineEditableOption; export type TimelineOptionsItemCallbackFunction = (item: TimelineItem, callback: (item: TimelineItem | null) => void) => void; export type TimelineOptionsGroupCallbackFunction = (group: TimelineGroup, callback: (group: TimelineGroup | null) => void) => void; export type TimelineOptionsGroupEditableType = boolean | TimelineGroupEditableOption; export type TimelineOptionsGroupOrderType = string | TimelineOptionsComparisonFunction; export type TimelineOptionsGroupOrderSwapFunction = (fromGroup: any, toGroup: any, groups: DataSet<DataGroup>) => void; export type TimelineOptionsHiddenDatesType = TimelineHiddenDateOption | TimelineHiddenDateOption[]; export type TimelineOptionsItemsAlwaysDraggableType = boolean | TimelineItemsAlwaysDraggableOption; export type TimelineOptionsMarginType = number | TimelineMarginOption; export type TimelineOptionsOrientationType = string | TimelineOrientationOption; export type TimelineOptionsSnapFunction = (date: Date, scale: string, step: number) => Date | number; export type TimelineOptionsTemplateFunction = (item?: any, element?: any, data?: any) => string; export type TimelineOptionsComparisonFunction = (a: any, b: any) => number; export interface TimelineOptions { align?: TimelineAlignType | undefined; autoResize?: boolean | undefined; clickToUse?: boolean | undefined; configure?: TimelineOptionsConfigureType | undefined; dataAttributes?: TimelineOptionsDataAttributesType | undefined; editable?: TimelineOptionsEditableType | undefined; end?: DateType | undefined; format?: TimelineFormatOption | undefined; groupEditable?: TimelineOptionsGroupEditableType | undefined; groupOrder?: TimelineOptionsGroupOrderType | undefined; groupOrderSwap?: TimelineOptionsGroupOrderSwapFunction | undefined; groupTemplate?: TimelineOptionsTemplateFunction | undefined; height?: HeightWidthType | undefined; hiddenDates?: TimelineOptionsHiddenDatesType | undefined; horizontalScroll?: boolean | undefined; itemsAlwaysDraggable?: TimelineOptionsItemsAlwaysDraggableType | undefined; locale?: string | undefined; locales?: Locales | undefined; moment?: MomentConstructor | undefined; margin?: TimelineOptionsMarginType | undefined; max?: DateType | undefined; maxHeight?: HeightWidthType | undefined; maxMinorChars?: number | undefined; min?: DateType | undefined; minHeight?: HeightWidthType | undefined; moveable?: boolean | undefined; multiselect?: boolean | undefined; multiselectPerGroup?: boolean | undefined; onAdd?: TimelineOptionsItemCallbackFunction | undefined; onAddGroup?: TimelineOptionsGroupCallbackFunction | undefined; onInitialDrawComplete?: (() => void) | undefined; onUpdate?: TimelineOptionsItemCallbackFunction | undefined; onMove?: TimelineOptionsItemCallbackFunction | undefined; onMoveGroup?: TimelineOptionsGroupCallbackFunction | undefined; onMoving?: TimelineOptionsItemCallbackFunction | undefined; onRemove?: TimelineOptionsItemCallbackFunction | undefined; onRemoveGroup?: TimelineOptionsGroupCallbackFunction | undefined; order?: TimelineOptionsComparisonFunction | undefined; orientation?: TimelineOptionsOrientationType | undefined; rollingMode?: TimelineRollingModeOption | undefined; rtl?: boolean | undefined; selectable?: boolean | undefined; showCurrentTime?: boolean | undefined; showMajorLabels?: boolean | undefined; showMinorLabels?: boolean | undefined; showTooltips?: boolean | undefined; stack?: boolean | undefined; stackSubgroups?: boolean | undefined; snap?: TimelineOptionsSnapFunction | undefined; start?: DateType | undefined; template?: TimelineOptionsTemplateFunction | undefined; visibleFrameTemplate?: TimelineOptionsTemplateFunction | undefined; throttleRedraw?: number | undefined; timeAxis?: TimelineTimeAxisOption | undefined; type?: string | undefined; tooltip?: TimelineTooltipOption | undefined; tooltipOnItemUpdateTime?: boolean | { template(item: any): any } | undefined; verticalScroll?: boolean | undefined; width?: HeightWidthType | undefined; zoomable?: boolean | undefined; zoomKey?: string | undefined; zoomMax?: number | undefined; zoomMin?: number | undefined; } /** * If true (default) or an Object, the range is animated smoothly to the new window. * An object can be provided to specify duration and easing function. * Default duration is 500 ms, and default easing function is 'easeInOutQuad'. */ export type TimelineAnimationType = boolean | AnimationOptions; export interface TimelineAnimationOptions { animation?: TimelineAnimationType | undefined; } export interface TimelineEventPropertiesResult { /** * The id of the clicked group */ group?: number | null | undefined; /** * The id of the clicked item. */ item?: IdType | null | undefined; /** * Absolute horizontal position of the click event. */ pageX: number; /** * Absolute vertical position of the click event. */ pageY: number; /** * Relative horizontal position of the click event. */ x: number; /** * Relative vertical position of the click event. */ y: number; /** * Date of the clicked event. */ time: Date; /** * Date of the clicked event, snapped to a nice value. */ snappedTime: Date; /** * Name of the clicked thing. */ what?: TimelineEventPropertiesResultWhatType | undefined; /** * The original click event. */ event: Event; } /** * Options that can be passed to a DataSet. */ export interface DataSetOptions extends DataSetQueueOptions { /** * The name of the field containing the id of the items. * When data is fetched from a server which uses some specific field to identify items, * this field name can be specified in the DataSet using the option fieldId. * For example CouchDB uses the field "_id" to identify documents. */ fieldId?: string | undefined; /** * An object containing field names as key, and data types as value. * By default, the type of the properties of items are left unchanged. * Item properties can be normalized by specifying a field type. * This is useful for example to automatically convert stringified dates coming * from a server into JavaScript Date objects. * The available data types are listed in section Data Types. */ type?: any; } export interface DataSetQueueOptions { /** * Queue data changes ('add', 'update', 'remove') and flush them at once. * The queue can be flushed manually by calling DataSet.flush(), * or can be flushed after a configured delay or maximum number of entries. * When queue is true, a queue is created with default options. * Options can be specified by providing an object: * delay: number - The queue will be flushed automatically after an inactivity of this delay in milliseconds. Default value is null. * Default value is null. * max: number - When the queue exceeds the given maximum number of entries, the queue is flushed automatically. Default value is Infinity. * Default value is Infinity. */ queue?: any | boolean | undefined; } export class DataSet<T extends DataItem | DataGroup | Node | Edge> { /** * Creates an instance of DataSet. * * @param [options] DataSet options. */ constructor(options: DataSetOptions); /** * Creates an instance of DataSet. * * @param [data] An Array with items. * @param [options] DataSet options. */ constructor(data?: T[], options?: DataSetOptions); /** * The number of items in the DataSet. */ length: number; /** * Add one or multiple items to the DataSet. * Adding an item will fail when there already is an item with the same id. * * @param data data can be a single item or an array with items. * @param [senderId] Optional sender id. * @returns The function returns an array with the ids of the added items. */ add(data: T | T[], senderId?: IdType): IdType[]; /** * Clear all data from the DataSet. * * @param [senderId] Optional sender id. * @returns The function returns an array with the ids of the removed items. */ clear(senderId?: IdType): IdType[]; /** * Find all distinct values of a specified field. * If data items do not contain the specified field are ignored. * * @param field The search term. * @returns Returns an unordered array containing all distinct values. */ distinct(field: string): any[]; /** * Flush queued changes. * Only available when the DataSet is configured with the option queue. */ flush(): void; /** * Execute a callback function for every item in the dataset. * * @param callback The item callback. * @param [options] Optional options */ forEach(callback: (item: T, id: IdType) => void, options?: DataSelectionOptions<T>): void; /** * Get all items from the DataSet. * * @param [options] Optional options. * @returns When no item is found, null is returned when a single item was requested, * and and empty Array is returned in case of multiple id's. */ get(options?: DataSelectionOptions<T>): T[]; /** * Get a single item from the DataSet. * * @param id The item id. * @returns When no item is found, null is returned when a single item was requested, * and and empty Array is returned in case of multiple id's. */ get(id: IdType, options?: DataSelectionOptions<T>): T | null; /** * Get multiple items from the DataSet. * * @param ids Array of item ids. * @param [options] Optional options. * @returns When no item is found, null is returned when a single item was requested, * and and empty Array is returned in case of multiple id's. */ get(ids: IdType[], options?: DataSelectionOptions<T>): T[]; /** * Get the DataSet itself. * In case of a DataView, this function does not return the DataSet * to which the DataView is connected. * * @returns The DataSet itself. */ getDataSet(): DataSet<T>; /** * Get ids of all items or of a filtered set of items. * * @returns ids of all items or of a filtered set of items. */ getIds(options?: DataSelectionOptions<T>): IdType[]; /** * Map every item in the DataSet. * * @param callback The mapping callback. * @param [options] Optional options. * @returns The mapped items. */ map<M>(callback: (item: T, id: IdType) => M, options?: DataSelectionOptions<T>): M[]; /** * Find the item with maximum value of specified field. * * @returns Returns null if no item is found. */ max(field: string): T; /** * Find the item with minimum value of specified field. * * @returns Returns null if no item is found. */ min(field: string): T; /** * Subscribe from an event. * * @param event The event name. * @param callback * a callback function which will be called each time the event occurs. */ on(event: string, callback: (event: string, properties: any, senderId: IdType) => void): void; /** * Unsubscribe to an event. * * @param event The event name. * @param callback * The exact same callback that was used when calling 'on'. */ off(event: string, callback: (event: string, properties: any, senderId: IdType) => void): void; /** * Remove one or more items by id. * * @param id The item id. * @param [senderId] The sender id. * @returns Returns an array with the ids of the removed items. */ remove(id: IdType | IdType[], senderId?: IdType): IdType[]; /** * Set options for the DataSet. */ setOptions(options?: DataSetQueueOptions): void; /** * Update one or multiple existing items. * When an item doesn't exist, it will be created. * * @param data a single item or an array with items. * @returns Returns an array with the ids of the updated items. */ update(data: T | T[], senderId?: IdType): IdType[]; } /** * The DataSet contains functionality to format, filter, and sort data retrieved * via the methods get, getIds, forEach, and map. * These methods can have these options as a parameter. */ export interface DataSelectionOptions<T> { /** * An array with field names, or an object with current field name * and new field name that the field is returned as. * By default, all properties of the items are emitted. * When fields is defined, only the properties whose name is specified * in fields will be included in the returned items. */ fields?: string[] | any | undefined; /** * An object containing field names as key, and data types as value. * By default, the type of the properties of an item are left unchanged. * When a field type is specified, this field in the items will be converted to the specified type. * This can be used for example to convert ISO strings containing a date to a JavaScript Date object, * or convert strings to numbers or vice versa. The available data types are listed in section Data Types. */ type?: any; /** * Items can be filtered on specific properties by providing a filter function. * A filter function is executed for each of the items in the DataSet, * and is called with the item as parameter. * The function must return a boolean. * All items for which the filter function returns true will be emitted. * See section Data Filtering. */ filter?(item: T): boolean; /** * Order the items by a field name or custom sort function. */ order?: string | ((a: T, b: T) => number) | undefined; /** * Determine the type of output of the get function. * Allowed values are 'Array' | 'Object'. * The default returnType is an Array. * The Object type will return a JSON object with the ID's as keys. */ returnType?: "Array" | "Object" | undefined; } export class DataView<T extends DataItem | DataGroup> { length: number; constructor(items: T[]); } export type DataItemCollectionType = DataItem[] | DataSet<DataItem> | DataView<DataItem>; export type DataGroupCollectionType = DataGroup[] | DataSet<DataGroup> | DataView<DataGroup>; export interface TitleOption { text?: string | undefined; style?: string | undefined; } export interface RangeType { min: IdType; max: IdType; } export interface DataAxisSideOption { range?: RangeType | undefined; format?(): string; title?: TitleOption | undefined; } export interface Graph2dBarChartOption { width?: number | undefined; minWidth?: number | undefined; sideBySide?: boolean | undefined; align?: Graph2dBarChartAlign | undefined; } export interface Graph2dDataAxisOption { orientation?: TimelineOptionsOrientationType | undefined; showMinorLabels?: boolean | undefined; showMajorLabels?: boolean | undefined; majorLinesOffset?: number | undefined; minorLinesOffset?: number | undefined; labelOffsetX?: number | undefined; labelOffsetY?: number | undefined; iconWidth?: number | undefined; width?: string | undefined; icons?: boolean | undefined; visible?: boolean | undefined; alignZeros?: boolean | undefined; left?: DataAxisSideOption | undefined; right?: DataAxisSideOption | undefined; } export interface Graph2dDrawPointsOption { enabled?: boolean | undefined; onRender?(): boolean; // TODO size?: number | undefined; style: Graph2dDrawPointsStyle; } export interface Graph2dShadedOption { orientation?: TopBottomEnumType | undefined; groupid?: IdType | undefined; } export type Graph2dOptionBarChart = number | Graph2dBarChartOption; export type Graph2dOptionDataAxis = boolean | Graph2dDataAxisOption; export type Graph2dOptionDrawPoints = boolean | Graph2dDrawPointsOption; export type Graph2dLegendOption = boolean | LegendOptions; export interface Graph2dOptions { autoResize?: boolean | undefined; barChart?: Graph2dOptionBarChart | undefined; clickToUse?: boolean | undefined; configure?: TimelineOptionsConfigureType | undefined; dataAxis?: Graph2dOptionDataAxis | undefined; defaultGroup?: string | undefined; drawPoints?: Graph2dOptionDrawPoints | undefined; end?: DateType | undefined; format?: any; // TODO graphHeight?: HeightWidthType | undefined; height?: HeightWidthType | undefined; hiddenDates?: any; // TODO legend?: Graph2dLegendOption | undefined; locale?: string | undefined; locales?: Locales | undefined; moment?: MomentConstructor | undefined; max?: DateType | undefined; maxHeight?: HeightWidthType | undefined; maxMinorChars?: number | undefined; min?: DateType | undefined; minHeight?: HeightWidthType | undefined; moveable?: boolean | undefined; multiselect?: boolean | undefined; orientation?: string | undefined; sampling?: boolean | undefined; showCurrentTime?: boolean | undefined; showMajorLabels?: boolean | undefined; showMinorLabels?: boolean | undefined; sort?: boolean | undefined; stack?: boolean | undefined; start?: DateType | undefined; style?: Graph2dStyleType | undefined; throttleRedraw?: number | undefined; timeAxis?: TimelineTimeAxisOption | undefined; width?: HeightWidthType | undefined; yAxisOrientation?: RightLeftEnumType | undefined; zoomable?: boolean | undefined; zoomKey?: string | undefined; zoomMax?: number | undefined; zoomMin?: number | undefined; zIndex?: number | undefined; } export class Graph2d { constructor( container: HTMLElement, items: DataItemCollectionType, groups: DataGroupCollectionType, options?: Graph2dOptions ); constructor( container: HTMLElement, items: DataItemCollectionType, options?: Graph2dOptions ); addCustomTime(time: DateType, id?: IdType): IdType; destroy(): void; fit(options?: TimelineAnimationOptions): void; focus(ids: IdType | IdType[], options?: TimelineAnimationOptions): void; getCurrentTime(): Date; getCustomTime(id?: IdType): Date; getEventProperties(event: Event): TimelineEventPropertiesResult; getItemRange(): any; // TODO getSelection(): IdType[]; getVisibleItems(): IdType[]; getWindow(): { start: Date, end: Date }; moveTo(time: DateType, options?: TimelineAnimationOptions): void; on(event: TimelineEvents, callback: () => void): void; off(event: TimelineEvents, callback: () => void): void; redraw(): void; removeCustomTime(id: IdType): void; setCurrentTime(time: DateType): void; setCustomTime(time: DateType, id?: IdType): void; setCustomTimeTitle(title: string, id?: IdType): void; setData(data: { groups?: DataGroupCollectionType | undefined; items?: DataItemCollectionType | undefined }): void; setGroups(groups?: DataGroupCollectionType): void; setItems(items: DataItemCollectionType): void; setOptions(options: TimelineOptions): void; setSelection(ids: IdType | IdType[]): void; setWindow(start: DateType, end: DateType, options?: TimelineAnimationOptions): void; } export interface Graph2d { setGroups(groups?: TimelineGroup[]): void; setItems(items?: TimelineItem[]): void; getLegend(): TimelineWindow; getWindow(): TimelineWindow; setWindow(start: any, date: any): void; focus(selection: any): void; on(event?: string, callback?: (properties: any) => void): void; } export class Timeline { constructor( container: HTMLElement, items: DataItemCollectionType, groups: DataGroupCollectionType, options?: TimelineOptions ); constructor( container: HTMLElement, items: DataItemCollectionType, options?: TimelineOptions ); /** * Add new vertical bar representing a custom time that can be dragged by the user. * Parameter time can be a Date, Number, or String, and is new Date() by default. * Parameter id can be Number or String and is undefined by default. * The id is added as CSS class name of the custom time bar, allowing to style multiple time bars differently. * The method returns id of the created bar. */ addCustomTime(time: DateType, id?: IdType): IdType; /** * Destroy the Timeline. The timeline is removed from memory. all DOM elements and event listeners are cleaned up. */ destroy(): void; /** * Adjust the visible window such that it fits all items. See also focus(id). */ fit(options?: TimelineAnimationOptions): void; /** * Adjust the visible window such that the selected item (or multiple items) are centered on screen. See also function fit() */ focus(ids: IdType | IdType[], options?: TimelineAnimationOptions): void; /** * Get the current time. Only applicable when option showCurrentTime is true. */ getCurrentTime(): Date; /** * Retrieve the custom time from the custom time bar with given id. * @param id Id is undefined by default. */ getCustomTime(id?: IdType): Date; getEventProperties(event: Event): TimelineEventPropertiesResult; /** * Get the range of all the items as an object containing min date and max date */ getItemRange(): { min: Date, max: Date }; /** * Get an array with the ids of the currently selected items */ getSelection(): IdType[]; /** * Get an array with the ids of the currently visible items. */ getVisibleItems(): IdType[]; /** * Get the current visible window. */ getWindow(): TimelineWindow; /** * Move the window such that given time is centered on screen. */ moveTo(time: DateType, options?: TimelineAnimationOptions, callback?: (properties?: any) => void): void; /** * Create an event listener. The callback function is invoked every time the event is triggered. */ on(event: TimelineEvents, callback?: (properties?: any) => void): void; /** * Remove an event listener created before via function on(event[, callback]). */ off(event: TimelineEvents, callback?: (properties?: any) => void): void; /** * Force a redraw of the Timeline. The size of all items will be recalculated. * Can be useful to manually redraw when option autoResize=false and the window has been resized, or when the items CSS has been changed. */ redraw(): void; /** * Remove vertical bars previously added to the timeline via addCustomTime method. * @param id ID of the custom vertical bar returned by addCustomTime method. */ removeCustomTime(id: IdType): void; /** * Set a current time. This can be used for example to ensure that a client's time is synchronized with a shared server time. * Only applicable when option showCurrentTime is true. */ setCurrentTime(time: DateType): void; /** * Adjust the time of a custom time bar. * @param time The time the custom time bar should point to * @param id Id of the custom time bar, and is undefined by default. */ setCustomTime(time: DateType, id?: IdType): void; /** * Adjust the title attribute of a custom time bar. * @param title The title shown when hover over time bar * @param id Id of the custom time bar, and is undefined by default. */ setCustomTimeTitle(title: string, id?: IdType): void; /** * Set both groups and items at once. Both properties are optional. * This is a convenience method for individually calling both setItems(items) and setGroups(groups). * Both items and groups can be an Array with Objects, a DataSet (offering 2 way data binding), or a DataView (offering 1 way data binding). */ setData(data: { groups?: DataGroupCollectionType | undefined; items?: DataItemCollectionType | undefined }): void; /** * Set a data set with groups for the Timeline. */ setGroups(groups?: DataGroupCollectionType): void; /** * Set a data set with items for the Timeline. */ setItems(items: DataItemCollectionType): void; /** * Set or update options. It is possible to change any option of the timeline at any time. * You can for example switch orientation on the fly. */ setOptions(options: TimelineOptions): void; /** * Select one or multiple items by their id. The currently selected items will be unselected. * To unselect all selected items, call `setSelection([])`. */ setSelection(ids: IdType | IdType[], options?: { focus: boolean, animation: TimelineAnimationOptions }): void; /** * Set the current visible window. * @param start If the parameter value of start is null, the parameter will be left unchanged. * @param end If the parameter value of end is null, the parameter will be left unchanged. * @param options Timeline animation options. See {@link TimelineAnimationOptions} * @param callback The callback function */ setWindow(start: DateType, end: DateType, options?: TimelineAnimationOptions, callback?: () => void): void; /** * Toggle rollingMode. */ toggleRollingMode(): void; /** * Zoom in the current visible window. * @param percentage A number and must be between 0 and 1. If null, the window will be left unchanged. * @param options Timeline animation options. See {@link TimelineAnimationOptions} * @param callback The callback function */ zoomIn(percentage: number, options?: TimelineAnimationOptions, callback?: () => void): void; /** * Zoom out the current visible window. * @param percentage A number and must be between 0 and 1. If null, the window will be left unchanged. * @param options Timeline animation options. See {@link TimelineAnimationOptions} * @param callback The callback function */ zoomOut(percentage: number, options?: TimelineAnimationOptions, callback?: () => void): void; } export interface TimelineStatic { new(id: HTMLElement, data: any, options?: any): vis.Timeline; } export interface Timeline { setGroups(groups?: TimelineGroup[]): void; setItems(items?: TimelineItem[]): void; getWindow(): TimelineWindow; setWindow(start: any, date: any): void; focus(selection: any): void; on(event?: string, callback?: (properties: any) => void): void; off(event: string, callback?: (properties?: any) => void): void; } export interface TimelineWindow { start: Date; end: Date; } export interface TimelineItemEditableOption { remove?: boolean | undefined; updateGroup?: boolean | undefined; updateTime?: boolean | undefined; } export type TimelineItemEditableType = boolean | TimelineItemEditableOption; export interface TimelineItem { className?: string | undefined; align?: TimelineAlignType | undefined; content: string; end?: DateType | undefined; group?: IdType | undefined; id: IdType; start: DateType; style?: string | undefined; subgroup?: IdType | undefined; title?: string | undefined; type?: TimelineItemType | undefined; editable?: TimelineItemEditableType | undefined; } export interface TimelineGroup { className?: string | undefined; content: string | HTMLElement; id: IdType; style?: string | undefined; order?: number | undefined; subgroupOrder?: TimelineOptionsGroupOrderType | undefined; title?: string | undefined; visible?: boolean | undefined; nestedGroups?: IdType[] | undefined; showNested?: boolean | undefined; } export interface VisSelectProperties { items: number[]; } export type NetworkEvents = 'click' | 'doubleClick' | 'oncontext' | 'hold' | 'release' | 'select' | 'selectNode' | 'selectEdge' | 'deselectNode' | 'deselectEdge' | 'dragStart' | 'dragging' | 'dragEnd' | 'controlNodeDragging' | 'controlNodeDragEnd' | 'hoverNode' | 'blurNode' | 'hoverEdge' | 'blurEdge' | 'zoom' | 'showPopup' | 'hidePopup' | 'startStabilizing' | 'stabilizationProgress' | 'stabilizationIterationsDone' | 'stabilized' | 'resize' | 'initRedraw' | 'beforeDrawing' | 'afterDrawing' | 'animationFinished' | 'configChange'; /** * Network is a visualization to display networks and networks consisting of nodes and edges. * The visualization is easy to use and supports custom shapes, styles, colors, sizes, images, and more. * The network visualization works smooth on any modern browser for up to a few thousand nodes and edges. * To handle a larger amount of nodes, Network has clustering support. Network uses HTML canvas for rendering. */ export class Network { /** * Creates an instance of Network. * * @param container the HTML element representing the network container * @param data network data * @param [options] optional network options */ constructor(container: HTMLElement, data: Data, options?: Options); /** * Remove the network from the DOM and remove all Hammer bindings and references. */ destroy(): void; /** * Override all the data in the network. * If stabilization is enabled in the physics module, * the network will stabilize again. * This method is also performed when first initializing the network. * * @param data network data */ setData(data: Data): void; /** * Set the options. * All available options can be found in the modules above. * Each module requires it's own container with the module name to contain its options. * * @param options network options */ setOptions(options: Options): void; /** * Set an event listener. * Depending on the type of event you get different parameters for the callback function. * * @param eventName the name of the event, f.e. 'click' * @param callback the callback function that will be raised */ on(eventName: NetworkEvents, callback: (params?: any) => void): void; /** * Remove an event listener. * The function you supply has to be the exact same as the one you used in the on function. * If no function is supplied, all listeners will be removed. * * @param eventName the name of the event, f.e. 'click' * @param [callback] the exact same callback function that was used when calling 'on' */ off(eventName: NetworkEvents, callback?: (params?: any) => void): void; /** * Set an event listener only once. * After it has taken place, the event listener will be removed. * Depending on the type of event you get different parameters for the callback function. * * @param eventName the name of the event, f.e. 'click' * @param callback the callback function that will be raised once */ once(eventName: NetworkEvents, callback: (params?: any) => void): void; /** * This function converts canvas coordinates to coordinates on the DOM. * Input and output are in the form of {x:Number, y:Number} (IPosition interface). * The DOM values are relative to the network container. * * @param position the canvas coordinates * @returns the DOM coordinates */ canvasToDOM(position: Position): Position; /** * This function converts DOM coordinates to coordinates on the canvas. * Input and output are in the form of {x:Number,y:Number} (IPosition interface). * The DOM values are relative to the network container. * * @param position the DOM coordinates * @returns the canvas coordinates */ DOMtoCanvas(position: Position): Position; /** * Redraw the network. */ redraw(): void; /** * Set the size of the canvas. * This is automatically done on a window resize. * * @param width width in a common format, f.e. '100px' * @param height height in a common format, f.e. '100px' */ setSize(width: string, height: string): void; /** * The joinCondition function is presented with all nodes. */ cluster(options?: ClusterOptions): void; /** * This method looks at the provided node and makes a cluster of it and all it's connected nodes. * The behaviour can be customized by proving the options object. * All options of this object are explained below. * The joinCondition is only presented with the connected nodes. * * @param nodeId the id of the node * @param [options] the cluster options */ clusterByConnection(nodeId: string, options?: ClusterOptions): void; /** * This method checks all nodes in the network and those with a equal or higher * amount of edges than specified with the hubsize qualify. * If a hubsize is not defined, the hubsize will be determined as the average * value plus two standard deviations. * For all qualifying nodes, clusterByConnection is performed on each of them. * The options object is described for clusterByConnection and does the same here. * * @param [hubsize] optional hubsize * @param [options] optional cluster options */ clusterByHubsize(hubsize?: number, options?: ClusterOptions): void; /** * This method will cluster all nodes with 1 edge with their respective connected node. * * @param [options] optional cluster options */ clusterOutliers(options?: ClusterOptions): void; /** * Nodes can be in clusters. * Clusters can also be in clusters. * This function returns an array of nodeIds showing where the node is. * * Example: * cluster 'A' contains cluster 'B', cluster 'B' contains cluster 'C', * cluster 'C' contains node 'fred'. * * network.clustering.findNode('fred') will return ['A','B','C','fred']. * * @param nodeId the node id. * @returns an array of nodeIds showing where the node is */ findNode(nodeId: IdType): IdType[]; /** * Similar to findNode in that it returns all the edge ids that were * created from the provided edge during clustering. * * @param baseEdgeId the base edge id * @returns an array of edgeIds */ getClusteredEdges(baseEdgeId: IdType): IdType[]; /** * When a clusteredEdgeId is available, this method will return the original * baseEdgeId provided in data.edges ie. * After clustering the 'SelectEdge' event is fired but provides only the clustered edge. * This method can then be used to return the baseEdgeId. */ getBaseEdge(clusteredEdgeId: IdType): IdType; /** * For the given clusteredEdgeId, this method will return all the original * base edge id's provided in data.edges. * For a non-clustered (i.e. 'base') edge, clusteredEdgeId is returned. * Only the base edge id's are returned. * All clustered edges id's under clusteredEdgeId are skipped, * but scanned recursively to return their base id's. */ getBaseEdges(clusteredEdgeId: IdType): IdType[]; /** * Visible edges between clustered nodes are not the same edge as the ones provided * in data.edges passed on network creation. With each layer of clustering, copies of * the edges between clusters are created and the previous edges are hidden, * until the cluster is opened. This method takes an edgeId (ie. a base edgeId from data.edges) * and applys the options to it and any edges that were created from it while clustering. */ updateEdge(startEdgeId: IdType, options?: EdgeOptions): void; /** * Clustered Nodes when created are not contained in the original data.nodes * passed on network creation. This method updates the cluster node. */ updateClusteredNode(clusteredNodeId: IdType, options?: NodeOptions): void; /** * Returns true if the node whose ID has been supplied is a cluster. * * @param nodeId the node id. */ isCluster(nodeId: IdType): boolean; /** * Returns an array of all nodeIds of the nodes that * would be released if you open the cluster. * * @param clusterNodeId the id of the cluster node */ getNodesInCluster(clusterNodeId: IdType): IdType[]; /** * Opens the cluster, releases the contained nodes and edges, * removing the cluster node and cluster edges. * The options object is optional and currently supports one option, * releaseFunction, which is a function that can be used to manually * position the nodes after the cluster is opened. * * @param nodeId the node id * @param [options] optional open cluster options */ openCluster(nodeId: IdType, options?: OpenClusterOptions): void; /** * If you like the layout of your network * and would like it to start in the same way next time, * ask for the seed using this method and put it in the layout.randomSeed option. * * @returns the current seed of the network. */ getSeed(): number; /** * Programatically enable the edit mode. * Similar effect to pressing the edit button. */ enableEditMode(): void; /** * Programatically disable the edit mode. * Similar effect to pressing the close icon (small cross in the corner of the toolbar). */ disableEditMode(): void; /** * Go into addNode mode. Having edit mode or manipulation enabled is not required. * To get out of this mode, call disableEditMode(). * The callback functions defined in handlerFunctions still apply. * To use these methods without having the manipulation GUI, make sure you set enabled to false. */ addNodeMode(): void; /** * Edit the selected node. * The explaination from addNodeMode applies here as well. */ editNode(): void; /** * Go into addEdge mode. * The explaination from addNodeMode applies here as well. */ addEdgeMode(): void; /** * Go into editEdge mode. * The explaination from addNodeMode applies here as well. */ editEdgeMode(): void; /** * Delete selected. * Having edit mode or manipulation enabled is not required. */ deleteSelected(): void; /** * Returns the x y positions in canvas space of the nodes with the supplied nodeIds as an object. * * Alternative inputs are a String containing a nodeId or nothing. * When a String is supplied, the position of the node corresponding to the ID is returned. * When nothing is supplied, the positions of all nodes are returned. */ getPositions(nodeIds?: IdType[]): { [nodeId: string]: Position }; getPositions(nodeId: IdType): Position; /** * When using the vis.DataSet to load your nodes into the network, * this method will put the X and Y positions of all nodes into that dataset. * If you're loading your nodes from a database and have this dynamically coupled with the DataSet, * you can use this to stablize your network once, then save the positions in that database * through the DataSet so the next time you load the nodes, stabilization will be near instantaneous. * * If the nodes are still moving and you're using dynamic smooth edges (which is on by default), * you can use the option stabilization.onlyDynamicEdges in the physics module to improve initialization time. * * This method does not support clustering. * At the moment it is not possible to cache positions when using clusters since * they cannot be correctly initialized from just the positions. */ storePositions(): void; /** * You can use this to programatically move a node. * The supplied x and y positions have to be in canvas space! * * @param nodeId the node that will be moved * @param x new canvas space x position * @param y new canvas space y position */ moveNode(nodeId: IdType, x: number, y: number): void; /** * Returns a bounding box for the node including label. * */ getBoundingBox(nodeId: IdType): BoundingBox; /** * Returns an array of nodeIds of the all the nodes that are directly connected to this node. * If you supply an edgeId, vis will first match the id to nodes. * If no match is found, it will search in the edgelist and return an array: [fromId, toId]. * * @param nodeOrEdgeId a node or edge id */ getConnectedNodes(nodeOrEdgeId: IdType, direction?: DirectionType): IdType[] | Array<{ fromId: IdType, toId: IdType }>; /** * Returns an array of edgeIds of the edges connected to this node. * * @param nodeId the node id */ getConnectedEdges(nodeId: IdType): IdType[]; /** * Start the physics simulation. * This is normally done whenever needed and is only really useful * if you stop the simulation yourself and wish to continue it afterwards. */ startSimulation(): void; /** * This stops the physics simulation and triggers a stabilized event. * Tt can be restarted by dragging a node, * altering the dataset or calling startSimulation(). */ stopSimulation(): void; /** * You can manually call stabilize at any time. * All the stabilization options above are used. * You can optionally supply the number of iterations it should do. * * @param [iterations] the number of iterations it should do */ stabilize(iterations?: number): void; /** * Returns an object with selected nodes and edges ids. * */ getSelection(): { nodes: IdType[], edges: IdType[] }; /** * Returns an array of selected node ids like so: * [nodeId1, nodeId2, ..]. * */ getSelectedNodes(): IdType[]; /** * Returns an array of selected edge ids like so: * [edgeId1, edgeId2, ..]. * */ getSelectedEdges(): IdType[]; /** * Returns a nodeId or undefined. * The DOM positions are expected to be in pixels from the top left corner of the canvas. * */ getNodeAt(position: Position): IdType; /** * Returns a edgeId or undefined. * The DOM positions are expected to be in pixels from the top left corner of the canvas. * */ getEdgeAt(position: Position): IdType; /** * Selects the nodes corresponding to the id's in the input array. * If highlightEdges is true or undefined, the neighbouring edges will also be selected. * This method unselects all other objects before selecting its own objects. Does not fire events. * */ selectNodes(nodeIds: IdType[], highlightEdges?: boolean): void; /** * Selects the edges corresponding to the id's in the input array. * This method unselects all other objects before selecting its own objects. * Does not fire events. * */ selectEdges(edgeIds: IdType[]): void; /** * Sets the selection. * You can also pass only nodes or edges in selection object. * */ setSelection(selection: { nodes: IdType[], edges: IdType[] }, options?: SelectionOptions): void; /** * Unselect all objects. * Does not fire events. */ unselectAll(): void; /** * Returns the current scale of the network. * 1.0 is comparible to 100%, 0 is zoomed out infinitely. * * @returns the current scale of the network */ getScale(): number; /** * Returns the current central focus point of the view in the form: { x: {Number}, y: {Number} } * * @returns the view position; */ getViewPosition(): Position; /** * Zooms out so all nodes fit on the canvas. * * @param [options] All options are optional for the fit method */ fit(options?: FitOptions): void; /** * You can focus on a node with this function. * What that means is the view will lock onto that node, if it is moving, the view will also move accordingly. * If the view is dragged by the user, the focus is broken. You can supply options to customize the effect. * */ focus(nodeId: IdType, options?: FocusOptions): void; /** * You can animate or move the camera using the moveTo method. * */ moveTo(options: MoveToOptions): void; /** * Programatically release the focussed node. */ releaseNode(): void; /** * If you use the configurator, you can call this method to get an options object that contains * all differences from the default options caused by users interacting with the configurator. * */ getOptionsFromConfigurator(): any; } /** * Options interface for focus function. */ export interface FocusOptions extends ViewPortOptions { /** * Locked denotes whether or not the view remains locked to * the node once the zoom-in animation is finished. * Default value is true. */ locked?: boolean | undefined; } /** * Base options interface for some viewport functions. */ export interface ViewPortOptions { /** * The scale is the target zoomlevel. * Default value is 1.0. */ scale?: number | undefined; /** * The offset (in DOM units) is how many pixels from the center the view is focussed. * Default value is {x:0,y:0} */ offset?: Position | undefined; /** * For animation you can either use a Boolean to use it with the default options or * disable it or you can define the duration (in milliseconds) and easing function manually. */ animation?: AnimationOptions | boolean | undefined; } /** * You will have to define at least a scale, position or offset. * Otherwise, there is nothing to move to. */ export interface MoveToOptions extends ViewPortOptions { /** * The position (in canvas units!) is the position of the central focus point of the camera. */ position?: Position | undefined; } /** * Animation options interface. */ export interface AnimationOptions { /** * The duration (in milliseconds). */ duration: number; /** * The easing function. * * Available are: * linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, * easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, * easeInQuint, easeOutQuint, easeInOutQuint. */ easingFunction: EasingFunction; } export type EasingFunction = 'linear' | 'easeInQuad' | 'easeOutQuad' | 'easeInOutQuad' | 'easeInCubic' | 'easeOutCubic' | 'easeInOutCubic' | 'easeInQuart' | 'easeOutQuart' | 'easeInOutQuart' | 'easeInQuint' | 'easeOutQuint' | 'easeInOutQuint'; /** * Optional options for the fit method. */ export interface FitOptions { /** * The nodes can be used to zoom to fit only specific nodes in the view. */ nodes?: string[] | undefined; /** * For animation you can either use a Boolean to use it with the default options or * disable it or you can define the duration (in milliseconds) and easing function manually. */ animation: TimelineAnimationType; } export interface SelectionOptions { unselectAll?: boolean | undefined; highlightEdges?: boolean | undefined; } /** * These values are in canvas space. */ export interface BoundingBox { top: number; left: number; right: number; bottom: number; } /** * Cluster methods options interface. */ export interface ClusterOptions { /** * Optional for all but the cluster method. * The cluster module loops over all nodes that are selected to be in the cluster * and calls this function with their data as argument. If this function returns true, * this node will be added to the cluster. You have access to all options (including the default) * as well as any custom fields you may have added to the node to determine whether or not to include it in the cluster. */ joinCondition?(nodeOptions: any): boolean; /** * Optional. * Before creating the new cluster node, this (optional) function will be called with the properties * supplied by you (clusterNodeProperties), all contained nodes and all contained edges. * You can use this to update the properties of the cluster based on which items it contains. * The function should return the properties to create the cluster node. */ processProperties?(clusterOptions: any, childNodesOptions: any[], childEdgesOptions: any[]): any; /** * Optional. * This is an object containing the options for the cluster node. * All options described in the nodes module are allowed. * This allows you to style your cluster node any way you want. * This is also the style object that is provided in the processProperties function for fine tuning. * If undefined, default node options will be used. */ clusterNodeProperties?: NodeOptions | undefined; /** * Optional. * This is an object containing the options for the edges connected to the cluster. * All options described in the edges module are allowed. * Using this, you can style the edges connecting to the cluster any way you want. * If none are provided, the options from the edges that are replaced are used. * If undefined, default edge options will be used. */ clusterEdgeProperties?: EdgeOptions | undefined; } /** * Options for the openCluster function of Network. */ export interface OpenClusterOptions { /** * A function that can be used to manually position the nodes after the cluster is opened. * The containedNodesPositions contain the positions of the nodes in the cluster at the * moment they were clustered. This function is expected to return the newPositions, * which can be the containedNodesPositions (altered) or a new object. * This has to be an object with keys equal to the nodeIds that exist in the * containedNodesPositions and an {x:x,y:y} position object. * * For all nodeIds not listed in this returned object, * we will position them at the location of the cluster. * This is also the default behaviour when no releaseFunction is defined. */ releaseFunction( clusterPosition: Position, containedNodesPositions: { [nodeId: string]: Position }): { [nodeId: string]: Position }; } export interface Position { x: number; y: number; } export interface Properties { nodes: string[]; edges: string[]; event: string[]; pointer: { DOM: Position; canvas: Position; }; previousSelection?: { nodes: string[]; edges: string[]; } | undefined; } export interface Callback { callback?(params?: any): void; } export interface Data { nodes?: Node[] | DataSet<Node> | undefined; edges?: Edge[] | DataSet<Edge> | undefined; } export interface Node extends NodeOptions { id?: IdType | undefined; } export interface Edge extends EdgeOptions { from?: IdType | undefined; to?: IdType | undefined; id?: IdType | undefined; } export interface Locales { [language: string]: LocaleMessages | undefined; en?: LocaleMessages | undefined; cn?: LocaleMessages | undefined; de?: LocaleMessages | undefined; es?: LocaleMessages | undefined; it?: LocaleMessages | undefined; nl?: LocaleMessages | undefined; 'pt-br'?: LocaleMessages | undefined; ru?: LocaleMessages | undefined; } export interface LocaleMessages { edit: string; del: string; back: string; addNode: string; addEdge: string; editNode: string; editEdge: string; addDescription: string; edgeDescription: string; editEdgeDescription: string; createEdgeError: string; deleteClusterError: string; editClusterError: string; } export interface Options { autoResize?: boolean | undefined; width?: string | undefined; height?: string | undefined; locale?: string | undefined; locales?: Locales | undefined; clickToUse?: boolean | undefined; configure?: NetworkConfigure | undefined; edges?: EdgeOptions | undefined; nodes?: NodeOptions | undefined; groups?: any; layout?: any; // http://visjs.org/docs/network/layout.html interaction?: any; // visjs.org/docs/network/interaction.html?keywords=edges manipulation?: any; // http://visjs.org/docs/network/manipulation.html# physics?: any; // http://visjs.org/docs/network/physics.html# } export interface Image { unselected?: string | undefined; selected?: string | undefined; } export interface NetworkConfigure { enabled?: boolean | undefined; filter?: string | string[] | boolean | undefined; // please note, filter could be also a function. This case is not represented here container?: any; showButton?: boolean | undefined; } export interface Color { border?: string | undefined; background?: string | undefined; highlight?: string | { border?: string | undefined; background?: string | undefined; } | undefined; hover?: string | { border?: string | undefined; background?: string | undefined; } | undefined; } export interface NodeOptions { borderWidth?: number | undefined; borderWidthSelected?: number | undefined; brokenImage?: string | undefined; color?: string | Color | undefined; fixed?: boolean | { x?: boolean | undefined, y?: boolean | undefined, } | undefined; font?: string | Font | undefined; group?: string | undefined; hidden?: boolean | undefined; icon?: { face?: string | undefined, code?: string | undefined, size?: number | undefined, // 50, color?: string | undefined, } | undefined; image?: string | Image | undefined; label?: string | undefined; labelHighlightBold?: boolean | undefined; level?: number | undefined; margin?: { top?: number | undefined; right?: number | undefined; bottom?: number | undefined; left?: number | undefined; } | undefined; mass?: number | undefined; physics?: boolean | undefined; scaling?: OptionsScaling | undefined; shadow?: boolean | OptionsShadow | undefined; shape?: string | undefined; shapeProperties?: { borderDashes?: boolean | number[] | undefined, // only for borders borderRadius?: number | undefined, // only for box shape interpolation?: boolean | undefined, // only for image and circularImage shapes useImageSize?: boolean | undefined, // only for image and circularImage shapes useBorderWithImage?: boolean | undefined // only for image shape } | undefined; size?: number | undefined; title?: string | undefined; value?: number | undefined; /** * If false, no widthConstraint is applied. If a number is specified, the minimum and maximum widths of the node are set to the value. * The node's label's lines will be broken on spaces to stay below the maximum and the node's width * will be set to the minimum if less than the value. */ widthConstraint?: number | boolean | { minimum?: number | undefined, maximum?: number | undefined } | undefined; x?: number | undefined; y?: number | undefined; } export interface EdgeOptions { arrows?: string | { to?: boolean | ArrowHead | undefined middle?: boolean | ArrowHead | undefined from?: boolean | ArrowHead | undefined } | undefined; endPointOffset?: { from?: number | undefined, to?: number | undefined } | undefined; arrowStrikethrough?: boolean | undefined; chosen?: boolean | { edge?: boolean | undefined, // please note, chosen.edge could be also a function. This case is not represented here label?: boolean | undefined, // please note, chosen.label could be also a function. This case is not represented here } | undefined; color?: string | { color?: string | undefined, highlight?: string | undefined, hover?: string | undefined, inherit?: boolean | string | undefined, opacity?: number | undefined, } | undefined; dashes?: boolean | number[] | undefined; font?: string | Font | undefined; hidden?: boolean | undefined; hoverWidth?: number | undefined; // please note, hoverWidth could be also a function. This case is not represented here label?: string | undefined; labelHighlightBold?: boolean | undefined; length?: number | undefined; physics?: boolean | undefined; scaling?: OptionsScaling | undefined; selectionWidth?: number | undefined; // please note, selectionWidth could be also a function. This case is not represented here selfReferenceSize?: number | undefined; selfReference?: { size?: number | undefined, angle?: number | undefined, renderBehindTheNode?: boolean | undefined } | undefined; shadow?: boolean | OptionsShadow | undefined; smooth?: boolean | { enabled: boolean, type: string, forceDirection?: string | boolean | undefined, roundness: number, } | undefined; title?: string | undefined; value?: number | undefined; width?: number | undefined; widthConstraint?: number | boolean | { maximum?: number | undefined; } | undefined; } export interface ArrowHead { enabled?: boolean | undefined; imageHeight?: number | undefined; imageWidth?: number | undefined; scaleFactor?: number | undefined; src?: string | undefined; type?: string | undefined; } export interface Font { color?: string | undefined; size?: number | undefined; // px face?: string | undefined; background?: string | undefined; strokeWidth?: number | undefined; // px strokeColor?: string | undefined; align?: string | undefined; vadjust?: number | undefined; multi?: boolean | string | undefined; bold?: string | FontStyles | undefined; ital?: string | FontStyles | undefined; boldital?: string | FontStyles | undefined; mono?: string | FontStyles | undefined; } export interface FontStyles { color?: string | undefined; size?: number | undefined; face?: string | undefined; mod?: string | undefined; vadjust?: number | undefined; } export interface OptionsScaling { min?: number | undefined; max?: number | undefined; label?: boolean | { enabled?: boolean | undefined, min?: number | undefined, max?: number | undefined, maxVisible?: number | undefined, drawThreshold?: number | undefined } | undefined; customScalingFunction?(min?: number, max?: number, total?: number, value?: number): number; } export interface OptionsShadow { enabled?: boolean | undefined; color?: string | undefined; size?: number | undefined; x?: number | undefined; y?: number | undefined; } export as namespace vis;
the_stack
/* eslint-disable @typescript-eslint/class-name-casing */ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-empty-interface */ /* eslint-disable @typescript-eslint/no-namespace */ /* eslint-disable no-irregular-whitespace */ import { OAuth2Client, JWT, Compute, UserRefreshClient, BaseExternalAccountClient, GaxiosPromise, GoogleConfigurable, createAPIRequest, MethodOptions, StreamMethodOptions, GlobalOptions, GoogleAuth, BodyResponseCallback, APIRequestContext, } from 'googleapis-common'; import {Readable} from 'stream'; export namespace drive_v3 { export interface Options extends GlobalOptions { version: 'v3'; } interface StandardParameters { /** * Auth client or API Key for the request */ auth?: | string | OAuth2Client | JWT | Compute | UserRefreshClient | BaseExternalAccountClient | GoogleAuth; /** * Data format for the response. */ alt?: string; /** * Selector specifying which fields to include in a partial response. */ fields?: string; /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * An opaque string that represents a user for quota purposes. Must not exceed 40 characters. */ quotaUser?: string; /** * Deprecated. Please use quotaUser instead. */ userIp?: string; } /** * Drive API * * Manages files in Drive including uploading, downloading, searching, detecting changes, and updating sharing permissions. * * @example * ```js * const {google} = require('googleapis'); * const drive = google.drive('v3'); * ``` */ export class Drive { context: APIRequestContext; about: Resource$About; changes: Resource$Changes; channels: Resource$Channels; comments: Resource$Comments; drives: Resource$Drives; files: Resource$Files; permissions: Resource$Permissions; replies: Resource$Replies; revisions: Resource$Revisions; teamdrives: Resource$Teamdrives; constructor(options: GlobalOptions, google?: GoogleConfigurable) { this.context = { _options: options || {}, google, }; this.about = new Resource$About(this.context); this.changes = new Resource$Changes(this.context); this.channels = new Resource$Channels(this.context); this.comments = new Resource$Comments(this.context); this.drives = new Resource$Drives(this.context); this.files = new Resource$Files(this.context); this.permissions = new Resource$Permissions(this.context); this.replies = new Resource$Replies(this.context); this.revisions = new Resource$Revisions(this.context); this.teamdrives = new Resource$Teamdrives(this.context); } } /** * Information about the user, the user's Drive, and system capabilities. */ export interface Schema$About { /** * Whether the user has installed the requesting app. */ appInstalled?: boolean | null; /** * Whether the user can create shared drives. */ canCreateDrives?: boolean | null; /** * Deprecated - use canCreateDrives instead. */ canCreateTeamDrives?: boolean | null; /** * A list of themes that are supported for shared drives. */ driveThemes?: Array<{ backgroundImageLink?: string; colorRgb?: string; id?: string; }> | null; /** * A map of source MIME type to possible targets for all supported exports. */ exportFormats?: {[key: string]: string[]} | null; /** * The currently supported folder colors as RGB hex strings. */ folderColorPalette?: string[] | null; /** * A map of source MIME type to possible targets for all supported imports. */ importFormats?: {[key: string]: string[]} | null; /** * Identifies what kind of resource this is. Value: the fixed string "drive#about". */ kind?: string | null; /** * A map of maximum import sizes by MIME type, in bytes. */ maxImportSizes?: {[key: string]: string} | null; /** * The maximum upload size in bytes. */ maxUploadSize?: string | null; /** * The user's storage quota limits and usage. All fields are measured in bytes. */ storageQuota?: { limit?: string; usage?: string; usageInDrive?: string; usageInDriveTrash?: string; } | null; /** * Deprecated - use driveThemes instead. */ teamDriveThemes?: Array<{ backgroundImageLink?: string; colorRgb?: string; id?: string; }> | null; /** * The authenticated user. */ user?: Schema$User; } /** * A change to a file or shared drive. */ export interface Schema$Change { /** * The type of the change. Possible values are file and drive. */ changeType?: string | null; /** * The updated state of the shared drive. Present if the changeType is drive, the user is still a member of the shared drive, and the shared drive has not been deleted. */ drive?: Schema$Drive; /** * The ID of the shared drive associated with this change. */ driveId?: string | null; /** * The updated state of the file. Present if the type is file and the file has not been removed from this list of changes. */ file?: Schema$File; /** * The ID of the file which has changed. */ fileId?: string | null; /** * Identifies what kind of resource this is. Value: the fixed string "drive#change". */ kind?: string | null; /** * Whether the file or shared drive has been removed from this list of changes, for example by deletion or loss of access. */ removed?: boolean | null; /** * Deprecated - use drive instead. */ teamDrive?: Schema$TeamDrive; /** * Deprecated - use driveId instead. */ teamDriveId?: string | null; /** * The time of this change (RFC 3339 date-time). */ time?: string | null; /** * Deprecated - use changeType instead. */ type?: string | null; } /** * A list of changes for a user. */ export interface Schema$ChangeList { /** * The list of changes. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ changes?: Schema$Change[]; /** * Identifies what kind of resource this is. Value: the fixed string "drive#changeList". */ kind?: string | null; /** * The starting page token for future changes. This will be present only if the end of the current changes list has been reached. */ newStartPageToken?: string | null; /** * The page token for the next page of changes. This will be absent if the end of the changes list has been reached. If the token is rejected for any reason, it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string | null; } /** * An notification channel used to watch for resource changes. */ export interface Schema$Channel { /** * The address where notifications are delivered for this channel. */ address?: string | null; /** * Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional. */ expiration?: string | null; /** * A UUID or similar unique string that identifies this channel. */ id?: string | null; /** * Identifies this as a notification channel used to watch for changes to a resource, which is "api#channel". */ kind?: string | null; /** * Additional parameters controlling delivery channel behavior. Optional. */ params?: {[key: string]: string} | null; /** * A Boolean value to indicate whether payload is wanted. Optional. */ payload?: boolean | null; /** * An opaque ID that identifies the resource being watched on this channel. Stable across different API versions. */ resourceId?: string | null; /** * A version-specific identifier for the watched resource. */ resourceUri?: string | null; /** * An arbitrary string delivered to the target address with each notification delivered over this channel. Optional. */ token?: string | null; /** * The type of delivery mechanism used for this channel. Valid values are "web_hook" (or "webhook"). Both values refer to a channel where Http requests are used to deliver messages. */ type?: string | null; } /** * A comment on a file. */ export interface Schema$Comment { /** * A region of the document represented as a JSON string. For details on defining anchor properties, refer to Add comments and replies. */ anchor?: string | null; /** * The author of the comment. The author's email address and permission ID will not be populated. */ author?: Schema$User; /** * The plain text content of the comment. This field is used for setting the content, while htmlContent should be displayed. */ content?: string | null; /** * The time at which the comment was created (RFC 3339 date-time). */ createdTime?: string | null; /** * Whether the comment has been deleted. A deleted comment has no content. */ deleted?: boolean | null; /** * The content of the comment with HTML formatting. */ htmlContent?: string | null; /** * The ID of the comment. */ id?: string | null; /** * Identifies what kind of resource this is. Value: the fixed string "drive#comment". */ kind?: string | null; /** * The last time the comment or any of its replies was modified (RFC 3339 date-time). */ modifiedTime?: string | null; /** * The file content to which the comment refers, typically within the anchor region. For a text file, for example, this would be the text at the location of the comment. */ quotedFileContent?: {mimeType?: string; value?: string} | null; /** * The full list of replies to the comment in chronological order. */ replies?: Schema$Reply[]; /** * Whether the comment has been resolved by one of its replies. */ resolved?: boolean | null; } /** * A list of comments on a file. */ export interface Schema$CommentList { /** * The list of comments. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ comments?: Schema$Comment[]; /** * Identifies what kind of resource this is. Value: the fixed string "drive#commentList". */ kind?: string | null; /** * The page token for the next page of comments. This will be absent if the end of the comments list has been reached. If the token is rejected for any reason, it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string | null; } /** * A restriction for accessing the content of the file. */ export interface Schema$ContentRestriction { /** * Whether the content of the file is read-only. If a file is read-only, a new revision of the file may not be added, comments may not be added or modified, and the title of the file may not be modified. */ readOnly?: boolean | null; /** * Reason for why the content of the file is restricted. This is only mutable on requests that also set readOnly=true. */ reason?: string | null; /** * The user who set the content restriction. Only populated if readOnly is true. */ restrictingUser?: Schema$User; /** * The time at which the content restriction was set (formatted RFC 3339 timestamp). Only populated if readOnly is true. */ restrictionTime?: string | null; /** * The type of the content restriction. Currently the only possible value is globalContentRestriction. */ type?: string | null; } /** * Representation of a shared drive. */ export interface Schema$Drive { /** * An image file and cropping parameters from which a background image for this shared drive is set. This is a write only field; it can only be set on drive.drives.update requests that don't set themeId. When specified, all fields of the backgroundImageFile must be set. */ backgroundImageFile?: { id?: string; width?: number; xCoordinate?: number; yCoordinate?: number; } | null; /** * A short-lived link to this shared drive's background image. */ backgroundImageLink?: string | null; /** * Capabilities the current user has on this shared drive. */ capabilities?: { canAddChildren?: boolean; canChangeCopyRequiresWriterPermissionRestriction?: boolean; canChangeDomainUsersOnlyRestriction?: boolean; canChangeDriveBackground?: boolean; canChangeDriveMembersOnlyRestriction?: boolean; canComment?: boolean; canCopy?: boolean; canDeleteChildren?: boolean; canDeleteDrive?: boolean; canDownload?: boolean; canEdit?: boolean; canListChildren?: boolean; canManageMembers?: boolean; canReadRevisions?: boolean; canRename?: boolean; canRenameDrive?: boolean; canShare?: boolean; canTrashChildren?: boolean; } | null; /** * The color of this shared drive as an RGB hex string. It can only be set on a drive.drives.update request that does not set themeId. */ colorRgb?: string | null; /** * The time at which the shared drive was created (RFC 3339 date-time). */ createdTime?: string | null; /** * Whether the shared drive is hidden from default view. */ hidden?: boolean | null; /** * The ID of this shared drive which is also the ID of the top level folder of this shared drive. */ id?: string | null; /** * Identifies what kind of resource this is. Value: the fixed string "drive#drive". */ kind?: string | null; /** * The name of this shared drive. */ name?: string | null; /** * A set of restrictions that apply to this shared drive or items inside this shared drive. */ restrictions?: { adminManagedRestrictions?: boolean; copyRequiresWriterPermission?: boolean; domainUsersOnly?: boolean; driveMembersOnly?: boolean; } | null; /** * The ID of the theme from which the background image and color will be set. The set of possible driveThemes can be retrieved from a drive.about.get response. When not specified on a drive.drives.create request, a random theme is chosen from which the background image and color are set. This is a write-only field; it can only be set on requests that don't set colorRgb or backgroundImageFile. */ themeId?: string | null; } /** * A list of shared drives. */ export interface Schema$DriveList { /** * The list of shared drives. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ drives?: Schema$Drive[]; /** * Identifies what kind of resource this is. Value: the fixed string "drive#driveList". */ kind?: string | null; /** * The page token for the next page of shared drives. This will be absent if the end of the list has been reached. If the token is rejected for any reason, it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string | null; } /** * The metadata for a file. */ export interface Schema$File { /** * A collection of arbitrary key-value pairs which are private to the requesting app. * Entries with null values are cleared in update and copy requests. These properties can only be retrieved using an authenticated request. An authenticated request uses an access token obtained with a OAuth 2 client ID. You cannot use an API key to retrieve private properties. */ appProperties?: {[key: string]: string} | null; /** * Capabilities the current user has on this file. Each capability corresponds to a fine-grained action that a user may take. */ capabilities?: { canAcceptOwnership?: boolean; canAddChildren?: boolean; canAddFolderFromAnotherDrive?: boolean; canAddMyDriveParent?: boolean; canChangeCopyRequiresWriterPermission?: boolean; canChangeSecurityUpdateEnabled?: boolean; canChangeViewersCanCopyContent?: boolean; canComment?: boolean; canCopy?: boolean; canDelete?: boolean; canDeleteChildren?: boolean; canDownload?: boolean; canEdit?: boolean; canListChildren?: boolean; canModifyContent?: boolean; canModifyContentRestriction?: boolean; canMoveChildrenOutOfDrive?: boolean; canMoveChildrenOutOfTeamDrive?: boolean; canMoveChildrenWithinDrive?: boolean; canMoveChildrenWithinTeamDrive?: boolean; canMoveItemIntoTeamDrive?: boolean; canMoveItemOutOfDrive?: boolean; canMoveItemOutOfTeamDrive?: boolean; canMoveItemWithinDrive?: boolean; canMoveItemWithinTeamDrive?: boolean; canMoveTeamDriveItem?: boolean; canReadDrive?: boolean; canReadRevisions?: boolean; canReadTeamDrive?: boolean; canRemoveChildren?: boolean; canRemoveMyDriveParent?: boolean; canRename?: boolean; canShare?: boolean; canTrash?: boolean; canTrashChildren?: boolean; canUntrash?: boolean; } | null; /** * Additional information about the content of the file. These fields are never populated in responses. */ contentHints?: { indexableText?: string; thumbnail?: {image?: string; mimeType?: string}; } | null; /** * Restrictions for accessing the content of the file. Only populated if such a restriction exists. */ contentRestrictions?: Schema$ContentRestriction[]; /** * Whether the options to copy, print, or download this file, should be disabled for readers and commenters. */ copyRequiresWriterPermission?: boolean | null; /** * The time at which the file was created (RFC 3339 date-time). */ createdTime?: string | null; /** * A short description of the file. */ description?: string | null; /** * ID of the shared drive the file resides in. Only populated for items in shared drives. */ driveId?: string | null; /** * Whether the file has been explicitly trashed, as opposed to recursively trashed from a parent folder. */ explicitlyTrashed?: boolean | null; /** * Links for exporting Docs Editors files to specific formats. */ exportLinks?: {[key: string]: string} | null; /** * The final component of fullFileExtension. This is only available for files with binary content in Google Drive. */ fileExtension?: string | null; /** * The color for a folder or shortcut to a folder as an RGB hex string. The supported colors are published in the folderColorPalette field of the About resource. * If an unsupported color is specified, the closest color in the palette will be used instead. */ folderColorRgb?: string | null; /** * The full file extension extracted from the name field. May contain multiple concatenated extensions, such as "tar.gz". This is only available for files with binary content in Google Drive. * This is automatically updated when the name field changes, however it is not cleared if the new name does not contain a valid extension. */ fullFileExtension?: string | null; /** * Whether there are permissions directly on this file. This field is only populated for items in shared drives. */ hasAugmentedPermissions?: boolean | null; /** * Whether this file has a thumbnail. This does not indicate whether the requesting app has access to the thumbnail. To check access, look for the presence of the thumbnailLink field. */ hasThumbnail?: boolean | null; /** * The ID of the file's head revision. This is currently only available for files with binary content in Google Drive. */ headRevisionId?: string | null; /** * A static, unauthenticated link to the file's icon. */ iconLink?: string | null; /** * The ID of the file. */ id?: string | null; /** * Additional metadata about image media, if available. */ imageMediaMetadata?: { aperture?: number; cameraMake?: string; cameraModel?: string; colorSpace?: string; exposureBias?: number; exposureMode?: string; exposureTime?: number; flashUsed?: boolean; focalLength?: number; height?: number; isoSpeed?: number; lens?: string; location?: {altitude?: number; latitude?: number; longitude?: number}; maxApertureValue?: number; meteringMode?: string; rotation?: number; sensor?: string; subjectDistance?: number; time?: string; whiteBalance?: string; width?: number; } | null; /** * Whether the file was created or opened by the requesting app. */ isAppAuthorized?: boolean | null; /** * Identifies what kind of resource this is. Value: the fixed string "drive#file". */ kind?: string | null; /** * The last user to modify the file. */ lastModifyingUser?: Schema$User; /** * Contains details about the link URLs that clients are using to refer to this item. */ linkShareMetadata?: { securityUpdateEligible?: boolean; securityUpdateEnabled?: boolean; } | null; /** * The MD5 checksum for the content of the file. This is only applicable to files with binary content in Google Drive. */ md5Checksum?: string | null; /** * The MIME type of the file. * Google Drive will attempt to automatically detect an appropriate value from uploaded content if no value is provided. The value cannot be changed unless a new revision is uploaded. * If a file is created with a Google Doc MIME type, the uploaded content will be imported if possible. The supported import formats are published in the About resource. */ mimeType?: string | null; /** * Whether the file has been modified by this user. */ modifiedByMe?: boolean | null; /** * The last time the file was modified by the user (RFC 3339 date-time). */ modifiedByMeTime?: string | null; /** * The last time the file was modified by anyone (RFC 3339 date-time). * Note that setting modifiedTime will also update modifiedByMeTime for the user. */ modifiedTime?: string | null; /** * The name of the file. This is not necessarily unique within a folder. Note that for immutable items such as the top level folders of shared drives, My Drive root folder, and Application Data folder the name is constant. */ name?: string | null; /** * The original filename of the uploaded content if available, or else the original value of the name field. This is only available for files with binary content in Google Drive. */ originalFilename?: string | null; /** * Whether the user owns the file. Not populated for items in shared drives. */ ownedByMe?: boolean | null; /** * The owner of this file. Only certain legacy files may have more than one owner. This field isn't populated for items in shared drives. */ owners?: Schema$User[]; /** * The IDs of the parent folders which contain the file. * If not specified as part of a create request, the file will be placed directly in the user's My Drive folder. If not specified as part of a copy request, the file will inherit any discoverable parents of the source file. Update requests must use the addParents and removeParents parameters to modify the parents list. */ parents?: string[] | null; /** * List of permission IDs for users with access to this file. */ permissionIds?: string[] | null; /** * The full list of permissions for the file. This is only available if the requesting user can share the file. Not populated for items in shared drives. */ permissions?: Schema$Permission[]; /** * A collection of arbitrary key-value pairs which are visible to all apps. * Entries with null values are cleared in update and copy requests. */ properties?: {[key: string]: string} | null; /** * The number of storage quota bytes used by the file. This includes the head revision as well as previous revisions with keepForever enabled. */ quotaBytesUsed?: string | null; /** * A key needed to access the item via a shared link. */ resourceKey?: string | null; /** * Whether the file has been shared. Not populated for items in shared drives. */ shared?: boolean | null; /** * The time at which the file was shared with the user, if applicable (RFC 3339 date-time). */ sharedWithMeTime?: string | null; /** * The user who shared the file with the requesting user, if applicable. */ sharingUser?: Schema$User; /** * Shortcut file details. Only populated for shortcut files, which have the mimeType field set to application/vnd.google-apps.shortcut. */ shortcutDetails?: { targetId?: string; targetMimeType?: string; targetResourceKey?: string; } | null; /** * The size of the file's content in bytes. This is applicable to binary files in Google Drive and Google Docs files. */ size?: string | null; /** * The list of spaces which contain the file. The currently supported values are 'drive', 'appDataFolder' and 'photos'. */ spaces?: string[] | null; /** * Whether the user has starred the file. */ starred?: boolean | null; /** * Deprecated - use driveId instead. */ teamDriveId?: string | null; /** * A short-lived link to the file's thumbnail, if available. Typically lasts on the order of hours. Only populated when the requesting app can access the file's content. If the file isn't shared publicly, the URL returned in Files.thumbnailLink must be fetched using a credentialed request. */ thumbnailLink?: string | null; /** * The thumbnail version for use in thumbnail cache invalidation. */ thumbnailVersion?: string | null; /** * Whether the file has been trashed, either explicitly or from a trashed parent folder. Only the owner may trash a file. The trashed item is excluded from all files.list responses returned for any user who does not own the file. However, all users with access to the file can see the trashed item metadata in an API response. All users with access can copy, download, export, and share the file. */ trashed?: boolean | null; /** * The time that the item was trashed (RFC 3339 date-time). Only populated for items in shared drives. */ trashedTime?: string | null; /** * If the file has been explicitly trashed, the user who trashed it. Only populated for items in shared drives. */ trashingUser?: Schema$User; /** * A monotonically increasing version number for the file. This reflects every change made to the file on the server, even those not visible to the user. */ version?: string | null; /** * Additional metadata about video media. This may not be available immediately upon upload. */ videoMediaMetadata?: { durationMillis?: string; height?: number; width?: number; } | null; /** * Whether the file has been viewed by this user. */ viewedByMe?: boolean | null; /** * The last time the file was viewed by the user (RFC 3339 date-time). */ viewedByMeTime?: string | null; /** * Deprecated - use copyRequiresWriterPermission instead. */ viewersCanCopyContent?: boolean | null; /** * A link for downloading the content of the file in a browser. This is only available for files with binary content in Google Drive. */ webContentLink?: string | null; /** * A link for opening the file in a relevant Google editor or viewer in a browser. */ webViewLink?: string | null; /** * Whether users with only writer permission can modify the file's permissions. Not populated for items in shared drives. */ writersCanShare?: boolean | null; } /** * A list of files. */ export interface Schema$FileList { /** * The list of files. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ files?: Schema$File[]; /** * Whether the search process was incomplete. If true, then some search results may be missing, since all documents were not searched. This may occur when searching multiple drives with the "allDrives" corpora, but all corpora could not be searched. When this happens, it is suggested that clients narrow their query by choosing a different corpus such as "user" or "drive". */ incompleteSearch?: boolean | null; /** * Identifies what kind of resource this is. Value: the fixed string "drive#fileList". */ kind?: string | null; /** * The page token for the next page of files. This will be absent if the end of the files list has been reached. If the token is rejected for any reason, it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string | null; } /** * A list of generated file IDs which can be provided in create requests. */ export interface Schema$GeneratedIds { /** * The IDs generated for the requesting user in the specified space. */ ids?: string[] | null; /** * Identifies what kind of resource this is. Value: the fixed string "drive#generatedIds". */ kind?: string | null; /** * The type of file that can be created with these IDs. */ space?: string | null; } /** * A permission for a file. A permission grants a user, group, domain or the world access to a file or a folder hierarchy. */ export interface Schema$Permission { /** * Whether the permission allows the file to be discovered through search. This is only applicable for permissions of type domain or anyone. */ allowFileDiscovery?: boolean | null; /** * Whether the account associated with this permission has been deleted. This field only pertains to user and group permissions. */ deleted?: boolean | null; /** * The "pretty" name of the value of the permission. The following is a list of examples for each type of permission: * - user - User's full name, as defined for their Google account, such as "Joe Smith." * - group - Name of the Google Group, such as "The Company Administrators." * - domain - String domain name, such as "thecompany.com." * - anyone - No displayName is present. */ displayName?: string | null; /** * The domain to which this permission refers. */ domain?: string | null; /** * The email address of the user or group to which this permission refers. */ emailAddress?: string | null; /** * The time at which this permission will expire (RFC 3339 date-time). Expiration times have the following restrictions: * - They can only be set on user and group permissions * - The time must be in the future * - The time cannot be more than a year in the future */ expirationTime?: string | null; /** * The ID of this permission. This is a unique identifier for the grantee, and is published in User resources as permissionId. IDs should be treated as opaque values. */ id?: string | null; /** * Identifies what kind of resource this is. Value: the fixed string "drive#permission". */ kind?: string | null; /** * Whether the account associated with this permission is a pending owner. Only populated for user type permissions for files that are not in a shared drive. */ pendingOwner?: boolean | null; /** * Details of whether the permissions on this shared drive item are inherited or directly on this item. This is an output-only field which is present only for shared drive items. */ permissionDetails?: Array<{ inherited?: boolean; inheritedFrom?: string; permissionType?: string; role?: string; }> | null; /** * A link to the user's profile photo, if available. */ photoLink?: string | null; /** * The role granted by this permission. While new values may be supported in the future, the following are currently allowed: * - owner * - organizer * - fileOrganizer * - writer * - commenter * - reader */ role?: string | null; /** * Deprecated - use permissionDetails instead. */ teamDrivePermissionDetails?: Array<{ inherited?: boolean; inheritedFrom?: string; role?: string; teamDrivePermissionType?: string; }> | null; /** * The type of the grantee. Valid values are: * - user * - group * - domain * - anyone When creating a permission, if type is user or group, you must provide an emailAddress for the user or group. When type is domain, you must provide a domain. There isn't extra information required for a anyone type. */ type?: string | null; /** * Indicates the view for this permission. Only populated for permissions that belong to a view. published is the only supported value. */ view?: string | null; } /** * A list of permissions for a file. */ export interface Schema$PermissionList { /** * Identifies what kind of resource this is. Value: the fixed string "drive#permissionList". */ kind?: string | null; /** * The page token for the next page of permissions. This field will be absent if the end of the permissions list has been reached. If the token is rejected for any reason, it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string | null; /** * The list of permissions. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ permissions?: Schema$Permission[]; } /** * A reply to a comment on a file. */ export interface Schema$Reply { /** * The action the reply performed to the parent comment. Valid values are: * - resolve * - reopen */ action?: string | null; /** * The author of the reply. The author's email address and permission ID will not be populated. */ author?: Schema$User; /** * The plain text content of the reply. This field is used for setting the content, while htmlContent should be displayed. This is required on creates if no action is specified. */ content?: string | null; /** * The time at which the reply was created (RFC 3339 date-time). */ createdTime?: string | null; /** * Whether the reply has been deleted. A deleted reply has no content. */ deleted?: boolean | null; /** * The content of the reply with HTML formatting. */ htmlContent?: string | null; /** * The ID of the reply. */ id?: string | null; /** * Identifies what kind of resource this is. Value: the fixed string "drive#reply". */ kind?: string | null; /** * The last time the reply was modified (RFC 3339 date-time). */ modifiedTime?: string | null; } /** * A list of replies to a comment on a file. */ export interface Schema$ReplyList { /** * Identifies what kind of resource this is. Value: the fixed string "drive#replyList". */ kind?: string | null; /** * The page token for the next page of replies. This will be absent if the end of the replies list has been reached. If the token is rejected for any reason, it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string | null; /** * The list of replies. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ replies?: Schema$Reply[]; } /** * The metadata for a revision to a file. */ export interface Schema$Revision { /** * Links for exporting Docs Editors files to specific formats. */ exportLinks?: {[key: string]: string} | null; /** * The ID of the revision. */ id?: string | null; /** * Whether to keep this revision forever, even if it is no longer the head revision. If not set, the revision will be automatically purged 30 days after newer content is uploaded. This can be set on a maximum of 200 revisions for a file. * This field is only applicable to files with binary content in Drive. */ keepForever?: boolean | null; /** * Identifies what kind of resource this is. Value: the fixed string "drive#revision". */ kind?: string | null; /** * The last user to modify this revision. */ lastModifyingUser?: Schema$User; /** * The MD5 checksum of the revision's content. This is only applicable to files with binary content in Drive. */ md5Checksum?: string | null; /** * The MIME type of the revision. */ mimeType?: string | null; /** * The last time the revision was modified (RFC 3339 date-time). */ modifiedTime?: string | null; /** * The original filename used to create this revision. This is only applicable to files with binary content in Drive. */ originalFilename?: string | null; /** * Whether subsequent revisions will be automatically republished. This is only applicable to Docs Editors files. */ publishAuto?: boolean | null; /** * Whether this revision is published. This is only applicable to Docs Editors files. */ published?: boolean | null; /** * A link to the published revision. This is only populated for Google Sites files. */ publishedLink?: string | null; /** * Whether this revision is published outside the domain. This is only applicable to Docs Editors files. */ publishedOutsideDomain?: boolean | null; /** * The size of the revision's content in bytes. This is only applicable to files with binary content in Drive. */ size?: string | null; } /** * A list of revisions of a file. */ export interface Schema$RevisionList { /** * Identifies what kind of resource this is. Value: the fixed string "drive#revisionList". */ kind?: string | null; /** * The page token for the next page of revisions. This will be absent if the end of the revisions list has been reached. If the token is rejected for any reason, it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string | null; /** * The list of revisions. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ revisions?: Schema$Revision[]; } export interface Schema$StartPageToken { /** * Identifies what kind of resource this is. Value: the fixed string "drive#startPageToken". */ kind?: string | null; /** * The starting page token for listing changes. */ startPageToken?: string | null; } /** * Deprecated: use the drive collection instead. */ export interface Schema$TeamDrive { /** * An image file and cropping parameters from which a background image for this Team Drive is set. This is a write only field; it can only be set on drive.teamdrives.update requests that don't set themeId. When specified, all fields of the backgroundImageFile must be set. */ backgroundImageFile?: { id?: string; width?: number; xCoordinate?: number; yCoordinate?: number; } | null; /** * A short-lived link to this Team Drive's background image. */ backgroundImageLink?: string | null; /** * Capabilities the current user has on this Team Drive. */ capabilities?: { canAddChildren?: boolean; canChangeCopyRequiresWriterPermissionRestriction?: boolean; canChangeDomainUsersOnlyRestriction?: boolean; canChangeTeamDriveBackground?: boolean; canChangeTeamMembersOnlyRestriction?: boolean; canComment?: boolean; canCopy?: boolean; canDeleteChildren?: boolean; canDeleteTeamDrive?: boolean; canDownload?: boolean; canEdit?: boolean; canListChildren?: boolean; canManageMembers?: boolean; canReadRevisions?: boolean; canRemoveChildren?: boolean; canRename?: boolean; canRenameTeamDrive?: boolean; canShare?: boolean; canTrashChildren?: boolean; } | null; /** * The color of this Team Drive as an RGB hex string. It can only be set on a drive.teamdrives.update request that does not set themeId. */ colorRgb?: string | null; /** * The time at which the Team Drive was created (RFC 3339 date-time). */ createdTime?: string | null; /** * The ID of this Team Drive which is also the ID of the top level folder of this Team Drive. */ id?: string | null; /** * Identifies what kind of resource this is. Value: the fixed string "drive#teamDrive". */ kind?: string | null; /** * The name of this Team Drive. */ name?: string | null; /** * A set of restrictions that apply to this Team Drive or items inside this Team Drive. */ restrictions?: { adminManagedRestrictions?: boolean; copyRequiresWriterPermission?: boolean; domainUsersOnly?: boolean; teamMembersOnly?: boolean; } | null; /** * The ID of the theme from which the background image and color will be set. The set of possible teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a drive.teamdrives.create request, a random theme is chosen from which the background image and color are set. This is a write-only field; it can only be set on requests that don't set colorRgb or backgroundImageFile. */ themeId?: string | null; } /** * A list of Team Drives. */ export interface Schema$TeamDriveList { /** * Identifies what kind of resource this is. Value: the fixed string "drive#teamDriveList". */ kind?: string | null; /** * The page token for the next page of Team Drives. This will be absent if the end of the Team Drives list has been reached. If the token is rejected for any reason, it should be discarded, and pagination should be restarted from the first page of results. */ nextPageToken?: string | null; /** * The list of Team Drives. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. */ teamDrives?: Schema$TeamDrive[]; } /** * Information about a Drive user. */ export interface Schema$User { /** * A plain text displayable name for this user. */ displayName?: string | null; /** * The email address of the user. This may not be present in certain contexts if the user has not made their email address visible to the requester. */ emailAddress?: string | null; /** * Identifies what kind of resource this is. Value: the fixed string "drive#user". */ kind?: string | null; /** * Whether this user is the requesting user. */ me?: boolean | null; /** * The user's ID as visible in Permission resources. */ permissionId?: string | null; /** * A link to the user's profile photo, if available. */ photoLink?: string | null; } export class Resource$About { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets information about the user, the user's Drive, and system capabilities. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.metadata', * 'https://www.googleapis.com/auth/drive.metadata.readonly', * 'https://www.googleapis.com/auth/drive.photos.readonly', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.about.get({}); * console.log(res.data); * * // Example response * // { * // "appInstalled": false, * // "canCreateDrives": false, * // "canCreateTeamDrives": false, * // "driveThemes": [], * // "exportFormats": {}, * // "folderColorPalette": [], * // "importFormats": {}, * // "kind": "my_kind", * // "maxImportSizes": {}, * // "maxUploadSize": "my_maxUploadSize", * // "storageQuota": {}, * // "teamDriveThemes": [], * // "user": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$About$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$About$Get, options?: MethodOptions ): GaxiosPromise<Schema$About>; get( params: Params$Resource$About$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$About$Get, options: MethodOptions | BodyResponseCallback<Schema$About>, callback: BodyResponseCallback<Schema$About> ): void; get( params: Params$Resource$About$Get, callback: BodyResponseCallback<Schema$About> ): void; get(callback: BodyResponseCallback<Schema$About>): void; get( paramsOrCallback?: | Params$Resource$About$Get | BodyResponseCallback<Schema$About> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$About> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$About> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$About> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$About$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$About$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/about').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$About>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$About>(parameters); } } } export interface Params$Resource$About$Get extends StandardParameters {} export class Resource$Changes { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Gets the starting pageToken for listing future changes. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.metadata', * 'https://www.googleapis.com/auth/drive.metadata.readonly', * 'https://www.googleapis.com/auth/drive.photos.readonly', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.changes.getStartPageToken({ * // The ID of the shared drive for which the starting pageToken for listing future changes from that shared drive is returned. * driveId: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * // Deprecated use driveId instead. * teamDriveId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "kind": "my_kind", * // "startPageToken": "my_startPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ getStartPageToken( params: Params$Resource$Changes$Getstartpagetoken, options: StreamMethodOptions ): GaxiosPromise<Readable>; getStartPageToken( params?: Params$Resource$Changes$Getstartpagetoken, options?: MethodOptions ): GaxiosPromise<Schema$StartPageToken>; getStartPageToken( params: Params$Resource$Changes$Getstartpagetoken, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; getStartPageToken( params: Params$Resource$Changes$Getstartpagetoken, options: MethodOptions | BodyResponseCallback<Schema$StartPageToken>, callback: BodyResponseCallback<Schema$StartPageToken> ): void; getStartPageToken( params: Params$Resource$Changes$Getstartpagetoken, callback: BodyResponseCallback<Schema$StartPageToken> ): void; getStartPageToken( callback: BodyResponseCallback<Schema$StartPageToken> ): void; getStartPageToken( paramsOrCallback?: | Params$Resource$Changes$Getstartpagetoken | BodyResponseCallback<Schema$StartPageToken> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$StartPageToken> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$StartPageToken> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$StartPageToken> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Changes$Getstartpagetoken; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Changes$Getstartpagetoken; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/changes/startPageToken').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$StartPageToken>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$StartPageToken>(parameters); } } /** * Lists the changes for a user or shared drive. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.metadata', * 'https://www.googleapis.com/auth/drive.metadata.readonly', * 'https://www.googleapis.com/auth/drive.photos.readonly', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.changes.list({ * // The shared drive from which changes are returned. If specified the change IDs will be reflective of the shared drive; use the combined drive ID and change ID as an identifier. * driveId: 'placeholder-value', * // Whether changes should include the file resource if the file is still accessible by the user at the time of the request, even when a file was removed from the list of changes and there will be no further change entries for this file. * includeCorpusRemovals: 'placeholder-value', * // Whether both My Drive and shared drive items should be included in results. * includeItemsFromAllDrives: 'placeholder-value', * // Specifies which additional view's permissions to include in the response. Only 'published' is supported. * includePermissionsForView: 'placeholder-value', * // Whether to include changes indicating that items have been removed from the list of changes, for example by deletion or loss of access. * includeRemoved: 'placeholder-value', * // Deprecated use includeItemsFromAllDrives instead. * includeTeamDriveItems: 'placeholder-value', * // The maximum number of changes to return per page. * pageSize: 'placeholder-value', * // The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response or to the response from the getStartPageToken method. * pageToken: 'placeholder-value', * // Whether to restrict the results to changes inside the My Drive hierarchy. This omits changes to files such as those in the Application Data folder or shared files which have not been added to My Drive. * restrictToMyDrive: 'placeholder-value', * // A comma-separated list of spaces to query within the user corpus. Supported values are 'drive', 'appDataFolder' and 'photos'. * spaces: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * // Deprecated use driveId instead. * teamDriveId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "changes": [], * // "kind": "my_kind", * // "newStartPageToken": "my_newStartPageToken", * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Changes$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Changes$List, options?: MethodOptions ): GaxiosPromise<Schema$ChangeList>; list( params: Params$Resource$Changes$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Changes$List, options: MethodOptions | BodyResponseCallback<Schema$ChangeList>, callback: BodyResponseCallback<Schema$ChangeList> ): void; list( params: Params$Resource$Changes$List, callback: BodyResponseCallback<Schema$ChangeList> ): void; list(callback: BodyResponseCallback<Schema$ChangeList>): void; list( paramsOrCallback?: | Params$Resource$Changes$List | BodyResponseCallback<Schema$ChangeList> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ChangeList> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ChangeList> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$ChangeList> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Changes$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Changes$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/changes').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['pageToken'], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$ChangeList>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ChangeList>(parameters); } } /** * Subscribes to changes for a user. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.metadata', * 'https://www.googleapis.com/auth/drive.metadata.readonly', * 'https://www.googleapis.com/auth/drive.photos.readonly', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.changes.watch({ * // The shared drive from which changes are returned. If specified the change IDs will be reflective of the shared drive; use the combined drive ID and change ID as an identifier. * driveId: 'placeholder-value', * // Whether changes should include the file resource if the file is still accessible by the user at the time of the request, even when a file was removed from the list of changes and there will be no further change entries for this file. * includeCorpusRemovals: 'placeholder-value', * // Whether both My Drive and shared drive items should be included in results. * includeItemsFromAllDrives: 'placeholder-value', * // Specifies which additional view's permissions to include in the response. Only 'published' is supported. * includePermissionsForView: 'placeholder-value', * // Whether to include changes indicating that items have been removed from the list of changes, for example by deletion or loss of access. * includeRemoved: 'placeholder-value', * // Deprecated use includeItemsFromAllDrives instead. * includeTeamDriveItems: 'placeholder-value', * // The maximum number of changes to return per page. * pageSize: 'placeholder-value', * // The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response or to the response from the getStartPageToken method. * pageToken: 'placeholder-value', * // Whether to restrict the results to changes inside the My Drive hierarchy. This omits changes to files such as those in the Application Data folder or shared files which have not been added to My Drive. * restrictToMyDrive: 'placeholder-value', * // A comma-separated list of spaces to query within the user corpus. Supported values are 'drive', 'appDataFolder' and 'photos'. * spaces: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * // Deprecated use driveId instead. * teamDriveId: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "address": "my_address", * // "expiration": "my_expiration", * // "id": "my_id", * // "kind": "my_kind", * // "params": {}, * // "payload": false, * // "resourceId": "my_resourceId", * // "resourceUri": "my_resourceUri", * // "token": "my_token", * // "type": "my_type" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "address": "my_address", * // "expiration": "my_expiration", * // "id": "my_id", * // "kind": "my_kind", * // "params": {}, * // "payload": false, * // "resourceId": "my_resourceId", * // "resourceUri": "my_resourceUri", * // "token": "my_token", * // "type": "my_type" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ watch( params: Params$Resource$Changes$Watch, options: StreamMethodOptions ): GaxiosPromise<Readable>; watch( params?: Params$Resource$Changes$Watch, options?: MethodOptions ): GaxiosPromise<Schema$Channel>; watch( params: Params$Resource$Changes$Watch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; watch( params: Params$Resource$Changes$Watch, options: MethodOptions | BodyResponseCallback<Schema$Channel>, callback: BodyResponseCallback<Schema$Channel> ): void; watch( params: Params$Resource$Changes$Watch, callback: BodyResponseCallback<Schema$Channel> ): void; watch(callback: BodyResponseCallback<Schema$Channel>): void; watch( paramsOrCallback?: | Params$Resource$Changes$Watch | BodyResponseCallback<Schema$Channel> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Channel> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Channel> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Channel> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Changes$Watch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Changes$Watch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/changes/watch').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['pageToken'], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$Channel>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Channel>(parameters); } } } export interface Params$Resource$Changes$Getstartpagetoken extends StandardParameters { /** * The ID of the shared drive for which the starting pageToken for listing future changes from that shared drive is returned. */ driveId?: string; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; /** * Deprecated use driveId instead. */ teamDriveId?: string; } export interface Params$Resource$Changes$List extends StandardParameters { /** * The shared drive from which changes are returned. If specified the change IDs will be reflective of the shared drive; use the combined drive ID and change ID as an identifier. */ driveId?: string; /** * Whether changes should include the file resource if the file is still accessible by the user at the time of the request, even when a file was removed from the list of changes and there will be no further change entries for this file. */ includeCorpusRemovals?: boolean; /** * Whether both My Drive and shared drive items should be included in results. */ includeItemsFromAllDrives?: boolean; /** * Specifies which additional view's permissions to include in the response. Only 'published' is supported. */ includePermissionsForView?: string; /** * Whether to include changes indicating that items have been removed from the list of changes, for example by deletion or loss of access. */ includeRemoved?: boolean; /** * Deprecated use includeItemsFromAllDrives instead. */ includeTeamDriveItems?: boolean; /** * The maximum number of changes to return per page. */ pageSize?: number; /** * The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response or to the response from the getStartPageToken method. */ pageToken?: string; /** * Whether to restrict the results to changes inside the My Drive hierarchy. This omits changes to files such as those in the Application Data folder or shared files which have not been added to My Drive. */ restrictToMyDrive?: boolean; /** * A comma-separated list of spaces to query within the user corpus. Supported values are 'drive', 'appDataFolder' and 'photos'. */ spaces?: string; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; /** * Deprecated use driveId instead. */ teamDriveId?: string; } export interface Params$Resource$Changes$Watch extends StandardParameters { /** * The shared drive from which changes are returned. If specified the change IDs will be reflective of the shared drive; use the combined drive ID and change ID as an identifier. */ driveId?: string; /** * Whether changes should include the file resource if the file is still accessible by the user at the time of the request, even when a file was removed from the list of changes and there will be no further change entries for this file. */ includeCorpusRemovals?: boolean; /** * Whether both My Drive and shared drive items should be included in results. */ includeItemsFromAllDrives?: boolean; /** * Specifies which additional view's permissions to include in the response. Only 'published' is supported. */ includePermissionsForView?: string; /** * Whether to include changes indicating that items have been removed from the list of changes, for example by deletion or loss of access. */ includeRemoved?: boolean; /** * Deprecated use includeItemsFromAllDrives instead. */ includeTeamDriveItems?: boolean; /** * The maximum number of changes to return per page. */ pageSize?: number; /** * The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response or to the response from the getStartPageToken method. */ pageToken?: string; /** * Whether to restrict the results to changes inside the My Drive hierarchy. This omits changes to files such as those in the Application Data folder or shared files which have not been added to My Drive. */ restrictToMyDrive?: boolean; /** * A comma-separated list of spaces to query within the user corpus. Supported values are 'drive', 'appDataFolder' and 'photos'. */ spaces?: string; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; /** * Deprecated use driveId instead. */ teamDriveId?: string; /** * Request body metadata */ requestBody?: Schema$Channel; } export class Resource$Channels { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Stop watching resources through this channel * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.metadata', * 'https://www.googleapis.com/auth/drive.metadata.readonly', * 'https://www.googleapis.com/auth/drive.photos.readonly', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.channels.stop({ * // Request body metadata * requestBody: { * // request body parameters * // { * // "address": "my_address", * // "expiration": "my_expiration", * // "id": "my_id", * // "kind": "my_kind", * // "params": {}, * // "payload": false, * // "resourceId": "my_resourceId", * // "resourceUri": "my_resourceUri", * // "token": "my_token", * // "type": "my_type" * // } * }, * }); * console.log(res.data); * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ stop( params: Params$Resource$Channels$Stop, options: StreamMethodOptions ): GaxiosPromise<Readable>; stop( params?: Params$Resource$Channels$Stop, options?: MethodOptions ): GaxiosPromise<void>; stop( params: Params$Resource$Channels$Stop, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; stop( params: Params$Resource$Channels$Stop, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void> ): void; stop( params: Params$Resource$Channels$Stop, callback: BodyResponseCallback<void> ): void; stop(callback: BodyResponseCallback<void>): void; stop( paramsOrCallback?: | Params$Resource$Channels$Stop | BodyResponseCallback<void> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<void> | BodyResponseCallback<Readable>, callback?: BodyResponseCallback<void> | BodyResponseCallback<Readable> ): void | GaxiosPromise<void> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Channels$Stop; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Channels$Stop; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/channels/stop').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<void>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<void>(parameters); } } } export interface Params$Resource$Channels$Stop extends StandardParameters { /** * Request body metadata */ requestBody?: Schema$Channel; } export class Resource$Comments { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Creates a new comment on a file. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.comments.create({ * // The ID of the file. * fileId: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "anchor": "my_anchor", * // "author": {}, * // "content": "my_content", * // "createdTime": "my_createdTime", * // "deleted": false, * // "htmlContent": "my_htmlContent", * // "id": "my_id", * // "kind": "my_kind", * // "modifiedTime": "my_modifiedTime", * // "quotedFileContent": {}, * // "replies": [], * // "resolved": false * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "anchor": "my_anchor", * // "author": {}, * // "content": "my_content", * // "createdTime": "my_createdTime", * // "deleted": false, * // "htmlContent": "my_htmlContent", * // "id": "my_id", * // "kind": "my_kind", * // "modifiedTime": "my_modifiedTime", * // "quotedFileContent": {}, * // "replies": [], * // "resolved": false * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Comments$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Comments$Create, options?: MethodOptions ): GaxiosPromise<Schema$Comment>; create( params: Params$Resource$Comments$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Comments$Create, options: MethodOptions | BodyResponseCallback<Schema$Comment>, callback: BodyResponseCallback<Schema$Comment> ): void; create( params: Params$Resource$Comments$Create, callback: BodyResponseCallback<Schema$Comment> ): void; create(callback: BodyResponseCallback<Schema$Comment>): void; create( paramsOrCallback?: | Params$Resource$Comments$Create | BodyResponseCallback<Schema$Comment> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Comment> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Comment> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Comment> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Comments$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Comments$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files/{fileId}/comments').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['fileId'], pathParams: ['fileId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Comment>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Comment>(parameters); } } /** * Deletes a comment. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.comments.delete({ * // The ID of the comment. * commentId: 'placeholder-value', * // The ID of the file. * fileId: 'placeholder-value', * }); * console.log(res.data); * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Comments$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Comments$Delete, options?: MethodOptions ): GaxiosPromise<void>; delete( params: Params$Resource$Comments$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Comments$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void> ): void; delete( params: Params$Resource$Comments$Delete, callback: BodyResponseCallback<void> ): void; delete(callback: BodyResponseCallback<void>): void; delete( paramsOrCallback?: | Params$Resource$Comments$Delete | BodyResponseCallback<void> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<void> | BodyResponseCallback<Readable>, callback?: BodyResponseCallback<void> | BodyResponseCallback<Readable> ): void | GaxiosPromise<void> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Comments$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Comments$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/drive/v3/files/{fileId}/comments/{commentId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['fileId', 'commentId'], pathParams: ['commentId', 'fileId'], context: this.context, }; if (callback) { createAPIRequest<void>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<void>(parameters); } } /** * Gets a comment by ID. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.comments.get({ * // The ID of the comment. * commentId: 'placeholder-value', * // The ID of the file. * fileId: 'placeholder-value', * // Whether to return deleted comments. Deleted comments will not include their original content. * includeDeleted: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "anchor": "my_anchor", * // "author": {}, * // "content": "my_content", * // "createdTime": "my_createdTime", * // "deleted": false, * // "htmlContent": "my_htmlContent", * // "id": "my_id", * // "kind": "my_kind", * // "modifiedTime": "my_modifiedTime", * // "quotedFileContent": {}, * // "replies": [], * // "resolved": false * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Comments$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Comments$Get, options?: MethodOptions ): GaxiosPromise<Schema$Comment>; get( params: Params$Resource$Comments$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Comments$Get, options: MethodOptions | BodyResponseCallback<Schema$Comment>, callback: BodyResponseCallback<Schema$Comment> ): void; get( params: Params$Resource$Comments$Get, callback: BodyResponseCallback<Schema$Comment> ): void; get(callback: BodyResponseCallback<Schema$Comment>): void; get( paramsOrCallback?: | Params$Resource$Comments$Get | BodyResponseCallback<Schema$Comment> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Comment> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Comment> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Comment> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Comments$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Comments$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/drive/v3/files/{fileId}/comments/{commentId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['fileId', 'commentId'], pathParams: ['commentId', 'fileId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Comment>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Comment>(parameters); } } /** * Lists a file's comments. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.comments.list({ * // The ID of the file. * fileId: 'placeholder-value', * // Whether to include deleted comments. Deleted comments will not include their original content. * includeDeleted: 'placeholder-value', * // The maximum number of comments to return per page. * pageSize: 'placeholder-value', * // The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. * pageToken: 'placeholder-value', * // The minimum value of 'modifiedTime' for the result comments (RFC 3339 date-time). * startModifiedTime: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "comments": [], * // "kind": "my_kind", * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Comments$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Comments$List, options?: MethodOptions ): GaxiosPromise<Schema$CommentList>; list( params: Params$Resource$Comments$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Comments$List, options: MethodOptions | BodyResponseCallback<Schema$CommentList>, callback: BodyResponseCallback<Schema$CommentList> ): void; list( params: Params$Resource$Comments$List, callback: BodyResponseCallback<Schema$CommentList> ): void; list(callback: BodyResponseCallback<Schema$CommentList>): void; list( paramsOrCallback?: | Params$Resource$Comments$List | BodyResponseCallback<Schema$CommentList> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$CommentList> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$CommentList> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$CommentList> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Comments$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Comments$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files/{fileId}/comments').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['fileId'], pathParams: ['fileId'], context: this.context, }; if (callback) { createAPIRequest<Schema$CommentList>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$CommentList>(parameters); } } /** * Updates a comment with patch semantics. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.comments.update({ * // The ID of the comment. * commentId: 'placeholder-value', * // The ID of the file. * fileId: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "anchor": "my_anchor", * // "author": {}, * // "content": "my_content", * // "createdTime": "my_createdTime", * // "deleted": false, * // "htmlContent": "my_htmlContent", * // "id": "my_id", * // "kind": "my_kind", * // "modifiedTime": "my_modifiedTime", * // "quotedFileContent": {}, * // "replies": [], * // "resolved": false * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "anchor": "my_anchor", * // "author": {}, * // "content": "my_content", * // "createdTime": "my_createdTime", * // "deleted": false, * // "htmlContent": "my_htmlContent", * // "id": "my_id", * // "kind": "my_kind", * // "modifiedTime": "my_modifiedTime", * // "quotedFileContent": {}, * // "replies": [], * // "resolved": false * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ update( params: Params$Resource$Comments$Update, options: StreamMethodOptions ): GaxiosPromise<Readable>; update( params?: Params$Resource$Comments$Update, options?: MethodOptions ): GaxiosPromise<Schema$Comment>; update( params: Params$Resource$Comments$Update, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; update( params: Params$Resource$Comments$Update, options: MethodOptions | BodyResponseCallback<Schema$Comment>, callback: BodyResponseCallback<Schema$Comment> ): void; update( params: Params$Resource$Comments$Update, callback: BodyResponseCallback<Schema$Comment> ): void; update(callback: BodyResponseCallback<Schema$Comment>): void; update( paramsOrCallback?: | Params$Resource$Comments$Update | BodyResponseCallback<Schema$Comment> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Comment> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Comment> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Comment> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Comments$Update; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Comments$Update; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/drive/v3/files/{fileId}/comments/{commentId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['fileId', 'commentId'], pathParams: ['commentId', 'fileId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Comment>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Comment>(parameters); } } } export interface Params$Resource$Comments$Create extends StandardParameters { /** * The ID of the file. */ fileId?: string; /** * Request body metadata */ requestBody?: Schema$Comment; } export interface Params$Resource$Comments$Delete extends StandardParameters { /** * The ID of the comment. */ commentId?: string; /** * The ID of the file. */ fileId?: string; } export interface Params$Resource$Comments$Get extends StandardParameters { /** * The ID of the comment. */ commentId?: string; /** * The ID of the file. */ fileId?: string; /** * Whether to return deleted comments. Deleted comments will not include their original content. */ includeDeleted?: boolean; } export interface Params$Resource$Comments$List extends StandardParameters { /** * The ID of the file. */ fileId?: string; /** * Whether to include deleted comments. Deleted comments will not include their original content. */ includeDeleted?: boolean; /** * The maximum number of comments to return per page. */ pageSize?: number; /** * The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. */ pageToken?: string; /** * The minimum value of 'modifiedTime' for the result comments (RFC 3339 date-time). */ startModifiedTime?: string; } export interface Params$Resource$Comments$Update extends StandardParameters { /** * The ID of the comment. */ commentId?: string; /** * The ID of the file. */ fileId?: string; /** * Request body metadata */ requestBody?: Schema$Comment; } export class Resource$Drives { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Creates a new shared drive. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/drive'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.drives.create({ * // An ID, such as a random UUID, which uniquely identifies this user's request for idempotent creation of a shared drive. A repeated request by the same user and with the same request ID will avoid creating duplicates by attempting to create the same shared drive. If the shared drive already exists a 409 error will be returned. * requestId: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "backgroundImageFile": {}, * // "backgroundImageLink": "my_backgroundImageLink", * // "capabilities": {}, * // "colorRgb": "my_colorRgb", * // "createdTime": "my_createdTime", * // "hidden": false, * // "id": "my_id", * // "kind": "my_kind", * // "name": "my_name", * // "restrictions": {}, * // "themeId": "my_themeId" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "backgroundImageFile": {}, * // "backgroundImageLink": "my_backgroundImageLink", * // "capabilities": {}, * // "colorRgb": "my_colorRgb", * // "createdTime": "my_createdTime", * // "hidden": false, * // "id": "my_id", * // "kind": "my_kind", * // "name": "my_name", * // "restrictions": {}, * // "themeId": "my_themeId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Drives$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Drives$Create, options?: MethodOptions ): GaxiosPromise<Schema$Drive>; create( params: Params$Resource$Drives$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Drives$Create, options: MethodOptions | BodyResponseCallback<Schema$Drive>, callback: BodyResponseCallback<Schema$Drive> ): void; create( params: Params$Resource$Drives$Create, callback: BodyResponseCallback<Schema$Drive> ): void; create(callback: BodyResponseCallback<Schema$Drive>): void; create( paramsOrCallback?: | Params$Resource$Drives$Create | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Drive> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Drives$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Drives$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/drives').replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, requiredParams: ['requestId'], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$Drive>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Drive>(parameters); } } /** * Permanently deletes a shared drive for which the user is an organizer. The shared drive cannot contain any untrashed items. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/drive'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.drives.delete({ * // The ID of the shared drive. * driveId: 'placeholder-value', * }); * console.log(res.data); * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Drives$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Drives$Delete, options?: MethodOptions ): GaxiosPromise<void>; delete( params: Params$Resource$Drives$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Drives$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void> ): void; delete( params: Params$Resource$Drives$Delete, callback: BodyResponseCallback<void> ): void; delete(callback: BodyResponseCallback<void>): void; delete( paramsOrCallback?: | Params$Resource$Drives$Delete | BodyResponseCallback<void> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<void> | BodyResponseCallback<Readable>, callback?: BodyResponseCallback<void> | BodyResponseCallback<Readable> ): void | GaxiosPromise<void> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Drives$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Drives$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/drives/{driveId}').replace( /([^:]\/)\/+/g, '$1' ), method: 'DELETE', }, options ), params, requiredParams: ['driveId'], pathParams: ['driveId'], context: this.context, }; if (callback) { createAPIRequest<void>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<void>(parameters); } } /** * Gets a shared drive's metadata by ID. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.drives.get({ * // The ID of the shared drive. * driveId: 'placeholder-value', * // Issue the request as a domain administrator; if set to true, then the requester will be granted access if they are an administrator of the domain to which the shared drive belongs. * useDomainAdminAccess: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "backgroundImageFile": {}, * // "backgroundImageLink": "my_backgroundImageLink", * // "capabilities": {}, * // "colorRgb": "my_colorRgb", * // "createdTime": "my_createdTime", * // "hidden": false, * // "id": "my_id", * // "kind": "my_kind", * // "name": "my_name", * // "restrictions": {}, * // "themeId": "my_themeId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Drives$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Drives$Get, options?: MethodOptions ): GaxiosPromise<Schema$Drive>; get( params: Params$Resource$Drives$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Drives$Get, options: MethodOptions | BodyResponseCallback<Schema$Drive>, callback: BodyResponseCallback<Schema$Drive> ): void; get( params: Params$Resource$Drives$Get, callback: BodyResponseCallback<Schema$Drive> ): void; get(callback: BodyResponseCallback<Schema$Drive>): void; get( paramsOrCallback?: | Params$Resource$Drives$Get | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Drive> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Drives$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Drives$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/drives/{driveId}').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['driveId'], pathParams: ['driveId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Drive>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Drive>(parameters); } } /** * Hides a shared drive from the default view. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/drive'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.drives.hide({ * // The ID of the shared drive. * driveId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "backgroundImageFile": {}, * // "backgroundImageLink": "my_backgroundImageLink", * // "capabilities": {}, * // "colorRgb": "my_colorRgb", * // "createdTime": "my_createdTime", * // "hidden": false, * // "id": "my_id", * // "kind": "my_kind", * // "name": "my_name", * // "restrictions": {}, * // "themeId": "my_themeId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ hide( params: Params$Resource$Drives$Hide, options: StreamMethodOptions ): GaxiosPromise<Readable>; hide( params?: Params$Resource$Drives$Hide, options?: MethodOptions ): GaxiosPromise<Schema$Drive>; hide( params: Params$Resource$Drives$Hide, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; hide( params: Params$Resource$Drives$Hide, options: MethodOptions | BodyResponseCallback<Schema$Drive>, callback: BodyResponseCallback<Schema$Drive> ): void; hide( params: Params$Resource$Drives$Hide, callback: BodyResponseCallback<Schema$Drive> ): void; hide(callback: BodyResponseCallback<Schema$Drive>): void; hide( paramsOrCallback?: | Params$Resource$Drives$Hide | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Drive> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Drives$Hide; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Drives$Hide; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/drives/{driveId}/hide').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['driveId'], pathParams: ['driveId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Drive>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Drive>(parameters); } } /** * Lists the user's shared drives. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.drives.list({ * // Maximum number of shared drives to return per page. * pageSize: 'placeholder-value', * // Page token for shared drives. * pageToken: 'placeholder-value', * // Query string for searching shared drives. * q: 'placeholder-value', * // Issue the request as a domain administrator; if set to true, then all shared drives of the domain in which the requester is an administrator are returned. * useDomainAdminAccess: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "drives": [], * // "kind": "my_kind", * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Drives$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Drives$List, options?: MethodOptions ): GaxiosPromise<Schema$DriveList>; list( params: Params$Resource$Drives$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Drives$List, options: MethodOptions | BodyResponseCallback<Schema$DriveList>, callback: BodyResponseCallback<Schema$DriveList> ): void; list( params: Params$Resource$Drives$List, callback: BodyResponseCallback<Schema$DriveList> ): void; list(callback: BodyResponseCallback<Schema$DriveList>): void; list( paramsOrCallback?: | Params$Resource$Drives$List | BodyResponseCallback<Schema$DriveList> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$DriveList> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$DriveList> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$DriveList> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Drives$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Drives$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/drives').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$DriveList>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$DriveList>(parameters); } } /** * Restores a shared drive to the default view. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/drive'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.drives.unhide({ * // The ID of the shared drive. * driveId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "backgroundImageFile": {}, * // "backgroundImageLink": "my_backgroundImageLink", * // "capabilities": {}, * // "colorRgb": "my_colorRgb", * // "createdTime": "my_createdTime", * // "hidden": false, * // "id": "my_id", * // "kind": "my_kind", * // "name": "my_name", * // "restrictions": {}, * // "themeId": "my_themeId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ unhide( params: Params$Resource$Drives$Unhide, options: StreamMethodOptions ): GaxiosPromise<Readable>; unhide( params?: Params$Resource$Drives$Unhide, options?: MethodOptions ): GaxiosPromise<Schema$Drive>; unhide( params: Params$Resource$Drives$Unhide, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; unhide( params: Params$Resource$Drives$Unhide, options: MethodOptions | BodyResponseCallback<Schema$Drive>, callback: BodyResponseCallback<Schema$Drive> ): void; unhide( params: Params$Resource$Drives$Unhide, callback: BodyResponseCallback<Schema$Drive> ): void; unhide(callback: BodyResponseCallback<Schema$Drive>): void; unhide( paramsOrCallback?: | Params$Resource$Drives$Unhide | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Drive> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Drives$Unhide; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Drives$Unhide; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/drives/{driveId}/unhide').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['driveId'], pathParams: ['driveId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Drive>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Drive>(parameters); } } /** * Updates the metadate for a shared drive. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/drive'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.drives.update({ * // The ID of the shared drive. * driveId: 'placeholder-value', * // Issue the request as a domain administrator; if set to true, then the requester will be granted access if they are an administrator of the domain to which the shared drive belongs. * useDomainAdminAccess: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "backgroundImageFile": {}, * // "backgroundImageLink": "my_backgroundImageLink", * // "capabilities": {}, * // "colorRgb": "my_colorRgb", * // "createdTime": "my_createdTime", * // "hidden": false, * // "id": "my_id", * // "kind": "my_kind", * // "name": "my_name", * // "restrictions": {}, * // "themeId": "my_themeId" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "backgroundImageFile": {}, * // "backgroundImageLink": "my_backgroundImageLink", * // "capabilities": {}, * // "colorRgb": "my_colorRgb", * // "createdTime": "my_createdTime", * // "hidden": false, * // "id": "my_id", * // "kind": "my_kind", * // "name": "my_name", * // "restrictions": {}, * // "themeId": "my_themeId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ update( params: Params$Resource$Drives$Update, options: StreamMethodOptions ): GaxiosPromise<Readable>; update( params?: Params$Resource$Drives$Update, options?: MethodOptions ): GaxiosPromise<Schema$Drive>; update( params: Params$Resource$Drives$Update, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; update( params: Params$Resource$Drives$Update, options: MethodOptions | BodyResponseCallback<Schema$Drive>, callback: BodyResponseCallback<Schema$Drive> ): void; update( params: Params$Resource$Drives$Update, callback: BodyResponseCallback<Schema$Drive> ): void; update(callback: BodyResponseCallback<Schema$Drive>): void; update( paramsOrCallback?: | Params$Resource$Drives$Update | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Drive> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Drive> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Drives$Update; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Drives$Update; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/drives/{driveId}').replace( /([^:]\/)\/+/g, '$1' ), method: 'PATCH', }, options ), params, requiredParams: ['driveId'], pathParams: ['driveId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Drive>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Drive>(parameters); } } } export interface Params$Resource$Drives$Create extends StandardParameters { /** * An ID, such as a random UUID, which uniquely identifies this user's request for idempotent creation of a shared drive. A repeated request by the same user and with the same request ID will avoid creating duplicates by attempting to create the same shared drive. If the shared drive already exists a 409 error will be returned. */ requestId?: string; /** * Request body metadata */ requestBody?: Schema$Drive; } export interface Params$Resource$Drives$Delete extends StandardParameters { /** * The ID of the shared drive. */ driveId?: string; } export interface Params$Resource$Drives$Get extends StandardParameters { /** * The ID of the shared drive. */ driveId?: string; /** * Issue the request as a domain administrator; if set to true, then the requester will be granted access if they are an administrator of the domain to which the shared drive belongs. */ useDomainAdminAccess?: boolean; } export interface Params$Resource$Drives$Hide extends StandardParameters { /** * The ID of the shared drive. */ driveId?: string; } export interface Params$Resource$Drives$List extends StandardParameters { /** * Maximum number of shared drives to return per page. */ pageSize?: number; /** * Page token for shared drives. */ pageToken?: string; /** * Query string for searching shared drives. */ q?: string; /** * Issue the request as a domain administrator; if set to true, then all shared drives of the domain in which the requester is an administrator are returned. */ useDomainAdminAccess?: boolean; } export interface Params$Resource$Drives$Unhide extends StandardParameters { /** * The ID of the shared drive. */ driveId?: string; } export interface Params$Resource$Drives$Update extends StandardParameters { /** * The ID of the shared drive. */ driveId?: string; /** * Issue the request as a domain administrator; if set to true, then the requester will be granted access if they are an administrator of the domain to which the shared drive belongs. */ useDomainAdminAccess?: boolean; /** * Request body metadata */ requestBody?: Schema$Drive; } export class Resource$Files { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Creates a copy of a file and applies any requested updates with patch semantics. Folders cannot be copied. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.photos.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.files.copy({ * // Deprecated. Copying files into multiple folders is no longer supported. Use shortcuts instead. * enforceSingleParent: 'placeholder-value', * // The ID of the file. * fileId: 'placeholder-value', * // Whether to ignore the domain's default visibility settings for the created file. Domain administrators can choose to make all uploaded files visible to the domain by default; this parameter bypasses that behavior for the request. Permissions are still inherited from parent folders. * ignoreDefaultVisibility: 'placeholder-value', * // Specifies which additional view's permissions to include in the response. Only 'published' is supported. * includePermissionsForView: 'placeholder-value', * // Whether to set the 'keepForever' field in the new head revision. This is only applicable to files with binary content in Google Drive. Only 200 revisions for the file can be kept forever. If the limit is reached, try deleting pinned revisions. * keepRevisionForever: 'placeholder-value', * // A language hint for OCR processing during image import (ISO 639-1 code). * ocrLanguage: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "appProperties": {}, * // "capabilities": {}, * // "contentHints": {}, * // "contentRestrictions": [], * // "copyRequiresWriterPermission": false, * // "createdTime": "my_createdTime", * // "description": "my_description", * // "driveId": "my_driveId", * // "explicitlyTrashed": false, * // "exportLinks": {}, * // "fileExtension": "my_fileExtension", * // "folderColorRgb": "my_folderColorRgb", * // "fullFileExtension": "my_fullFileExtension", * // "hasAugmentedPermissions": false, * // "hasThumbnail": false, * // "headRevisionId": "my_headRevisionId", * // "iconLink": "my_iconLink", * // "id": "my_id", * // "imageMediaMetadata": {}, * // "isAppAuthorized": false, * // "kind": "my_kind", * // "lastModifyingUser": {}, * // "linkShareMetadata": {}, * // "md5Checksum": "my_md5Checksum", * // "mimeType": "my_mimeType", * // "modifiedByMe": false, * // "modifiedByMeTime": "my_modifiedByMeTime", * // "modifiedTime": "my_modifiedTime", * // "name": "my_name", * // "originalFilename": "my_originalFilename", * // "ownedByMe": false, * // "owners": [], * // "parents": [], * // "permissionIds": [], * // "permissions": [], * // "properties": {}, * // "quotaBytesUsed": "my_quotaBytesUsed", * // "resourceKey": "my_resourceKey", * // "shared": false, * // "sharedWithMeTime": "my_sharedWithMeTime", * // "sharingUser": {}, * // "shortcutDetails": {}, * // "size": "my_size", * // "spaces": [], * // "starred": false, * // "teamDriveId": "my_teamDriveId", * // "thumbnailLink": "my_thumbnailLink", * // "thumbnailVersion": "my_thumbnailVersion", * // "trashed": false, * // "trashedTime": "my_trashedTime", * // "trashingUser": {}, * // "version": "my_version", * // "videoMediaMetadata": {}, * // "viewedByMe": false, * // "viewedByMeTime": "my_viewedByMeTime", * // "viewersCanCopyContent": false, * // "webContentLink": "my_webContentLink", * // "webViewLink": "my_webViewLink", * // "writersCanShare": false * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "appProperties": {}, * // "capabilities": {}, * // "contentHints": {}, * // "contentRestrictions": [], * // "copyRequiresWriterPermission": false, * // "createdTime": "my_createdTime", * // "description": "my_description", * // "driveId": "my_driveId", * // "explicitlyTrashed": false, * // "exportLinks": {}, * // "fileExtension": "my_fileExtension", * // "folderColorRgb": "my_folderColorRgb", * // "fullFileExtension": "my_fullFileExtension", * // "hasAugmentedPermissions": false, * // "hasThumbnail": false, * // "headRevisionId": "my_headRevisionId", * // "iconLink": "my_iconLink", * // "id": "my_id", * // "imageMediaMetadata": {}, * // "isAppAuthorized": false, * // "kind": "my_kind", * // "lastModifyingUser": {}, * // "linkShareMetadata": {}, * // "md5Checksum": "my_md5Checksum", * // "mimeType": "my_mimeType", * // "modifiedByMe": false, * // "modifiedByMeTime": "my_modifiedByMeTime", * // "modifiedTime": "my_modifiedTime", * // "name": "my_name", * // "originalFilename": "my_originalFilename", * // "ownedByMe": false, * // "owners": [], * // "parents": [], * // "permissionIds": [], * // "permissions": [], * // "properties": {}, * // "quotaBytesUsed": "my_quotaBytesUsed", * // "resourceKey": "my_resourceKey", * // "shared": false, * // "sharedWithMeTime": "my_sharedWithMeTime", * // "sharingUser": {}, * // "shortcutDetails": {}, * // "size": "my_size", * // "spaces": [], * // "starred": false, * // "teamDriveId": "my_teamDriveId", * // "thumbnailLink": "my_thumbnailLink", * // "thumbnailVersion": "my_thumbnailVersion", * // "trashed": false, * // "trashedTime": "my_trashedTime", * // "trashingUser": {}, * // "version": "my_version", * // "videoMediaMetadata": {}, * // "viewedByMe": false, * // "viewedByMeTime": "my_viewedByMeTime", * // "viewersCanCopyContent": false, * // "webContentLink": "my_webContentLink", * // "webViewLink": "my_webViewLink", * // "writersCanShare": false * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ copy( params: Params$Resource$Files$Copy, options: StreamMethodOptions ): GaxiosPromise<Readable>; copy( params?: Params$Resource$Files$Copy, options?: MethodOptions ): GaxiosPromise<Schema$File>; copy( params: Params$Resource$Files$Copy, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; copy( params: Params$Resource$Files$Copy, options: MethodOptions | BodyResponseCallback<Schema$File>, callback: BodyResponseCallback<Schema$File> ): void; copy( params: Params$Resource$Files$Copy, callback: BodyResponseCallback<Schema$File> ): void; copy(callback: BodyResponseCallback<Schema$File>): void; copy( paramsOrCallback?: | Params$Resource$Files$Copy | BodyResponseCallback<Schema$File> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$File> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$File> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$File> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Files$Copy; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Files$Copy; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files/{fileId}/copy').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['fileId'], pathParams: ['fileId'], context: this.context, }; if (callback) { createAPIRequest<Schema$File>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$File>(parameters); } } /** * Creates a new file. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.files.create({ * // Deprecated. Creating files in multiple folders is no longer supported. * enforceSingleParent: 'placeholder-value', * // Whether to ignore the domain's default visibility settings for the created file. Domain administrators can choose to make all uploaded files visible to the domain by default; this parameter bypasses that behavior for the request. Permissions are still inherited from parent folders. * ignoreDefaultVisibility: 'placeholder-value', * // Specifies which additional view's permissions to include in the response. Only 'published' is supported. * includePermissionsForView: 'placeholder-value', * // Whether to set the 'keepForever' field in the new head revision. This is only applicable to files with binary content in Google Drive. Only 200 revisions for the file can be kept forever. If the limit is reached, try deleting pinned revisions. * keepRevisionForever: 'placeholder-value', * // A language hint for OCR processing during image import (ISO 639-1 code). * ocrLanguage: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * // Whether to use the uploaded content as indexable text. * useContentAsIndexableText: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "appProperties": {}, * // "capabilities": {}, * // "contentHints": {}, * // "contentRestrictions": [], * // "copyRequiresWriterPermission": false, * // "createdTime": "my_createdTime", * // "description": "my_description", * // "driveId": "my_driveId", * // "explicitlyTrashed": false, * // "exportLinks": {}, * // "fileExtension": "my_fileExtension", * // "folderColorRgb": "my_folderColorRgb", * // "fullFileExtension": "my_fullFileExtension", * // "hasAugmentedPermissions": false, * // "hasThumbnail": false, * // "headRevisionId": "my_headRevisionId", * // "iconLink": "my_iconLink", * // "id": "my_id", * // "imageMediaMetadata": {}, * // "isAppAuthorized": false, * // "kind": "my_kind", * // "lastModifyingUser": {}, * // "linkShareMetadata": {}, * // "md5Checksum": "my_md5Checksum", * // "mimeType": "my_mimeType", * // "modifiedByMe": false, * // "modifiedByMeTime": "my_modifiedByMeTime", * // "modifiedTime": "my_modifiedTime", * // "name": "my_name", * // "originalFilename": "my_originalFilename", * // "ownedByMe": false, * // "owners": [], * // "parents": [], * // "permissionIds": [], * // "permissions": [], * // "properties": {}, * // "quotaBytesUsed": "my_quotaBytesUsed", * // "resourceKey": "my_resourceKey", * // "shared": false, * // "sharedWithMeTime": "my_sharedWithMeTime", * // "sharingUser": {}, * // "shortcutDetails": {}, * // "size": "my_size", * // "spaces": [], * // "starred": false, * // "teamDriveId": "my_teamDriveId", * // "thumbnailLink": "my_thumbnailLink", * // "thumbnailVersion": "my_thumbnailVersion", * // "trashed": false, * // "trashedTime": "my_trashedTime", * // "trashingUser": {}, * // "version": "my_version", * // "videoMediaMetadata": {}, * // "viewedByMe": false, * // "viewedByMeTime": "my_viewedByMeTime", * // "viewersCanCopyContent": false, * // "webContentLink": "my_webContentLink", * // "webViewLink": "my_webViewLink", * // "writersCanShare": false * // } * }, * media: { * mimeType: 'placeholder-value', * body: 'placeholder-value', * }, * }); * console.log(res.data); * * // Example response * // { * // "appProperties": {}, * // "capabilities": {}, * // "contentHints": {}, * // "contentRestrictions": [], * // "copyRequiresWriterPermission": false, * // "createdTime": "my_createdTime", * // "description": "my_description", * // "driveId": "my_driveId", * // "explicitlyTrashed": false, * // "exportLinks": {}, * // "fileExtension": "my_fileExtension", * // "folderColorRgb": "my_folderColorRgb", * // "fullFileExtension": "my_fullFileExtension", * // "hasAugmentedPermissions": false, * // "hasThumbnail": false, * // "headRevisionId": "my_headRevisionId", * // "iconLink": "my_iconLink", * // "id": "my_id", * // "imageMediaMetadata": {}, * // "isAppAuthorized": false, * // "kind": "my_kind", * // "lastModifyingUser": {}, * // "linkShareMetadata": {}, * // "md5Checksum": "my_md5Checksum", * // "mimeType": "my_mimeType", * // "modifiedByMe": false, * // "modifiedByMeTime": "my_modifiedByMeTime", * // "modifiedTime": "my_modifiedTime", * // "name": "my_name", * // "originalFilename": "my_originalFilename", * // "ownedByMe": false, * // "owners": [], * // "parents": [], * // "permissionIds": [], * // "permissions": [], * // "properties": {}, * // "quotaBytesUsed": "my_quotaBytesUsed", * // "resourceKey": "my_resourceKey", * // "shared": false, * // "sharedWithMeTime": "my_sharedWithMeTime", * // "sharingUser": {}, * // "shortcutDetails": {}, * // "size": "my_size", * // "spaces": [], * // "starred": false, * // "teamDriveId": "my_teamDriveId", * // "thumbnailLink": "my_thumbnailLink", * // "thumbnailVersion": "my_thumbnailVersion", * // "trashed": false, * // "trashedTime": "my_trashedTime", * // "trashingUser": {}, * // "version": "my_version", * // "videoMediaMetadata": {}, * // "viewedByMe": false, * // "viewedByMeTime": "my_viewedByMeTime", * // "viewersCanCopyContent": false, * // "webContentLink": "my_webContentLink", * // "webViewLink": "my_webViewLink", * // "writersCanShare": false * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Files$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Files$Create, options?: MethodOptions ): GaxiosPromise<Schema$File>; create( params: Params$Resource$Files$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Files$Create, options: MethodOptions | BodyResponseCallback<Schema$File>, callback: BodyResponseCallback<Schema$File> ): void; create( params: Params$Resource$Files$Create, callback: BodyResponseCallback<Schema$File> ): void; create(callback: BodyResponseCallback<Schema$File>): void; create( paramsOrCallback?: | Params$Resource$Files$Create | BodyResponseCallback<Schema$File> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$File> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$File> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$File> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Files$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Files$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files').replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, mediaUrl: (rootUrl + '/upload/drive/v3/files').replace( /([^:]\/)\/+/g, '$1' ), requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$File>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$File>(parameters); } } /** * Permanently deletes a file owned by the user without moving it to the trash. If the file belongs to a shared drive the user must be an organizer on the parent. If the target is a folder, all descendants owned by the user are also deleted. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.files.delete({ * // Deprecated. If an item is not in a shared drive and its last parent is deleted but the item itself is not, the item will be placed under its owner's root. * enforceSingleParent: 'placeholder-value', * // The ID of the file. * fileId: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * }); * console.log(res.data); * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Files$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Files$Delete, options?: MethodOptions ): GaxiosPromise<void>; delete( params: Params$Resource$Files$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Files$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void> ): void; delete( params: Params$Resource$Files$Delete, callback: BodyResponseCallback<void> ): void; delete(callback: BodyResponseCallback<void>): void; delete( paramsOrCallback?: | Params$Resource$Files$Delete | BodyResponseCallback<void> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<void> | BodyResponseCallback<Readable>, callback?: BodyResponseCallback<void> | BodyResponseCallback<Readable> ): void | GaxiosPromise<void> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Files$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Files$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files/{fileId}').replace( /([^:]\/)\/+/g, '$1' ), method: 'DELETE', }, options ), params, requiredParams: ['fileId'], pathParams: ['fileId'], context: this.context, }; if (callback) { createAPIRequest<void>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<void>(parameters); } } /** * Permanently deletes all of the user's trashed files. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/drive'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.files.emptyTrash({ * // Deprecated. If an item is not in a shared drive and its last parent is deleted but the item itself is not, the item will be placed under its owner's root. * enforceSingleParent: 'placeholder-value', * }); * console.log(res.data); * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ emptyTrash( params: Params$Resource$Files$Emptytrash, options: StreamMethodOptions ): GaxiosPromise<Readable>; emptyTrash( params?: Params$Resource$Files$Emptytrash, options?: MethodOptions ): GaxiosPromise<void>; emptyTrash( params: Params$Resource$Files$Emptytrash, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; emptyTrash( params: Params$Resource$Files$Emptytrash, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void> ): void; emptyTrash( params: Params$Resource$Files$Emptytrash, callback: BodyResponseCallback<void> ): void; emptyTrash(callback: BodyResponseCallback<void>): void; emptyTrash( paramsOrCallback?: | Params$Resource$Files$Emptytrash | BodyResponseCallback<void> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<void> | BodyResponseCallback<Readable>, callback?: BodyResponseCallback<void> | BodyResponseCallback<Readable> ): void | GaxiosPromise<void> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Files$Emptytrash; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Files$Emptytrash; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files/trash').replace( /([^:]\/)\/+/g, '$1' ), method: 'DELETE', }, options ), params, requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<void>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<void>(parameters); } } /** * Exports a Google Workspace document to the requested MIME type and returns exported byte content. Note that the exported content is limited to 10MB. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.files.export({ * // The ID of the file. * fileId: 'placeholder-value', * // The MIME type of the format requested for this export. * mimeType: 'placeholder-value', * }); * console.log(res.data); * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ export( params: Params$Resource$Files$Export, options: StreamMethodOptions ): GaxiosPromise<Readable>; export( params?: Params$Resource$Files$Export, options?: MethodOptions ): GaxiosPromise<unknown>; export( params: Params$Resource$Files$Export, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; export( params: Params$Resource$Files$Export, options: MethodOptions | BodyResponseCallback<unknown>, callback: BodyResponseCallback<unknown> ): void; export( params: Params$Resource$Files$Export, callback: BodyResponseCallback<unknown> ): void; export(callback: BodyResponseCallback<unknown>): void; export( paramsOrCallback?: | Params$Resource$Files$Export | BodyResponseCallback<unknown> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<unknown> | BodyResponseCallback<Readable>, callback?: BodyResponseCallback<unknown> | BodyResponseCallback<Readable> ): void | GaxiosPromise<unknown> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Files$Export; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Files$Export; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files/{fileId}/export').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['fileId', 'mimeType'], pathParams: ['fileId'], context: this.context, }; if (callback) { createAPIRequest<unknown>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<unknown>(parameters); } } /** * Generates a set of file IDs which can be provided in create or copy requests. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.files.generateIds({ * // The number of IDs to return. * count: 'placeholder-value', * // The space in which the IDs can be used to create new files. Supported values are 'drive' and 'appDataFolder'. (Default: 'drive') * space: 'placeholder-value', * // The type of items which the IDs can be used for. Supported values are 'files' and 'shortcuts'. Note that 'shortcuts' are only supported in the drive 'space'. (Default: 'files') * type: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "ids": [], * // "kind": "my_kind", * // "space": "my_space" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ generateIds( params: Params$Resource$Files$Generateids, options: StreamMethodOptions ): GaxiosPromise<Readable>; generateIds( params?: Params$Resource$Files$Generateids, options?: MethodOptions ): GaxiosPromise<Schema$GeneratedIds>; generateIds( params: Params$Resource$Files$Generateids, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; generateIds( params: Params$Resource$Files$Generateids, options: MethodOptions | BodyResponseCallback<Schema$GeneratedIds>, callback: BodyResponseCallback<Schema$GeneratedIds> ): void; generateIds( params: Params$Resource$Files$Generateids, callback: BodyResponseCallback<Schema$GeneratedIds> ): void; generateIds(callback: BodyResponseCallback<Schema$GeneratedIds>): void; generateIds( paramsOrCallback?: | Params$Resource$Files$Generateids | BodyResponseCallback<Schema$GeneratedIds> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GeneratedIds> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GeneratedIds> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$GeneratedIds> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Files$Generateids; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Files$Generateids; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files/generateIds').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$GeneratedIds>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GeneratedIds>(parameters); } } /** * Gets a file's metadata or content by ID. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.metadata', * 'https://www.googleapis.com/auth/drive.metadata.readonly', * 'https://www.googleapis.com/auth/drive.photos.readonly', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.files.get({ * // Whether the user is acknowledging the risk of downloading known malware or other abusive files. This is only applicable when alt=media. * acknowledgeAbuse: 'placeholder-value', * // The ID of the file. * fileId: 'placeholder-value', * // Specifies which additional view's permissions to include in the response. Only 'published' is supported. * includePermissionsForView: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "appProperties": {}, * // "capabilities": {}, * // "contentHints": {}, * // "contentRestrictions": [], * // "copyRequiresWriterPermission": false, * // "createdTime": "my_createdTime", * // "description": "my_description", * // "driveId": "my_driveId", * // "explicitlyTrashed": false, * // "exportLinks": {}, * // "fileExtension": "my_fileExtension", * // "folderColorRgb": "my_folderColorRgb", * // "fullFileExtension": "my_fullFileExtension", * // "hasAugmentedPermissions": false, * // "hasThumbnail": false, * // "headRevisionId": "my_headRevisionId", * // "iconLink": "my_iconLink", * // "id": "my_id", * // "imageMediaMetadata": {}, * // "isAppAuthorized": false, * // "kind": "my_kind", * // "lastModifyingUser": {}, * // "linkShareMetadata": {}, * // "md5Checksum": "my_md5Checksum", * // "mimeType": "my_mimeType", * // "modifiedByMe": false, * // "modifiedByMeTime": "my_modifiedByMeTime", * // "modifiedTime": "my_modifiedTime", * // "name": "my_name", * // "originalFilename": "my_originalFilename", * // "ownedByMe": false, * // "owners": [], * // "parents": [], * // "permissionIds": [], * // "permissions": [], * // "properties": {}, * // "quotaBytesUsed": "my_quotaBytesUsed", * // "resourceKey": "my_resourceKey", * // "shared": false, * // "sharedWithMeTime": "my_sharedWithMeTime", * // "sharingUser": {}, * // "shortcutDetails": {}, * // "size": "my_size", * // "spaces": [], * // "starred": false, * // "teamDriveId": "my_teamDriveId", * // "thumbnailLink": "my_thumbnailLink", * // "thumbnailVersion": "my_thumbnailVersion", * // "trashed": false, * // "trashedTime": "my_trashedTime", * // "trashingUser": {}, * // "version": "my_version", * // "videoMediaMetadata": {}, * // "viewedByMe": false, * // "viewedByMeTime": "my_viewedByMeTime", * // "viewersCanCopyContent": false, * // "webContentLink": "my_webContentLink", * // "webViewLink": "my_webViewLink", * // "writersCanShare": false * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Files$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Files$Get, options?: MethodOptions ): GaxiosPromise<Schema$File>; get( params: Params$Resource$Files$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Files$Get, options: MethodOptions | BodyResponseCallback<Schema$File>, callback: BodyResponseCallback<Schema$File> ): void; get( params: Params$Resource$Files$Get, callback: BodyResponseCallback<Schema$File> ): void; get(callback: BodyResponseCallback<Schema$File>): void; get( paramsOrCallback?: | Params$Resource$Files$Get | BodyResponseCallback<Schema$File> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$File> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$File> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$File> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Files$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Files$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files/{fileId}').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['fileId'], pathParams: ['fileId'], context: this.context, }; if (callback) { createAPIRequest<Schema$File>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$File>(parameters); } } /** * Lists or searches files. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.metadata', * 'https://www.googleapis.com/auth/drive.metadata.readonly', * 'https://www.googleapis.com/auth/drive.photos.readonly', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.files.list({ * // Groupings of files to which the query applies. Supported groupings are: 'user' (files created by, opened by, or shared directly with the user), 'drive' (files in the specified shared drive as indicated by the 'driveId'), 'domain' (files shared to the user's domain), and 'allDrives' (A combination of 'user' and 'drive' for all drives where the user is a member). When able, use 'user' or 'drive', instead of 'allDrives', for efficiency. * corpora: 'placeholder-value', * // The source of files to list. Deprecated: use 'corpora' instead. * corpus: 'placeholder-value', * // ID of the shared drive to search. * driveId: 'placeholder-value', * // Whether both My Drive and shared drive items should be included in results. * includeItemsFromAllDrives: 'placeholder-value', * // Specifies which additional view's permissions to include in the response. Only 'published' is supported. * includePermissionsForView: 'placeholder-value', * // Deprecated use includeItemsFromAllDrives instead. * includeTeamDriveItems: 'placeholder-value', * // A comma-separated list of sort keys. Valid keys are 'createdTime', 'folder', 'modifiedByMeTime', 'modifiedTime', 'name', 'name_natural', 'quotaBytesUsed', 'recency', 'sharedWithMeTime', 'starred', and 'viewedByMeTime'. Each key sorts ascending by default, but may be reversed with the 'desc' modifier. Example usage: ?orderBy=folder,modifiedTime desc,name. Please note that there is a current limitation for users with approximately one million files in which the requested sort order is ignored. * orderBy: 'placeholder-value', * // The maximum number of files to return per page. Partial or empty result pages are possible even before the end of the files list has been reached. * pageSize: 'placeholder-value', * // The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. * pageToken: 'placeholder-value', * // A query for filtering the file results. See the "Search for Files" guide for supported syntax. * q: 'placeholder-value', * // A comma-separated list of spaces to query within the corpus. Supported values are 'drive' and 'appDataFolder'. * spaces: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * // Deprecated use driveId instead. * teamDriveId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "files": [], * // "incompleteSearch": false, * // "kind": "my_kind", * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Files$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Files$List, options?: MethodOptions ): GaxiosPromise<Schema$FileList>; list( params: Params$Resource$Files$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Files$List, options: MethodOptions | BodyResponseCallback<Schema$FileList>, callback: BodyResponseCallback<Schema$FileList> ): void; list( params: Params$Resource$Files$List, callback: BodyResponseCallback<Schema$FileList> ): void; list(callback: BodyResponseCallback<Schema$FileList>): void; list( paramsOrCallback?: | Params$Resource$Files$List | BodyResponseCallback<Schema$FileList> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$FileList> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$FileList> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$FileList> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Files$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Files$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$FileList>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$FileList>(parameters); } } /** * Updates a file's metadata and/or content. When calling this method, only populate fields in the request that you want to modify. When updating fields, some fields might change automatically, such as modifiedDate. This method supports patch semantics. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.metadata', * 'https://www.googleapis.com/auth/drive.scripts', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.files.update({ * // A comma-separated list of parent IDs to add. * addParents: 'placeholder-value', * // Deprecated. Adding files to multiple folders is no longer supported. Use shortcuts instead. * enforceSingleParent: 'placeholder-value', * // The ID of the file. * fileId: 'placeholder-value', * // Specifies which additional view's permissions to include in the response. Only 'published' is supported. * includePermissionsForView: 'placeholder-value', * // Whether to set the 'keepForever' field in the new head revision. This is only applicable to files with binary content in Google Drive. Only 200 revisions for the file can be kept forever. If the limit is reached, try deleting pinned revisions. * keepRevisionForever: 'placeholder-value', * // A language hint for OCR processing during image import (ISO 639-1 code). * ocrLanguage: 'placeholder-value', * // A comma-separated list of parent IDs to remove. * removeParents: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * // Whether to use the uploaded content as indexable text. * useContentAsIndexableText: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "appProperties": {}, * // "capabilities": {}, * // "contentHints": {}, * // "contentRestrictions": [], * // "copyRequiresWriterPermission": false, * // "createdTime": "my_createdTime", * // "description": "my_description", * // "driveId": "my_driveId", * // "explicitlyTrashed": false, * // "exportLinks": {}, * // "fileExtension": "my_fileExtension", * // "folderColorRgb": "my_folderColorRgb", * // "fullFileExtension": "my_fullFileExtension", * // "hasAugmentedPermissions": false, * // "hasThumbnail": false, * // "headRevisionId": "my_headRevisionId", * // "iconLink": "my_iconLink", * // "id": "my_id", * // "imageMediaMetadata": {}, * // "isAppAuthorized": false, * // "kind": "my_kind", * // "lastModifyingUser": {}, * // "linkShareMetadata": {}, * // "md5Checksum": "my_md5Checksum", * // "mimeType": "my_mimeType", * // "modifiedByMe": false, * // "modifiedByMeTime": "my_modifiedByMeTime", * // "modifiedTime": "my_modifiedTime", * // "name": "my_name", * // "originalFilename": "my_originalFilename", * // "ownedByMe": false, * // "owners": [], * // "parents": [], * // "permissionIds": [], * // "permissions": [], * // "properties": {}, * // "quotaBytesUsed": "my_quotaBytesUsed", * // "resourceKey": "my_resourceKey", * // "shared": false, * // "sharedWithMeTime": "my_sharedWithMeTime", * // "sharingUser": {}, * // "shortcutDetails": {}, * // "size": "my_size", * // "spaces": [], * // "starred": false, * // "teamDriveId": "my_teamDriveId", * // "thumbnailLink": "my_thumbnailLink", * // "thumbnailVersion": "my_thumbnailVersion", * // "trashed": false, * // "trashedTime": "my_trashedTime", * // "trashingUser": {}, * // "version": "my_version", * // "videoMediaMetadata": {}, * // "viewedByMe": false, * // "viewedByMeTime": "my_viewedByMeTime", * // "viewersCanCopyContent": false, * // "webContentLink": "my_webContentLink", * // "webViewLink": "my_webViewLink", * // "writersCanShare": false * // } * }, * media: { * mimeType: 'placeholder-value', * body: 'placeholder-value', * }, * }); * console.log(res.data); * * // Example response * // { * // "appProperties": {}, * // "capabilities": {}, * // "contentHints": {}, * // "contentRestrictions": [], * // "copyRequiresWriterPermission": false, * // "createdTime": "my_createdTime", * // "description": "my_description", * // "driveId": "my_driveId", * // "explicitlyTrashed": false, * // "exportLinks": {}, * // "fileExtension": "my_fileExtension", * // "folderColorRgb": "my_folderColorRgb", * // "fullFileExtension": "my_fullFileExtension", * // "hasAugmentedPermissions": false, * // "hasThumbnail": false, * // "headRevisionId": "my_headRevisionId", * // "iconLink": "my_iconLink", * // "id": "my_id", * // "imageMediaMetadata": {}, * // "isAppAuthorized": false, * // "kind": "my_kind", * // "lastModifyingUser": {}, * // "linkShareMetadata": {}, * // "md5Checksum": "my_md5Checksum", * // "mimeType": "my_mimeType", * // "modifiedByMe": false, * // "modifiedByMeTime": "my_modifiedByMeTime", * // "modifiedTime": "my_modifiedTime", * // "name": "my_name", * // "originalFilename": "my_originalFilename", * // "ownedByMe": false, * // "owners": [], * // "parents": [], * // "permissionIds": [], * // "permissions": [], * // "properties": {}, * // "quotaBytesUsed": "my_quotaBytesUsed", * // "resourceKey": "my_resourceKey", * // "shared": false, * // "sharedWithMeTime": "my_sharedWithMeTime", * // "sharingUser": {}, * // "shortcutDetails": {}, * // "size": "my_size", * // "spaces": [], * // "starred": false, * // "teamDriveId": "my_teamDriveId", * // "thumbnailLink": "my_thumbnailLink", * // "thumbnailVersion": "my_thumbnailVersion", * // "trashed": false, * // "trashedTime": "my_trashedTime", * // "trashingUser": {}, * // "version": "my_version", * // "videoMediaMetadata": {}, * // "viewedByMe": false, * // "viewedByMeTime": "my_viewedByMeTime", * // "viewersCanCopyContent": false, * // "webContentLink": "my_webContentLink", * // "webViewLink": "my_webViewLink", * // "writersCanShare": false * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ update( params: Params$Resource$Files$Update, options: StreamMethodOptions ): GaxiosPromise<Readable>; update( params?: Params$Resource$Files$Update, options?: MethodOptions ): GaxiosPromise<Schema$File>; update( params: Params$Resource$Files$Update, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; update( params: Params$Resource$Files$Update, options: MethodOptions | BodyResponseCallback<Schema$File>, callback: BodyResponseCallback<Schema$File> ): void; update( params: Params$Resource$Files$Update, callback: BodyResponseCallback<Schema$File> ): void; update(callback: BodyResponseCallback<Schema$File>): void; update( paramsOrCallback?: | Params$Resource$Files$Update | BodyResponseCallback<Schema$File> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$File> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$File> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$File> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Files$Update; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Files$Update; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files/{fileId}').replace( /([^:]\/)\/+/g, '$1' ), method: 'PATCH', }, options ), params, mediaUrl: (rootUrl + '/upload/drive/v3/files/{fileId}').replace( /([^:]\/)\/+/g, '$1' ), requiredParams: ['fileId'], pathParams: ['fileId'], context: this.context, }; if (callback) { createAPIRequest<Schema$File>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$File>(parameters); } } /** * Subscribes to changes to a file * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.metadata', * 'https://www.googleapis.com/auth/drive.metadata.readonly', * 'https://www.googleapis.com/auth/drive.photos.readonly', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.files.watch({ * // Whether the user is acknowledging the risk of downloading known malware or other abusive files. This is only applicable when alt=media. * acknowledgeAbuse: 'placeholder-value', * // The ID of the file. * fileId: 'placeholder-value', * // Specifies which additional view's permissions to include in the response. Only 'published' is supported. * includePermissionsForView: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "address": "my_address", * // "expiration": "my_expiration", * // "id": "my_id", * // "kind": "my_kind", * // "params": {}, * // "payload": false, * // "resourceId": "my_resourceId", * // "resourceUri": "my_resourceUri", * // "token": "my_token", * // "type": "my_type" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "address": "my_address", * // "expiration": "my_expiration", * // "id": "my_id", * // "kind": "my_kind", * // "params": {}, * // "payload": false, * // "resourceId": "my_resourceId", * // "resourceUri": "my_resourceUri", * // "token": "my_token", * // "type": "my_type" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ watch( params: Params$Resource$Files$Watch, options: StreamMethodOptions ): GaxiosPromise<Readable>; watch( params?: Params$Resource$Files$Watch, options?: MethodOptions ): GaxiosPromise<Schema$Channel>; watch( params: Params$Resource$Files$Watch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; watch( params: Params$Resource$Files$Watch, options: MethodOptions | BodyResponseCallback<Schema$Channel>, callback: BodyResponseCallback<Schema$Channel> ): void; watch( params: Params$Resource$Files$Watch, callback: BodyResponseCallback<Schema$Channel> ): void; watch(callback: BodyResponseCallback<Schema$Channel>): void; watch( paramsOrCallback?: | Params$Resource$Files$Watch | BodyResponseCallback<Schema$Channel> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Channel> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Channel> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Channel> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Files$Watch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Files$Watch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files/{fileId}/watch').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['fileId'], pathParams: ['fileId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Channel>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Channel>(parameters); } } } export interface Params$Resource$Files$Copy extends StandardParameters { /** * Deprecated. Copying files into multiple folders is no longer supported. Use shortcuts instead. */ enforceSingleParent?: boolean; /** * The ID of the file. */ fileId?: string; /** * Whether to ignore the domain's default visibility settings for the created file. Domain administrators can choose to make all uploaded files visible to the domain by default; this parameter bypasses that behavior for the request. Permissions are still inherited from parent folders. */ ignoreDefaultVisibility?: boolean; /** * Specifies which additional view's permissions to include in the response. Only 'published' is supported. */ includePermissionsForView?: string; /** * Whether to set the 'keepForever' field in the new head revision. This is only applicable to files with binary content in Google Drive. Only 200 revisions for the file can be kept forever. If the limit is reached, try deleting pinned revisions. */ keepRevisionForever?: boolean; /** * A language hint for OCR processing during image import (ISO 639-1 code). */ ocrLanguage?: string; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; /** * Request body metadata */ requestBody?: Schema$File; } export interface Params$Resource$Files$Create extends StandardParameters { /** * Deprecated. Creating files in multiple folders is no longer supported. */ enforceSingleParent?: boolean; /** * Whether to ignore the domain's default visibility settings for the created file. Domain administrators can choose to make all uploaded files visible to the domain by default; this parameter bypasses that behavior for the request. Permissions are still inherited from parent folders. */ ignoreDefaultVisibility?: boolean; /** * Specifies which additional view's permissions to include in the response. Only 'published' is supported. */ includePermissionsForView?: string; /** * Whether to set the 'keepForever' field in the new head revision. This is only applicable to files with binary content in Google Drive. Only 200 revisions for the file can be kept forever. If the limit is reached, try deleting pinned revisions. */ keepRevisionForever?: boolean; /** * A language hint for OCR processing during image import (ISO 639-1 code). */ ocrLanguage?: string; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; /** * Whether to use the uploaded content as indexable text. */ useContentAsIndexableText?: boolean; /** * Request body metadata */ requestBody?: Schema$File; /** * Media metadata */ media?: { /** * Media mime-type */ mimeType?: string; /** * Media body contents */ body?: any; }; } export interface Params$Resource$Files$Delete extends StandardParameters { /** * Deprecated. If an item is not in a shared drive and its last parent is deleted but the item itself is not, the item will be placed under its owner's root. */ enforceSingleParent?: boolean; /** * The ID of the file. */ fileId?: string; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; } export interface Params$Resource$Files$Emptytrash extends StandardParameters { /** * Deprecated. If an item is not in a shared drive and its last parent is deleted but the item itself is not, the item will be placed under its owner's root. */ enforceSingleParent?: boolean; } export interface Params$Resource$Files$Export extends StandardParameters { /** * The ID of the file. */ fileId?: string; /** * The MIME type of the format requested for this export. */ mimeType?: string; } export interface Params$Resource$Files$Generateids extends StandardParameters { /** * The number of IDs to return. */ count?: number; /** * The space in which the IDs can be used to create new files. Supported values are 'drive' and 'appDataFolder'. (Default: 'drive') */ space?: string; /** * The type of items which the IDs can be used for. Supported values are 'files' and 'shortcuts'. Note that 'shortcuts' are only supported in the drive 'space'. (Default: 'files') */ type?: string; } export interface Params$Resource$Files$Get extends StandardParameters { /** * Whether the user is acknowledging the risk of downloading known malware or other abusive files. This is only applicable when alt=media. */ acknowledgeAbuse?: boolean; /** * The ID of the file. */ fileId?: string; /** * Specifies which additional view's permissions to include in the response. Only 'published' is supported. */ includePermissionsForView?: string; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; } export interface Params$Resource$Files$List extends StandardParameters { /** * Groupings of files to which the query applies. Supported groupings are: 'user' (files created by, opened by, or shared directly with the user), 'drive' (files in the specified shared drive as indicated by the 'driveId'), 'domain' (files shared to the user's domain), and 'allDrives' (A combination of 'user' and 'drive' for all drives where the user is a member). When able, use 'user' or 'drive', instead of 'allDrives', for efficiency. */ corpora?: string; /** * The source of files to list. Deprecated: use 'corpora' instead. */ corpus?: string; /** * ID of the shared drive to search. */ driveId?: string; /** * Whether both My Drive and shared drive items should be included in results. */ includeItemsFromAllDrives?: boolean; /** * Specifies which additional view's permissions to include in the response. Only 'published' is supported. */ includePermissionsForView?: string; /** * Deprecated use includeItemsFromAllDrives instead. */ includeTeamDriveItems?: boolean; /** * A comma-separated list of sort keys. Valid keys are 'createdTime', 'folder', 'modifiedByMeTime', 'modifiedTime', 'name', 'name_natural', 'quotaBytesUsed', 'recency', 'sharedWithMeTime', 'starred', and 'viewedByMeTime'. Each key sorts ascending by default, but may be reversed with the 'desc' modifier. Example usage: ?orderBy=folder,modifiedTime desc,name. Please note that there is a current limitation for users with approximately one million files in which the requested sort order is ignored. */ orderBy?: string; /** * The maximum number of files to return per page. Partial or empty result pages are possible even before the end of the files list has been reached. */ pageSize?: number; /** * The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. */ pageToken?: string; /** * A query for filtering the file results. See the "Search for Files" guide for supported syntax. */ q?: string; /** * A comma-separated list of spaces to query within the corpus. Supported values are 'drive' and 'appDataFolder'. */ spaces?: string; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; /** * Deprecated use driveId instead. */ teamDriveId?: string; } export interface Params$Resource$Files$Update extends StandardParameters { /** * A comma-separated list of parent IDs to add. */ addParents?: string; /** * Deprecated. Adding files to multiple folders is no longer supported. Use shortcuts instead. */ enforceSingleParent?: boolean; /** * The ID of the file. */ fileId?: string; /** * Specifies which additional view's permissions to include in the response. Only 'published' is supported. */ includePermissionsForView?: string; /** * Whether to set the 'keepForever' field in the new head revision. This is only applicable to files with binary content in Google Drive. Only 200 revisions for the file can be kept forever. If the limit is reached, try deleting pinned revisions. */ keepRevisionForever?: boolean; /** * A language hint for OCR processing during image import (ISO 639-1 code). */ ocrLanguage?: string; /** * A comma-separated list of parent IDs to remove. */ removeParents?: string; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; /** * Whether to use the uploaded content as indexable text. */ useContentAsIndexableText?: boolean; /** * Request body metadata */ requestBody?: Schema$File; /** * Media metadata */ media?: { /** * Media mime-type */ mimeType?: string; /** * Media body contents */ body?: any; }; } export interface Params$Resource$Files$Watch extends StandardParameters { /** * Whether the user is acknowledging the risk of downloading known malware or other abusive files. This is only applicable when alt=media. */ acknowledgeAbuse?: boolean; /** * The ID of the file. */ fileId?: string; /** * Specifies which additional view's permissions to include in the response. Only 'published' is supported. */ includePermissionsForView?: string; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; /** * Request body metadata */ requestBody?: Schema$Channel; } export class Resource$Permissions { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Creates a permission for a file or shared drive. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.permissions.create({ * // A plain text custom message to include in the notification email. * emailMessage: 'placeholder-value', * // Deprecated. See moveToNewOwnersRoot for details. * enforceSingleParent: 'placeholder-value', * // The ID of the file or shared drive. * fileId: 'placeholder-value', * // This parameter will only take effect if the item is not in a shared drive and the request is attempting to transfer the ownership of the item. If set to true, the item will be moved to the new owner's My Drive root folder and all prior parents removed. If set to false, parents are not changed. * moveToNewOwnersRoot: 'placeholder-value', * // Whether to send a notification email when sharing to users or groups. This defaults to true for users and groups, and is not allowed for other requests. It must not be disabled for ownership transfers. * sendNotificationEmail: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * // Whether to transfer ownership to the specified user and downgrade the current owner to a writer. This parameter is required as an acknowledgement of the side effect. File owners can only transfer ownership of files existing on My Drive. Files existing in a shared drive are owned by the organization that owns that shared drive. Ownership transfers are not supported for files and folders in shared drives. Organizers of a shared drive can move items from that shared drive into their My Drive which transfers the ownership to them. * transferOwnership: 'placeholder-value', * // Issue the request as a domain administrator; if set to true, then the requester will be granted access if the file ID parameter refers to a shared drive and the requester is an administrator of the domain to which the shared drive belongs. * useDomainAdminAccess: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "allowFileDiscovery": false, * // "deleted": false, * // "displayName": "my_displayName", * // "domain": "my_domain", * // "emailAddress": "my_emailAddress", * // "expirationTime": "my_expirationTime", * // "id": "my_id", * // "kind": "my_kind", * // "pendingOwner": false, * // "permissionDetails": [], * // "photoLink": "my_photoLink", * // "role": "my_role", * // "teamDrivePermissionDetails": [], * // "type": "my_type", * // "view": "my_view" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "allowFileDiscovery": false, * // "deleted": false, * // "displayName": "my_displayName", * // "domain": "my_domain", * // "emailAddress": "my_emailAddress", * // "expirationTime": "my_expirationTime", * // "id": "my_id", * // "kind": "my_kind", * // "pendingOwner": false, * // "permissionDetails": [], * // "photoLink": "my_photoLink", * // "role": "my_role", * // "teamDrivePermissionDetails": [], * // "type": "my_type", * // "view": "my_view" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Permissions$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Permissions$Create, options?: MethodOptions ): GaxiosPromise<Schema$Permission>; create( params: Params$Resource$Permissions$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Permissions$Create, options: MethodOptions | BodyResponseCallback<Schema$Permission>, callback: BodyResponseCallback<Schema$Permission> ): void; create( params: Params$Resource$Permissions$Create, callback: BodyResponseCallback<Schema$Permission> ): void; create(callback: BodyResponseCallback<Schema$Permission>): void; create( paramsOrCallback?: | Params$Resource$Permissions$Create | BodyResponseCallback<Schema$Permission> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Permission> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Permission> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Permission> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Permissions$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Permissions$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files/{fileId}/permissions').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['fileId'], pathParams: ['fileId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Permission>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Permission>(parameters); } } /** * Deletes a permission. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.permissions.delete({ * // The ID of the file or shared drive. * fileId: 'placeholder-value', * // The ID of the permission. * permissionId: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * // Issue the request as a domain administrator; if set to true, then the requester will be granted access if the file ID parameter refers to a shared drive and the requester is an administrator of the domain to which the shared drive belongs. * useDomainAdminAccess: 'placeholder-value', * }); * console.log(res.data); * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Permissions$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Permissions$Delete, options?: MethodOptions ): GaxiosPromise<void>; delete( params: Params$Resource$Permissions$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Permissions$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void> ): void; delete( params: Params$Resource$Permissions$Delete, callback: BodyResponseCallback<void> ): void; delete(callback: BodyResponseCallback<void>): void; delete( paramsOrCallback?: | Params$Resource$Permissions$Delete | BodyResponseCallback<void> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<void> | BodyResponseCallback<Readable>, callback?: BodyResponseCallback<void> | BodyResponseCallback<Readable> ): void | GaxiosPromise<void> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Permissions$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Permissions$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/drive/v3/files/{fileId}/permissions/{permissionId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['fileId', 'permissionId'], pathParams: ['fileId', 'permissionId'], context: this.context, }; if (callback) { createAPIRequest<void>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<void>(parameters); } } /** * Gets a permission by ID. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.metadata', * 'https://www.googleapis.com/auth/drive.metadata.readonly', * 'https://www.googleapis.com/auth/drive.photos.readonly', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.permissions.get({ * // The ID of the file. * fileId: 'placeholder-value', * // The ID of the permission. * permissionId: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * // Issue the request as a domain administrator; if set to true, then the requester will be granted access if the file ID parameter refers to a shared drive and the requester is an administrator of the domain to which the shared drive belongs. * useDomainAdminAccess: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "allowFileDiscovery": false, * // "deleted": false, * // "displayName": "my_displayName", * // "domain": "my_domain", * // "emailAddress": "my_emailAddress", * // "expirationTime": "my_expirationTime", * // "id": "my_id", * // "kind": "my_kind", * // "pendingOwner": false, * // "permissionDetails": [], * // "photoLink": "my_photoLink", * // "role": "my_role", * // "teamDrivePermissionDetails": [], * // "type": "my_type", * // "view": "my_view" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Permissions$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Permissions$Get, options?: MethodOptions ): GaxiosPromise<Schema$Permission>; get( params: Params$Resource$Permissions$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Permissions$Get, options: MethodOptions | BodyResponseCallback<Schema$Permission>, callback: BodyResponseCallback<Schema$Permission> ): void; get( params: Params$Resource$Permissions$Get, callback: BodyResponseCallback<Schema$Permission> ): void; get(callback: BodyResponseCallback<Schema$Permission>): void; get( paramsOrCallback?: | Params$Resource$Permissions$Get | BodyResponseCallback<Schema$Permission> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Permission> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Permission> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Permission> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Permissions$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Permissions$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/drive/v3/files/{fileId}/permissions/{permissionId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['fileId', 'permissionId'], pathParams: ['fileId', 'permissionId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Permission>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Permission>(parameters); } } /** * Lists a file's or shared drive's permissions. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.metadata', * 'https://www.googleapis.com/auth/drive.metadata.readonly', * 'https://www.googleapis.com/auth/drive.photos.readonly', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.permissions.list({ * // The ID of the file or shared drive. * fileId: 'placeholder-value', * // Specifies which additional view's permissions to include in the response. Only 'published' is supported. * includePermissionsForView: 'placeholder-value', * // The maximum number of permissions to return per page. When not set for files in a shared drive, at most 100 results will be returned. When not set for files that are not in a shared drive, the entire list will be returned. * pageSize: 'placeholder-value', * // The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. * pageToken: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * // Issue the request as a domain administrator; if set to true, then the requester will be granted access if the file ID parameter refers to a shared drive and the requester is an administrator of the domain to which the shared drive belongs. * useDomainAdminAccess: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "kind": "my_kind", * // "nextPageToken": "my_nextPageToken", * // "permissions": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Permissions$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Permissions$List, options?: MethodOptions ): GaxiosPromise<Schema$PermissionList>; list( params: Params$Resource$Permissions$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Permissions$List, options: MethodOptions | BodyResponseCallback<Schema$PermissionList>, callback: BodyResponseCallback<Schema$PermissionList> ): void; list( params: Params$Resource$Permissions$List, callback: BodyResponseCallback<Schema$PermissionList> ): void; list(callback: BodyResponseCallback<Schema$PermissionList>): void; list( paramsOrCallback?: | Params$Resource$Permissions$List | BodyResponseCallback<Schema$PermissionList> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$PermissionList> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$PermissionList> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$PermissionList> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Permissions$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Permissions$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files/{fileId}/permissions').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['fileId'], pathParams: ['fileId'], context: this.context, }; if (callback) { createAPIRequest<Schema$PermissionList>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$PermissionList>(parameters); } } /** * Updates a permission with patch semantics. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.permissions.update({ * // The ID of the file or shared drive. * fileId: 'placeholder-value', * // The ID of the permission. * permissionId: 'placeholder-value', * // Whether to remove the expiration date. * removeExpiration: 'placeholder-value', * // Whether the requesting application supports both My Drives and shared drives. * supportsAllDrives: 'placeholder-value', * // Deprecated use supportsAllDrives instead. * supportsTeamDrives: 'placeholder-value', * // Whether to transfer ownership to the specified user and downgrade the current owner to a writer. This parameter is required as an acknowledgement of the side effect. File owners can only transfer ownership of files existing on My Drive. Files existing in a shared drive are owned by the organization that owns that shared drive. Ownership transfers are not supported for files and folders in shared drives. Organizers of a shared drive can move items from that shared drive into their My Drive which transfers the ownership to them. * transferOwnership: 'placeholder-value', * // Issue the request as a domain administrator; if set to true, then the requester will be granted access if the file ID parameter refers to a shared drive and the requester is an administrator of the domain to which the shared drive belongs. * useDomainAdminAccess: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "allowFileDiscovery": false, * // "deleted": false, * // "displayName": "my_displayName", * // "domain": "my_domain", * // "emailAddress": "my_emailAddress", * // "expirationTime": "my_expirationTime", * // "id": "my_id", * // "kind": "my_kind", * // "pendingOwner": false, * // "permissionDetails": [], * // "photoLink": "my_photoLink", * // "role": "my_role", * // "teamDrivePermissionDetails": [], * // "type": "my_type", * // "view": "my_view" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "allowFileDiscovery": false, * // "deleted": false, * // "displayName": "my_displayName", * // "domain": "my_domain", * // "emailAddress": "my_emailAddress", * // "expirationTime": "my_expirationTime", * // "id": "my_id", * // "kind": "my_kind", * // "pendingOwner": false, * // "permissionDetails": [], * // "photoLink": "my_photoLink", * // "role": "my_role", * // "teamDrivePermissionDetails": [], * // "type": "my_type", * // "view": "my_view" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ update( params: Params$Resource$Permissions$Update, options: StreamMethodOptions ): GaxiosPromise<Readable>; update( params?: Params$Resource$Permissions$Update, options?: MethodOptions ): GaxiosPromise<Schema$Permission>; update( params: Params$Resource$Permissions$Update, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; update( params: Params$Resource$Permissions$Update, options: MethodOptions | BodyResponseCallback<Schema$Permission>, callback: BodyResponseCallback<Schema$Permission> ): void; update( params: Params$Resource$Permissions$Update, callback: BodyResponseCallback<Schema$Permission> ): void; update(callback: BodyResponseCallback<Schema$Permission>): void; update( paramsOrCallback?: | Params$Resource$Permissions$Update | BodyResponseCallback<Schema$Permission> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Permission> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Permission> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Permission> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Permissions$Update; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Permissions$Update; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/drive/v3/files/{fileId}/permissions/{permissionId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['fileId', 'permissionId'], pathParams: ['fileId', 'permissionId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Permission>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Permission>(parameters); } } } export interface Params$Resource$Permissions$Create extends StandardParameters { /** * A plain text custom message to include in the notification email. */ emailMessage?: string; /** * Deprecated. See moveToNewOwnersRoot for details. */ enforceSingleParent?: boolean; /** * The ID of the file or shared drive. */ fileId?: string; /** * This parameter will only take effect if the item is not in a shared drive and the request is attempting to transfer the ownership of the item. If set to true, the item will be moved to the new owner's My Drive root folder and all prior parents removed. If set to false, parents are not changed. */ moveToNewOwnersRoot?: boolean; /** * Whether to send a notification email when sharing to users or groups. This defaults to true for users and groups, and is not allowed for other requests. It must not be disabled for ownership transfers. */ sendNotificationEmail?: boolean; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; /** * Whether to transfer ownership to the specified user and downgrade the current owner to a writer. This parameter is required as an acknowledgement of the side effect. File owners can only transfer ownership of files existing on My Drive. Files existing in a shared drive are owned by the organization that owns that shared drive. Ownership transfers are not supported for files and folders in shared drives. Organizers of a shared drive can move items from that shared drive into their My Drive which transfers the ownership to them. */ transferOwnership?: boolean; /** * Issue the request as a domain administrator; if set to true, then the requester will be granted access if the file ID parameter refers to a shared drive and the requester is an administrator of the domain to which the shared drive belongs. */ useDomainAdminAccess?: boolean; /** * Request body metadata */ requestBody?: Schema$Permission; } export interface Params$Resource$Permissions$Delete extends StandardParameters { /** * The ID of the file or shared drive. */ fileId?: string; /** * The ID of the permission. */ permissionId?: string; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; /** * Issue the request as a domain administrator; if set to true, then the requester will be granted access if the file ID parameter refers to a shared drive and the requester is an administrator of the domain to which the shared drive belongs. */ useDomainAdminAccess?: boolean; } export interface Params$Resource$Permissions$Get extends StandardParameters { /** * The ID of the file. */ fileId?: string; /** * The ID of the permission. */ permissionId?: string; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; /** * Issue the request as a domain administrator; if set to true, then the requester will be granted access if the file ID parameter refers to a shared drive and the requester is an administrator of the domain to which the shared drive belongs. */ useDomainAdminAccess?: boolean; } export interface Params$Resource$Permissions$List extends StandardParameters { /** * The ID of the file or shared drive. */ fileId?: string; /** * Specifies which additional view's permissions to include in the response. Only 'published' is supported. */ includePermissionsForView?: string; /** * The maximum number of permissions to return per page. When not set for files in a shared drive, at most 100 results will be returned. When not set for files that are not in a shared drive, the entire list will be returned. */ pageSize?: number; /** * The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. */ pageToken?: string; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; /** * Issue the request as a domain administrator; if set to true, then the requester will be granted access if the file ID parameter refers to a shared drive and the requester is an administrator of the domain to which the shared drive belongs. */ useDomainAdminAccess?: boolean; } export interface Params$Resource$Permissions$Update extends StandardParameters { /** * The ID of the file or shared drive. */ fileId?: string; /** * The ID of the permission. */ permissionId?: string; /** * Whether to remove the expiration date. */ removeExpiration?: boolean; /** * Whether the requesting application supports both My Drives and shared drives. */ supportsAllDrives?: boolean; /** * Deprecated use supportsAllDrives instead. */ supportsTeamDrives?: boolean; /** * Whether to transfer ownership to the specified user and downgrade the current owner to a writer. This parameter is required as an acknowledgement of the side effect. File owners can only transfer ownership of files existing on My Drive. Files existing in a shared drive are owned by the organization that owns that shared drive. Ownership transfers are not supported for files and folders in shared drives. Organizers of a shared drive can move items from that shared drive into their My Drive which transfers the ownership to them. */ transferOwnership?: boolean; /** * Issue the request as a domain administrator; if set to true, then the requester will be granted access if the file ID parameter refers to a shared drive and the requester is an administrator of the domain to which the shared drive belongs. */ useDomainAdminAccess?: boolean; /** * Request body metadata */ requestBody?: Schema$Permission; } export class Resource$Replies { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Creates a new reply to a comment. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.replies.create({ * // The ID of the comment. * commentId: 'placeholder-value', * // The ID of the file. * fileId: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "action": "my_action", * // "author": {}, * // "content": "my_content", * // "createdTime": "my_createdTime", * // "deleted": false, * // "htmlContent": "my_htmlContent", * // "id": "my_id", * // "kind": "my_kind", * // "modifiedTime": "my_modifiedTime" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "action": "my_action", * // "author": {}, * // "content": "my_content", * // "createdTime": "my_createdTime", * // "deleted": false, * // "htmlContent": "my_htmlContent", * // "id": "my_id", * // "kind": "my_kind", * // "modifiedTime": "my_modifiedTime" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Replies$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Replies$Create, options?: MethodOptions ): GaxiosPromise<Schema$Reply>; create( params: Params$Resource$Replies$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Replies$Create, options: MethodOptions | BodyResponseCallback<Schema$Reply>, callback: BodyResponseCallback<Schema$Reply> ): void; create( params: Params$Resource$Replies$Create, callback: BodyResponseCallback<Schema$Reply> ): void; create(callback: BodyResponseCallback<Schema$Reply>): void; create( paramsOrCallback?: | Params$Resource$Replies$Create | BodyResponseCallback<Schema$Reply> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Reply> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Reply> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Reply> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Replies$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Replies$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/drive/v3/files/{fileId}/comments/{commentId}/replies' ).replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, requiredParams: ['fileId', 'commentId'], pathParams: ['commentId', 'fileId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Reply>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Reply>(parameters); } } /** * Deletes a reply. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.replies.delete({ * // The ID of the comment. * commentId: 'placeholder-value', * // The ID of the file. * fileId: 'placeholder-value', * // The ID of the reply. * replyId: 'placeholder-value', * }); * console.log(res.data); * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Replies$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Replies$Delete, options?: MethodOptions ): GaxiosPromise<void>; delete( params: Params$Resource$Replies$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Replies$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void> ): void; delete( params: Params$Resource$Replies$Delete, callback: BodyResponseCallback<void> ): void; delete(callback: BodyResponseCallback<void>): void; delete( paramsOrCallback?: | Params$Resource$Replies$Delete | BodyResponseCallback<void> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<void> | BodyResponseCallback<Readable>, callback?: BodyResponseCallback<void> | BodyResponseCallback<Readable> ): void | GaxiosPromise<void> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Replies$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Replies$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/drive/v3/files/{fileId}/comments/{commentId}/replies/{replyId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['fileId', 'commentId', 'replyId'], pathParams: ['commentId', 'fileId', 'replyId'], context: this.context, }; if (callback) { createAPIRequest<void>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<void>(parameters); } } /** * Gets a reply by ID. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.replies.get({ * // The ID of the comment. * commentId: 'placeholder-value', * // The ID of the file. * fileId: 'placeholder-value', * // Whether to return deleted replies. Deleted replies will not include their original content. * includeDeleted: 'placeholder-value', * // The ID of the reply. * replyId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "action": "my_action", * // "author": {}, * // "content": "my_content", * // "createdTime": "my_createdTime", * // "deleted": false, * // "htmlContent": "my_htmlContent", * // "id": "my_id", * // "kind": "my_kind", * // "modifiedTime": "my_modifiedTime" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Replies$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Replies$Get, options?: MethodOptions ): GaxiosPromise<Schema$Reply>; get( params: Params$Resource$Replies$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Replies$Get, options: MethodOptions | BodyResponseCallback<Schema$Reply>, callback: BodyResponseCallback<Schema$Reply> ): void; get( params: Params$Resource$Replies$Get, callback: BodyResponseCallback<Schema$Reply> ): void; get(callback: BodyResponseCallback<Schema$Reply>): void; get( paramsOrCallback?: | Params$Resource$Replies$Get | BodyResponseCallback<Schema$Reply> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Reply> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Reply> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Reply> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Replies$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Replies$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/drive/v3/files/{fileId}/comments/{commentId}/replies/{replyId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['fileId', 'commentId', 'replyId'], pathParams: ['commentId', 'fileId', 'replyId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Reply>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Reply>(parameters); } } /** * Lists a comment's replies. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.replies.list({ * // The ID of the comment. * commentId: 'placeholder-value', * // The ID of the file. * fileId: 'placeholder-value', * // Whether to include deleted replies. Deleted replies will not include their original content. * includeDeleted: 'placeholder-value', * // The maximum number of replies to return per page. * pageSize: 'placeholder-value', * // The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. * pageToken: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "kind": "my_kind", * // "nextPageToken": "my_nextPageToken", * // "replies": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Replies$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Replies$List, options?: MethodOptions ): GaxiosPromise<Schema$ReplyList>; list( params: Params$Resource$Replies$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Replies$List, options: MethodOptions | BodyResponseCallback<Schema$ReplyList>, callback: BodyResponseCallback<Schema$ReplyList> ): void; list( params: Params$Resource$Replies$List, callback: BodyResponseCallback<Schema$ReplyList> ): void; list(callback: BodyResponseCallback<Schema$ReplyList>): void; list( paramsOrCallback?: | Params$Resource$Replies$List | BodyResponseCallback<Schema$ReplyList> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ReplyList> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ReplyList> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$ReplyList> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Replies$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Replies$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/drive/v3/files/{fileId}/comments/{commentId}/replies' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['fileId', 'commentId'], pathParams: ['commentId', 'fileId'], context: this.context, }; if (callback) { createAPIRequest<Schema$ReplyList>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ReplyList>(parameters); } } /** * Updates a reply with patch semantics. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.file', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.replies.update({ * // The ID of the comment. * commentId: 'placeholder-value', * // The ID of the file. * fileId: 'placeholder-value', * // The ID of the reply. * replyId: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "action": "my_action", * // "author": {}, * // "content": "my_content", * // "createdTime": "my_createdTime", * // "deleted": false, * // "htmlContent": "my_htmlContent", * // "id": "my_id", * // "kind": "my_kind", * // "modifiedTime": "my_modifiedTime" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "action": "my_action", * // "author": {}, * // "content": "my_content", * // "createdTime": "my_createdTime", * // "deleted": false, * // "htmlContent": "my_htmlContent", * // "id": "my_id", * // "kind": "my_kind", * // "modifiedTime": "my_modifiedTime" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ update( params: Params$Resource$Replies$Update, options: StreamMethodOptions ): GaxiosPromise<Readable>; update( params?: Params$Resource$Replies$Update, options?: MethodOptions ): GaxiosPromise<Schema$Reply>; update( params: Params$Resource$Replies$Update, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; update( params: Params$Resource$Replies$Update, options: MethodOptions | BodyResponseCallback<Schema$Reply>, callback: BodyResponseCallback<Schema$Reply> ): void; update( params: Params$Resource$Replies$Update, callback: BodyResponseCallback<Schema$Reply> ): void; update(callback: BodyResponseCallback<Schema$Reply>): void; update( paramsOrCallback?: | Params$Resource$Replies$Update | BodyResponseCallback<Schema$Reply> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Reply> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Reply> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Reply> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Replies$Update; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Replies$Update; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/drive/v3/files/{fileId}/comments/{commentId}/replies/{replyId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['fileId', 'commentId', 'replyId'], pathParams: ['commentId', 'fileId', 'replyId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Reply>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Reply>(parameters); } } } export interface Params$Resource$Replies$Create extends StandardParameters { /** * The ID of the comment. */ commentId?: string; /** * The ID of the file. */ fileId?: string; /** * Request body metadata */ requestBody?: Schema$Reply; } export interface Params$Resource$Replies$Delete extends StandardParameters { /** * The ID of the comment. */ commentId?: string; /** * The ID of the file. */ fileId?: string; /** * The ID of the reply. */ replyId?: string; } export interface Params$Resource$Replies$Get extends StandardParameters { /** * The ID of the comment. */ commentId?: string; /** * The ID of the file. */ fileId?: string; /** * Whether to return deleted replies. Deleted replies will not include their original content. */ includeDeleted?: boolean; /** * The ID of the reply. */ replyId?: string; } export interface Params$Resource$Replies$List extends StandardParameters { /** * The ID of the comment. */ commentId?: string; /** * The ID of the file. */ fileId?: string; /** * Whether to include deleted replies. Deleted replies will not include their original content. */ includeDeleted?: boolean; /** * The maximum number of replies to return per page. */ pageSize?: number; /** * The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. */ pageToken?: string; } export interface Params$Resource$Replies$Update extends StandardParameters { /** * The ID of the comment. */ commentId?: string; /** * The ID of the file. */ fileId?: string; /** * The ID of the reply. */ replyId?: string; /** * Request body metadata */ requestBody?: Schema$Reply; } export class Resource$Revisions { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Permanently deletes a file version. You can only delete revisions for files with binary content in Google Drive, like images or videos. Revisions for other files, like Google Docs or Sheets, and the last remaining file version can't be deleted. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.revisions.delete({ * // The ID of the file. * fileId: 'placeholder-value', * // The ID of the revision. * revisionId: 'placeholder-value', * }); * console.log(res.data); * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Revisions$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Revisions$Delete, options?: MethodOptions ): GaxiosPromise<void>; delete( params: Params$Resource$Revisions$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Revisions$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void> ): void; delete( params: Params$Resource$Revisions$Delete, callback: BodyResponseCallback<void> ): void; delete(callback: BodyResponseCallback<void>): void; delete( paramsOrCallback?: | Params$Resource$Revisions$Delete | BodyResponseCallback<void> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<void> | BodyResponseCallback<Readable>, callback?: BodyResponseCallback<void> | BodyResponseCallback<Readable> ): void | GaxiosPromise<void> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Revisions$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Revisions$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/drive/v3/files/{fileId}/revisions/{revisionId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['fileId', 'revisionId'], pathParams: ['fileId', 'revisionId'], context: this.context, }; if (callback) { createAPIRequest<void>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<void>(parameters); } } /** * Gets a revision's metadata or content by ID. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.metadata', * 'https://www.googleapis.com/auth/drive.metadata.readonly', * 'https://www.googleapis.com/auth/drive.photos.readonly', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.revisions.get({ * // Whether the user is acknowledging the risk of downloading known malware or other abusive files. This is only applicable when alt=media. * acknowledgeAbuse: 'placeholder-value', * // The ID of the file. * fileId: 'placeholder-value', * // The ID of the revision. * revisionId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "exportLinks": {}, * // "id": "my_id", * // "keepForever": false, * // "kind": "my_kind", * // "lastModifyingUser": {}, * // "md5Checksum": "my_md5Checksum", * // "mimeType": "my_mimeType", * // "modifiedTime": "my_modifiedTime", * // "originalFilename": "my_originalFilename", * // "publishAuto": false, * // "published": false, * // "publishedLink": "my_publishedLink", * // "publishedOutsideDomain": false, * // "size": "my_size" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Revisions$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Revisions$Get, options?: MethodOptions ): GaxiosPromise<Schema$Revision>; get( params: Params$Resource$Revisions$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Revisions$Get, options: MethodOptions | BodyResponseCallback<Schema$Revision>, callback: BodyResponseCallback<Schema$Revision> ): void; get( params: Params$Resource$Revisions$Get, callback: BodyResponseCallback<Schema$Revision> ): void; get(callback: BodyResponseCallback<Schema$Revision>): void; get( paramsOrCallback?: | Params$Resource$Revisions$Get | BodyResponseCallback<Schema$Revision> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Revision> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Revision> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Revision> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Revisions$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Revisions$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/drive/v3/files/{fileId}/revisions/{revisionId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['fileId', 'revisionId'], pathParams: ['fileId', 'revisionId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Revision>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Revision>(parameters); } } /** * Lists a file's revisions. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * 'https://www.googleapis.com/auth/drive.metadata', * 'https://www.googleapis.com/auth/drive.metadata.readonly', * 'https://www.googleapis.com/auth/drive.photos.readonly', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.revisions.list({ * // The ID of the file. * fileId: 'placeholder-value', * // The maximum number of revisions to return per page. * pageSize: 'placeholder-value', * // The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. * pageToken: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "kind": "my_kind", * // "nextPageToken": "my_nextPageToken", * // "revisions": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Revisions$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Revisions$List, options?: MethodOptions ): GaxiosPromise<Schema$RevisionList>; list( params: Params$Resource$Revisions$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Revisions$List, options: MethodOptions | BodyResponseCallback<Schema$RevisionList>, callback: BodyResponseCallback<Schema$RevisionList> ): void; list( params: Params$Resource$Revisions$List, callback: BodyResponseCallback<Schema$RevisionList> ): void; list(callback: BodyResponseCallback<Schema$RevisionList>): void; list( paramsOrCallback?: | Params$Resource$Revisions$List | BodyResponseCallback<Schema$RevisionList> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$RevisionList> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$RevisionList> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$RevisionList> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Revisions$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Revisions$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/files/{fileId}/revisions').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['fileId'], pathParams: ['fileId'], context: this.context, }; if (callback) { createAPIRequest<Schema$RevisionList>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$RevisionList>(parameters); } } /** * Updates a revision with patch semantics. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.appdata', * 'https://www.googleapis.com/auth/drive.file', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.revisions.update({ * // The ID of the file. * fileId: 'placeholder-value', * // The ID of the revision. * revisionId: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "exportLinks": {}, * // "id": "my_id", * // "keepForever": false, * // "kind": "my_kind", * // "lastModifyingUser": {}, * // "md5Checksum": "my_md5Checksum", * // "mimeType": "my_mimeType", * // "modifiedTime": "my_modifiedTime", * // "originalFilename": "my_originalFilename", * // "publishAuto": false, * // "published": false, * // "publishedLink": "my_publishedLink", * // "publishedOutsideDomain": false, * // "size": "my_size" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "exportLinks": {}, * // "id": "my_id", * // "keepForever": false, * // "kind": "my_kind", * // "lastModifyingUser": {}, * // "md5Checksum": "my_md5Checksum", * // "mimeType": "my_mimeType", * // "modifiedTime": "my_modifiedTime", * // "originalFilename": "my_originalFilename", * // "publishAuto": false, * // "published": false, * // "publishedLink": "my_publishedLink", * // "publishedOutsideDomain": false, * // "size": "my_size" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ update( params: Params$Resource$Revisions$Update, options: StreamMethodOptions ): GaxiosPromise<Readable>; update( params?: Params$Resource$Revisions$Update, options?: MethodOptions ): GaxiosPromise<Schema$Revision>; update( params: Params$Resource$Revisions$Update, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; update( params: Params$Resource$Revisions$Update, options: MethodOptions | BodyResponseCallback<Schema$Revision>, callback: BodyResponseCallback<Schema$Revision> ): void; update( params: Params$Resource$Revisions$Update, callback: BodyResponseCallback<Schema$Revision> ): void; update(callback: BodyResponseCallback<Schema$Revision>): void; update( paramsOrCallback?: | Params$Resource$Revisions$Update | BodyResponseCallback<Schema$Revision> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Revision> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Revision> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Revision> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Revisions$Update; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Revisions$Update; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/drive/v3/files/{fileId}/revisions/{revisionId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['fileId', 'revisionId'], pathParams: ['fileId', 'revisionId'], context: this.context, }; if (callback) { createAPIRequest<Schema$Revision>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Revision>(parameters); } } } export interface Params$Resource$Revisions$Delete extends StandardParameters { /** * The ID of the file. */ fileId?: string; /** * The ID of the revision. */ revisionId?: string; } export interface Params$Resource$Revisions$Get extends StandardParameters { /** * Whether the user is acknowledging the risk of downloading known malware or other abusive files. This is only applicable when alt=media. */ acknowledgeAbuse?: boolean; /** * The ID of the file. */ fileId?: string; /** * The ID of the revision. */ revisionId?: string; } export interface Params$Resource$Revisions$List extends StandardParameters { /** * The ID of the file. */ fileId?: string; /** * The maximum number of revisions to return per page. */ pageSize?: number; /** * The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. */ pageToken?: string; } export interface Params$Resource$Revisions$Update extends StandardParameters { /** * The ID of the file. */ fileId?: string; /** * The ID of the revision. */ revisionId?: string; /** * Request body metadata */ requestBody?: Schema$Revision; } export class Resource$Teamdrives { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Deprecated use drives.create instead. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/drive'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.teamdrives.create({ * // An ID, such as a random UUID, which uniquely identifies this user's request for idempotent creation of a Team Drive. A repeated request by the same user and with the same request ID will avoid creating duplicates by attempting to create the same Team Drive. If the Team Drive already exists a 409 error will be returned. * requestId: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "backgroundImageFile": {}, * // "backgroundImageLink": "my_backgroundImageLink", * // "capabilities": {}, * // "colorRgb": "my_colorRgb", * // "createdTime": "my_createdTime", * // "id": "my_id", * // "kind": "my_kind", * // "name": "my_name", * // "restrictions": {}, * // "themeId": "my_themeId" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "backgroundImageFile": {}, * // "backgroundImageLink": "my_backgroundImageLink", * // "capabilities": {}, * // "colorRgb": "my_colorRgb", * // "createdTime": "my_createdTime", * // "id": "my_id", * // "kind": "my_kind", * // "name": "my_name", * // "restrictions": {}, * // "themeId": "my_themeId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Teamdrives$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Teamdrives$Create, options?: MethodOptions ): GaxiosPromise<Schema$TeamDrive>; create( params: Params$Resource$Teamdrives$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Teamdrives$Create, options: MethodOptions | BodyResponseCallback<Schema$TeamDrive>, callback: BodyResponseCallback<Schema$TeamDrive> ): void; create( params: Params$Resource$Teamdrives$Create, callback: BodyResponseCallback<Schema$TeamDrive> ): void; create(callback: BodyResponseCallback<Schema$TeamDrive>): void; create( paramsOrCallback?: | Params$Resource$Teamdrives$Create | BodyResponseCallback<Schema$TeamDrive> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$TeamDrive> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$TeamDrive> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$TeamDrive> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Teamdrives$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Teamdrives$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/teamdrives').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['requestId'], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$TeamDrive>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$TeamDrive>(parameters); } } /** * Deprecated use drives.delete instead. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/drive'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.teamdrives.delete({ * // The ID of the Team Drive * teamDriveId: 'placeholder-value', * }); * console.log(res.data); * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Teamdrives$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Teamdrives$Delete, options?: MethodOptions ): GaxiosPromise<void>; delete( params: Params$Resource$Teamdrives$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Teamdrives$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void> ): void; delete( params: Params$Resource$Teamdrives$Delete, callback: BodyResponseCallback<void> ): void; delete(callback: BodyResponseCallback<void>): void; delete( paramsOrCallback?: | Params$Resource$Teamdrives$Delete | BodyResponseCallback<void> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<void> | BodyResponseCallback<Readable>, callback?: BodyResponseCallback<void> | BodyResponseCallback<Readable> ): void | GaxiosPromise<void> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Teamdrives$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Teamdrives$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/teamdrives/{teamDriveId}').replace( /([^:]\/)\/+/g, '$1' ), method: 'DELETE', }, options ), params, requiredParams: ['teamDriveId'], pathParams: ['teamDriveId'], context: this.context, }; if (callback) { createAPIRequest<void>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<void>(parameters); } } /** * Deprecated use drives.get instead. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.teamdrives.get({ * // The ID of the Team Drive * teamDriveId: 'placeholder-value', * // Issue the request as a domain administrator; if set to true, then the requester will be granted access if they are an administrator of the domain to which the Team Drive belongs. * useDomainAdminAccess: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "backgroundImageFile": {}, * // "backgroundImageLink": "my_backgroundImageLink", * // "capabilities": {}, * // "colorRgb": "my_colorRgb", * // "createdTime": "my_createdTime", * // "id": "my_id", * // "kind": "my_kind", * // "name": "my_name", * // "restrictions": {}, * // "themeId": "my_themeId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Teamdrives$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Teamdrives$Get, options?: MethodOptions ): GaxiosPromise<Schema$TeamDrive>; get( params: Params$Resource$Teamdrives$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Teamdrives$Get, options: MethodOptions | BodyResponseCallback<Schema$TeamDrive>, callback: BodyResponseCallback<Schema$TeamDrive> ): void; get( params: Params$Resource$Teamdrives$Get, callback: BodyResponseCallback<Schema$TeamDrive> ): void; get(callback: BodyResponseCallback<Schema$TeamDrive>): void; get( paramsOrCallback?: | Params$Resource$Teamdrives$Get | BodyResponseCallback<Schema$TeamDrive> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$TeamDrive> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$TeamDrive> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$TeamDrive> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Teamdrives$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Teamdrives$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/teamdrives/{teamDriveId}').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['teamDriveId'], pathParams: ['teamDriveId'], context: this.context, }; if (callback) { createAPIRequest<Schema$TeamDrive>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$TeamDrive>(parameters); } } /** * Deprecated use drives.list instead. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/drive', * 'https://www.googleapis.com/auth/drive.readonly', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.teamdrives.list({ * // Maximum number of Team Drives to return. * pageSize: 'placeholder-value', * // Page token for Team Drives. * pageToken: 'placeholder-value', * // Query string for searching Team Drives. * q: 'placeholder-value', * // Issue the request as a domain administrator; if set to true, then all Team Drives of the domain in which the requester is an administrator are returned. * useDomainAdminAccess: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "kind": "my_kind", * // "nextPageToken": "my_nextPageToken", * // "teamDrives": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Teamdrives$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Teamdrives$List, options?: MethodOptions ): GaxiosPromise<Schema$TeamDriveList>; list( params: Params$Resource$Teamdrives$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Teamdrives$List, options: MethodOptions | BodyResponseCallback<Schema$TeamDriveList>, callback: BodyResponseCallback<Schema$TeamDriveList> ): void; list( params: Params$Resource$Teamdrives$List, callback: BodyResponseCallback<Schema$TeamDriveList> ): void; list(callback: BodyResponseCallback<Schema$TeamDriveList>): void; list( paramsOrCallback?: | Params$Resource$Teamdrives$List | BodyResponseCallback<Schema$TeamDriveList> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$TeamDriveList> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$TeamDriveList> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$TeamDriveList> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Teamdrives$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Teamdrives$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/teamdrives').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$TeamDriveList>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$TeamDriveList>(parameters); } } /** * Deprecated use drives.update instead * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/drive.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const drive = google.drive('v3'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/drive'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await drive.teamdrives.update({ * // The ID of the Team Drive * teamDriveId: 'placeholder-value', * // Issue the request as a domain administrator; if set to true, then the requester will be granted access if they are an administrator of the domain to which the Team Drive belongs. * useDomainAdminAccess: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "backgroundImageFile": {}, * // "backgroundImageLink": "my_backgroundImageLink", * // "capabilities": {}, * // "colorRgb": "my_colorRgb", * // "createdTime": "my_createdTime", * // "id": "my_id", * // "kind": "my_kind", * // "name": "my_name", * // "restrictions": {}, * // "themeId": "my_themeId" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "backgroundImageFile": {}, * // "backgroundImageLink": "my_backgroundImageLink", * // "capabilities": {}, * // "colorRgb": "my_colorRgb", * // "createdTime": "my_createdTime", * // "id": "my_id", * // "kind": "my_kind", * // "name": "my_name", * // "restrictions": {}, * // "themeId": "my_themeId" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ update( params: Params$Resource$Teamdrives$Update, options: StreamMethodOptions ): GaxiosPromise<Readable>; update( params?: Params$Resource$Teamdrives$Update, options?: MethodOptions ): GaxiosPromise<Schema$TeamDrive>; update( params: Params$Resource$Teamdrives$Update, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; update( params: Params$Resource$Teamdrives$Update, options: MethodOptions | BodyResponseCallback<Schema$TeamDrive>, callback: BodyResponseCallback<Schema$TeamDrive> ): void; update( params: Params$Resource$Teamdrives$Update, callback: BodyResponseCallback<Schema$TeamDrive> ): void; update(callback: BodyResponseCallback<Schema$TeamDrive>): void; update( paramsOrCallback?: | Params$Resource$Teamdrives$Update | BodyResponseCallback<Schema$TeamDrive> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$TeamDrive> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$TeamDrive> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$TeamDrive> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Teamdrives$Update; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Teamdrives$Update; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/drive/v3/teamdrives/{teamDriveId}').replace( /([^:]\/)\/+/g, '$1' ), method: 'PATCH', }, options ), params, requiredParams: ['teamDriveId'], pathParams: ['teamDriveId'], context: this.context, }; if (callback) { createAPIRequest<Schema$TeamDrive>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$TeamDrive>(parameters); } } } export interface Params$Resource$Teamdrives$Create extends StandardParameters { /** * An ID, such as a random UUID, which uniquely identifies this user's request for idempotent creation of a Team Drive. A repeated request by the same user and with the same request ID will avoid creating duplicates by attempting to create the same Team Drive. If the Team Drive already exists a 409 error will be returned. */ requestId?: string; /** * Request body metadata */ requestBody?: Schema$TeamDrive; } export interface Params$Resource$Teamdrives$Delete extends StandardParameters { /** * The ID of the Team Drive */ teamDriveId?: string; } export interface Params$Resource$Teamdrives$Get extends StandardParameters { /** * The ID of the Team Drive */ teamDriveId?: string; /** * Issue the request as a domain administrator; if set to true, then the requester will be granted access if they are an administrator of the domain to which the Team Drive belongs. */ useDomainAdminAccess?: boolean; } export interface Params$Resource$Teamdrives$List extends StandardParameters { /** * Maximum number of Team Drives to return. */ pageSize?: number; /** * Page token for Team Drives. */ pageToken?: string; /** * Query string for searching Team Drives. */ q?: string; /** * Issue the request as a domain administrator; if set to true, then all Team Drives of the domain in which the requester is an administrator are returned. */ useDomainAdminAccess?: boolean; } export interface Params$Resource$Teamdrives$Update extends StandardParameters { /** * The ID of the Team Drive */ teamDriveId?: string; /** * Issue the request as a domain administrator; if set to true, then the requester will be granted access if they are an administrator of the domain to which the Team Drive belongs. */ useDomainAdminAccess?: boolean; /** * Request body metadata */ requestBody?: Schema$TeamDrive; } }
the_stack
import * as core from '@spyglassmc/core' import { localeQuote, localize } from '@spyglassmc/locales' import * as mcdoc from '@spyglassmc/mcdoc' import type { NbtByteNode, NbtCompoundNode, NbtNode, NbtNumberNode, NbtPathNode, NbtPrimitiveArrayNode, NbtPrimitiveNode } from '../node/index.js' import { NbtListNode } from '../node/index.js' import { localizeTag } from '../util.js' import { getBlocksFromItem, getEntityFromItem, getSpecialStringParser } from './mcdocUtil.js' interface Options { allowUnknownKey?: boolean, isPredicate?: boolean, } interface PathOptions { allowUnknownKey?: boolean, } declare global { // https://github.com/microsoft/TypeScript/issues/17002#issuecomment-536946686 interface ArrayConstructor { isArray(arg: unknown): arg is unknown[] | readonly unknown[] } } /** * @param id If the registry is under the `custom` namespace, `id` can only be a string. Otherwise it can be a string, string array, or `undefined`. * If set to `undefined` or an empty array, all mcdoc compound definitions for this registry will be merged for checking, and unknown keys are allowed. */ export function index(registry: string, id: core.FullResourceLocation | readonly core.FullResourceLocation[] | undefined, options?: Options): core.SyncChecker<NbtCompoundNode> export function index(registry: string, id: core.FullResourceLocation, options?: Options): core.SyncChecker<NbtCompoundNode> export function index(registry: string, id: core.FullResourceLocation | readonly core.FullResourceLocation[] | undefined, options: Options = {}): core.SyncChecker<NbtCompoundNode> { switch (registry) { case 'custom:blockitemstates': const blockIds = getBlocksFromItem(id as core.FullResourceLocation) return blockIds ? blockStates(blockIds, options) : core.checker.noop case 'custom:blockstates': return blockStates([id as string], options) case 'custom:spawnitemtag': const entityId = getEntityFromItem(id as core.FullResourceLocation) return entityId ? index('entity_type', entityId, options) : core.checker.noop default: return (node, ctx) => { // const { allowUnknownKey, value } = resolveRootRegistry(registry, id, ctx, node) // options.allowUnknownKey ||= allowUnknownKey // compound(value, options)(node, ctx) } } } /** * @param identifier An identifier of mcdoc compound definition. e.g. `::minecraft::util::invitem::InventoryItem` */ export function definition(identifier: `::${string}::${string}`, options: Options = {}): core.SyncChecker<NbtCompoundNode> { const index = identifier.lastIndexOf('::') const module = identifier.slice(0, index) const compoundDef = identifier.slice(index + 2) const path: core.SymbolPath = { category: 'mcdoc', path: [module, compoundDef] } return (node, ctx) => { // const { allowUnknownKey, value } = resolveSymbolPaths([path], ctx, node) // options.allowUnknownKey ||= allowUnknownKey // compound(value, options)(node, ctx) } } export function blockStates(blocks: string[], _options: Options = {}): core.SyncChecker<NbtCompoundNode> { return (node, ctx) => { const states = core.getStates('block', blocks, ctx) for (const { key: keyNode, value: valueNode } of node.children) { if (!keyNode || !valueNode) { continue } // Type check. if (valueNode.type === 'nbt:byte' && (ctx.src.slice(valueNode.range).toLowerCase() === 'false' || ctx.src.slice(valueNode.range).toLowerCase() === 'true')) { ctx.err.report(localize('nbt.checker.block-states.fake-boolean'), valueNode, core.ErrorSeverity.Warning) continue } else if (valueNode.type !== 'string' && valueNode.type !== 'nbt:int') { ctx.err.report(localize('nbt.checker.block-states.unexpected-value-type'), valueNode, core.ErrorSeverity.Warning) continue } if (Object.keys(states).includes(keyNode.value)) { // The current state exists. Check the value. const stateValues = states[keyNode.value]! if (!stateValues.includes(valueNode.value.toString())) { ctx.err.report(localize('expected-got', stateValues, localeQuote(valueNode.value.toString())), valueNode, core.ErrorSeverity.Warning) } } else { // The current state doesn't exist. ctx.err.report( localize('nbt.checker.block-states.unknown-state', localeQuote(keyNode.value), blocks), keyNode, core.ErrorSeverity.Warning ) } } } } /** * @param path The {@link core.SymbolPath} to the compound definition. */ export function compound(data: any, options: Options = {}): core.SyncChecker<NbtCompoundNode> { return (node, ctx) => { for (const { key: keyNode, value: valueNode } of node.children) { if (!keyNode || !valueNode) { continue } const key = keyNode.value const fieldData = data[key] if (fieldData) { fieldData.query.enter({ usage: { type: 'reference', node: keyNode } }) fieldValue(fieldData.data, options)(valueNode, ctx) } else if (!options.allowUnknownKey) { ctx.err.report(localize('unknown-key', localeQuote(key)), keyNode, core.ErrorSeverity.Warning) } } } } export function enum_(path: core.SymbolPath | undefined, _options: Options = {}): core.SyncChecker<NbtPrimitiveNode> { if (!path) { return core.checker.noop } return (node, ctx) => { // const query = ctx.symbols.query(ctx.doc, path.category, ...path.path) // const data = query.symbol?.data as mcdoc.EnumNode.SymbolData | undefined // // Check type. // if (data?.enumKind && node.type !== data.enumKind && node.type !== `nbt:${data.enumKind}`) { // ctx.err.report(localize('expected', localize(`nbt.node.${data.enumKind}`)), node, core.ErrorSeverity.Warning) // } // // Get all enum members. // const enumMembers: Record<string, string> = {} // query.forEachMember((name, memberQuery) => { // const value = (memberQuery.symbol?.data as mcdoc.EnumFieldNode.SymbolData | undefined)?.value // if (value !== undefined) { // enumMembers[name] = value.toString() // } // }) // // Check value. // if (!Object.values(enumMembers).includes(node.value.toString())) { // ctx.err.report(localize('expected', // Object.entries(enumMembers).map(([k, v]) => `${k} = ${v}`) // ), node, core.ErrorSeverity.Warning) // } } } /** * @param id If set to `undefined` or an empty array, all mcdoc compound definitions for this registry will be merged for checking, and unknown keys are allowed. */ export function path(registry: string, id: core.FullResourceLocation | readonly core.FullResourceLocation[] | undefined): core.SyncChecker<NbtPathNode> { return (node, ctx) => { // const resolveResult = resolveRootRegistry(registry, id, ctx, undefined) // let targetType: mcdoc.McdocType | undefined = { // kind: 'dispatcher', // registry, // index: ((): mcdoc.DispatcherData['index'] => { // if (id === undefined) { // return { kind: 'static', value: { keyword: '()' } } // } else if (typeof id === 'string') { // return { kind: 'static', value: id } // } else { // return id.map(v => ({ kind: 'static', value: v })) // } // })(), // } // const options: Options = { allowUnknownKey: resolveResult.allowUnknownKey, isPredicate: true } // let currentCompound: NbtCompoundNode | undefined // for (const child of node.children) { // if (NbtCompoundNode.is(child)) { // // Compound filter. // currentCompound = child // if (data?.type === 'union') { // } // if (data?.type === 'resolved_compound') { // compound(data.data, options)(child, ctx) // } else { // ctx.err.report(localize('nbt.checker.path.unexpected-filter'), child, core.ErrorSeverity.Warning) // } // } else if (core.StringNode.is(child)) { // // Key. // if (data?.type === 'union') { // } // if (data?.type === 'resolved_compound') { // const fieldData: ResolvedCompoundData[string] = data.data[child.value] // if (fieldData) { // fieldData.query.enter({ usage: { type: 'reference', node: child } }) // if (fieldData.data.type === 'byte_array' || fieldData.data.type === 'int_array' || fieldData.data.type === 'long_array' || fieldData.data.type === 'list' || fieldData.data.type === 'union') { // data = fieldData.data // } else { // const resolveResult = resolveSymbolData(fieldData.data, ctx, currentCompound) // if (resolveResult.value) { // options.allowUnknownKey ||= resolveResult.allowUnknownKey // data.data = resolveResult.value // } else { // data = undefined // } // } // targetType = fieldData.data // } else { // if (!options.allowUnknownKey) { // ctx.err.report(localize('unknown-key', localeQuote(child.value)), child, core.ErrorSeverity.Warning) // } // targetType = undefined // break // } // } else { // ctx.err.report(localize('nbt.checker.path.unexpected-key'), child, core.ErrorSeverity.Warning) // targetType = undefined // break // } // currentCompound = undefined // } else { // // Index. // if (data?.type === 'byte_array' || data?.type === 'int_array' || data?.type === 'long_array' || data?.type === 'list') { // // Check content. // if (child.children !== undefined) { // const [content] = child.children // if (content.type === 'integer') { // const absIndex = content.value < 0 ? -1 - content.value : content.value // const [, maxLength] = data.lengthRange ?? [undefined, undefined] // if (maxLength !== undefined && absIndex >= maxLength) { // ctx.err.report(localize('nbt.checker.path.index-out-of-bound', content.value, maxLength), content, core.ErrorSeverity.Warning) // } // } else { // let isUnexpectedFilter = true // if (data.type === 'list') { // const { allowUnknownKey, value } = resolveSymbolData(data.item, ctx, currentCompound) // options.allowUnknownKey ||= allowUnknownKey // if (value) { // isUnexpectedFilter = false // compound(value, options)(content, ctx) // } // } // if (isUnexpectedFilter) { // ctx.err.report(localize('nbt.checker.path.unexpected-filter'), content, core.ErrorSeverity.Warning) // targetType = undefined // break // } // currentCompound = content // } // } // // Set data for the next iteration. // if (data.type === 'list') { // const { allowUnknownKey, value } = resolveSymbolData(data.item, ctx, currentCompound) // options.allowUnknownKey ||= allowUnknownKey // targetType = data.item // if (value) { // data = { type: 'resolved_compound', data: value } // } else { // data = undefined // } // } else { // targetType = { // type: data.type.split('_')[0] as 'byte' | 'int' | 'long', // valueRange: data.valueRange, // } // data = undefined // } // } else { // ctx.err.report(localize('nbt.checker.path.unexpected-index'), child, core.ErrorSeverity.Warning) // targetType = undefined // break // } // } // } // ctx.ops.set(node, 'targetType', targetType) } } export function fieldValue(type: mcdoc.McdocType, options: Options): core.SyncChecker<NbtNode> { const isInRange = (value: number, [min, max]: [number | undefined, number | undefined]) => (min ?? -Infinity) <= value && value <= (max ?? Infinity) const ExpectedTypes: Record<Exclude<mcdoc.McdocType['kind'], 'any' | 'dispatcher' | 'enum' | 'literal' | 'reference' | 'union'>, NbtNode['type']> = { boolean: 'nbt:byte', byte: 'nbt:byte', byte_array: 'nbt:byte_array', double: 'nbt:double', float: 'nbt:float', int: 'nbt:int', int_array: 'nbt:int_array', list: 'nbt:list', long: 'nbt:long', long_array: 'nbt:long_array', short: 'nbt:short', string: 'string', struct: 'nbt:compound', tuple: 'nbt:list', } return (node, ctx): void => { // Rough type check. if (type.kind !== 'any' && type.kind !== 'dispatcher' && type.kind !== 'enum' && type.kind !== 'literal' && type.kind !== 'reference' && type.kind !== 'union' && node.type !== ExpectedTypes[type.kind]) { ctx.err.report(localize('expected', localizeTag(ExpectedTypes[type.kind])), node, core.ErrorSeverity.Warning) return } switch (type.kind) { case 'boolean': node = node as NbtByteNode if (node.value !== 0 && node.value !== 1) { ctx.err.report( localize('nbt.checker.boolean.out-of-range', localeQuote('0b'), localeQuote('1b')), node, core.ErrorSeverity.Warning ) } break case 'byte_array': case 'int_array': case 'long_array': node = node as NbtPrimitiveArrayNode if (type.lengthRange && !isInRange(node.children.length, type.lengthRange)) { ctx.err.report(localize('expected', localize('nbt.checker.collection.length-between', localizeTag(node.type), type.lengthRange[0] ?? '-∞', type.lengthRange[1] ?? '+∞' )), node, core.ErrorSeverity.Warning) } if (type.valueRange) { for (const { value: childNode } of node.children) { if (childNode && !isInRange(Number(childNode.value), type.valueRange)) { ctx.err.report(localize('number.between', type.valueRange[0] ?? '-∞', type.valueRange[1] ?? '+∞' ), node, core.ErrorSeverity.Warning) } } } break case 'byte': case 'short': case 'int': case 'long': case 'float': case 'double': node = node as NbtNumberNode if (type.valueRange && !isInRange(Number(node.value), type.valueRange)) { ctx.err.report(localize('number.between', type.valueRange[0] ?? '-∞', type.valueRange[1] ?? '+∞' ), node, core.ErrorSeverity.Warning) } break case 'dispatcher': node = node as NbtCompoundNode // const id = resolveFieldPath(node.parent?.parent, type.index.path) // if (type.index.registry) { // if (ExtendableRootRegistry.is(type.index.registry)) { // index(type.index.registry, id ? core.ResourceLocation.lengthen(id) : undefined, options)(node, ctx) // } else if (id) { // index(type.index.registry, core.ResourceLocation.lengthen(id), options)(node, ctx) // } // } break case 'list': node = node as NbtListNode type = mcdoc.simplifyListType(type) if (type.lengthRange && !isInRange(node.children.length, type.lengthRange)) { ctx.err.report(localize('expected', localize('nbt.checker.collection.length-between', localizeTag(node.type), type.lengthRange[0] ?? '-∞', type.lengthRange[1] ?? '+∞' )), node, core.ErrorSeverity.Warning) } for (const { value: childNode } of node.children) { if (childNode) { fieldValue(type.item, options)(childNode, ctx) } } break case 'string': node = node as core.StringNode let suffix = '' let valueNode: NbtNode = node if (core.ItemNode.is(node.parent) && NbtListNode.is(node.parent.parent)) { suffix = '[]' valueNode = node.parent.parent } if (core.PairNode.is<core.StringNode, NbtNode>(valueNode.parent)) { const structMcdocPath = valueNode.parent.key?.symbol?.parentSymbol?.path.join('::') const key = valueNode.parent.key?.value const path = `${structMcdocPath}.${key}${suffix}` const parserName = getSpecialStringParser(path) if (parserName) { try { const parser = ctx.meta.getParser(parserName) const result = core.parseStringValue(parser, node.value, node.valueMap, ctx) if (result !== core.Failure) { node.children = [result] result.parent = node } } catch (e) { ctx.logger.error('[nbt.checker.fieldValue#string]', e) } } } break case 'reference': node = node as NbtCompoundNode // if (type.symbol) { // const { allowUnknownKey, value } = resolveSymbolPaths([type.symbol], ctx, node) // compound(value, { ...options, allowUnknownKey: options.allowUnknownKey || allowUnknownKey })(node, ctx) // } break case 'union': type = mcdoc.flattenUnionType(type) if (type.members.length === 0) { ctx.err.report( localize('nbt.checker.compound.field.union-empty-members'), core.PairNode.is(node.parent) ? (node.parent.key ?? node.parent) : node, core.ErrorSeverity.Warning ) } else { (core.checker.any(type.members.map(t => fieldValue(t, options))) as core.SyncChecker<NbtNode>)(node, ctx) } break } } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { Features } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { FeatureClient } from "../featureClient"; import { FeatureResult, FeaturesListAllNextOptionalParams, FeaturesListAllOptionalParams, FeaturesListNextOptionalParams, FeaturesListOptionalParams, FeaturesListAllResponse, FeaturesListResponse, FeaturesGetOptionalParams, FeaturesGetResponse, FeaturesRegisterOptionalParams, FeaturesRegisterResponse, FeaturesUnregisterOptionalParams, FeaturesUnregisterResponse, FeaturesListAllNextResponse, FeaturesListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing Features operations. */ export class FeaturesImpl implements Features { private readonly client: FeatureClient; /** * Initialize a new instance of the class Features class. * @param client Reference to the service client */ constructor(client: FeatureClient) { this.client = client; } /** * Gets all the preview features that are available through AFEC for the subscription. * @param options The options parameters. */ public listAll( options?: FeaturesListAllOptionalParams ): PagedAsyncIterableIterator<FeatureResult> { const iter = this.listAllPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAllPagingPage(options); } }; } private async *listAllPagingPage( options?: FeaturesListAllOptionalParams ): AsyncIterableIterator<FeatureResult[]> { let result = await this._listAll(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAllNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listAllPagingAll( options?: FeaturesListAllOptionalParams ): AsyncIterableIterator<FeatureResult> { for await (const page of this.listAllPagingPage(options)) { yield* page; } } /** * Gets all the preview features in a provider namespace that are available through AFEC for the * subscription. * @param resourceProviderNamespace The namespace of the resource provider for getting features. * @param options The options parameters. */ public list( resourceProviderNamespace: string, options?: FeaturesListOptionalParams ): PagedAsyncIterableIterator<FeatureResult> { const iter = this.listPagingAll(resourceProviderNamespace, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(resourceProviderNamespace, options); } }; } private async *listPagingPage( resourceProviderNamespace: string, options?: FeaturesListOptionalParams ): AsyncIterableIterator<FeatureResult[]> { let result = await this._list(resourceProviderNamespace, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceProviderNamespace, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceProviderNamespace: string, options?: FeaturesListOptionalParams ): AsyncIterableIterator<FeatureResult> { for await (const page of this.listPagingPage( resourceProviderNamespace, options )) { yield* page; } } /** * Gets all the preview features that are available through AFEC for the subscription. * @param options The options parameters. */ private _listAll( options?: FeaturesListAllOptionalParams ): Promise<FeaturesListAllResponse> { return this.client.sendOperationRequest({ options }, listAllOperationSpec); } /** * Gets all the preview features in a provider namespace that are available through AFEC for the * subscription. * @param resourceProviderNamespace The namespace of the resource provider for getting features. * @param options The options parameters. */ private _list( resourceProviderNamespace: string, options?: FeaturesListOptionalParams ): Promise<FeaturesListResponse> { return this.client.sendOperationRequest( { resourceProviderNamespace, options }, listOperationSpec ); } /** * Gets the preview feature with the specified name. * @param resourceProviderNamespace The resource provider namespace for the feature. * @param featureName The name of the feature to get. * @param options The options parameters. */ get( resourceProviderNamespace: string, featureName: string, options?: FeaturesGetOptionalParams ): Promise<FeaturesGetResponse> { return this.client.sendOperationRequest( { resourceProviderNamespace, featureName, options }, getOperationSpec ); } /** * Registers the preview feature for the subscription. * @param resourceProviderNamespace The namespace of the resource provider. * @param featureName The name of the feature to register. * @param options The options parameters. */ register( resourceProviderNamespace: string, featureName: string, options?: FeaturesRegisterOptionalParams ): Promise<FeaturesRegisterResponse> { return this.client.sendOperationRequest( { resourceProviderNamespace, featureName, options }, registerOperationSpec ); } /** * Unregisters the preview feature for the subscription. * @param resourceProviderNamespace The namespace of the resource provider. * @param featureName The name of the feature to unregister. * @param options The options parameters. */ unregister( resourceProviderNamespace: string, featureName: string, options?: FeaturesUnregisterOptionalParams ): Promise<FeaturesUnregisterResponse> { return this.client.sendOperationRequest( { resourceProviderNamespace, featureName, options }, unregisterOperationSpec ); } /** * ListAllNext * @param nextLink The nextLink from the previous successful call to the ListAll method. * @param options The options parameters. */ private _listAllNext( nextLink: string, options?: FeaturesListAllNextOptionalParams ): Promise<FeaturesListAllNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listAllNextOperationSpec ); } /** * ListNext * @param resourceProviderNamespace The namespace of the resource provider for getting features. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceProviderNamespace: string, nextLink: string, options?: FeaturesListNextOptionalParams ): Promise<FeaturesListNextResponse> { return this.client.sendOperationRequest( { resourceProviderNamespace, nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listAllOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Features/features", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.FeatureOperationsListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.FeatureOperationsListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceProviderNamespace ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.FeatureResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceProviderNamespace, Parameters.featureName ], headerParameters: [Parameters.accept], serializer }; const registerOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/register", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.FeatureResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceProviderNamespace, Parameters.featureName ], headerParameters: [Parameters.accept], serializer }; const unregisterOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/unregister", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.FeatureResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceProviderNamespace, Parameters.featureName ], headerParameters: [Parameters.accept], serializer }; const listAllNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.FeatureOperationsListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.FeatureOperationsListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceProviderNamespace ], headerParameters: [Parameters.accept], serializer };
the_stack
import {addImport, paths, RecipeBuilder} from "@blitzjs/installer" import j from "jscodeshift" import {join} from "path" export default RecipeBuilder() .setName("Base Web") .setDescription(`This will install all necessary dependencies and configure Base Web for use.`) .setOwner("Konrad Kalemba <konrad@kale.mba>") .setRepoLink("https://github.com/blitz-js/blitz") .addAddDependenciesStep({ stepId: "addDeps", stepName: "Add dependencies", explanation: `Add 'baseui' and Styletron as a dependency too -- it's a toolkit for CSS in JS styling which Base Web relies on.`, packages: [ {name: "baseui", version: "10.x"}, {name: "styletron-engine-atomic", version: "1.x"}, {name: "styletron-react", version: "6.x"}, ], }) .addNewFilesStep({ stepId: "addStyletronUtil", stepName: "Add Styletron util file", explanation: `Next, we need to add a util file that will help us to make Styletron work both client- and server-side.`, targetDirectory: "./utils", templatePath: join(__dirname, "templates", "utils"), templateValues: {}, }) .addTransformFilesStep({ stepId: "addStyletronAndBaseProvidersToApp", stepName: "Import required providers and wrap the root of the app with them", explanation: `Additionally we supply StyletronProvider with 'value' and 'debug' props. BaseProvider requires a 'theme' prop we set with default Base Web's light theme.`, singleFileSearch: paths.app(), transform(program) { const styletronProviderImport = j.importDeclaration( [j.importSpecifier(j.identifier("Provider"), j.identifier("StyletronProvider"))], j.literal("styletron-react"), ) const styletronAndDebugImport = j.importDeclaration( [j.importSpecifier(j.identifier("styletron")), j.importSpecifier(j.identifier("debug"))], j.literal("utils/styletron"), ) const themeAndBaseProviderImport = j.importDeclaration( [ j.importSpecifier(j.identifier("LightTheme")), j.importSpecifier(j.identifier("BaseProvider")), ], j.literal("baseui"), ) addImport(program, styletronProviderImport) addImport(program, styletronAndDebugImport) addImport(program, themeAndBaseProviderImport) program .find(j.JSXElement) .filter( (path) => path.parent?.parent?.parent?.value?.id?.name === "App" && path.parent?.value.type === j.ReturnStatement.toString(), ) .forEach((path) => { const {node} = path path.replace( j.jsxElement( j.jsxOpeningElement(j.jsxIdentifier("StyletronProvider"), [ j.jsxAttribute( j.jsxIdentifier("value"), j.jsxExpressionContainer(j.identifier("styletron")), ), j.jsxAttribute( j.jsxIdentifier("debug"), j.jsxExpressionContainer(j.identifier("debug")), ), j.jsxAttribute(j.jsxIdentifier("debugAfterHydration")), ]), j.jsxClosingElement(j.jsxIdentifier("StyletronProvider")), [ j.literal("\n"), j.jsxElement( j.jsxOpeningElement(j.jsxIdentifier("BaseProvider"), [ j.jsxAttribute( j.jsxIdentifier("theme"), j.jsxExpressionContainer(j.identifier("LightTheme")), ), ]), j.jsxClosingElement(j.jsxIdentifier("BaseProvider")), [j.literal("\n"), node, j.literal("\n")], ), j.literal("\n"), ], ), ) }) return program }, }) .addTransformFilesStep({ stepId: "modifyGetInitialPropsAndAddStylesheetsToDocument", stepName: "Modify getInitialProps method and add stylesheets to Document", explanation: `To make Styletron work server-side we need to modify getInitialProps method of custom Document class. We also have to put Styletron's generated stylesheets in DocumentHead.`, singleFileSearch: paths.document(), transform(program) { const styletronProviderImport = j.importDeclaration( [j.importSpecifier(j.identifier("Provider"), j.identifier("StyletronProvider"))], j.literal("styletron-react"), ) const styletronServerAndSheetImport = j.importDeclaration( [j.importSpecifier(j.identifier("Sheet"))], j.literal("styletron-engine-atomic"), ) const styletronImport = j.importDeclaration( [j.importSpecifier(j.identifier("styletron"))], j.literal("utils/styletron"), ) addImport(program, styletronProviderImport) addImport(program, styletronServerAndSheetImport) addImport(program, styletronImport) program.find(j.ImportDeclaration, {source: {value: "blitz"}}).forEach((blitzImportPath) => { let specifiers = blitzImportPath.value.specifiers || [] if ( !specifiers .filter((spec) => j.ImportSpecifier.check(spec)) .some((node) => (node as j.ImportSpecifier)?.imported?.name === "DocumentContext") ) { specifiers.push(j.importSpecifier(j.identifier("DocumentContext"))) } }) program.find(j.ClassDeclaration).forEach((path) => { const props = j.typeAlias( j.identifier("MyDocumentProps"), null, j.objectTypeAnnotation([ j.objectTypeProperty( j.identifier("stylesheets"), j.arrayTypeAnnotation(j.genericTypeAnnotation(j.identifier("Sheet"), null)), false, ), ]), ) path.insertBefore(props) path.value.superTypeParameters = j.typeParameterInstantiation([ j.genericTypeAnnotation(j.identifier("MyDocumentProps"), null), ]) }) program.find(j.ClassBody).forEach((path) => { const {node} = path const ctxParam = j.identifier("ctx") ctxParam.typeAnnotation = j.tsTypeAnnotation( j.tsTypeReference(j.identifier("DocumentContext")), ) const stylesheetsObjectProperty = j.objectProperty( j.identifier("stylesheets"), j.identifier("stylesheets"), ) stylesheetsObjectProperty.shorthand = true const getInitialPropsBody = j.blockStatement([ j.variableDeclaration("const", [ j.variableDeclarator( j.identifier("originalRenderPage"), j.memberExpression(j.identifier("ctx"), j.identifier("renderPage")), ), ]), j.expressionStatement( j.assignmentExpression( "=", j.memberExpression(j.identifier("ctx"), j.identifier("renderPage")), j.arrowFunctionExpression( [], j.callExpression(j.identifier("originalRenderPage"), [ j.objectExpression([ j.objectProperty( j.identifier("enhanceApp"), j.arrowFunctionExpression( [j.identifier("App")], j.arrowFunctionExpression( [j.identifier("props")], j.jsxElement( j.jsxOpeningElement(j.jsxIdentifier("StyletronProvider"), [ j.jsxAttribute( j.jsxIdentifier("value"), j.jsxExpressionContainer(j.identifier("styletron")), ), ]), j.jsxClosingElement(j.jsxIdentifier("StyletronProvider")), [ j.literal("\n"), j.jsxElement( j.jsxOpeningElement( j.jsxIdentifier("App"), [j.jsxSpreadAttribute(j.identifier("props"))], true, ), ), j.literal("\n"), ], ), ), ), ), ]), ]), ), ), ), j.variableDeclaration("const", [ j.variableDeclarator( j.identifier("initialProps"), j.awaitExpression( j.callExpression( j.memberExpression(j.identifier("Document"), j.identifier("getInitialProps")), [j.identifier("ctx")], ), ), ), ]), j.variableDeclaration("const", [ j.variableDeclarator( j.identifier("stylesheets"), j.logicalExpression( "||", j.callExpression( j.memberExpression(j.identifier("styletron"), j.identifier("getStylesheets")), [], ), j.arrayExpression([]), ), ), ]), j.returnStatement( j.objectExpression([ j.spreadElement(j.identifier("initialProps")), stylesheetsObjectProperty, ]), ), ]) const getInitialPropsMethod = j.classMethod( "method", j.identifier("getInitialProps"), [ctxParam], getInitialPropsBody, false, true, ) getInitialPropsMethod.async = true // TODO: better way will be to check if the method already exists and modify it or else add it // currently it gets added assuming it did not exist before node.body.splice(0, 0, getInitialPropsMethod) }) program .find(j.JSXElement, {openingElement: {name: {name: "DocumentHead"}}}) .forEach((path) => { const {node} = path path.replace( j.jsxElement( j.jsxOpeningElement(j.jsxIdentifier("DocumentHead")), j.jsxClosingElement(j.jsxIdentifier("DocumentHead")), [ ...(node.children || []), j.literal("\n"), j.jsxExpressionContainer( j.callExpression( j.memberExpression( j.memberExpression( j.memberExpression(j.thisExpression(), j.identifier("props")), j.identifier("stylesheets"), ), j.identifier("map"), ), [ j.arrowFunctionExpression( [j.identifier("sheet"), j.identifier("i")], j.jsxElement( j.jsxOpeningElement( j.jsxIdentifier("style"), [ j.jsxAttribute( j.jsxIdentifier("className"), j.literal("_styletron_hydrate_"), ), j.jsxAttribute( j.jsxIdentifier("dangerouslySetInnerHTML"), j.jsxExpressionContainer( j.objectExpression([ j.objectProperty( j.identifier("__html"), j.memberExpression( j.identifier("sheet"), j.identifier("css"), ), ), ]), ), ), j.jsxAttribute( j.jsxIdentifier("media"), j.jsxExpressionContainer( j.memberExpression( j.memberExpression( j.identifier("sheet"), j.identifier("attrs"), ), j.identifier("media"), ), ), ), j.jsxAttribute( j.jsxIdentifier("data-hydrate"), j.jsxExpressionContainer( j.memberExpression( j.memberExpression( j.identifier("sheet"), j.identifier("attrs"), ), j.stringLiteral("data-hydrate"), true, ), ), ), j.jsxAttribute( j.jsxIdentifier("key"), j.jsxExpressionContainer(j.jsxIdentifier("i")), ), ], true, ), ), ), ], ), ), j.literal("\n"), ], ), ) }) return program }, }) .build()
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * An intent represents a user's intent to interact with a conversational agent. * * To get more information about Intent, see: * * * [API documentation](https://cloud.google.com/dialogflow/cx/docs/reference/rest/v3/projects.locations.agents.intents) * * How-to Guides * * [Official Documentation](https://cloud.google.com/dialogflow/cx/docs) * * ## Example Usage * ### Dialogflowcx Intent Full * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const agent = new gcp.diagflow.CxAgent("agent", { * displayName: "dialogflowcx-agent", * location: "global", * defaultLanguageCode: "en", * supportedLanguageCodes: [ * "fr", * "de", * "es", * ], * timeZone: "America/New_York", * description: "Example description.", * avatarUri: "https://cloud.google.com/_static/images/cloud/icons/favicons/onecloud/super_cloud.png", * enableStackdriverLogging: true, * enableSpellCorrection: true, * speechToTextSettings: { * enableSpeechAdaptation: true, * }, * }); * const basicIntent = new gcp.diagflow.CxIntent("basicIntent", { * parent: agent.id, * displayName: "Example", * priority: 1, * description: "Intent example", * trainingPhrases: [{ * parts: [ * { * text: "training", * }, * { * text: "phrase", * }, * { * text: "example", * }, * ], * repeatCount: 1, * }], * parameters: [{ * id: "param1", * entityType: "projects/-/locations/-/agents/-/entityTypes/sys.date", * }], * labels: { * label1: "value1", * label2: "value2", * }, * }); * ``` * * ## Import * * Intent can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:diagflow/cxIntent:CxIntent default {{parent}}/intents/{{name}} * ``` * * ```sh * $ pulumi import gcp:diagflow/cxIntent:CxIntent default {{parent}}/{{name}} * ``` */ export class CxIntent extends pulumi.CustomResource { /** * Get an existing CxIntent resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: CxIntentState, opts?: pulumi.CustomResourceOptions): CxIntent { return new CxIntent(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:diagflow/cxIntent:CxIntent'; /** * Returns true if the given object is an instance of CxIntent. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is CxIntent { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === CxIntent.__pulumiType; } /** * Human readable description for better understanding an intent like its scope, content, result etc. Maximum character limit: 140 characters. */ public readonly description!: pulumi.Output<string | undefined>; /** * The human-readable name of the intent, unique within the agent. */ public readonly displayName!: pulumi.Output<string>; /** * Indicates whether this is a fallback intent. Currently only default fallback intent is allowed in the agent, which is added upon agent creation. * Adding training phrases to fallback intent is useful in the case of requests that are mistakenly matched, since training phrases assigned to fallback intents act as negative examples that triggers no-match event. */ public readonly isFallback!: pulumi.Output<boolean | undefined>; /** * The key/value metadata to label an intent. Labels can contain lowercase letters, digits and the symbols '-' and '_'. International characters are allowed, including letters from unicase alphabets. Keys must start with a letter. Keys and values can be no longer than 63 characters and no more than 128 bytes. * Prefix "sys-" is reserved for Dialogflow defined labels. Currently allowed Dialogflow defined labels include: * sys-head * sys-contextual The above labels do not require value. "sys-head" means the intent is a head intent. "sys.contextual" means the intent is a contextual intent. * An object containing a list of "key": value pairs. Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }. */ public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>; /** * The language of the following fields in intent: * Intent.training_phrases.parts.text * If not specified, the agent's default language is used. Many languages are supported. Note: languages must be enabled in the agent before they can be used. */ public readonly languageCode!: pulumi.Output<string | undefined>; /** * The unique identifier of the intent. Format: projects/<Project ID>/locations/<Location ID>/agents/<Agent * ID>/intents/<Intent ID>. */ public /*out*/ readonly name!: pulumi.Output<string>; /** * The collection of parameters associated with the intent. * Structure is documented below. */ public readonly parameters!: pulumi.Output<outputs.diagflow.CxIntentParameter[] | undefined>; /** * The agent to create an intent for. * Format: projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>. */ public readonly parent!: pulumi.Output<string | undefined>; /** * The priority of this intent. Higher numbers represent higher priorities. * If the supplied value is unspecified or 0, the service translates the value to 500,000, which corresponds to the Normal priority in the console. * If the supplied value is negative, the intent is ignored in runtime detect intent requests. */ public readonly priority!: pulumi.Output<number | undefined>; /** * The collection of training phrases the agent is trained on to identify the intent. * Structure is documented below. */ public readonly trainingPhrases!: pulumi.Output<outputs.diagflow.CxIntentTrainingPhrase[] | undefined>; /** * Create a CxIntent resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: CxIntentArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: CxIntentArgs | CxIntentState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as CxIntentState | undefined; inputs["description"] = state ? state.description : undefined; inputs["displayName"] = state ? state.displayName : undefined; inputs["isFallback"] = state ? state.isFallback : undefined; inputs["labels"] = state ? state.labels : undefined; inputs["languageCode"] = state ? state.languageCode : undefined; inputs["name"] = state ? state.name : undefined; inputs["parameters"] = state ? state.parameters : undefined; inputs["parent"] = state ? state.parent : undefined; inputs["priority"] = state ? state.priority : undefined; inputs["trainingPhrases"] = state ? state.trainingPhrases : undefined; } else { const args = argsOrState as CxIntentArgs | undefined; if ((!args || args.displayName === undefined) && !opts.urn) { throw new Error("Missing required property 'displayName'"); } inputs["description"] = args ? args.description : undefined; inputs["displayName"] = args ? args.displayName : undefined; inputs["isFallback"] = args ? args.isFallback : undefined; inputs["labels"] = args ? args.labels : undefined; inputs["languageCode"] = args ? args.languageCode : undefined; inputs["parameters"] = args ? args.parameters : undefined; inputs["parent"] = args ? args.parent : undefined; inputs["priority"] = args ? args.priority : undefined; inputs["trainingPhrases"] = args ? args.trainingPhrases : undefined; inputs["name"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(CxIntent.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering CxIntent resources. */ export interface CxIntentState { /** * Human readable description for better understanding an intent like its scope, content, result etc. Maximum character limit: 140 characters. */ description?: pulumi.Input<string>; /** * The human-readable name of the intent, unique within the agent. */ displayName?: pulumi.Input<string>; /** * Indicates whether this is a fallback intent. Currently only default fallback intent is allowed in the agent, which is added upon agent creation. * Adding training phrases to fallback intent is useful in the case of requests that are mistakenly matched, since training phrases assigned to fallback intents act as negative examples that triggers no-match event. */ isFallback?: pulumi.Input<boolean>; /** * The key/value metadata to label an intent. Labels can contain lowercase letters, digits and the symbols '-' and '_'. International characters are allowed, including letters from unicase alphabets. Keys must start with a letter. Keys and values can be no longer than 63 characters and no more than 128 bytes. * Prefix "sys-" is reserved for Dialogflow defined labels. Currently allowed Dialogflow defined labels include: * sys-head * sys-contextual The above labels do not require value. "sys-head" means the intent is a head intent. "sys.contextual" means the intent is a contextual intent. * An object containing a list of "key": value pairs. Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The language of the following fields in intent: * Intent.training_phrases.parts.text * If not specified, the agent's default language is used. Many languages are supported. Note: languages must be enabled in the agent before they can be used. */ languageCode?: pulumi.Input<string>; /** * The unique identifier of the intent. Format: projects/<Project ID>/locations/<Location ID>/agents/<Agent * ID>/intents/<Intent ID>. */ name?: pulumi.Input<string>; /** * The collection of parameters associated with the intent. * Structure is documented below. */ parameters?: pulumi.Input<pulumi.Input<inputs.diagflow.CxIntentParameter>[]>; /** * The agent to create an intent for. * Format: projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>. */ parent?: pulumi.Input<string>; /** * The priority of this intent. Higher numbers represent higher priorities. * If the supplied value is unspecified or 0, the service translates the value to 500,000, which corresponds to the Normal priority in the console. * If the supplied value is negative, the intent is ignored in runtime detect intent requests. */ priority?: pulumi.Input<number>; /** * The collection of training phrases the agent is trained on to identify the intent. * Structure is documented below. */ trainingPhrases?: pulumi.Input<pulumi.Input<inputs.diagflow.CxIntentTrainingPhrase>[]>; } /** * The set of arguments for constructing a CxIntent resource. */ export interface CxIntentArgs { /** * Human readable description for better understanding an intent like its scope, content, result etc. Maximum character limit: 140 characters. */ description?: pulumi.Input<string>; /** * The human-readable name of the intent, unique within the agent. */ displayName: pulumi.Input<string>; /** * Indicates whether this is a fallback intent. Currently only default fallback intent is allowed in the agent, which is added upon agent creation. * Adding training phrases to fallback intent is useful in the case of requests that are mistakenly matched, since training phrases assigned to fallback intents act as negative examples that triggers no-match event. */ isFallback?: pulumi.Input<boolean>; /** * The key/value metadata to label an intent. Labels can contain lowercase letters, digits and the symbols '-' and '_'. International characters are allowed, including letters from unicase alphabets. Keys must start with a letter. Keys and values can be no longer than 63 characters and no more than 128 bytes. * Prefix "sys-" is reserved for Dialogflow defined labels. Currently allowed Dialogflow defined labels include: * sys-head * sys-contextual The above labels do not require value. "sys-head" means the intent is a head intent. "sys.contextual" means the intent is a contextual intent. * An object containing a list of "key": value pairs. Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The language of the following fields in intent: * Intent.training_phrases.parts.text * If not specified, the agent's default language is used. Many languages are supported. Note: languages must be enabled in the agent before they can be used. */ languageCode?: pulumi.Input<string>; /** * The collection of parameters associated with the intent. * Structure is documented below. */ parameters?: pulumi.Input<pulumi.Input<inputs.diagflow.CxIntentParameter>[]>; /** * The agent to create an intent for. * Format: projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>. */ parent?: pulumi.Input<string>; /** * The priority of this intent. Higher numbers represent higher priorities. * If the supplied value is unspecified or 0, the service translates the value to 500,000, which corresponds to the Normal priority in the console. * If the supplied value is negative, the intent is ignored in runtime detect intent requests. */ priority?: pulumi.Input<number>; /** * The collection of training phrases the agent is trained on to identify the intent. * Structure is documented below. */ trainingPhrases?: pulumi.Input<pulumi.Input<inputs.diagflow.CxIntentTrainingPhrase>[]>; }
the_stack
import { HookIndex } from '../../../interfacesPublic'; import { HookParser, HookPosition } from '../../../interfacesPublic'; import { OutletOptions } from '../options/options'; import { isDevMode, Injectable, Renderer2, RendererFactory2 } from '@angular/core'; import { PlatformService } from '../../../platform/platformService'; /** * An atomic replace instruction. Reads as: Replace the text from startIndex to endIndex with replacement. */ interface ReplaceInstruction { startIndex: number; endIndex: number; replacement: string; } /** * Stores a HookPosition along with the parser who found it */ interface ParserResult { parser: HookParser; hookPosition: HookPosition; } /** * Stores the HookValue as well as the text surrounding it */ interface HookSegments { enclosing: boolean; textBefore: string; openingTag: string; innerValue: string; closingTag: string; textAfter: string; } /** * The service responsible for finding all Hooks in the content, replacing them with component placeholders * and creating the HookIndex */ @Injectable() export class HooksReplacer { private renderer: Renderer2; constructor(rendererFactory: RendererFactory2, private platform: PlatformService) { this.renderer = rendererFactory.createRenderer(null, null); } // 1. Replacing hooks // ----------------------------------------------------------------------------------------------------------------------- /** * Lets all registered parsers anaylyze the content to find all hooks within. Then replaces those hooks with component placeholder elements * (that will remain empty for now) and creates the hookIndex. * * It optionally also sanitizes the content and fixes paragraph artifacts. * * @param content - The text to parse * @param context - The current context object * @param parsers - All of the registered parsers * @param token - A random token to attach to all created selector elements * @param options - The current OutletOptions * @param hookIndex - The hookIndex object to fill */ replaceHooksWithNodes(content: string, context: any, parsers: Array<HookParser>, token: string, options: OutletOptions, hookIndex: HookIndex): {content: string, hookIndex: HookIndex} { let hookCount = 1; // Collect all parser results (before changing content), sort by startIndex let parserResults: Array<ParserResult> = []; for (const parser of parsers) { for (const hookPosition of parser.findHooks(content, context)) { parserResults.push({parser, hookPosition}); } } parserResults.sort((a, b) => a.hookPosition.openingTagStartIndex - b.hookPosition.openingTagStartIndex); // Validate parser results parserResults = this.validateHookPositions(parserResults, content); // Process parser results to // a) Create an array of simple ReplaceInstructions to replace the hooks with the component placeholders // b) Enter each found hook into hookIndex // c) Replace tag artifacts const selectorReplaceInstructions: Array<ReplaceInstruction> = []; for (const pr of parserResults) { // Some info about this hook const hookSegments = this.getHookSegments(pr.hookPosition, content); // Create ReplaceInstructions array // Notes: // 1. Attach some parsing info as attributes to the placeholders for dynamically creating the components later // 2. Use encoded tag syntax to make them pass sanitization unnoticed (decoded again below after sanitization) // 3. Since the component selector of lazy-loaded components can't be known at this point, use placeholders tags for now (replaced with real selectors in ComponentCreator) // 4. Still use custom tags however to circumvent HTML nesting rules for established tags (browser might autocorrect nesting structure otherwise) selectorReplaceInstructions.push({ startIndex: pr.hookPosition.openingTagStartIndex, endIndex: pr.hookPosition.openingTagEndIndex, replacement: this.encodeComponentPlaceholderElement('<dynamic-component-placeholder hookid="' + hookCount + '" parsetoken="' + token + '" ' + (pr.parser.name ? 'parser="' + pr.parser.name + '"' : '') + '>')}); selectorReplaceInstructions.push({ startIndex: hookSegments.enclosing ? pr.hookPosition.closingTagStartIndex : pr.hookPosition.openingTagEndIndex, endIndex: hookSegments.enclosing ? pr.hookPosition.closingTagEndIndex : pr.hookPosition.openingTagEndIndex, replacement: this.encodeComponentPlaceholderElement('</dynamic-component-placeholder>') }); // Enter hook into index hookIndex[hookCount] = { id: hookCount, parser: pr.parser, value: { openingTag: hookSegments.openingTag, closingTag: hookSegments.closingTag }, data: null, bindings: null, previousBindings: null, componentRef: null, dirtyInputs: new Set(), outputSubscriptions: {} }; hookCount++; // Remove tag artifacts (does not change parser results indexes) if (hookSegments.enclosing && options.fixParagraphTags) { const firstResult = this.removeTagArtifacts(hookSegments.textBefore, '<p>', '</p>', hookSegments.innerValue, '</p>', '<p>'); hookSegments.textBefore = firstResult.firstText; hookSegments.innerValue = firstResult.secondText; const secondResult = this.removeTagArtifacts(hookSegments.innerValue, '<p>', '</p>', hookSegments.textAfter, '</p>', '<p>'); hookSegments.innerValue = secondResult.firstText; hookSegments.textAfter = secondResult.secondText; content = hookSegments.textBefore + hookSegments.openingTag + hookSegments.innerValue + hookSegments.closingTag + hookSegments.textAfter; } } // Sort replace instructions by startIndex so indexModifier only applies to indexes that follow, not precede selectorReplaceInstructions.sort((a, b) => a.startIndex - b.startIndex); // Replace found hooks with encoded component placeholders let indexModifier = 0; for (const selectorReplaceInstruction of selectorReplaceInstructions) { const textBeforeSelector = content.substr(0, selectorReplaceInstruction.startIndex + indexModifier); const textAfterSelector = content.substr(selectorReplaceInstruction.endIndex + indexModifier); const oldDynamicTextLength = content.length; // Reassemble and correct index content = textBeforeSelector + selectorReplaceInstruction.replacement + textAfterSelector; indexModifier += content.length - oldDynamicTextLength; } // Sanitize? (ignores the encoded component selector elements) if (options.sanitize) { content = this.platform.sanitize(content); } // Decode component selector elements again content = this.decodeComponentPlaceholderElements(content); return { content: content, hookIndex: hookIndex }; } /** * Takes a HookPosition and returns the HookValue as well as the text surrounding it * * @param hookPosition - The HookPosition in question * @param content - The source text for the HookPosition */ private getHookSegments(hookPosition: HookPosition, content: string): HookSegments { const enclosing = (Number.isInteger(hookPosition.closingTagStartIndex) && Number.isInteger(hookPosition.closingTagEndIndex)); return { enclosing: enclosing, textBefore: content.substr(0, hookPosition.openingTagStartIndex), openingTag: content.substr(hookPosition.openingTagStartIndex, hookPosition.openingTagEndIndex - hookPosition.openingTagStartIndex), innerValue: enclosing ? content.substr(hookPosition.openingTagEndIndex, hookPosition.closingTagStartIndex - hookPosition.openingTagEndIndex) : null, closingTag: enclosing ? content.substr(hookPosition.closingTagStartIndex, hookPosition.closingTagEndIndex - hookPosition.closingTagStartIndex) : null, textAfter: enclosing ? content.substr(hookPosition.closingTagEndIndex) : content.substr(hookPosition.openingTagEndIndex) }; } /** * Checks the hookPositions of the combined parserResults to ensure they do not collide/overlap. * Any that do are removed from the results. * * @param parserResults - The parserResults from replaceHooksWithNodes() * @param content - The source text for the parserResults */ private validateHookPositions(parserResults: Array<ParserResult>, content: string): Array<ParserResult> { const checkedParserResults = []; outerloop: for (const [index, parserResult] of parserResults.entries()) { const enclosing = (Number.isInteger(parserResult.hookPosition.closingTagStartIndex) && Number.isInteger(parserResult.hookPosition.closingTagEndIndex)); const hookPos = parserResult.hookPosition; // Check if hook is in itself well-formed if (hookPos.openingTagStartIndex >= hookPos.openingTagEndIndex) { if (isDevMode()) { console.warn('Error when checking hook positions - openingTagEndIndex has to be greater than openingTagStartIndex. Ignoring.', hookPos); } continue; } if (enclosing && hookPos.openingTagEndIndex > hookPos.closingTagStartIndex) { if (isDevMode()) { console.warn('Error when checking hook positions - The closing tag must start after the opening tag has concluded. Ignoring.', hookPos); } continue; } if (enclosing && hookPos.closingTagStartIndex >= hookPos.closingTagEndIndex) { if (isDevMode()) { console.warn('Error when checking hook positions - closingTagEndIndex has to be greater than closingTagStartIndex. Ignoring.', hookPos); } continue; } // Check if hook overlaps with other hooks const previousHooks = parserResults.slice(0, index); innerloop: for (const previousHook of previousHooks) { const prevHookPos = previousHook.hookPosition; const prevIsEnclosing = (Number.isInteger(prevHookPos.closingTagStartIndex) && Number.isInteger(prevHookPos.closingTagEndIndex)); // Check if identical hook position if ( hookPos.openingTagStartIndex === prevHookPos.openingTagStartIndex && hookPos.openingTagEndIndex === prevHookPos.openingTagEndIndex && (!enclosing || !prevIsEnclosing || ( hookPos.closingTagStartIndex === prevHookPos.closingTagStartIndex && hookPos.closingTagEndIndex === prevHookPos.closingTagEndIndex )) ) { this.generateHookPosWarning('A hook with the same position as another hook was found. There may be multiple identical parsers active that are looking for the same hook. Ignoring duplicates.', hookPos, prevHookPos, content); continue outerloop; } // Opening tag must begin after previous opening tag has ended if (hookPos.openingTagStartIndex < prevHookPos.openingTagEndIndex) { this.generateHookPosWarning('Error when checking hook positions: Hook opening tag starts before previous hook opening tag ends. Ignoring.', hookPos, prevHookPos, content); continue outerloop; } // Opening tag must not overlap with previous closing tag if (prevIsEnclosing && !( hookPos.openingTagEndIndex <= prevHookPos.closingTagStartIndex || hookPos.openingTagStartIndex >= prevHookPos.closingTagEndIndex )) { this.generateHookPosWarning('Error when checking hook positions: Opening tag of hook overlaps with closing tag of previous hook. Ignoring.', hookPos, prevHookPos, content); continue outerloop; } // Closing tag must not overlap with previous closing tag if (prevIsEnclosing && enclosing && !( hookPos.closingTagEndIndex <= prevHookPos.closingTagStartIndex || hookPos.closingTagStartIndex >= prevHookPos.closingTagEndIndex )) { this.generateHookPosWarning('Error when checking hook positions: Closing tag of hook overlaps with closing tag of previous hook. Ignoring.', hookPos, prevHookPos, content); continue outerloop; } // Check if hooks are incorrectly nested, e.g. "<outer-hook><inner-hook></outer-hook></inner-hook>" if (enclosing && prevIsEnclosing && hookPos.openingTagEndIndex <= prevHookPos.closingTagStartIndex && hookPos.closingTagStartIndex >= prevHookPos.closingTagEndIndex ) { this.generateHookPosWarning('Error when checking hook positions: The closing tag of a nested hook lies beyond the closing tag of the outer hook. Ignoring.', hookPos, prevHookPos, content); continue outerloop; } } // If everything okay, add to result array checkedParserResults.push(parserResult); } return checkedParserResults; } /** * Outputs a warning in the console when the positions of two hooks are invalid in some manner * * @param message - The error message * @param hookPos - The first HookPosition * @param prevHookPos - The second HookPosition * @param content - The source text for the HookPositions */ private generateHookPosWarning(message: string, hookPos: HookPosition, prevHookPos: HookPosition, content: string): void { if (isDevMode()) { const prevHookSegments = this.getHookSegments(prevHookPos, content); const hookSegments = this.getHookSegments(hookPos, content); const prevHookData = { openingTag: prevHookSegments.openingTag, openingTagStartIndex: prevHookPos.openingTagStartIndex, openingTagEndIndex: prevHookPos.openingTagEndIndex, closingTag: prevHookSegments.closingTag, closingTagStartIndex: prevHookPos.closingTagStartIndex, closingTagEndIndex: prevHookPos.closingTagEndIndex }; const hookData = { openingTag: hookSegments.openingTag, openingTagStartIndex: hookPos.openingTagStartIndex, openingTagEndIndex: hookPos.openingTagEndIndex, closingTag: hookSegments.closingTag, closingTagStartIndex: hookPos.closingTagStartIndex, closingTagEndIndex: hookPos.closingTagEndIndex }; console.warn(message + '\nFirst hook: ', prevHookData, '\nSecond hook:', hookData); } } /** * When using an enclosing hook that is spread over several lines in an HTML editor, p-elements tend to get ripped apart. For example: * * <p><app-hook></p> * <h2>This is the hook content</h2> * <p></app-hook></p> * * would cause the innerValue of app-hook to have a lone closing and opening p-tag (as their counterparts are outside of the hook). * To clean up the HTML, this function removes a pair of these artifacts (e.g. <p> before hook, </p> inside hook) if BOTH are found. * This is important as the HTML parser will otherwise mess up the intended HTML and sometimes even put what should be ng-content below the component. * * @param firstText - The text on one side of the hook * @param firstArtifact - A string that should be removed from firstText... * @param firstRemoveIfAfter - ...if it appears after the last occurrence of this string * @param secondText - The text on the other side of the hook * @param secondArtifact - A string that should be removed from secondText... * @param secondRemoveIfBefore - ...if it appears before the first occurrence of this string */ private removeTagArtifacts(firstText: string, firstArtifact: string, firstRemoveIfAfter: string, secondText: string, secondArtifact: string = null, secondRemoveIfBefore: string): {firstText: string, secondText: string} { let firstArtifactFound = false; let secondArtifactFound = false; // a) Look for first artifact const firstArtifactIndex = firstText.lastIndexOf(firstArtifact); const firstArtifactIfAfterIndex = firstText.lastIndexOf(firstRemoveIfAfter); if ( (firstArtifactIndex >= 0 && firstArtifactIfAfterIndex === -1) || (firstArtifactIndex > firstArtifactIfAfterIndex) ) { firstArtifactFound = true; } // b) Look for second artifact const secondArtifactIndex = secondText.indexOf(secondArtifact); const secondArtifactIfBeforeIndex = secondText.indexOf(secondRemoveIfBefore); if ( // If startArtifact appears before startArtifactNotBefore (secondArtifactIndex >= 0 && secondArtifactIfBeforeIndex === -1) || (secondArtifactIndex < secondArtifactIfBeforeIndex) ) { secondArtifactFound = true; } // If artifacts found on both sides, remove both by overwriting them with empty spaces (doesn't change index) if (firstArtifactFound && secondArtifactFound) { firstText = firstText.substr(0, firstArtifactIndex) + ' '.repeat(firstArtifact.length) + firstText.substr(firstArtifactIndex + firstArtifact.length); secondText = secondText.substr(0, secondArtifactIndex) + ' '.repeat(secondArtifact.length) + secondText.substr(secondArtifactIndex + secondArtifact.length); } // Trim after artifacts removed return { firstText: firstText, secondText: secondText }; } /** * Encodes the special html chars in a component placeholder tag * * @param element - The placeholder element as a string */ encodeComponentPlaceholderElement(element: string): string { element = element.replace(/</g, '@@@hook-lt@@@'); element = element.replace(/>/g, '@@@hook-gt@@@'); element = element.replace(/"/g, '@@@hook-dq@@@'); return element; } /** * Decodes the special html chars in a component placeholder tag * * @param element - The placeholder element as a string */ decodeComponentPlaceholderElements(element: string): string { element = element.replace(/@@@hook-lt@@@/g, '<'); element = element.replace(/@@@hook-gt@@@/g, '>'); element = element.replace(/@@@hook-dq@@@/g, '"'); return element; } /** * Converts all HTML entities to normal characters * * @param text - The text with the potential HTML entities */ convertHTMLEntities(text: string): string { const div = this.renderer.createElement('div'); const result = text.replace(/&[#A-Za-z0-9]+;/gi, (hmtlEntity) => { // Replace invisible nbsp-whitespace with normal whitespace (not \u00A0). Leads to problems with JSON.parse() otherwise. if (hmtlEntity === ('&nbsp;')) { return ' '; } this.platform.setInnerContent(div,hmtlEntity); return this.platform.getInnerText(div); }); return result; } }
the_stack
import BN from 'bignumber.js'; import { flattenDeep } from 'lodash'; import { encodeParams, Loggy, ZWeb3 } from '@openzeppelin/upgrades'; import { MethodArgType } from '../prompts/prompt'; import { zipWith } from 'lodash'; import { isAddress, isHex } from 'web3-utils'; // TODO: Deprecate in favor of a combination of parseArg and parseArray export function parseArgs(args: string): string[] | never { if (typeof args !== 'string') throw Error(`Cannot parse ${typeof args}`); // The following is inspired from ethereum/remix (Copyright (c) 2016) // https://github.com/ethereum/remix/blob/89f34fc4f35eca0c386379550c300205d35bfae0/remix-lib/src/execution/txFormat.js#L51-L53 try { // Parse string to array. const parsedArgs = JSON.parse(`[${quoteArguments(args)}]`); // Replace boolean strings with boolean literals. return parsedArgs.map(value => { if (typeof value === 'string') { if (value.toLowerCase() === 'false') return false; else if (value.toLowerCase() === 'true') return true; } return value; }); } catch (e) { throw Error(`Error parsing arguments: ${e}`); } } function quoteArguments(args: string) { const START_LOOKBEHIND = '(?<=^|([,[]\\s*))'; // Character before match is start of line, comma or opening bracket. const END_LOOKAHEAD = '(?=$|([,\\]]\\s*))'; // Character after match is end of line, comma or closing bracket. // Replace non quoted hex string by quoted hex string. const MATCH_HEX = new RegExp(START_LOOKBEHIND + '(0[xX][0-9a-fA-F]+)' + END_LOOKAHEAD, 'g'); args = args.replace(MATCH_HEX, '"$2"'); // Replace scientific notation numbers by regular numbers. const MATCH_SCIENTIFIC = new RegExp( START_LOOKBEHIND + '(\\s*[-]?\\d+(\\.\\d+)?e(\\+)?\\d+\\s*)' + END_LOOKAHEAD, 'g', ); args = args.replace(MATCH_SCIENTIFIC, val => `${new BN(val).toString(10)}`); // Replace non quoted number by quoted number. const MATCH_WORDS = new RegExp(START_LOOKBEHIND + '([-]?\\w+)' + END_LOOKAHEAD, 'g'); args = args.replace(MATCH_WORDS, '"$2"'); return args; } type NestedArray<T> = T[] | NestedArray<T>[]; export function parseMultipleArgs(args: NestedArray<string>, types: MethodArgType[]): unknown[] { if (args.length !== types.length) { throw new Error(`Expected ${types.length} values but got ${args.length}`); } return zipWith(args, types, parseArg); } export function parseArg(input: string | NestedArray<string>, { type, components }: MethodArgType): any { const TRUE_VALUES = ['y', 'yes', 't', 'true', '1']; const FALSE_VALUES = ['n', 'no', 'f', 'false', '0']; const ARRAY_TYPE_REGEX = /(.+)\[\d*\]$/; // matches array type identifiers like uint[] or byte[4] // Tuples: recursively parse if (type === 'tuple') { const inputs = typeof input === 'string' ? parseArray(stripParens(input), '(', ')') : input; return parseMultipleArgs(inputs, components); } // Arrays: recursively parse else if (type.match(ARRAY_TYPE_REGEX)) { const arrayType = type.match(ARRAY_TYPE_REGEX)[1]; const inputs = typeof input === 'string' ? parseArray(stripBrackets(input)) : input; // TypeScript cannot type the .map call because NestedArray<string> is too // complex a union type. See https://github.com/TypeScript/pull/29011. return (inputs as unknown[]).map((input: NestedArray<string>) => parseArg(input, { type: arrayType })); } // Integers: passed via bignumber to handle signs and scientific notation else if ( (type.startsWith('uint') || type.startsWith('int') || type.startsWith('fixed') || type.startsWith('ufixed')) && requireInputString(input) ) { const parsed = new BN(input); if (parsed.isNaN()) throw new Error(`Could not parse '${input}' as ${type}`); return parsed.toString(10); } // Booleans: match against true, t, yes, 1, etc else if (type === 'bool' && requireInputString(input)) { const lowercaseInput = input.toLowerCase(); if (TRUE_VALUES.includes(lowercaseInput)) return true; else if (FALSE_VALUES.includes(lowercaseInput)) return false; else throw new Error(`Could not parse boolean value ${input}`); } // Address: just validate them else if (type === 'address' && requireInputString(input)) { if (!isAddress(input)) { throw new Error(`${input} is not a valid address`); } return input; } // Bytes: same, just check they are a valid hex else if (type.startsWith('bytes') && requireInputString(input)) { if (!isHex(input)) { throw new Error(`${input} is not a valid hexadecimal`); } return input; } // Strings: pass through else if (type === 'string' && requireInputString(input)) { return input; } // Warn if we see a type we don't recognise, but return it as is else { Loggy.noSpin.warn(__filename, 'parseArg', 'util-parse-arg', `Unknown argument ${type} (skipping input validation)`); return input; } } export function stripBrackets(inputMaybeWithBrackets: string): string { return `${inputMaybeWithBrackets.replace(/^\s*\[/, '').replace(/\]\s*$/, '')}`; } export function stripParens(inputMaybeWithParens: string): string { return `${inputMaybeWithParens.replace(/^\s*\(/, '').replace(/\)\s*$/, '')}`; } function requireInputString(arg: string | NestedArray<string>): arg is string { if (typeof arg !== 'string') { throw new Error(`Expected ${flattenDeep(arg).join(',')} to be a scalar value but was an array`); } return true; } /** * Parses a string as an arbitrarily nested array of strings. Handles * unquoted strings in the input, or quotes using both simple and double quotes. * @param input string to parse * @returns parsed ouput. */ export function parseArray(input: string, open = '[', close = ']'): NestedArray<string> { let i = 0; // index for traversing input function innerParseQuotedString(quoteChar: string): string { const start = i; while (i < input.length) { const char = input[i++]; if (char === quoteChar) return input.slice(start, i - 1); else continue; } throw new Error(`Unterminated string literal ${input.slice(start)}`); } function innerParseUnquotedString(): string { const start = i; while (i < input.length) { const char = input[i++]; if (char === ',') { return input.slice(start, i - 1); } else if (char === '"' || char === "'") { throw new Error(`Unexpected quote at position ${i}`); } else if (char === open || char === "'") { throw new Error(`Unexpected opening bracket at position ${i}`); } else if (char === close) { return input.slice(start, --i); } } return input.slice(start, i); } function requireCommaOrClosing(): void { while (i < input.length) { const char = input[i++]; if (char === ' ') { continue; } else if (char === ',') { return; } else if (char === close) { i--; return; } else { throw new Error(`Expected a comma after ${input.slice(0, i - 1)}`); } } } function innerParseArray(requireClosingBracket = true): string[] { const result = []; const start = i; while (i < input.length) { const char = input[i++]; if (char === ' ') { continue; } else if (char === '"' || char === "'") { result.push(innerParseQuotedString(char)); requireCommaOrClosing(); } else if (char === open) { const innerArray = innerParseArray(); result.push(innerArray); requireCommaOrClosing(); } else if (char === close) { if (!requireClosingBracket) throw new Error(`Unexpected closing array at position ${i + 1} in ${input}`); return result; } else { i--; const unquotedString = innerParseUnquotedString(); const trimmedString = unquotedString.replace(/\s+$/, ''); result.push(trimmedString); } } if (requireClosingBracket) throw new Error(`Unclosed array ${input.slice(start)}`); return result; } try { return innerParseArray(false); } catch (err) { err.message = `Malformed array argument ${input}: ${err.message}`; throw err; } } export function parseMethodParams(options: any, defaultMethod?: string): { methodName: any; methodArgs: any[] } { const { method, init } = options; let methodName = method || init; let { args: methodArgs } = options; if (typeof methodName === 'boolean') methodName = defaultMethod; if (!methodName && typeof methodArgs !== 'undefined') methodName = defaultMethod; // TODO: Change to use parseArray instead if (typeof methodArgs === 'string') methodArgs = parseArgs(methodArgs); else if (!methodArgs || typeof methodArgs === 'boolean' || methodName) methodArgs = []; return { methodName, methodArgs }; } export function validateSalt(salt: string, required = false) { if (!salt || salt.length === 0) { if (required) { throw new Error('A non-empty salt is required to calculate the deployment address.'); } else { return; } } try { encodeParams(['uint256'], [salt]); } catch (err) { throw new Error(`Invalid salt ${salt}, must be an uint256 value.`); } } export function getSampleInput(arg: MethodArgType): string | null { const ARRAY_TYPE_REGEX = /(.+)\[\d*\]$/; // matches array type identifiers like uint[] or byte[4] const { type, components } = arg; if (type.match(ARRAY_TYPE_REGEX)) { const arrayType = type.match(ARRAY_TYPE_REGEX)[1]; const itemPlaceholder = getSampleInput({ type: arrayType }); return `[${itemPlaceholder}, ${itemPlaceholder}]`; } else if ( type.startsWith('uint') || type.startsWith('int') || type.startsWith('fixed') || type.startsWith('ufixed') ) { return '42'; } else if (type === 'bool') { return 'true'; } else if (type === 'bytes') { return '0xabcdef'; } else if (type === 'address') { return '0x1df62f291b2e969fb0849d99d9ce41e2f137006e'; } else if (type === 'string') { return 'Hello world'; } else if (type === 'tuple' && components) { return `(${components.map(c => getSampleInput(c)).join(', ')})`; } else if (type === 'tuple') { return `(Hello world, 42)`; } else { return null; } }
the_stack
// This provides parsing and serialization for HTTP structured headers as specified in: // https://tools.ietf.org/html/draft-ietf-httpbis-header-structure-19 // (the ABNF fragments are quoted from the spec, unless otherwise specified, // and the code pretty much just follows the algorithms given there). // // parseList, parseItem, serializeList, and serializeItem are the main entry points. // // Currently dictionary handling is not implemented (but would likely be easy // to add). Serialization of decimals and byte sequences is also not // implemented. export const enum ResultKind { ERROR = 0, PARAM_NAME = 1, PARAMETER = 2, PARAMETERS = 3, ITEM = 4, INTEGER = 5, DECIMAL = 6, STRING = 7, TOKEN = 8, BINARY = 9, BOOLEAN = 10, LIST = 11, INNER_LIST = 12, SERIALIZATION_RESULT = 13, } export interface Error { kind: ResultKind.ERROR; } export interface Integer { kind: ResultKind.INTEGER; value: number; } export interface Decimal { kind: ResultKind.DECIMAL; value: number; } export interface String { kind: ResultKind.STRING; value: string; } export interface Token { kind: ResultKind.TOKEN; value: string; } export interface Binary { kind: ResultKind.BINARY; // This is undecoded base64 value: string; } export interface Boolean { kind: ResultKind.BOOLEAN; value: boolean; } // bare-item = sf-integer / sf-decimal / sf-string / sf-token // / sf-binary / sf-boolean export type BareItem = Integer|Decimal|String|Token|Binary|Boolean; export interface ParamName { kind: ResultKind.PARAM_NAME; value: string; } // parameter = param-name [ "=" param-value ] // param-value = bare-item export interface Parameter { kind: ResultKind.PARAMETER; name: ParamName; value: BareItem; } // parameters = *( ";" *SP parameter ) export interface Parameters { kind: ResultKind.PARAMETERS; items: Parameter[]; } // sf-item = bare-item parameters export interface Item { kind: ResultKind.ITEM; value: BareItem; parameters: Parameters; } // inner-list = "(" *SP [ sf-item *( 1*SP sf-item ) *SP ] ")" // parameters export interface InnerList { kind: ResultKind.INNER_LIST; items: Item[]; parameters: Parameters; } // list-member = sf-item / inner-list export type ListMember = Item|InnerList; // sf-list = list-member *( OWS "," OWS list-member ) export interface List { kind: ResultKind.LIST; items: ListMember[]; } export interface SerializationResult { kind: ResultKind.SERIALIZATION_RESULT; value: string; } const CHAR_MINUS: number = '-'.charCodeAt(0); const CHAR_0: number = '0'.charCodeAt(0); const CHAR_9: number = '9'.charCodeAt(0); const CHAR_A: number = 'A'.charCodeAt(0); const CHAR_Z: number = 'Z'.charCodeAt(0); const CHAR_LOWER_A: number = 'a'.charCodeAt(0); const CHAR_LOWER_Z: number = 'z'.charCodeAt(0); const CHAR_DQUOTE: number = '"'.charCodeAt(0); const CHAR_COLON: number = ':'.charCodeAt(0); const CHAR_QUESTION_MARK: number = '?'.charCodeAt(0); const CHAR_STAR: number = '*'.charCodeAt(0); const CHAR_UNDERSCORE: number = '_'.charCodeAt(0); const CHAR_DOT: number = '.'.charCodeAt(0); const CHAR_BACKSLASH: number = '\\'.charCodeAt(0); const CHAR_SLASH: number = '/'.charCodeAt(0); const CHAR_PLUS: number = '+'.charCodeAt(0); const CHAR_EQUALS: number = '='.charCodeAt(0); const CHAR_EXCLAMATION: number = '!'.charCodeAt(0); const CHAR_HASH: number = '#'.charCodeAt(0); const CHAR_DOLLAR: number = '$'.charCodeAt(0); const CHAR_PERCENT: number = '%'.charCodeAt(0); const CHAR_AND: number = '&'.charCodeAt(0); const CHAR_SQUOTE: number = '\''.charCodeAt(0); const CHAR_HAT: number = '^'.charCodeAt(0); const CHAR_BACKTICK: number = '`'.charCodeAt(0); const CHAR_PIPE: number = '|'.charCodeAt(0); const CHAR_TILDE: number = '~'.charCodeAt(0); // ASCII printable range. const CHAR_MIN_ASCII_PRINTABLE: number = 0x20; const CHAR_MAX_ASCII_PRINTABLE: number = 0x7e; // Note: structured headers operates over ASCII, not unicode, so these are // all indeed supposed to return false on things outside 32-127 range regardless // of them being other kinds of digits or letters. function isDigit(charCode: number|undefined): boolean { // DIGIT = %x30-39 ; 0-9 (from RFC 5234) if (charCode === undefined) { return false; } return charCode >= CHAR_0 && charCode <= CHAR_9; } function isAlpha(charCode: number|undefined): boolean { // ALPHA = %x41-5A / %x61-7A ; A-Z / a-z (from RFC 5234) if (charCode === undefined) { return false; } return (charCode >= CHAR_A && charCode <= CHAR_Z) || (charCode >= CHAR_LOWER_A && charCode <= CHAR_LOWER_Z); } function isLcAlpha(charCode: number|undefined): boolean { // lcalpha = %x61-7A ; a-z if (charCode === undefined) { return false; } return (charCode >= CHAR_LOWER_A && charCode <= CHAR_LOWER_Z); } function isTChar(charCode: number|undefined): boolean { if (charCode === undefined) { return false; } // tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / // "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA (from RFC 7230) if (isDigit(charCode) || isAlpha(charCode)) { return true; } switch (charCode) { case CHAR_EXCLAMATION: case CHAR_HASH: case CHAR_DOLLAR: case CHAR_PERCENT: case CHAR_AND: case CHAR_SQUOTE: case CHAR_STAR: case CHAR_PLUS: case CHAR_MINUS: case CHAR_DOT: case CHAR_HAT: case CHAR_UNDERSCORE: case CHAR_BACKTICK: case CHAR_PIPE: case CHAR_TILDE: return true; default: return false; } } class Input { private readonly data: string; private pos: number; constructor(input: string) { this.data = input; this.pos = 0; // 4.2 step 2 is to discard any leading SP characters. this.skipSP(); } peek(): string|undefined { return this.data[this.pos]; } peekCharCode(): number|undefined { return (this.pos < this.data.length ? this.data.charCodeAt(this.pos) : undefined); } eat(): void { ++this.pos; } // Matches SP*. // SP = %x20, from RFC 5234 skipSP(): void { while (this.data[this.pos] === ' ') { ++this.pos; } } // Matches OWS // OWS = *( SP / HTAB ) , from RFC 7230 skipOWS(): void { while (this.data[this.pos] === ' ' || this.data[this.pos] === '\t') { ++this.pos; } } atEnd(): boolean { return (this.pos === this.data.length); } // 4.2 steps 6,7 --- checks for trailing characters. allParsed(): boolean { this.skipSP(); return (this.pos === this.data.length); } } function makeError(): Error { return {kind: ResultKind.ERROR}; } // 4.2.1. Parsing a list function parseListInternal(input: Input): List|Error { const result: List = {kind: ResultKind.LIST, items: []}; while (!input.atEnd()) { const piece: ListMember|Error = parseItemOrInnerList(input); if (piece.kind === ResultKind.ERROR) { return piece; } result.items.push(piece); input.skipOWS(); if (input.atEnd()) { return result; } if (input.peek() !== ',') { return makeError(); } input.eat(); input.skipOWS(); // "If input_string is empty, there is a trailing comma; fail parsing." if (input.atEnd()) { return makeError(); } } return result; // this case corresponds to an empty list. } // 4.2.1.1. Parsing an Item or Inner List function parseItemOrInnerList(input: Input): ListMember|Error { if (input.peek() === '(') { return parseInnerList(input); } return parseItemInternal(input); } // 4.2.1.2. Parsing an Inner List function parseInnerList(input: Input): InnerList|Error { if (input.peek() !== '(') { return makeError(); } input.eat(); const items: Item[] = []; while (!input.atEnd()) { input.skipSP(); if (input.peek() === ')') { input.eat(); const params: Parameters|Error = parseParameters(input); if (params.kind === ResultKind.ERROR) { return params; } return { kind: ResultKind.INNER_LIST, items: items, parameters: params, }; } const item: Item|Error = parseItemInternal(input); if (item.kind === ResultKind.ERROR) { return item; } items.push(item); if (input.peek() !== ' ' && input.peek() !== ')') { return makeError(); } } // Didn't see ), so error. return makeError(); } // 4.2.3. Parsing an Item function parseItemInternal(input: Input): Item|Error { const bareItem: BareItem|Error = parseBareItem(input); if (bareItem.kind === ResultKind.ERROR) { return bareItem; } const params: Parameters|Error = parseParameters(input); if (params.kind === ResultKind.ERROR) { return params; } return {kind: ResultKind.ITEM, value: bareItem, parameters: params}; } // 4.2.3.1. Parsing a Bare Item function parseBareItem(input: Input): BareItem|Error { const upcoming = input.peekCharCode(); if (upcoming === CHAR_MINUS || isDigit(upcoming)) { return parseIntegerOrDecimal(input); } if (upcoming === CHAR_DQUOTE) { return parseString(input); } if (upcoming === CHAR_COLON) { return parseByteSequence(input); } if (upcoming === CHAR_QUESTION_MARK) { return parseBoolean(input); } if (upcoming === CHAR_STAR || isAlpha(upcoming)) { return parseToken(input); } return makeError(); } // 4.2.3.2. Parsing Parameters function parseParameters(input: Input): Parameters|Error { // The main noteworthy thing here is handling of duplicates and ordering: // // "Note that Parameters are ordered as serialized" // // "If parameters already contains a name param_name (comparing // character-for-character), overwrite its value." // // "Note that when duplicate Parameter keys are encountered, this has the // effect of ignoring all but the last instance." const items: Map<string, Parameter> = new Map<string, Parameter>(); while (!input.atEnd()) { if (input.peek() !== ';') { break; } input.eat(); input.skipSP(); const paramName = parseKey(input); if (paramName.kind === ResultKind.ERROR) { return paramName; } let paramValue: BareItem = {kind: ResultKind.BOOLEAN, value: true}; if (input.peek() === '=') { input.eat(); const parsedParamValue: BareItem|Error = parseBareItem(input); if (parsedParamValue.kind === ResultKind.ERROR) { return parsedParamValue; } paramValue = parsedParamValue; } // Delete any previous occurrence of duplicates to get the ordering right. if (items.has(paramName.value)) { items.delete(paramName.value); } items.set(paramName.value, {kind: ResultKind.PARAMETER, name: paramName, value: paramValue}); } return {kind: ResultKind.PARAMETERS, items: [...items.values()]}; } // 4.2.3.3. Parsing a Key function parseKey(input: Input): ParamName|Error { let outputString: string = ''; const first = input.peekCharCode(); if (first !== CHAR_STAR && !isLcAlpha(first)) { return makeError(); } while (!input.atEnd()) { const upcoming = input.peekCharCode(); if (!isLcAlpha(upcoming) && !isDigit(upcoming) && upcoming !== CHAR_UNDERSCORE && upcoming !== CHAR_MINUS && upcoming !== CHAR_DOT && upcoming !== CHAR_STAR) { break; } outputString += input.peek(); input.eat(); } return {kind: ResultKind.PARAM_NAME, value: outputString}; } // 4.2.4. Parsing an Integer or Decimal function parseIntegerOrDecimal(input: Input): Integer|Decimal|Error { let resultKind = ResultKind.INTEGER; let sign: number = 1; let inputNumber = ''; if (input.peek() === '-') { input.eat(); sign = -1; } // This case includes end of input. if (!isDigit(input.peekCharCode())) { return makeError(); } while (!input.atEnd()) { const char = input.peekCharCode(); if (char !== undefined && isDigit(char)) { input.eat(); inputNumber += String.fromCodePoint(char); } else if (char === CHAR_DOT && resultKind === ResultKind.INTEGER) { input.eat(); if (inputNumber.length > 12) { return makeError(); } inputNumber += '.'; resultKind = ResultKind.DECIMAL; } else { break; } if (resultKind === ResultKind.INTEGER && inputNumber.length > 15) { return makeError(); } if (resultKind === ResultKind.DECIMAL && inputNumber.length > 16) { return makeError(); } } if (resultKind === ResultKind.INTEGER) { const num = sign * Number.parseInt(inputNumber, 10); if (num < -999999999999999 || num > 999999999999999) { return makeError(); } return {kind: ResultKind.INTEGER, value: num}; } const afterDot = inputNumber.length - 1 - inputNumber.indexOf('.'); if (afterDot > 3 || afterDot === 0) { return makeError(); } return {kind: ResultKind.DECIMAL, value: sign * Number.parseFloat(inputNumber)}; } // 4.2.5. Parsing a String function parseString(input: Input): String|Error { let outputString = ''; if (input.peek() !== '"') { return makeError(); } input.eat(); while (!input.atEnd()) { const char = input.peekCharCode(); // can't happen due to atEnd(), but help the typechecker out. if (char === undefined) { return makeError(); } input.eat(); if (char === CHAR_BACKSLASH) { if (input.atEnd()) { return makeError(); } const nextChar = input.peekCharCode(); input.eat(); if (nextChar !== CHAR_BACKSLASH && nextChar !== CHAR_DQUOTE) { return makeError(); } outputString += String.fromCodePoint(nextChar); } else if (char === CHAR_DQUOTE) { return {kind: ResultKind.STRING, value: outputString}; } else if (char<CHAR_MIN_ASCII_PRINTABLE || char>CHAR_MAX_ASCII_PRINTABLE) { return makeError(); } else { outputString += String.fromCodePoint(char); } } // No closing quote. return makeError(); } // 4.2.6. Parsing a Token function parseToken(input: Input): Token|Error { const first = input.peekCharCode(); if (first !== CHAR_STAR && !isAlpha(first)) { return makeError(); } let outputString = ''; while (!input.atEnd()) { const upcoming = input.peekCharCode(); if (upcoming === undefined || !isTChar(upcoming) && upcoming !== CHAR_COLON && upcoming !== CHAR_SLASH) { break; } input.eat(); outputString += String.fromCodePoint(upcoming); } return {kind: ResultKind.TOKEN, value: outputString}; } // 4.2.7. Parsing a Byte Sequence function parseByteSequence(input: Input): Binary|Error { let outputString = ''; if (input.peek() !== ':') { return makeError(); } input.eat(); while (!input.atEnd()) { const char = input.peekCharCode(); // can't happen due to atEnd(), but help the typechecker out. if (char === undefined) { return makeError(); } input.eat(); if (char === CHAR_COLON) { return {kind: ResultKind.BINARY, value: outputString}; } if (isDigit(char) || isAlpha(char) || char === CHAR_PLUS || char === CHAR_SLASH || char === CHAR_EQUALS) { outputString += String.fromCodePoint(char); } else { return makeError(); } } // No closing : return makeError(); } // 4.2.8. Parsing a Boolean function parseBoolean(input: Input): Boolean|Error { if (input.peek() !== '?') { return makeError(); } input.eat(); if (input.peek() === '0') { input.eat(); return {kind: ResultKind.BOOLEAN, value: false}; } if (input.peek() === '1') { input.eat(); return {kind: ResultKind.BOOLEAN, value: true}; } return makeError(); } export function parseItem(input: string): Item|Error { const i = new Input(input); const result: Item|Error = parseItemInternal(i); if (!i.allParsed()) { return makeError(); } return result; } export function parseList(input: string): List|Error { // No need to look for trailing stuff here since parseListInternal does it already. return parseListInternal(new Input(input)); } // 4.1.3. Serializing an Item export function serializeItem(input: Item): SerializationResult|Error { const bareItemVal = serializeBareItem(input.value); if (bareItemVal.kind === ResultKind.ERROR) { return bareItemVal; } const paramVal = serializeParameters(input.parameters); if (paramVal.kind === ResultKind.ERROR) { return paramVal; } return {kind: ResultKind.SERIALIZATION_RESULT, value: bareItemVal.value + paramVal.value}; } // 4.1.1. Serializing a List export function serializeList(input: List): SerializationResult|Error { const outputPieces: string[] = []; for (let i = 0; i < input.items.length; ++i) { const item = input.items[i]; if (item.kind === ResultKind.INNER_LIST) { const itemResult = serializeInnerList(item); if (itemResult.kind === ResultKind.ERROR) { return itemResult; } outputPieces.push(itemResult.value); } else { const itemResult = serializeItem(item); if (itemResult.kind === ResultKind.ERROR) { return itemResult; } outputPieces.push(itemResult.value); } } const output = outputPieces.join(', '); return {kind: ResultKind.SERIALIZATION_RESULT, value: output}; } // 4.1.1.1. Serializing an Inner List function serializeInnerList(input: InnerList): SerializationResult|Error { const outputPieces: string[] = []; for (let i = 0; i < input.items.length; ++i) { const itemResult = serializeItem(input.items[i]); if (itemResult.kind === ResultKind.ERROR) { return itemResult; } outputPieces.push(itemResult.value); } let output = '(' + outputPieces.join(' ') + ')'; const paramResult = serializeParameters(input.parameters); if (paramResult.kind === ResultKind.ERROR) { return paramResult; } output += paramResult.value; return {kind: ResultKind.SERIALIZATION_RESULT, value: output}; } // 4.1.1.2. Serializing Parameters function serializeParameters(input: Parameters): SerializationResult|Error { let output = ''; for (const item of input.items) { output += ';'; const nameResult = serializeKey(item.name); if (nameResult.kind === ResultKind.ERROR) { return nameResult; } output += nameResult.value; const itemVal: BareItem = item.value; if (itemVal.kind !== ResultKind.BOOLEAN || !itemVal.value) { output += '='; const itemValResult = serializeBareItem(itemVal); if (itemValResult.kind === ResultKind.ERROR) { return itemValResult; } output += itemValResult.value; } } return {kind: ResultKind.SERIALIZATION_RESULT, value: output}; } // 4.1.1.3. Serializing a Key function serializeKey(input: ParamName): SerializationResult|Error { if (input.value.length === 0) { return makeError(); } const firstChar = input.value.charCodeAt(0); if (!isLcAlpha(firstChar) && firstChar !== CHAR_STAR) { return makeError(); } for (let i = 1; i < input.value.length; ++i) { const char = input.value.charCodeAt(i); if (!isLcAlpha(char) && !isDigit(char) && char !== CHAR_UNDERSCORE && char !== CHAR_MINUS && char !== CHAR_DOT && char !== CHAR_STAR) { return makeError(); } } return {kind: ResultKind.SERIALIZATION_RESULT, value: input.value}; } // 4.1.3.1. Serializing a Bare Item function serializeBareItem(input: BareItem): SerializationResult|Error { if (input.kind === ResultKind.INTEGER) { return serializeInteger(input); } if (input.kind === ResultKind.DECIMAL) { return serializeDecimal(input); } if (input.kind === ResultKind.STRING) { return serializeString(input); } if (input.kind === ResultKind.TOKEN) { return serializeToken(input); } if (input.kind === ResultKind.BOOLEAN) { return serializeBoolean(input); } if (input.kind === ResultKind.BINARY) { return serializeByteSequence(input); } return makeError(); } // 4.1.4. Serializing an Integer function serializeInteger(input: Integer): SerializationResult|Error { if (input.value < -999999999999999 || input.value > 999999999999999 || !Number.isInteger(input.value)) { return makeError(); } return {kind: ResultKind.SERIALIZATION_RESULT, value: input.value.toString(10)}; } // 4.1.5. Serializing a Decimal function serializeDecimal(_input: Decimal): SerializationResult|Error { throw 'Unimplemented'; } // 4.1.6. Serializing a String function serializeString(input: String): SerializationResult|Error { // Only printable ASCII strings are supported by the spec. for (let i = 0; i < input.value.length; ++i) { const char = input.value.charCodeAt(i); if (char<CHAR_MIN_ASCII_PRINTABLE || char>CHAR_MAX_ASCII_PRINTABLE) { return makeError(); } } let output = '"'; for (let i = 0; i < input.value.length; ++i) { const charStr = input.value[i]; if (charStr === '"' || charStr === '\\') { output += '\\'; } output += charStr; } output += '"'; return {kind: ResultKind.SERIALIZATION_RESULT, value: output}; } // 4.1.7. Serializing a Token function serializeToken(input: Token): SerializationResult|Error { if (input.value.length === 0) { return makeError(); } const firstChar = input.value.charCodeAt(0); if (!isAlpha(firstChar) && firstChar !== CHAR_STAR) { return makeError(); } for (let i = 1; i < input.value.length; ++i) { const char = input.value.charCodeAt(i); if (!isTChar(char) && char !== CHAR_COLON && char !== CHAR_SLASH) { return makeError(); } } return {kind: ResultKind.SERIALIZATION_RESULT, value: input.value}; } // 4.1.8. Serializing a Byte Sequence function serializeByteSequence(_input: Binary): SerializationResult|Error { throw 'Unimplemented'; } // 4.1.9. Serializing a Boolean function serializeBoolean(input: Boolean): SerializationResult|Error { return {kind: ResultKind.SERIALIZATION_RESULT, value: input.value ? '?1' : '?0'}; }
the_stack
// tslint:disable:max-line-length import * as aws from "@pulumi/aws"; import * as pulumi from "@pulumi/pulumi"; import * as mod from "."; import * as x from ".."; import * as utils from "../utils"; export interface ListenerEndpoint { hostname: string; port: number; } export abstract class Listener extends pulumi.ComponentResource implements x.ecs.ContainerPortMappingProvider, x.ecs.ContainerLoadBalancerProvider { public readonly listener: aws.lb.Listener; public readonly loadBalancer: x.lb.LoadBalancer; public readonly defaultTargetGroup?: x.lb.TargetGroup; public readonly endpoint: pulumi.Output<ListenerEndpoint>; private readonly defaultListenerAction?: ListenerDefaultAction; // tslint:disable-next-line:variable-name private readonly __isListenerInstance = true; constructor(type: string, name: string, defaultListenerAction: ListenerDefaultAction | undefined, args: ListenerArgs, opts: pulumi.ComponentResourceOptions) { // By default, we'd like to be parented by the LB . However, we didn't use to do this. // Create an alias from teh old urn to the new one so that we don't cause these to eb // created/destroyed. super(type, name, {}, { parent: args.loadBalancer, ...pulumi.mergeOptions(opts, { aliases: [{ parent: opts.parent }] }), }); // If SSL is used, and no ssl policy was we automatically insert the recommended ELB // security policy from: // http://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-https-listener.html. const defaultSslPolicy = pulumi.output(args.certificateArn) .apply(a => a ? "ELBSecurityPolicy-2016-08" : undefined!); this.listener = args.listener || new aws.lb.Listener(name, { ...args, loadBalancerArn: args.loadBalancer.loadBalancer.arn, sslPolicy: utils.ifUndefined(args.sslPolicy, defaultSslPolicy), }, { parent: this }); const loadBalancer = args.loadBalancer.loadBalancer; this.endpoint = this.listener.urn.apply(_ => pulumi.output({ hostname: loadBalancer.dnsName, port: args.port, })); this.loadBalancer = args.loadBalancer; this.defaultListenerAction = defaultListenerAction; if (defaultListenerAction instanceof mod.TargetGroup) { this.defaultTargetGroup = defaultListenerAction; } if (defaultListenerAction) { // If our default rule hooked up this listener to a target group, then add our listener // to the set of listeners the target group knows about. This is necessary so that // anything that depends on the target group will end up depending on this rule getting // created. defaultListenerAction.registerListener(this); } } /** @internal */ public static isListenerInstance(obj: any): obj is Listener { return obj && !!(<Listener>obj).__isListenerInstance; } public containerPortMapping(name: string, parent: pulumi.Resource) { if (!x.ecs.isContainerPortMappingProvider(this.defaultListenerAction)) { throw new Error("[Listener] was not connected to a [defaultAction] that can provide [portMapping]s"); } return this.defaultListenerAction.containerPortMapping(name, parent); } public containerLoadBalancer(name: string, parent: pulumi.Resource) { if (!x.ecs.isContainerLoadBalancerProvider(this.defaultListenerAction)) { throw new Error("[Listener] was not connected to a [defaultAction] that can provide [containerLoadBalancer]s"); } return this.defaultListenerAction.containerLoadBalancer(name, parent); } public addListenerRule(name: string, args: x.lb.ListenerRuleArgs, opts?: pulumi.ComponentResourceOptions) { return new x.lb.ListenerRule(name, this, args, opts); } /** * Attaches a target to the `defaultTargetGroup` for this Listener. */ public attachTarget(name: string, args: mod.LoadBalancerTarget, opts: pulumi.CustomResourceOptions = {}) { if (!this.defaultTargetGroup) { throw new pulumi.ResourceError("Listener must have a [defaultTargetGroup] in order to attach a target.", this); } return this.defaultTargetGroup.attachTarget(name, args, opts); } } utils.Capture(Listener.prototype).containerPortMapping.doNotCapture = true; utils.Capture(Listener.prototype).containerLoadBalancer.doNotCapture = true; utils.Capture(Listener.prototype).addListenerRule.doNotCapture = true; utils.Capture(Listener.prototype).attachTarget.doNotCapture = true; /** * See https://www.terraform.io/docs/providers/aws/r/lb_listener.html#default_action */ export interface ListenerDefaultActionArgs { authenticateCognito?: pulumi.Input<{ /** * The query parameters to include in the redirect request to the authorization endpoint. * Max: 10. */ authenticationRequestExtraParams?: pulumi.Input<{ [key: string]: any; }>; /** * The behavior if the user is not authenticated. Valid values: deny, allow and * authenticate. */ onUnauthenticatedRequest?: pulumi.Input<string>; /** * The set of user claims to be requested from the IdP. */ scope?: pulumi.Input<string>; /** * The name of the cookie used to maintain session information. */ sessionCookieName?: pulumi.Input<string>; /** * The maximum duration of the authentication session, in seconds. */ sessionTimeout?: pulumi.Input<number>; /** * The ARN of the Cognito user pool. */ userPoolArn: pulumi.Input<string>; /** * The ID of the Cognito user pool client. */ userPoolClientId: pulumi.Input<string>; /** * The domain prefix or fully-qualified domain name of the Cognito user pool. */ userPoolDomain: pulumi.Input<string>; }>; authenticateOidc?: pulumi.Input<{ /** * The query parameters to include in the redirect request to the authorization endpoint. * Max: 10. */ authenticationRequestExtraParams?: pulumi.Input<{ [key: string]: any; }>; /** * The authorization endpoint of the IdP. */ authorizationEndpoint: pulumi.Input<string>; /** * The OAuth 2.0 client identifier. */ clientId: pulumi.Input<string>; /** * The OAuth 2.0 client secret. */ clientSecret: pulumi.Input<string>; /** * The OIDC issuer identifier of the IdP. */ issuer: pulumi.Input<string>; /** * The behavior if the user is not authenticated. Valid values: deny, allow and authenticate */ onUnauthenticatedRequest?: pulumi.Input<string>; /** * The set of user claims to be requested from the IdP. */ scope?: pulumi.Input<string>; /** * The name of the cookie used to maintain session information. */ sessionCookieName?: pulumi.Input<string>; /** * The maximum duration of the authentication session, in seconds. */ sessionTimeout?: pulumi.Input<number>; /** * The token endpoint of the IdP. */ tokenEndpoint: pulumi.Input<string>; /** * The user info endpoint of the IdP. */ userInfoEndpoint: pulumi.Input<string>; }>; /** * Information for creating an action that returns a custom HTTP response. Required if type is * "fixed-response". */ fixedResponse?: pulumi.Input<{ /** * The content type. Valid values are text/plain, text/css, text/html, * application/javascript and application/json. */ contentType: pulumi.Input<string>; messageBody?: pulumi.Input<string>; /** * The HTTP response code. Valid values are 2XX, 4XX, or 5XX. */ statusCode?: pulumi.Input<string>; }>; order?: pulumi.Input<number>; /** * Information for creating a redirect action. Required if type is "redirect". */ redirect?: pulumi.Input<{ /** * The hostname. This component is not percent-encoded. The hostname can contain #{host}. * Defaults to #{host}. */ host?: pulumi.Input<string>; /** * The absolute path, starting with the leading "/". This component is not percent-encoded. * The path can contain #{host}, #{path}, and #{port}. Defaults to /#{path}. */ path?: pulumi.Input<string>; /** * The port. Specify a value from 1 to 65535 or #{port}. Defaults to #{port}. */ port?: pulumi.Input<string>; /** * The protocol. Valid values are HTTP, HTTPS, or #{protocol}. Defaults to #{protocol}. */ protocol?: pulumi.Input<string>; /** * The query parameters, URL-encoded when necessary, but not percent-encoded. Do not include * the leading "?". */ query?: pulumi.Input<string>; /** * The HTTP redirect code. The redirect is either permanent (HTTP_301) or temporary * (HTTP_302). */ statusCode: pulumi.Input<string>; }>; /** * The ARN of the Target Group to which to route traffic. Required if type is "forward". */ targetGroupArn?: pulumi.Input<string>; /** * The type of routing action. Valid values are "forward", "redirect", "fixed-response", * "authenticate-cognito" and "authenticate-oidc". */ type: pulumi.Input<string>; } export interface ListenerDefaultAction { listenerDefaultAction(): pulumi.Input<ListenerDefaultActionArgs>; registerListener(listener: Listener): void; } export interface ListenerActions { actions(): aws.lb.ListenerRuleArgs["actions"]; registerListener(listener: Listener): void; } /** @internal */ export function isListenerDefaultAction(obj: any): obj is ListenerDefaultAction { return obj && (<ListenerDefaultAction>obj).listenerDefaultAction instanceof Function && (<ListenerDefaultAction>obj).registerListener instanceof Function; } /** @internal */ export function isListenerActions(obj: any): obj is ListenerActions { return obj && (<ListenerActions>obj).actions instanceof Function && (<ListenerActions>obj).registerListener instanceof Function; } type OverwriteShape = utils.Overwrite<aws.lb.ListenerArgs, { loadBalancer: x.lb.LoadBalancer; certificateArn?: pulumi.Input<string>; defaultActions: pulumi.Input<pulumi.Input<ListenerDefaultActionArgs>[]>; loadBalancerArn?: never; port: pulumi.Input<number>; protocol: pulumi.Input<"HTTP" | "HTTPS" | "TCP" | "TLS" | "GENEVE" | "UDP" | "TCP_UDP">; sslPolicy?: pulumi.Input<string>; }>; export interface ListenerArgs { /** * An existing aws.lb.Listener to use for this awsx.lb.Listener. * If not provided, one will be created. */ listener?: aws.lb.Listener; loadBalancer: x.lb.LoadBalancer; /** * The ARN of the default SSL server certificate. Exactly one certificate is required if the * protocol is HTTPS. For adding additional SSL certificates, see the * [`aws_lb_listener_certificate` * resource](https://www.terraform.io/docs/providers/aws/r/lb_listener_certificate.html). */ certificateArn?: pulumi.Input<string>; /** * An list of Action blocks. See [ListenerDefaultActionArgs] for more information. */ defaultActions: pulumi.Input<pulumi.Input<ListenerDefaultActionArgs>[]>; /** * The port. Specify a value from `1` to `65535`. */ port: pulumi.Input<number>; /** * The protocol. */ protocol: pulumi.Input<"HTTP" | "HTTPS" | "TCP" | "TLS" | "GENEVE" | "UDP" | "TCP_UDP">; /** * The name of the SSL Policy for the listener. Required if `protocol` is `HTTPS`. */ sslPolicy?: pulumi.Input<string>; } const test1: string = utils.checkCompat<OverwriteShape, ListenerArgs>();
the_stack
import * as coreClient from "@azure/core-client"; /** The list of domain service operation response. */ export interface OperationEntityListResult { /** The list of operations. */ value?: OperationEntity[]; /** * The continuation token for the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** The operation supported by Domain Services. */ export interface OperationEntity { /** Operation name: {provider}/{resource}/{operation}. */ name?: string; /** The operation supported by Domain Services. */ display?: OperationDisplayInfo; /** The origin of the operation. */ origin?: string; } /** The operation supported by Domain Services. */ export interface OperationDisplayInfo { /** The description of the operation. */ description?: string; /** The action that users can perform, based on their permission level. */ operation?: string; /** Service provider: Domain Services. */ provider?: string; /** Resource on which the operation is performed. */ resource?: string; } /** An error response from the Domain Services. */ export interface CloudError { /** An error response from the Domain Services. */ error?: CloudErrorBody; } /** An error response from the Domain Services. */ export interface CloudErrorBody { /** An identifier for the error. Codes are invariant and are intended to be consumed programmatically. */ code?: string; /** A message describing the error, intended to be suitable for display in a user interface. */ message?: string; /** The target of the particular error. For example, the name of the property in error. */ target?: string; /** A list of additional details about the error. */ details?: CloudErrorBody[]; } /** The response from the List Domain Services operation. */ export interface DomainServiceListResult { /** the list of domain services. */ value?: DomainService[]; /** * The continuation token for the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Replica Set Definition */ export interface ReplicaSet { /** * ReplicaSet Id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly replicaSetId?: string; /** Virtual network location */ location?: string; /** * Virtual network site id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly vnetSiteId?: string; /** The name of the virtual network that Domain Services will be deployed on. The id of the subnet that Domain Services will be deployed on. /virtualNetwork/vnetName/subnets/subnetName. */ subnetId?: string; /** * List of Domain Controller IP Address * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly domainControllerIpAddress?: string[]; /** * External access ip address. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly externalAccessIpAddress?: string; /** * Status of Domain Service instance * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly serviceStatus?: string; /** * Last domain evaluation run DateTime * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly healthLastEvaluated?: Date; /** * List of Domain Health Monitors * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly healthMonitors?: HealthMonitor[]; /** * List of Domain Health Alerts * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly healthAlerts?: HealthAlert[]; } /** Health Monitor Description */ export interface HealthMonitor { /** * Health Monitor Id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * Health Monitor Name * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * Health Monitor Details * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly details?: string; } /** Health Alert Description */ export interface HealthAlert { /** * Health Alert Id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * Health Alert Name * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * Health Alert Issue * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly issue?: string; /** * Health Alert Severity * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly severity?: string; /** * Health Alert Raised DateTime * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly raised?: Date; /** * Health Alert Last Detected DateTime * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastDetected?: Date; /** * Health Alert TSG Link * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resolutionUri?: string; } /** Secure LDAP Settings */ export interface LdapsSettings { /** A flag to determine whether or not Secure LDAP is enabled or disabled. */ ldaps?: Ldaps; /** The certificate required to configure Secure LDAP. The parameter passed here should be a base64encoded representation of the certificate pfx file. */ pfxCertificate?: string; /** The password to decrypt the provided Secure LDAP certificate pfx file. */ pfxCertificatePassword?: string; /** * Public certificate used to configure secure ldap. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly publicCertificate?: string; /** * Thumbprint of configure ldaps certificate. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly certificateThumbprint?: string; /** * NotAfter DateTime of configure ldaps certificate. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly certificateNotAfter?: Date; /** A flag to determine whether or not Secure LDAP access over the internet is enabled or disabled. */ externalAccess?: ExternalAccess; } /** Settings for Resource Forest */ export interface ResourceForestSettings { /** List of settings for Resource Forest */ settings?: ForestTrust[]; /** Resource Forest */ resourceForest?: string; } /** Forest Trust Setting */ export interface ForestTrust { /** Trusted Domain FQDN */ trustedDomainFqdn?: string; /** Trust Direction */ trustDirection?: string; /** Friendly Name */ friendlyName?: string; /** Remote Dns ips */ remoteDnsIps?: string; /** Trust Password */ trustPassword?: string; } /** Domain Security Settings */ export interface DomainSecuritySettings { /** A flag to determine whether or not NtlmV1 is enabled or disabled. */ ntlmV1?: NtlmV1; /** A flag to determine whether or not TlsV1 is enabled or disabled. */ tlsV1?: TlsV1; /** A flag to determine whether or not SyncNtlmPasswords is enabled or disabled. */ syncNtlmPasswords?: SyncNtlmPasswords; /** A flag to determine whether or not SyncKerberosPasswords is enabled or disabled. */ syncKerberosPasswords?: SyncKerberosPasswords; /** A flag to determine whether or not SyncOnPremPasswords is enabled or disabled. */ syncOnPremPasswords?: SyncOnPremPasswords; /** A flag to determine whether or not KerberosRc4Encryption is enabled or disabled. */ kerberosRc4Encryption?: KerberosRc4Encryption; /** A flag to determine whether or not KerberosArmoring is enabled or disabled. */ kerberosArmoring?: KerberosArmoring; } /** Settings for notification */ export interface NotificationSettings { /** Should global admins be notified */ notifyGlobalAdmins?: NotifyGlobalAdmins; /** Should domain controller admins be notified */ notifyDcAdmins?: NotifyDcAdmins; /** The list of additional recipients */ additionalRecipients?: string[]; } /** Migration Properties */ export interface MigrationProperties { /** * Old Subnet Id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly oldSubnetId?: string; /** * Old Vnet Site Id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly oldVnetSiteId?: string; /** * Migration Progress * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly migrationProgress?: MigrationProgress; } /** Migration Progress */ export interface MigrationProgress { /** Completion Percentage */ completionPercentage?: number; /** Progress Message */ progressMessage?: string; } /** Configuration Diagnostics */ export interface ConfigDiagnostics { /** Last domain configuration diagnostics DateTime */ lastExecuted?: Date; /** List of Configuration Diagnostics validator results. */ validatorResults?: ConfigDiagnosticsValidatorResult[]; } /** Config Diagnostics validator result data */ export interface ConfigDiagnosticsValidatorResult { /** Validator identifier */ validatorId?: string; /** Replica set location and subnet name */ replicaSetSubnetDisplayName?: string; /** Status for individual validator after running diagnostics. */ status?: Status; /** List of resource config validation issues. */ issues?: ConfigDiagnosticsValidatorResultIssue[]; } /** Specific issue for a particular config diagnostics validator */ export interface ConfigDiagnosticsValidatorResultIssue { /** Validation issue identifier. */ id?: string; /** List of domain resource property name or values used to compose a rich description. */ descriptionParams?: string[]; } /** The Resource model definition. */ export interface Resource { /** * Resource Id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * Resource name * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * Resource type * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** Resource location */ location?: string; /** Resource tags */ tags?: { [propertyName: string]: string }; /** Resource etag */ etag?: string; /** * The system meta data relating to this resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; } /** Metadata pertaining to creation and last modification of the resource. */ export interface SystemData { /** The identity that created the resource. */ createdBy?: string; /** The type of identity that created the resource. */ createdByType?: CreatedByType; /** The timestamp of resource creation (UTC). */ createdAt?: Date; /** The identity that last modified the resource. */ lastModifiedBy?: string; /** The type of identity that last modified the resource. */ lastModifiedByType?: CreatedByType; /** The timestamp of resource last modification (UTC) */ lastModifiedAt?: Date; } /** The response from the List OuContainer operation. */ export interface OuContainerListResult { /** The list of OuContainer. */ value?: OuContainer[]; /** * The continuation token for the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Container Account Description */ export interface ContainerAccount { /** The account name */ accountName?: string; /** The account spn */ spn?: string; /** The account password */ password?: string; } /** Domain service. */ export type DomainService = Resource & { /** * Data Model Version * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly version?: number; /** * Azure Active Directory Tenant Id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly tenantId?: string; /** The name of the Azure domain that the user would like to deploy Domain Services to. */ domainName?: string; /** * Deployment Id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly deploymentId?: string; /** * SyncOwner ReplicaSet Id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly syncOwner?: string; /** List of ReplicaSets */ replicaSets?: ReplicaSet[]; /** Secure LDAP Settings */ ldapsSettings?: LdapsSettings; /** Resource Forest Settings */ resourceForestSettings?: ResourceForestSettings; /** DomainSecurity Settings */ domainSecuritySettings?: DomainSecuritySettings; /** Domain Configuration Type */ domainConfigurationType?: string; /** Sku Type */ sku?: string; /** Enabled or Disabled flag to turn on Group-based filtered sync */ filteredSync?: FilteredSync; /** Notification Settings */ notificationSettings?: NotificationSettings; /** * Migration Properties * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly migrationProperties?: MigrationProperties; /** * the current deployment or provisioning state, which only appears in the response. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; /** Configuration diagnostics data containing latest execution from client. */ configDiagnostics?: ConfigDiagnostics; }; /** Resource for OuContainer. */ export type OuContainer = Resource & { /** * Azure Active Directory tenant id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly tenantId?: string; /** * The domain name of Domain Services. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly domainName?: string; /** * The Deployment id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly deploymentId?: string; /** * The OuContainer name * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly containerId?: string; /** The list of container accounts */ accounts?: ContainerAccount[]; /** * Status of OuContainer instance * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly serviceStatus?: string; /** * Distinguished Name of OuContainer instance * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly distinguishedName?: string; /** * The current deployment or provisioning state, which only appears in the response. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; }; /** Known values of {@link Ldaps} that the service accepts. */ export enum KnownLdaps { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for Ldaps. \ * {@link KnownLdaps} can be used interchangeably with Ldaps, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type Ldaps = string; /** Known values of {@link ExternalAccess} that the service accepts. */ export enum KnownExternalAccess { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for ExternalAccess. \ * {@link KnownExternalAccess} can be used interchangeably with ExternalAccess, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type ExternalAccess = string; /** Known values of {@link NtlmV1} that the service accepts. */ export enum KnownNtlmV1 { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for NtlmV1. \ * {@link KnownNtlmV1} can be used interchangeably with NtlmV1, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type NtlmV1 = string; /** Known values of {@link TlsV1} that the service accepts. */ export enum KnownTlsV1 { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for TlsV1. \ * {@link KnownTlsV1} can be used interchangeably with TlsV1, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type TlsV1 = string; /** Known values of {@link SyncNtlmPasswords} that the service accepts. */ export enum KnownSyncNtlmPasswords { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for SyncNtlmPasswords. \ * {@link KnownSyncNtlmPasswords} can be used interchangeably with SyncNtlmPasswords, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type SyncNtlmPasswords = string; /** Known values of {@link SyncKerberosPasswords} that the service accepts. */ export enum KnownSyncKerberosPasswords { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for SyncKerberosPasswords. \ * {@link KnownSyncKerberosPasswords} can be used interchangeably with SyncKerberosPasswords, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type SyncKerberosPasswords = string; /** Known values of {@link SyncOnPremPasswords} that the service accepts. */ export enum KnownSyncOnPremPasswords { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for SyncOnPremPasswords. \ * {@link KnownSyncOnPremPasswords} can be used interchangeably with SyncOnPremPasswords, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type SyncOnPremPasswords = string; /** Known values of {@link KerberosRc4Encryption} that the service accepts. */ export enum KnownKerberosRc4Encryption { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for KerberosRc4Encryption. \ * {@link KnownKerberosRc4Encryption} can be used interchangeably with KerberosRc4Encryption, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type KerberosRc4Encryption = string; /** Known values of {@link KerberosArmoring} that the service accepts. */ export enum KnownKerberosArmoring { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for KerberosArmoring. \ * {@link KnownKerberosArmoring} can be used interchangeably with KerberosArmoring, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type KerberosArmoring = string; /** Known values of {@link FilteredSync} that the service accepts. */ export enum KnownFilteredSync { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for FilteredSync. \ * {@link KnownFilteredSync} can be used interchangeably with FilteredSync, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type FilteredSync = string; /** Known values of {@link NotifyGlobalAdmins} that the service accepts. */ export enum KnownNotifyGlobalAdmins { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for NotifyGlobalAdmins. \ * {@link KnownNotifyGlobalAdmins} can be used interchangeably with NotifyGlobalAdmins, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type NotifyGlobalAdmins = string; /** Known values of {@link NotifyDcAdmins} that the service accepts. */ export enum KnownNotifyDcAdmins { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for NotifyDcAdmins. \ * {@link KnownNotifyDcAdmins} can be used interchangeably with NotifyDcAdmins, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type NotifyDcAdmins = string; /** Known values of {@link Status} that the service accepts. */ export enum KnownStatus { None = "None", Running = "Running", OK = "OK", Failure = "Failure", Warning = "Warning", Skipped = "Skipped" } /** * Defines values for Status. \ * {@link KnownStatus} can be used interchangeably with Status, * this enum contains the known values that the service supports. * ### Known values supported by the service * **None** \ * **Running** \ * **OK** \ * **Failure** \ * **Warning** \ * **Skipped** */ export type Status = string; /** Known values of {@link CreatedByType} that the service accepts. */ export enum KnownCreatedByType { User = "User", Application = "Application", ManagedIdentity = "ManagedIdentity", Key = "Key" } /** * Defines values for CreatedByType. \ * {@link KnownCreatedByType} can be used interchangeably with CreatedByType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **User** \ * **Application** \ * **ManagedIdentity** \ * **Key** */ export type CreatedByType = string; /** Optional parameters. */ export interface DomainServiceOperationsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type DomainServiceOperationsListResponse = OperationEntityListResult; /** Optional parameters. */ export interface DomainServiceOperationsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type DomainServiceOperationsListNextResponse = OperationEntityListResult; /** Optional parameters. */ export interface DomainServicesListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type DomainServicesListResponse = DomainServiceListResult; /** Optional parameters. */ export interface DomainServicesListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type DomainServicesListByResourceGroupResponse = DomainServiceListResult; /** Optional parameters. */ export interface DomainServicesCreateOrUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the createOrUpdate operation. */ export type DomainServicesCreateOrUpdateResponse = DomainService; /** Optional parameters. */ export interface DomainServicesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type DomainServicesGetResponse = DomainService; /** Optional parameters. */ export interface DomainServicesDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface DomainServicesUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type DomainServicesUpdateResponse = DomainService; /** Optional parameters. */ export interface DomainServicesListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type DomainServicesListNextResponse = DomainServiceListResult; /** Optional parameters. */ export interface DomainServicesListByResourceGroupNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroupNext operation. */ export type DomainServicesListByResourceGroupNextResponse = DomainServiceListResult; /** Optional parameters. */ export interface OuContainerOperationsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type OuContainerOperationsListResponse = OperationEntityListResult; /** Optional parameters. */ export interface OuContainerOperationsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type OuContainerOperationsListNextResponse = OperationEntityListResult; /** Optional parameters. */ export interface OuContainerListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type OuContainerListResponse = OuContainerListResult; /** Optional parameters. */ export interface OuContainerGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type OuContainerGetResponse = OuContainer; /** Optional parameters. */ export interface OuContainerCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type OuContainerCreateResponse = OuContainer; /** Optional parameters. */ export interface OuContainerDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface OuContainerUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type OuContainerUpdateResponse = OuContainer; /** Optional parameters. */ export interface OuContainerListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type OuContainerListNextResponse = OuContainerListResult; /** Optional parameters. */ export interface DomainServicesClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import { ImageStyle, TextProps, TextStyle, ViewStyle } from "react-native"; declare type ActivityIndicatorSizeType = "small" | "large"; interface InputLabelType extends TextStyle { numberOfLines?: number } interface InputType extends TextStyle { autoCapitalize?: string, selectionColor?: string, placeholderTextColor?: string, underlineColorAndroid?: string, } // Activity Indicator export interface ActivityIndicatorType { container?: ViewStyle, indicator?: { color?: string size?: ActivityIndicatorSizeType } } // Animation export interface AnimationType { container?: ViewStyle } // Background Image export interface BackgroundImageType { container?: ViewStyle, image?: ImageStyle & { svgColor?: string } } // Badge export interface BadgeType { container?: ViewStyle, caption?: TextStyle } // Bottom Sheet export interface BottomSheetType { container?: ViewStyle, containerWhenExpandedFullscreen?: ViewStyle, modal?: ViewStyle, modalItems?: { container?: ViewStyle & { rippleColor?: string; } defaultStyle?: TextStyle; primaryStyle?: TextStyle; dangerStyle?: TextStyle; customStyle?: TextStyle; } } // Action Button interface ButtonContainerType extends ViewStyle { rippleColor?: string } interface ButtonStyleType extends ViewStyle { size?: number } interface ButtonIconType extends ButtonStyleType { color?: string } export interface ActionButtonType { container?: ButtonContainerType, containerDisabled?: ViewStyle, icon?: ButtonIconType, iconDisabled?: ButtonIconType, caption?: TextStyle captionDisabled?: TextStyle } // Carousel export interface CarouselLayoutType { slideItem?: ViewStyle, inactiveSlideItem?: { opacity?: number, scale?: number }, pagination?: { container?: ViewStyle, text?: TextStyle, dotContainerStyle?: ViewStyle, dotStyle?: ViewStyle & { color?: string }, inactiveDotStyle?: { color?: string, scale?: number, opacity?: number } } } export interface CarouselType { container?: ViewStyle, fullWidthLayout?: CarouselLayoutType, cardLayout?: CarouselLayoutType, activityIndicator?: { color?: string } } // Checkbox interface CheckBoxInputType extends TextStyle { thumbColorOn?: string, thumbColorOff?: string, trackColorOn?: string, trackColorOff?: string, } export interface CheckBoxType { container?: ViewStyle, containerDisabled?: ViewStyle, label?: InputLabelType, labelDisabled?: TextStyle, input?: CheckBoxInputType, inputDisabled?: CheckBoxInputType, inputError?: CheckBoxInputType, validationMessage?: TextStyle } // Color Picker export interface ColorPickerType { container?: ViewStyle, thumbnail?: ViewStyle } // Container export interface ContainerType { container?: ViewStyle & { rippleColor?: string; } containerDisabled?: ViewStyle; } // Date Picker export interface DatePickerType { container?: ViewStyle, containerDisabled?: ViewStyle, label?: InputLabelType, labelDisabled?: TextStyle, pickerIOS?: { color?: string } & ViewStyle, pickerBackdropIOS?: ViewStyle, pickerTopIOS?: ViewStyle, value?: TextStyle, valueDisabled?: TextStyle, placeholder?: TextStyle, placeholderDisabled?: TextStyle, validationMessage?: TextStyle } // Drop Down export interface DropDownType { container?: ViewStyle, containerDisabled?: ViewStyle, label?: InputLabelType, labelDisabled?: TextStyle, value?: { placeholderTextColor?: string } & TextStyle, valueDisabled?: TextStyle, validationMessage?: TextStyle, /* New dropdown styles start */ valueContainer?: { rippleColor?: string } & ViewStyle; valueContainerFocused?: ViewStyle; valueContainerDisabled?: ViewStyle; valueFocused?: TextStyle; menuWrapper?: ViewStyle; iconStyle?: TextStyle; item?: TextStyle; itemContainer?: ViewStyle & { rippleColor?: string; underlayColor?: string; activeOpacity?: number; }; selectedItem?: TextStyle; selectedItemContainer?: ViewStyle; /* New dropdown styles end */ useUniformDesign?: boolean; // Flag for using old dropdown design with PickerWheel in IOS // Old dropdown styles start pickerIOS?: ViewStyle, pickerItemIOS?: ViewStyle, pickerBackdropIOS?: ViewStyle, pickerTopIOS?: ViewStyle, // Old dropdown styles end } // Feedback export interface FeedbackType { floatingButton?: ViewStyle, dialog?: ViewStyle, title?: TextStyle, textAreaInput?: InputType, switchLabel?: TextStyle, switchInput?: CheckBoxInputType, button?: { color?: string, borderColor?: string, borderWidth?: number }, activityIndicator?: { color?: string } } // Floating Action Button export interface FloatingActionButtonType { container?: ViewStyle, button?: ButtonStyleType & { rippleColor?: string }, buttonIcon?: ButtonIconType secondaryButton?: ButtonStyleType secondaryButtonIcon?: ButtonIconType secondaryButtonCaption?: TextStyle, secondaryButtonCaptionContainer?: ViewStyle, } // Images export interface ImageType { container?: ButtonContainerType, containerDisabled?: ViewStyle, image?: ImageStyle imageDisabled?: ImageStyle } // Intro Screen export interface IntroScreenButtonType { container?: ButtonContainerType, icon?: ButtonIconType, caption?: TextStyle } interface IntroScreenPaginationType { buttonSkip?: IntroScreenButtonType, buttonPrevious?: IntroScreenButtonType, buttonNext?: IntroScreenButtonType, buttonDone?: IntroScreenButtonType, } export interface IntroScreenType { fullscreenContainer?: ViewStyle, popupContainer?: ViewStyle, paginationContainer?: ViewStyle, paginationText?: TextStyle, dotStyle?: ViewStyle, activeDotStyle?: ViewStyle, paginationAbove?: IntroScreenPaginationType & { buttonsContainer?: ViewStyle, }, paginationBetween?: IntroScreenPaginationType } // Layout grid export interface LayoutGridType { container?: ViewStyle } // Line chart interface LineChartGridStyle { backgroundColor?: string; dashArray?: string; lineColor?: string; lineWidth?: number; padding?: number; paddingBottom?: number; paddingHorizontal?: number; paddingLeft?: number; paddingRight?: number; paddingTop?: number; paddingVertical?: number; } interface LineChartAxisStyle<T extends "X" | "Y"> { color?: string; dashArray?: string; fontFamily?: string; fontSize?: number; fontStyle?: "normal" | "italic"; fontWeight?: "normal" | "bold" | "100" | "200" | "300" | "400" | "500" | "600" | "700" | "800" | "900"; lineColor?: string; lineWidth?: number; label?: TextStyle & { relativePositionGrid?: T extends "X" ? "bottom" | "right" : "top" | "left"; }; } interface LineChartLineStyle { line?: { dashArray?: string; ending?: "flat" | "round"; lineColor?: string; lineWidth?: number; }; markers?: { backgroundColor?: string; borderColor?: string; borderWidth?: number; display?: "false" | "underneath" | "onTop"; size?: number; symbol?: "circle" | "diamond" | "plus" | "minus" | "square" | "star" | "triangleDown" | "triangleUp"; }; } interface LineChartLegendStyle { container?: ViewStyle; item?: ViewStyle; indicator?: ViewStyle; label?: TextStyle; } export interface LineChartType { container?: ViewStyle; errorMessage?: TextStyle; chart?: ViewStyle; grid?: LineChartGridStyle; xAxis?: LineChartAxisStyle<"X">; yAxis?: LineChartAxisStyle<"Y">; legend?: LineChartLegendStyle; lines?: { lineColorPalette?: string; customLineStyles?: { [key: string]: LineChartLineStyle; }; }; } // Bar chart interface BarChartGridStyle { backgroundColor?: string; dashArray?: string; lineColor?: string; padding?: number; paddingBottom?: number; paddingHorizontal?: number; paddingLeft?: number; paddingRight?: number; paddingTop?: number; paddingVertical?: number; width?: number; } interface BarChartAxisStyle<T extends "X" | "Y"> { color?: string; dashArray?: string; fontFamily?: string; fontSize?: number; fontStyle?: "normal" | "italic"; fontWeight?: "normal" | "bold" | "100" | "200" | "300" | "400" | "500" | "600" | "700" | "800" | "900"; label?: TextStyle & { relativePositionGrid?: T extends "X" ? "bottom" | "right" : "top" | "left"; }; lineColor?: string; width?: number; } interface BarChartBarStyle { ending?: number; barColor?: string; width?: number; } interface BarChartBarLabelStyle { // color is the same as bar color fontFamily?: string; fontSize?: number; fontStyle?: "normal" | "italic"; fontWeight?: "normal" | "bold" | "100" | "200" | "300" | "400" | "500" | "600" | "700" | "800" | "900"; } export interface BarChartLegendStyle { container?: ViewStyle; item?: ViewStyle; indicator?: ViewStyle; label?: TextStyle; } export interface BarChartType { container?: ViewStyle; errorMessage?: TextStyle; chart?: ViewStyle; grid?: BarChartGridStyle; xAxis?: BarChartAxisStyle<"X">; yAxis?: BarChartAxisStyle<"Y">; legend?: BarChartLegendStyle; bars?: { customBarStyles?: { [key: string]: { bar?: BarChartBarStyle, label?: BarChartBarLabelStyle } }; barsOffset?: number; // only applicable to Grouped presentation mode barColorPalette?: string; }; domain?: { padding?: { x?: number; y?: number }; }; } // List view export interface ListViewType { container?: ViewStyle & { numColumns?: number }, listItem?: ViewStyle, listItemDisabled?: ViewStyle, } // List View Swipe interface ListViewSwipeActionType extends ViewStyle { panelSize?: number } export interface ListViewSwipeType { container?: ViewStyle, leftAction?: ListViewSwipeActionType, rightAction?: ListViewSwipeActionType, } // Maps export interface MapsType { container?: ViewStyle, loadingOverlay?: ViewStyle, loadingIndicator?: { color?: string }, marker?: { color?: string, opacity?: number } } // Navigation export interface NavigationType { bottomBar?: { container?: ViewStyle, label?: TextStyle, selectedLabel?: TextStyle, icon?: TextStyle, selectedIcon?: TextStyle, }, progressOverlay?: { background?: ViewStyle, container?: ViewStyle, activityIndicator?: ViewStyle & { color?: string, size?: ActivityIndicatorSizeType } text?: TextStyle }, } // Page Title export interface PageTitleType { container?: ViewStyle, text?: TextStyle } // Progress Bar export interface ProgressBarType { container?: ViewStyle, bar?: ViewStyle, fill?: { backgroundColor?: string }, validationMessage?: TextStyle } // Progress Circle export interface ProgressCircleType { container?: ViewStyle, circle?: { size?: number, borderWidth?: number, borderColor?: string }, fill?: { width?: number, backgroundColor?: string, lineCapRounded?: boolean, }, text?: TextStyle validationMessage?: TextStyle } // Popup Menu export interface PopupMenuType { container?: ViewStyle; basic: BasicItemStyle; custom: CustomItemStyle buttonContainer?: ViewStyle; } interface CustomItemStyle extends ViewStyle { container?: ViewStyle; itemStyle: { rippleColor?: string }; } interface BasicItemStyle { itemStyle?: ItemStyle; container?: ViewStyle; dividerColor?: string; } interface ItemStyle { rippleColor?: string; ellipsizeMode?: TextProps["ellipsizeMode"]; defaultStyle?: TextStyle; primaryStyle?: TextStyle; dangerStyle?: TextStyle; customStyle?: TextStyle; } // QR Code export interface QRCodeType { container?: ViewStyle, qrcode?: { size?: number, color?: string, backgroundColor?: string } } // Rating export interface RatingType { container?: ViewStyle, containerDisabled?: ViewStyle, icon?: ViewStyle & { size?: number, color?: string, selectedColor?: string, } } // Safe Area View export interface SafeAreaViewType { container?: ViewStyle } // Slider export interface SliderType { container?: ViewStyle, track?: ViewStyle, trackDisabled?: ViewStyle, highlight?: ViewStyle, highlightDisabled?: ViewStyle, marker?: ViewStyle, markerActive?: ViewStyle, markerDisabled?: ViewStyle, validationMessage?: TextStyle, } // Tab Container export interface TabContainerType { container?: ViewStyle, tabBar?: ViewStyle & { bounces?: boolean, pressColor?: string, pressOpacity?: number, scrollEnabled?: boolean }, indicator?: ViewStyle, tab?: ViewStyle, label?: TextStyle, activeLabel?: TextStyle, badgeContainer?: ViewStyle, badgeCaption?: TextStyle } // Text Box export interface TextBoxType { container?: ViewStyle, containerDisabled?: ViewStyle, label?: InputLabelType, labelDisabled?: TextStyle, input?: InputType, inputDisabled?: InputType, inputError?: InputType, inputFocused?: InputType; validationMessage?: TextStyle } // Toggle Buttons export interface ToggleButtonsType { container?: ViewStyle, containerDisabled?: ViewStyle, button?: ViewStyle, text?: TextStyle, activeButton?: ViewStyle, activeButtonText?: TextStyle, validationMessage?: TextStyle, } // Text export interface TextType { container?: ViewStyle, text?: TextStyle } // Video Player export interface VideoPlayerType { container?: ViewStyle, indicator?: { backgroundColor?: string, }, video?: ViewStyle } // Web View export interface WebViewType { container?: ViewStyle, errorContainer?: ViewStyle, errorText?: TextStyle }
the_stack
import path from 'path'; import { loadFromPath } from '../../src/fhirdefs/load'; import { FHIRDefinitions } from '../../src/fhirdefs/FHIRDefinitions'; import { StructureDefinition } from '../../src/fhirtypes/StructureDefinition'; import { FshCode } from '../../src/fshtypes/FshCode'; import { TestFisher } from '../testhelpers'; describe('ElementDefinition', () => { let defs: FHIRDefinitions; let medicationRequest: StructureDefinition; let medication: StructureDefinition; let fisher: TestFisher; beforeAll(() => { defs = new FHIRDefinitions(); loadFromPath(path.join(__dirname, '..', 'testhelpers', 'testdefs'), 'r4-definitions', defs); fisher = new TestFisher().withFHIR(defs); }); beforeEach(() => { medicationRequest = fisher.fishForStructureDefinition('MedicationRequest'); medication = fisher.fishForStructureDefinition('Medication'); }); describe('#assignValue', () => { // NOTE: Most assignValue tests are in separate type-specific files. We only test outliers here. it('should throw MismatchedTypeException when attempting to assign a value with an unsupported type', () => { const authoredOn = medicationRequest.elements.find( e => e.id === 'MedicationRequest.authoredOn' ); expect(() => { // @ts-ignore: Argument of type 'Date' is not assignable to parameter of type 'AssignmentValueType' authoredOn.assignValue(new Date()); // Date is not a supported type -- only strings are allowed }).toThrow(/Cannot assign Date value.*Value does not match element type: dateTime/); expect(() => { // @ts-ignore: Argument of type 'Date' is not assignable to parameter of type 'AssignmentValueType' authoredOn.assignValue(new Date(), true); // Date is not a supported type -- only strings are allowed }).toThrow(/Cannot assign Date value.*Value does not match element type: dateTime/); }); it('should throw ValueAlreadyAssignedError when assigning a value assigned via parent pattern', () => { const medicationForm = medication.elements.find(e => e.id === 'Medication.form'); medicationForm.assignValue(new FshCode('foo', 'http://thankYouForSettingMe.com')); const medicationFormCodingSystem = medication.findElementByPath('form.coding.system', fisher); expect(() => { medicationFormCodingSystem.assignValue('http://ohManIWillNeverGetSet.sad'); }).toThrow( 'Cannot assign "http://ohManIWillNeverGetSet.sad" to this element; a different uri is already assigned: "http://thankYouForSettingMe.com".' ); expect(() => { medicationFormCodingSystem.assignValue('http://ohManIWillNeverGetSet.sad', true); }).toThrow( 'Cannot assign "http://ohManIWillNeverGetSet.sad" to this element; a different uri is already assigned: "http://thankYouForSettingMe.com".' ); }); it('should ensure that minimum cardinality is 1 when assigning a value mentioned in a parent slice discriminator', () => { const cat = medicationRequest.elements.find(e => e.id === 'MedicationRequest.category'); cat.slicing = { discriminator: [{ type: 'value', path: 'coding.code' }], rules: 'open' }; cat.addSlice('mouse'); const catMouseCodingCode = medicationRequest.findElementByPath( 'category[mouse].coding.code', fisher ); expect(catMouseCodingCode.min).toBe(0); catMouseCodingCode.assignValue(new FshCode('cheese')); expect(catMouseCodingCode.patternCode).toBe('cheese'); expect(catMouseCodingCode.min).toBe(1); }); it('should ensure that minimum cardinality is 1 when assigning a value mentioned in the discriminator of a grandparent slice', () => { const cat = medicationRequest.elements.find(e => e.id === 'MedicationRequest.category'); cat.slicing = { discriminator: [{ type: 'value', path: 'coding.code' }], rules: 'open' }; cat.addSlice('mouse'); const catCoding = medicationRequest.findElementByPath('category.coding', fisher); catCoding.slicing = { discriminator: [{ type: 'value', path: 'coding' }], rules: 'open' }; catCoding.addSlice('rat'); const catMouseCodingRatCode = medicationRequest.findElementByPath( 'category[mouse].coding[rat].code', fisher ); expect(catMouseCodingRatCode.min).toBe(0); catMouseCodingRatCode.assignValue(new FshCode('cheese')); expect(catMouseCodingRatCode.patternCode).toBe('cheese'); expect(catMouseCodingRatCode.min).toBe(1); }); it('should not ensure that minimum cardinality is 1 when assigning a value mentioned in a slice discriminator via $this', () => { const inUri = medicationRequest.elements.find( e => e.id === 'MedicationRequest.instantiatesUri' ); inUri.slicing = { discriminator: [{ type: 'value', path: '$this' }], rules: 'open' }; inUri.addSlice('mouse'); const inUriMouse = medicationRequest.findElementByPath('instantiatesUri[mouse]', fisher); expect(inUriMouse.min).toBe(0); inUriMouse.assignValue('http://mice.cheese'); expect(inUriMouse.patternUri).toBe('http://mice.cheese'); expect(inUriMouse.min).toBe(0); }); it('should not ensure that minimum cardinality is 1 when assigning a value not mentioned in a slice discriminator', () => { const cat = medicationRequest.elements.find(e => e.id === 'MedicationRequest.category'); cat.slicing = { discriminator: [{ type: 'value', path: 'coding.code' }], rules: 'open' }; cat.addSlice('mouse'); const catMouseCodingSystem = medicationRequest.findElementByPath( 'category[mouse].coding.system', fisher ); expect(catMouseCodingSystem.min).toBe(0); catMouseCodingSystem.assignValue('http://mice.cheese'); expect(catMouseCodingSystem.patternUri).toBe('http://mice.cheese'); expect(catMouseCodingSystem.min).toBe(0); }); it('should not ensure that minimum cardinality is 1 when assigning a value mentioned in a non value/pattern discriminator', () => { const cat = medicationRequest.elements.find(e => e.id === 'MedicationRequest.category'); cat.slicing = { discriminator: [{ type: 'exists', path: 'coding.code' }], rules: 'open' }; cat.addSlice('mouse'); const catMouseCodingCode = medicationRequest.findElementByPath( 'category[mouse].coding.code', fisher ); expect(catMouseCodingCode.min).toBe(0); catMouseCodingCode.assignValue(new FshCode('cheese')); expect(catMouseCodingCode.patternCode).toBe('cheese'); expect(catMouseCodingCode.min).toBe(0); }); it('should not ensure that minimum cardinality is 1 when assigning a value with min card > 1 mentioned in a parent slice discriminator', () => { const cat = medicationRequest.elements.find(e => e.id === 'MedicationRequest.category'); cat.slicing = { discriminator: [{ type: 'value', path: 'coding' }], rules: 'open' }; cat.addSlice('mouse'); const catMouseCoding = medicationRequest.findElementByPath('category[mouse].coding', fisher); catMouseCoding.min = 2; expect(catMouseCoding.min).toBe(2); catMouseCoding.assignValue(new FshCode('cheese')); expect(catMouseCoding.patternCoding).toEqual({ code: 'cheese' }); expect(catMouseCoding.min).toBe(2); // We do not try to decrease min to 1 }); it('should not ensure that minimum cardinality is 1 when assigning a value with no parent slice discriminator', () => { const cat = medicationRequest.elements.find(e => e.id === 'MedicationRequest.category'); cat.slicing = { rules: 'open' }; cat.addSlice('mouse'); const catMouseCoding = medicationRequest.findElementByPath('category[mouse].coding', fisher); expect(catMouseCoding.min).toBe(0); catMouseCoding.assignValue(new FshCode('cheese')); expect(catMouseCoding.patternCoding).toEqual({ code: 'cheese' }); expect(catMouseCoding.min).toBe(0); // We do not increase min, since no discriminator }); }); describe('#assignedByDirectParent', () => { it('should find a fixed[x] value from the parent when it exists', () => { const statusReason = medicationRequest.elements.find( e => e.id === 'MedicationRequest.statusReason' ); statusReason.assignValue(new FshCode('foo'), true); const statusReasonCoding = medicationRequest.findElementByPath('statusReason.coding', fisher); const assignedValue = statusReasonCoding.assignedByDirectParent(); expect(assignedValue).toEqual([{ code: 'foo' }]); }); it('should find a pattern[x] value from the parent when it exists', () => { const statusReason = medicationRequest.elements.find( e => e.id === 'MedicationRequest.statusReason' ); statusReason.assignValue(new FshCode('foo')); const statusReasonCoding = medicationRequest.findElementByPath('statusReason.coding', fisher); const patternValue = statusReasonCoding.assignedByDirectParent(); expect(patternValue).toEqual([{ code: 'foo' }]); }); it('should not find a fixed[x] or pattern[x] value from the parent when none is present', () => { const statusReasonCoding = medicationRequest.findElementByPath('statusReason.coding', fisher); const patternValue = statusReasonCoding.assignedByDirectParent(); expect(patternValue).toBeUndefined(); }); it('should return undefined when being run on the root element', () => { const root = medicationRequest.elements.find(e => e.id === 'MedicationRequest'); const patternValue = root.assignedByDirectParent(); expect(patternValue).toBeUndefined(); }); }); describe('#assignedByAnyParent', () => { it('should find a fixed[x] value from a direct parent when it exists', () => { const statusReason = medicationRequest.elements.find( e => e.id === 'MedicationRequest.statusReason' ); statusReason.assignValue(new FshCode('foo'), true); const statusReasonCoding = medicationRequest.findElementByPath('statusReason.coding', fisher); const assignedValue = statusReasonCoding.assignedByAnyParent(); expect(assignedValue).toEqual([{ code: 'foo' }]); }); it('should find a pattern[x] value from a direct parent when it exists', () => { const statusReason = medicationRequest.elements.find( e => e.id === 'MedicationRequest.statusReason' ); statusReason.assignValue(new FshCode('foo')); const statusReasonCoding = medicationRequest.findElementByPath('statusReason.coding', fisher); const patternValue = statusReasonCoding.assignedByAnyParent(); expect(patternValue).toEqual([{ code: 'foo' }]); }); it('should find a fixed[x] value from a grandparent when it exists', () => { const identifier = medicationRequest.elements.find( e => e.id === 'MedicationRequest.identifier' ); identifier.max = '1'; // @ts-ignore identifier.fixedIdentifier = { period: { start: '2011-11-11' } }; const identifierPeriodStart = medicationRequest.findElementByPath( 'identifier.period.start', fisher ); const assignedValue = identifierPeriodStart.assignedByAnyParent(); expect(assignedValue).toBe('2011-11-11'); }); it('should find a pattern value from a grandparent when it exists', () => { const identifier = medicationRequest.elements.find( e => e.id === 'MedicationRequest.identifier' ); identifier.max = '1'; // @ts-ignore identifier.patternIdentifier = { period: { start: '2011-11-11' } }; const identifierPeriodStart = medicationRequest.findElementByPath( 'identifier.period.start', fisher ); const patternValue = identifierPeriodStart.assignedByAnyParent(); expect(patternValue).toBe('2011-11-11'); }); it('should find an array fixed[x] value from a grandparent when it exists', () => { const statusReason = medicationRequest.elements.find( e => e.id === 'MedicationRequest.statusReason' ); statusReason.assignValue(new FshCode('foo', 'http://bar.com'), true); const statusReasonCodingSystem = medicationRequest.findElementByPath( 'statusReason.coding.system', fisher ); // Single element in array let assignedValue = statusReasonCodingSystem.assignedByAnyParent(); expect(assignedValue).toBe('http://bar.com'); // Multiple not matching array elements statusReason.fixedCodeableConcept = { coding: [{ system: 'http://foo.com' }, { system: 'http://bar.com' }] }; assignedValue = statusReasonCodingSystem.assignedByAnyParent(); expect(assignedValue).toEqual(['http://foo.com', 'http://bar.com']); // Multiple matching array elements statusReason.fixedCodeableConcept = { coding: [{ system: 'http://foo.com' }, { system: 'http://foo.com' }] }; assignedValue = statusReasonCodingSystem.assignedByAnyParent(); expect(assignedValue).toBe('http://foo.com'); }); it('should find an array pattern value from a grandparent when it exists', () => { const statusReason = medicationRequest.elements.find( e => e.id === 'MedicationRequest.statusReason' ); statusReason.assignValue(new FshCode('foo', 'http://bar.com')); const statusReasonCodingSystem = medicationRequest.findElementByPath( 'statusReason.coding.system', fisher ); // Single element in array let patternValue = statusReasonCodingSystem.assignedByAnyParent(); expect(patternValue).toBe('http://bar.com'); // Multiple not matching array elements statusReason.patternCodeableConcept = { coding: [{ system: 'http://foo.com' }, { system: 'http://bar.com' }] }; patternValue = statusReasonCodingSystem.assignedByAnyParent(); expect(patternValue).toEqual(['http://foo.com', 'http://bar.com']); // Multiple matching array elements statusReason.patternCodeableConcept = { coding: [{ system: 'http://foo.com' }, { system: 'http://foo.com' }] }; patternValue = statusReasonCodingSystem.assignedByAnyParent(); expect(patternValue).toBe('http://foo.com'); }); it('should not find a fixed[x] or pattern[x] value from the parent when none is present', () => { const statusReasonCoding = medicationRequest.findElementByPath( 'statusReason.coding.version', fisher ); const value = statusReasonCoding.assignedByAnyParent(); expect(value).toBeUndefined(); }); it('should return undefined when being run on the root element', () => { const root = medicationRequest.elements.find(e => e.id === 'MedicationRequest'); const patternValue = root.assignedByAnyParent(); expect(patternValue).toBeUndefined(); }); }); });
the_stack
import { autoBindMethodsForReact } from 'class-autobind-decorator'; import classnames from 'classnames'; import React, { CSSProperties, Fragment, PureComponent, ReactNode } from 'react'; import ReactDOM from 'react-dom'; import { AUTOBIND_CFG } from '../../../../common/constants'; import { hotKeyRefs } from '../../../../common/hotkeys'; import { executeHotKey } from '../../../../common/hotkeys-listener'; import { fuzzyMatch } from '../../../../common/misc'; import { KeydownBinder } from '../../keydown-binder'; import { DropdownButton } from './dropdown-button'; import { DropdownDivider } from './dropdown-divider'; import { DropdownItem } from './dropdown-item'; const dropdownsContainer = document.querySelector('#dropdowns-container'); export interface DropdownProps { children: ReactNode; right?: boolean; outline?: boolean; wide?: boolean; onOpen?: Function; onHide?: Function; className?: string; style?: CSSProperties; beside?: boolean; } interface State { open: boolean; dropUp: boolean; filter: string; filterVisible: boolean; filterItems?: number[] | null; filterActiveIndex: number; forcedPosition?: {x: number; y: number} | null; uniquenessKey: number; } @autoBindMethodsForReact(AUTOBIND_CFG) export class Dropdown extends PureComponent<DropdownProps, State> { private _node: HTMLDivElement | null = null; private _dropdownList: HTMLDivElement | null = null; private _filter: HTMLInputElement | null = null; state: State = { open: false, dropUp: false, // Filter Stuff filter: '', filterVisible: false, filterItems: null, filterActiveIndex: 0, // Position forcedPosition: null, // Use this to force new menu every time dropdown opens uniquenessKey: 0, }; _setRef(n: HTMLDivElement) { this._node = n; } _handleCheckFilterSubmit(e) { if (e.key === 'Enter') { // Listen for the Enter key and "click" on the active list item const selector = `li[data-filter-index="${this.state.filterActiveIndex}"] button`; const button = this._dropdownList?.querySelector(selector); // @ts-expect-error -- TSCONVERSION button?.click(); } } _handleChangeFilter(event: React.ChangeEvent<HTMLInputElement>) { const newFilter = event.target.value; // Nothing to do if the filter didn't change if (newFilter === this.state.filter) { return; } // Filter the list items that are filterable (have data-filter-index property) const filterItems: number[] = []; // @ts-expect-error -- TSCONVERSION convert to array or use querySelectorAll().forEach for (const listItem of this._dropdownList.querySelectorAll('li')) { if (!listItem.hasAttribute('data-filter-index')) { continue; } const match = fuzzyMatch(newFilter, listItem.textContent); if (!newFilter || match) { const filterIndex = listItem.getAttribute('data-filter-index'); filterItems.push(parseInt(filterIndex, 10)); } } this.setState({ filter: newFilter, filterItems: newFilter ? filterItems : null, filterActiveIndex: filterItems[0] || -1, filterVisible: this.state.filterVisible ? true : newFilter.length > 0, }); } _handleDropdownNavigation(e) { const { key, shiftKey } = e; // Handle tab and arrows to move up and down dropdown entries const { filterItems, filterActiveIndex } = this.state; if (['Tab', 'ArrowDown', 'ArrowUp'].includes(key)) { e.preventDefault(); const items = filterItems || []; if (!filterItems) { // @ts-expect-error -- TSCONVERSION convert to array or use querySelectorAll().forEach for (const li of this._dropdownList.querySelectorAll('li')) { if (li.hasAttribute('data-filter-index')) { const filterIndex = li.getAttribute('data-filter-index'); items.push(parseInt(filterIndex, 10)); } } } const i = items.indexOf(filterActiveIndex); if (key === 'ArrowUp' || (key === 'Tab' && shiftKey)) { const nextI = i > 0 ? items[i - 1] : items[items.length - 1]; this.setState({ filterActiveIndex: nextI, }); } else { this.setState({ filterActiveIndex: items[i + 1] || items[0], }); } } this._filter?.focus(); } _handleBodyKeyDown(e) { if (!this.state.open) { return; } // Catch all key presses (like global app hotkeys) if we're open e.stopPropagation(); this._handleDropdownNavigation(e); executeHotKey(e, hotKeyRefs.CLOSE_DROPDOWN, () => { this.hide(); }); } _checkSizeAndPosition() { if (!this.state.open || !this._dropdownList) { return; } // Get dropdown menu const dropdownList = this._dropdownList; // Compute the size of all the menus // @ts-expect-error -- TSCONVERSION should exit if node is not defined let dropdownBtnRect = this._node.getBoundingClientRect(); const bodyRect = document.body.getBoundingClientRect(); const dropdownListRect = dropdownList.getBoundingClientRect(); const { forcedPosition } = this.state; if (forcedPosition) { // @ts-expect-error -- TSCONVERSION missing properties dropdownBtnRect = { left: forcedPosition.x, right: bodyRect.width - forcedPosition.x, top: forcedPosition.y, bottom: bodyRect.height - forcedPosition.y, width: 100, height: 10, }; } // Should it drop up? const bodyHeight = bodyRect.height; const dropdownTop = dropdownBtnRect.top; const dropUp = dropdownTop > bodyHeight - 200; // Reset all the things so we can start fresh this._dropdownList.style.left = 'initial'; this._dropdownList.style.right = 'initial'; this._dropdownList.style.top = 'initial'; this._dropdownList.style.bottom = 'initial'; this._dropdownList.style.minWidth = 'initial'; this._dropdownList.style.maxWidth = 'initial'; const screenMargin = 6; const { right, wide } = this.props; if (right || wide) { const { right: originalRight } = dropdownBtnRect; // Prevent dropdown from squishing against left side of screen const right = Math.max(dropdownListRect.width + screenMargin, originalRight); const { beside } = this.props; const offset = beside ? dropdownBtnRect.width - 40 : 0; this._dropdownList.style.right = `${bodyRect.width - right + offset}px`; this._dropdownList.style.maxWidth = `${Math.min(dropdownListRect.width, right + offset)}px`; } if (!right || wide) { const { left: originalLeft } = dropdownBtnRect; const { beside } = this.props; const offset = beside ? dropdownBtnRect.width - 40 : 0; // Prevent dropdown from squishing against right side of screen const left = Math.min(bodyRect.width - dropdownListRect.width - screenMargin, originalLeft); this._dropdownList.style.left = `${left + offset}px`; this._dropdownList.style.maxWidth = `${Math.min( dropdownListRect.width, bodyRect.width - left - offset, )}px`; } if (dropUp) { const { top } = dropdownBtnRect; this._dropdownList.style.bottom = `${bodyRect.height - top}px`; this._dropdownList.style.maxHeight = `${top - screenMargin}px`; } else { const { bottom } = dropdownBtnRect; this._dropdownList.style.top = `${bottom}px`; this._dropdownList.style.maxHeight = `${bodyRect.height - bottom - screenMargin}px`; } } _handleClick(e) { e.preventDefault(); e.stopPropagation(); this.toggle(); } static _handleMouseDown(e) { // Intercept mouse down so that clicks don't trigger things like drag and drop. e.preventDefault(); } _addDropdownListRef(n: HTMLDivElement) { this._dropdownList = n; } _addFilterRef(n: HTMLInputElement) { this._filter = n; // Automatically focus the filter element when mounted so we can start typing if (this._filter) { this._filter.focus(); } } _getFlattenedChildren(children) { let newChildren: ReactNode[] = []; // Ensure children is an array children = Array.isArray(children) ? children : [children]; for (const child of children) { if (!child) { // Ignore null components continue; } if (child.type === Fragment) { newChildren = [...newChildren, ...this._getFlattenedChildren(child.props.children)]; } else if (Array.isArray(child)) { newChildren = [...newChildren, ...this._getFlattenedChildren(child)]; } else { newChildren.push(child); } } return newChildren; } componentDidUpdate() { this._checkSizeAndPosition(); } hide() { // Focus the dropdown button after hiding if (this._node) { const button = this._node.querySelector('button'); button?.focus(); } this.setState({ open: false, }); this.props.onHide?.(); } show(filterVisible = false, forcedPosition: { x: number; y: number } | null = null) { const bodyHeight = document.body.getBoundingClientRect().height; // @ts-expect-error -- TSCONVERSION _node can be undefined const dropdownTop = this._node.getBoundingClientRect().top; const dropUp = dropdownTop > bodyHeight - 200; this.setState({ open: true, dropUp, forcedPosition, filterVisible, filter: '', filterItems: null, filterActiveIndex: -1, uniquenessKey: this.state.uniquenessKey + 1, }); this.props.onOpen?.(); } toggle(filterVisible = false) { if (this.state.open) { this.hide(); } else { this.show(filterVisible); } } render() { const { right, outline, wide, className, style, children } = this.props; const { dropUp, open, uniquenessKey, filterVisible, filterActiveIndex, filterItems, filter, } = this.state; const classes = classnames('dropdown', className, { 'dropdown--wide': wide, 'dropdown--open': open, }); const menuClasses = classnames({ // eslint-disable-next-line camelcase dropdown__menu: true, 'theme--dropdown__menu': true, 'dropdown__menu--open': open, 'dropdown__menu--outlined': outline, 'dropdown__menu--up': dropUp, 'dropdown__menu--right': right, }); const dropdownButtons: ReactNode[] = []; const dropdownItems: ReactNode[] = []; const allChildren = this._getFlattenedChildren(children); const visibleChildren = allChildren.filter((child, i) => { // @ts-expect-error -- TSCONVERSION this should cater for all types that ReactNode can be if (child.type.name !== DropdownItem.name) { return true; } // It's visible if its index is in the filterItems return !filterItems || filterItems.includes(i); }); for (let i = 0; i < allChildren.length; i++) { const child = allChildren[i]; // @ts-expect-error -- TSCONVERSION this should cater for all types that ReactNode can be if (child.type.name === DropdownButton.name) { dropdownButtons.push(child); // @ts-expect-error -- TSCONVERSION this should cater for all types that ReactNode can be } else if (child.type.name === DropdownItem.name) { const active = i === filterActiveIndex; const hide = !visibleChildren.includes(child); dropdownItems.push( <li key={i} data-filter-index={i} className={classnames({ active, hide, })} > {child} </li>, ); // @ts-expect-error -- TSCONVERSION this should cater for all types that ReactNode can be } else if (child.type.name === DropdownDivider.name) { const currentIndex = visibleChildren.indexOf(child); const nextChild = visibleChildren[currentIndex + 1]; // Only show the divider if the next child is a DropdownItem // @ts-expect-error -- TSCONVERSION this should cater for all types that ReactNode can be if (nextChild && nextChild.type.name === DropdownItem.name) { dropdownItems.push(<li key={i}>{child}</li>); } } } let finalChildren: React.ReactNode = []; if (dropdownButtons.length !== 1) { console.error(`Dropdown needs exactly one DropdownButton! Got ${dropdownButtons.length}`, { allChildren, }); } else { const noResults = filter && filterItems && filterItems.length === 0; finalChildren = [ dropdownButtons[0], ReactDOM.createPortal( <div key="item" className={menuClasses} aria-hidden={!open} > <div className="dropdown__backdrop theme--transparent-overlay" /> <div key={uniquenessKey} ref={this._addDropdownListRef} tabIndex={-1} className={classnames('dropdown__list', { 'dropdown__list--filtering': filterVisible, })} > <div className="form-control dropdown__filter"> <i className="fa fa-search" /> <input type="text" onChange={this._handleChangeFilter} ref={this._addFilterRef} onKeyPress={this._handleCheckFilterSubmit} /> </div> {noResults && <div className="text-center pad warning">No match :(</div>} <ul className={classnames({ hide: noResults, })} > {dropdownItems} </ul> </div> </div>, // @ts-expect-error -- TSCONVERSION dropdownsContainer, ), ]; } return ( <KeydownBinder stopMetaPropagation onKeydown={this._handleBodyKeyDown} disabled={!open}> <div style={style} className={classes} ref={this._setRef} onClick={this._handleClick} tabIndex={-1} onMouseDown={Dropdown._handleMouseDown} > {finalChildren} </div> </KeydownBinder> ); } }
the_stack
import { Observable, Subject, forkJoin, of, from, defer, concat, empty } from 'rxjs'; import { DatabaseService } from '@wizdm/connect/database'; import { DatabaseBatch } from '@wizdm/connect/database/document'; import { StorageService, StorageRef } from '@wizdm/connect/storage'; import { FunctionsClient } from '@wizdm/connect/functions/client'; import { UserProfile, UserData } from 'app/utils/user'; import { map, scan, tap, switchMap } from 'rxjs/operators'; import { animationFrameScheduler } from 'rxjs'; import { UserRecord } from '../admin-types'; import { Component } from '@angular/core'; import { append } from '@wizdm/rxjs'; /** Users Analysis Report */ export interface UserReport { // Input data users: UserRecord[]; profiles: UserData[]; folders: StorageRef[]; // Users vs profiles comparison missing?: UserRecord[]; orphans?: UserData[]; // Profile inconsistencies userNameMissing: UserData[]; fullNameMissing: UserData[]; searchIndexMissing: UserData[]; // Status report currentId?: string; currentIndex?: number; errorsCount?: number; done?: boolean; } @Component({ selector: 'wm-profile-fixer', templateUrl: './profile-fixer.component.html', styleUrls: ['./profile-fixer.component.scss'] }) export class ProfileFixerComponent { readonly report$: Observable<UserReport>; readonly run$ = new Subject<void>(); /** WriteBatch collecting all the fixes to be applied over the database */ public batch: DatabaseBatch; /** The DatabaseService */ private get db(): DatabaseService { return this.users.db; } constructor(private client: FunctionsClient, private users: UserProfile, private st: StorageService ) { // Builds the report observable to emit each step of the analysis this.report$ = this.run$.pipe( // Starts by resetting the WriteBatch, if any. tap( () => { this.batch = null; }), // Concatenates two tasks switchMap( () => concat( // First task simply emits an empty report to display the 'Fetchind data' message while loading data from the server of({} as UserReport), // Second task starts by loading all the data from the server forkJoin( this.listAllUsers(), this.listAllProfiles(), this.listAllFolders() ).pipe( // Collects the results to initialize the repoprt with the input data map( ([users, profiles, folders]) => ({ users, profiles, folders, missing: [], orphans: [], currentId: '', errorsCount: 0 } as UserReport) ), // Runs every UserRecord by the animationScheduler switchMap( report => from(report.users, animationFrameScheduler).pipe( // Analyze each record building up the resulting report scan( (report, user, index) => { // Keeps track of the pregress report.currentId = user.uid; report.currentIndex = index; // Gets the profile supposidely matching the UserRecord. Note that both UserRecord[] and // UserData[] arrays are purposely sorted in ascending uid order server side const profile = report.profiles[index - report.missing.length + report.orphans.length]; // Matches the UserRecord with the profile: // 1. Accounts for missing profiles (the user exists without a profile) if(!profile || profile.id > user.uid) { report.missing.push( user ); report.errorsCount++; } // 2. Accounts for orphan profiles (the profile exists without a user) else if(profile.id < user.uid) { report.orphans.push( profile ); report.errorsCount++; } // Verifies the user has a storage folder const folderIndex = report.folders.findIndex( folder => folder.name === user.uid); if(folderIndex >= 0) { report.folders.splice(folderIndex, 1); } // Analyzes the profile for inconsistencies this.analyzeProfile(profile, report); // Emits the current report return report; }, report), // Once every UserRecord as being analyzed, lets check for orphan profiles append( report => { // Computes the starting position accounting for missing and already discovered orphan profiles const start = report.users.length - report.missing.length + report.orphans.length; // Completes if there's nothing left to do if(start >= report.profiles.length) { return empty(); } // Runs every profile left otherwise return from( report.profiles.slice(start), animationFrameScheduler).pipe( // Analyze each orhpan profile scan( (report, profile) => { // Keeps track of the progress report.currentId = profile.id; report.currentIndex++; // Collects the orphans report.orphans.push( profile ); report.errorsCount++; // Emits the report return report; }, report) ); }, report), // Done append( report => of({ ...report, done: true })) )) ) )) ); } /** List all users returning them in ascending order sorted by uid */ private listAllUsers(): Observable<UserRecord[]> { return this.client.get<UserRecord[]>('users'); } /** List all user's profile ordered by id */ private listAllProfiles(): Observable<UserData[]> { return defer( () => this.users.get( qf => qf.orderBy(this.db.sentinelId) )); } /** Deletes a storage folder from the default bucket */ private deleteFolder(prefix: string): Observable<void> { return this.client.delete<void>(`folders/${prefix}`); } /** List all storage folders */ private listAllFolders(): Observable<StorageRef[]> { return this.st.reference('/').listAll().pipe( map( result => result.prefixes ) ); } /** Analyzes a profile serching for inconsistencies */ private analyzeProfile(profile: UserData, report: UserReport) { // Skips when no profile is given if(!profile) { return report; } // Checks for user names. Required for user profile navigation if(!profile.userName) { report.userNameMissing = (report['userNameMissing'] || []).concat(profile); report.errorsCount++; } // Checks for full names. Required for user sorting if(!profile.fullName) { report.fullNameMissing = (report['fullNameMissing'] || []).concat(profile); report.errorsCount++; } // Checks for search indexes. Required for user searching if(!profile.searchIndex) { report.searchIndexMissing = (report['searchIndexMissing'] || []).concat(profile); report.errorsCount++; } else { // Computes a new search index to compare the profile with const { searchIndex } = this.users.formatData({ lastName: '', ...profile }); // Compare the search indexes for equality if(searchIndex.length !== profile.searchIndex.length || searchIndex.some( (value, index) => value !== profile.searchIndex[index])) { report.searchIndexMissing = (report['searchIndexMissing'] || []).concat(profile); report.errorsCount++; } } return report; } /** Creates a new profile from the user record (BatchWrite) */ public createMissingProfile(user: UserRecord, report: UserReport) { const index = report.missing.findIndex( missing => missing === user); if(index >= 0) { const batch = this.batch || ( this.batch = this.db.batch() ); batch.set(this.users.ref.doc(user.uid), this.users.userData(user as any)); report.missing.splice(index, 1); report.errorsCount--; } } /** Deletes the orphan profile (WriteBatch) */ public deleteOrphanProfile(profile: UserData, report: UserReport) { const index = report.orphans.findIndex(orphan => orphan === profile); if(index >= 0) { const batch = this.batch || ( this.batch = this.db.batch() ); batch.delete(this.users.ref.doc(profile.id)); report.orphans.splice(index, 1); report.errorsCount--; } } /** Deletes the orphan folder immediately */ public deleteOrphanFolder(folder: StorageRef, report: UserReport) { const index = report.folders.findIndex(orphan => orphan === folder); if(index >= 0) { this.deleteFolder(folder.name).subscribe( () => { report.folders.splice(index, 1); report.errorsCount--; }); } } /** Guesse a user nick-name (WriteBatch) */ public guessMissingUserNames(profiles: UserData[], report: UserReport) { if(!profiles) { return; } const batch = this.batch || ( this.batch = this.db.batch() ); const guesses: string[] = []; Promise.all( profiles.map( profile => { const { fullName } = this.users.formatData({ lastName: '', ...profile }); return this.users.guessUserName(fullName).then( userName => { while(guesses.find( guess => guess === userName )) { userName = userName.concat('z'); } console.log("Guessing", userName); batch.update(this.users.ref.doc(profile.id), { userName }); guesses.push(userName); report.errorsCount--; }); })).then( () => delete report.userNameMissing ); } /** Guesses a user's fullName (WriteBatch) */ public guessMissingFullNames(profiles: UserData[], report: UserReport) { if(!profiles) { return; } const batch = this.batch || ( this.batch = this.db.batch() ); profiles.forEach( profile => { const { fullName } = this.users.formatData({ lastName: '', ...profile }); batch.update(this.users.ref.doc(profile.id), { fullName }); report.errorsCount--; }); delete report.userNameMissing; } /** Coputes the search index (WriteBatch) */ public computeMissingSearchIndex(profiles: UserData[], report: UserReport) { if(!profiles) { return; } const batch = this.batch || ( this.batch = this.db.batch() ); profiles.forEach( profile => { const { searchIndex } = this.users.formatData({ lastName: '', ...profile }); batch.update(this.users.ref.doc(profile.id), { searchIndex }); report.errorsCount--; }); delete report.searchIndexMissing; } /** */ public fixAllAnomalies(report: UserReport) { report.missing?.forEach( user => this.createMissingProfile(user, report) ); report.orphans?.forEach( profile => this.deleteOrphanProfile(profile, report) ); this.guessMissingUserNames(report.userNameMissing, report); this.computeMissingSearchIndex(report.searchIndexMissing, report); } public applyAllFixes(report: UserReport) { if(!report) { return; } forkJoin( from( this.batch ? this.batch.commit() : empty() ), from( report.folders || [] ).pipe( switchMap( folder => this.deleteFolder(folder.name) ) ) ).toPromise().then( () => this.batch = null ); } }
the_stack
import ReactDom from 'react-dom'; import { CommandRegistryImpl, CommandRegistry, IPreferenceSettingsService, PreferenceScope, KeybindingRegistryImpl, KeybindingRegistry, setLanguageId, } from '@opensumi/ide-core-browser'; import { IToolbarRegistry } from '@opensumi/ide-core-browser/lib/toolbar'; import { IMenuRegistry, MenuRegistryImpl, IMenuItem } from '@opensumi/ide-core-browser/src/menu/next'; import { NextToolbarRegistryImpl } from '@opensumi/ide-core-browser/src/toolbar/toolbar.registry'; import { IActivationEventService, ExtensionBeforeActivateEvent } from '@opensumi/ide-extension/lib/browser/types'; import { IMainLayoutService } from '@opensumi/ide-main-layout'; import { LayoutService } from '@opensumi/ide-main-layout/lib/browser/layout.service'; import { TabbarService } from '@opensumi/ide-main-layout/lib/browser/tabbar/tabbar.service'; import { PreferenceSettingsService } from '@opensumi/ide-preferences/lib/browser/preference-settings.service'; import { WorkbenchThemeService } from '@opensumi/ide-theme/lib/browser/workbench.theme.service'; import { IThemeService, getColorRegistry } from '@opensumi/ide-theme/lib/common'; import '@opensumi/ide-i18n'; import { MockInjector } from '../../../../../tools/dev-tool/src/mock-injector'; import { AbstractExtInstanceManagementService } from '../../../src/browser/types'; import { ExtensionService, IExtCommandManagement, AbstractExtensionManagementService, IRequireInterceptorService, } from '../../../src/common'; import { MOCK_EXTENSIONS, setupExtensionServiceInjector } from './extension-service-mock-helper'; describe('Extension service', () => { let extensionService: ExtensionService; let extCommandManagement: IExtCommandManagement; let extInstanceManagementService: AbstractExtInstanceManagementService; let extensionManagementService: AbstractExtensionManagementService; let injector: MockInjector; beforeAll(() => { injector = setupExtensionServiceInjector(); injector.get(IMainLayoutService).viewReady.resolve(); extensionService = injector.get(ExtensionService); extCommandManagement = injector.get(IExtCommandManagement); extInstanceManagementService = injector.get(AbstractExtInstanceManagementService); extensionManagementService = injector.get(AbstractExtensionManagementService); }); describe('activate', () => { it('should activate extension service.', async () => { await extensionService.activate(); }); it('emit event before activate', (done) => { // @ts-ignore extensionService.eventBus.on(ExtensionBeforeActivateEvent, () => { done(); }); // @ts-ignore extensionService.doActivate(); }); it('emit onStartupFinished activationEvent after activate', (done) => { const activationEventService = injector.get<IActivationEventService>(IActivationEventService); activationEventService.onEvent('onStartupFinished', () => { done(); }); // @ts-ignore extensionService.doActivate(); }); }); describe('get extension', () => { it.skip('should return all mock extensions', async () => { const exts = await extInstanceManagementService.getExtensionInstances(); expect(exts).toEqual(MOCK_EXTENSIONS); }); it('should return all mock extensions JSON', async () => { const jsons = await extensionManagementService.getAllExtensionJson(); expect(jsons).toEqual(MOCK_EXTENSIONS.map((e) => e.toJSON())); }); it('should return specified extension props', async () => { const extensionMetadata = await extensionManagementService.getExtensionProps(MOCK_EXTENSIONS[0].path, { readme: './README.md', }); expect(extensionMetadata?.extraMetadata).toEqual({ readme: './README.md' }); }); it('should return extension by extensionId', async () => { const extension = extensionManagementService.getExtensionByExtId('test.sumi-extension'); expect(extension?.extensionId).toBe(MOCK_EXTENSIONS[0].extensionId); }); }); describe('extension status sync', () => { it('should return false when extension is not running', async () => { const extension = await extensionManagementService.getExtensionByPath(MOCK_EXTENSIONS[0].path); expect(extension?.activated).toBe(false); }); }); describe('activate extension', () => { it('should activate mock browser extension without ext process', async () => { await extensionService.activeExtension(MOCK_EXTENSIONS[0]); const layoutService: IMainLayoutService = injector.get(IMainLayoutService); const tabbarService: TabbarService = layoutService.getTabbarService('left'); const containerInfo = tabbarService.getContainer('test.sumi-extension:Leftview'); expect(containerInfo?.options?.titleComponent).toBeDefined(); expect(containerInfo?.options?.titleProps).toBeDefined(); // setTimeout(() => { // }, 1000); }); it('extension should not repeated activation', async () => { const extInstances = await extInstanceManagementService.getExtensionInstances(); expect(extInstances).toHaveLength(1); await extensionManagementService.postChangedExtension(false, MOCK_EXTENSIONS[0].realPath); const postExtInstances = await extInstanceManagementService.getExtensionInstances(); expect(postExtInstances).toHaveLength(1); }); }); describe('extension contributes', () => { it('should register toolbar actions via new toolbar action contribution point', () => { const toolbarRegistry: IToolbarRegistry = injector.get(IToolbarRegistry); (toolbarRegistry as NextToolbarRegistryImpl).init(); const groups = toolbarRegistry.getActionGroups('default'); expect(groups!.length).toBe(1); expect(toolbarRegistry.getToolbarActions({ location: 'default', group: groups![0].id })!.actions!.length).toBe(1); }); it('should register shadow command via command contribution point', () => { const commandRegistry: CommandRegistryImpl = injector.get(CommandRegistry); expect(commandRegistry.getCommand('HelloKaitian')).toBeDefined(); }); it('should use english nls as alias', async () => { const commandRegistry: CommandRegistryImpl = injector.get(CommandRegistry); const command = commandRegistry.getCommand('Test'); expect(command).toBeDefined(); expect(command?.label).toBe('this is label'); expect(command?.alias).toBe('this is alias'); expect(command?.category).toBe('this is category'); expect(command?.aliasCategory).toBe('this is aliasCategory'); }); it('should register menus in editor/title and editor/context position', () => { const newMenuRegistry: MenuRegistryImpl = injector.get(IMenuRegistry); const contextMenu = newMenuRegistry.getMenuItems('editor/context'); expect(contextMenu.length).toBe(1); expect((contextMenu[0] as IMenuItem).command!).toBe('HelloKaitian'); const actionMenu = newMenuRegistry.getMenuItems('editor/title'); expect(actionMenu.length).toBe(1); expect(actionMenu.findIndex((item) => (item as IMenuItem).command === 'HelloKaitian')).toBeGreaterThan(-1); }); it('should register viewContainer in activityBar', () => { const layoutService: LayoutService = injector.get(IMainLayoutService); const handler = layoutService.getTabbarHandler('package-explorer'); expect(handler).toBeDefined(); const holdHandler = layoutService.getTabbarHandler('hold-container'); expect(holdHandler).toBeUndefined(); }); it('should register extension configuration', () => { const preferenceSettingsService: PreferenceSettingsService = injector.get(IPreferenceSettingsService); const preferences = preferenceSettingsService.getSections('extension', PreferenceScope.Default); expect(preferences.length).toBe(1); expect(preferences[0].title).toBe('Mock Extension Config'); }); it('should register browserView', () => { const layoutService: LayoutService = injector.get(IMainLayoutService); const tabbar = layoutService.getTabbarHandler('test.sumi-extension:KaitianViewContribute'); expect(tabbar).toBeDefined(); expect(tabbar?.containerId).toBe('test.sumi-extension:KaitianViewContribute'); }); it('should register browserView', () => { const layoutService: IMainLayoutService = injector.get(IMainLayoutService); const tabbar = layoutService.getTabbarHandler('test.sumi-extension:KaitianViewContribute'); expect(tabbar).toBeDefined(); }); it('should register keybinding for HelloKaitian command', () => { const keyBinding: KeybindingRegistryImpl = injector.get(KeybindingRegistry); const commandKeyBindings = keyBinding.getKeybindingsForCommand('HelloKaitian'); expect(commandKeyBindings.length).toBe(1); expect(typeof commandKeyBindings[0].keybinding).toBe('string'); }); it('should register mock color', async () => { const themeService: WorkbenchThemeService = injector.get(IThemeService); const colorRegister = getColorRegistry(); const theme = await themeService.getCurrentTheme(); const color = colorRegister.resolveDefaultColor('mock.superstatus.error', theme); expect(color).toBeDefined(); expect(color?.toString()).toBe('#ff004f'); }); }); describe('extension host commands', () => { it("should define a command in 'node' host.", async () => { const commandId = 'mock_command'; const disposable = extCommandManagement.registerExtensionCommandEnv(commandId, 'node'); const env = extCommandManagement.getExtensionCommandEnv(commandId); expect(env).toBe('node'); disposable.dispose(); expect(extCommandManagement.getExtensionCommandEnv(commandId)).toBe(undefined); }); }); describe('load browser require interceptor contribution', () => { it('should get ReactDOM interceptor', async () => { // @ts-ignore await extensionService.doActivate(); const requireInterceptorService: IRequireInterceptorService = injector.get(IRequireInterceptorService); const interceptor = requireInterceptorService.getRequireInterceptor('ReactDOM'); const result = interceptor?.load({}); expect(result).toBe(ReactDom); }); }); describe('extension process restart', () => { it('restart ext process when visibility change', async () => { // 开始进行 visibilitychange 事件监听 await extensionService.activate(); /** * 如果页面不可见,那么不会执行插件进程重启操作 */ Object.defineProperty(document, 'visibilityState', { configurable: true, get() { return 'hidden'; }, }); const extProcessRestartHandler = jest.spyOn(extensionService as any, 'extProcessRestartHandler'); extensionService.restartExtProcess(); expect(extProcessRestartHandler).not.toBeCalled(); expect(extensionService['isExtProcessWaitingForRestart']).toBe(true); /** * 页面变为可见后,开始执行插件进程重启操作 */ Object.defineProperty(document, 'visibilityState', { configurable: true, get() { return 'visible'; }, }); // 手动派发一个 visibilitychange 事件 const visibilityChangeEvent = new Event('visibilitychange'); visibilityChangeEvent.initEvent('visibilitychange', false, false); document.dispatchEvent(visibilityChangeEvent); expect(extProcessRestartHandler).toBeCalled(); }); }); });
the_stack
import { ComponentOptions } from '../Base/ComponentOptions'; import { LocalStorageUtils } from '../../utils/LocalStorageUtils'; import { ResultListEvents, IDisplayedNewResultEventArgs } from '../../events/ResultListEvents'; import { DebugEvents } from '../../events/DebugEvents'; import { IQueryResults } from '../../rest/QueryResults'; import { IQueryResult } from '../../rest/QueryResult'; import { $$, Dom } from '../../utils/Dom'; import { StringUtils } from '../../utils/StringUtils'; import { SearchEndpoint } from '../../rest/SearchEndpoint'; import { RootComponent } from '../Base/RootComponent'; import { BaseComponent } from '../Base/BaseComponent'; import { ModalBox as ModalBoxModule } from '../../ExternalModulesShim'; import Globalize = require('globalize'); import * as _ from 'underscore'; import 'styling/_Debug'; import { l } from '../../strings/Strings'; import { IComponentBindings } from '../Base/ComponentBindings'; import { DebugHeader } from './DebugHeader'; import { QueryEvents, IQuerySuccessEventArgs } from '../../events/QueryEvents'; import { DebugForResult } from './DebugForResult'; import { exportGlobally } from '../../GlobalExports'; import { Template } from '../Templates/Template'; export interface IDebugOptions { enableDebug?: boolean; } export class Debug extends RootComponent { static ID = 'Debug'; static doExport = () => { exportGlobally({ Debug: Debug }); }; static options: IDebugOptions = { enableDebug: ComponentOptions.buildBooleanOption({ defaultValue: false }) }; static customOrder = ['error', 'queryDuration', 'result', 'fields', 'rankingInfo', 'template', 'query', 'results', 'state']; static durationKeys = ['indexDuration', 'proxyDuration', 'clientDuration', 'duration']; static maxDepth = 10; public localStorageDebug: LocalStorageUtils<string[]>; public collapsedSections: string[]; private modalBox: Coveo.ModalBox.ModalBox; private opened = false; private stackDebug: any; private debugHeader: DebugHeader; public showDebugPanel: () => void; constructor( public element: HTMLElement, public bindings: IComponentBindings, public options?: IDebugOptions, public ModalBox = ModalBoxModule ) { super(element, Debug.ID); this.options = ComponentOptions.initComponentOptions(element, Debug, options); // This gets debounced so the following logic works correctly : // When you alt dbl click on a component, it's possible to add/merge multiple debug info source together // They will be merged together in this.addInfoToDebugPanel // Then, openModalBox, even if it's called from multiple different caller will be opened only once all the info has been merged together correctly this.showDebugPanel = _.debounce(() => this.openModalBox(), 100); $$(this.element).on(ResultListEvents.newResultDisplayed, (e, args: IDisplayedNewResultEventArgs) => this.handleNewResultDisplayed(args) ); $$(this.element).on(DebugEvents.showDebugPanel, (e, args) => this.handleShowDebugPanel(args)); $$(this.element).on(QueryEvents.querySuccess, (e, args: IQuerySuccessEventArgs) => this.handleQuerySuccess(args)); $$(this.element).on(QueryEvents.newQuery, () => this.handleNewQuery()); this.localStorageDebug = new LocalStorageUtils<string[]>('DebugPanel'); this.collapsedSections = this.localStorageDebug.load() || []; } public debugInfo() { return null; } public addInfoToDebugPanel(info: any) { if (this.stackDebug == null) { this.stackDebug = {}; } this.stackDebug = { ...this.stackDebug, ...info }; } private handleNewResultDisplayed(args: IDisplayedNewResultEventArgs) { $$(args.item).on('dblclick', (e: MouseEvent) => { this.handleResultDoubleClick(e, args); }); } private handleResultDoubleClick(e: MouseEvent, args: IDisplayedNewResultEventArgs) { if (e.altKey) { const index = args.result.index; const template = args.item['template']; const findResult = (results?: IQueryResults) => results != null ? _.find(results.results, (result: IQueryResult) => result.index == index) : args.result; const debugInfo = { ...new DebugForResult(this.bindings).generateDebugInfoForResult(args.result), findResult, template: this.templateToJson(template) }; this.addInfoToDebugPanel(debugInfo); this.showDebugPanel(); } } private handleQuerySuccess(args: IQuerySuccessEventArgs) { if (this.opened) { if (this.stackDebug && this.stackDebug.findResult) { this.addInfoToDebugPanel(new DebugForResult(this.bindings).generateDebugInfoForResult(this.stackDebug.findResult(args.results))); } this.redrawDebugPanel(); this.hideAnimationDuringQuery(); } } private handleNewQuery() { if (this.opened) { this.showAnimationDuringQuery(); } } private handleShowDebugPanel(args: any) { this.addInfoToDebugPanel(args); this.showDebugPanel(); } private buildStackPanel(): { body: HTMLElement; json: any } { const body = $$('div', { className: 'coveo-debug' }); const keys = _.chain(this.stackDebug) .omit('findResult') // findResult is a duplicate of the simpler "result" key used to retrieve the results only .keys() .value(); // TODO Can't chain this properly due to a bug in underscore js definition file. // Yep, A PR is opened to DefinitelyTyped. let keysPaired = _.pairs(keys); keysPaired = keysPaired.sort((a: any[], b: any[]) => { const indexA = _.indexOf(Debug.customOrder, a[1]); const indexB = _.indexOf(Debug.customOrder, b[1]); if (indexA != -1 && indexB != -1) { return indexA - indexB; } if (indexA != -1) { return -1; } if (indexB != -1) { return 1; } return a[0] - b[0]; }); const json = {}; _.forEach(keysPaired, (key: string[]) => { const section = this.buildSection(key[1]); const build = this.buildStackPanelSection(this.stackDebug[key[1]], this.stackDebug['result']); section.container.append(build.section); if (build.json != null) { json[key[1]] = build.json; } body.append(section.dom.el); }); return { body: body.el, json: json }; } private getModalBody() { if (this.modalBox && this.modalBox.content) { return $$(this.modalBox.content).find('.coveo-modal-body'); } return null; } private redrawDebugPanel() { const build = this.buildStackPanel(); const body = this.getModalBody(); if (body) { $$(body).empty(); $$(body).append(build.body); } this.updateSearchFunctionnality(build); } private openModalBox() { const build = this.buildStackPanel(); this.opened = true; this.modalBox = this.ModalBox.open(build.body, { title: l('Debug'), className: 'coveo-debug', titleClose: true, overlayClose: true, validation: () => { this.onCloseModalBox(); return true; }, sizeMod: 'big', body: this.bindings.root }); const title = $$(this.modalBox.wrapper).find('.coveo-modal-header'); if (title) { if (!this.debugHeader) { this.debugHeader = new DebugHeader(this, title, (value: string) => this.search(value, build.body), this.stackDebug); } else { this.debugHeader.moveTo(title); this.updateSearchFunctionnality(build); } } else { this.logger.warn('No title found in modal box.'); } } private updateSearchFunctionnality(build: { body: HTMLElement; json: any }) { if (this.debugHeader) { this.debugHeader.setNewInfoToDebug(this.stackDebug); this.debugHeader.setSearch((value: string) => this.search(value, build.body)); } } private onCloseModalBox() { this.stackDebug = null; this.opened = false; } private buildStackPanelSection(value: any, results: IQueryResults): { section: HTMLElement; json?: any } { if (value instanceof HTMLElement) { return { section: value }; } else if (_.isFunction(value)) { return this.buildStackPanelSection(value(results), results); } const json = this.toJson(value); return { section: this.buildProperty(json), json: json }; } private findInProperty(element: HTMLElement, value: string): boolean { const wrappedElement = $$(element); let match = element['label'].indexOf(value) != -1; if (match) { this.highlightSearch(element['labelDom'], value); } else { this.removeHighlightSearch(element['labelDom']); } if (wrappedElement.hasClass('coveo-property-object')) { wrappedElement.toggleClass('coveo-search-match', match); const children = element['buildKeys'](); let submatch = false; _.each(children, (child: HTMLElement) => { submatch = this.findInProperty(child, value) || submatch; }); wrappedElement.toggleClass('coveo-search-submatch', submatch); return match || submatch; } else { if (element['values'].indexOf(value) != -1) { this.highlightSearch(element['valueDom'], value); match = true; } else { this.removeHighlightSearch(element['valueDom']); } wrappedElement.toggleClass('coveo-search-match', match); } return match; } private buildSection(id: string) { const dom = $$('div', { className: `coveo-section coveo-${id}-section` }); const header = $$('div', { className: 'coveo-section-header' }); $$(header).text(id); dom.append(header.el); const container = $$('div', { className: 'coveo-section-container' }); dom.append(container.el); if (_.contains(this.collapsedSections, id)) { $$(dom).addClass('coveo-debug-collapsed'); } header.on('click', () => { $$(dom).toggleClass('coveo-debug-collapsed'); if (_.contains(this.collapsedSections, id)) { this.collapsedSections = _.without(this.collapsedSections, id); } else { this.collapsedSections.push(id); } this.localStorageDebug.save(this.collapsedSections); }); return { dom: dom, header: header, container: container }; } private buildProperty(value: any, label?: string): HTMLElement { if (value instanceof Promise) { return this.buildPromise(value, label); } else if ((_.isArray(value) || _.isObject(value)) && !_.isString(value)) { return this.buildObjectProperty(value, label); } else { return this.buildBasicProperty(value, label); } } private buildPromise(promise: Promise<any>, label?: string): HTMLElement { const dom = $$('div', { className: 'coveo-property coveo-property-promise' }); promise.then(value => { const resolvedDom = this.buildProperty(value, label); dom.replaceWith(resolvedDom); }); return dom.el; } private buildObjectProperty(object: any, label?: string): HTMLElement { const dom = $$('div', { className: 'coveo-property coveo-property-object' }); const valueContainer = $$('div', { className: 'coveo-property-value' }); const keys = _.keys(object); if (!_.isArray(object)) { keys.sort(); } let children: HTMLElement[]; const buildKeys = () => { if (children == null) { children = []; _.each(keys, (key: string) => { const property = this.buildProperty(object[key], key); if (property != null) { children.push(property); valueContainer.append(property); } }); } return children; }; dom.el['buildKeys'] = buildKeys; if (label != null) { const labelDom = $$('div', { className: 'coveo-property-label' }); labelDom.text(label); dom.el['labelDom'] = labelDom.el; dom.append(labelDom.el); if (keys.length != 0) { dom.addClass('coveo-collapsible'); labelDom.on('click', () => { buildKeys(); let className = dom.el.className.split(/\s+/); if (_.contains(className, 'coveo-expanded')) { className = _.without(className, 'coveo-expanded'); } else { className.push('coveo-expanded'); } dom.el.className = className.join(' '); }); } } else { buildKeys(); } if (keys.length == 0) { const className = _.without(dom.el.className.split(/\s+/), 'coveo-property-object'); className.push('coveo-property-basic'); dom.el.className = className.join(' '); if (_.isArray(object)) { valueContainer.setHtml('[]'); } else { valueContainer.setHtml('{}'); } dom.el['values'] = ''; } dom.el['label'] = label != null ? label.toLowerCase() : ''; dom.append(valueContainer.el); return dom.el; } private buildBasicProperty(value: string, label?: string): HTMLElement { const dom = $$('div', { className: 'coveo-property coveo-property-basic' }); if (label != null) { const labelDom = $$('div', { className: 'coveo-property-label' }); labelDom.text(label); dom.append(labelDom.el); dom.el['labelDom'] = labelDom.el; } const stringValue = value != null ? value.toString() : String(value); if (value != null && value['ref'] != null) { value = value['ref']; } const valueDom = $$('div'); valueDom.text(stringValue); valueDom.on('dblclick', () => { this.selectElementText(valueDom.el); }); dom.append(valueDom.el); dom.el['valueDom'] = valueDom; const className: string[] = ['coveo-property-value']; if (_.isString(value)) { className.push('coveo-property-value-string'); } if (_.isNull(value) || _.isUndefined(value)) { className.push('coveo-property-value-null'); } if (_.isNumber(value)) { className.push('coveo-property-value-number'); } if (_.isBoolean(value)) { className.push('coveo-property-value-boolean'); } if (_.isDate(value)) { className.push('coveo-property-value-date'); } if (_.isObject(value)) { className.push('coveo-property-value-object'); } if (_.isArray(value)) { className.push('coveo-property-value-array'); } valueDom.el.className = className.join(' '); dom.el['label'] = label != null ? label.toLowerCase() : ''; dom.el['values'] = stringValue.toLowerCase(); return dom.el; } private toJson(value: any, depth = 0, done: any[] = []) { if (value instanceof BaseComponent || value instanceof SearchEndpoint) { return this.componentToJson(value, depth); } if (value instanceof HTMLElement) { return this.htmlToJson(value); } if (value instanceof Template) { return this.templateToJson(value); } if (value instanceof Promise) { return value.then(value => { return this.toJson(value, depth, done); }); } if (value == window) { return this.toJsonRef(value); } if (_.isArray(value) || _.isObject(value)) { if (_.contains(done, value)) { return this.toJsonRef(value, '< RECURSIVE >'); } else if (depth >= Debug.maxDepth) { return this.toJsonRef(value); } else if (_.isArray(value)) { return _.map(value, (subValue, key) => this.toJson(subValue, depth + 1, done.concat([value]))); } else if (_.isDate(value)) { return this.toJsonRef(value, Globalize.format(value, 'F')); } else { const result = {}; _.each(value, (subValue, key) => { result[key] = this.toJson(subValue, depth + 1, done.concat([value])); }); result['ref']; return result; } } return value; } private toJsonRef(value: any, stringValue?: String): String { stringValue = new String(stringValue || value); stringValue['ref'] = value; return stringValue; } private componentToJson(value: BaseComponent | SearchEndpoint, depth = 0): any { const options = _.keys(value['options']); if (options.length > 0) { return this.toJson(value['options'], depth); } else { return this.toJsonRef(value['options'], new String('No options')); } } private htmlToJson(value: HTMLElement): any { if (value == null) { return undefined; } return { tagName: value.tagName, id: value.id, classList: value.className.split(/\s+/) }; } private templateToJson(template: Template) { if (template == null) { return null; } const element: HTMLElement = template['element']; const templateObject: any = { type: template.getType() }; if (element != null) { templateObject.id = element.id; templateObject.condition = element.attributes['data-condition']; templateObject.content = element.innerText; } return templateObject; } private selectElementText(el: HTMLElement) { if (window.getSelection && document.createRange) { const selection = window.getSelection(); const range = document.createRange(); range.selectNodeContents(el); selection.removeAllRanges(); selection.addRange(range); } else if ('createTextRange' in document.body) { const textRange = document.body['createTextRange'](); textRange.moveToElementText(el); textRange.select(); } } private search(value: string, body: HTMLElement) { if (_.isEmpty(value)) { $$(body) .findAll('.coveo-search-match, .coveo-search-submatch') .forEach(el => { $$(el).removeClass('coveo-search-match, coveo-search-submatch'); }); $$(body).removeClass('coveo-searching'); } else { $$(body).addClass('coveo-searching-loading'); setTimeout(() => { const rootProperties = $$(body).findAll('.coveo-section .coveo-section-container > .coveo-property'); _.each(rootProperties, (element: HTMLElement) => { this.findInProperty(element, value); }); $$(body).addClass('coveo-searching'); $$(body).removeClass('coveo-searching-loading'); }); } } private highlightSearch(elementToSearch: HTMLElement | Dom, search: string) { let asHTMLElement: HTMLElement; if (elementToSearch instanceof HTMLElement) { asHTMLElement = elementToSearch; } else if (elementToSearch instanceof Dom) { asHTMLElement = elementToSearch.el; } if (asHTMLElement != null && asHTMLElement.innerText != null) { const match = asHTMLElement.innerText.split(new RegExp('(?=' + StringUtils.regexEncode(search) + ')', 'gi')); asHTMLElement.innerHTML = ''; match.forEach(value => { const regex = new RegExp('(' + StringUtils.regexEncode(search) + ')', 'i'); const group = value.match(regex); let span; if (group != null) { span = $$('span', { className: 'coveo-debug-highlight' }); span.text(group[1]); asHTMLElement.appendChild(span.el); span = $$('span'); span.text(value.substr(group[1].length)); asHTMLElement.appendChild(span.el); } else { span = $$('span'); span.text(value); asHTMLElement.appendChild(span.el); } }); } } private removeHighlightSearch(element: HTMLElement) { if (element != null) { element.innerHTML = element.innerText; } } private showAnimationDuringQuery() { $$(this.modalBox.content).addClass('coveo-debug-loading'); } private hideAnimationDuringQuery() { $$(this.modalBox.content).removeClass('coveo-debug-loading'); } }
the_stack
import * as assert from 'assert'; import { TerminalConfigHelper } from 'vs/workbench/contrib/terminal/browser/terminalConfigHelper'; import { EDITOR_FONT_DEFAULTS } from 'vs/editor/common/config/editorOptions'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { LinuxDistro } from 'vs/workbench/contrib/terminal/browser/terminal'; class TestTerminalConfigHelper extends TerminalConfigHelper { set linuxDistro(distro: LinuxDistro) { this._linuxDistro = distro; } } suite('Workbench - TerminalConfigHelper', () => { let fixture: HTMLElement; setup(() => { fixture = document.body; }); test('TerminalConfigHelper - getFont fontFamily', async () => { const configurationService = new TestConfigurationService(); await configurationService.setUserConfiguration('editor', { fontFamily: 'foo' }); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: 'bar' } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontFamily, 'bar', 'terminal.integrated.fontFamily should be selected over editor.fontFamily'); }); test('TerminalConfigHelper - getFont fontFamily (Linux Fedora)', async () => { const configurationService = new TestConfigurationService(); await configurationService.setUserConfiguration('editor', { fontFamily: 'foo' }); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: null } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.linuxDistro = LinuxDistro.Fedora; configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontFamily, '\'DejaVu Sans Mono\', monospace', 'Fedora should have its font overridden when terminal.integrated.fontFamily not set'); }); test('TerminalConfigHelper - getFont fontFamily (Linux Ubuntu)', async () => { const configurationService = new TestConfigurationService(); await configurationService.setUserConfiguration('editor', { fontFamily: 'foo' }); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: null } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.linuxDistro = LinuxDistro.Ubuntu; configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontFamily, '\'Ubuntu Mono\', monospace', 'Ubuntu should have its font overridden when terminal.integrated.fontFamily not set'); }); test('TerminalConfigHelper - getFont fontFamily (Linux Unknown)', async () => { const configurationService = new TestConfigurationService(); await configurationService.setUserConfiguration('editor', { fontFamily: 'foo' }); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: null } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontFamily, 'foo', 'editor.fontFamily should be the fallback when terminal.integrated.fontFamily not set'); }); test('TerminalConfigHelper - getFont fontSize', async () => { const configurationService = new TestConfigurationService(); await configurationService.setUserConfiguration('editor', { fontFamily: 'foo', fontSize: 9 }); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: 'bar', fontSize: 10 } }); let configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontSize, 10, 'terminal.integrated.fontSize should be selected over editor.fontSize'); await configurationService.setUserConfiguration('editor', { fontFamily: 'foo' }); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: null, fontSize: 0 } }); configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.linuxDistro = LinuxDistro.Ubuntu; configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontSize, 8, 'The minimum terminal font size (with adjustment) should be used when terminal.integrated.fontSize less than it'); configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontSize, 6, 'The minimum terminal font size should be used when terminal.integrated.fontSize less than it'); await configurationService.setUserConfiguration('editor', { fontFamily: 'foo' }); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: 0, fontSize: 1500 } }); configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontSize, 100, 'The maximum terminal font size should be used when terminal.integrated.fontSize more than it'); await configurationService.setUserConfiguration('editor', { fontFamily: 'foo' }); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: 0, fontSize: null } }); configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.linuxDistro = LinuxDistro.Ubuntu; configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontSize, EDITOR_FONT_DEFAULTS.fontSize + 2, 'The default editor font size (with adjustment) should be used when terminal.integrated.fontSize is not set'); configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().fontSize, EDITOR_FONT_DEFAULTS.fontSize, 'The default editor font size should be used when terminal.integrated.fontSize is not set'); }); test('TerminalConfigHelper - getFont lineHeight', async () => { const configurationService = new TestConfigurationService(); await configurationService.setUserConfiguration('editor', { fontFamily: 'foo', lineHeight: 1 }); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: 0, lineHeight: 2 } }); let configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().lineHeight, 2, 'terminal.integrated.lineHeight should be selected over editor.lineHeight'); await configurationService.setUserConfiguration('editor', { fontFamily: 'foo', lineHeight: 1 }); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: 0, lineHeight: 0 } }); configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.getFont().lineHeight, 1, 'editor.lineHeight should be 1 when terminal.integrated.lineHeight not set'); }); test('TerminalConfigHelper - isMonospace monospace', async function () { const configurationService = new TestConfigurationService(); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: 'monospace' } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.configFontIsMonospace(), true, 'monospace is monospaced'); }); test('TerminalConfigHelper - isMonospace sans-serif', async () => { const configurationService = new TestConfigurationService(); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: 'sans-serif' } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.configFontIsMonospace(), false, 'sans-serif is not monospaced'); }); test('TerminalConfigHelper - isMonospace serif', async () => { const configurationService = new TestConfigurationService(); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: 'serif' } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.configFontIsMonospace(), false, 'serif is not monospaced'); }); test('TerminalConfigHelper - isMonospace monospace falls back to editor.fontFamily', async () => { const configurationService = new TestConfigurationService(); await configurationService.setUserConfiguration('editor', { fontFamily: 'monospace' }); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: null } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.configFontIsMonospace(), true, 'monospace is monospaced'); }); test('TerminalConfigHelper - isMonospace sans-serif falls back to editor.fontFamily', async () => { const configurationService = new TestConfigurationService(); await configurationService.setUserConfiguration('editor', { fontFamily: 'sans-serif' }); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: null } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.configFontIsMonospace(), false, 'sans-serif is not monospaced'); }); test('TerminalConfigHelper - isMonospace serif falls back to editor.fontFamily', async () => { const configurationService = new TestConfigurationService(); await configurationService.setUserConfiguration('editor', { fontFamily: 'serif' }); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: null } }); const configHelper = new TestTerminalConfigHelper(configurationService, null!, null!, null!, null!, null!); configHelper.panelContainer = fixture; assert.strictEqual(configHelper.configFontIsMonospace(), false, 'serif is not monospaced'); }); });
the_stack
import { ConfiguredDocumentClass, ConfiguredObjectClassForName } from '../../../../../../types/helperTypes'; import { PasteOptions } from '../placeablesLayer'; declare global { /** * The Walls canvas layer which provides a container for Wall objects within the rendered Scene. * @see {@link WallDocument} * @see {@link Wall} */ class WallsLayer extends PlaceablesLayer<'Wall', WallsLayer.LayerOptions> { constructor(); /** * A graphics layer used to display chained Wall selection * @defaultValue `null` */ chain: PIXI.Graphics | null; /** * An array of all the unique perception-blocking endpoints which are present in the layer * We keep this array cached for faster sight polygon computations * @defaultValue `[]` */ endpoints: PointArray[]; /** * Track whether we are currently within a chained placement workflow * @defaultValue `false` */ protected _chain: boolean; /** * Track whether the layer is currently toggled to snap at exact grid precision * @defaultValue `false` */ protected _forceSnap: boolean; /** * Track the most recently created or updated wall data for use with the clone tool * @defaultValue `null` * @remarks This is intentional `public` because it is accessed from Wall */ _cloneType: ReturnType<foundry.documents.BaseWall['toJSON']> | null; /** * Reference the last interacted wall endpoint for the purposes of chaining * @defaultValue * ``` * { * id: null, * point: null, * } * ``` */ protected last: { id: string | null; point: PointArray | null; }; /** * @remarks This is not overridden in foundry but reflects the real behavior. */ static get instance(): Canvas['walls']; /** * @override * @defaultValue * ``` * mergeObject(super.layerOptions, { * name: "walls" * controllableObjects: true, * objectClass: Wall, * quadtree: true, * sheetClass: WallConfig, * sortActiveTop: true, * zIndex: 40 * }) * ``` */ static get layerOptions(): WallsLayer.LayerOptions; /** @override */ static documentName: 'Wall'; /** * An Array of Wall instances in the current Scene which act as Doors. */ get doors(): InstanceType<ConfiguredObjectClassForName<'Wall'>>[]; /** * Gate the precision of wall snapping to become less precise for small scale maps. * @remarks Returns `1 | 4 | 8 | 16` */ get gridPrecision(): number; /** * @override */ draw(): Promise<this>; /** @override */ deactivate(): this; /** * Perform initialization steps for the WallsLayer whenever the composition of walls in the Scene is changed. * Cache unique wall endpoints and identify interior walls using overhead roof tiles. */ initialize(): void; /** * Identify walls which are treated as "interior" because they are contained fully within a roof tile. */ identifyInteriorWalls(): void; /** * Given a point and the coordinates of a wall, determine which endpoint is closer to the point * @param point - The origin point of the new Wall placement * @param wall - The existing Wall object being chained to * @returns The [x,y] coordinates of the starting endpoint */ static getClosestEndpoint(point: Point, wall: InstanceType<ConfiguredObjectClassForName<'Wall'>>): PointArray; /** * Given an array of Wall instances, identify the unique endpoints across all walls. * @param walls - An array of Wall instances * @param options - Additional options which modify the set of endpoints identified * (defaultValue: `{}`) * @returns An array of endpoints */ static getUniqueEndpoints( walls: | InstanceType<ConfiguredObjectClassForName<'Wall'>>[] | Set<InstanceType<ConfiguredObjectClassForName<'Wall'>>>, options?: EndpointOptions ): PointArray[]; /** * Test whether movement along a given Ray collides with a Wall. * @param ray - The attempted movement * @param options - Options which customize how collision is tested * @returns Does a collision occur? */ checkCollision(ray: Ray, options: CollisionOptions & { mode: 'all' }): boolean | RayIntersection[]; checkCollision(ray: Ray, options: CollisionOptions & { mode: 'closest' }): boolean | RayIntersection | null; checkCollision(ray: Ray, options: CollisionOptions & { mode: 'any' }): boolean; checkCollision(ray: Ray, options: Omit<CollisionOptions, 'mode'>): boolean; checkCollision(ray: Ray, options: CollisionOptions): boolean | RayIntersection | null; checkCollision(ray: Ray, options?: CollisionOptions): boolean; /** * Highlight the endpoints of Wall segments which are currently group-controlled on the Walls layer */ highlightControlledSegments(): void; /** @override */ releaseAll(options?: PlaceableObject.ReleaseOptions): number; /** * @override * @param options - (unused) */ pasteObjects( position: Point, options?: PasteOptions ): Promise<InstanceType<ConfiguredDocumentClass<typeof foundry.documents.BaseWall>>[]>; /** * Pan the canvas view when the cursor position gets close to the edge of the frame * @param event - The originating mouse movement event * @param x - The x-coordinate * @param y - The y-coordinate */ protected _panCanvasEdge(event: MouseEvent, x: number, y: number): void | ReturnType<Canvas['animatePan']>; /** * Get the endpoint coordinates for a wall placement, snapping to grid at a specified precision * Require snap-to-grid until a redesign of the wall chaining system can occur. * @param point - The initial candidate point * @param snap - Whether to snap to grid * (default: `true`) * @returns The endpoint coordinates [x,y] */ protected _getWallEndpointCoordinates(point: Point, { snap }?: { snap?: boolean }): PointArray; /** * The Scene Controls tools provide several different types of prototypical Walls to choose from * This method helps to translate each tool into a default wall data configuration for that type * @param tool - The active canvas tool */ protected _getWallDataFromActiveTool(tool: string): | { move: foundry.CONST.WALL_MOVEMENT_TYPES; sense: foundry.CONST.WALL_SENSE_TYPES; door?: foundry.CONST.WALL_DOOR_TYPES; } | this['_cloneType']; /** @override */ protected _onDragLeftStart(event: PIXI.InteractionEvent): void; /** @override */ protected _onDragLeftMove(event: PIXI.InteractionEvent): void; /** @override */ protected _onDragLeftDrop(event: PIXI.InteractionEvent): void; /** @override */ protected _onDragLeftCancel(event: PointerEvent): void; /** @override */ protected _onClickRight(event: PIXI.InteractionEvent): void; /** * Compute source polygons of a requested type for a given origin position and maximum radius. * This method returns two polygons, one which is unrestricted by the provided radius, and one that is constrained * by the maximum radius. * * @param origin - An point with coordinates x and y representing the origin of the test * @param radius - A distance in canvas pixels which reflects the visible range * @param options - Additional options which modify the sight computation * (default: `{}`) * @returns The computed rays and polygons */ computePolygon( origin: Point, radius: number, options?: ComputePolygonOptions ): { rays: Ray[]; los: PIXI.Polygon; fov: PIXI.Polygon }; /** * Get the set of wall collisions for a given Ray * @param ray - The Ray being tested * @param options - Options which customize how collision is tested * (default: `{}`) * @returns An array of collisions, if mode is "all" * The closest collision, if mode is "closest" * Whether any collision occurred if mode is "any" */ getRayCollisions(ray: Ray, options: RayCollisionsOptions & { mode: 'all' }): RayIntersection[]; getRayCollisions(ray: Ray, options: RayCollisionsOptions & { mode: 'closest' }): RayIntersection | null; getRayCollisions(ray: Ray, options: RayCollisionsOptions & { mode: 'any' }): boolean; getRayCollisions(ray: Ray, options?: Partial<Omit<RayCollisionsOptions, 'mode'>>): RayIntersection[]; getRayCollisions(ray: Ray, options?: RayCollisionsOptions): RayIntersection[] | RayIntersection | boolean | null; /** * A helper method responsible for casting rays at wall endpoints. * Rays are restricted by limiting angles. * * @param x - The origin x-coordinate * @param y - The origin y-coordinate * @param distance - The ray distance * @param density - The desired radial density * (default: `4`) * @param endpoints - An array of endpoints to target * @param limitAngle - Whether the rays should be cast subject to a limited angle of emission * (default: `false`) * @param aMin - The minimum bounding angle * @param aMax - The maximum bounding angle * * @returns An array of Ray objects */ static castRays( x: number, y: number, distance: number, { density, endpoints, limitAngle, aMin, aMax }?: { density?: number; endpoints?: PointArray[]; limitAngle?: boolean; aMin?: number; aMax?: number } ): Ray[]; /** * Test a single Ray against a single Wall * @param ray - The Ray being tested * @param wall - The Wall against which to test * @returns A RayIntersection if a collision occurred, or null */ static testWall(ray: Ray, wall: InstanceType<ConfiguredObjectClassForName<'Wall'>>): RayIntersection | null; /** * Identify the closest collision point from an array of collisions * @param collisions - An array of intersection points * @returns The closest blocking intersection or null if no collision occurred */ static getClosestCollision(collisions: RayIntersection[]): RayIntersection | null; /** * Normalize an angle to ensure it is baselined to be the smallest angle that is greater than a minimum. * @param aMin - The lower-bound minimum angle * @param angle - The angle to adjust * @returns The adjusted angle which is greater than or equal to aMin. */ protected static _normalizeAngle(aMin: number, angle: number): number; /** * Map source types to wall collision types * @param type - The source polygon type * @returns The wall collision attribute */ protected static _mapCollisionType(type: 'movement'): 'move'; protected static _mapCollisionType(type: 'light'): 'sense'; protected static _mapCollisionType(type: 'sight'): 'sense'; protected static _mapCollisionType(type: 'sound'): 'sound'; /** * @deprecated since 0.8.0 */ get blockVision(): InstanceType<ConfiguredObjectClassForName<'Wall'>>[]; /** * @deprecated since 0.8.0 */ get blockMovement(): InstanceType<ConfiguredObjectClassForName<'Wall'>>[]; } namespace WallsLayer { interface LayerOptions extends PlaceablesLayer.LayerOptions<'Wall'> { name: 'walls'; controllableObjects: true; objectClass: typeof Wall; quadtree: true; sheetClass: ConstructorOf<FormApplication>; sortActiveTop: boolean; zIndex: number; } } } interface EndpointOptions { /** * An optional bounding rectangle within which the endpoint must lie. */ bounds?: NormalizedRectangle; /** * The type of polygon being computed: "movement", "sight", or "sound" * @defaultValue `'movement'` */ type?: 'movement' | 'sight' | 'sound'; } interface CollisionOptions { /** * Which collision type to check: movement, sight, sound * @defaultValue `'movement'` */ type?: 'movement' | 'sight' | 'sound'; /** * Which type of collisions are returned: any, closest, all * @defaultValue `'any'` */ mode?: 'any' | 'closest' | 'all'; } interface ComputePolygonOptions { /** * The type of polygon being computed: "movement", "sight", or "sound" * @defaultValue `'sight'` */ type?: 'movement' | 'sight' | 'sound'; /** * An optional limited angle of emission with which to restrict polygons * @defaultValue `360` */ angle?: number; /** * The desired radial density of emission for rays, in degrees * @defaultValue `6` */ density?: number; /** * The current angle of rotation, used when the angle is limited * @defaultValue `0` */ rotation?: number; /** * Compute sight that is fully unrestricted by walls * @defaultValue `false` */ unrestricted?: boolean; } interface RayCollisionsOptions { /** * Which collision type to check: movement, sight, sound * @defaultValue `'movement'` */ type?: 'movement' | 'sight' | 'sound'; /** * Which type of collisions are returned: any, closest, all * @defaultValue `'all'` */ mode?: `any` | `closest` | `all`; /** * Internal performance tracking */ _performance?: { tests: number }; }
the_stack
import { isArray, map, mapValues, reverse } from "lodash-es"; import axios from "axios"; import { Translator } from "@/warframe/translate"; import { i18n } from "../i18n"; export interface WarframeStat { timestamp: string; news: News[]; events: Event[]; alerts: Alert[]; sortie: Sortie; steelPath: SteelPath; syndicateMissions: SyndicateMission[]; fissures: Fissure[]; globalUpgrades: GlobalUpgrade[]; flashSales: FlashSale[]; invasions: Invasion[]; darkSectors: DarkSector[]; voidTrader: VoidTrader; dailyDeals: DailyDeal[]; simaris: Simaris; conclaveChallenges: ConclaveChallenge[]; persistentEnemies: any[]; earthCycle: EarthCycle; cetusCycle: CetusCycle; constructionProgress: ConstructionProgress; vallisCycle: VallisCycle; nightwave: Nightwave; sentientOutposts: SentientOutpost; kuva: Kuva[]; arbitration: Arbitration; twitter: Twitter[]; } export interface SentientOutpost { mission: Mission; activation: string; expiry: string; active: boolean; } export interface Kuva { activation: string; expiry: string; solnode: string; node: string; name: string; tile: string; planet: string; enemy: string; type: string; node_type: string; archwing: boolean; sharkwing: boolean; } export interface Arbitration { activation: string; expiry: string; solnode: string; node: string; name: string; tile: string; planet: string; enemy: string; type: string; node_type: string; archwing: boolean; sharkwing: boolean; } export interface Nightwave { id: string; activation: string; startString: string; expiry: string; active: boolean; season: number; tag: string; phase: number; params: Param; possibleChallenges: ActiveChallenge[]; activeChallenges: ActiveChallenge[]; rewardTypes: string[]; } export interface ActiveChallenge { id: string; activation: string; startString: string; expiry: string; active: boolean; isDaily: boolean; isElite: boolean; desc: string; title: string; reputation: number; // extend type: string; } export interface Param { wgsc: number; wsr: number; } export interface VallisCycle { id: string; expiry: string; isWarm: boolean; timeLeft: string; shortString: string; } export interface GlobalUpgrade { start: string; end: string; upgrade: string; operation: string; operationSymbol: string; upgradeOperationValue: number; expired: boolean; eta: string; desc: string; } export interface Twitter { id: string; uniqueId: string; tweets: Tweet[]; } export interface Tweet { created_at: string; id: number; id_str: string; full_text: string; truncated: boolean; display_text_range: number[]; entities: any; extended_entities?: any; source: string; in_reply_to_status_id?: number; in_reply_to_status_id_str?: string; in_reply_to_user_id?: number; in_reply_to_user_id_str?: string; in_reply_to_screen_name?: string; user: TwitterUser; geo?: any; coordinates?: any; place?: any; contributors?: any; is_quote_status: boolean; retweet_count: number; favorite_count: number; favorited: boolean; retweeted: boolean; possibly_sensitive?: boolean; lang: string; retweeted_status?: any; } interface TwitterUser { id: number; id_str: string; name: string; screen_name: string; location: string; description: string; url?: string; entities: any; protected: boolean; followers_count: number; friends_count: number; listed_count: number; created_at: string; favourites_count: number; utc_offset?: any; time_zone?: any; geo_enabled: boolean; verified: boolean; statuses_count: number; lang: string; contributors_enabled: boolean; is_translator: boolean; is_translation_enabled: boolean; profile_background_color: string; profile_background_image_url: string; profile_background_image_url_https: string; profile_background_tile: boolean; profile_image_url: string; profile_image_url_https: string; profile_banner_url: string; profile_link_color: string; profile_sidebar_border_color: string; profile_sidebar_fill_color: string; profile_text_color: string; profile_use_background_image: boolean; has_extended_profile: boolean; default_profile: boolean; default_profile_image: boolean; following?: any; follow_request_sent?: any; notifications?: any; translator_type: string; } export interface ConstructionProgress { id: string; fomorianProgress: string; razorbackProgress: string; unknownProgress: string; } export interface CetusCycle { id: string; expiry: string; isDay: boolean; timeLeft: string; isCetus: boolean; shortString: string; } export interface EarthCycle { id: string; expiry: string; isDay: boolean; timeLeft: string; } export interface ConclaveChallenge { id: string; description: string; expiry: string; amount: number; mode: string; category: string; eta: string; expired: boolean; daily: boolean; rootChallenge: boolean; endString: string; asString: string; } export interface Simaris { target: string; isTargetActive: boolean; asString: string; } export interface DailyDeal { item: string; expiry: string; originalPrice: number; salePrice: number; total: number; sold: number; id: string; eta: string; discount: number; } export interface VoidTrader { id: string; activation: string; startString: string; expiry: string; active: boolean; character: string; location: string; inventory: Inventory[]; psId: string; endString: string; } export interface Inventory { item: string; ducats: number; credits: number; } export interface DarkSector { id: string; isAlliance: boolean; defenderName: string; defenderDeployemntActivation: number; defenderMOTD: string; deployerName: string; deployerClan?: string; history: any[]; } export interface Invasion { id: string; activation: string; startString: string; node: string; desc: string; attackerReward: InvasionReward; attackingFaction: string; defenderReward: InvasionReward; defendingFaction: string; vsInfestation: boolean; count: number; requiredRuns: number; completion: number; completed: boolean; eta: string; rewardTypes: string[]; } export interface InvasionReward { items: any[]; countedItems: CountedItem[]; credits: number; asString: string; itemString: string; thumbnail: string; color: number; } export interface CountedItem { count: number; type: string; } export interface FlashSale { item: string; expiry: string; discount: number; premiumOverride: number; isFeatured: boolean; isPopular: boolean; id: string; expired: boolean; eta: string; } export interface Fissure { id: string; node: string; missionType: string; enemy: string; tier: string; tierNum: number; activation: string; expiry: string; expired: boolean; eta: string; } export interface SyndicateMission { id: string; activation: string; expiry: string; syndicate: string; nodes: string[]; jobs: Job[]; eta: string; } export interface Event { id: string; activation: string; startString: string; expiry: string; active: boolean; maximumScore: number; currentScore: number; description: string; tooltip: string; node: string; concurrentNodes: any[]; victimNode: string; scoreLocTag: string; rewards: Reward[]; expired: boolean; health: string; interimSteps: InterimStep[]; affiliatedWith: string; jobs: Job[]; progressSteps: any[]; showTotalAtEndOfMission: boolean; isPersonal: boolean; isCommunity: boolean; regionDrops: string[]; archwingDrops: string[]; asString: string; } export interface InterimStep { goal: number; reward: Reward; message: Message; winnerCount: number; } export interface Message { sender: string; subject: string; message: string; senderIcon: string; attachments: string[]; } export interface Job { id: string; type: string; enemyLevels: number[]; // [10,30] standingStages: number[]; rewardPool: string[]; } export interface Sortie { id: string; activation: string; expiry: string; rewardPool: string; variants: Variant[]; boss: string; faction: string; expired: boolean; eta: string; } export interface Variant { boss: string; // Deprecated planet: string; // Deprecated missionType: string; modifier: string; modifierDescription: string; node: string; // "Cassini (Saturn)" } export interface Alert { id: string; activation: string; expiry: string; mission: Mission; expired: boolean; eta: string; rewardTypes: string[]; } export interface Mission { description?: string; node: string; type: string; faction: string; reward?: Reward; minEnemyLevel?: number; maxEnemyLevel?: number; nightmare?: boolean; archwingRequired?: boolean; maxWaveNum?: number; } export interface Reward { items: string[]; countedItems: any[]; credits: number; asString: string; itemString: string; thumbnail: string; color: number; } export interface News { id: string; message: string; link: string; imageLink: string; priority: boolean; date: string; eta: string; update: boolean; primeAccess: boolean; stream: boolean; translations: Translations; asString: string; } export interface Translations { en: string; fr?: string; it?: string; de?: string; es?: string; pt?: string; ru?: string; tr?: string; ja?: string; zh?: string; ko?: string; tc?: string; } export interface SteelPath { currentReward: CurrentReward; activation: string; expiry: string; remaining: string; rotation: CurrentReward[]; evergreens: CurrentReward[]; incursions: Incursions; } export interface Incursions { id: string; activation: string; expiry: string; } export interface CurrentReward { name: string; cost: number; } /** * Warframe World Stat from https://api.warframestat.us/ * * @export * @class WorldStat */ export class WorldStat { data: WarframeStat; platform = "pc"; get APIBase() { return "https://api.warframestat.us/" + this.platform; } /** * 获取最新数据 */ fetch() { return new Promise((resolve, reject) => { axios .get(this.APIBase, { timeout: 10e3, headers: { // "Accept-Language": "English", }, }) .then(data => { this.data = data.data; resolve(this.data); }) .catch(reject); }); } /** * 深层递归翻译 * @param obj 需要翻译的对象 */ deepTranslate<T extends Object>(obj: T, namespace = "messages"): T { if (isArray(obj)) return map(obj, v => (typeof v === "string" ? Translator.getLocText(v, namespace) : typeof v === "object" ? this.deepTranslate(v, namespace) : v)) as any; else return mapValues(obj, (v, i) => typeof v === "string" ? i === "node" || i === "location" ? this.nodeTranslate(v) : Translator.getLocText(v, namespace) : typeof v === "object" ? this.deepTranslate(v, namespace) : v ) as T; } /** * 地图节点翻译 * @param node 节点 */ nodeTranslate(node: string) { return node.replace(/(.+) \((.+)\)/, (_, a, b) => `${this.nodeNameTranslate(a)} | ${Translator.getLocText(b)}`); } nodeNameTranslate(node: string) { node = node.replace(/Relay$/, Translator.getLocText("Relay")); const tranlate = Translator.getLocText(node); if (node.startsWith("War") || tranlate.toLowerCase() === node.toLowerCase()) return node; else return tranlate; } /** * 突击信息 */ get sortie() { if (!this.data) return { id: "", activation: "", expiry: "", rewardPool: "Sortie Rewards", variants: [], boss: "", faction: "", expired: false, eta: "", }; return this.deepTranslate(this.data.sortie); } filterType = [ "nightmare", "endo", "traces", "credits", "resource", "ferrite", "nanoSpores", "alloyPlate", "salvage", "polymerBundle", "cryotic", "circuits", "plastids", "rubedo", "argonCrystal", "controlModule", "gallium", "morphics", "neuralSensors", "neurodes", "orokinCell", "oxium", "tellurium", ]; /** * 警报信息 */ get alerts() { if (!this.data || !this.data.alerts) return []; return this.deepTranslate(this.data.alerts.filter(v => !this.filterType.includes(v.rewardTypes[0]))); } filterMission = ["Mobile Defense"]; /** * 裂缝信息 */ get fissures() { if (!this.data) return []; return this.deepTranslate(this.data.fissures.filter(v => !this.filterMission.includes(v.missionType)).sort((a, b) => a.tierNum - b.tierNum)); } /** * 新闻信息 */ get news() { if (!this.data) return []; return reverse( this.deepTranslate(this.data.news.filter(v => v.translations.en)).map(v => { if (v.translations[i18n.locale.substr(0, 2)]) v.message = v.translations[i18n.locale.substr(0, 2)]; return v; }) ); } /** 事件 */ get event() { if (!this.data) return []; return reverse( this.deepTranslate(this.data.news.filter(v => v.translations.en)).map(v => { if (v.translations[i18n.locale.substr(0, 2)]) v.message = v.translations[i18n.locale.substr(0, 2)]; return v; }) ); } filterInvasion = ["fieldron", "detonite", "mutagen"]; /** * 入侵信息 */ get invasions() { if (!this.data) return []; return this.deepTranslate(this.data.invasions.filter(v => !v.completed && !v.rewardTypes.every(k => this.filterInvasion.includes(k)))); } /** * 地球平原赏金信息 */ get ostrons() { if (!this.data) return []; let data = this.data.syndicateMissions.find(v => v.syndicate === "Ostrons"); if (!data) return []; return this.deepTranslate(data.jobs.map(v => (v.rewardPool && (v.rewardPool = v.rewardPool.map(k => k.replace(/(\d+)X (.+)$/, "$1 $2"))), v))); } /** * 金星平原赏金信息 */ get solarisUnited() { if (!this.data) return []; let data = this.data.syndicateMissions.find(v => v.syndicate === "Solaris United"); if (!data) return []; return this.deepTranslate(data.jobs.map(v => (v.rewardPool && (v.rewardPool = v.rewardPool.map(k => k.replace(/(\d+)X (.+)$/, "$1 $2"))), v))); } /** * 虚空商人 */ get voidTrader() { if (!this.data) return null; let data = this.data.voidTrader; if (!data) return null; return this.deepTranslate(data); } /** * 午夜电波 */ get nightwave() { if (!this.data) return null; let data = this.data.nightwave; if (!data) return null; data.activeChallenges = data.activeChallenges.map(v => { v.type = v.isDaily ? (v.isElite ? "Daily Elite" : "Daily") : v.isElite ? "Weekly Elite" : "Weekly"; return v; }); return this.deepTranslate(data, "nightwave"); } /** * 赤毒 */ get kuva() { if (!this.data) return null; let data = this.data.kuva; if (!data) return null; return this.deepTranslate(data); } /** * 仲裁 */ get arbitration() { if (!this.data) return null; let data = this.data.arbitration; if (!data) return null; return this.deepTranslate(data); } /** * S船 */ get sentientOutposts() { if (!this.data) return null; let data = this.data.sentientOutposts; if (!data) return null; return this.deepTranslate(data); } /** * 希图斯时间 */ get cetusCycle() { return this.data.cetusCycle; } /** * 福尔图娜时间 */ get vallisCycle() { return this.data.vallisCycle; } }
the_stack
declare module "crypto" { import * as stream from "stream"; interface Certificate { exportChallenge(spkac: string | Buffer | NodeJS.TypedArray | DataView): Buffer; exportPublicKey(spkac: string | Buffer | NodeJS.TypedArray | DataView): Buffer; verifySpkac(spkac: Buffer | NodeJS.TypedArray | DataView): boolean; } const Certificate: { new(): Certificate; (): Certificate; }; /** @deprecated since v10.0.0 */ const fips: boolean; interface CredentialDetails { pfx: string; key: string; passphrase: string; cert: string; ca: string | string[]; crl: string | string[]; ciphers: string; } /** @deprecated since v0.11.13 - use tls.SecureContext instead. */ interface Credentials { context?: any; } /** @deprecated since v0.11.13 - use tls.createSecureContext instead. */ function createCredentials(details: CredentialDetails): Credentials; function createHash(algorithm: string, options?: stream.TransformOptions): Hash; function createHmac(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Hmac; type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; interface Hash extends stream.Transform { update(data: string | Buffer | NodeJS.TypedArray | DataView): Hash; update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hash; digest(): Buffer; digest(encoding: HexBase64Latin1Encoding): string; } interface Hmac extends stream.Transform { update(data: string | Buffer | NodeJS.TypedArray | DataView): Hmac; update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hmac; digest(): Buffer; digest(encoding: HexBase64Latin1Encoding): string; } type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm'; type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; interface CipherCCMOptions extends stream.TransformOptions { authTagLength: number; } interface CipherGCMOptions extends stream.TransformOptions { authTagLength?: number; } /** @deprecated since v10.0.0 use createCipheriv() */ function createCipher(algorithm: CipherCCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): CipherCCM; /** @deprecated since v10.0.0 use createCipheriv() */ function createCipher(algorithm: CipherGCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): CipherGCM; /** @deprecated since v10.0.0 use createCipheriv() */ function createCipher(algorithm: string, password: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Cipher; function createCipheriv(algorithm: CipherCCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): CipherCCM; function createCipheriv(algorithm: CipherGCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): CipherGCM; function createCipheriv(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Cipher; interface Cipher extends stream.Transform { update(data: string | Buffer | NodeJS.TypedArray | DataView): Buffer; update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; update(data: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64BinaryEncoding): string; update(data: Buffer | NodeJS.TypedArray | DataView, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; // second arg ignored update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; final(): Buffer; final(output_encoding: string): string; setAutoPadding(auto_padding?: boolean): this; // getAuthTag(): Buffer; // setAAD(buffer: Buffer): this; // docs only say buffer } interface CipherCCM extends Cipher { setAAD(buffer: Buffer, options: { plaintextLength: number }): this; getAuthTag(): Buffer; } interface CipherGCM extends Cipher { setAAD(buffer: Buffer, options?: { plaintextLength: number }): this; getAuthTag(): Buffer; } /** @deprecated since v10.0.0 use createDecipheriv() */ function createDecipher(algorithm: CipherCCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): DecipherCCM; /** @deprecated since v10.0.0 use createDecipheriv() */ function createDecipher(algorithm: CipherGCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): DecipherGCM; /** @deprecated since v10.0.0 use createDecipheriv() */ function createDecipher(algorithm: string, password: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Decipher; function createDecipheriv( algorithm: CipherCCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions, ): DecipherCCM; function createDecipheriv( algorithm: CipherGCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions, ): DecipherGCM; function createDecipheriv(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Decipher; interface Decipher extends stream.Transform { update(data: Buffer | NodeJS.TypedArray | DataView): Buffer; update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; update(data: Buffer | NodeJS.TypedArray | DataView, input_encoding: HexBase64BinaryEncoding | undefined, output_encoding: Utf8AsciiBinaryEncoding): string; // second arg is ignored update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; final(): Buffer; final(output_encoding: string): string; setAutoPadding(auto_padding?: boolean): this; // setAuthTag(tag: Buffer | NodeJS.TypedArray | DataView): this; // setAAD(buffer: Buffer | NodeJS.TypedArray | DataView): this; } interface DecipherCCM extends Decipher { setAuthTag(buffer: Buffer | NodeJS.TypedArray | DataView): this; setAAD(buffer: Buffer | NodeJS.TypedArray | DataView, options: { plaintextLength: number }): this; } interface DecipherGCM extends Decipher { setAuthTag(buffer: Buffer | NodeJS.TypedArray | DataView): this; setAAD(buffer: Buffer | NodeJS.TypedArray | DataView, options?: { plaintextLength: number }): this; } function createSign(algorithm: string, options?: stream.WritableOptions): Signer; interface Signer extends NodeJS.WritableStream { update(data: string | Buffer | NodeJS.TypedArray | DataView): Signer; update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer; sign(private_key: string | { key: string; passphrase?: string, padding?: number, saltLength?: number }): Buffer; sign(private_key: string | { key: string; passphrase?: string, padding?: number, saltLength?: number }, output_format: HexBase64Latin1Encoding): string; } function createVerify(algorith: string, options?: stream.WritableOptions): Verify; interface Verify extends NodeJS.WritableStream { update(data: string | Buffer | NodeJS.TypedArray | DataView): Verify; update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Verify; verify(object: string | Object, signature: Buffer | NodeJS.TypedArray | DataView): boolean; verify(object: string | Object, signature: string, signature_format: HexBase64Latin1Encoding): boolean; // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format // The signature field accepts a TypedArray type, but it is only available starting ES2017 } function createDiffieHellman(prime_length: number, generator?: number | Buffer | NodeJS.TypedArray | DataView): DiffieHellman; function createDiffieHellman(prime: Buffer | NodeJS.TypedArray | DataView): DiffieHellman; function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer | NodeJS.TypedArray | DataView): DiffieHellman; function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; interface DiffieHellman { generateKeys(): Buffer; generateKeys(encoding: HexBase64Latin1Encoding): string; computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView): Buffer; computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64Latin1Encoding): string; computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; getPrime(): Buffer; getPrime(encoding: HexBase64Latin1Encoding): string; getGenerator(): Buffer; getGenerator(encoding: HexBase64Latin1Encoding): string; getPublicKey(): Buffer; getPublicKey(encoding: HexBase64Latin1Encoding): string; getPrivateKey(): Buffer; getPrivateKey(encoding: HexBase64Latin1Encoding): string; setPublicKey(public_key: Buffer | NodeJS.TypedArray | DataView): void; setPublicKey(public_key: string, encoding: string): void; setPrivateKey(private_key: Buffer | NodeJS.TypedArray | DataView): void; setPrivateKey(private_key: string, encoding: string): void; verifyError: number; } function getDiffieHellman(group_name: string): DiffieHellman; function pbkdf2( password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, iterations: number, keylen: number, digest: string, callback: (err: Error | null, derivedKey: Buffer) => any, ): void; function pbkdf2Sync(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, iterations: number, keylen: number, digest: string): Buffer; function randomBytes(size: number): Buffer; function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; function pseudoRandomBytes(size: number): Buffer; function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; function randomFillSync<T extends Buffer | NodeJS.TypedArray | DataView>(buffer: T, offset?: number, size?: number): T; function randomFill<T extends Buffer | NodeJS.TypedArray | DataView>(buffer: T, callback: (err: Error | null, buf: T) => void): void; function randomFill<T extends Buffer | NodeJS.TypedArray | DataView>(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; function randomFill<T extends Buffer | NodeJS.TypedArray | DataView>(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; interface ScryptOptions { N?: number; r?: number; p?: number; maxmem?: number; } function scrypt( password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void, ): void; function scrypt( password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, keylen: number, options: ScryptOptions, callback: (err: Error | null, derivedKey: Buffer) => void, ): void; function scryptSync(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, keylen: number, options?: ScryptOptions): Buffer; interface RsaPublicKey { key: string; padding?: number; } interface RsaPrivateKey { key: string; passphrase?: string; padding?: number; } function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; function getCiphers(): string[]; function getCurves(): string[]; function getHashes(): string[]; class ECDH { static convertKey( key: string | Buffer | NodeJS.TypedArray | DataView, curve: string, inputEncoding?: HexBase64Latin1Encoding, outputEncoding?: "latin1" | "hex" | "base64", format?: "uncompressed" | "compressed" | "hybrid", ): Buffer | string; generateKeys(): Buffer; generateKeys(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView): Buffer; computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64Latin1Encoding): string; computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; getPrivateKey(): Buffer; getPrivateKey(encoding: HexBase64Latin1Encoding): string; getPublicKey(): Buffer; getPublicKey(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; setPrivateKey(private_key: Buffer | NodeJS.TypedArray | DataView): void; setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; } function createECDH(curve_name: string): ECDH; function timingSafeEqual(a: Buffer | NodeJS.TypedArray | DataView, b: Buffer | NodeJS.TypedArray | DataView): boolean; /** @deprecated since v10.0.0 */ const DEFAULT_ENCODING: string; export type KeyType = 'rsa' | 'dsa' | 'ec'; export type KeyFormat = 'pem' | 'der'; interface BasePrivateKeyEncodingOptions<T extends KeyFormat> { format: T; cipher?: string; passphrase?: string; } interface RSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { /** * Key size in bits */ modulusLength: number; /** * @default 0x10001 */ publicExponent?: number; publicKeyEncoding: { type: 'pkcs1' | 'spki'; format: PubF; }; privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { type: 'pkcs1' | 'pkcs8'; }; } interface DSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { /** * Key size in bits */ modulusLength: number; /** * Size of q in bits */ divisorLength: number; publicKeyEncoding: { type: 'spki'; format: PubF; }; privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { type: 'pkcs8'; }; } interface ECKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { /** * Name of the curve to use. */ namedCurve: string; publicKeyEncoding: { type: 'pkcs1' | 'spki'; format: PubF; }; privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { type: 'sec1' | 'pkcs8'; }; } interface KeyPairSyncResult<T1 extends string | Buffer, T2 extends string | Buffer> { publicKey: T1; privateKey: T2; } function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>; function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>; function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>; function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; namespace generateKeyPair { function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; } }
the_stack
/// <reference types="chrome" /> declare interface Window { whale: typeof whale; } declare namespace chrome.downloads { export interface StateType { readonly COMPLETE: string; readonly IN_PROGRESS: string; readonly INTERRUPTED: string; } export const State: StateType; } declare namespace whale { /** * 지정한 주기 혹은 시간에 코드가 실행되도록 예약합니다 * 권한: "alarms" * @since Chrome 22. */ export import alarms = chrome.alarms; /** * 북마크의 생성, 삭제, 수정 및 폴더 변경 등 북마크에 관한 기능을 제공합니다. 이 API를 이용해 북마크 관리자를 만들 수 있습니다. * 권한: "bookmarks" * @since Chrome 5. */ export import bookmarks = chrome.bookmarks; /** * 주소창 오른쪽 툴바 영역에 나타나는 버튼을 제어 할 수 있습니다. 아이콘을 변경하거나 뱃지를 표시할 수도 있고, 팝업이 나타나게 할 수도 있습니다. * Manifest: "browser_action": {...} * @since Chrome 5. */ export import browserAction = chrome.browserAction; /** * 인터넷 사용 기록을 삭제할 수 있습니다. 설정 > 개인정보 보호 > 인터넷 사용 기록 삭제 영역의 각 항목별 삭제를 수행할 수 있습니다. * 권한: "browsingData" * @since Chrome 19. */ export import browsingData = chrome.browsingData; /** * 확장앱에 단축키를 부여할 수 있습니다. * Manifest: "commands": {...} * @since Chrome 16. */ export import commands = chrome.commands; /** * 쿠키, 자바스크립트, 마이크 등 웹 사이트에서 요청한 정보를 제공할 것인지 설정할 수 있습니다. 설정 > 개인정보 보호 > 콘텐츠 설정에서 확인할 수 있는 항목을 제어할 수 있습니다. * 권한: "contentSettings" * @since Chrome 16. */ export import contentSettings = chrome.contentSettings; /** * 마우스 오른쪽 버튼을 클릭하면 나타나는 콘텍스트 메뉴를 만들 수 있습니다. 페이지, 링크, 이미지 등 클릭한 위치에 따라 서로 다른 메뉴를 표시할 수 있습니다 * 권한: "contextMenus" * @since Chrome 6. */ export import contextMenus = chrome.contextMenus; /** * 쿠키를 제어하거나 변경시 이벤트를 수신할 수 있습니다 * 권한: "cookies", host 권한 * @since Chrome 6. */ export import cookies = chrome.cookies; /** * 특정 탭의 네트워크 통신, JavaScript 디버깅, DOM · CSS 변형 등 디버그를 위한 [원격 디버깅 프로토콜](https://chromedevtools.github.io/devtools-protocol/tot/Network)을 사용할 수 있습니다. * `sendCommand()` 메소드와 `onEvent` 핸들러 함수를 이용해 개발자도구에서 제공하는 개별 기능을 명령 단위로 수행할 수 있습니다. * 권한: "debugger" * @since Chrome 18. */ const _debugger: typeof chrome.debugger; export { _debugger as debugger }; /** * 웹 페이지에 대한 접근 권한 요청없이 특정 페이지의 콘텐트 혹은 상태에 의존적인 동작을 수행할 수 있습니다. * 권한: "declarativeContent" * @since Chrome 33. */ export import declarativeContent = chrome.declarativeContent; /** * 화면, 윈도우 또는 탭의 콘텐츠를 캡쳐할 수 있습니다. * 권한: "desktopCapture" * @since Chrome 34. */ export import desktopCapture = chrome.desktopCapture; export namespace devtools { /** * 개발자도구를 이용한 검사(Inspect)가 진행중인 윈도우에서 코드를 실행하거나 페이지를 새로고침 하는 등의 작업을 수행할 수 있습니다. * @since Chrome 18. */ export import inspectedWindow = chrome.devtools.inspectedWindow; /** * 개발자도구 > 네트워크 패널에서 수신하는 정보들을 수신할 수 있습니다. * @since Chrome 18. */ export import network = chrome.devtools.network; /** * 개발자도구에 새로운 패널을 추가하거나 기존의 패널에 접근할 수 있습니다. * @since Chrome 18. */ export import panels = chrome.devtools.panels; } /** * 지정한 URL의 파일 다운로드, 진행중인 다운로드의 제어 및 검색 등 파일 다운로드에 관련된 기능을 사용할 수 있습니다. * 권한: "downloads" * @since Chrome 31 */ export import downloads = chrome.downloads; /** * 웨일 브라우저 API에서 사용되는 공통 이벤트 자료형을 포함하는 네임스페이스입니다. * @since Chrome 21. */ export import events = chrome.events; /** * 서로 다른 확장앱 사이에 메시지를 교환하거나, 현재 확장앱에 관한 정보를 얻을 수 있습니다. * @since Chrome 5. */ export import extension = chrome.extension; /** * 글꼴 관련 설정을 제어할 수 있습니다. * 권한: "fontSettings" * @since Chrome 22. */ export import fontSettings = chrome.fontSettings; /** * Google Cloud Messaging 서비스와 메시지를 주고받습니다. * 권한: "gcm" * @since Chrome 35. */ export import gcm = chrome.gcm; /** * 방문 기록의 생성, 삭제 및 검색 등 방문 기록에 관한 기능을 제공합니다. 이 API를 이용해 방문 기록 페이지를 만들 수 있습니다. * 권한: "history" * @since Chrome 5. */ export import history = chrome.history; /** * 다국어 지원을 위한 기능을 제공합니다. * @since Chrome 5. */ export import i18n = chrome.i18n; /** * 시스템의 유휴 상태(Idle) 여부를 확인하거나 변화를 감지할 수 있습니다. * 권한: "idle" * @since Chrome 6. */ export import idle = chrome.idle; /** * 설치되어 있는 확장앱 정보를 얻어 제어할 수 있습니다. * 권한: "management" * @since Chrome 8. */ export import management = chrome.management; /** * 시스템 트레이에 알림창을 표시할 수 있습니다. * 권한: "notifications" * @since Chrome 28. */ export import notifications = chrome.notifications; /** * 주소창에서 특정 키워드를 입력하면 확장앱이 주소창 영역에 관여하게 할 수 있습니다. * Manifest: "omnibox": {...} * @since Chrome 9. */ export import omnibox = chrome.omnibox; /** * 주소창 오른쪽 툴바 영역에 나타나는 버튼을 제어 할 수 있습니다. * `browserAction`과 거의 동일하지만 현재 페이지에 대해서만 기능을 수행하기 위해 제공된다는 점이 다릅니다. 비활성 상태에서는 버튼이 회색으로 표시됩니다. * Manifest: "page_action": {...} * @since Chrome 5. */ export import pageAction = chrome.pageAction; /** * 지정한 탭의 웹 페이지를 MHTML 형식으로 저장할 수 있습니다. * 권한: "pageCapture" * @since Chrome 18. */ export import pageCapture = chrome.pageCapture; /** * 매니페스트에 optional_permissions로 정의한 추가 권한을 사용자에게 요청할 수 있습니다 * @since Chrome 16. */ export import permissions = chrome.permissions; /** * 전원 관리 기능을 제어할 수 있습니다. * 권한: "power" */ export import power = chrome.power; /** * The chrome.printerProvider API exposes events used by print manager to query printers controlled by extensions, to query their capabilities and to submit print jobs to these printers. * 권한: "printerProvider" */ export import printerProvider = chrome.printerProvider; /** * 개인정보 보호 관련 설정을 제어할 수 있습니다. * 권한: "privacy" */ export import privacy = chrome.privacy; /** * 프록시 관련 설정을 제어할 수 있습니다. * 권한: "proxy" */ export import proxy = chrome.proxy; /** * 백그라운드 페이지 검색, 매니페스트 확인 및 확장앱 수명주기에 관한 이벤트 수신, 메시지 교환 등의 기능을 제공합니다. */ export import runtime = chrome.runtime; /** * 웨일 사이드바 API. * Manifest: "sidebar_action": {...} * @since whale */ export namespace sidebarAction { export interface SidebarShowDetail { /** Optional. 사이드바 영역에 표시할 페이지 URL. 지정하지 않으면 매니페스트에 정의한 default_page. */ url?: string | undefined; /** * Optional. url 인자와 현재 URL이 같을 때에도 페이지를 새로고침 할 것인지 여부. * @default false */ reload?: boolean | undefined; } export interface SidebarTitleDetail { title: string; } export interface SidebarIconDetail { /** * 아이콘 이미지 데이터입니다. @see https://developer.chrome.com/extensions/pageAction#type-ImageDataType * */ icon: ImageData; } export interface SidebarPageDetail { /** html 파일의 리소스 경로. 빈 문자열(‘’)로 설정하면 사이드바에 빈화면이 보입니다. */ page: string; } export interface SidebarBadgeDetail { /** 설정할 badge 문자열 */ text: string; } export interface SidebarDockDetail { /** 부모 윈도우의 ID. 지정하지 않으면 마지막 사용된 윈도우에 도킹합니다. */ targetWindowId?: number | undefined; } export interface BadgeBackgroundColorDetails { /** 색상값 배열([255, 0, 0, 255]) 혹은 HEX 색상 표현 문자열(#FF0000). */ color: string | ColorArray; } export type ColorArray = [number, number, number, number]; export interface BrowserClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> {} /** * 지정한 윈도우에 사이드바 영역을 열고 포커스를 주는 메소드입니다. 이미 사이드바가 열려있다면 포커스만 옮겨줍니다. * * @param windowId Optional. 대상 윈도우의 ID. * @param details Optional. url 설정 * @param callback Optional. 콜백 함수. 인자값으로 windowId가 넘어감 */ export function show( windowId: number, details?: SidebarShowDetail, callback?: (windowId: number) => void ): void; /** * 현재 윈도우에 사이드바 영역을 열고 포커스를 주는 메소드입니다. 이미 사이드바가 열려있다면 포커스만 옮겨줍니다. * * @param details Optional. url 설정 * @param callback Optional. 콜백 함수. 인자값으로 windowId가 넘어감 */ export function show( details: SidebarShowDetail, callback?: (windowId: number) => void ): void; /** * 현재 윈도우에 사이드바 영역을 열고 포커스를 주는 메소드입니다. 이미 사이드바가 열려있다면 포커스만 옮겨줍니다. * * @param callback Optional. 콜백 함수. 인자값으로 windowId가 넘어감 */ export function show(callback: (windowId: number) => void): void; /** * 현재 윈도우에 사이드바 영역을 열고 포커스를 주는 메소드입니다. 이미 사이드바가 열려있다면 포커스만 옮겨줍니다. * */ export function show(): void; /** * 지정된 윈도우의 사이드바를 닫습니다. 현재 확장앱에 포커스가 있는 상황에만 동작합니다. * @param windowId Optional. 대상 윈도우의 ID. 지정하지 않으면 현재 윈도우. * @param callback Optional. 콜백 함수. 인자값으로 windowId가 넘어감 */ export function hide( windowId: number, callback?: (windowId: number) => void ): void; /** * 현재 윈도우의 사이드바를 닫습니다. 현재 확장앱에 포커스가 있는 상황에만 동작합니다. * @param callback Optional. 콜백 함수. 인자값으로 windowId가 넘어감 */ export function hide(callback: (windowId: number) => void): void; /** * 현재 윈도우의 사이드바를 닫습니다. 현재 확장앱에 포커스가 있는 상황에만 동작합니다. */ export function hide(): void; /** * 확장앱 아이콘에 마우스를 올렸을 때 나타나는 툴팁 문자열을 변경합니다. * sidebar_action 에서 default_title 속성으로 지정하는 영역입니다. * 열려 있는 모든 윈도우에 동시 적용됩니다. * @param details 설정 할 데이터 */ export function setTitle(details: SidebarTitleDetail): void; /** * 확장앱 아이콘에 마우스를 올렸을 때 나타나는 툴팁 문자열을 반환합니다. * sidebar_action 에서 default_title 속성으로 지정한 영역입니다. * @param callback title을 담은 결과를 인자값으로 넣은 콜백 함수 */ export function getTitle(callback: (result: string) => void): void; /** * 확장앱 아이콘을 동적으로 변경합니다. 열려 있는 모든 윈도우에 동시 적용됩니다. * @param details 아이콘 데이터 */ export function setIcon(details: SidebarIconDetail): void; /** * 확장앱 아이콘이 클릭되었을 때, 로딩되는 페이지 리소스의 경로를 변경합니다. * @param details 페이지 상세 정보 */ export function setPage(details: SidebarPageDetail): void; /** * 사이드바 확장앱 아이콘이 클릭되었을 때, 로딩되는 페이지 리소스의 경로를 반환합니다. * @param callback 현재 page 경로를 인자값으로 넣은 콜백 함수 */ export function getPage(callback: (result: string) => void): void; /** * 확장앱 아이콘 위에 표시되는 뱃지의 문자열을 변경합니다. 열려 있는 모든 윈도우에 동시 적용됩니다. * @param details badge 정보 */ export function setBadgeText(details: SidebarBadgeDetail): void; /** * 사이드바 확장앱 아이콘 위에 표시되는 뱃지의 문자열을 반환합니다. * @param callback 현재 뱃지 텍스트를 인자값으로 넣은 콜백 함수. */ export function getBadgeText(callback: (result: string) => void): void; /** * 확장앱 아이콘 위에 표시되는 뱃지의 배경 색상을 변경합니다. 열려 있는 모든 윈도우에 동시 적용됩니다. * @param details 뱃지 배경 색상을 담은 객체 */ export function setBadgeBackgroundColor( details: BadgeBackgroundColorDetails ): void; /** * 확장앱 아이콘 위에 표시되는 뱃지의 배경색상을 반환합니다. * @param callback 뱃지 배경 색상. RGBA 색상값 배열 [R, G, B, A]를 담은 인자값으로 넣은 콜백 함수. */ export function getBadgeBackgroundColor( callback: (color: ColorArray) => void ): void; /** * 팝업 윈도우를 사이드바에 도킹합니다. details를 통해 도킹하고자 하는 부모 윈도우를 지정할 수 있습니다. * 도킹 후에는 팝업 윈도우의 ID는 더 이상 유효하지 않습니다. * @param popupWindowId 팝업 윈도우의 ID. * @param details Optional. 부모 윈도우의 ID를 담은 객체 * @param callback 도킹 된 windowId를 인자값으로 넣은 콜백 함수. */ export function dock( popupWindowId: number, details: SidebarDockDetail, callback: (windowId: number) => void ): void; /** * 팝업 윈도우를 사이드바에 도킹합니다. details를 통해 도킹하고자 하는 부모 윈도우를 지정할 수 있습니다. * 도킹 후에는 팝업 윈도우의 ID는 더 이상 유효하지 않습니다. * @param popupWindowId 팝업 윈도우의 ID. * @param callback 도킹 된 windowId를 인자값으로 넣은 콜백 함수. */ export function dock( popupWindowId: number, callback: (windowId: number) => void ): void; /** * 도킹된 윈도우를 부모 윈도우에서 떼어냅니다. * @param popupWindowId 부모 윈도우의 ID * @param callback 새로 부여된 윈도우 Id를 인자값으로 넣은 콜백 함수. * 여기서 windowId는 `whale.sidebarAction.dock()`으로 붙일 때 사용했던 윈도우 ID와는 다르다. */ export function undock( popupWindowId: number, callback: (windowId: number) => void ): void; /** * 사이드바 확장앱 아이콘이 클릭될 때 발생하는 이벤트 핸들러 */ export var onClicked: BrowserClickedEvent; } /** * 데이터 저장소 기능을 제공합니다. 데이터 변경시 이벤트를 수신할 수 있습니다. 이 API를 이용해 저장한 데이터는 쿠키, 웹 스토리지 등 인터넷 사용 기록과는 별도로 관리됩니다. * 권한: "storage" * @since Chrome 20. */ export import storage = chrome.storage; export namespace system { /** * 시스템 CPU 관련 정보를 얻을 수 있습니다. * 권한: "system.cpu" * @since Chrome 32. */ export import cpu = chrome.system.cpu; /** * 시스템 메모리 관련 정보를 얻을 수 있습니다. * 권한: "system.memory" * @since Chrome 32. */ export import memory = chrome.system.memory; /** * 시스템 연결된 이동식 저장매체에 대한 정보를 얻을 수 있습니다. 새로운 이동식 저장매체가 연결되거나, 이미 연결되어 있던 매체가 연결 해제되는 경우 이벤트를 수신할 수 있습니다. * Permissions: "system.storage" * @since Chrome 30. */ export import storage = chrome.system.storage; } /** * 지정한 탭의 미디어 스트림을 캡쳐할 수 있습니다 * 권한: "tabCapture" * @since Chrome 31. */ export import tabCapture = chrome.tabCapture; /** * 새로운 탭을 생성하거나 이미 생성된 탭을 제어할 수 있습니다. * @since Chrome 5. */ export import tabs = chrome.tabs; /** * 새 탭 페이지의 "자주 가는 사이트" 목록을 얻거나 수정, 검색 할 수 있습니다. * Whale에서 더 많은 기능을 지원합니다. * 권한: "topSites" * @since Chrome 19. * */ export namespace topSites { /** 많이 방문한 URL을 저장하는 Object입니다. get에서 사용됩니다. */ export interface MostVisitedURL { /** 많이 방문한 url. */ url: string; /** 페이지 제목 */ title: string; /** * 방문기록에서 판단한 여부입니다. * api로 추가한 경우에는 false입니다. */ from_history: boolean; } /** 많이 방문한 URL을 저장하는 Object입니다. search에서 사용됩니다. */ export interface MostVisitedURL2 { /** 많이 방문한 url. */ url: string; /** 페이지 제목 */ title: string; } /** * 자주 가는 사이트를 전부 리스트로 담아옵니다. * @param callback 결과를 콜백함수의 인자값으로 보냅니다. */ export function get(callback: (data: MostVisitedURL[]) => void): void; /** * 자주 가는 사이트에 url과 title을 추가합니다. * @param url 추가할 url * @param title 제목 * @param callback 상태를 콜백 함수의 인자값으로 보냅니다. 성공시 true, 실패시 false */ export function add( url: string, title: string, callback?: (status: boolean) => void ): void; /** * 자주 가는 사이트에서 해당 url을 삭제합니다. * @param url 삭제할 url */ var _delete: (url: string) => void; export { _delete as delete }; /** * 자주 가는 사이트에서 해당 url을 숨깁니다. * @param url block할 url */ export function block(url: string): void; /** * 자주 가는 사이트에서 숨겨진 url을 보이게 합니다. * @param url block을 풀 url */ export function unblock(url: string): void; /** * 자주 가는 사이트에 block당한 여부를 확인합니다. * @param url 확인할 uri * @param callback block 여부를 콜백함수의 인자값으로 보냅니다. */ export function isBlocked( url: string, callback: (status: boolean) => void ): void; /** * 방문기록에서 자주 가는 사이트 순으로 검색을 합니다. * @param term 검색할 키워드 * @param count 검색할 개수. * @param callback 결과 리스트를 함수의 인자값으로 보냅니다. */ export function search( term: string, count: number, callback?: (result: MostVisitedURL2[]) => void ): void; /** * 자주 가는 사이트에 해당 배열을 추가합니다. * 만약 다시 update를 실행하면 기존에 update에 존재하는 배열은 삭제됩니다. * @param urls url, title로 구성된 Object Array */ export function update(urls: MostVisitedURL2[]); } /** * text-to-speech를 사용할 수 있는 api입니다. * 권한: "tts" * @since Chrome 14. */ export import tts = chrome.tts; /** * text-to-speech를 사용할 수 있는 api입니다. * 권한: "tts" * @since Chrome 14. */ export import ttsEngine = chrome.ttsEngine; /** * Whale API의 type 정보를 얻을 수 있습니다. * @since Chrome 13. */ export import types = chrome.types; /** * 웹 탐색 요청을 수신하여 제어할 수 있습니다. * 권한: "webNavigation" * @since Chrome 16. */ export import webNavigation = chrome.webNavigation; /** * 웹 요청을 감지하여 차단, 수정 및 간섭할 수 있습니다. * 권한: "webRequest", host 권한 * @since Chrome 17. */ export import webRequest = chrome.webRequest; /** * 새로운 창을 생성하거나 이미 생성된 창을 제어할 수 있습니다. * 아무런 권한이 없어도 되지만, Tab권한이 있어야 favocon, uri, title의 정보를 불러올 수 있다. * @since Chrome 5. */ export import windows = chrome.windows; }
the_stack
import { Component, State, Event, EventEmitter, Element, h } from '@stencil/core'; import '@visa/visa-charts-data-table'; import '@visa/keyboard-instructions'; @Component({ tag: 'app-circle-packing', styleUrl: 'app-circle-packing.scss' }) export class AppCirclePacking { @State() data: any = []; @State() chartData: any; @State() stateTrigger: any = 0; @State() clickElement: any = []; @State() hoverElement: any = ''; @State() bigClickElement: any = []; @State() bigHoverElement: any = ''; // @State() @State() groupChartProp: any = []; @State() codeString: any = ''; @State() value: any = 0; // this is for handling value changes for button to control which dataset to send @State() scatterAttribute: any; @State() scatterAttribute2: any; @State() barAttribute: any; @State() nodeAccessor: any = 'Type'; @State() parentAccessor: any = 'Country'; @State() sizeAccessor: any = 'value'; @State() lineData: any; @State() pieData: any; @State() zoomTo: any; @State() bigZoomTo: any; @State() index: any = 1; @State() size: number = 500; @State() hellishData: any; @State() animations: any = { disabled: false }; @State() annotations: any = [ { note: { label: '2018', bgPadding: 0, align: 'middle', wrap: 210 }, accessibilityDescription: '2018 High Spend band total is 5,596', x: '8%', y: '40%', disable: ['connector', 'subject'], // dy: '-1%', color: '#000000', className: 'testing1 testing2 testing3', collisionHideOnly: false }, { note: { label: 'oasijfoiajsf', bgPadding: 0, align: 'middle', wrap: 210 }, accessibilityDescription: '2018 High Spend band total is 5,596', x: '8%', y: '40%', disable: ['connector', 'subject'], // dy: '-1%', color: '#000000', className: 'testing1 testing2 testing3', collisionHideOnly: false } ]; @Event() updateComponent: EventEmitter; @State() accessibility: any = { longDescription: 'This is a chart template that was made to showcase some of the capabilities of Visa Chart Components', contextExplanation: 'This chart exists in a demo app created to let you quickly change props and see results', executiveSummary: 'The United States group has more children than the other two groups', purpose: 'The purpose of this chart template is to test the functionality of a basic circle packing chart in the chart library', statisticalNotes: "This chart is using organizational data on Visa's product team", keyboardNavConfig: { disabled: false } }; @State() suppressEvents: boolean = false; @Element() appEl: HTMLElement; height: any = 400; width: any = 400; dataLabel: any = { visible: true, labelAccessor: 'cLabel', placement: 'auto', // this really only can be auto or anything else collisionPlacement: 'all' }; bigDataLabel: any = { visible: true, labelAccessor: 'LastName' }; bigClickStyle: any = { color: 'categorical_blue', stroke: 'base_grey', strokeWidth: 0.5, dashed: '3 1' }; bigHoverStyle: any = { color: 'sec_yellow', strokeWidth: 1 }; bigTooltipLabel: any = { labelAccessor: ['DisplayName', 'Title', 'Department', 'Node Spread'], labelTitle: ['Name', 'Title', 'Department', 'Direct Reports'], format: [] }; bigAccessibility: any = { longDescription: 'This is a chart template that was made to showcase some of the capabilities of Visa Chart Components', contextExplanation: 'This chart exists in a demo app created to let you quickly change props and see results', executiveSummary: 'The United States group has more children than the other two groups', purpose: 'The purpose of this chart template is to test the functionality of a basic circle packing chart in the chart library', statisticalNotes: "This chart is using organizational data on Visa's product team" }; lifeCycleTestData = []; lifeCycleStates = [ [ { altType: 'ALL', altCountry: '', altValue: 42, id: 1, Type: 'World', Country: '', value: 7 }, { altType: 'HAT', altCountry: 'ALL', altValue: 32, id: 2, Type: 'Mexico', Country: 'World', value: 50 }, { altType: 'CAT', altCountry: 'ALL', altValue: 34, id: 3, Type: 'United States', Country: 'World', value: 25 }, { altType: 'BAT', altCountry: 'ALL', altValue: 52, id: 4, Type: 'Canada', Country: 'World', value: 5 }, { altType: 'a', altCountry: 'HAT', altValue: 15, id: 5, Type: 'A', Country: 'Mexico', value: 64 }, { altType: 'b', altCountry: 'HAT', altValue: 34, id: 6, Type: 'B', Country: 'Mexico', value: 45 }, { altType: 'c', altCountry: 'BAT', altValue: 63, id: 7, Type: 'C', Country: 'Canada', value: 13 }, { altType: 'd', altCountry: 'BAT', altValue: 24, id: 8, Type: 'D', Country: 'Canada', value: 43 }, { altType: 'e', altCountry: 'HAT', altValue: 34, id: 9, Type: 'E', Country: 'Mexico', value: 22 }, { altType: 'f', altCountry: 'CAT', altValue: 44, id: 10, Type: 'F', Country: 'United States', value: 63 }, { altType: 'g', altCountry: 'CAT', altValue: 62, id: 11, Type: 'G', Country: 'United States', value: 23 }, { altType: 'h', altCountry: 'BAT', altValue: 22, id: 12, Type: 'H', Country: 'Canada', value: 39 }, { altType: 'i', altCountry: 'CAT', altValue: 30, id: 13, Type: 'I', Country: 'United States', value: 40 } ], [ { altType: 'ALL', altCountry: '', altValue: 42, id: 1, Type: 'World', Country: '', value: 70 }, { altType: 'HAT', altCountry: 'ALL', altValue: 32, id: 2, Type: 'Mexico', Country: 'World', value: 50 }, { altType: 'CAT', altCountry: 'ALL', altValue: 24, id: 3, Type: 'United States', Country: 'World', value: 25 }, { altType: 'BAT', altCountry: 'ALL', altValue: 12, id: 4, Type: 'Canada', Country: 'World', value: 5 }, { altType: 'a', altCountry: 'HAT', altValue: 45, id: 5, Type: 'A', Country: 'Mexico', value: 64 }, { altType: 'b', altCountry: 'HAT', altValue: 34, id: 6, Type: 'B', Country: 'Mexico', value: 45 }, { altType: 'c', altCountry: 'BAT', altValue: 13, id: 7, Type: 'C', Country: 'Canada', value: 83 }, { altType: 'd', altCountry: 'BAT', altValue: 54, id: 8, Type: 'D', Country: 'Canada', value: 43 }, { altType: 'e', altCountry: 'HAT', altValue: 14, id: 9, Type: 'E', Country: 'Mexico', value: 22 }, { altType: 'f', altCountry: 'CAT', altValue: 24, id: 10, Type: 'F', Country: 'United States', value: 13 }, { altType: 'g', altCountry: 'CAT', altValue: 32, id: 11, Type: 'G', Country: 'United States', value: 23 }, { altType: 'h', altCountry: 'BAT', altValue: 62, id: 12, Type: 'H', Country: 'Canada', value: 39 }, { altType: 'i', altCountry: 'CAT', altValue: 60, id: 13, Type: 'I', Country: 'United States', value: 40 } ], [ { altType: 'ALL', altCountry: '', altValue: 12, id: 1, Type: 'World', Country: '', value: 7 }, { altType: 'HAT', altCountry: 'ALL', altValue: 62, id: 2, Type: 'Mexico', Country: 'World', value: 50 }, { altType: 'CAT', altCountry: 'ALL', altValue: 24, id: 3, Type: 'United States', Country: 'World', value: 25 }, { altType: 'BAT', altCountry: 'ALL', altValue: 42, id: 4, Type: 'Canada', Country: 'World', value: 5 }, { altType: 'a', altCountry: 'HAT', altValue: 45, id: 5, Type: 'A', Country: 'Mexico', value: 64 }, { altType: 'b', altCountry: 'HAT', altValue: 34, id: 6, Type: 'B', Country: 'Mexico', value: 45 }, { altType: 'f', altCountry: 'CAT', altValue: 24, id: 7, Type: 'C', Country: 'United States', value: 13 }, { altType: 'd', altCountry: 'BAT', altValue: 54, id: 8, Type: 'D', Country: 'Canada', value: 43 }, { altType: 'e', altCountry: 'HAT', altValue: 14, id: 9, Type: 'E', Country: 'Mexico', value: 22 }, { altType: 'f', altCountry: 'CAT', altValue: 24, id: 10, Type: 'F', Country: 'United States', value: 63 }, { altType: 'g', altCountry: 'CAT', altValue: 32, id: 11, Type: 'G', Country: 'United States', value: 23 }, { altType: 'h', altCountry: 'BAT', altValue: 62, id: 12, Type: 'H', Country: 'Canada', value: 39 }, { altType: 'i', altCountry: 'CAT', altValue: 60, id: 13, Type: 'I', Country: 'United States', value: 40 } ] ]; circlePackComponentData: any = [ { p: null, c: '@visa/circle-packing', cLabel: '@visa/circle-packing', v: 1 }, { p: '@visa/circle-packing', c: 'import', cLabel: 'import', v: 1 }, { p: 'import', c: '@stencil/core{Component}', cLabel: '@stencil/core{Component}', v: 1 }, { p: 'import', c: '@stencil/core{Element}', cLabel: '@stencil/core{Element}', v: 1 }, { p: 'import', c: '@stencil/core{Prop}', cLabel: '@stencil/core{Prop}', v: 1 }, { p: 'import', c: '@stencil/core{h}', cLabel: '@stencil/core{h}', v: 1 }, { p: 'import', c: '@stencil/core{Watch}', cLabel: '@stencil/core{Watch}', v: 1 }, { p: 'import', c: '@stencil/core{Event}', cLabel: '@stencil/core{Event}', v: 1 }, { p: 'import', c: '@stencil/core{EventEmitter}', cLabel: '@stencil/core{EventEmitter}', v: 1 }, { p: 'import', c: '@visa/charts-types{IBoxModelType}', cLabel: '@visa/charts-types{IBoxModelType}', v: 1 }, { p: 'import', c: '@visa/charts-types{IHoverStyleType}', cLabel: '@visa/charts-types{IHoverStyleType}', v: 1 }, { p: 'import', c: '@visa/charts-types{IClickStyleType}', cLabel: '@visa/charts-types{IClickStyleType}', v: 1 }, { p: 'import', c: '@visa/charts-types{IDataLabelType}', cLabel: '@visa/charts-types{IDataLabelType}', v: 1 }, { p: 'import', c: '@visa/charts-types{ITooltipLabelType}', cLabel: '@visa/charts-types{ITooltipLabelType}', v: 1 }, { p: 'import', c: '@visa/charts-types{IAccessibilityType}', cLabel: '@visa/charts-types{IAccessibilityType}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{getContrastingStroke}', cLabel: '@visa/visa-charts-utils{getContrastingStroke}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{createTextStrokeFilter}', cLabel: '@visa/visa-charts-utils{createTextStrokeFilter}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{convertColorsToTextures}', cLabel: '@visa/visa-charts-utils{convertColorsToTextures}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{initializeElementAccess}', cLabel: '@visa/visa-charts-utils{initializeElementAccess}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{initializeDescriptionRoot}', cLabel: '@visa/visa-charts-utils{initializeDescriptionRoot}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{setElementFocusHandler}', cLabel: '@visa/visa-charts-utils{setElementFocusHandler}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{setAccessibilityController}', cLabel: '@visa/visa-charts-utils{setAccessibilityController}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{hideNonessentialGroups}', cLabel: '@visa/visa-charts-utils{hideNonessentialGroups}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{setAccessTitle}', cLabel: '@visa/visa-charts-utils{setAccessTitle}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{setAccessSubtitle}', cLabel: '@visa/visa-charts-utils{setAccessSubtitle}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{setAccessLongDescription}', cLabel: '@visa/visa-charts-utils{setAccessLongDescription}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{setAccessExecutiveSummary}', cLabel: '@visa/visa-charts-utils{setAccessExecutiveSummary}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{setAccessPurpose}', cLabel: '@visa/visa-charts-utils{setAccessPurpose}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{setAccessContext}', cLabel: '@visa/visa-charts-utils{setAccessContext}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{setAccessStatistics}', cLabel: '@visa/visa-charts-utils{setAccessStatistics}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{setAccessChartCounts}', cLabel: '@visa/visa-charts-utils{setAccessChartCounts}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{setAccessStructure}', cLabel: '@visa/visa-charts-utils{setAccessStructure}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{setAccessAnnotation}', cLabel: '@visa/visa-charts-utils{setAccessAnnotation}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{retainAccessFocus}', cLabel: '@visa/visa-charts-utils{retainAccessFocus}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{checkAccessFocus}', cLabel: '@visa/visa-charts-utils{checkAccessFocus}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{setElementInteractionAccessState}', cLabel: '@visa/visa-charts-utils{setElementInteractionAccessState}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{drawTooltip}', cLabel: '@visa/visa-charts-utils{drawTooltip}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{setAccessibilityDescriptionWidth}', cLabel: '@visa/visa-charts-utils{setAccessibilityDescriptionWidth}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{annotate}', cLabel: '@visa/visa-charts-utils{annotate}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{getPadding}', cLabel: '@visa/visa-charts-utils{getPadding}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{chartAccessors}', cLabel: '@visa/visa-charts-utils{chartAccessors}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{checkInteraction}', cLabel: '@visa/visa-charts-utils{checkInteraction}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{checkClicked}', cLabel: '@visa/visa-charts-utils{checkClicked}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{checkHovered}', cLabel: '@visa/visa-charts-utils{checkHovered}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{convertVisaColor}', cLabel: '@visa/visa-charts-utils{convertVisaColor}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{getColors}', cLabel: '@visa/visa-charts-utils{getColors}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{getLicenses}', cLabel: '@visa/visa-charts-utils{getLicenses}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{getScopedData}', cLabel: '@visa/visa-charts-utils{getScopedData}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{initTooltipStyle}', cLabel: '@visa/visa-charts-utils{initTooltipStyle}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{transitionEndAll}', cLabel: '@visa/visa-charts-utils{transitionEndAll}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{overrideTitleTooltip}', cLabel: '@visa/visa-charts-utils{overrideTitleTooltip}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{roundTo}', cLabel: '@visa/visa-charts-utils{roundTo}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{scopeDataKeys}', cLabel: '@visa/visa-charts-utils{scopeDataKeys}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{visaColors}', cLabel: '@visa/visa-charts-utils{visaColors}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{validateAccessibilityProps}', cLabel: '@visa/visa-charts-utils{validateAccessibilityProps}', v: 1 }, { p: 'import', c: '@visa/visa-charts-utils{findTagLevel}', cLabel: '@visa/visa-charts-utils{findTagLevel}', v: 1 }, { p: 'import', c: 'd3-selection{select}', cLabel: 'd3-selection{select}', v: 1 }, { p: 'import', c: 'd3-selection{event}', cLabel: 'd3-selection{event}', v: 1 }, { p: 'import', c: 'd3-array{max}', cLabel: 'd3-array{max}', v: 1 }, { p: 'import', c: 'd3-transition{*}', cLabel: 'd3-transition{*}', v: 1 }, { p: 'import', c: 'd3-hierarchy{hierarchy}', cLabel: 'd3-hierarchy{hierarchy}', v: 1 }, { p: 'import', c: 'uuid{v4}', cLabel: 'uuid{v4}', v: 1 }, { p: '@visa/circle-packing', c: '@Event', cLabel: '@Event', v: 1 }, { p: '@Event', c: 'clickFunc', cLabel: 'clickFunc', v: 1 }, { p: '@Event', c: 'hoverFunc', cLabel: 'hoverFunc', v: 1 }, { p: '@Event', c: 'mouseOutFunc', cLabel: 'mouseOutFunc', v: 1 }, { p: '@visa/circle-packing', c: '@Prop', cLabel: '@Prop', v: 1 }, { p: '@Prop', c: 'mainTitle', cLabel: 'mainTitle', v: 1 }, { p: '@Prop', c: 'subTitle', cLabel: 'subTitle', v: 1 }, { p: '@Prop', c: 'height', cLabel: 'height', v: 1 }, { p: '@Prop', c: 'width', cLabel: 'width', v: 1 }, { p: '@Prop', c: 'margin', cLabel: 'margin', v: 1 }, { p: '@Prop', c: 'padding', cLabel: 'padding', v: 1 }, { p: '@Prop', c: 'circlePadding', cLabel: 'circlePadding', v: 1 }, { p: '@Prop', c: 'highestHeadingLevel', cLabel: 'highestHeadingLevel', v: 1 }, { p: '@Prop', c: 'data', cLabel: 'data', v: 1 }, { p: '@Prop', c: 'uniqueID', cLabel: 'uniqueID', v: 1 }, { p: '@Prop', c: 'dataDepth', cLabel: 'dataDepth', v: 1 }, { p: '@Prop', c: 'displayDepth', cLabel: 'displayDepth', v: 1 }, { p: '@Prop', c: 'parentAccessor', cLabel: 'parentAccessor', v: 1 }, { p: '@Prop', c: 'nodeAccessor', cLabel: 'nodeAccessor', v: 1 }, { p: '@Prop', c: 'sizeAccessor', cLabel: 'sizeAccessor', v: 1 }, { p: '@Prop', c: 'colorPalette', cLabel: 'colorPalette', v: 1 }, { p: '@Prop', c: 'colors', cLabel: 'colors', v: 1 }, { p: '@Prop', c: 'cursor', cLabel: 'cursor', v: 1 }, { p: '@Prop', c: 'hoverStyle', cLabel: 'hoverStyle', v: 1 }, { p: '@Prop', c: 'clickStyle', cLabel: 'clickStyle', v: 1 }, { p: '@Prop', c: 'hoverOpacity', cLabel: 'hoverOpacity', v: 1 }, { p: '@Prop', c: 'showTooltip', cLabel: 'showTooltip', v: 1 }, { p: '@Prop', c: 'tooltipLabel', cLabel: 'tooltipLabel', v: 1 }, { p: '@Prop', c: 'dataLabel', cLabel: 'dataLabel', v: 1 }, { p: '@Prop', c: 'annotations', cLabel: 'annotations', v: 1 }, { p: '@Prop', c: 'accessibility', cLabel: 'accessibility', v: 1 }, { p: '@Prop', c: 'suppressEvents', cLabel: 'suppressEvents', v: 1 }, { p: '@Prop', c: 'interactionKeys', cLabel: 'interactionKeys', v: 1 }, { p: '@Prop', c: 'hoverHighlight', cLabel: 'hoverHighlight', v: 1 }, { p: '@Prop', c: 'clickHighlight', cLabel: 'clickHighlight', v: 1 }, { p: '@Prop', c: 'zoomToNode', cLabel: 'zoomToNode', v: 1 }, { p: '@visa/circle-packing', c: '@Element', cLabel: '@Element', v: 1 }, { p: '@Element', c: 'circlePackingEl', cLabel: 'circlePackingEl', v: 1 }, { p: '@Element', c: 'shouldValidateAccessibility', cLabel: 'shouldValidateAccessibility', v: 1 }, { p: '@Element', c: 'svg', cLabel: 'svg', v: 1 }, { p: '@Element', c: 'root', cLabel: 'root', v: 1 }, { p: '@Element', c: 'rootG', cLabel: 'rootG', v: 1 }, { p: '@Element', c: 'duration', cLabel: 'duration', v: 1 }, { p: '@Element', c: 'innerHeight', cLabel: 'innerHeight', v: 1 }, { p: '@Element', c: 'innerWidth', cLabel: 'innerWidth', v: 1 }, { p: '@Element', c: 'innerPaddedHeight', cLabel: 'innerPaddedHeight', v: 1 }, { p: '@Element', c: 'innerPaddedWidth', cLabel: 'innerPaddedWidth', v: 1 }, { p: '@Element', c: 'current', cLabel: 'current', v: 1 }, { p: '@Element', c: 'circle', cLabel: 'circle', v: 1 }, { p: '@Element', c: 'circleG', cLabel: 'circleG', v: 1 }, { p: '@Element', c: 'enterCircle', cLabel: 'enterCircle', v: 1 }, { p: '@Element', c: 'exitCircle', cLabel: 'exitCircle', v: 1 }, { p: '@Element', c: 'updateParentCircle', cLabel: 'updateParentCircle', v: 1 }, { p: '@Element', c: 'enterText', cLabel: 'enterText', v: 1 }, { p: '@Element', c: 'updateText', cLabel: 'updateText', v: 1 }, { p: '@Element', c: 'exitText', cLabel: 'exitText', v: 1 }, { p: '@Element', c: 'tooltipG', cLabel: 'tooltipG', v: 1 }, { p: '@Element', c: 'nodes', cLabel: 'nodes', v: 1 }, { p: '@Element', c: 'view', cLabel: 'view', v: 1 }, { p: '@Element', c: 'zoomRatio', cLabel: 'zoomRatio', v: 1 }, { p: '@Element', c: 'text', cLabel: 'text', v: 1 }, { p: '@Element', c: 'textG', cLabel: 'textG', v: 1 }, { p: '@Element', c: 'focus', cLabel: 'focus', v: 1 }, { p: '@Element', c: 'colorArr', cLabel: 'colorArr', v: 1 }, { p: '@Element', c: 'preparedColors', cLabel: 'preparedColors', v: 1 }, { p: '@Element', c: 'rootCircle', cLabel: 'rootCircle', v: 1 }, { p: '@Element', c: 'enter', cLabel: 'enter', v: 1 }, { p: '@Element', c: 'holder', cLabel: 'holder', v: 1 }, { p: '@Element', c: 'diameter', cLabel: 'diameter', v: 1 }, { p: '@Element', c: 'currentDepth', cLabel: 'currentDepth', v: 1 }, { p: '@Element', c: 'zooming', cLabel: 'zooming', v: 1 }, { p: '@Element', c: 'timer', cLabel: 'timer', v: 1 }, { p: '@Element', c: 'delay', cLabel: 'delay', v: 1 }, { p: '@Element', c: 'prevent', cLabel: 'prevent', v: 1 }, { p: '@Element', c: 'tableData', cLabel: 'tableData', v: 1 }, { p: '@Element', c: 'tableColumns', cLabel: 'tableColumns', v: 1 }, { p: '@Element', c: 'updated', cLabel: 'updated', v: 1 }, { p: '@Element', c: 'exitSize', cLabel: 'exitSize', v: 1 }, { p: '@Element', c: 'enterSize', cLabel: 'enterSize', v: 1 }, { p: '@Element', c: 'textFilter', cLabel: 'textFilter', v: 1 }, { p: '@Element', c: 'filter', cLabel: 'filter', v: 1 }, { p: '@Element', c: 'innerDisplayDepth', cLabel: 'innerDisplayDepth', v: 1 }, { p: '@Element', c: 'innerDataDepth', cLabel: 'innerDataDepth', v: 1 }, { p: '@Element', c: 'chartID', cLabel: 'chartID', v: 1 }, { p: '@Element', c: 'shouldZoom', cLabel: 'shouldZoom', v: 1 }, { p: '@Element', c: 'shouldValidateInteractionKeys', cLabel: 'shouldValidateInteractionKeys', v: 1 }, { p: '@Element', c: 'shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: '@Element', c: 'shouldUpdateClickFunc', cLabel: 'shouldUpdateClickFunc', v: 1 }, { p: '@Element', c: 'shouldUpdateHoverFunc', cLabel: 'shouldUpdateHoverFunc', v: 1 }, { p: '@Element', c: 'shouldUpdateMouseoutFunc', cLabel: 'shouldUpdateMouseoutFunc', v: 1 }, { p: '@Element', c: 'shouldUpdateAnnotations', cLabel: 'shouldUpdateAnnotations', v: 1 }, { p: '@Element', c: 'shouldResetRoot', cLabel: 'shouldResetRoot', v: 1 }, { p: '@Element', c: 'shouldSetColors', cLabel: 'shouldSetColors', v: 1 }, { p: '@Element', c: 'shouldUpdateDisplayDepth', cLabel: 'shouldUpdateDisplayDepth', v: 1 }, { p: '@Element', c: 'shouldUpdateLabels', cLabel: 'shouldUpdateLabels', v: 1 }, { p: '@Element', c: 'shouldAddStrokeUnder', cLabel: 'shouldAddStrokeUnder', v: 1 }, { p: '@Element', c: 'shouldUpdateCursor', cLabel: 'shouldUpdateCursor', v: 1 }, { p: '@Element', c: 'shouldUpdateData', cLabel: 'shouldUpdateData', v: 1 }, { p: '@Element', c: 'shouldUpdateTableData', cLabel: 'shouldUpdateTableData', v: 1 }, { p: '@Element', c: 'shouldValidate', cLabel: 'shouldValidate', v: 1 }, { p: '@Element', c: 'shouldBindInteractivity', cLabel: 'shouldBindInteractivity', v: 1 }, { p: '@Element', c: 'shouldUpdateDescriptionWrapper', cLabel: 'shouldUpdateDescriptionWrapper', v: 1 }, { p: '@Element', c: 'shouldSetChartAccessibilityTitle', cLabel: 'shouldSetChartAccessibilityTitle', v: 1 }, { p: '@Element', c: 'shouldSetChartAccessibilitySubtitle', cLabel: 'shouldSetChartAccessibilitySubtitle', v: 1 }, { p: '@Element', c: 'shouldSetChartAccessibilityLongDescription', cLabel: 'shouldSetChartAccessibilityLongDescription', v: 1 }, { p: '@Element', c: 'shouldSetChartAccessibilityExecutiveSummary', cLabel: 'shouldSetChartAccessibilityExecutiveSummary', v: 1 }, { p: '@Element', c: 'shouldSetChartAccessibilityStatisticalNotes', cLabel: 'shouldSetChartAccessibilityStatisticalNotes', v: 1 }, { p: '@Element', c: 'shouldSetChartAccessibilityStructureNotes', cLabel: 'shouldSetChartAccessibilityStructureNotes', v: 1 }, { p: '@Element', c: 'shouldSetParentSVGAccessibility', cLabel: 'shouldSetParentSVGAccessibility', v: 1 }, { p: '@Element', c: 'shouldSetGeometryAccessibilityAttributes', cLabel: 'shouldSetGeometryAccessibilityAttributes', v: 1 }, { p: '@Element', c: 'shouldSetGeometryAriaLabels', cLabel: 'shouldSetGeometryAriaLabels', v: 1 }, { p: '@Element', c: 'shouldSetGroupAccessibilityAttributes', cLabel: 'shouldSetGroupAccessibilityAttributes', v: 1 }, { p: '@Element', c: 'shouldSetGroupAccessibilityLabel', cLabel: 'shouldSetGroupAccessibilityLabel', v: 1 }, { p: '@Element', c: 'shouldSetChartAccessibilityPurpose', cLabel: 'shouldSetChartAccessibilityPurpose', v: 1 }, { p: '@Element', c: 'shouldSetChartAccessibilityContext', cLabel: 'shouldSetChartAccessibilityContext', v: 1 }, { p: '@Element', c: 'shouldSetChartAccessibilityCount', cLabel: 'shouldSetChartAccessibilityCount', v: 1 }, { p: '@Element', c: 'shouldUpdateLayout', cLabel: 'shouldUpdateLayout', v: 1 }, { p: '@Element', c: 'shouldSetTextures', cLabel: 'shouldSetTextures', v: 1 }, { p: '@Element', c: 'shouldSetStrokes', cLabel: 'shouldSetStrokes', v: 1 }, { p: '@Element', c: 'shouldSetTextStrokes', cLabel: 'shouldSetTextStrokes', v: 1 }, { p: '@Element', c: 'shouldSetTagLevels', cLabel: 'shouldSetTagLevels', v: 1 }, { p: '@Element', c: 'shouldRedrawWrapper', cLabel: 'shouldRedrawWrapper', v: 1 }, { p: '@Element', c: 'shouldSetIDs', cLabel: 'shouldSetIDs', v: 1 }, { p: '@Element', c: 'innerInteractionKeys', cLabel: 'innerInteractionKeys', v: 1 }, { p: '@Element', c: 'defaultsLoaded', cLabel: 'defaultsLoaded', v: 1 }, { p: '@Element', c: 'bottomLevel', cLabel: 'bottomLevel', v: 1 }, { p: '@Element', c: 'topLevel', cLabel: 'topLevel', v: 1 }, { p: '@Element', c: 'strokes', cLabel: 'strokes', v: 1 }, { p: 'data', c: 'dataWatcher', cLabel: 'dataWatcher', v: 1 }, { p: 'dataWatcher', c: 'dataWatcher.updated', cLabel: 'updated', v: 1 }, { p: 'dataWatcher', c: 'dataWatcher.shouldUpdateData', cLabel: 'shouldUpdateData', v: 1 }, { p: 'dataWatcher', c: 'dataWatcher.shouldUpdateTableData', cLabel: 'shouldUpdateTableData', v: 1 }, { p: 'dataWatcher', c: 'dataWatcher.shouldValidate', cLabel: 'shouldValidate', v: 1 }, { p: 'dataWatcher', c: 'dataWatcher.shouldZoom', cLabel: 'shouldZoom', v: 1 }, { p: 'dataWatcher', c: 'dataWatcher.shouldAddStrokeUnder', cLabel: 'shouldAddStrokeUnder', v: 1 }, { p: 'dataWatcher', c: 'dataWatcher.shouldSetGeometryAccessibilityAttributes', cLabel: 'shouldSetGeometryAccessibilityAttributes', v: 1 }, { p: 'dataWatcher', c: 'dataWatcher.shouldSetGeometryAriaLabels', cLabel: 'shouldSetGeometryAriaLabels', v: 1 }, { p: 'dataWatcher', c: 'dataWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'dataWatcher', c: 'dataWatcher.shouldSetTextures', cLabel: 'shouldSetTextures', v: 1 }, { p: 'dataWatcher', c: 'dataWatcher.shouldSetStrokes', cLabel: 'shouldSetStrokes', v: 1 }, { p: 'dataWatcher', c: 'dataWatcher.shouldSetColors', cLabel: 'shouldSetColors', v: 1 }, { p: 'mainTitle', c: 'titleWatcher', cLabel: 'titleWatcher', v: 1 }, { p: 'titleWatcher', c: 'titleWatcher.shouldValidate', cLabel: 'shouldValidate', v: 1 }, { p: 'titleWatcher', c: 'titleWatcher.shouldUpdateDescriptionWrapper', cLabel: 'shouldUpdateDescriptionWrapper', v: 1 }, { p: 'titleWatcher', c: 'titleWatcher.shouldSetChartAccessibilityTitle', cLabel: 'shouldSetChartAccessibilityTitle', v: 1 }, { p: 'titleWatcher', c: 'titleWatcher.shouldSetParentSVGAccessibility', cLabel: 'shouldSetParentSVGAccessibility', v: 1 }, { p: 'subTitle', c: 'subtitleWatcher', cLabel: 'subtitleWatcher', v: 1 }, { p: 'subtitleWatcher', c: 'subtitleWatcher.shouldSetChartAccessibilitySubtitle', cLabel: 'shouldSetChartAccessibilitySubtitle', v: 1 }, { p: 'subtitleWatcher', c: 'subtitleWatcher.shouldSetParentSVGAccessibility', cLabel: 'shouldSetParentSVGAccessibility', v: 1 }, { p: 'highestHeadingLevel', c: 'headingWatcher', cLabel: 'headingWatcher', v: 1 }, { p: 'headingWatcher', c: 'headingWatcher.shouldRedrawWrapper', cLabel: 'shouldRedrawWrapper', v: 1 }, { p: 'headingWatcher', c: 'headingWatcher.shouldSetTagLevels', cLabel: 'shouldSetTagLevels', v: 1 }, { p: 'headingWatcher', c: 'headingWatcher.shouldSetChartAccessibilityCount', cLabel: 'shouldSetChartAccessibilityCount', v: 1 }, { p: 'headingWatcher', c: 'headingWatcher.shouldUpdateDescriptionWrapper', cLabel: 'shouldUpdateDescriptionWrapper', v: 1 }, { p: 'headingWatcher', c: 'headingWatcher.shouldSetChartAccessibilityTitle', cLabel: 'shouldSetChartAccessibilityTitle', v: 1 }, { p: 'headingWatcher', c: 'headingWatcher.shouldSetChartAccessibilitySubtitle', cLabel: 'shouldSetChartAccessibilitySubtitle', v: 1 }, { p: 'headingWatcher', c: 'headingWatcher.shouldSetChartAccessibilityLongDescription', cLabel: 'shouldSetChartAccessibilityLongDescription', v: 1 }, { p: 'headingWatcher', c: 'headingWatcher.shouldSetChartAccessibilityContext', cLabel: 'shouldSetChartAccessibilityContext', v: 1 }, { p: 'headingWatcher', c: 'headingWatcher.shouldSetChartAccessibilityExecutiveSummary', cLabel: 'shouldSetChartAccessibilityExecutiveSummary', v: 1 }, { p: 'headingWatcher', c: 'headingWatcher.shouldSetChartAccessibilityPurpose', cLabel: 'shouldSetChartAccessibilityPurpose', v: 1 }, { p: 'headingWatcher', c: 'headingWatcher.shouldSetChartAccessibilityStatisticalNotes', cLabel: 'shouldSetChartAccessibilityStatisticalNotes', v: 1 }, { p: 'headingWatcher', c: 'headingWatcher.shouldSetChartAccessibilityStructureNotes', cLabel: 'shouldSetChartAccessibilityStructureNotes', v: 1 }, { p: 'parentAccessor', c: 'clusterWatcher', cLabel: 'clusterWatcher', v: 1 }, { p: 'clusterWatcher', c: 'clusterWatcher.shouldUpdateData', cLabel: 'shouldUpdateData', v: 1 }, { p: 'clusterWatcher', c: 'clusterWatcher.shouldUpdateTableData', cLabel: 'shouldUpdateTableData', v: 1 }, { p: 'clusterWatcher', c: 'clusterWatcher.shouldZoom', cLabel: 'shouldZoom', v: 1 }, { p: 'clusterWatcher', c: 'clusterWatcher.shouldAddStrokeUnder', cLabel: 'shouldAddStrokeUnder', v: 1 }, { p: 'clusterWatcher', c: 'clusterWatcher.shouldSetGeometryAriaLabels', cLabel: 'shouldSetGeometryAriaLabels', v: 1 }, { p: 'clusterWatcher', c: 'clusterWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'nodeAccessor', c: 'nodeWatcher', cLabel: 'nodeWatcher', v: 1 }, { p: 'nodeWatcher', c: 'nodeWatcher.shouldUpdateData', cLabel: 'shouldUpdateData', v: 1 }, { p: 'nodeWatcher', c: 'nodeWatcher.shouldUpdateTableData', cLabel: 'shouldUpdateTableData', v: 1 }, { p: 'nodeWatcher', c: 'nodeWatcher.shouldZoom', cLabel: 'shouldZoom', v: 1 }, { p: 'nodeWatcher', c: 'nodeWatcher.shouldAddStrokeUnder', cLabel: 'shouldAddStrokeUnder', v: 1 }, { p: 'nodeWatcher', c: 'nodeWatcher.shouldSetGeometryAriaLabels', cLabel: 'shouldSetGeometryAriaLabels', v: 1 }, { p: 'nodeWatcher', c: 'nodeWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'sizeAccessor', c: 'sizeWatcher', cLabel: 'sizeWatcher', v: 1 }, { p: 'sizeWatcher', c: 'sizeWatcher.shouldUpdateData', cLabel: 'shouldUpdateData', v: 1 }, { p: 'sizeWatcher', c: 'sizeWatcher.shouldUpdateTableData', cLabel: 'shouldUpdateTableData', v: 1 }, { p: 'sizeWatcher', c: 'sizeWatcher.shouldSetGeometryAriaLabels', cLabel: 'shouldSetGeometryAriaLabels', v: 1 }, { p: 'sizeWatcher', c: 'sizeWatcher.shouldZoom', cLabel: 'shouldZoom', v: 1 }, { p: 'height', c: 'heightWatcher', cLabel: 'heightWatcher', v: 1 }, { p: 'width', c: 'widthWatcher', cLabel: 'widthWatcher', v: 1 }, { p: 'padding', c: 'paddingWatcher', cLabel: 'paddingWatcher', v: 1 }, { p: 'margin', c: 'marginWatcher', cLabel: 'marginWatcher', v: 1 }, { p: 'heightWatcher', c: 'heightWatcher.shouldUpdateLayout', cLabel: 'shouldUpdateLayout', v: 1 }, { p: 'heightWatcher', c: 'heightWatcher.shouldResetRoot', cLabel: 'shouldResetRoot', v: 1 }, { p: 'heightWatcher', c: 'heightWatcher.shouldUpdateData', cLabel: 'shouldUpdateData', v: 1 }, { p: 'heightWatcher', c: 'heightWatcher.shouldZoom', cLabel: 'shouldZoom', v: 1 }, { p: 'heightWatcher', c: 'heightWatcher.shouldAddStrokeUnder', cLabel: 'shouldAddStrokeUnder', v: 1 }, { p: 'widthWatcher', c: 'widthWatcher.shouldUpdateLayout', cLabel: 'shouldUpdateLayout', v: 1 }, { p: 'widthWatcher', c: 'widthWatcher.shouldResetRoot', cLabel: 'shouldResetRoot', v: 1 }, { p: 'widthWatcher', c: 'widthWatcher.shouldUpdateData', cLabel: 'shouldUpdateData', v: 1 }, { p: 'widthWatcher', c: 'widthWatcher.shouldZoom', cLabel: 'shouldZoom', v: 1 }, { p: 'widthWatcher', c: 'widthWatcher.shouldAddStrokeUnder', cLabel: 'shouldAddStrokeUnder', v: 1 }, { p: 'paddingWatcher', c: 'paddingWatcher.shouldUpdateLayout', cLabel: 'shouldUpdateLayout', v: 1 }, { p: 'paddingWatcher', c: 'paddingWatcher.shouldResetRoot', cLabel: 'shouldResetRoot', v: 1 }, { p: 'paddingWatcher', c: 'paddingWatcher.shouldUpdateData', cLabel: 'shouldUpdateData', v: 1 }, { p: 'paddingWatcher', c: 'paddingWatcher.shouldZoom', cLabel: 'shouldZoom', v: 1 }, { p: 'paddingWatcher', c: 'paddingWatcher.shouldAddStrokeUnder', cLabel: 'shouldAddStrokeUnder', v: 1 }, { p: 'marginWatcher', c: 'marginWatcher.shouldUpdateLayout', cLabel: 'shouldUpdateLayout', v: 1 }, { p: 'marginWatcher', c: 'marginWatcher.shouldResetRoot', cLabel: 'shouldResetRoot', v: 1 }, { p: 'marginWatcher', c: 'marginWatcher.shouldUpdateData', cLabel: 'shouldUpdateData', v: 1 }, { p: 'marginWatcher', c: 'marginWatcher.shouldZoom', cLabel: 'shouldZoom', v: 1 }, { p: 'marginWatcher', c: 'marginWatcher.shouldAddStrokeUnder', cLabel: 'shouldAddStrokeUnder', v: 1 }, { p: 'dataDepth', c: 'dataDepthWatcher', cLabel: 'dataDepthWatcher', v: 1 }, { p: 'dataDepthWatcher', c: 'dataDepthWatcher.shouldUpdateData', cLabel: 'shouldUpdateData', v: 1 }, { p: 'dataDepthWatcher', c: 'dataDepthWatcher.shouldSetColors', cLabel: 'shouldSetColors', v: 1 }, { p: 'dataDepthWatcher', c: 'dataDepthWatcher.shouldZoom', cLabel: 'shouldZoom', v: 1 }, { p: 'displayDepth', c: 'displayDepthWatcher', cLabel: 'displayDepthWatcher', v: 1 }, { p: 'displayDepthWatcher', c: 'displayDepthWatcher.shouldUpdateDisplayDepth', cLabel: 'shouldUpdateDisplayDepth', v: 1 }, { p: 'displayDepthWatcher', c: 'displayDepthWatcher.shouldZoom', cLabel: 'shouldZoom', v: 1 }, { p: 'circlePadding', c: 'circlePaddingWatcher', cLabel: 'circlePaddingWatcher', v: 1 }, { p: 'circlePaddingWatcher', c: 'circlePaddingWatcher.shouldUpdateData', cLabel: 'shouldUpdateData', v: 1 }, { p: 'circlePaddingWatcher', c: 'circlePaddingWatcher.shouldZoom', cLabel: 'shouldZoom', v: 1 }, { p: 'colors', c: 'colorsWatcher', cLabel: 'colorsWatcher', v: 1 }, { p: 'colorPalette', c: 'colorPaletteWatcher', cLabel: 'colorPaletteWatcher', v: 1 }, { p: 'colorsWatcher', c: 'colorsWatcher.shouldSetColors', cLabel: 'shouldSetColors', v: 1 }, { p: 'colorsWatcher', c: 'colorsWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'colorsWatcher', c: 'colorsWatcher.shouldSetTextures', cLabel: 'shouldSetTextures', v: 1 }, { p: 'colorsWatcher', c: 'colorsWatcher.shouldSetStrokes', cLabel: 'shouldSetStrokes', v: 1 }, { p: 'colorPaletteWatcher', c: 'colorPaletteWatcher.shouldSetColors', cLabel: 'shouldSetColors', v: 1 }, { p: 'colorPaletteWatcher', c: 'colorPaletteWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'colorPaletteWatcher', c: 'colorPaletteWatcher.shouldSetTextures', cLabel: 'shouldSetTextures', v: 1 }, { p: 'colorPaletteWatcher', c: 'colorPaletteWatcher.shouldSetStrokes', cLabel: 'shouldSetStrokes', v: 1 }, { p: 'showTooltip', c: 'showTooltipWatcher', cLabel: 'showTooltipWatcher', v: 1 }, { p: 'showTooltipWatcher', c: 'showTooltipWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'tooltipLabel', c: 'tooltipLabelWatcher', cLabel: 'tooltipLabelWatcher', v: 1 }, { p: 'tooltipLabelWatcher', c: 'tooltipLabelWatcher.shouldUpdateTableData', cLabel: 'shouldUpdateTableData', v: 1 }, { p: 'hoverOpacity', c: 'hoverOpacityWatcher', cLabel: 'hoverOpacityWatcher', v: 1 }, { p: 'hoverOpacityWatcher', c: 'hoverOpacityWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'clickStyle', c: 'interactionStyleWatcher', cLabel: 'interactionStyleWatcher', v: 1 }, { p: 'hoverStyle', c: 'hoverStyleWatcher', cLabel: 'hoverStyleWatcher', v: 1 }, { p: 'interactionStyleWatcher', c: 'interactionStyleWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'interactionStyleWatcher', c: 'interactionStyleWatcher.shouldSetTextures', cLabel: 'shouldSetTextures', v: 1 }, { p: 'interactionStyleWatcher', c: 'interactionStyleWatcher.shouldSetStrokes', cLabel: 'shouldSetStrokes', v: 1 }, { p: 'interactionStyleWatcher', c: 'interactionStyleWatcher.shouldSetColors', cLabel: 'shouldSetColors', v: 1 }, { p: 'hoverStyleWatcher', c: 'hoverStyleWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'hoverStyleWatcher', c: 'hoverStyleWatcher.shouldSetTextures', cLabel: 'shouldSetTextures', v: 1 }, { p: 'hoverStyleWatcher', c: 'hoverStyleWatcher.shouldSetStrokes', cLabel: 'shouldSetStrokes', v: 1 }, { p: 'hoverStyleWatcher', c: 'hoverStyleWatcher.shouldSetColors', cLabel: 'shouldSetColors', v: 1 }, { p: 'cursor', c: 'cursorWatcher', cLabel: 'cursorWatcher', v: 1 }, { p: 'cursorWatcher', c: 'cursorWatcher.shouldUpdateCursor', cLabel: 'shouldUpdateCursor', v: 1 }, { p: 'clickHighlight', c: 'clickWatcher', cLabel: 'clickWatcher', v: 1 }, { p: 'clickWatcher', c: 'clickWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'hoverHighlight', c: 'hoverWatcher', cLabel: 'hoverWatcher', v: 1 }, { p: 'hoverWatcher', c: 'hoverWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'zoomToNode', c: 'zoomWatcher', cLabel: 'zoomWatcher', v: 1 }, { p: 'zoomWatcher', c: 'zoomWatcher.shouldZoom', cLabel: 'shouldZoom', v: 1 }, { p: 'interactionKeys', c: 'interactionWatcher', cLabel: 'interactionWatcher', v: 1 }, { p: 'interactionWatcher', c: 'interactionWatcher.shouldValidateInteractionKeys', cLabel: 'shouldValidateInteractionKeys', v: 1 }, { p: 'interactionWatcher', c: 'interactionWatcher.shouldUpdateTableData', cLabel: 'shouldUpdateTableData', v: 1 }, { p: 'interactionWatcher', c: 'interactionWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'interactionWatcher', c: 'interactionWatcher.shouldSetGeometryAriaLabels', cLabel: 'shouldSetGeometryAriaLabels', v: 1 }, { p: 'dataLabel', c: 'labelWatcher', cLabel: 'labelWatcher', v: 1 }, { p: 'labelWatcher', c: 'labelWatcher.shouldUpdateTableData', cLabel: 'shouldUpdateTableData', v: 1 }, { p: 'labelWatcher', c: 'labelWatcher.shouldUpdateLabels', cLabel: 'shouldUpdateLabels', v: 1 }, { p: 'labelWatcher', c: 'labelWatcher.shouldAddStrokeUnder', cLabel: 'shouldAddStrokeUnder', v: 1 }, { p: 'accessibility', c: 'accessibilityWatcher', cLabel: 'accessibilityWatcher', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldValidate', cLabel: 'shouldValidate', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldUpdateDescriptionWrapper', cLabel: 'shouldUpdateDescriptionWrapper', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldSetChartAccessibilityTitle', cLabel: 'shouldSetChartAccessibilityTitle', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldSetParentSVGAccessibility', cLabel: 'shouldSetParentSVGAccessibility', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldSetChartAccessibilityExecutiveSummary', cLabel: 'shouldSetChartAccessibilityExecutiveSummary', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldSetChartAccessibilityPurpose', cLabel: 'shouldSetChartAccessibilityPurpose', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldSetChartAccessibilityLongDescription', cLabel: 'shouldSetChartAccessibilityLongDescription', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldSetChartAccessibilityContext', cLabel: 'shouldSetChartAccessibilityContext', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldSetChartAccessibilityStatisticalNotes', cLabel: 'shouldSetChartAccessibilityStatisticalNotes', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldSetChartAccessibilityStructureNotes', cLabel: 'shouldSetChartAccessibilityStructureNotes', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldSetGroupAccessibilityLabel', cLabel: 'shouldSetGroupAccessibilityLabel', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldSetGeometryAriaLabels', cLabel: 'shouldSetGeometryAriaLabels', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldSetParentSVGAccessibility', cLabel: 'shouldSetParentSVGAccessibility', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldSetTextures', cLabel: 'shouldSetTextures', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldSetStrokes', cLabel: 'shouldSetStrokes', v: 1 }, { p: 'accessibilityWatcher', c: 'accessibilityWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'annotations', c: 'annotationsWatcher', cLabel: 'annotationsWatcher', v: 1 }, { p: 'annotationsWatcher', c: 'annotationsWatcher.shouldValidate', cLabel: 'shouldValidate', v: 1 }, { p: 'annotationsWatcher', c: 'annotationsWatcher.shouldUpdateAnnotations', cLabel: 'shouldUpdateAnnotations', v: 1 }, { p: 'uniqueID', c: 'idWatcher', cLabel: 'idWatcher', v: 1 }, { p: 'idWatcher', c: 'idWatcher.chartID', cLabel: 'chartID', v: 1 }, { p: 'idWatcher', c: 'idWatcher.shouldValidate', cLabel: 'shouldValidate', v: 1 }, { p: 'idWatcher', c: 'idWatcher.shouldUpdateDescriptionWrapper', cLabel: 'shouldUpdateDescriptionWrapper', v: 1 }, { p: 'idWatcher', c: 'idWatcher.shouldSetParentSVGAccessibility', cLabel: 'shouldSetParentSVGAccessibility', v: 1 }, { p: 'idWatcher', c: 'idWatcher.shouldSetTextures', cLabel: 'shouldSetTextures', v: 1 }, { p: 'idWatcher', c: 'idWatcher.shouldDrawInteractionState', cLabel: 'shouldDrawInteractionState', v: 1 }, { p: 'idWatcher', c: 'idWatcher.shouldSetStrokes', cLabel: 'shouldSetStrokes', v: 1 }, { p: 'idWatcher', c: 'idWatcher.shouldSetTextStrokes', cLabel: 'shouldSetTextStrokes', v: 1 }, { p: 'idWatcher', c: 'idWatcher.shouldSetIDs', cLabel: 'shouldSetIDs', v: 1 }, { p: 'suppressEvents', c: 'suppressWatcher', cLabel: 'suppressWatcher', v: 1 }, { p: 'suppressWatcher', c: 'suppressWatcher.shouldBindInteractivity', cLabel: 'shouldBindInteractivity', v: 1 }, { p: 'suppressWatcher', c: 'suppressWatcher.shouldUpdateCursor', cLabel: 'shouldUpdateCursor', v: 1 } ]; updateClick(item) { if (Array.isArray(item)) { item.length === 0 || this.clickElement === item ? (this.clickElement = []) : (this.clickElement = item); } else { item === '' || this.clickElement === item ? (this.clickElement = []) : (this.clickElement = [item]); } } drawChart() { return <div>{this.clickElement}</div>; } onClickCountryFunc(d) { if (d.detail && d.detail.location_id > 100) { this.clickElement = [d.detail]; } } onClickFunc(d) { if (d.detail) { const alreadyClicked = this.clickElement.filter(e => e.id === d.detail.id).length > 0; this.clickElement = alreadyClicked ? [] : [d.detail]; //toggle this to test that zoomToNode works watcher works as expected this.zoomTo = !this.zoomTo ? d.detail : this.zoomTo.id !== d.detail.id ? d.detail : undefined; // this.zoomTo = this.lifeCycleStates[1][1]; } } changeProps() { this.size = Math.max(100, this.size + Math.floor(Math.random() * (Math.random() < 0.5 ? -100 : 100))); } changeData() { this.stateTrigger = this.stateTrigger < this.lifeCycleStates.length - 1 ? this.stateTrigger + 1 : 0; } changeAccessElements() { this.accessibility = { ...this.accessibility, elementsAreInterface: !this.accessibility.elementsAreInterface }; } changeKeyNav() { const keyboardNavConfig = { disabled: !this.accessibility.keyboardNavConfig.disabled }; this.accessibility = { ...this.accessibility, keyboardNavConfig }; } toggleSuppress() { this.suppressEvents = !this.suppressEvents; } onHoverFunc(d) { this.hoverElement = d.detail; } onMouseOut() { this.hoverElement = ''; } onBigHoverFunc(d) { this.bigHoverElement = d.detail; } onBigMouseOut() { this.bigHoverElement = ''; } onBigClickFunc(d) { if (d.detail) { const alreadyClicked = this.bigClickElement.filter(e => e.id === d.detail.id).length > 0; this.bigClickElement = alreadyClicked ? [] : [d.detail]; this.bigZoomTo = !this.bigZoomTo ? d.detail : this.bigZoomTo.id !== d.detail.id ? d.detail : undefined; } } changeNodeAccessor() { this.nodeAccessor = this.nodeAccessor !== 'Type' ? 'Type' : 'altType'; this.parentAccessor = this.parentAccessor !== 'Country' ? 'Country' : 'altCountry'; } changeHeight() { this.height = this.height !== 400 ? 400 : 200; } changeWidth() { this.width = this.height !== 400 ? 400 : 100; } // changeParentAccessor() { // this.nodeAccessor = this.nodeAccessor !== 'Type' ? 'Type' : 'altType'; // this.parentAccessor = this.parentAccessor !== 'Country' ? 'Country' : 'altCountry'; // } changeSizeAccessor() { this.sizeAccessor = this.sizeAccessor !== 'value' ? 'value' : 'altValue'; } toggleAnimations() { this.animations = { disabled: !this.animations.disabled }; } render() { this.lifeCycleTestData = this.lifeCycleStates[this.index]; this.chartData = this.lifeCycleStates[this.stateTrigger]; // tslint:disable-next-line:no-unused-expression // const cat = ['Sketch', 'SQL', 'React']; return ( <div style={{ padding: '50px' }}> <button onClick={() => { this.changeAccessElements(); }} > change elementsAreInterface </button> <button onClick={() => { this.toggleSuppress(); }} > toggle event suppression </button> <button onClick={() => { this.changeKeyNav(); }} > toggle keyboard nav </button> <button onClick={() => { this.changeData(); }} > change data </button> <button onClick={() => { this.changeNodeAccessor(); }} > change node & parent accessor </button> <button onClick={() => { this.changeHeight(); }} > change height </button> <button onClick={() => { this.changeWidth(); }} > change width </button> <button onClick={() => { this.toggleAnimations(); }} > Toggle Animations </button> {/* <button onClick={() => { this.changeParentAccessor(); }} > change parent accessor </button> */} <button onClick={() => { this.changeSizeAccessor(); }} > change size accessor </button> <div style={{ display: 'flex', flexDirection: 'row' }}> {/* <circle-packing data={this.chartData} nodeAccessor={this.nodeAccessor} parentAccessor={this.parentAccessor} sizeAccessor={this.sizeAccessor} height={this.height} width={this.width} animationConfig={this.animations} // nodeAccessor={'Type'} // parentAccessor={'Country'} // sizeAccessor={'value'} subTitle={''} mainTitle={'Chart Height is ' + this.height + 'px and Width is ' + this.width} displayDepth={1} // hoverStyle={{ // strokeWidth: 2, // color: '#fafafa' // }} // clickStyle={{ // strokeWidth: 4, // color: '#e4e4e4' // }} colors={['white', 'white', 'white']} dataLabel={this.dataLabel} onHoverFunc={d => this.onHoverFunc(d)} onClickFunc={d => this.onClickFunc(d)} onMouseOutFunc={() => this.onMouseOut()} clickHighlight={this.clickElement} hoverHighlight={this.hoverElement} zoomToNode={this.zoomTo} accessibility={{ ...this.accessibility, hideTextures: true }} suppressEvents={this.suppressEvents} circlePadding={3} /> */} </div> <div style={{ display: 'flex', flexDirection: 'row' }}> <circle-packing data={this.circlePackComponentData} nodeAccessor="c" parentAccessor="p" sizeAccessor="v" height={this.height} width={this.width} subTitle={''} mainTitle={'Circle Packing Component Structure'} displayDepth={4} dataDepth={5} dataLabel={this.dataLabel} tooltipLabel={{ labelAccessor: ['p', 'cLabel'], labelTitle: ['Caller', 'Callee'], format: ['', ''] }} // hoverStyle={{ // strokeWidth: 2, // color: '#fafafa' // }} // clickStyle={{ // strokeWidth: 4, // color: '#e4e4e4' // }} colors={['white', 'white', 'white', 'white', 'white', 'white']} onHoverFunc={d => this.onHoverFunc(d)} onClickFunc={d => this.onClickFunc(d)} onMouseOutFunc={() => this.onMouseOut()} clickHighlight={this.clickElement} hoverHighlight={this.hoverElement} zoomToNode={this.zoomTo} // annotations={this.annotations} accessibility={{ ...this.accessibility, hideTextures: true }} circlePadding={3} /> </div> </div> ); } }
the_stack
import * as babel from '@babel/types'; import {ElementMixin} from '..'; import * as jsdocLib from '../javascript/jsdoc'; import {AstNodeWithLanguage, Document, Feature, Method, Privacy, Property, Resolvable, ScannedFeature, ScannedMethod, ScannedProperty, ScannedReference, Severity, SourceRange, Warning} from '../model/model'; import {ParsedDocument} from '../parser/document'; import {DeclaredWithStatement} from './document'; import {Demo} from './element-base'; import {ImmutableMap, unsafeAsMutable} from './immutable'; /** * Represents a JS class as encountered in source code. * * We only emit a ScannedClass when there's not a more specific kind of feature. * Like, we don't emit a ScannedClass when we encounter an element or a mixin * (though in the future those features will likely extend from * ScannedClass/Class). * * TODO(rictic): currently there's a ton of duplicated code across the Class, * Element, Mixin, PolymerElement, and PolymerMixin classes. We should * really unify this stuff to a single representation and set of algorithms. */ export class ScannedClass implements ScannedFeature, Resolvable { readonly name: string|undefined; /** The name of the class in the local scope where it is defined. */ readonly localName: string|undefined; readonly astNode: AstNodeWithLanguage; readonly statementAst: babel.Statement|undefined; readonly jsdoc: jsdocLib.Annotation; readonly description: string; readonly summary: string; readonly sourceRange: SourceRange; readonly properties: Map<string, ScannedProperty>; readonly staticMethods: ImmutableMap<string, ScannedMethod>; readonly methods: ImmutableMap<string, ScannedMethod>; readonly constructorMethod?: ScannedMethod; readonly superClass: ScannedReference<'class'>|undefined; // TODO: add a 'mixin' type independent of elements, use that here. readonly mixins: ScannedReference<'element-mixin'>[]; readonly abstract: boolean; readonly privacy: Privacy; readonly warnings: Warning[]; readonly demos: Demo[]; constructor( className: string|undefined, localClassName: string|undefined, astNode: AstNodeWithLanguage, statementAst: babel.Statement|undefined, jsdoc: jsdocLib.Annotation, description: string, sourceRange: SourceRange, properties: Map<string, ScannedProperty>, methods: Map<string, ScannedMethod>, constructorMethod: ScannedMethod|undefined, staticMethods: Map<string, ScannedMethod>, superClass: ScannedReference<'class'>|undefined, mixins: Array<ScannedReference<'element-mixin'>>, privacy: Privacy, warnings: Warning[], abstract: boolean, demos: Demo[]) { this.name = className; this.localName = localClassName; this.astNode = astNode; this.statementAst = statementAst; this.jsdoc = jsdoc; this.description = description; this.sourceRange = sourceRange; this.properties = properties; this.methods = methods; this.constructorMethod = constructorMethod; this.staticMethods = staticMethods; this.superClass = superClass; this.mixins = mixins; this.privacy = privacy; this.warnings = warnings; this.abstract = abstract; const summaryTag = jsdocLib.getTag(jsdoc, 'summary'); this.summary = (summaryTag && summaryTag.description) || ''; this.demos = demos; } resolve(document: Document): Feature|undefined { return new Class(this, document); } /** * Allows additional properties and methods * to be added to the class after initialization. * For example, members found attached to the * prototype at a later place in the document */ finishInitialization( methods: Map<string, ScannedMethod>, properties: Map<string, ScannedProperty>) { const mutableMethods = unsafeAsMutable(this.methods); for (const [name, method] of methods) { mutableMethods.set(name, method); } for (const [name, prop] of properties) { this.properties.set(name, prop); } } } declare module '../model/queryable' { interface FeatureKindMap { 'class': Class; } } export interface ClassInit { readonly sourceRange: SourceRange|undefined; readonly astNode: AstNodeWithLanguage|undefined; readonly statementAst: babel.Statement|undefined; readonly warnings?: Warning[]; readonly summary: string; // TODO(rictic): we don't need both name and className here. readonly name?: string; readonly className?: string; readonly jsdoc?: jsdocLib.Annotation; readonly description: string; readonly properties?: ImmutableMap<string, Property>; readonly staticMethods: ImmutableMap<string, Method>; readonly methods?: ImmutableMap<string, Method>; readonly constructorMethod?: Method; readonly superClass?: ScannedReference<'class'>|undefined; // TODO: add a 'mixin' type independent of elements, use that here. readonly mixins?: Array<ScannedReference<'element-mixin'>>; readonly abstract: boolean; readonly privacy: Privacy; readonly demos?: Demo[]; } export class Class implements Feature, DeclaredWithStatement { readonly kinds = new Set(['class']); readonly identifiers = new Set<string>(); readonly sourceRange: SourceRange|undefined; readonly astNode: AstNodeWithLanguage|undefined; readonly statementAst: babel.Statement|undefined; readonly warnings: Warning[]; readonly summary: string; readonly name: string|undefined; /** * @deprecated use the `name` field instead. */ get className() { return this.name; } readonly jsdoc: jsdocLib.Annotation|undefined; description: string; readonly properties = new Map<string, Property>(); readonly methods = new Map<string, Method>(); constructorMethod?: Method; readonly staticMethods = new Map<string, Method>(); readonly superClass: ScannedReference<'class'>|undefined; /** * Mixins that this class declares with `@mixes`. * * Mixins are applied linearly after the superclass, in order from first * to last. Mixins that compose other mixins will be flattened into a * single list. A mixin can be applied more than once, each time its * members override those before it in the prototype chain. */ readonly mixins: ReadonlyArray<ScannedReference<'element-mixin'>> = []; readonly abstract: boolean; readonly privacy: Privacy; demos: Demo[]; private readonly _parsedDocument: ParsedDocument; constructor(init: ClassInit, document: Document) { ({ jsdoc: this.jsdoc, description: this.description, summary: this.summary, abstract: this.abstract, privacy: this.privacy, astNode: this.astNode, statementAst: this.statementAst, sourceRange: this.sourceRange } = init); this._parsedDocument = document.parsedDocument; this.warnings = init.warnings === undefined ? [] : Array.from(init.warnings); this.demos = [...init.demos || [], ...jsdocLib.extractDemos(init.jsdoc)]; this.name = init.name || init.className; if (this.name) { this.identifiers.add(this.name); } if (init.superClass) { this.superClass = init.superClass; } this.mixins = (init.mixins || []); this.constructorMethod = init.constructorMethod; const superClassLikes = this._getSuperclassAndMixins(document, init); for (const superClassLike of superClassLikes) { this.inheritFrom(superClassLike); } if (init.properties !== undefined) { this._overwriteInherited( this.properties, init.properties, undefined, true); } if (init.methods !== undefined) { this._overwriteInherited(this.methods, init.methods, undefined, true); } if (init.constructorMethod !== undefined) { this.constructorMethod = this._overwriteSingleInherited( this.constructorMethod, init.constructorMethod, undefined); } if (init.staticMethods !== undefined) { this._overwriteInherited( this.staticMethods, init.staticMethods, undefined, true); } } protected inheritFrom(superClass: Class) { this._overwriteInherited( this.staticMethods, superClass.staticMethods, superClass.name); this._overwriteInherited( this.properties, superClass.properties, superClass.name); this._overwriteInherited(this.methods, superClass.methods, superClass.name); this.constructorMethod = this._overwriteSingleInherited( this.constructorMethod, superClass.constructorMethod, superClass.name); } /** * This method is applied to an array of members to overwrite members lower in * the prototype graph (closer to Object) with members higher up (closer to * the final class we're constructing). * * @param . existing The array of members so far. N.B. *This param is * mutated.* * @param . overriding The array of members from this new, higher prototype in * the graph * @param . overridingClassName The name of the prototype whose members are * being applied over the existing ones. Should be `undefined` when * applyingSelf is true * @param . applyingSelf True on the last call to this method, when we're * applying the class's own local members. */ protected _overwriteInherited<P extends PropertyLike>( existing: Map<string, P>, overriding: ImmutableMap<string, P>, overridingClassName: string|undefined, applyingSelf = false) { for (const [key, overridingVal] of overriding) { const newVal = Object.assign({}, overridingVal, { inheritedFrom: overridingVal['inheritedFrom'] || overridingClassName }); if (existing.has(key)) { /** * TODO(rictic): if existingVal.privacy is protected, newVal should be * protected unless an explicit privacy was specified. * https://github.com/Polymer/polymer-analyzer/issues/631 */ const existingValue = existing.get(key)!; if (existingValue.privacy === 'private') { let warningSourceRange = this.sourceRange!; if (applyingSelf) { warningSourceRange = newVal.sourceRange || this.sourceRange!; } this.warnings.push(new Warning({ code: 'overriding-private', message: `Overriding private member '${overridingVal.name}' ` + `inherited from ${existingValue.inheritedFrom || 'parent'}`, sourceRange: warningSourceRange, severity: Severity.WARNING, parsedDocument: this._parsedDocument, })); } } existing.set(key, newVal); } } /** * This method is applied to a single member to overwrite members lower in * the prototype graph (closer to Object) with members higher up (closer to * the final class we're constructing). * * @param . existing The existin property on the class * @param . overriding The array of members from this new, higher prototype in * the graph * @param . overridingClassName The name of the prototype whose members are * being applied over the existing ones. Should be `undefined` when * applyingSelf is true * @param . applyingSelf True on the last call to this method, when we're * applying the class's own local members. */ protected _overwriteSingleInherited<P extends PropertyLike>( existing: P|undefined, overridingVal: P|undefined, overridingClassName: string|undefined): P|undefined { if (!overridingVal) { return existing; } return Object.assign({}, overridingVal, { inheritedFrom: overridingVal['inheritedFrom'] || overridingClassName }); } /** * Returns the elementLikes that make up this class's prototype chain. * * Should return them in the order that they're constructed in JS * engine (i.e. closest to HTMLElement first, closest to `this` last). */ protected _getSuperclassAndMixins(document: Document, _init: ClassInit) { const mixins = this.mixins.map((m) => this._resolveReferenceToSuperClass(m, document)); const superClass = this._resolveReferenceToSuperClass(this.superClass, document); const prototypeChain: Class[] = []; if (superClass) { prototypeChain.push(superClass); } for (const mixin of mixins) { if (mixin) { prototypeChain.push(mixin); } } return prototypeChain; } protected _resolveReferenceToSuperClass( scannedReference: ScannedReference<'class'|'element-mixin'>|undefined, document: Document): Class|ElementMixin|undefined { if (!scannedReference || scannedReference.identifier === 'HTMLElement') { return undefined; } const reference = scannedReference.resolve(document); if (reference.warnings.length > 0) { this.warnings.push(...reference.warnings); } return reference.feature; } emitMetadata(): object { return {}; } emitPropertyMetadata(_property: Property): object { return {}; } emitMethodMetadata(_method: Method): object { return {}; } } export interface PropertyLike { name: string; sourceRange?: SourceRange; inheritedFrom?: string; privacy?: Privacy; }
the_stack
import * as angular from 'angular'; import {moduleName} from "./module-name"; //import OpsManagerFeedService from "../../services/OpsManagerFeedService"; //import Nvd3ChartService from "../../services/Nvd3ChartService"; //import {FeedStatsService} from "./FeedStatsService" const d3 = require('d3'); import * as _ from "underscore"; import * as moment from "moment"; import {DateTimeUtils} from '../../../common/utils/DateTimeUtils'; export default class controller{ dataLoaded:boolean = false; /** flag when processor chart is loading **/ processChartLoading:boolean = false; /** * the last time the data was refreshed * @type {null} */ lastProcessorChartRefresh: any = null; /** * last time the execution graph was refreshed * @type {null} */ lastFeedTimeChartRefresh:any = null; /** flag when the feed time chart is loading **/ showFeedTimeChartLoading:boolean = false; showProcessorChartLoading:boolean = false; statusPieChartApi:any = {}; /** * Initial Time Frame setting * @type {string} */ timeFrame:string = 'FIVE_MIN'; /** * Array of fixed times * @type {Array} */ timeframeOptions:any[] = []; /** * last time the page was refreshed * @type {null} */ lastRefreshTime:any = null; /** * map of the the timeFrame value to actual timeframe object (i.e. FIVE_MIN:{timeFrameObject}) * @type {{}} */ timeFramOptionsLookupMap:any = {}; /** * The selected Time frame * @type {{}} */ selectedTimeFrameOptionObject:any = {}; /** * Flag to enable disable auto refresh * @type {boolean} */ autoRefresh:boolean = true; /** * Flag to indicate if we are zoomed or not * @type {boolean} */ isZoomed:boolean = false; /** * Zoom helper * @type {boolean} */ isAtInitialZoom:boolean = true; /** * Difference in overall min/max time for the chart * Used to help calcuate the correct xXais label (i.e. for larger time periods show Date + time, else show time * @type {null} */ timeDiff:number = null; /** * millis to wait after a zoom is complete to update the charts * @type {number} */ ZOOM_DELAY:number = 700; /** * Constant set to indicate we are not zoomed * @type {number} */ UNZOOMED_VALUE:number = -1; /** * After a chart is rendered it will always call the zoom function. * Flag to prevent the initial zoom from triggering after refresh of the chart * @type {boolean} */ preventZoomChange:boolean = false; /** * Timeout promise to prevent zoom * @type {undefined} */ preventZoomPromise:angular.IPromise<any> = undefined; /** * The Min Date of data. This will be the zoomed value if we are zooming, otherwise the min value in the dataset */ minDisplayTime:any; /** * The max date of the data. this will be the zoomed value if zooming otherwise the max value in the dataset */ maxDisplayTime:any; /** * max Y value (when not zoomed) * @type {number} */ maxY:number = 0; minY:number = 0; /** * max Y Value when zoomed * @type {number} */ zoomMaxY:number = 0; zoomMinY:number = 0; /** * Min time frame to enable zooming. * Defaults to 30 min. * Anything less than this will not be zoomable * @type {number} */ minZoomTime:number = 1000*60*30; /** * Flag to indicate if zooming is enabled. * Zooming is only enabled for this.minZoomTime or above * * @type {boolean} */ zoomEnabled:boolean = false; /** * A bug in nvd3 charts exists where if the zoom is toggle to true it requires a force of the x axis when its toggled back to false upon every data refresh. * this flag will be triggered when the zoom enabled changes and from then on it will manually reset the x domain when the data refreshes * @type {boolean} */ forceXDomain:boolean = false; /** * Flag to force the rendering of the chart to refresh * @type {boolean} */ forceChartRefresh:boolean = false; /** * Summary stats should come from the service * @type {*} */ summaryStatistics:any; feedChartLegendState:any[] = []; feedChartData:any[] = []; feedChartApi:any = {}; feedChartOptions:any = {}; processorChartApi:any = {}; processorChartData:any[] = []; processorChartOptions:any = {}; selectedProcessorStatisticFunction:string = 'Average Duration'; processorStatsFunctions:any; /** * The Feed we are looking at * @type {{displayStatus: string}} */ feed:any = { displayStatus: '' }; /** * Latest summary stats * @type {{}} */ summaryStatsData:any = {}; eventSuccessKpi:any = { value: 0, icon: '', color: '' }; flowRateKpi:any = { value: 0, icon: 'tune', color: '#1f77b4' }; avgDurationKpi:any = { value: 0, icon: 'access_time', color: '#1f77b4' }; /** * Errors for th error table (if any) * @type {*} */ feedProcessorErrorsTable:any = { sortOrder: '-errorMessageTimestamp', filter: '', rowLimit: 5, page: 1 }; feedProcessorErrors: any; zoomedMinTime: any; zoomedMaxTime: any; changeZoomPromise: any; minTime: any; maxTime: any; timeFrameOptions: any; timeFrameOptionIndex: any; displayLabel: string; feedTimeChartLoading: any; feedProcessorErrorsLoading: any; feedName: string; refreshInterval: angular.IPromise<any>; refreshIntervalTime: number; timeFrameOptionIndexLength: any; constructor(private $scope: angular.IScope, private $element: angular.IAugmentedJQuery, private $http: angular.IHttpService, private $interval: angular.IIntervalService, private $timeout: angular.ITimeoutService, private $q: angular.IQService, private $mdToast: angular.material.IToastService, private ProvenanceEventStatsService: any, private FeedStatsService: any, private Nvd3ChartService: any, private OpsManagerFeedService: any, private StateService: any, private $filter: angular.IFilterService){ this.showFeedTimeChartLoading = true; this.showProcessorChartLoading = true; this.summaryStatistics = FeedStatsService.summaryStatistics; this.processorStatsFunctions = FeedStatsService.processorStatsFunctions(); this.feedProcessorErrors = FeedStatsService.feedProcessorErrors; } /** * When a user clicks the Refresh Button */ onRefreshButtonClick () { this.refresh(); }; /** * Navigate to the Feed Manager Feed Details * @param ev */ gotoFeedDetails(ev: any){ if (this.feed.feedId != undefined) { this.StateService.FeedManager().Feed().navigateToFeedDetails(this.feed.feedId); } }; /** * Show detailed Errors */ viewNewFeedProcessorErrors (){ this.feedProcessorErrors.viewAllData(); }; toggleFeedProcessorErrorsRefresh(autoRefresh: boolean) { if (autoRefresh) { this.feedProcessorErrors.viewAllData(); this.feedProcessorErrors.autoRefreshMessage = 'enabled'; } else { this.feedProcessorErrors.autoRefreshMessage = 'disabled'; } }; /** * Called when a user click on the Reset Zoom button */ onResetZoom(){ if(this.isZoomed) { this.initiatePreventZoom(); this.resetZoom(); this.feedChartOptions.chart.xDomain = [this.minTime,this.maxTime] this.feedChartOptions.chart.yDomain = [this.minY,this.maxY] this.feedChartApi.refresh(); this.buildProcessorChartData(); } } /** * prevent the initial zoom to fire in chart after reload */ initiatePreventZoom(){ var cancelled = false; if(angular.isDefined(this.preventZoomPromise)) { this.$timeout.cancel(this.preventZoomPromise); this.preventZoomPromise = undefined; cancelled =true; } if(!this.preventZoomChange || cancelled) { this.preventZoomChange = true; this.preventZoomPromise = this.$timeout(()=> { this.preventZoomChange = false; this.preventZoomPromise = undefined; }, 1000); } } /** * Help adjust the x axis label depending on time window * @param d */ private timeSeriesXAxisLabel(d:number){ var maxTime = 1000*60*60*12; //12 hrs if(this.timeDiff >=maxTime ){ //show the date if it spans larger than maxTime return d3.time.format('%Y-%m-%d %H:%M')(new Date(d)) } else { return d3.time.format('%X')(new Date(d)) } } /** * Prevent zooming into a level of detail that the data doesnt allow * Stats > a day are aggregated up to the nearest hour * Stats > 10 hours are aggregated up to the nearest minute * If a user is looking at data within the 2 time frames above, prevent the zoom to a level greater than the hour/minute * @param xDomain * @param yDomain * @return {boolean} */ private canZoom(xDomain:number[], yDomain:number[]) { var diff = this.maxTime - this.minTime; var minX = Math.floor(xDomain[0]); var maxX = Math.floor(xDomain[1]); var zoomDiff = maxX - minX; //everything above the day should be zoomed at the hour level //everything above 10 hrs should be zoomed at the minute level if(diff >= (1000*60*60*24)){ if(zoomDiff < (1000*60*60)){ return false //prevent zooming! } } else if(diff >= (1000*60*60*10)) { // zoom at minute level if(zoomDiff < (1000*60)){ return false; } } return true; }; /** * Initialize the Charts */ setupChartOptions() { let self = this; this.processorChartOptions = { chart: { type: 'multiBarHorizontalChart', height: 400, margin: { top: 5, //otherwise top of numeric value is cut off right: 50, bottom: 50, //otherwise bottom labels are not visible left: 150 }, duration: 500, x: (d: any)=> { return d.label.length > 60 ? d.label.substr(0, 60) + "..." : d.label; }, y: (d: any)=> { return d.value; }, showControls: false, showValues: true, xAxis: { showMaxMin: false }, interactiveLayer: {tooltip: {gravity: 's'}}, yAxis: { axisLabel: self.FeedStatsService.processorStatsFunctionMap[self.selectedProcessorStatisticFunction].axisLabel, tickFormat: (d: any)=> { return d3.format(',.2f')(d); } }, valueFormat: (d: any)=> { return d3.format(',.2f')(d); }, noData: self.$filter('translate')('view.feed-stats-charts.noData') } } this.feedChartOptions = { chart: { type: 'lineChart', height: 450, margin: { top: 10, right: 20, bottom: 110, left: 65 }, x: (d: any)=> { return d[0]; }, y: (d: any)=> { return d3.format('.2f')(d[1]); }, showTotalInTooltip: true, interpolate: 'linear', useVoronoi: false, duration: 250, clipEdge:false, useInteractiveGuideline: true, interactiveLayer: {tooltip: {gravity: 's'}}, valueFormat: (d: any)=> { return d3.format(',')(parseInt(d)) }, xAxis: { axisLabel: self.$filter('translate')('view.feed-stats-charts.Time'), showMaxMin: false, tickFormat: (d:number) =>self.timeSeriesXAxisLabel(d), rotateLabels: -45 }, yAxis: { axisLabel: this.$filter('translate')('view.feed-stats-charts.FPS'), axisLabelDistance: -10 }, legend: { dispatch: { stateChange: (e: any)=>{ self.feedChartLegendState = e.disabled; } } }, //https://github.com/krispo/angular-nvd3/issues/548 zoom: { enabled: false, scale: 1, scaleExtent: [1, 50], verticalOff: true, unzoomEventType: 'dblclick.zoom', useFixedDomain:false, zoomed: (xDomain: any, yDomain: any)=> { //zoomed will get called initially (even if not zoomed) // because of this we need to check to ensure the 'preventZoomChange' flag was not triggered after initially refreshing the dataset if(!self.preventZoomChange) { self.isZoomed = true; if(self.canZoom(xDomain,yDomain)) { self.zoomedMinTime = Math.floor(xDomain[0]); self.zoomedMaxTime = Math.floor(xDomain[1]); self.timeDiff = self.zoomedMaxTime - self.zoomedMinTime; var max1 = Math.ceil(yDomain[0]); var max2 = Math.ceil(yDomain[1]); self.zoomMaxY = max2 > max1 ? max2 : max1; } return {x1: self.zoomedMinTime, x2: self.zoomedMaxTime, y1: yDomain[0], y2: yDomain[1]}; } else { return {x1: self.minTime, x2: self.maxTime, y1: self.minY, y2: self.maxY} } }, unzoomed: (xDomain: any, yDomain: any)=> { return self.resetZoom(); } }, interactiveLayer2: { //interactiveLayer dispatch: { elementClick: (t: any, u: any)=> {} } }, dispatch: { } } }; } /** * Reset the Zoom and return the x,y values pertaining to the min/max of the complete dataset * @return {{x1: *, x2: (*|number|endTime|{name, fn}|Number), y1: number, y2: (number|*)}} */ resetZoom(){ if(this.isZoomed) { this.isZoomed = false; this.zoomedMinTime = this.UNZOOMED_VALUE; this.zoomedMaxTime = this.UNZOOMED_VALUE; this.minDisplayTime=this.minTime; this.maxDisplayTime =this.maxTime; this.timeDiff = this.maxTime - this.minTime; return {x1: this.minTime, x2: this.maxTime, y1: this.minY, y2: this.maxY} } } changeZoom(){ this.timeDiff = this.zoomedMaxTime- this.zoomedMinTime; this.autoRefresh = false; this.isZoomed = true; this.isAtInitialZoom = true; // FeedStatsService.setTimeBoundaries(this.minTime, this.maxTime); this.buildProcessorChartData(); this.minDisplayTime=this.zoomedMinTime; this.maxDisplayTime =this.zoomedMaxTime /* if(this.zoomedMinTime != UNZOOMED_VALUE) { //reset x xaxis to the zoom values this.feedChartOptions.chart.xDomain = [this.zoomedMinTime,this.zoomedMaxTime] var y = this.zoomMaxY > 0 ? this.zoomMaxY : this.maxY; this.feedChartOptions.chart.yDomain = [0,this.maxY] } else { this.feedChartOptions.chart.xDomain = [this.minTime,this.maxTime]; this.feedChartOptions.chart.yDomain = [0,this.maxY] } this.feedChartApi.update(); */ } /** * Cancel the zoom timeout watcher */ cancelPreviousOnZoomed(){ if (!_.isUndefined(this.changeZoomPromise)) { this.$timeout.cancel(this.changeZoomPromise); this.changeZoomPromise = undefined; } } onTimeFrameChanged(){ if (!_.isUndefined(this.timeFrameOptions)) { this.timeFrame = this.timeFrameOptions[Math.floor(this.timeFrameOptionIndex)].value; this.displayLabel = this.timeFrameOptions[Math.floor(this.timeFrameOptionIndex)].label; this.isZoomed = false; this.zoomedMinTime = this.UNZOOMED_VALUE; this.zoomedMaxTime = this.UNZOOMED_VALUE; this.initiatePreventZoom(); this.onTimeFrameChanged2(this.timeFrame); } } /* $scope.$watch( //update time frame when slider is moved function () { return this.timeFrameOptionIndex; }, function () { if (!_.isUndefined(this.timeFrameOptions)) { this.timeFrame = this.timeFrameOptions[Math.floor(this.timeFrameOptionIndex)].value; this.displayLabel = this.timeFrame.label; this.isZoomed = false; this.zoomedMinTime = UNZOOMED_VALUE; this.zoomedMaxTime = UNZOOMED_VALUE; onTimeFrameChanged(this.timeFrame); } } ); */ refresh(){ var to = new Date().getTime(); var millis = this.timeFrameOptions[this.timeFrameOptionIndex].properties.millis; var from = to - millis; this.minDisplayTime = from; this.maxDisplayTime = to; this.FeedStatsService.setTimeBoundaries(from, to); this.buildChartData(true); } enableZoom(){ this.zoomEnabled = true; this.feedChartOptions.chart.zoom.enabled=true; this.forceChartRefresh = true; this.forceXDomain = true; } disableZoom(){ this.resetZoom(); this.zoomEnabled = false; this.feedChartOptions.chart.zoom.enabled=false; this.forceChartRefresh = true; } /** * When a user changes the Processor drop down * @type {onProcessorChartFunctionChanged} */ onProcessorChartFunctionChanged(){ this.FeedStatsService.setSelectedChartFunction(this.selectedProcessorStatisticFunction); var chartData = this.FeedStatsService.changeProcessorChartDataFunction(this.selectedProcessorStatisticFunction); this.processorChartData[0].values = chartData.data; this.FeedStatsService.updateBarChartHeight(this.processorChartOptions, this.processorChartApi, chartData.data.length, this.selectedProcessorStatisticFunction); } buildChartData(timeIntervalChange: boolean){ if (!this.FeedStatsService.isLoading()) { timeIntervalChange = angular.isUndefined(timeIntervalChange) ? false : timeIntervalChange; this.feedTimeChartLoading = true; this.processChartLoading = true; this.buildProcessorChartData(); this.buildFeedCharts(); this.fetchFeedProcessorErrors(timeIntervalChange); } this.getFeedHealth(); } updateSuccessEventsPercentKpi() { if (this.summaryStatsData.totalEvents == 0) { this.eventSuccessKpi.icon = 'remove'; this.eventSuccessKpi.color = "#1f77b4" this.eventSuccessKpi.value = "--"; } else { var failed = this.summaryStatsData.totalEvents > 0 ? (<any>(this.summaryStatsData.failedEvents / this.summaryStatsData.totalEvents)).toFixed(2) * 100 : 0; var value = (100 - failed).toFixed(0); var icon = 'offline_pin'; var iconColor = "#3483BA" this.eventSuccessKpi.icon = icon; this.eventSuccessKpi.color = iconColor; this.eventSuccessKpi.value = value } } updateFlowRateKpi() { this.flowRateKpi.value = this.summaryStatistics.flowsStartedPerSecond; } updateAvgDurationKpi(){ var avgMillis = this.summaryStatistics.avgFlowDurationMilis; this.avgDurationKpi.value = new DateTimeUtils(this.$filter('translate')).formatMillisAsText(avgMillis,false,true); } formatSecondsToMinutesAndSeconds(s:number) { // accepts seconds as Number or String. Returns m:ss return ( s - ( s %= 60 )) / 60 + (9 < s ? ':' : ':0' ) + s; } updateSummaryKpis() { this.updateFlowRateKpi(); this.updateSuccessEventsPercentKpi(); this.updateAvgDurationKpi(); } buildProcessorChartData() { var values = []; this.processChartLoading = true; var minTime = undefined; var maxTime = undefined; if(this.isZoomed && this.zoomedMinTime != this.UNZOOMED_VALUE) { //reset x xaxis to the zoom values minTime=this.zoomedMinTime; maxTime =this.zoomedMaxTime } this.$q.when( this.FeedStatsService.fetchProcessorStatistics(minTime,maxTime)).then((response: any)=> { this.summaryStatsData = this.FeedStatsService.summaryStatistics; this.updateSummaryKpis(); this.processorChartData = this.FeedStatsService.buildProcessorDurationChartData(); this.FeedStatsService.updateBarChartHeight(this.processorChartOptions, this.processorChartApi, this.processorChartData[0].values.length, this.selectedProcessorStatisticFunction); this.processChartLoading = false; this.lastProcessorChartRefresh = new Date().getTime(); this.lastRefreshTime = new Date(); }, ()=> { this.processChartLoading = false; this.lastProcessorChartRefresh = new Date().getTime(); }); } buildFeedCharts() { this.feedTimeChartLoading = true; this.$q.when( this.FeedStatsService.fetchFeedTimeSeriesData()).then( (feedTimeSeries: any)=> { this.minTime = feedTimeSeries.time.startTime; this.maxTime = feedTimeSeries.time.endTime; this.timeDiff = this.maxTime - this.minTime; var chartArr = []; chartArr.push({ label: this.$filter('translate')('view.feed-stats-charts.Completed'), color: '#9c27b0', valueFn: function (item: any) { return item.jobsFinishedPerSecond; } }); chartArr.push({ label: this.$filter('translate')('view.feed-stats-charts.Started'), area: true, color: "#2196f3", valueFn: function (item: any) { return item.jobsStartedPerSecond; } }); //preserve the legend selections if ( this.feedChartLegendState.length > 0) { _.each(chartArr, (item:any, i: any)=> { item.disabled = this.feedChartLegendState[i]; }); } this.feedChartData = this.Nvd3ChartService.toLineChartData(feedTimeSeries.raw.stats, chartArr, 'minEventTime', null,this.minTime, this.maxTime); var max = this.Nvd3ChartService.determineMaxY(this.feedChartData); if(this.isZoomed) { max = this.zoomMaxY; } var maxChanged = this.maxY < max; this.minY = 0; this.maxY = max; if(max <5){ max = 5; } this.feedChartOptions.chart.forceY = [0, max]; if (this.feedChartOptions.chart.yAxis.ticks != max) { this.feedChartOptions.chart.yDomain = [0, max]; var ticks = max; if (ticks > 8) { ticks = 8; } if(angular.isUndefined(ticks) || ticks <5){ ticks = 5; } this.feedChartOptions.chart.yAxis.ticks = ticks; } if(this.isZoomed && (this.forceXDomain == true || this.zoomedMinTime !=this.UNZOOMED_VALUE)) { //reset x xaxis to the zoom values this.feedChartOptions.chart.xDomain = [this.zoomedMinTime,this.zoomedMaxTime] var y = this.zoomMaxY > 0 ? this.zoomMaxY : this.maxY; this.feedChartOptions.chart.yDomain = [0,y] } else if(!this.isZoomed && this.forceXDomain){ this.feedChartOptions.chart.xDomain = [this.minTime,this.maxTime]; this.feedChartOptions.chart.yDomain = [0,this.maxY] } this.initiatePreventZoom(); if (this.feedChartApi && this.feedChartApi.refresh && this.feedChartApi.update) { if(maxChanged || this.forceChartRefresh ) { this.feedChartApi.refresh(); this.forceChartRefresh = false; } else { this.feedChartApi.update(); } } this.feedTimeChartLoading = false; this.lastFeedTimeChartRefresh = new Date().getTime(); }, ()=> { this.feedTimeChartLoading = false; this.lastFeedTimeChartRefresh = new Date().getTime(); }); } /** * fetch and append the errors to the FeedStatsService.feedProcessorErrors.data object * @param resetWindow optionally reset the feed errors to start a new array of errors in the feedProcessorErrors.data */ fetchFeedProcessorErrors(resetWindow: any) { this.feedProcessorErrorsLoading = true; this.$q.when(this.FeedStatsService.fetchFeedProcessorErrors(resetWindow)).then((feedProcessorErrors: any)=> { this.feedProcessorErrorsLoading = false; }, (err: any)=> { this.feedProcessorErrorsLoading = false; }); } /** * Gets the Feed Health */ getFeedHealth(){ var successFn = (response: any)=> { if (response.data) { //transform the data for UI if (response.data.feedSummary) { angular.extend(this.feed, response.data.feedSummary[0]); this.feed.feedId = this.feed.feedHealth.feedId; if (this.feed.running) { this.feed.displayStatus = 'RUNNING'; } else { this.feed.displayStatus = 'STOPPED'; } } } } var errorFn = (err: any)=> { } this.$http.get(this.OpsManagerFeedService.SPECIFIC_FEED_HEALTH_URL(this.feedName)).then(successFn, errorFn); } clearRefreshInterval() { if (this.refreshInterval != null) { this.$interval.cancel(this.refreshInterval); this.refreshInterval = null; } } setRefreshInterval() { this.clearRefreshInterval(); if (this.autoRefresh ) { // anything below 5 minute interval to be refreshed every 5 seconds, // anything above 5 minutes to be refreshed in proportion to its time span, i.e. the longer the time span the less it is refreshed var option = this.timeFramOptionsLookupMap[this.timeFrame]; if (!_.isUndefined(option)) { //timeframe option will be undefined when page loads for the first time var refreshInterval = option.properties.millis / 60; this.refreshIntervalTime = refreshInterval < 5000 ? 5000 : refreshInterval; } if (this.refreshIntervalTime) { this.refreshInterval = this.$interval(()=> { this.refresh(); }, this.refreshIntervalTime ); } } } /** * Initialize the charts */ initCharts() { this.FeedStatsService.setFeedName(this.feedName); this.setupChartOptions(); this.onRefreshButtonClick(); this.dataLoaded = true; } /** * Fetch and load the Time slider options */ loadTimeFrameOption() { this.ProvenanceEventStatsService.getTimeFrameOptions().then((response: any)=> { this.timeFrameOptions = response.data; this.timeFrameOptionIndexLength = this.timeFrameOptions.length; _.each(response.data, (labelValue: any)=> { this.timeFramOptionsLookupMap[labelValue.value] = labelValue; }); this.$timeout(()=> { //update initial slider position in UI this.timeFrameOptionIndex = _.findIndex(this.timeFrameOptions, (option: any)=> { return option.value === this.timeFrame; }); this.initCharts(); }, 1); }); } /** * When the controller is ready, initialize */ $onInit(): void { /** * Enable/disable the refresh interval */ this.$scope.$watch( ()=> { return this.autoRefresh; }, (newVal: any, oldVal: any)=> { if (!this.autoRefresh) { this.clearRefreshInterval(); //toast this.$mdToast.show( this.$mdToast.simple() .textContent('Auto refresh disabled') .hideDelay(3000) ); } else { this.setRefreshInterval(); this.$mdToast.show( this.$mdToast.simple() .textContent('Auto refresh enabled') .hideDelay(3000) ); } } ); /** * Watch when a zoom is active. */ this.$scope.$watch( ()=> { return this.zoomedMinTime; }, (newVal: any, oldVal: any)=> { if (!_.isUndefined(this.zoomedMinTime) && this.zoomedMinTime > 0) { // if (this.isAtInitialZoom) { // this.isAtInitialZoom = false; // } else { this.cancelPreviousOnZoomed(); this.changeZoomPromise = this.$timeout(this.changeZoom, this.ZOOM_DELAY); // } } } ); this.$scope.$on('$destroy', ()=> { this.clearRefreshInterval(); this.cancelPreviousOnZoomed(); }); this.loadTimeFrameOption(); } /** * When the slider is changed refresh the charts/data * @param timeFrame */ onTimeFrameChanged2(timeFrame?: any) { if(this.isZoomed){ this.resetZoom(); } this.isAtInitialZoom = true; this.timeFrame = timeFrame; var millis = this.timeFrameOptions[this.timeFrameOptionIndex].properties.millis; if(millis >= this.minZoomTime){ this.enableZoom(); } else { this.disableZoom(); } this.clearRefreshInterval(); this.refresh(); //disable refresh if > 30 min timeframe if(millis >(1000*60*30)){ this.autoRefresh = false; } else { if(!this.autoRefresh) { this.autoRefresh = true; } else { this.setRefreshInterval(); } } } } angular.module(moduleName) .controller('FeedStatsChartsController', ["$scope", "$element", "$http", "$interval", "$timeout", "$q","$mdToast", "ProvenanceEventStatsService", "FeedStatsService", "Nvd3ChartService", "OpsManagerFeedService", "StateService", "$filter", controller]); angular.module(moduleName) .directive('kyloFeedStatsCharts', [ ()=> { return { restrict: "EA", scope: {}, bindToController: { panelTitle: "@", refreshIntervalTime: "@", feedName: '@' }, controllerAs: 'vm', templateUrl: 'js/ops-mgr/feeds/feed-stats/feed-stats-charts.html', controller: "FeedStatsChartsController", link: function ($scope, element, attrs) { $scope.$on('$destroy', function () { }); } //DOM manipulation\} } } ]);
the_stack
import { LibMathRevertErrors } from '@0x/contracts-exchange-libs'; import { blockchainTests, constants, expect, verifyEventsFromLogs } from '@0x/contracts-test-utils'; import { AssetProxyId, RevertReason } from '@0x/types'; import { BigNumber } from '@0x/utils'; import * as _ from 'lodash'; import { DydxBridgeActionType, DydxBridgeData, dydxBridgeDataEncoder } from '../src/dydx_bridge_encoder'; import { ERC20BridgeProxyContract, IAssetDataContract } from '../src/wrappers'; import { artifacts } from './artifacts'; import { TestDydxBridgeContract, TestDydxBridgeEvents } from './wrappers'; blockchainTests.resets('DydxBridge unit tests', env => { const defaultAccountNumber = new BigNumber(1); const marketId = new BigNumber(2); const defaultAmount = new BigNumber(4); const notAuthorized = '0x0000000000000000000000000000000000000001'; const defaultDepositAction = { actionType: DydxBridgeActionType.Deposit, accountIdx: constants.ZERO_AMOUNT, marketId, conversionRateNumerator: constants.ZERO_AMOUNT, conversionRateDenominator: constants.ZERO_AMOUNT, }; const defaultWithdrawAction = { actionType: DydxBridgeActionType.Withdraw, accountIdx: constants.ZERO_AMOUNT, marketId, conversionRateNumerator: constants.ZERO_AMOUNT, conversionRateDenominator: constants.ZERO_AMOUNT, }; let testContract: TestDydxBridgeContract; let testProxyContract: ERC20BridgeProxyContract; let assetDataEncoder: IAssetDataContract; let owner: string; let authorized: string; let accountOwner: string; let receiver: string; before(async () => { // Get accounts const accounts = await env.web3Wrapper.getAvailableAddressesAsync(); [owner, authorized, accountOwner, receiver] = accounts; // Deploy dydx bridge testContract = await TestDydxBridgeContract.deployFrom0xArtifactAsync( artifacts.TestDydxBridge, env.provider, env.txDefaults, artifacts, [accountOwner, receiver], ); // Deploy test erc20 bridge proxy testProxyContract = await ERC20BridgeProxyContract.deployFrom0xArtifactAsync( artifacts.ERC20BridgeProxy, env.provider, env.txDefaults, artifacts, ); await testProxyContract.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); // Setup asset data encoder assetDataEncoder = new IAssetDataContract(constants.NULL_ADDRESS, env.provider); }); describe('bridgeTransferFrom()', () => { const callBridgeTransferFrom = async ( from: string, to: string, amount: BigNumber, bridgeData: DydxBridgeData, sender: string, ): Promise<string> => { const returnValue = await testContract .bridgeTransferFrom( constants.NULL_ADDRESS, from, to, amount, dydxBridgeDataEncoder.encode({ bridgeData }), ) .callAsync({ from: sender }); return returnValue; }; const executeBridgeTransferFromAndVerifyEvents = async ( from: string, to: string, amount: BigNumber, bridgeData: DydxBridgeData, sender: string, ): Promise<void> => { // Execute transaction. const txReceipt = await testContract .bridgeTransferFrom( constants.NULL_ADDRESS, from, to, amount, dydxBridgeDataEncoder.encode({ bridgeData }), ) .awaitTransactionSuccessAsync({ from: sender }); // Verify `OperateAccount` event. const expectedOperateAccountEvents = []; for (const accountNumber of bridgeData.accountNumbers) { expectedOperateAccountEvents.push({ owner: accountOwner, number: accountNumber, }); } verifyEventsFromLogs(txReceipt.logs, expectedOperateAccountEvents, TestDydxBridgeEvents.OperateAccount); // Verify `OperateAction` event. const weiDenomination = 0; const deltaAmountRef = 0; const expectedOperateActionEvents = []; for (const action of bridgeData.actions) { expectedOperateActionEvents.push({ actionType: action.actionType as number, accountIdx: action.accountIdx, amountSign: action.actionType === DydxBridgeActionType.Deposit ? true : false, amountDenomination: weiDenomination, amountRef: deltaAmountRef, amountValue: action.conversionRateDenominator.gt(0) ? amount .times(action.conversionRateNumerator) .dividedToIntegerBy(action.conversionRateDenominator) : amount, primaryMarketId: marketId, secondaryMarketId: constants.ZERO_AMOUNT, otherAddress: action.actionType === DydxBridgeActionType.Deposit ? from : to, otherAccountId: constants.ZERO_AMOUNT, data: '0x', }); } verifyEventsFromLogs(txReceipt.logs, expectedOperateActionEvents, TestDydxBridgeEvents.OperateAction); }; it('succeeds when calling with zero amount', async () => { const bridgeData = { accountNumbers: [defaultAccountNumber], actions: [defaultDepositAction], }; await executeBridgeTransferFromAndVerifyEvents( accountOwner, receiver, constants.ZERO_AMOUNT, bridgeData, authorized, ); }); it('succeeds when calling with no accounts', async () => { const bridgeData = { accountNumbers: [], actions: [defaultDepositAction], }; await executeBridgeTransferFromAndVerifyEvents( accountOwner, receiver, defaultAmount, bridgeData, authorized, ); }); it('succeeds when calling with no actions', async () => { const bridgeData = { accountNumbers: [defaultAccountNumber], actions: [], }; await executeBridgeTransferFromAndVerifyEvents( accountOwner, receiver, defaultAmount, bridgeData, authorized, ); }); it('succeeds when calling `operate` with the `deposit` action and a single account', async () => { const bridgeData = { accountNumbers: [defaultAccountNumber], actions: [defaultDepositAction], }; await executeBridgeTransferFromAndVerifyEvents( accountOwner, receiver, defaultAmount, bridgeData, authorized, ); }); it('succeeds when calling `operate` with the `deposit` action and multiple accounts', async () => { const bridgeData = { accountNumbers: [defaultAccountNumber, defaultAccountNumber.plus(1)], actions: [defaultDepositAction], }; await executeBridgeTransferFromAndVerifyEvents( accountOwner, receiver, defaultAmount, bridgeData, authorized, ); }); it('succeeds when calling `operate` with the `withdraw` action and a single account', async () => { const bridgeData = { accountNumbers: [defaultAccountNumber], actions: [defaultWithdrawAction], }; await executeBridgeTransferFromAndVerifyEvents( accountOwner, receiver, defaultAmount, bridgeData, authorized, ); }); it('succeeds when calling `operate` with the `withdraw` action and multiple accounts', async () => { const bridgeData = { accountNumbers: [defaultAccountNumber, defaultAccountNumber.plus(1)], actions: [defaultWithdrawAction], }; await executeBridgeTransferFromAndVerifyEvents( accountOwner, receiver, defaultAmount, bridgeData, authorized, ); }); it('succeeds when calling `operate` with the `deposit` action and multiple accounts', async () => { const bridgeData = { accountNumbers: [defaultAccountNumber, defaultAccountNumber.plus(1)], actions: [defaultWithdrawAction, defaultDepositAction], }; await executeBridgeTransferFromAndVerifyEvents( accountOwner, receiver, defaultAmount, bridgeData, authorized, ); }); it('succeeds when calling `operate` with multiple actions under a single account', async () => { const bridgeData = { accountNumbers: [defaultAccountNumber], actions: [defaultWithdrawAction, defaultDepositAction], }; await executeBridgeTransferFromAndVerifyEvents( accountOwner, receiver, defaultAmount, bridgeData, authorized, ); }); it('succeeds when scaling the `amount` to deposit', async () => { const conversionRateNumerator = new BigNumber(1); const conversionRateDenominator = new BigNumber(2); const bridgeData = { accountNumbers: [defaultAccountNumber], actions: [ defaultWithdrawAction, { ...defaultDepositAction, conversionRateNumerator, conversionRateDenominator, }, ], }; await executeBridgeTransferFromAndVerifyEvents( accountOwner, receiver, defaultAmount, bridgeData, authorized, ); }); it('succeeds when scaling the `amount` to withdraw', async () => { const conversionRateNumerator = new BigNumber(1); const conversionRateDenominator = new BigNumber(2); const bridgeData = { accountNumbers: [defaultAccountNumber], actions: [ defaultDepositAction, { ...defaultWithdrawAction, conversionRateNumerator, conversionRateDenominator, }, ], }; await executeBridgeTransferFromAndVerifyEvents( accountOwner, receiver, defaultAmount, bridgeData, authorized, ); }); it('reverts if not called by the ERC20 Bridge Proxy', async () => { const bridgeData = { accountNumbers: [defaultAccountNumber], actions: [defaultDepositAction], }; const callBridgeTransferFromPromise = callBridgeTransferFrom( accountOwner, receiver, defaultAmount, bridgeData, notAuthorized, ); const expectedError = RevertReason.DydxBridgeOnlyCallableByErc20BridgeProxy; return expect(callBridgeTransferFromPromise).to.revertWith(expectedError); }); it('should return magic bytes if call succeeds', async () => { const bridgeData = { accountNumbers: [defaultAccountNumber], actions: [defaultDepositAction], }; const returnValue = await callBridgeTransferFrom( accountOwner, receiver, defaultAmount, bridgeData, authorized, ); expect(returnValue).to.equal(AssetProxyId.ERC20Bridge); }); it('should revert when `Operate` reverts', async () => { // Set revert flag. await testContract.setRevertOnOperate(true).awaitTransactionSuccessAsync(); // Execute transfer. const bridgeData = { accountNumbers: [defaultAccountNumber], actions: [defaultDepositAction], }; const tx = callBridgeTransferFrom(accountOwner, receiver, defaultAmount, bridgeData, authorized); const expectedError = 'TestDydxBridge/SHOULD_REVERT_ON_OPERATE'; return expect(tx).to.revertWith(expectedError); }); it('should revert when there is a rounding error', async () => { // Setup a rounding error const conversionRateNumerator = new BigNumber(5318); const conversionRateDenominator = new BigNumber(47958); const amount = new BigNumber(9000); const bridgeData = { accountNumbers: [defaultAccountNumber], actions: [ defaultDepositAction, { ...defaultWithdrawAction, conversionRateNumerator, conversionRateDenominator, }, ], }; // Execute transfer and assert error. const tx = callBridgeTransferFrom(accountOwner, receiver, amount, bridgeData, authorized); const expectedError = new LibMathRevertErrors.RoundingError( conversionRateNumerator, conversionRateDenominator, amount, ); return expect(tx).to.revertWith(expectedError); }); }); describe('ERC20BridgeProxy.transferFrom()', () => { const bridgeData = { accountNumbers: [defaultAccountNumber], actions: [defaultWithdrawAction], }; let assetData: string; before(async () => { const testTokenAddress = await testContract.getTestToken().callAsync(); assetData = assetDataEncoder .ERC20Bridge(testTokenAddress, testContract.address, dydxBridgeDataEncoder.encode({ bridgeData })) .getABIEncodedTransactionData(); }); it('should succeed if `bridgeTransferFrom` succeeds', async () => { await testProxyContract .transferFrom(assetData, accountOwner, receiver, defaultAmount) .awaitTransactionSuccessAsync({ from: authorized }); }); it('should revert if `bridgeTransferFrom` reverts', async () => { // Set revert flag. await testContract.setRevertOnOperate(true).awaitTransactionSuccessAsync(); const tx = testProxyContract .transferFrom(assetData, accountOwner, receiver, defaultAmount) .awaitTransactionSuccessAsync({ from: authorized }); const expectedError = 'TestDydxBridge/SHOULD_REVERT_ON_OPERATE'; return expect(tx).to.revertWith(expectedError); }); }); });
the_stack
import { VssueAPI } from 'vssue'; import MockAdapter from 'axios-mock-adapter'; import fixtures from './fixtures'; import GithubV3 from '../src/index'; import { normalizeUser, normalizeIssue, normalizeComment, normalizeReactions, } from '../src/utils'; const baseURL = 'https://github.com'; const APIEndpoint = 'https://api.github.com'; const options = { owner: 'owner', repo: 'repo', clientId: 'clientId', clientSecret: 'clientSecret', state: 'state', labels: fixtures.issue.labels.map(item => item.name), proxy: url => `https://porxy/${url}`, }; const API = new GithubV3(options); const mock = new MockAdapter(API.$http); const mockCode = 'test-code'; const mockToken = 'test-token'; describe('properties', () => { test('common properties', () => { expect(API.owner).toBe(options.owner); expect(API.repo).toBe(options.repo); expect(API.clientId).toBe(options.clientId); expect(API.clientSecret).toBe(options.clientSecret); expect(API.state).toBe(options.state); expect(API.labels).toBe(options.labels); expect(API.proxy).toBe(options.proxy); expect(API.platform.name).toBe('GitHub'); expect(API.platform.version).toBe('v3'); }); test('with default baseURL', () => { expect(API.baseURL).toBe(baseURL); expect(API.platform.link).toBe(baseURL); expect(API.$http.defaults.baseURL).toBe(APIEndpoint); }); test('with custom baseURL', () => { const customBaseURL = 'https://github.vssue.com'; const customAPIEndPoint = `${customBaseURL}/api/v3`; const customAPI = new GithubV3({ baseURL: customBaseURL, ...options, }); expect(customAPI.baseURL).toBe(customBaseURL); expect(customAPI.platform.link).toBe(customBaseURL); expect(customAPI.$http.defaults.baseURL).toBe(customAPIEndPoint); }); }); describe('methods', () => { afterEach(() => { mock.reset(); }); test('error', async () => { mock.onGet(new RegExp('/error')).reply(200, { error: 'error', error_description: 'error_description', }); await expect(API.$http.get('/error')).rejects.toThrowError( 'error_description' ); }); test('redirectAuth', () => { // to make `window.location` writable const location = window.location; delete window.location; const url = 'https://vssue.js.org'; window.location = { href: url } as any; API.redirectAuth(); expect(window.location.href).toBe( `${baseURL}/login/oauth/authorize?client_id=${ options.clientId }&redirect_uri=${encodeURIComponent(url)}&scope=public_repo&state=${ options.state }` ); // reset `window.location` window.location = location; }); describe('handleAuth', () => { beforeEach(() => { mock.onPost(new RegExp('login/oauth/access_token')).reply(200, { access_token: mockToken, }); }); test('without code', async () => { const url = `https://vssue.js.org/`; window.history.replaceState(null, '', url); const token = await API.handleAuth(); expect(mock.history.post.length).toBe(0); expect(window.location.href).toBe(url); expect(token).toBe(null); }); test('with matched state', async () => { const url = `https://vssue.js.org/?code=${mockCode}&state=${options.state}`; window.history.replaceState(null, '', url); const token = await API.handleAuth(); expect(mock.history.post.length).toBe(1); expect(window.location.href).toBe('https://vssue.js.org/'); expect(token).toBe(mockToken); }); test('with unmatched state', async () => { const url = `https://vssue.js.org/?code=${mockCode}&state=${options.state}-unmatched`; window.history.replaceState(null, '', url); const token = await API.handleAuth(); expect(mock.history.post.length).toBe(0); expect(window.location.href).toBe(url); expect(token).toBe(null); }); describe('getAccessToken', () => { test('with function proxy', async () => { const token = await API.getAccessToken({ code: mockCode }); expect(mock.history.post.length).toBe(1); const request = mock.history.post[0]; const data = JSON.parse(request.data); expect(request.url).toBe( options.proxy(`${baseURL}/login/oauth/access_token`) ); expect(request.method).toBe('post'); expect(data.client_id).toBe(options.clientId); expect(data.client_secret).toBe(options.clientSecret); expect(data.code).toBe(mockCode); expect(token).toBe(mockToken); }); test('with string proxy', async () => { const proxy = `https://string.proxy?target=${baseURL}/login/oauth/access_token`; API.proxy = proxy; const token = await API.getAccessToken({ code: mockCode }); expect(mock.history.post.length).toBe(1); const request = mock.history.post[0]; const data = JSON.parse(request.data); expect(request.url).toBe(proxy); expect(request.method).toBe('post'); expect(data.client_id).toBe(options.clientId); expect(data.client_secret).toBe(options.clientSecret); expect(data.code).toBe(mockCode); expect(token).toBe(mockToken); API.proxy = options.proxy; }); }); }); test('getUser', async () => { mock.onGet(new RegExp('/user$')).reply(200, fixtures.user); const user = await API.getUser({ accessToken: mockToken }); expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(request.headers.Authorization).toBe(`token ${mockToken}`); expect(user).toEqual(normalizeUser(fixtures.user)); }); describe('getIssue', () => { describe('with issue id', () => { const issueId = fixtures.issue.number; describe('issue exists', () => { beforeEach(() => { mock .onGet( new RegExp( `repos/${options.owner}/${options.repo}/issues/${issueId}$` ) ) .reply(200, fixtures.issue); }); test('login', async () => { const issue = (await API.getIssue({ issueId, accessToken: mockToken, })) as VssueAPI.Issue; expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(request.headers.Authorization).toBe(`token ${mockToken}`); expect(issue).toEqual(normalizeIssue(fixtures.issue)); }); test('not login', async () => { const issue = (await API.getIssue({ issueId, accessToken: null, })) as VssueAPI.Issue; expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(request.headers.Authorization).toBeUndefined(); expect(issue).toEqual(normalizeIssue(fixtures.issue)); }); }); test('issue does not exist', async () => { mock .onGet( new RegExp( `repos/${options.owner}/${options.repo}/issues/${issueId}$` ) ) .reply(404); const issue = await API.getIssue({ issueId, accessToken: null, }); expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(issue).toBe(null); }); test('error', async () => { mock .onGet( new RegExp( `repos/${options.owner}/${options.repo}/issues/${issueId}$` ) ) .reply(500); await expect( API.getIssue({ issueId, accessToken: null, }) ).rejects.toThrow(); expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); }); }); describe('with issue title', () => { const issueTitle = fixtures.issues.items[0].title; describe('issue exists', () => { beforeEach(() => { mock.onGet(new RegExp(`search/issues$`)).reply(200, fixtures.issues); }); test('login', async () => { const issue = (await API.getIssue({ issueTitle, accessToken: mockToken, })) as VssueAPI.Issue; expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(request.headers.Authorization).toBe(`token ${mockToken}`); expect(request.params.q).toEqual(expect.stringContaining(issueTitle)); expect(issue).toEqual(normalizeIssue(fixtures.issues.items[0])); }); test('not login', async () => { const issue = (await API.getIssue({ issueTitle, accessToken: null, })) as VssueAPI.Issue; expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(request.headers.Authorization).toBeUndefined(); expect(request.params.q).toEqual(expect.stringContaining(issueTitle)); expect(issue).toEqual(normalizeIssue(fixtures.issues.items[0])); }); }); test('issue does not exist', async () => { mock.onGet(new RegExp(`search/issues$`)).reply(200, { items: [] }); const issue = await API.getIssue({ issueTitle, accessToken: null, }); expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(issue).toBe(null); }); }); }); test('postIssue', async () => { const title = fixtures.issue.title; const content = fixtures.issue.body; mock .onPost(new RegExp(`repos/${options.owner}/${options.repo}/issues$`)) .reply(201, fixtures.issue); const issue = (await API.postIssue({ title, content, accessToken: mockToken, })) as VssueAPI.Issue; expect(mock.history.post.length).toBe(1); const request = mock.history.post[0]; expect(request.method).toBe('post'); expect(request.headers.Authorization).toBe(`token ${mockToken}`); const data = JSON.parse(request.data); expect(data.title).toBe(title); expect(data.body).toBe(content); expect(data.labels).toEqual(options.labels); expect(issue).toEqual(normalizeIssue(fixtures.issue)); }); describe('getComments', () => { const issueId = 1; beforeEach(() => { mock .onGet( new RegExp( `repos/${options.owner}/${options.repo}/issues/${issueId}$` ) ) .reply(200, fixtures.issue) .onGet( new RegExp( `repos/${options.owner}/${options.repo}/issues/${issueId}/comments$` ) ) .reply(200, fixtures.comments, { link: null }); }); test('login', async () => { /* eslint-disable-next-line no-unused-expressions */ (await API.getComments({ issueId, accessToken: mockToken, })) as VssueAPI.Comments; expect(mock.history.get.length).toBe(2); const requestIssue = mock.history.get[0]; expect(requestIssue.method).toBe('get'); expect(requestIssue.headers.Authorization).toBe(`token ${mockToken}`); const requestComments = mock.history.get[1]; expect(requestComments.method).toBe('get'); expect(requestComments.headers.Authorization).toBe(`token ${mockToken}`); }); test('not login', async () => { /* eslint-disable-next-line no-unused-expressions */ (await API.getComments({ issueId, accessToken: null, })) as VssueAPI.Comments; expect(mock.history.get.length).toBe(2); const requestIssue = mock.history.get[0]; expect(requestIssue.method).toBe('get'); expect(requestIssue.headers.Authorization).toBeUndefined(); const requestComments = mock.history.get[1]; expect(requestComments.method).toBe('get'); expect(requestComments.headers.Authorization).toBeUndefined(); }); describe('query', () => { const query = { page: 1, perPage: 10, }; test('common', async () => { const comments = (await API.getComments({ issueId, accessToken: mockToken, query, })) as VssueAPI.Comments; const request = mock.history.get[1]; expect(request.method).toBe('get'); expect(request.headers.Accept).toEqual( expect.arrayContaining([ 'application/vnd.github.v3.raw+json', 'application/vnd.github.v3.html+json', 'application/vnd.github.squirrel-girl-preview', ]) ); expect(request.params.page).toBe(query.page); expect(request.params.per_page).toBe(query.perPage); expect(request.params.sort).toBeUndefined(); expect(comments.count).toEqual(fixtures.comments.length); expect(comments.page).toEqual(query.page); expect(comments.perPage).toEqual(query.perPage); expect(comments.data).toEqual( fixtures.comments.slice(0, query.perPage).map(normalizeComment) ); }); test('default value', async () => { /* eslint-disable-next-line no-unused-expressions */ (await API.getComments({ issueId, accessToken: mockToken, query: {}, })) as VssueAPI.Comments; const request = mock.history.get[1]; expect(request.params.page).toBe(1); expect(request.params.per_page).toBe(10); expect(request.params.sort).toBeUndefined(); }); }); }); test('postComment', async () => { const issueId = 1; const content = fixtures.comment.body; mock .onPost( new RegExp( `repos/${options.owner}/${options.repo}/issues/${issueId}/comments$` ) ) .reply(201, fixtures.comment); const comment = (await API.postComment({ issueId, content, accessToken: mockToken, })) as VssueAPI.Comment; expect(mock.history.post.length).toBe(1); const request = mock.history.post[0]; expect(request.method).toBe('post'); expect(request.headers.Authorization).toBe(`token ${mockToken}`); expect(request.headers.Accept).toEqual( expect.arrayContaining([ 'application/vnd.github.v3.raw+json', 'application/vnd.github.v3.html+json', 'application/vnd.github.squirrel-girl-preview', ]) ); const data = JSON.parse(request.data); expect(data.body).toBe(content); expect(comment).toEqual(normalizeComment(fixtures.comment)); }); test('putComment', async () => { const issueId = 1; const commentId = fixtures.comment.id; const content = fixtures.comment.body; mock .onPatch( new RegExp( `repos/${options.owner}/${options.repo}/issues/comments/${commentId}$` ) ) .reply(200, fixtures.comment); const comment = (await API.putComment({ issueId, commentId, content, accessToken: mockToken, })) as VssueAPI.Comment; expect(mock.history.patch.length).toBe(1); const request = mock.history.patch[0]; expect(request.method).toBe('patch'); expect(request.headers.Authorization).toBe(`token ${mockToken}`); expect(request.headers.Accept).toEqual( expect.arrayContaining([ 'application/vnd.github.v3.raw+json', 'application/vnd.github.v3.html+json', 'application/vnd.github.squirrel-girl-preview', ]) ); const data = JSON.parse(request.data); expect(data.body).toBe(content); expect(comment).toEqual(normalizeComment(fixtures.comment)); }); test('deleteComment', async () => { const issueId = 1; const commentId = fixtures.comment.id; mock .onDelete( new RegExp( `repos/${options.owner}/${options.repo}/issues/comments/${commentId}$` ) ) .reply(204); const success = await API.deleteComment({ issueId, commentId, accessToken: mockToken, }); expect(mock.history.delete.length).toBe(1); const request = mock.history.delete[0]; expect(request.method).toBe('delete'); expect(request.headers.Authorization).toBe(`token ${mockToken}`); expect(success).toBe(true); }); test('getCommentReactions', async () => { const issueId = 1; const commentId = fixtures.comment.id; mock .onGet( new RegExp( `repos/${options.owner}/${options.repo}/issues/comments/${commentId}$` ) ) .reply(200, fixtures.comment); const reactions = (await API.getCommentReactions({ issueId, commentId, accessToken: mockToken, })) as VssueAPI.Reactions; expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(request.headers.Authorization).toBe(`token ${mockToken}`); expect(request.headers.Accept).toBe( 'application/vnd.github.squirrel-girl-preview' ); expect(reactions).toEqual(normalizeReactions(fixtures.comment.reactions)); }); describe('postCommentReaction', () => { test('created', async () => { const issueId = 1; const commentId = fixtures.comment.id; mock .onPost( new RegExp( `repos/${options.owner}/${options.repo}/issues/comments/${commentId}/reactions$` ) ) .reply(201); const success = (await API.postCommentReaction({ issueId, commentId, accessToken: mockToken, reaction: 'like', })) as VssueAPI.Reactions; expect(mock.history.post.length).toBe(1); const request = mock.history.post[0]; expect(request.method).toBe('post'); expect(request.headers.Authorization).toBe(`token ${mockToken}`); expect(request.headers.Accept).toBe( 'application/vnd.github.squirrel-girl-preview' ); expect(success).toBe(true); }); test('deleted', async () => { const issueId = 1; const commentId = fixtures.comment.id; const reactionId = fixtures.reaction.id; mock .onPost( new RegExp( `repos/${options.owner}/${options.repo}/issues/comments/${commentId}/reactions$` ) ) .reply(200, fixtures.reaction) .onDelete( new RegExp( `repos/${options.owner}/${options.repo}/issues/comments/${commentId}/reactions/${reactionId}$` ) ) .reply(204); const success = (await API.postCommentReaction({ issueId, commentId, accessToken: mockToken, reaction: 'like', })) as VssueAPI.Reactions; expect(mock.history.post.length).toBe(1); expect(mock.history.delete.length).toBe(1); const request = mock.history.delete[0]; expect(request.method).toBe('delete'); expect(request.headers.Authorization).toBe(`token ${mockToken}`); expect(request.headers.Accept).toBe( 'application/vnd.github.squirrel-girl-preview' ); expect(success).toBe(true); }); }); });
the_stack
import {inject} from 'aurelia-framework'; @inject(Element) export class BlurImageCustomAttribute { element; constructor(element) { this.element = element; } valueChanged(newImage) { if (newImage.complete) { drawBlur(this.element, newImage); } else { newImage.onload = () => drawBlur(this.element, newImage); } } } /* This Snippet is using a modified Stack Blur js lib for blurring the header images. */ /* StackBlur - a fast almost Gaussian Blur For Canvas Version: 0.5 Author: Mario Klingemann Contact: mario@quasimondo.com Website: http://www.quasimondo.com/StackBlurForCanvas Twitter: @quasimondo In case you find this class useful - especially in commercial projects - I am not totally unhappy for a small donation to my PayPal account mario@quasimondo.de Or support me on flattr: https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript Copyright (c) 2010 Mario Klingemann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var mul_table = [ 512, 512, 456, 512, 328, 456, 335, 512, 405, 328, 271, 456, 388, 335, 292, 512, 454, 405, 364, 328, 298, 271, 496, 456, 420, 388, 360, 335, 312, 292, 273, 512, 482, 454, 428, 405, 383, 364, 345, 328, 312, 298, 284, 271, 259, 496, 475, 456, 437, 420, 404, 388, 374, 360, 347, 335, 323, 312, 302, 292, 282, 273, 265, 512, 497, 482, 468, 454, 441, 428, 417, 405, 394, 383, 373, 364, 354, 345, 337, 328, 320, 312, 305, 298, 291, 284, 278, 271, 265, 259, 507, 496, 485, 475, 465, 456, 446, 437, 428, 420, 412, 404, 396, 388, 381, 374, 367, 360, 354, 347, 341, 335, 329, 323, 318, 312, 307, 302, 297, 292, 287, 282, 278, 273, 269, 265, 261, 512, 505, 497, 489, 482, 475, 468, 461, 454, 447, 441, 435, 428, 422, 417, 411, 405, 399, 394, 389, 383, 378, 373, 368, 364, 359, 354, 350, 345, 341, 337, 332, 328, 324, 320, 316, 312, 309, 305, 301, 298, 294, 291, 287, 284, 281, 278, 274, 271, 268, 265, 262, 259, 257, 507, 501, 496, 491, 485, 480, 475, 470, 465, 460, 456, 451, 446, 442, 437, 433, 428, 424, 420, 416, 412, 408, 404, 400, 396, 392, 388, 385, 381, 377, 374, 370, 367, 363, 360, 357, 354, 350, 347, 344, 341, 338, 335, 332, 329, 326, 323, 320, 318, 315, 312, 310, 307, 304, 302, 299, 297, 294, 292, 289, 287, 285, 282, 280, 278, 275, 273, 271, 269, 267, 265, 263, 261, 259]; var shg_table = [ 9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24]; var BLUR_RADIUS = 40; function stackBlurCanvasRGBA(canvas, top_x, top_y, width, height, radius) { if (isNaN(radius) || radius < 1) return; radius |= 0; var context = canvas.getContext("2d"); var imageData; try { imageData = context.getImageData(top_x, top_y, width, height); } catch (e) { throw new Error("unable to access image data: " + e); } var pixels = imageData.data; var x, y, i, p, yp, yi, yw, r_sum, g_sum, b_sum, a_sum, r_out_sum, g_out_sum, b_out_sum, a_out_sum, r_in_sum, g_in_sum, b_in_sum, a_in_sum, pr, pg, pb, pa, rbs; var div = radius + radius + 1; var w4 = width << 2; var widthMinus1 = width - 1; var heightMinus1 = height - 1; var radiusPlus1 = radius + 1; var sumFactor = radiusPlus1 * (radiusPlus1 + 1) / 2; var stackStart = new BlurStack(); var stack = stackStart; for (i = 1; i < div; i++) { stack = stack.next = new BlurStack(); if (i == radiusPlus1) var stackEnd = stack; } stack.next = stackStart; var stackIn = null; var stackOut = null; yw = yi = 0; var mul_sum = mul_table[radius]; var shg_sum = shg_table[radius]; for (y = 0; y < height; y++) { r_in_sum = g_in_sum = b_in_sum = a_in_sum = r_sum = g_sum = b_sum = a_sum = 0; r_out_sum = radiusPlus1 * (pr = pixels[yi]); g_out_sum = radiusPlus1 * (pg = pixels[yi + 1]); b_out_sum = radiusPlus1 * (pb = pixels[yi + 2]); a_out_sum = radiusPlus1 * (pa = pixels[yi + 3]); r_sum += sumFactor * pr; g_sum += sumFactor * pg; b_sum += sumFactor * pb; a_sum += sumFactor * pa; stack = stackStart; for (i = 0; i < radiusPlus1; i++) { stack.r = pr; stack.g = pg; stack.b = pb; stack.a = pa; stack = stack.next; } for (i = 1; i < radiusPlus1; i++) { p = yi + ((widthMinus1 < i ? widthMinus1 : i) << 2); r_sum += (stack.r = (pr = pixels[p])) * (rbs = radiusPlus1 - i); g_sum += (stack.g = (pg = pixels[p + 1])) * rbs; b_sum += (stack.b = (pb = pixels[p + 2])) * rbs; a_sum += (stack.a = (pa = pixels[p + 3])) * rbs; r_in_sum += pr; g_in_sum += pg; b_in_sum += pb; a_in_sum += pa; stack = stack.next; } stackIn = stackStart; stackOut = stackEnd; for (x = 0; x < width; x++) { pixels[yi + 3] = pa = (a_sum * mul_sum) >> shg_sum; if (pa != 0) { pa = 255 / pa; pixels[yi] = ((r_sum * mul_sum) >> shg_sum) * pa; pixels[yi + 1] = ((g_sum * mul_sum) >> shg_sum) * pa; pixels[yi + 2] = ((b_sum * mul_sum) >> shg_sum) * pa; } else { pixels[yi] = pixels[yi + 1] = pixels[yi + 2] = 0; } r_sum -= r_out_sum; g_sum -= g_out_sum; b_sum -= b_out_sum; a_sum -= a_out_sum; r_out_sum -= stackIn.r; g_out_sum -= stackIn.g; b_out_sum -= stackIn.b; a_out_sum -= stackIn.a; p = (yw + ((p = x + radius + 1) < widthMinus1 ? p : widthMinus1)) << 2; r_in_sum += (stackIn.r = pixels[p]); g_in_sum += (stackIn.g = pixels[p + 1]); b_in_sum += (stackIn.b = pixels[p + 2]); a_in_sum += (stackIn.a = pixels[p + 3]); r_sum += r_in_sum; g_sum += g_in_sum; b_sum += b_in_sum; a_sum += a_in_sum; stackIn = stackIn.next; r_out_sum += (pr = stackOut.r); g_out_sum += (pg = stackOut.g); b_out_sum += (pb = stackOut.b); a_out_sum += (pa = stackOut.a); r_in_sum -= pr; g_in_sum -= pg; b_in_sum -= pb; a_in_sum -= pa; stackOut = stackOut.next; yi += 4; } yw += width; } for (x = 0; x < width; x++) { g_in_sum = b_in_sum = a_in_sum = r_in_sum = g_sum = b_sum = a_sum = r_sum = 0; yi = x << 2; r_out_sum = radiusPlus1 * (pr = pixels[yi]); g_out_sum = radiusPlus1 * (pg = pixels[yi + 1]); b_out_sum = radiusPlus1 * (pb = pixels[yi + 2]); a_out_sum = radiusPlus1 * (pa = pixels[yi + 3]); r_sum += sumFactor * pr; g_sum += sumFactor * pg; b_sum += sumFactor * pb; a_sum += sumFactor * pa; stack = stackStart; for (i = 0; i < radiusPlus1; i++) { stack.r = pr; stack.g = pg; stack.b = pb; stack.a = pa; stack = stack.next; } yp = width; for (i = 1; i <= radius; i++) { yi = (yp + x) << 2; r_sum += (stack.r = (pr = pixels[yi])) * (rbs = radiusPlus1 - i); g_sum += (stack.g = (pg = pixels[yi + 1])) * rbs; b_sum += (stack.b = (pb = pixels[yi + 2])) * rbs; a_sum += (stack.a = (pa = pixels[yi + 3])) * rbs; r_in_sum += pr; g_in_sum += pg; b_in_sum += pb; a_in_sum += pa; stack = stack.next; if (i < heightMinus1) { yp += width; } } yi = x; stackIn = stackStart; stackOut = stackEnd; for (y = 0; y < height; y++) { p = yi << 2; pixels[p + 3] = pa = (a_sum * mul_sum) >> shg_sum; if (pa > 0) { pa = 255 / pa; pixels[p] = ((r_sum * mul_sum) >> shg_sum) * pa; pixels[p + 1] = ((g_sum * mul_sum) >> shg_sum) * pa; pixels[p + 2] = ((b_sum * mul_sum) >> shg_sum) * pa; } else { pixels[p] = pixels[p + 1] = pixels[p + 2] = 0; } r_sum -= r_out_sum; g_sum -= g_out_sum; b_sum -= b_out_sum; a_sum -= a_out_sum; r_out_sum -= stackIn.r; g_out_sum -= stackIn.g; b_out_sum -= stackIn.b; a_out_sum -= stackIn.a; p = (x + (((p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1) * width)) << 2; r_sum += (r_in_sum += (stackIn.r = pixels[p])); g_sum += (g_in_sum += (stackIn.g = pixels[p + 1])); b_sum += (b_in_sum += (stackIn.b = pixels[p + 2])); a_sum += (a_in_sum += (stackIn.a = pixels[p + 3])); stackIn = stackIn.next; r_out_sum += (pr = stackOut.r); g_out_sum += (pg = stackOut.g); b_out_sum += (pb = stackOut.b); a_out_sum += (pa = stackOut.a); r_in_sum -= pr; g_in_sum -= pg; b_in_sum -= pb; a_in_sum -= pa; stackOut = stackOut.next; yi += width; } } context.putImageData(imageData, top_x, top_y); } function BlurStack() { this.r = 0; this.g = 0; this.b = 0; this.a = 0; this.next = null; } function drawBlur(canvas, image) { var w = canvas.width; var h = canvas.height; var canvasContext = canvas.getContext('2d'); canvasContext.drawImage(image, 0, 0, w, h); stackBlurCanvasRGBA(canvas, 0, 0, w, h, BLUR_RADIUS); };
the_stack
import assert = require("assert"); import * as path from "path"; import * as ts from "typescript"; import { sort, joinPaths, FS, normalizeSlashes, hasWindowsSlashes } from "@definitelytyped/utils"; import { readFileAndThrowOnBOM } from "./definition-parser"; import { getMangledNameForScopedPackage } from "../packages"; export function getModuleInfo(packageName: string, all: Map<string, ts.SourceFile>): ModuleInfo { const dependencies = new Set<string>(); const declaredModules: string[] = []; const globals = new Set<string>(); function addDependency(ref: string): void { if (ref.startsWith(".")) { return; } const dependency = rootName(ref, all, packageName); if (dependency !== packageName) { dependencies.add(dependency); } } for (const sourceFile of all.values()) { for (const ref of imports(sourceFile)) { addDependency(ref); } for (const ref of sourceFile.typeReferenceDirectives) { addDependency(ref.fileName); } if (ts.isExternalModule(sourceFile)) { if (sourceFileExportsSomething(sourceFile)) { declaredModules.push(properModuleName(packageName, sourceFile.fileName)); const namespaceExport = sourceFile.statements.find(ts.isNamespaceExportDeclaration); if (namespaceExport) { globals.add(namespaceExport.name.text); } } } else { for (const node of sourceFile.statements) { switch (node.kind) { case ts.SyntaxKind.ModuleDeclaration: { const decl = node as ts.ModuleDeclaration; const name = decl.name.text; if (decl.name.kind === ts.SyntaxKind.StringLiteral) { declaredModules.push(assertNoWindowsSlashes(packageName, name)); } else if (isValueNamespace(decl)) { globals.add(name); } break; } case ts.SyntaxKind.VariableStatement: for (const decl of (node as ts.VariableStatement).declarationList.declarations) { if (decl.name.kind === ts.SyntaxKind.Identifier) { globals.add(decl.name.text); } } break; case ts.SyntaxKind.EnumDeclaration: case ts.SyntaxKind.ClassDeclaration: case ts.SyntaxKind.FunctionDeclaration: { // Deliberately not doing this for types, because those won't show up in JS code and can't be used for ATA const nameNode = (node as ts.EnumDeclaration | ts.ClassDeclaration | ts.FunctionDeclaration).name; if (nameNode) { globals.add(nameNode.text); } break; } case ts.SyntaxKind.ImportEqualsDeclaration: case ts.SyntaxKind.InterfaceDeclaration: case ts.SyntaxKind.TypeAliasDeclaration: break; default: throw new Error(`Unexpected node kind ${ts.SyntaxKind[node.kind]}`); } } } } return { dependencies, declaredModules, globals: sort(globals) }; } /** * A file is a proper module if it is an external module *and* it has at least one export. * A module with only imports is not a proper module; it likely just augments some other module. */ function sourceFileExportsSomething({ statements }: ts.SourceFile): boolean { return statements.some(statement => { switch (statement.kind) { case ts.SyntaxKind.ImportEqualsDeclaration: case ts.SyntaxKind.ImportDeclaration: return false; case ts.SyntaxKind.ModuleDeclaration: return (statement as ts.ModuleDeclaration).name.kind === ts.SyntaxKind.Identifier; default: return true; } }); } interface ModuleInfo { dependencies: Set<string>; // Anything from a `declare module "foo"` declaredModules: string[]; // Every global symbol globals: string[]; } /** * Given a file name, get the name of the module it declares. * `foo/index.d.ts` declares "foo", `foo/bar.d.ts` declares "foo/bar", "foo/bar/index.d.ts" declares "foo/bar" */ function properModuleName(folderName: string, fileName: string): string { const part = path.basename(fileName) === "index.d.ts" ? path.dirname(fileName) : withoutExtension(fileName, ".d.ts"); return part === "." ? folderName : joinPaths(folderName, part); } /** * "foo/bar/baz" -> "foo"; "@foo/bar/baz" -> "@foo/bar" * Note: Throws an error for references like * "bar/v3" because referencing old versions of *other* packages is illegal; * those directories won't exist in the published @types package. */ function rootName(importText: string, typeFiles: Map<string, unknown>, packageName: string): string { let slash = importText.indexOf("/"); // Root of `@foo/bar/baz` is `@foo/bar` if (importText.startsWith("@")) { // Use second "/" slash = importText.indexOf("/", slash + 1); } const root = importText.slice(0, slash); const postImport = importText.slice(slash + 1); if (slash > -1 && postImport.match(/v\d+$/) && !typeFiles.has(postImport + ".d.ts") && root !== packageName) { throw new Error(`${importText}: do not directly import specific versions of another types package. You should work with the latest version of ${root} instead.`); } return slash === -1 ? importText : root; } function withoutExtension(str: string, ext: string): string { assert(str.endsWith(ext)); return str.slice(0, str.length - ext.length); } /** Returns a map from filename (path relative to `directory`) to the SourceFile we parsed for it. */ export function allReferencedFiles( entryFilenames: readonly string[], fs: FS, packageName: string, baseDirectory: string ): { types: Map<string, ts.SourceFile>; tests: Map<string, ts.SourceFile>; hasNonRelativeImports: boolean } { const seenReferences = new Set<string>(); const types = new Map<string, ts.SourceFile>(); const tests = new Map<string, ts.SourceFile>(); let hasNonRelativeImports = false; entryFilenames.forEach(text => recur({ text, exact: true })); return { types, tests, hasNonRelativeImports }; function recur({ text, exact }: Reference): void { const resolvedFilename = exact ? text : resolveModule(text, fs); if (seenReferences.has(resolvedFilename)) { return; } seenReferences.add(resolvedFilename); // tslint:disable-next-line:non-literal-fs-path -- Not a reference to the fs package if (fs.exists(resolvedFilename)) { const src = createSourceFile(resolvedFilename, readFileAndThrowOnBOM(resolvedFilename, fs)); if ( resolvedFilename.endsWith(".d.ts") || resolvedFilename.endsWith(".d.mts") || resolvedFilename.endsWith(".d.cts") ) { types.set(resolvedFilename, src); } else { tests.set(resolvedFilename, src); } const { refs, hasNonRelativeImports: result } = findReferencedFiles( src, packageName, path.dirname(resolvedFilename), normalizeSlashes(path.relative(baseDirectory, fs.debugPath())) ); refs.forEach(recur); hasNonRelativeImports = hasNonRelativeImports || result; } } } function resolveModule(importSpecifier: string, fs: FS): string { importSpecifier = importSpecifier.endsWith("/") ? importSpecifier.slice(0, importSpecifier.length - 1) : importSpecifier; if (importSpecifier !== "." && importSpecifier !== "..") { // tslint:disable-next-line:non-literal-fs-path -- Not a reference to the fs package if (fs.exists(importSpecifier + ".d.ts")) { return importSpecifier + ".d.ts"; } // tslint:disable-next-line:non-literal-fs-path -- Not a reference to the fs package if (fs.exists(importSpecifier + ".ts")) { return importSpecifier + ".ts"; } // tslint:disable-next-line:non-literal-fs-path -- Not a reference to the fs package if (fs.exists(importSpecifier + ".tsx")) { return importSpecifier + ".tsx"; } } return importSpecifier === "." ? "index.d.ts" : joinPaths(importSpecifier, "index.d.ts"); } interface Reference { /** <reference path> includes exact filename, so true. import "foo" may reference "foo.d.ts" or "foo/index.d.ts", so false. */ readonly exact: boolean; text: string; } /** * @param subDirectory The specific directory within the DefinitelyTyped directory we are in. * For example, `baseDirectory` may be `react-router` and `subDirectory` may be `react-router/lib`. * versionsBaseDirectory may be "" when not in typesVersions or ".." when inside `react-router/ts3.1` */ function findReferencedFiles(src: ts.SourceFile, packageName: string, subDirectory: string, baseDirectory: string) { const refs: Reference[] = []; let hasNonRelativeImports = false; for (const ref of src.referencedFiles) { // Any <reference path="foo"> is assumed to be local addReference({ text: ref.fileName, exact: true }); } for (const ref of src.typeReferenceDirectives) { // only <reference types="../packagename/x" /> references are local (or "packagename/x", though in 3.7 that doesn't work in DT). if (ref.fileName.startsWith("../" + packageName + "/")) { addReference({ text: ref.fileName, exact: false }); } else if (ref.fileName.startsWith(packageName + "/")) { addReference({ text: convertToRelativeReference(ref.fileName), exact: false }); } } for (const ref of imports(src)) { if (ref.startsWith(".")) { addReference({ text: ref, exact: false }); } else if (getMangledNameForScopedPackage(ref).startsWith(packageName + "/")) { addReference({ text: convertToRelativeReference(ref), exact: false }); hasNonRelativeImports = true; } } return { refs, hasNonRelativeImports }; function addReference(ref: Reference): void { // `path.normalize` may add windows slashes let full = normalizeSlashes( path.normalize(joinPaths(subDirectory, assertNoWindowsSlashes(src.fileName, ref.text))) ); // allow files in typesVersions directories (i.e. 'ts3.1') to reference files in parent directory if (full.startsWith("../" + packageName + "/")) { full = full.slice(packageName.length + 4); } else if (baseDirectory && full.startsWith("../" + baseDirectory + "/")) { full = full.slice(baseDirectory.length + 4); } else if ( full.startsWith("..") && (baseDirectory === "" || path.normalize(joinPaths(baseDirectory, full)).startsWith("..")) ) { throw new Error( `${src.fileName}: ` + 'Definitions must use global references to other packages, not parent ("../xxx") references.' + `(Based on reference '${ref.text}')` ); } ref.text = full; refs.push(ref); } /** boring/foo -> ./foo when subDirectory === '.'; ../foo when it's === 'x'; ../../foo when it's 'x/y' */ function convertToRelativeReference(name: string) { let relative = "."; if (subDirectory !== ".") { relative += "/..".repeat(subDirectory.split("/").length); if (baseDirectory && subDirectory.startsWith("..")) { relative = relative.slice(0, -2) + baseDirectory; } } return relative + name.slice(packageName.length); } } /** * All strings referenced in `import` statements. * Does *not* include <reference> directives. */ function imports({ statements }: ts.SourceFile): Iterable<string> { const result: string[] = []; for (const node of statements) { recur(node); } return result; function recur(node: ts.Node) { switch (node.kind) { case ts.SyntaxKind.ImportDeclaration: case ts.SyntaxKind.ExportDeclaration: { const { moduleSpecifier } = node as ts.ImportDeclaration | ts.ExportDeclaration; if (moduleSpecifier && moduleSpecifier.kind === ts.SyntaxKind.StringLiteral) { result.push((moduleSpecifier as ts.StringLiteral).text); } break; } case ts.SyntaxKind.ImportEqualsDeclaration: { const { moduleReference } = node as ts.ImportEqualsDeclaration; if (moduleReference.kind === ts.SyntaxKind.ExternalModuleReference) { result.push(parseRequire(moduleReference)); } break; } case ts.SyntaxKind.ImportType: { const { argument } = node as ts.ImportTypeNode; if (ts.isLiteralTypeNode(argument) && ts.isStringLiteral(argument.literal)) { result.push(argument.literal.text); } break; } default: ts.forEachChild(node, recur); } } } function parseRequire(reference: ts.ExternalModuleReference): string { const { expression } = reference; if (!expression || !ts.isStringLiteral(expression)) { throw new Error(`Bad 'import =' reference: ${reference.getText()}`); } return expression.text; } function isValueNamespace(ns: ts.ModuleDeclaration): boolean { if (!ns.body) { throw new Error("@types should not use shorthand ambient modules"); } return ns.body.kind === ts.SyntaxKind.ModuleDeclaration ? isValueNamespace(ns.body as ts.ModuleDeclaration) : (ns.body as ts.ModuleBlock).statements.some(statementDeclaresValue); } function statementDeclaresValue(statement: ts.Statement): boolean { switch (statement.kind) { case ts.SyntaxKind.VariableStatement: case ts.SyntaxKind.ClassDeclaration: case ts.SyntaxKind.FunctionDeclaration: case ts.SyntaxKind.EnumDeclaration: return true; case ts.SyntaxKind.ModuleDeclaration: return isValueNamespace(statement as ts.ModuleDeclaration); case ts.SyntaxKind.InterfaceDeclaration: case ts.SyntaxKind.TypeAliasDeclaration: case ts.SyntaxKind.ImportEqualsDeclaration: return false; default: throw new Error(`Forgot to implement ambient namespace statement ${ts.SyntaxKind[statement.kind]}`); } } function assertNoWindowsSlashes(packageName: string, fileName: string): string { if (hasWindowsSlashes(fileName)) { throw new Error(`In ${packageName}: Use forward slash instead when referencing ${fileName}`); } return fileName; } export function getTestDependencies( packageName: string, typeFiles: Map<string, unknown>, testFiles: Iterable<string>, dependencies: ReadonlySet<string>, fs: FS ): Iterable<string> { const testDependencies = new Set<string>(); for (const filename of testFiles) { const content = readFileAndThrowOnBOM(filename, fs); const sourceFile = createSourceFile(filename, content); const { fileName, referencedFiles, typeReferenceDirectives } = sourceFile; const filePath = () => path.join(packageName, fileName); let hasImports = false; let isModule = false; let referencesSelf = false; for (const { fileName: ref } of referencedFiles) { throw new Error(`Test files should not use '<reference path="" />'. '${filePath()}' references '${ref}'.`); } for (const { fileName: referencedPackage } of typeReferenceDirectives) { if (dependencies.has(referencedPackage)) { throw new Error( `'${filePath()}' unnecessarily references '${referencedPackage}', which is already referenced in the type definition.` ); } if (referencedPackage === packageName) { referencesSelf = true; } testDependencies.add(referencedPackage); } for (const imported of imports(sourceFile)) { hasImports = true; if (!imported.startsWith(".")) { const dep = rootName(imported, typeFiles, packageName); if (!dependencies.has(dep) && dep !== packageName) { testDependencies.add(dep); } } } isModule = hasImports || (() => { // Note that this results in files without imports to be walked twice, // once in the `imports(...)` function, and once more here: for (const node of sourceFile.statements) { if (node.kind === ts.SyntaxKind.ExportAssignment || node.kind === ts.SyntaxKind.ExportDeclaration) { return true; } } return false; })(); if (isModule && referencesSelf) { throw new Error(`'${filePath()}' unnecessarily references the package. This can be removed.`); } } return testDependencies; } export function createSourceFile(filename: string, content: string): ts.SourceFile { return ts.createSourceFile(filename, content, ts.ScriptTarget.Latest, /*setParentNodes*/ false); }
the_stack
import assert from 'assert'; import clone from 'clone'; import config from './config'; import * as schemaObjects from '../helper/schema-objects'; import * as schemas from '../helper/schemas'; import * as humansCollection from '../helper/humans-collection'; import AsyncTestUtil from 'async-test-util'; import { createRxDatabase, RxDocument, isRxDocument, promiseWait, randomCouchString } from '../../plugins/core'; import { getRxStoragePouch } from '../../plugins/pouchdb'; import { filter, map, first, tap } from 'rxjs/operators'; config.parallel('reactive-query.test.js', () => { describe('positive', () => { it('get results of array when .subscribe() and filled array later', async () => { const c = await humansCollection.create(1); const query = c.find(); let lastValue: any = null; let count = 0; query.$.subscribe(newResults => { count++; lastValue = newResults; }); await AsyncTestUtil.waitUntil(() => count === 1); assert.ok(lastValue); assert.strictEqual(lastValue.length, 1); assert.strictEqual(count, 1); c.database.destroy(); }); it('get the updated docs on Collection.insert()', async () => { const c = await humansCollection.create(1); const query = c.find(); let lastValue: any[] = []; const pw8 = AsyncTestUtil.waitResolveable(500); query.$.subscribe(newResults => { lastValue = newResults; if (newResults) pw8.resolve(); }); await pw8.promise; assert.strictEqual(lastValue.length, 1); const addHuman = schemaObjects.human(); const newPromiseWait = AsyncTestUtil.waitResolveable(500); await c.insert(addHuman); await newPromiseWait.promise; assert.strictEqual(lastValue.length, 2); let isHere = false; lastValue.map(doc => { if (doc.get('passportId') === addHuman.passportId) isHere = true; }); assert.ok(isHere); c.database.destroy(); }); it('get the value twice when subscribing 2 times', async () => { const c = await humansCollection.create(1); const query = c.find(); let lastValue: any[] = []; query.$.subscribe(newResults => { lastValue = newResults; }); let lastValue2: any[] = []; query.$.subscribe(newResults => { lastValue2 = newResults; }); await promiseWait(100); await AsyncTestUtil.waitUntil(() => lastValue2 && lastValue2.length === 1); assert.deepStrictEqual(lastValue, lastValue2); c.database.destroy(); }); it('get the base-value when subscribing again later', async () => { const c = await humansCollection.create(1); const query = c.find(); let lastValue: any[] = []; query.$.subscribe(newResults => { lastValue = newResults; }); await AsyncTestUtil.waitUntil(() => lastValue.length > 0); let lastValue2: any[] = []; query.$.subscribe(newResults => { lastValue2 = newResults; }); await AsyncTestUtil.waitUntil(() => lastValue2.length > 0); await promiseWait(10); assert.strictEqual(lastValue2.length, 1); assert.deepStrictEqual(lastValue, lastValue2); c.database.destroy(); }); it('get new values on RxDocument.save', async () => { const c = await humansCollection.create(1); const doc: any = await c.findOne().exec(true); const pw8 = AsyncTestUtil.waitResolveable(500); let values: any; const querySub = c.find({ selector: { firstName: doc.get('firstName') } }).$.subscribe(newV => { values = newV; if (newV) pw8.resolve(); }); await pw8.promise; assert.strictEqual(values.length, 1); // change doc so query does not match const newPromiseWait = AsyncTestUtil.waitResolveable(500); await doc.atomicPatch({ firstName: 'foobar' }); await newPromiseWait.promise; assert.strictEqual(values.length, 0); querySub.unsubscribe(); c.database.destroy(); }); it('subscribing many times should not result in many database-requests', async () => { const c = await humansCollection.create(1); const query = c.find({ selector: { passportId: { $ne: 'foobar' } } }); await query.exec(); const countBefore = query._execOverDatabaseCount; await Promise.all( new Array(10).fill(0).map(() => { return query.$.pipe(first()).toPromise(); }) ); const countAfter = query._execOverDatabaseCount; assert.strictEqual(countBefore, countAfter); c.database.destroy(); }); }); describe('negative', () => { it('get no change when nothing happens', async () => { const c = await humansCollection.create(1); const query = c.find(); let received = 0; const querySub = query.$.subscribe(() => { received++; }); await AsyncTestUtil.waitUntil(() => received === 1); querySub.unsubscribe(); c.database.destroy(); }); }); describe('ISSUES', () => { it('#31 do not fire on doc-change when result-doc not affected', async () => { const c = await humansCollection.createAgeIndex(10); // take only 9 of 10 const valuesAr = []; const pw8 = AsyncTestUtil.waitResolveable(300); const querySub = c.find() .limit(9) .sort('age') .$ .pipe( tap(() => pw8.resolve()), filter(x => x !== null) ) .subscribe(newV => valuesAr.push(newV)); // get the 10th const doc = await c.findOne() .sort({ age: 'desc' }) .exec(true); await pw8.promise; assert.strictEqual(valuesAr.length, 1); // edit+save doc const newPromiseWait = AsyncTestUtil.waitResolveable(300); await doc.atomicPatch({ firstName: 'foobar' }); await newPromiseWait.promise; await promiseWait(20); assert.strictEqual(valuesAr.length, 1); querySub.unsubscribe(); c.database.destroy(); }); it('ISSUE: should have the document in DocCache when getting it from observe', async () => { const name = randomCouchString(10); const c = await humansCollection.createPrimary(1, name); const c2 = await humansCollection.createPrimary(0, name); const doc = await c.findOne().exec(true); const docId = doc.primary; assert.deepStrictEqual(c2._docCache.get(docId), undefined); const results = []; const sub = c2.find().$.subscribe(docs => results.push(docs)); await AsyncTestUtil.waitUntil(() => results.length >= 1); assert.strictEqual((c2._docCache.get(docId) as any).primary, docId); sub.unsubscribe(); c.database.destroy(); c2.database.destroy(); }); it('#136 : findOne(string).$ streams all documents (_id as primary)', async () => { const subs = []; const col = await humansCollection.create(3); const docData = schemaObjects.human(); const doc: any = await col.insert(docData); const _id = doc._id; const streamed: any[] = []; subs.push( col.findOne(_id).$ .pipe( filter(d => d !== null) ) .subscribe(d => { streamed.push(d); }) ); await AsyncTestUtil.waitUntil(() => streamed.length === 1); assert.ok(isRxDocument(streamed[0])); assert.strictEqual(streamed[0]._id, _id); const streamed2: any[] = []; subs.push( col.findOne().where('_id').eq(_id).$ .pipe( filter(d => d !== null) ) .subscribe(d => { streamed2.push(d); }) ); await AsyncTestUtil.waitUntil(() => streamed2.length === 1); assert.strictEqual(streamed2.length, 1); assert.ok(isRxDocument(streamed2[0])); assert.strictEqual(streamed2[0]._id, _id); subs.forEach(sub => sub.unsubscribe()); col.database.destroy(); }); it('#138 : findOne().$ returns every doc if no id given', async () => { const col = await humansCollection.create(3); const streamed: any[] = []; const sub = col.findOne().$ .pipe( filter(doc => doc !== null) ) .subscribe(doc => { streamed.push(doc); }); await AsyncTestUtil.waitUntil(() => streamed.length === 1); assert.strictEqual(streamed.length, 1); assert.ok(isRxDocument(streamed[0])); sub.unsubscribe(); col.database.destroy(); }); it('ISSUE emitted-order working when doing many atomicUpserts', async () => { const crawlStateSchema = { version: 0, type: 'object', primaryKey: 'key', properties: { key: { type: 'string' }, state: { type: 'object' } }, required: ['state'] }; const name = randomCouchString(10); const db = await createRxDatabase({ name, storage: getRxStoragePouch('memory'), ignoreDuplicate: true }); await db.addCollections({ crawlstate: { schema: crawlStateSchema } }); const db2 = await createRxDatabase({ name, storage: getRxStoragePouch('memory'), ignoreDuplicate: true }); await db2.addCollections({ crawlstate: { schema: crawlStateSchema } }); const emitted: any[] = []; const sub = db.crawlstate .findOne('registry').$ .pipe( filter(doc => doc !== null), map(doc => (doc as RxDocument).toJSON()) ).subscribe(data => emitted.push(data)); const emittedOwn = []; const sub2 = db2.crawlstate .findOne('registry').$ .pipe( filter(doc => doc !== null), map(doc => (doc as RxDocument).toJSON()) ).subscribe(data => emittedOwn.push(data)); const baseData = { lastProvider: null, providers: 0, sync: false, other: {} }; let count = 0; const getData = () => { const d2 = clone(baseData); d2.providers = count; count++; return d2; }; await Promise.all( new Array(5) .fill(0) .map(() => ({ key: 'registry', state: getData() })) .map(data => { return db2.crawlstate.atomicUpsert(data); }) ); await AsyncTestUtil.waitUntil(() => emitted.length > 0); await AsyncTestUtil.waitUntil(() => { const lastEmitted = emitted[emitted.length - 1]; return lastEmitted.state.providers === 4; }, 0, 300); await Promise.all( new Array(5) .fill(0) .map(() => ({ key: 'registry', state: getData() })) .map(data => db2.crawlstate.atomicUpsert(data)) ); await AsyncTestUtil.waitUntil(() => { if (!emitted.length) return false; const lastEmitted = emitted[emitted.length - 1]; return lastEmitted.state.providers === 9; }); // TODO this fails for unknown reasons on slow devices // await AsyncTestUtil.waitUntil(() => emittedOwn.length === 10); const last = emitted[emitted.length - 1]; assert.strictEqual(last.state.providers, 9); // on own collection, all events should have propagated // TODO this fails for unkonwn reason on slow device // assert.strictEqual(emittedOwn.length, 10); sub.unsubscribe(); sub2.unsubscribe(); db.destroy(); db2.destroy(); }); it( '#749 RxQuery subscription returns null as first result when ran immediately after another subscription or exec()', async () => { const name = randomCouchString(10); const db = await createRxDatabase({ name, storage: getRxStoragePouch('memory'), ignoreDuplicate: true }); const collections = await db.addCollections({ humans: { schema: schemas.human } }); const collection = collections.humans; await collection.insert(schemaObjects.human()); const results: any[] = []; const subs1 = collection.find().$.subscribe(x => { results.push(x); subs1.unsubscribe(); }); const subs2 = collection.find().$.subscribe(x => { results.push(x); subs2.unsubscribe(); }); // Let's try with a different query collection .find() .sort('passportId') .exec() .then((x) => { results.push(x); }); const subs3 = collection .find() .sort('passportId') .$.subscribe(x => { results.push(x); subs3.unsubscribe(); }); await AsyncTestUtil.waitUntil(() => results.length === 4); results.forEach(res => { assert.strictEqual(res.length, 1); }); db.destroy(); }); }); });
the_stack
import fs from 'fs'; import path from 'path'; import chai from 'chai'; import Regexes from '../../resources/regexes'; import { LooseTriggerSet } from '../../types/trigger'; import { CommonReplacement, commonReplacement, partialCommonReplacementKeys, } from '../../ui/raidboss/common_replacement'; import { TimelineParser, TimelineReplacement } from '../../ui/raidboss/timeline_parser'; const { assert } = chai; const parseTimelineFileFromTriggerFile = (filepath: string) => { const fileContents = fs.readFileSync(filepath, 'utf8'); const match = / {2}timelineFile: '(?<timelineFile>.*)',/.exec(fileContents); if (!match?.groups?.timelineFile) throw new Error(`Error: Trigger file ${filepath} has no timelineFile attribute defined`); return match.groups.timelineFile; }; type TestFile = { timelineFile: string; triggersFile: string; }; const testFiles: TestFile[] = []; const setup = (timelineFiles: string[]) => { timelineFiles.forEach((timelineFile) => { // For each timeline file, ensure that its corresponding trigger file is pointing to it. const filename = timelineFile.split('/').slice(-1)[0] ?? ''; const triggerFilenameJS = timelineFile.replace('.txt', '.js'); const triggerFilenameTS = timelineFile.replace('.txt', '.ts'); let triggerFile; if (fs.existsSync(triggerFilenameJS)) triggerFile = triggerFilenameJS; else if (fs.existsSync(triggerFilenameTS)) triggerFile = triggerFilenameTS; else throw new Error(`Error: Timeline file ${timelineFile} found without matching trigger file`); const timelineFileFromFile = parseTimelineFileFromTriggerFile(triggerFile); if (filename !== timelineFileFromFile) { throw new Error( `Error: Trigger file ${triggerFile} has \`triggerFile: '${timelineFileFromFile}'\`, but was expecting \`triggerFile: '${filename}'\``, ); } testFiles.push({ timelineFile: timelineFile, triggersFile: triggerFile, }); }); }; type ReplaceMap = Map<RegExp, string>; type TestCase = { type: keyof CommonReplacement; items: Set<string>; replace: ReplaceMap; }; const getTestCases = ( triggersFile: string, timeline: TimelineParser, trans: TimelineReplacement, skipPartialCommon?: boolean, ) => { const syncMap: ReplaceMap = new Map(); for (const [key, replaceSync] of Object.entries(trans.replaceSync ?? {})) syncMap.set(Regexes.parse(key), replaceSync); const textMap: ReplaceMap = new Map(); for (const [key, replaceText] of Object.entries(trans.replaceText ?? {})) textMap.set(Regexes.parse(key), replaceText); const testCases: TestCase[] = [ { type: 'replaceSync', items: new Set(timeline.syncStarts.map((x) => x.regex.source)), replace: syncMap, }, { type: 'replaceText', items: new Set(timeline.events.map((x) => x.text)), replace: textMap, }, ]; // Add all common replacements, so they can be checked for collisions as well. for (const testCase of testCases) { const common = commonReplacement[testCase.type]; for (const [key, localeText] of Object.entries(common)) { if (skipPartialCommon && partialCommonReplacementKeys.includes(key)) continue; const regexKey = Regexes.parse(key); const transText = localeText[trans.locale]; if (!transText) { // To avoid throwing a "missing translation" error for // every single common translation, automatically add noops. testCase.replace.set(regexKey, key); continue; } if (testCase.replace.has(regexKey)) { assert.fail( `${triggersFile}:locale ${trans.locale}:common replacement '${key}' found in ${testCase.type}`, ); } testCase.replace.set(regexKey, transText); } } return testCases; }; const getTestCasesWithoutPartialCommon = ( triggersFile: string, timeline: TimelineParser, trans: TimelineReplacement, ) => { return getTestCases(triggersFile, timeline, trans, true); }; const testTimelineFiles = (timelineFiles: string[]): void => { describe('timeline test', () => { setup(timelineFiles); for (const testFile of testFiles) { describe(`${testFile.timelineFile}`, () => { // Capture the test file params in scoped variables so that they are not changed // by the testFiles loop during the async `before` function below. const timelineFile = testFile.timelineFile; const triggersFile = testFile.triggersFile; let timelineText; let triggerSet: LooseTriggerSet; let timeline: TimelineParser; before(async () => { // Normalize path const importPath = '../../' + path.relative(process.cwd(), triggersFile).replace('.ts', '.js'); timelineText = String(fs.readFileSync(timelineFile)); // Dynamic imports don't have a type, so add type assertion. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access triggerSet = (await import(importPath)).default as LooseTriggerSet; timeline = new TimelineParser(timelineText, [], triggerSet.timelineTriggers ?? []); }); // This test loads an individual raidboss timeline and makes sure // that timeline.js can parse it without errors. it('should load without errors', () => { for (const e of timeline.errors) { if (e.line && e.lineNumber) assert.isNull(e, `${timelineFile}:${e.lineNumber}:${e.error}:${e.line}`); else assert.isNull(e, `${timelineFile}:${e.error}`); } }); it('should not have translation conflicts', () => { const translations = triggerSet.timelineReplace; if (!translations) return; for (const trans of translations) { const locale = trans.locale; // TODO: maybe this needs to be in the triggers test instead assert.isDefined(locale, `${triggersFile}: missing locale in translation block`); // Note: even if translations are missing, they should not have conflicts. const testCases = getTestCases(triggersFile, timeline, trans); // For both texts and syncs... for (const testCase of testCases) { // For every unique replaceable text or sync the timeline knows about... for (const orig of testCase.items) { // For every translation for that timeline... // Do a first pass to find which regexes, if any will apply to orig. type TranslateMatch = [RegExp, string, string]; const translateMatches: TranslateMatch[] = []; for (const [regex, replaceText] of testCase.replace) { const replaced = orig.replace(regex, replaceText); if (orig === replaced) continue; translateMatches.push([regex, replaceText, replaced]); } // Now do a second O(n^2) pass, only against regexes which apply. for (const [regex, replaceText, replaced] of translateMatches) { // If we get here, then |regex| is a valid replacement in |orig|. // The goal is to ensure via testing that there are no ordering // constraints in the timeline translations. To fix these issues, // add negative lookahead/lookbehind assertions to make the regexes unique. // (1) Verify that there is no pre-replacement collision,. // i.e. two regexes that apply to the same text or sync. // e.g. "Holy IV" is affected by both /Holy IV/ and /Holy/. for (const [otherRegex, otherReplaceText, otherReplaced] of translateMatches) { if (regex === otherRegex) continue; // If we get here, then there is a pre-replacement collision. // Verify if these two regexes can be applied in either order // to get the same result, if so, then this collision can be // safely ignored. // e.g. "Magnetism/Repel" is affected by both /Magnetism/ and /Repel/, // however these are independent and could be applied in either order. const otherFirst = otherReplaced.replace(regex, replaceText); const otherSecond = replaced.replace(otherRegex, otherReplaceText); assert.equal( otherFirst, otherSecond, `${triggersFile}:locale ${locale}: pre-translation collision on ${testCase.type} '${orig}' for '${regex.source}' and '${otherRegex.source}'`, ); } // (2) Verify that there is no post-replacement collision with this text, // i.e. a regex that applies to the replaced text that another regex // has already modified. We need to look through everything here // and not just through translateMatches, unfortunately. for (const [otherRegex, otherReplaceText] of testCase.replace) { if (regex === otherRegex) continue; const otherSecond = replaced.replace(otherRegex, otherReplaceText); if (replaced === otherSecond) continue; // If we get here, then there is a post-replacement collision. // Verify if these two regexes can be applied in either order // to get the same result, if so, then this collision can be // safely ignored. let otherFirst = orig.replace(otherRegex, otherReplaceText); otherFirst = otherFirst.replace(regex, replaceText); assert.equal( otherFirst, otherSecond, `${triggersFile}:locale ${locale}: post-translation collision on ${testCase.type} '${orig}' for '${regex.source}' => '${replaced}', then '${otherRegex.source}'`, ); } } } } } }); it('should not be missing translations', () => { const translations = triggerSet.timelineReplace; if (!translations) return; for (const trans of translations) { const locale = trans.locale; if (!locale) continue; // English cannot be missing translations and is always a "partial" translation. if (locale === 'en') continue; if (trans.missingTranslations) continue; // Ignore partial common translations here, as they don't // count towards completing missing translations. const testCases = getTestCasesWithoutPartialCommon(triggersFile, timeline, trans); const ignore = timeline.GetMissingTranslationsToIgnore(); const isIgnored = (x: string) => { for (const ig of ignore) { if (ig.test(x)) return true; } return false; }; for (const testCase of testCases) { for (const item of testCase.items) { if (isIgnored(item)) continue; let matched = false; for (const regex of testCase.replace.keys()) { if (regex.test(item)) { matched = true; break; } } assert( matched, `${triggersFile}:locale ${locale}:no translation for ${testCase.type} '${item}'`, ); } } } }); it('should not have bad characters', () => { const translations = triggerSet.timelineReplace; if (!translations) return; for (const trans of translations) { const locale = trans.locale; if (!locale) continue; const testCases = getTestCases(triggersFile, timeline, trans); // Text should not include ^ or $, unless preceded by \ or [ const badRegex = [ /(?<![\\[])[\^\$]/, ].map((x) => Regexes.parse(x)); for (const testCase of testCases) { for (const regex of testCase.replace.keys()) { for (const bad of badRegex) { assert.isNull( bad.exec(regex.source), `${triggersFile}:locale ${locale}:invalid character in ${testCase.type} '${regex.source}'`, ); } } } } }); it('should have proper sealed sync', () => { for (const sync of timeline.syncStarts) { const regex = sync.regex.source; // FIXME: This test will currently accept log lines with or without a second colon, // as "0839:" or "0839::". // Once we have completely converted things for 6.0, // we should come back here and make the doubled colon non-optional. if (regex.includes('is no longer sealed')) { assert( /00:0839::?\.\*is no longer sealed/.exec(regex), `${timelineFile}:${sync.lineNumber} 'is no longer sealed' sync must be exactly '00:0839::.*is no longer sealed'`, ); } else if (regex.includes('will be sealed')) { assert( /00:0839::?.*will be sealed/.exec(regex), `${timelineFile}:${sync.lineNumber} 'will be sealed' sync must be preceded by '00:0839::'`, ); } } }); }); } }); }; export default testTimelineFiles;
the_stack
import "../AsyncSupport"; import "../XMLDomInit"; import test from "ava"; import sinon from "sinon"; import xmldom from "xmldom"; import * as _ from "lodash"; import { goml, stringConverter, testComponent1, testComponent2, testComponent3, testComponentBase, testComponentOptional, testNode1, testNode2, testNode3, testNodeBase, conflictNode1, conflictNode2, conflictComponent1, conflictComponent2 } from "./GomlParserTest_Registering"; import GomlLoader from "../../src/Node/GomlLoader"; import GomlNode from "../../src/Node/GomlNode"; import Component from "../../src/Node/Component"; import Attribute from "../../src/Node/Attribute"; import NSIdentity from "../../src/Base/NSIdentity"; import GrimoireComponent from "../../src/Components/GrimoireComponent"; import GrimoireInterface from "../../src/Interface/GrimoireInterface"; import fs from "../fileHelper"; import PLH from "../PageLoadingHelper"; const tc1_goml = fs.readFile("../_TestResource/GomlNodeTest_Case1.goml"); const tc1_html = fs.readFile("../_TestResource/GomlNodeTest_Case1.html"); PLH.mockSetup(); PLH.mock("./GomlNodeTest_Case1.goml", tc1_goml); let stringConverterSpy, testComponent1Spy, testComponent2Spy, testComponent3Spy, testComponentBaseSpy, testComponentOptionalSpy, conflictComponent1Spy, conflictComponent2Spy; function resetSpies() { stringConverterSpy.reset(); testComponent1Spy.reset(); testComponent2Spy.reset(); testComponent3Spy.reset(); testComponentBaseSpy.reset(); testComponentOptionalSpy.reset(); conflictComponent1Spy.reset(); conflictComponent2Spy.reset(); } let rootNode: GomlNode; test.beforeEach(async () => { let spys = await PLH.reset(GrimoireInterface, tc1_html); stringConverterSpy = spys.stringConverterSpy; testComponent1Spy = spys.testComponent1Spy; testComponent2Spy = spys.testComponent2Spy; testComponentBaseSpy = spys.testComponent3Spy; testComponent3Spy = spys.testComponent3Spy; testComponentBaseSpy = spys.testComponentBaseSpy; testComponentOptionalSpy = spys.testComponentOptionalSpy; conflictComponent1Spy = spys.conflictComponent1Spy; conflictComponent2Spy = spys.conflictComponent2Spy; rootNode = _.values(GrimoireInterface.rootNodes)[0]; }); test("Root node must not have parent", (t) => { t.truthy(_.isNull(rootNode.parent)); }); test("Nodes must have companion", (t) => { const companion = rootNode.companion; t.truthy(companion); rootNode.callRecursively((n) => { t.truthy(companion === n.companion); }); }); test("Nodes must have tree", (t) => { const tree = rootNode.tree; t.truthy(tree); rootNode.callRecursively((n) => { t.truthy(tree === n.tree); }); }); test("default value works correctly.", t => { const testNode3 = rootNode.children[0]; // test-node3 const a = testNode3.getAttribute("hoge"); t.truthy(a === "AAA"); // node default const b = testNode3.getAttribute("hogehoge"); t.truthy(b === "hoge"); // component default t.truthy(testNode3.getAttribute("id") === "test"); // goml default t.truthy(testNode3.getAttribute("testAttr3") === "tc2default"); // component default }); test("mount should be called in ideal timing", (t) => { const testNode3 = rootNode.children[0]; testNode3.enabled = true; const order = [testComponent3Spy, testComponent2Spy, testComponentOptionalSpy, testComponent1Spy]; sinon.assert.callOrder(testComponent3Spy, testComponent2Spy, testComponentOptionalSpy, testComponent1Spy); order.forEach(v => { t.truthy(v.getCall(1).args[0] === "mount"); }); }); test("awake and mount should be called in ideal timing", (t) => { const order = [testComponent3Spy, testComponent2Spy, testComponentOptionalSpy, testComponent1Spy]; order.forEach(v => { t.truthy(v.getCall(0).args[0] === "awake"); t.truthy(v.getCall(1).args[0] === "mount"); }); }); test("Nodes should be mounted after loading", (t) => { t.truthy(rootNode.mounted); rootNode.callRecursively((n) => { t.truthy(n.mounted); }); }); test("attribute default value work correctly1", (t) => { t.truthy(rootNode.getAttribute("id") !== void 0); t.truthy(rootNode.getAttribute("id") === null); }); test("attribute watch should work correctly", (t) => { const idAttr = rootNode.getAttributeRaw("id"); const spy = sinon.spy(); const watcher = (newValue, oldValue, attr) => { // spy("watch", { newValue: newValue, oldValue: oldValue, attr: attr }); spy(newValue); }; idAttr.watch(watcher); idAttr.Value = "id"; t.truthy(spy.getCall(0).args[0] === "id"); spy.reset(); rootNode.enabled = false; idAttr.Value = "id"; sinon.assert.notCalled(spy); }); test("attribute watch should work correctly2", (t) => { const idAttr = rootNode.getAttributeRaw("id"); const spy = sinon.spy(); const watcher = (newValue, oldValue, attr) => { // spy("watch", { newValue: newValue, oldValue: oldValue, attr: attr }); spy(newValue); }; idAttr.watch(watcher); idAttr.unwatch(watcher); idAttr.Value = "id"; sinon.assert.notCalled(spy); idAttr.watch(watcher, false, true); rootNode.enabled = false; idAttr.Value = "idid"; t.truthy(spy.getCall(0).args[0] === "idid"); }); test("enabled should work correctly", (t) => { const testNode3 = rootNode.children[0]; const testNode2 = testNode3.children[0]; t.truthy(rootNode.enabled); t.truthy(rootNode.isActive); t.truthy(!testNode3.enabled); t.truthy(!testNode3.isActive); t.truthy(testNode2.enabled); t.truthy(!testNode2.isActive); testNode3.enabled = true; t.truthy(testNode3.enabled); t.truthy(testNode3.isActive); t.truthy(testNode2.enabled); t.truthy(testNode2.isActive); testNode2.enabled = false; t.truthy(!testNode2.enabled); t.truthy(!testNode2.isActive); rootNode.enabled = false; t.truthy(!rootNode.enabled); t.truthy(!rootNode.isActive); t.truthy(testNode3.enabled); t.truthy(!testNode3.isActive); t.truthy(!testNode2.enabled); t.truthy(!testNode2.isActive); }); test("Broadcast message should call correct order", (t) => { sinon.assert.callOrder(testComponent3Spy, testComponent2Spy, testComponentOptionalSpy, testComponent1Spy); }); test("Broadcast message with range should work correctly", (t) => { const testNode3 = rootNode.children[0]; resetSpies(); testNode3.enabled = true; rootNode.broadcastMessage(1, "onTest"); sinon.assert.called(testComponent3Spy); sinon.assert.notCalled(testComponent2Spy); sinon.assert.notCalled(testComponentOptionalSpy); sinon.assert.notCalled(testComponent1Spy); }); test("Broadcast message with enabled should work correctly", (t) => { const testNode3 = rootNode.children[0]; const testNode2 = testNode3.children[0]; resetSpies(); sinon.assert.notCalled(testComponent3Spy); sinon.assert.notCalled(testComponent2Spy); sinon.assert.notCalled(testComponentOptionalSpy); sinon.assert.notCalled(testComponent1Spy); resetSpies(); rootNode.broadcastMessage("onTest"); sinon.assert.notCalled(testComponent3Spy); sinon.assert.notCalled(testComponent2Spy); sinon.assert.notCalled(testComponentOptionalSpy); sinon.assert.notCalled(testComponent1Spy); resetSpies(); testNode3.enabled = true; testNode2.enabled = false; rootNode.broadcastMessage("onTest"); sinon.assert.called(testComponent3Spy); sinon.assert.notCalled(testComponent2Spy); sinon.assert.notCalled(testComponentOptionalSpy); sinon.assert.called(testComponent1Spy); resetSpies(); testNode2.enabled = true; rootNode.broadcastMessage("onTest"); sinon.assert.called(testComponent3Spy); sinon.assert.called(testComponent2Spy); sinon.assert.called(testComponentOptionalSpy); sinon.assert.called(testComponent1Spy); }); test("SendMessage should call correct order", (t) => { const testNode2 = rootNode.children[0].children[0]; testNode2.sendMessage("onTest"); sinon.assert.callOrder(testComponent2Spy, testComponentOptionalSpy); }); test("Detach node should invoke unmount before detaching", (t) => { const testNode3 = rootNode.children[0]; testNode3.enabled = true; resetSpies(); testNode3.detach(); const called = [testComponent2Spy, testComponentOptionalSpy, testComponent1Spy, testComponent3Spy]; sinon.assert.callOrder.apply(sinon.assert, called); called.forEach((v) => { t.truthy(v.getCall(0).args[0] === "unmount"); }); }); test("Remove() should invoke unmount before deleting", (t) => { const testNode3 = rootNode.children[0]; testNode3.enabled = true; resetSpies(); testNode3.remove(); const called = [testComponent2Spy, testComponentOptionalSpy, testComponent1Spy, testComponent3Spy]; sinon.assert.callOrder.apply(sinon.assert, called); called.forEach((v) => { t.truthy(v.getCall(0).args[0] === "unmount"); }); }); test("Get component return value correctly", (t) => { const testNode2 = rootNode.children[0].children[0]; t.truthy(!testNode2.getComponent("TestComponent1")); t.truthy(testNode2.getComponent("TestComponent2")); // Must check actually the instance being same. }); test("broadcastMessage should not invoke message if the component is not enabled", (t) => { const testNode3 = rootNode.children[0]; testNode3.enabled = true; resetSpies(); const optionalComponent = rootNode.children[0].children[0].getComponent<Component>("TestComponentOptional"); optionalComponent.enabled = false; rootNode.broadcastMessage("onTest"); const called = [testComponent3Spy, testComponent2Spy, testComponent1Spy]; sinon.assert.callOrder.apply(sinon.assert, called); sinon.assert.notCalled(testComponentOptionalSpy); }); test("broadcastMessage should not invoke message if the node is not enabled", (t) => { const testNode3 = rootNode.children[0]; testNode3.enabled = true; resetSpies(); const testNode2 = rootNode.children[0].children[0]; testNode2.enabled = false; rootNode.broadcastMessage("onTest"); const called = [testComponent3Spy, testComponent1Spy]; sinon.assert.callOrder.apply(sinon.assert, called); sinon.assert.notCalled(testComponentOptionalSpy); sinon.assert.notCalled(testComponent2Spy); }); test("class attribute can be obatined as default", (t) => { const testNode3 = rootNode.children[0]; let classes = testNode3.getAttribute("class"); t.truthy(classes.length === 1); t.truthy(classes[0] === "classTest"); }); test("id attribute can be obatined as default", (t) => { const testNode3 = rootNode.children[0]; t.truthy(testNode3.getAttribute("id") === "test"); }); test("enabled attribute can be obatined as default", (t) => { const testNode3 = rootNode.children[0]; t.truthy(testNode3.getAttribute("enabled") === false); }); test("id attribute should sync with element", (t) => { const testNode3 = rootNode.children[0]; const id = testNode3.getAttribute("id"); testNode3.setAttribute("id", "test2"); t.truthy(testNode3.element.id === "test2"); }); test("class attribute should sync with element", (t) => { const testNode3 = rootNode.children[0]; testNode3.setAttribute("class", "test"); t.truthy(testNode3.element.className === "test"); }); test("addComponent should work correctly", (t) => { const testNode3 = rootNode.children[0]; testNode3.addComponent("TestComponentOptional"); t.truthy(testNode3.getComponent("TestComponentOptional")); }); test("get/setAttribute should work correctly 1", t => { t.throws(() => { // throw error when get attribute for nonexist name. rootNode.getAttribute("hoge"); }); rootNode.setAttribute("hoge", "hogehoge"); const att = rootNode.getAttribute("hoge"); t.truthy(att === "hogehoge"); }); test("get/setAttribute should work correctly 2", t => { const c = rootNode.getComponent<Component>("GrimoireComponent"); (c as any).__addAttribute("hoge", { converter: "String", default: "aaa" }); const att = rootNode.getAttribute("hoge"); t.truthy(att === "aaa"); }); test("get/setAttribute should work correctly 3", t => { const c = rootNode.getComponent<Component>("GrimoireComponent"); rootNode.setAttribute("hoge", "bbb"); (c as any).__addAttribute("hoge", { converter: "String", default: "aaa" }); const att = rootNode.getAttribute("hoge"); t.truthy(att === "bbb"); }); test("get/setAttribute should work correctly 4", t => { const c = rootNode.getComponent<Component>("GrimoireComponent"); rootNode.setAttribute("ns1.hoge", "bbb"); (c as any).__addAttribute("hoge", { converter: "String", default: "aaa" }); const att = rootNode.getAttribute("hoge"); t.truthy(att === "aaa"); }); test("attribute buffer is valid only last set value.", t => { const c = rootNode.getComponent<Component>("GrimoireComponent"); rootNode.setAttribute("hoge", "bbb"); rootNode.setAttribute("ns1.hoge", "ccc"); (c as any).__addAttribute("ns1.hoge", { converter: "String", default: "aaa" }); let att = rootNode.getAttribute("ns1.hoge"); t.truthy(att === "ccc"); // both buffer are resolved in above __addAttribute. (c as any).__addAttribute("hoge", { converter: "String", default: "aaa" }); att = rootNode.getAttribute(NSIdentity.fromFQN(c.name.fqn + ".hoge")); t.truthy(att === "aaa"); rootNode.setAttribute("ns2.aaa", "1"); rootNode.setAttribute("aaa", "2"); rootNode.setAttribute("ns2.aaa", "3"); (c as any).__addAttribute("ns2.aaa", { converter: "String", default: "aaa" }); att = rootNode.getAttribute(NSIdentity.fromFQN(c.name.fqn + ".ns2.aaa")); t.truthy(att === "3"); }); test("get/setAttribute should work correctly 6", t => { const c = rootNode.getComponent<Component>("GrimoireComponent"); rootNode.setAttribute("ns1.hoge", "bbb"); rootNode.setAttribute("hoge", "ccc"); (c as any).__addAttribute("hoge", { converter: "String", default: "aaa" }); const att = rootNode.getAttribute("hoge"); t.truthy(att === "ccc"); }); test("get/setAttribute should work correctly 7", t => { const c = rootNode.getComponent<Component>("GrimoireComponent"); (c as any).__addAttribute("ns1.hoge", { converter: "String", default: "1" }); (c as any).__addAttribute("ns2.hoge", { converter: "String", default: "2" }); (c as any).__addAttribute("hoge", { converter: "String", default: "3" }); let att = rootNode.getAttribute("ns1.hoge"); t.truthy(att === "1"); t.throws(() => { rootNode.getAttribute("hoge"); // ambiguous! }); att = rootNode.getAttribute("ns2.hoge"); t.truthy(att === "2"); att = rootNode.getAttribute(NSIdentity.fromFQN(c.name.fqn + ".hoge")); t.truthy(att === "3"); }); test("get/setAttribute should work correctly 8", t => { const c = rootNode.getComponent<Component>("GrimoireComponent"); rootNode.setAttribute("hoge", "bbb"); rootNode.setAttribute("ns2.hoge", "ccc"); (c as any).__addAttribute("ns1.hoge", { // matchs hoge but not matchs ns2.hoge. converter: "String", default: "1" }); let att = rootNode.getAttribute("ns1.hoge"); t.truthy(att === "bbb"); (c as any).__addAttribute("ns2.hoge", { converter: "String", default: "2" }); t.throws(() => { rootNode.getAttribute("hoge"); }); att = rootNode.getAttribute("ns2.hoge"); t.truthy(att === "ccc"); (c as any).__addAttribute("hoge", { converter: "String", default: "3" }); att = rootNode.getAttribute(NSIdentity.fromFQN(c.name.fqn + ".hoge")); t.truthy(att === "3"); }); test("addNode works correctly", (t) => { const testNode2 = rootNode.children[0].children[0]; testNode2.addChildByName("test-node2", { testAttr2: "ADDEDNODE", id: "idtest" }); const child = testNode2.children[0]; t.truthy(child.name.name === "test-node2"); t.truthy(child.getAttribute("testAttr2") === "ADDEDNODE"); t.truthy(child.getAttribute("id") === "idtest"); t.truthy(child.element.id === "idtest"); t.truthy(child.getComponent(GrimoireComponent).getAttribute("id") === "idtest"); }); test("null should be \"\" as id and classname", async (t) => { const testNode2 = rootNode.children[0].children[0]; testNode2.addChildByName("test-node2", { testAttr2: "ADDEDNODE", id: null, class: null }); const child = testNode2.children[0]; t.truthy(child.name.name === "test-node2"); t.truthy(child.getAttribute("testAttr2") === "ADDEDNODE"); t.truthy(child.getAttribute("id") === null); t.truthy(child.element.id === ""); t.truthy(child.getComponent(GrimoireComponent).getAttribute("id") === null); t.truthy(child.getAttribute("class") === null); t.truthy(child.element.className === ""); t.truthy(child.getComponent(GrimoireComponent).getAttribute("class") === null); }); test("null should be \"\" as id and classname", async (t) => { const testNode2 = rootNode.children[0].children[0]; testNode2.addChildByName("test-node2", { testAttr2: "ADDEDNODE", id: null, class: null }); const child = testNode2.children[0]; t.truthy(child.name.name === "test-node2"); t.truthy(child.getAttribute("testAttr2") === "ADDEDNODE"); t.truthy(child.getAttribute("id") === null); t.truthy(child.element.id === ""); t.truthy(child.getComponent(GrimoireComponent).getAttribute("id") === null); t.truthy(child.getAttribute("class") === null); t.truthy(child.element.className === ""); t.truthy(child.getComponent(GrimoireComponent).getAttribute("class") === null); }); test("Grimoireinterface should works correctly", t => { const gi = GrimoireInterface("*"); t.truthy(gi.rootNodes.length === 1); });
the_stack
declare namespace Chroma { export interface ChromaStatic { /** * Creates a color from a string representation (as supported in CSS). * * @param color The string to convert to a color. * @return the color object. */ (color: string): Color; /** * Create a color in the specified color space using a, b and c as values. * * @param a * @param b * @param c * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". * @return the color object. */ (a: number, b: number, c: number, colorSpace?: string): Color; /** * Create a color in the specified color space using values. * * @param values An array of values (e.g. [r, g, b, a?]). * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". * @return the color object. */ (values: number[], colorSpace?: string): Color; /** * Create a color in the specified color space using a, b and c as values. * * @param a * @param b * @param c * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". * @return the color object. */ color(a: number, b: number, c: number, colorSpace?: string): Color; /** * Calculate the contrast ratio of two colors. * * @param color1 The first color. * @param color2 The second color. * @return the contrast ratio. */ contrast(color1: Color, color2: Color): number; /** * Calculate the contrast ratio of two colors. * * @param color1 The first color. * @param color2 The second color. * @return the contrast ratio. */ contrast(color1: Color, color2: string): number; /** * Calculate the contrast ratio of two colors. * * @param color1 The first color. * @param color2 The second color. * @return the contrast ratio. */ contrast(color1: string, color2: Color): number; /** * Calculate the contrast ratio of two colors. * * @param color1 The first color. * @param color2 The second color. * @return the contrast ratio. */ contrast(color1: string, color2: string): number; /** * Create a color from a hex or string representation (as supported in CSS). * * This is an alias of chroma.hex(). * * @param color The string to convert to a color. * @return the color object. */ css(color: string): Color; /** * Create a color from a hex or string representation (as supported in CSS). * * This is an alias of chroma.css(). * * @param color The string to convert to a color. * @return the color object. */ hex(color: string): Color; rgb(red: number, green: number, blue: number, alpha?: number): Color; hsl(hue: number, saturation: number, lightness: number, alpha?: number): Color; hsv(hue: number, saturation: number, value: number, alpha?: number): Color; lab(lightness: number, a: number, b: number, alpha?: number): Color; lch(lightness: number, chroma: number, hue: number, alpha?: number): Color; gl(red: number, green: number, blue: number, alpha?: number): Color; interpolate: InterpolateFunction; mix: InterpolateFunction; luminance(color: Color): number; luminance(color: string): number; /** * Creates a color scale using a pre-defined color scale. * * @param name The name of the color scale. * @return the resulting color scale. */ scale(name: string): Scale; /** * Creates a color scale function from the given set of colors. * * @param colors An Array of at least two color names or hex values. * @return the resulting color scale. */ scale(colors?: string[]): Scale; scales: PredefinedScales; } interface InterpolateFunction { (color1: Color, color2: Color, f: number, mode?: string): Color; (color1: Color, color2: string, f: number, mode?: string): Color; (color1: string, color2: Color, f: number, mode?: string): Color; (color1: string, color2: string, f: number, mode?: string): Color; bezier(colors: any[]): (t: number) => Color; } interface PredefinedScales { [key: string]: Scale; cool: Scale; hot: Scale; } export interface Color { /** * Creates a color from a string representation (as supported in CSS). * * @param color The string to convert to a color. */ new(color: string): Color; /** * Create a color in the specified color space using a, b and c as values. * * @param a * @param b * @param c * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". */ new(a: number, b: number, c: number, colorSpace?: string): Color; /** * Create a color in the specified color space using a, b and c as color values and alpha as the alpha value. * * @param a * @param b * @param c * @param alpha The alpha value of the color. * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". */ new(a: number, b: number, c: number, alpha: number, colorSpace?: string): Color; /** * Create a color in the specified color space using values. * * @param values An array of values (e.g. [r, g, b, a?]). * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". */ new(values: number[], colorSpace: string): Color; /** * Convert this color to CSS hex representation. * * @return this color's hex representation. */ hex(): string; /** * @return the relative luminance of the color, which is a value between 0 (black) and 1 (white). */ luminance(): number; /** * @return the X11 name of this color or its hex value if it does not have a name. */ name(): string; /** * @return the alpha value of the color. */ alpha(): number; /** * Set the alpha value. * * @param alpha The alpha value. * @return this */ alpha(alpha: number): Color; css(mode?: string): string; interpolate(color: Color, f: number, mode?: string): Color; interpolate(color: string, f: number, mode?: string): Color; premultiply(): Color; rgb(): number[]; rgba(): number[]; hsl(): number[]; hsv(): number[]; lab(): number[]; lch(): number[]; hsi(): number[]; gl(): number[]; darken(amount?: number): Color; darker(amount: number): Color; brighten(amount?: number): Color; brighter(amount: number): Color; saturate(amount?: number): Color; desaturate(amount?: number): Color; toString(): string; } export interface Scale { /** * Interpolate a color using the currently set range and domain. * * @param value The value to use for interpolation. * @return the interpolated hex color OR a Color object (depending on the mode set on this Scale). */ (value: number): any; /** * Retreive all possible colors generated by this scale if it has distinct classes. * * @param mode The output mode to use. Must be one of Color's getters. Defaults to "hex". * @return an array of colors in the type specified by mode. */ colors(mode?: string): any[]; correctLightness(): boolean; /** * Enable or disable automatic lightness correction of this scale. * * @param Whether to enable or disable automatic lightness correction. * @return this */ correctLightness(enable: boolean): Scale; /** * Get the current domain. * * @return The current domain. */ domain(): number[]; /** * Set the domain. * * @param domain An Array of at least two numbers (min and max). * @param classes The number of fixed classes to create between min and max. * @param mode The scale to use. Examples: log, quantiles, k-means. * @return this */ domain(domain: number[], classes?: number, mode?: string): Scale; /** * Specify in which color space the colors should be interpolated. Defaults to "rgb". * You can use any of the following spaces: rgb, hsv, hsl, lab, lch * * @param colorSpace The color space to use for interpolation. * @return this */ mode(colorSpace: string): Scale; /** * Set the output mode of this Scale. * * @param mode The output mode to use. Must be one of Color's getters. * @return this */ out(mode: string): Scale; /** * Set the color range after initialization. * * @param colors An Array of at least two color names or hex values. * @return this */ range(colors: string[]): Scale; } } declare var chroma: Chroma.ChromaStatic;
the_stack
import { Socket, createSocket, RemoteInfo } from 'dgram'; import { EventEmitter } from 'events'; import util from 'util'; import type log from 'loglevel'; import { encrypt, decrypt } from 'tplink-smarthome-crypto'; import type { MarkOptional } from 'ts-essentials'; import Device, { isBulbSysinfo, isPlugSysinfo } from './device'; import type { Sysinfo } from './device'; import Bulb from './bulb'; import Plug, { hasSysinfoChildren } from './plug'; import createLogger from './logger'; import type { Logger } from './logger'; import TcpConnection from './network/tcp-connection'; import UdpConnection from './network/udp-connection'; import { compareMac, isObjectLike } from './utils'; import { Realtime } from './shared/emeter'; const discoveryMsgBuf = encrypt('{"system":{"get_sysinfo":{}}}'); export type AnyDevice = Bulb | Plug; type DeviceDiscovery = { status: string; seenOnDiscovery: number }; type AnyDeviceDiscovery = (Bulb | Plug) & Partial<DeviceDiscovery>; type SysinfoResponse = { system: { get_sysinfo: Sysinfo } }; type EmeterResponse = PlugEmeterResponse | BulbEmeterResponse; type PlugEmeterResponse = { emeter?: { get_realtime?: { err_code: number } & Realtime }; }; type BulbEmeterResponse = { 'smartlife.iot.common.emeter'?: { get_realtime?: { err_code: number } & Realtime; }; }; type DiscoveryResponse = SysinfoResponse & EmeterResponse; type AnyDeviceOptions = | ConstructorParameters<typeof Bulb>[0] | ConstructorParameters<typeof Plug>[0]; type AnyDeviceOptionsCon = | MarkOptional<ConstructorParameters<typeof Plug>[0], 'client' | 'sysInfo'> | MarkOptional<ConstructorParameters<typeof Bulb>[0], 'client' | 'sysInfo'>; type DeviceOptionsDiscovery = | MarkOptional< ConstructorParameters<typeof Plug>[0], 'client' | 'sysInfo' | 'host' > | MarkOptional< ConstructorParameters<typeof Bulb>[0], 'client' | 'sysInfo' | 'host' >; export type DiscoveryDevice = { host: string; port?: number }; function isSysinfoResponse(candidate: unknown): candidate is SysinfoResponse { return ( isObjectLike(candidate) && 'system' in candidate && isObjectLike(candidate.system) && 'get_sysinfo' in candidate.system ); } export interface ClientConstructorOptions { /** * @defaultValue \{ * timeout: 10000, * transport: 'tcp', * useSharedSocket: false, * sharedSocketTimeout: 20000 * \} */ defaultSendOptions?: SendOptions; /** * @defaultValue 'warn' */ logLevel?: log.LogLevelDesc; logger?: Logger; } export interface DiscoveryOptions { /** * address to bind udp socket */ address?: string; /** * port to bind udp socket */ port?: number; /** * broadcast address * @defaultValue '255.255.255.255' */ broadcast?: string; /** * Interval in (ms) * @defaultValue 10000 */ discoveryInterval?: number; /** * Timeout in (ms) * @defaultValue 0 */ discoveryTimeout?: number; /** * Number of consecutive missed replies to consider offline * @defaultValue 3 */ offlineTolerance?: number; deviceTypes?: Array<'plug' | 'bulb'>; /** * MAC will be normalized, comparison will be done after removing special characters (`:`,`-`, etc.) and case insensitive, glob style *, and ? in pattern are supported * @defaultValue [] */ macAddresses?: string[]; /** * MAC will be normalized, comparison will be done after removing special characters (`:`,`-`, etc.) and case insensitive, glob style *, and ? in pattern are supported * @defaultValue [] */ excludeMacAddresses?: string[]; /** * called with fn(sysInfo), return truthy value to include device */ filterCallback?: (sysInfo: Sysinfo) => boolean; /** * if device has multiple outlets, create a separate plug for each outlet, otherwise create a plug for the main device * @defaultValue true */ breakoutChildren?: boolean; /** * passed to device constructors */ deviceOptions?: DeviceOptionsDiscovery; /** * known devices to query instead of relying only on broadcast */ devices?: DiscoveryDevice[]; } /** * Send Options. * * @typeParam timeout - (ms) * @typeParam transport - 'tcp','udp' * @typeParam useSharedSocket - attempt to reuse a shared socket if available, UDP only * @typeParam sharedSocketTimeout - (ms) how long to wait for another send before closing a shared socket. 0 = never automatically close socket */ export type SendOptions = { timeout?: number; transport?: 'tcp' | 'udp'; useSharedSocket?: boolean; sharedSocketTimeout?: number; }; export interface ClientEventEmitter { /** * First response from device. */ on( event: 'device-new', listener: (device: Device | Bulb | Plug) => void ): this; /** * Follow up response from device. */ on( event: 'device-online', listener: (device: Device | Bulb | Plug) => void ): this; /** * No response from device. */ on( event: 'device-offline', listener: (device: Device | Bulb | Plug) => void ): this; /** * First response from Bulb. */ on(event: 'bulb-new', listener: (device: Bulb) => void): this; /** * Follow up response from Bulb. */ on(event: 'bulb-online', listener: (device: Bulb) => void): this; /** * No response from Bulb. */ on(event: 'bulb-offline', listener: (device: Bulb) => void): this; /** * First response from Plug. */ on(event: 'plug-new', listener: (device: Plug) => void): this; /** * Follow up response from Plug. */ on(event: 'plug-online', listener: (device: Plug) => void): this; /** * No response from Plug. */ on(event: 'plug-offline', listener: (device: Plug) => void): this; /** * Invalid/Unknown response from device. */ on( event: 'discovery-invalid', listener: ({ rinfo, response, decryptedResponse, }: { rinfo: RemoteInfo; response: Buffer; decryptedResponse: Buffer; }) => void ): this; /** * Error during discovery. */ on(event: 'error', listener: (error: Error) => void): this; emit(event: 'device-new', device: Device | Bulb | Plug): boolean; emit(event: 'device-online', device: Device | Bulb | Plug): boolean; emit(event: 'device-offline', device: Device | Bulb | Plug): boolean; emit(event: 'bulb-new', device: Bulb): boolean; emit(event: 'bulb-online', device: Bulb): boolean; emit(event: 'bulb-offline', device: Bulb): boolean; emit(event: 'plug-new', device: Plug): boolean; emit(event: 'plug-online', device: Plug): boolean; emit(event: 'plug-offline', device: Plug): boolean; emit( event: 'discovery-invalid', { rinfo, response, decryptedResponse, }: { rinfo: RemoteInfo; response: Buffer; decryptedResponse: Buffer } ): boolean; emit(event: 'error', error: Error): boolean; } /** * Client that sends commands to specified devices or discover devices on the local subnet. * - Contains factory methods to create devices. * - Events are emitted after {@link #startDiscovery} is called. * @noInheritDoc */ export default class Client extends EventEmitter implements ClientEventEmitter { defaultSendOptions: Required<SendOptions> = { timeout: 10000, transport: 'tcp', useSharedSocket: false, sharedSocketTimeout: 20000, }; log: Logger; devices: Map<string, AnyDeviceDiscovery> = new Map(); discoveryTimer: NodeJS.Timeout | null = null; discoveryPacketSequence = 0; maxSocketId = 0; socket?: Socket; isSocketBound = false; constructor(options: ClientConstructorOptions = {}) { super(); const { defaultSendOptions, logLevel = 'warn', logger } = options; this.defaultSendOptions = { ...this.defaultSendOptions, ...defaultSendOptions, }; this.log = createLogger({ logger, level: logLevel }); } /** * Used by `tplink-connection` * @internal */ getNextSocketId(): number { this.maxSocketId += 1; return this.maxSocketId; } /** * {@link https://github.com/plasticrake/tplink-smarthome-crypto | Encrypts} `payload` and sends to device. * - If `payload` is not a string, it is `JSON.stringify`'d. * - Promise fulfills with encrypted string response. * * Devices use JSON to communicate.\ * For Example: * - If a device receives: * - `{"system":{"get_sysinfo":{}}}` * - It responds with: * ``` * {"system":{"get_sysinfo":{ * err_code: 0, * sw_ver: "1.0.8 Build 151113 Rel.24658", * hw_ver: "1.0", * ... * }}} * ``` * * All responses from device contain an `err_code` (`0` is success). * * @returns decrypted string response */ async send( payload: Record<string, unknown> | string, host: string, port = 9999, sendOptions?: SendOptions ): Promise<string> { const thisSendOptions = { ...this.defaultSendOptions, ...sendOptions, useSharedSocket: false, }; const payloadString = !(typeof payload === 'string') ? JSON.stringify(payload) : payload; let connection: UdpConnection | TcpConnection; if (thisSendOptions.transport === 'udp') { connection = new UdpConnection(host, port, this.log, this); } else { connection = new TcpConnection(host, port, this.log, this); } const response = await connection.send( payloadString, port, host, thisSendOptions ); connection.close(); return response; } /** * Requests `{system:{get_sysinfo:{}}}` from device. * * @returns parsed JSON response * @throws {@link ResponseError} * @throws {@link Error} */ async getSysInfo( host: string, port = 9999, sendOptions?: SendOptions ): Promise<Sysinfo> { this.log.debug('client.getSysInfo(%j)', { host, port, sendOptions }); const response = await this.send( '{"system":{"get_sysinfo":{}}}', host, port, sendOptions ); const responseObj = JSON.parse(response); if (isSysinfoResponse(responseObj)) { return responseObj.system.get_sysinfo; } throw new Error(`Unexpected Response: ${response}`); } /** * @internal */ // eslint-disable-next-line @typescript-eslint/no-explicit-any emit(eventName: string, ...args: any[]): boolean { // Add device- / plug- / bulb- to eventName let ret = false; if (args[0] instanceof Device) { if (super.emit(`device-${eventName}`, ...args)) { ret = true; } if (args[0].deviceType !== 'device') { if (super.emit(`${args[0].deviceType}-${eventName}`, ...args)) { ret = true; } } } else if (super.emit(eventName, ...args)) { ret = true; } return ret; } /** * Creates Bulb object. * * See [Device constructor]{@link Device} and [Bulb constructor]{@link Bulb} for valid options. * @param deviceOptions - passed to [Bulb constructor]{@link Bulb} */ getBulb( deviceOptions: MarkOptional<ConstructorParameters<typeof Bulb>[0], 'client'> ): Bulb { return new Bulb({ defaultSendOptions: this.defaultSendOptions, ...deviceOptions, client: this, }); } /** * Creates {@link Plug} object. * * See [Device constructor]{@link Device} and [Plug constructor]{@link Plug} for valid options. * @param deviceOptions - passed to [Plug constructor]{@link Plug} */ getPlug( deviceOptions: MarkOptional<ConstructorParameters<typeof Plug>[0], 'client'> ): Plug { return new Plug({ defaultSendOptions: this.defaultSendOptions, ...deviceOptions, client: this, }); } /** * Creates a {@link Plug} or {@link Bulb} from passed in sysInfo or after querying device to determine type. * * See [Device constructor]{@link Device}, [Bulb constructor]{@link Bulb}, [Plug constructor]{@link Plug} for valid options. * @param deviceOptions - passed to [Device constructor]{@link Device} * @throws {@link ResponseError} */ async getDevice( deviceOptions: AnyDeviceOptionsCon, sendOptions?: SendOptions ): Promise<AnyDevice> { this.log.debug('client.getDevice(%j)', { deviceOptions, sendOptions }); let sysInfo: Sysinfo; if ('sysInfo' in deviceOptions && deviceOptions.sysInfo !== undefined) { sysInfo = deviceOptions.sysInfo; } else { sysInfo = await this.getSysInfo( deviceOptions.host, deviceOptions.port, sendOptions ); } const combinedDeviceOptions = { ...deviceOptions, client: this, } as AnyDeviceOptions; return this.getDeviceFromSysInfo(sysInfo, combinedDeviceOptions); } /** * Creates device corresponding to the provided `sysInfo`. * * See [Device constructor]{@link Device}, [Bulb constructor]{@link Bulb}, [Plug constructor]{@link Plug} for valid options * @param deviceOptions - passed to device constructor * @throws {@link Error} */ getDeviceFromSysInfo( sysInfo: Sysinfo, deviceOptions: AnyDeviceOptionsCon ): AnyDevice { if (isPlugSysinfo(sysInfo)) { return this.getPlug({ ...deviceOptions, sysInfo }); } if (isBulbSysinfo(sysInfo)) { return this.getBulb({ ...deviceOptions, sysInfo }); } throw new Error('Could not determine device from sysinfo'); } /** * Guess the device type from provided `sysInfo`. * * Based on sysinfo.[type|mic_type] */ // eslint-disable-next-line class-methods-use-this getTypeFromSysInfo( sysInfo: { type: string } | { mic_type: string } ): 'plug' | 'bulb' | 'device' { const type = 'type' in sysInfo ? sysInfo.type : sysInfo.mic_type; switch (true) { case /plug/i.test(type): return 'plug'; case /bulb/i.test(type): return 'bulb'; default: return 'device'; } } /** * Discover TP-Link Smarthome devices on the network. * * - Sends a discovery packet (via UDP) to the `broadcast` address every `discoveryInterval`(ms). * - Stops discovery after `discoveryTimeout`(ms) (if `0`, runs until {@link Client.stopDiscovery} is called). * - If a device does not respond after `offlineTolerance` number of attempts, {@link Client.device-offline} is emitted. * - If `deviceTypes` are specified only matching devices are found. * - If `macAddresses` are specified only devices with matching MAC addresses are found. * - If `excludeMacAddresses` are specified devices with matching MAC addresses are excluded. * - if `filterCallback` is specified only devices where the callback returns a truthy value are found. * - If `devices` are specified it will attempt to contact them directly in addition to sending to the broadcast address. * - `devices` are specified as an array of `[{host, [port: 9999]}]`. * @fires Client#error * @fires Client#device-new * @fires Client#device-online * @fires Client#device-offline * @fires Client#bulb-new * @fires Client#bulb-online * @fires Client#bulb-offline * @fires Client#plug-new * @fires Client#plug-online * @fires Client#plug-offline * @fires Client#discovery-invalid */ startDiscovery(options: DiscoveryOptions = {}): this { this.log.debug('client.startDiscovery(%j)', options); const { address, port, broadcast = '255.255.255.255', discoveryInterval = 10000, discoveryTimeout = 0, offlineTolerance = 3, deviceTypes, macAddresses = [], excludeMacAddresses = [], filterCallback, breakoutChildren = true, deviceOptions, devices, } = options; try { const socket = createSocket('udp4'); this.socket = socket; socket.on('message', (msg, rinfo) => { const decryptedMsg = decrypt(msg).toString('utf8'); this.log.debug( `client.startDiscovery(): socket:message From: ${rinfo.address} ${rinfo.port} Message: ${decryptedMsg}` ); let response: DiscoveryResponse; let sysInfo: Sysinfo; try { response = JSON.parse(decryptedMsg); sysInfo = response.system.get_sysinfo; } catch (err) { this.log.debug( `client.startDiscovery(): Error parsing JSON: %s\nFrom: ${rinfo.address} ${rinfo.port} Original: [%s] Decrypted: [${decryptedMsg}]`, err, msg ); this.emit('discovery-invalid', { rinfo, response: msg, decryptedResponse: decrypt(msg), }); return; } if (deviceTypes && deviceTypes.length > 0) { const deviceType = this.getTypeFromSysInfo(sysInfo); if (!(deviceTypes as string[]).includes(deviceType)) { this.log.debug( `client.startDiscovery(): Filtered out: ${sysInfo.alias} [${sysInfo.deviceId}] (${deviceType}), allowed device types: (%j)`, deviceTypes ); return; } } let mac: string; if ('mac' in sysInfo) mac = sysInfo.mac; else if ('mic_mac' in sysInfo) mac = sysInfo.mic_mac; else if ('ethernet_mac' in sysInfo) mac = sysInfo.ethernet_mac; else mac = ''; if (macAddresses && macAddresses.length > 0) { if (!compareMac(mac, macAddresses)) { this.log.debug( `client.startDiscovery(): Filtered out: ${sysInfo.alias} [${sysInfo.deviceId}] (${mac}), allowed macs: (%j)`, macAddresses ); return; } } if (excludeMacAddresses && excludeMacAddresses.length > 0) { if (compareMac(mac, excludeMacAddresses)) { this.log.debug( `client.startDiscovery(): Filtered out: ${sysInfo.alias} [${sysInfo.deviceId}] (${mac}), excluded mac` ); return; } } if (typeof filterCallback === 'function') { if (!filterCallback(sysInfo)) { this.log.debug( `client.startDiscovery(): Filtered out: ${sysInfo.alias} [${sysInfo.deviceId}], callback` ); return; } } this.createOrUpdateDeviceFromSysInfo({ sysInfo, host: rinfo.address, port: rinfo.port, breakoutChildren, options: deviceOptions, }); }); socket.on('error', (err) => { this.log.error('client.startDiscovery: UDP Error: %s', err); this.stopDiscovery(); this.emit('error', err); // TODO }); socket.bind(port, address, () => { this.isSocketBound = true; const sockAddress = socket.address(); this.log.debug( `client.socket: UDP ${sockAddress.family} listening on ${sockAddress.address}:${sockAddress.port}` ); socket.setBroadcast(true); this.discoveryTimer = setInterval(() => { this.sendDiscovery(socket, broadcast, devices, offlineTolerance); }, discoveryInterval); this.sendDiscovery(socket, broadcast, devices, offlineTolerance); if (discoveryTimeout > 0) { setTimeout(() => { this.log.debug( 'client.startDiscovery: discoveryTimeout reached, stopping discovery' ); this.stopDiscovery(); }, discoveryTimeout); } }); } catch (err) { this.log.error('client.startDiscovery: %s', err); this.emit('error', err); } return this; } private static setSysInfoForDevice( device: AnyDeviceDiscovery, sysInfo: Sysinfo ): void { if (device instanceof Plug) { if (!isPlugSysinfo(sysInfo)) { throw new TypeError( util.format('Expected PlugSysinfo but received: %O', sysInfo) ); } device.setSysInfo(sysInfo); } else if (device instanceof Bulb) { if (!isBulbSysinfo(sysInfo)) { throw new TypeError( util.format('Expected BulbSysinfo but received: %O', sysInfo) ); } device.setSysInfo(sysInfo); } } private createOrUpdateDeviceFromSysInfo({ sysInfo, host, port, options, breakoutChildren, }: { sysInfo: Sysinfo; host: string; port: number; options?: DeviceOptionsDiscovery; breakoutChildren: boolean; }): void { const process = (id: string, childId?: string): void => { let device: AnyDeviceDiscovery; if (this.devices.has(id) && this.devices.get(id) !== undefined) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion device = this.devices.get(id)!; device.host = host; device.port = port; Client.setSysInfoForDevice(device, sysInfo); device.status = 'online'; device.seenOnDiscovery = this.discoveryPacketSequence; this.emit('online', device); } else { device = this.getDeviceFromSysInfo(sysInfo, { ...options, client: this, host, port, childId, }); device.status = 'online'; device.seenOnDiscovery = this.discoveryPacketSequence; this.devices.set(id, device); this.emit('new', device); } }; if (breakoutChildren && hasSysinfoChildren(sysInfo)) { sysInfo.children.forEach((child) => { const childId = child.id.length === 2 ? sysInfo.deviceId + child.id : child.id; process(childId, childId); }); } else { process(sysInfo.deviceId); } } /** * Stops discovery and closes UDP socket. */ stopDiscovery(): void { this.log.debug('client.stopDiscovery()'); if (this.discoveryTimer !== null) clearInterval(this.discoveryTimer); this.discoveryTimer = null; if (this.isSocketBound) { this.isSocketBound = false; if (this.socket != null) this.socket.close(); } } private sendDiscovery( socket: Socket, address: string, devices: DiscoveryDevice[] = [], offlineTolerance: number ): void { this.log.debug( 'client.sendDiscovery(%s, %j, %s)', address, devices, offlineTolerance ); try { this.devices.forEach((device) => { if (device.status !== 'offline') { const diff = this.discoveryPacketSequence - (device.seenOnDiscovery || 0); if (diff >= offlineTolerance) { // eslint-disable-next-line no-param-reassign device.status = 'offline'; this.emit('offline', device); } } }); // sometimes there is a race condition with setInterval where this is called after it was cleared // check and exit if (!this.isSocketBound) { return; } socket.send(discoveryMsgBuf, 0, discoveryMsgBuf.length, 9999, address); devices.forEach((d) => { this.log.debug('client.sendDiscovery() direct device:', d); socket.send( discoveryMsgBuf, 0, discoveryMsgBuf.length, d.port || 9999, d.host ); }); if (this.discoveryPacketSequence >= Number.MAX_VALUE) { this.discoveryPacketSequence = 0; } else { this.discoveryPacketSequence += 1; } } catch (err) { this.log.error('client.sendDiscovery: %s', err); this.emit('error', err); } } }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [inspector](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoninspector.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Inspector extends PolicyStatement { public servicePrefix = 'inspector'; /** * Statement provider for service [inspector](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoninspector.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 assign attributes (key and value pairs) to the findings that are specified by the ARNs of the findings * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_AddAttributesToFindings.html */ public toAddAttributesToFindings() { return this.to('AddAttributesToFindings'); } /** * Grants permission to create a new assessment target using the ARN of the resource group that is generated by CreateResourceGroup * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_CreateAssessmentTarget.html */ public toCreateAssessmentTarget() { return this.to('CreateAssessmentTarget'); } /** * Grants permission to create an assessment template for the assessment target that is specified by the ARN of the assessment target * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_CreateAssessmentTemplate.html */ public toCreateAssessmentTemplate() { return this.to('CreateAssessmentTemplate'); } /** * Grants permission to start the generation of an exclusions preview for the specified assessment template * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_CreateExclusionsPreview.html */ public toCreateExclusionsPreview() { return this.to('CreateExclusionsPreview'); } /** * Grants permission to create a resource group using the specified set of tags (key and value pairs) that are used to select the EC2 instances to be included in an Amazon Inspector assessment target * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_CreateResourceGroup.html */ public toCreateResourceGroup() { return this.to('CreateResourceGroup'); } /** * Grants permission to delete the assessment run that is specified by the ARN of the assessment run * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_DeleteAssessmentRun.html */ public toDeleteAssessmentRun() { return this.to('DeleteAssessmentRun'); } /** * Grants permission to delete the assessment target that is specified by the ARN of the assessment target * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_DeleteAssessmentTarget.html */ public toDeleteAssessmentTarget() { return this.to('DeleteAssessmentTarget'); } /** * Grants permission to delete the assessment template that is specified by the ARN of the assessment template * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_DeleteAssessmentTemplate.html */ public toDeleteAssessmentTemplate() { return this.to('DeleteAssessmentTemplate'); } /** * Grants permission to describe the assessment runs that are specified by the ARNs of the assessment runs * * Access Level: Read * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_DescribeAssessmentRuns.html */ public toDescribeAssessmentRuns() { return this.to('DescribeAssessmentRuns'); } /** * Grants permission to describe the assessment targets that are specified by the ARNs of the assessment targets * * Access Level: Read * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_DescribeAssessmentTargets.html */ public toDescribeAssessmentTargets() { return this.to('DescribeAssessmentTargets'); } /** * Grants permission to describe the assessment templates that are specified by the ARNs of the assessment templates * * Access Level: Read * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_DescribeAssessmentTemplates.html */ public toDescribeAssessmentTemplates() { return this.to('DescribeAssessmentTemplates'); } /** * Grants permission to describe the IAM role that enables Amazon Inspector to access your AWS account * * Access Level: Read * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_DescribeCrossAccountAccessRole.html */ public toDescribeCrossAccountAccessRole() { return this.to('DescribeCrossAccountAccessRole'); } /** * Grants permission to describe the exclusions that are specified by the exclusions' ARNs * * Access Level: Read * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_DescribeExclusions.html */ public toDescribeExclusions() { return this.to('DescribeExclusions'); } /** * Grants permission to describe the findings that are specified by the ARNs of the findings * * Access Level: Read * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_DescribeFindings.html */ public toDescribeFindings() { return this.to('DescribeFindings'); } /** * Grants permission to describe the resource groups that are specified by the ARNs of the resource groups * * Access Level: Read * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_DescribeResourceGroups.html */ public toDescribeResourceGroups() { return this.to('DescribeResourceGroups'); } /** * Grants permission to describe the rules packages that are specified by the ARNs of the rules packages * * Access Level: Read * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_DescribeRulesPackages.html */ public toDescribeRulesPackages() { return this.to('DescribeRulesPackages'); } /** * Grants permission to produce an assessment report that includes detailed and comprehensive results of a specified assessment run * * Access Level: Read * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_GetAssessmentReport.html */ public toGetAssessmentReport() { return this.to('GetAssessmentReport'); } /** * Grants permission to retrieve the exclusions preview (a list of ExclusionPreview objects) specified by the preview token * * Access Level: Read * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_GetExclusionsPreview.html */ public toGetExclusionsPreview() { return this.to('GetExclusionsPreview'); } /** * Grants permission to get information about the data that is collected for the specified assessment run * * Access Level: Read * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_GetTelemetryMetadata.html */ public toGetTelemetryMetadata() { return this.to('GetTelemetryMetadata'); } /** * Grants permission to list the agents of the assessment runs that are specified by the ARNs of the assessment runs * * Access Level: List * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_ListAssessmentRunAgents.html */ public toListAssessmentRunAgents() { return this.to('ListAssessmentRunAgents'); } /** * Grants permission to list the assessment runs that correspond to the assessment templates that are specified by the ARNs of the assessment templates * * Access Level: List * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_ListAssessmentRuns.html */ public toListAssessmentRuns() { return this.to('ListAssessmentRuns'); } /** * Grants permission to list the ARNs of the assessment targets within this AWS account * * Access Level: List * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_ListAssessmentTargets.html */ public toListAssessmentTargets() { return this.to('ListAssessmentTargets'); } /** * Grants permission to list the assessment templates that correspond to the assessment targets that are specified by the ARNs of the assessment targets * * Access Level: List * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_ListAssessmentTemplates.html */ public toListAssessmentTemplates() { return this.to('ListAssessmentTemplates'); } /** * Grants permission to list all the event subscriptions for the assessment template that is specified by the ARN of the assessment template * * Access Level: List * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_ListEventSubscriptions.html */ public toListEventSubscriptions() { return this.to('ListEventSubscriptions'); } /** * Grants permission to list exclusions that are generated by the assessment run * * Access Level: List * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_ListExclusions.html */ public toListExclusions() { return this.to('ListExclusions'); } /** * Grants permission to list findings that are generated by the assessment runs that are specified by the ARNs of the assessment runs * * Access Level: List * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_ListFindings.html */ public toListFindings() { return this.to('ListFindings'); } /** * Grants permission to list all available Amazon Inspector rules packages * * Access Level: List * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_ListRulesPackages.html */ public toListRulesPackages() { return this.to('ListRulesPackages'); } /** * Grants permission to list all tags associated with an assessment template * * Access Level: Read * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to preview the agents installed on the EC2 instances that are part of the specified assessment target * * Access Level: Read * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_PreviewAgents.html */ public toPreviewAgents() { return this.to('PreviewAgents'); } /** * Grants permission to register the IAM role that Amazon Inspector uses to list your EC2 instances at the start of the assessment run or when you call the PreviewAgents action * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_RegisterCrossAccountAccessRole.html */ public toRegisterCrossAccountAccessRole() { return this.to('RegisterCrossAccountAccessRole'); } /** * Grants permission to remove entire attributes (key and value pairs) from the findings that are specified by the ARNs of the findings where an attribute with the specified key exists * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_RemoveAttributesFromFindings.html */ public toRemoveAttributesFromFindings() { return this.to('RemoveAttributesFromFindings'); } /** * Grants permission to set tags (key and value pairs) to the assessment template that is specified by the ARN of the assessment template * * Access Level: Tagging * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_SetTagsForResource.html */ public toSetTagsForResource() { return this.to('SetTagsForResource'); } /** * Grants permission to start the assessment run specified by the ARN of the assessment template * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_StartAssessmentRun.html */ public toStartAssessmentRun() { return this.to('StartAssessmentRun'); } /** * Grants permission to stop the assessment run that is specified by the ARN of the assessment run * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_StopAssessmentRun.html */ public toStopAssessmentRun() { return this.to('StopAssessmentRun'); } /** * Grants permission to enable the process of sending Amazon Simple Notification Service (SNS) notifications about a specified event to a specified SNS topic * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_SubscribeToEvent.html */ public toSubscribeToEvent() { return this.to('SubscribeToEvent'); } /** * Grants permission to disable the process of sending Amazon Simple Notification Service (SNS) notifications about a specified event to a specified SNS topic * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_UnsubscribeFromEvent.html */ public toUnsubscribeFromEvent() { return this.to('UnsubscribeFromEvent'); } /** * Grants permission to update the assessment target that is specified by the ARN of the assessment target * * Access Level: Write * * https://docs.aws.amazon.com/inspector/latest/APIReference/API_UpdateAssessmentTarget.html */ public toUpdateAssessmentTarget() { return this.to('UpdateAssessmentTarget'); } protected accessLevelList: AccessLevelList = { "Write": [ "AddAttributesToFindings", "CreateAssessmentTarget", "CreateAssessmentTemplate", "CreateExclusionsPreview", "CreateResourceGroup", "DeleteAssessmentRun", "DeleteAssessmentTarget", "DeleteAssessmentTemplate", "RegisterCrossAccountAccessRole", "RemoveAttributesFromFindings", "StartAssessmentRun", "StopAssessmentRun", "SubscribeToEvent", "UnsubscribeFromEvent", "UpdateAssessmentTarget" ], "Read": [ "DescribeAssessmentRuns", "DescribeAssessmentTargets", "DescribeAssessmentTemplates", "DescribeCrossAccountAccessRole", "DescribeExclusions", "DescribeFindings", "DescribeResourceGroups", "DescribeRulesPackages", "GetAssessmentReport", "GetExclusionsPreview", "GetTelemetryMetadata", "ListTagsForResource", "PreviewAgents" ], "List": [ "ListAssessmentRunAgents", "ListAssessmentRuns", "ListAssessmentTargets", "ListAssessmentTemplates", "ListEventSubscriptions", "ListExclusions", "ListFindings", "ListRulesPackages" ], "Tagging": [ "SetTagsForResource" ] }; }
the_stack
// Converted from https://github.com/rburns/ansi-to-html // Includes patches from https://github.com/rburns/ansi-to-html/pull/84 // Converted to typescript by MarkusJx import _ from 'underscore'; import {AnsiToHtmlOptions, ColorCodes} from './ansi-to-html.interfaces'; const defaults: AnsiToHtmlOptions = { fg: '#FFF', bg: '#000', newline: false, escapeXML: false, stream: false, colors: getDefaultColors(), }; function getDefaultColors(): ColorCodes { const colors: ColorCodes = { 0: '#000', 1: '#A00', 2: '#0A0', 3: '#A50', 4: '#00A', 5: '#A0A', 6: '#0AA', 7: '#AAA', 8: '#555', 9: '#F55', 10: '#5F5', 11: '#FF5', 12: '#55F', 13: '#F5F', 14: '#5FF', 15: '#FFF', }; range(0, 5).forEach(red => { range(0, 5).forEach(green => { range(0, 5).forEach(blue => { setStyleColor(red, green, blue, colors); }); }); }); range(0, 23).forEach(gray => { const c = gray + 232; const l = toHexString(gray * 10 + 8); colors[c] = `#${l}${l}${l}`; }); return colors; } function setStyleColor(red: number, green: number, blue: number, colors: ColorCodes): void { const c = 16 + red * 36 + green * 6 + blue; const r = red > 0 ? red * 40 + 55 : 0; const g = green > 0 ? green * 40 + 55 : 0; const b = blue > 0 ? blue * 40 + 55 : 0; colors[c] = toColorHexString([r, g, b]); } /** * Converts from a number like 15 to a hex string like 'F' * * @param num - the number to convert * @returns the resulting hex string */ function toHexString(num: number): string { let str = num.toString(16); while (str.length < 2) { str = '0' + str; } return str; } /** * Converts from an array of numbers like [15, 15, 15] to a hex string like 'FFF' * * @param ref - the array of numbers to join * @returns the resulting hex string */ function toColorHexString(ref: number[]): string { const results: string[] = []; for (let j = 0, len = ref.length; j < len; j++) { results.push(toHexString(ref[j])); } return '#' + results.join(''); } function generateOutput(stack: string[], token: string, data: string | number, options: AnsiToHtmlOptions): string { if (token === 'text') { // Note: Param 'data' must be a string at this point return pushText(data as string, options); } else if (token === 'display') { return handleDisplay(stack, data, options); } else if (token === 'xterm256') { // Note: Param 'data' must be a string at this point return handleXterm256(stack, data as string, options); } else if (token === 'rgb') { // Note: Param 'data' must be a string at this point return handleRgb(stack, data as string, options); } return ''; } function handleRgb(stack: string[], data: string, options: AnsiToHtmlOptions) { data = data.substring(2).slice(0, -1); const operation = +data.substr(0, 2); const color = data.substring(5).split(';'); const rgb = color .map(value => { return ('0' + Number(value).toString(16)).substr(-2); }) .join(''); return pushStyle(stack, (operation === 38 ? 'color:#' : 'background-color:#') + rgb); } function handleXterm256(stack: string[], data: string, options: AnsiToHtmlOptions): string { data = data.substring(2).slice(0, -1); const operation = +data.substr(0, 2); const color = +data.substr(5); if (operation === 38) { // @ts-ignore Colors is autogenerated return pushForegroundColor(stack, options.colors[color]); } else { // @ts-ignore Colors is autogenerated return pushBackgroundColor(stack, options.colors[color]); } } function handleDisplay(stack: string[], _code: string | number, options: AnsiToHtmlOptions): string { const code: number = parseInt(_code as string, 10); const codeMap: Record<number, () => string> = { '-1': () => '<br />', // @ts-ignore 0: () => stack.length && resetStyles(stack), 1: () => pushTag(stack, 'b'), 2: () => pushStyle(stack, 'opacity:0.6'), 3: () => pushTag(stack, 'i'), 4: () => pushTag(stack, 'u'), 8: () => pushStyle(stack, 'display:none'), 9: () => pushTag(stack, 'strike'), 22: () => closeTag(stack, 'b'), 23: () => closeTag(stack, 'i'), 24: () => closeTag(stack, 'u'), 39: () => pushForegroundColor(stack, options.fg as string), 49: () => pushBackgroundColor(stack, options.bg as string), }; if (code in codeMap) { return codeMap[code](); } else if (4 < code && code < 7) { return pushTag(stack, 'blink'); } else if (code === 7) { return ''; } else if (29 < code && code < 38) { // @ts-ignore return pushForegroundColor(stack, options.colors[code - 30]); } else if (39 < code && code < 48) { // @ts-ignore return pushBackgroundColor(stack, options.colors[code - 40]); } else if (89 < code && code < 98) { // @ts-ignore return pushForegroundColor(stack, options.colors[8 + (code - 90)]); } else if (99 < code && code < 108) { // @ts-ignore return pushBackgroundColor(stack, options.colors[8 + (code - 100)]); } return 'Unknown code'; } /** * Clear all the styles */ function resetStyles(stack: string[]): string { const stackClone = stack.slice(0); stack.length = 0; return stackClone .reverse() .map(tag => `</${tag}>`) .join(''); } /** * Creates an array of numbers ranging from low to high * * @param low - the lowest number in the array to create * @param high - the highest number in the array to create * @returns the resulting array * @example range(3, 7); // creates [3, 4, 5, 6, 7] */ function range(low: number, high: number): number[] { const results: number[] = []; for (let j = low; j <= high; j++) { results.push(j); } return results; } /** * Returns a new function that is true if value is NOT the same category */ function notCategory(category: string): (e: StickyStackElement) => boolean { return (e: StickyStackElement): boolean => { return e.category !== category && category !== 'all'; }; } /** * Converts a code into an ansi token type * * @param _code - the code to convert * @returns the ansi token type */ function categoryForCode(_code: string | number): string { const code: number = parseInt(_code as string, 10); if (code === 0) { return 'all'; } else if (code === 1) { return 'bold'; } else if (2 < code && code < 5) { return 'underline'; } else if (4 < code && code < 7) { return 'blink'; } else if (code === 8) { return 'hide'; } else if (code === 9) { return 'strike'; } else if ((29 < code && code < 38) || code === 39 || (89 < code && code < 98)) { return 'foreground-color'; } else if ((39 < code && code < 48) || code === 49 || (99 < code && code < 108)) { return 'background-color'; } return ''; } function pushText(text: string, options: AnsiToHtmlOptions): string { if (options.escapeXML) { return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); } return text; } function pushTag(stack: string[], tag: string, style?: string): string { if (!style) { style = ''; } stack.push(tag); return ['<' + tag, style ? ' style="' + style + '"' : void 0, '>'].join(''); } function pushStyle(stack: string[], style: string): string { return pushTag(stack, 'span', style); } function pushForegroundColor(stack: string[], color: string): string { return pushTag(stack, 'span', 'color:' + color); } function pushBackgroundColor(stack: string[], color: string): string { return pushTag(stack, 'span', 'background-color:' + color); } function closeTag(stack: string[], style: string): string { let last: string | null = null; if (stack.slice(-1)[0] === style) { last = stack.pop() || null; } if (last) { return '</' + style + '>'; } return ''; } type TokenizeCallback = (token: string, data: string | number) => void; interface Token { pattern: RegExp; sub: (m: string, ...args: any[]) => string; } function tokenize(text: string, options: AnsiToHtmlOptions, callback: TokenizeCallback) { let ansiMatch = false; const ansiHandler = 3; function remove(): string { return ''; } function rgb(m) { callback('rgb', m); return ''; } function removeXterm256(m: string): string { callback('xterm256', m); return ''; } function newline(m: string): string { if (options.newline) { callback('display', -1); } else { callback('text', m); } return ''; } function ansiMess(m: string, g1: string): string { ansiMatch = true; if (g1.trim().length === 0) { g1 = '0'; } const res: string[] = g1.replace(/;+$/, '').split(';'); for (let o = 0, len = res.length; o < len; o++) { callback('display', res[o]); } return ''; } function realText(m: string): string { callback('text', m); return ''; } /* eslint no-control-regex:0 */ const tokens: Token[] = [ { pattern: /^\x08+/, sub: remove, }, { pattern: /^\x1b\[[012]?K/, sub: remove, }, { pattern: /^\x1b\[[34]8;2;\d+;\d+;\d+m/, sub: rgb, }, { pattern: /^\x1b\[[34]8;5;(\d+)m/, sub: removeXterm256, }, { pattern: /^\n/, sub: newline, }, { pattern: /^\x1b\[((?:\d{1,3};)*\d{1,3}|)m/, sub: ansiMess, }, { pattern: /^\x1b\[?[\d;]{0,3}/, sub: remove, }, { pattern: /^([^\x1b\x08\n]+)/, sub: realText, }, ]; function process(handler: Token, i: number): void { if (i > ansiHandler && ansiMatch) { return; } ansiMatch = false; text = text.replace(handler.pattern, handler.sub); } let handler: Token; const results1: number[] = []; let length: number = text.length; outer: while (length > 0) { for (let i = 0, o = 0, len = tokens.length; o < len; i = ++o) { handler = tokens[i]; process(handler, i); if (text.length !== length) { // We matched a token and removed it from the text. We need to // start matching *all* tokens against the new text. length = text.length; continue outer; } } if (text.length === length) { break; } else { results1.push(0); } length = text.length; } return results1; } /** * A sticky stack element */ interface StickyStackElement { token: string; data: number | string; category: string; } /** * If streaming, then the stack is "sticky" */ function updateStickyStack( stickyStack: StickyStackElement[], token: string, data: string | number ): StickyStackElement[] { if (token !== 'text') { stickyStack = stickyStack.filter(notCategory(categoryForCode(data))); stickyStack.push({ token: token, data: data, category: categoryForCode(data), }); } return stickyStack; } export class Filter { private readonly opts: AnsiToHtmlOptions; private readonly stack: string[]; private stickyStack: StickyStackElement[]; public constructor(options: AnsiToHtmlOptions) { if (options.colors) { options.colors = _.extend(defaults.colors, options.colors); } this.opts = _.extend({}, defaults, options); this.stack = []; this.stickyStack = []; } public toHtml(_input: string | string[]): string { const input: string[] = typeof _input === 'string' ? [_input] : _input; const stack = this.stack; const options = this.opts; const buf: string[] = []; this.stickyStack.forEach((element: StickyStackElement) => { const output: string = generateOutput(stack, element.token, element.data, options); if (output) { buf.push(output); } }); tokenize(input.join(''), options, (token, data) => { const output = generateOutput(stack, token, data, options); if (output) { buf.push(output); } if (options.stream) { this.stickyStack = updateStickyStack(this.stickyStack, token, data); } }); if (stack.length) { buf.push(resetStyles(stack)); } return buf.join(''); } public reset() { this.stickyStack = []; } }
the_stack
import * as Express from 'express' import * as Path from 'path' import * as HTTP from 'http' import * as SocketIo from 'socket.io' import * as Tool from './tools/initSystem' import * as Async from 'async' import * as Fs from 'fs' import * as Uuid from 'node-uuid' import * as Imap from './tools/imap' import CoNETConnectCalss from './tools/coNETConnect' import * as mime from 'mime-types' interface localConnect { socket: SocketIO.Socket login: boolean listenAfterPasswd: boolean } let logFileFlag = 'w' const saveLog = ( err: {} | string ) => { if ( !err ) { return } const data = `${ new Date().toUTCString () }: ${ typeof err === 'object' ? ( err['message'] ? err['message'] : '' ) : err }\r\n` console.log ( data ) return Fs.appendFile ( Tool.ErrorLogFile, data, { flag: logFileFlag }, () => { return logFileFlag = 'a' }) } const saveServerStartup = ( localIpaddress: string ) => { const info = `\n*************************** Kloak Platform [ ${ Tool.CoNET_version } ] server start up *****************************\n` + `Access url: http://${ localIpaddress }:${ Tool.LocalServerPortNumber }\n` saveLog ( info ) } const saveServerStartupError = ( err: {} ) => { const info = `\n*************************** Kloak Platform [ ${ Tool.CoNET_version } ] server startup falied *****************************\n` + `platform ${ process.platform }\n` + `${ err['message'] }\n` saveLog ( info ) } const imapErrorCallBack = ( message: string ) => { if ( message && message.length ) { if ( /auth|login|log in|Too many simultaneous|UNAVAILABLE/i.test( message )) { return 1 } if ( /ECONNREFUSED/i.test ( message )) { return 5 } if (/OVERQUOTA/i.test ( message )) { return 6 } if ( /certificate/i.test ( message )) { return 2 } if ( /timeout|ENOTFOUND/i.test ( message )) { return 0 } return 5 } return -1 } export default class localServer { private expressServer = Express() private httpServer = HTTP.createServer ( this.expressServer ) private socketServer = SocketIo ( this.httpServer ) public config: install_config = null public keyPair: keypair = null public savedPasswrod: string = '' public localConnected: Map < string, localConnect > = new Map () private openPgpKeyOption = null private localKeyPair = null private serverKeyPassword = Uuid.v4() private requestPool: Map < string, SocketIO.Socket > = new Map() private imapConnectPool: Map <string, CoNETConnectCalss> = new Map() private catchCmd ( mail: string, uuid: string ) { console.log ( `Get response from CoNET uuid [${ uuid }] length [${ mail.length }]`) const socket = this.requestPool.get ( uuid ) if ( !socket ) { return console.log (`Get cmd that have no matched socket \n\n`, mail ) } socket.emit ( 'doingRequest', mail, uuid ) } private tryConnectCoNET ( socket: SocketIO.Socket, imapData: IinputData, sendMail: boolean ) { console.log (`doing tryConnectCoNET`) // have CoGate connect let userConnet: CoNETConnectCalss = socket ["userConnet"] = socket ["userConnet"] || this.imapConnectPool.get ( imapData.account ) if ( userConnet ) { console.log (`tryConnectCoNET already have room;[${ userConnet.socket.id }]`) socket.join ( userConnet.socket.id ) return userConnet.Ping( sendMail ) } const _exitFunction = err => { console.trace ( `makeConnect on _exitFunction err this.CoNETConnectCalss destroy!`, err ) if ( err && err.message ) { // network error if ( / ECONNRESET /i.test) { if ( typeof userConnet.destroy === 'function' ) { userConnet.destroy () } this.imapConnectPool.set ( imapData.account, userConnet = socket [ "userConnet" ] = makeConnect ()) } } return console.log (`_exitFunction doing nathing!`) } const makeConnect = () => { return new CoNETConnectCalss ( imapData, this.socketServer, socket, ( mail, uuid ) => { return this.catchCmd ( mail, uuid ) }, _exitFunction ) } return this.imapConnectPool.set ( imapData.account, userConnet = socket ["userConnet"] = makeConnect ()) } private listenAfterPassword ( socket: SocketIO.Socket ) { const self = this let keyPair: Kloak_LocalServer_keyInfo = null let sendMail = false socket.on ( 'checkImap', ( imapConnectData, CallBack1 ) => { console.log ( `localServer on checkImap!` ) const uuid = Uuid.v4() CallBack1( uuid ) if ( !keyPair ) { return socket.emit ('imapTest', 'system' ) } return Tool.decryptoMessage ( keyPair.publicKeys, self.localKeyPair.privateKey, imapConnectData, ( err, data ) => { if ( err ) { console.log ( 'checkImap Tool.decryptoMessage error\n', err ) return socket.emit ('imapTest', 'system' ) } let imapData: IinputData = null try { imapData = JSON.parse ( data ) } catch ( ex ) { return socket.emit ('imapTest', 'system' ) } return self.doingCheckImap ( socket, imapData, keyPair ) }) }) socket.on ( 'tryConnectCoNET', ( imapData: IinputData, CallBack1 ) => { const uuid = Uuid.v4() CallBack1( uuid ) console.log ( `socket account [${ keyPair.email }]:[${ keyPair.keyID }] on tryConnectCoNET!\n\n` ) return this.tryConnectCoNET ( socket, imapData, sendMail ) }) socket.on ( 'doingRequest', ( uuid, request, CallBack1 ) => { const _uuid = Uuid.v4() CallBack1 ( _uuid ) const _callBack = ( ...data ) => { socket.emit ( _uuid, ...data ) } this.requestPool.set ( uuid, socket ) console.log ( `on doingRequest uuid = [${ uuid }]\n${ request }\n`) const userConnect = socket ["userConnet"] || this.imapConnectPool.get ( keyPair.email ) if ( userConnect ) { saveLog (`doingRequest on ${ uuid }`) return userConnect.requestCoNET_v1 ( uuid, request, _callBack ) } saveLog ( `doingRequest on ${ uuid } but have not CoNETConnectCalss need restart! socket.emit ( 'systemErr' )`) return socket.emit ( 'systemErr' ) }) socket.on ( 'getFilesFromImap', ( files: string, CallBack1 ) => { const uuid = Uuid.v4() CallBack1( uuid ) let ret = '' const _callBack = ( err ) => { socket.emit ( uuid, err, ret ) } if ( typeof files !== 'string' || !files.length ) { return _callBack ( new Error ( 'invalidRequest' )) } const _files = files.split (',') console.log (`socket.on ('getFilesFromImap') _files = [${ _files }] _files.length = [${ _files.length }]` ) const userConnect: CoNETConnectCalss = socket ["userConnet"] || this.imapConnectPool.get ( keyPair.email ) if ( !userConnect ) { console.log (`getFilesFromImap error:![ Have no userConnect ]`) return socket.emit ( 'systemErr' ) } return Async.eachSeries ( _files, ( n, next ) => { console.log (`Async.eachSeries _files[${ n }] typeof userConnect.getFile = [${ typeof userConnect.getFile }]`) return userConnect.getFile ( n, ( err, data ) => { if ( err ) { return next ( err ) } ret += data.toString () return next () }) }, _callBack ) }) socket.on ( 'sendRequestMail', ( message: string, imapData: IinputData, toMail: string, CallBack1 ) => { const _uuid = Uuid.v4() CallBack1 ( _uuid ) const _callBack = ( ...data ) => { socket.emit ( _uuid, ...data ) } sendMail = true const userConnect: CoNETConnectCalss = socket [ "userConnet" ] || this.imapConnectPool.get ( keyPair.email ) if ( userConnect ) { userConnect.Ping ( true ) } return Tool.sendCoNETConnectRequestEmail ( imapData, toMail, message, _callBack ) }) socket.on ( 'sendMedia', ( uuid, rawData, CallBack1 ) => { const _uuid = Uuid.v4() CallBack1( _uuid ) const _callBack = ( ...data ) => { socket.emit ( _uuid, ...data ) } const userConnect = this.imapConnectPool.get ( keyPair.email ) if ( !userConnect ) { return socket.emit ( 'systemErr' ) } return userConnect.sendDataToANewUuidFolder ( Buffer.from ( rawData ).toString ( 'base64' ), uuid, uuid, _callBack ) }) socket.on ( 'mime', ( _mime, CallBack1 ) => { const _uuid = Uuid.v4() CallBack1( _uuid ) console.log ( `socket.on ( 'mime' ) [${ _mime }]`) const _callBack = ( ...data ) => { socket.emit ( _uuid, ...data ) } let y = mime.lookup( _mime ) console.log ( y ) if ( !y ) { return _callBack ( new Error ('no mime')) } return _callBack ( null, y ) }) socket.on ( 'keypair', ( publicKey, CallBack ) => { console.log ( `socket.on ( 'keypair') \n`) const _uuid = Uuid.v4() CallBack( _uuid ) return Tool.getPublicKeyInfo ( publicKey, ( err, data ) => { if ( err ) { return socket.emit ( _uuid, err ) } keyPair = data let connect = false const _connect = this.imapConnectPool.get ( keyPair.email ) if ( _connect ) { connect = true } socket.emit ( _uuid, null, this.localKeyPair.public, connect ) }) }) /* socket.on ('getUrl', ( url: string, CallBack ) => { const uu = new URLSearchParams ( url ) if ( !uu || typeof uu.get !== 'function' ) { console.log (`getUrl [${ url }] have not any URLSearchParams`) return CallBack () } return CallBack ( null, uu.get('imgrefurl'), uu.get('/imgres?imgurl')) }) */ } private doingCheckImap ( socket: SocketIO.Socket, imapData: IinputData, keyPair:Kloak_LocalServer_keyInfo ) { return Async.series ([ next => Imap.imapAccountTest ( imapData, err => { if ( err ) { return next ( err ) } console.log (`imapAccountTest success!`, typeof next ) socket.emit ( 'imapTest' ) return next () }), next => Tool.smtpVerify ( imapData, next ) ], ( err: Error ) => { if ( err ) { console.log ( `doingCheckImap Async.series Error!`, err ) return socket.emit ( 'imapTest', err.message || err ) } imapData.imapTestResult = true return Tool.encryptMessage ( keyPair.publicKeys, this.localKeyPair.privateKey, JSON.stringify ( imapData ), ( err, data ) => { return socket.emit ( 'imapTestFinish' , err, data ) }) }) } private newKeyPair ( CallBack ) { return Tool.newKeyPair ( "admin@Localhost.local", "admin", this.serverKeyPassword, ( err, data ) => { if ( err ) { return CallBack ( err ) } this.localKeyPair = data return CallBack () }) } private socketServerConnected ( socket: SocketIO.Socket ) { const clientName = `[${ socket.id }][ ${ socket.conn.remoteAddress }]` let sessionHash = '' const clientObj: localConnect = { listenAfterPasswd: false, socket: socket, login: false } saveLog ( `socketServerConnected ${ clientName } connect ${ this.localConnected.size }`) return this.listenAfterPassword ( socket ) } constructor( private cmdResponse: ( cmd: QTGateAPIRequestCommand ) => void, test: boolean ) { //Express.static.mime.define({ 'message/rfc822' : ['mhtml','mht'] }) //Express.static.mime.define ({ 'multipart/related' : ['mhtml','mht'] }) Express.static.mime.define ({ 'application/x-mimearchive' : ['mhtml','mht'] }) this.expressServer.set ( 'views', Path.join ( __dirname, 'views' )) this.expressServer.set ( 'view engine', 'pug' ) this.expressServer.use ( Express.static ( Tool.QTGateFolder )) this.expressServer.use ( Express.static ( Path.join ( __dirname, 'public' ))) this.expressServer.use ( Express.static ( Path.join ( __dirname, 'html' ))) this.expressServer.get ( '/', ( req, res ) => { res.render( 'home', { title: 'home', proxyErr: false }) }) this.expressServer.get ( '/message', ( req, res ) => { res.render( 'home/message', { title: 'message', proxyErr: false }) }) this.expressServer.get ( '/browserNotSupport', ( req, res ) => { res.render( 'home/browserNotSupport', { title: 'browserNotSupport', proxyErr: false }) }) this.socketServer.on ( 'connection', socker => { return this.socketServerConnected ( socker ) }) this.httpServer.once ( 'error', err => { console.log (`httpServer error`, err ) saveServerStartupError ( err ) return process.exit (1) }) this.newKeyPair ( err => { if ( err ) { return saveServerStartupError ( err ) } return this.httpServer.listen ( Tool.LocalServerPortNumber, () => { saveServerStartup ( `localhost`) }) }) } }
the_stack
import * as csstree from 'css-tree' import { CSSColor, CSSColorHSL, cssColorHSL, CSSColorRGB, cssColorRGB, cssKeyword, CSSKeyword, CSSNumber, cssNumber, CSSNumberUnit, LengthUnit, LengthUnits, parseColor, ParsedCurlyBrace, parsedCurlyBrace, ParsedDoubleBar, parsedDoubleBar, } from '../../components/inspector/common/css-utils' import { Either, eitherToMaybe, isRight, left, right, Right, sequenceEither, traverseEither, mapEither, } from '../../core/shared/either' import * as csstreemissing from '../../missing-types/css-tree' import utils from '../../utils/utils' import { arrayIndexNotPresentParseError, descriptionParseError, parseAlternative, Parser, ParseResult, } from '../../utils/value-parser-utils' export function getLexerPropertyMatches( propertyName: string, propertyValue: unknown, defaultUnit: string, syntaxNamesToFilter?: ReadonlyArray<string>, ): Either<string, Array<LexerMatch>> { if (typeof propertyValue === 'string' || typeof propertyValue === 'number') { const valueToUse = typeof propertyValue === 'number' ? `${propertyValue}${defaultUnit}` : propertyValue const ast = csstree.parse(valueToUse, { context: 'value', }) const lexerMatch = (csstree as any).lexer.matchProperty(propertyName, ast) if (lexerMatch.error === null && ast.type === 'Value') { if (syntaxNamesToFilter != null) { const filtered = lexerMatch.matched.match.filter( (m: LexerMatch) => 'name' in m.syntax && syntaxNamesToFilter.includes(m.syntax.name), ) return right(filtered) } else { return right(lexerMatch.matched.match) } } else { return left(lexerMatch.error.message) } } return left(`Property ${propertyName}'s value is not a string`) } export function getLexerTypeMatches(typeName: string, value: unknown): Either<string, LexerMatch> { if (typeof value === 'string') { const ast = csstree.parse(value, { context: 'value', positions: true, }) const lexerMatch = (csstree as any).lexer.matchType(typeName, ast) if (lexerMatch.error === null && ast.type === 'Value') { return right(lexerMatch.matched) } else { return left(lexerMatch.error.message) } } return left(`Property ${typeName}'s value is not a string`) } // Keywords export const parseCSSKeyword: Parser<CSSKeyword> = (match: unknown) => { if (isLexerToken(match) && match.syntax != null && match.syntax.type === 'Keyword') { return right(cssKeyword(match.syntax.name)) } else { return left(descriptionParseError('Leaf is not a keyword')) } } export function parseCSSValidKeyword<T extends string>( valid: ReadonlyArray<T>, ): Parser<CSSKeyword<T>> { return function (value: unknown) { const parsed = parseCSSKeyword(value) if (isRight(parsed)) { if (valid.includes(parsed.value.value as T)) { return parsed as Right<CSSKeyword<T>> } else { return left(descriptionParseError(`${value} is not valid keyword`)) } } else { return parsed } } } // Numbers export const parseNumber: Parser<CSSNumber> = (value) => { if ( isLexerMatch(value) && isNamedSyntaxType(value.syntax, ['number']) && value.match[0] != null && isLexerToken(value.match[0]) && value.match[0].node.type === 'Number' ) { return right(cssNumber(Number(value.match[0].node.value), null)) } return left(descriptionParseError(`${value} is not a number`)) } export const parseAngle: Parser<CSSNumber> = (value) => { if ( isLexerMatch(value) && isNamedSyntaxType(value.syntax, ['angle']) && value.match[0] != null && isLexerToken(value.match[0]) && value.match[0].node.type === 'Dimension' ) { return right( cssNumber(Number(value.match[0].node.value), value.match[0].node.unit as CSSNumberUnit), ) } return left(descriptionParseError(`${value} is not an angle`)) } export const parsePercentage: Parser<CSSNumber> = (value: unknown) => { if (isLexerMatch(value) && value.match.length === 1) { const match = value.match[0] if (isLexerToken(match)) { if (match.node.type === 'Percentage') { const number = Number(match.node.value) if (!isNaN(number)) { return right(cssNumber(number, '%')) } else { return left(descriptionParseError(`${match.node.value} is not a valid percentage number`)) } } } } return left(descriptionParseError('leaf is not Percentage')) } export const parseLength: Parser<CSSNumber> = (value: unknown) => { if (isLexerMatch(value)) { if (value.match.length === 1 && value.match[0] != null) { const leaf = value.match[0] if (isLexerToken(leaf)) { if (leaf.node.type === 'Dimension') { const number = Number(leaf.node.value) const unit = leaf.node.unit ?? 'px' if (!isNaN(number) && LengthUnits.includes(unit as LengthUnit)) { return right(cssNumber(number, unit as LengthUnit)) } } else if (leaf.node.type === 'Number' && leaf.node.value === '0') { return right(cssNumber(0, null)) } } } else { return left(arrayIndexNotPresentParseError(0)) } } return left(descriptionParseError('leaf is not Dimension')) } export const parseLengthPercentage: Parser<CSSNumber> = (value: unknown) => { if (isLexerMatch(value) && value.match.length === 1) { if (value.syntax.type === 'Type' && value.syntax.name === 'length-percentage') { return parseAlternative<CSSNumber>( [parseLength, parsePercentage], 'Could not parse length-percentage', )(value.match[0]) } else { // TODO let's check from syntax if it's a length or percentage return parseAlternative<CSSNumber>( [parseLength, parsePercentage], 'Could not parse length-percentage', )(value) } } return left(descriptionParseError('Could not parse length-percentage')) } export function parseWholeValue<T>(parser: Parser<T>): Parser<T> { return function (match: unknown) { if (Array.isArray(match) && match.length === 1) { return parser(match[0]) } else { return left(descriptionParseError(`Match ${JSON.stringify(match)} is not an array`)) } } } export const parseAlphaValue: Parser<CSSNumber> = (value) => { if (isLexerMatch(value) && value.match[0] != null) { return parseAlternative<CSSNumber>( [parseNumber, parsePercentage], `Match ${JSON.stringify(value.match[0])} is not a valid number or percentage <alpha-value>`, )(value.match[0]) } else { return left( descriptionParseError( `Match ${JSON.stringify(value)} is not a valid <alpha-value> lexer match`, ), ) } } export const parseHue: Parser<CSSNumber> = (value) => { if (isLexerMatch(value) && value.match[0] != null) { return parseAlternative<CSSNumber>( [parseNumber, parseAngle], `Match ${JSON.stringify(value.match[0])} is not a valid number or angle <hue>`, )(value.match[0]) } else { return left( descriptionParseError(`Match ${JSON.stringify(value)} is not a valid <hue> lexer match`), ) } } export const parseRGBColor: Parser<CSSColorRGB> = (value) => { if (isLexerMatch(value) && isNamedSyntaxType(value.syntax, ['rgb()', 'rgba()'])) { let percentagesUsed: boolean = false let percentageAlpha: boolean = false const parsedComponents = utils.stripNulls( value.match.map((v) => { if ( isLexerMatch(v) && isNamedSyntaxType(v.syntax, ['percentage', 'number', 'alpha-value']) ) { switch (v.syntax.name) { case 'percentage': // lexer guarantees all value types match, so we can safely go off of last used percentagesUsed = true return eitherToMaybe(parsePercentage(v)) case 'number': percentagesUsed = false return eitherToMaybe(parseNumber(v)) case 'alpha-value': const parsed = parseAlphaValue(v) if (isRight(parsed) && parsed.value.unit === '%') { percentageAlpha = true parsed.value.value = parsed.value.value / 100 } return eitherToMaybe(parsed) default: const _exhaustiveCheck: never = v.syntax.name throw `Unexpected syntax name type in rgb()` } } return null }), ) if (parsedComponents.length >= 3) { const alpha = parsedComponents[3] != null ? parsedComponents[3].value : 1 return right( cssColorRGB( parsedComponents[0].value, parsedComponents[1].value, parsedComponents[2].value, alpha, percentageAlpha, percentagesUsed, ), ) } } return left(descriptionParseError(`Match ${JSON.stringify(value)} is not an rgb(a) color`)) } export const parseHSLColor: Parser<CSSColorHSL> = (value) => { if (isLexerMatch(value) && isNamedSyntaxType(value.syntax, ['hsl()', 'hsla()'])) { let percentageAlpha: boolean = false const parsedComponents = utils.stripNulls( value.match.map((v) => { if (isLexerMatch(v) && isNamedSyntaxType(v.syntax, ['hue', 'percentage', 'alpha-value'])) { switch (v.syntax.name) { case 'hue': return eitherToMaybe(parseHue(v)) case 'percentage': return eitherToMaybe(parsePercentage(v)) case 'alpha-value': const parsed = parseAlphaValue(v) if (isRight(parsed) && parsed.value.unit === '%') { percentageAlpha = true parsed.value.value = parsed.value.value / 100 } return eitherToMaybe(parsed) default: const _exhaustiveCheck: never = v.syntax.name throw `Unexpected syntax name type in hsl()` } } return null }), ) if ( parsedComponents.length >= 3 && (parsedComponents[0].unit === 'deg' || parsedComponents[0].unit === null) ) { const alpha = parsedComponents[3] != null ? parsedComponents[3].value : 1 return right( cssColorHSL( parsedComponents[0].value, parsedComponents[1].value, parsedComponents[2].value, alpha, percentageAlpha, ), ) } } return left(descriptionParseError(`Match ${JSON.stringify(value)} is not an hsl(a) color`)) } export const parseLexedColor: Parser<CSSColor> = (value) => { if ( isLexerMatch(value) && value.syntax.type === 'Type' && value.syntax.name === 'color' && value.match.length === 1 ) { if (value.match[0] != null) { const leaf = value.match[0] if (isLexerMatch(leaf)) { if (isNamedSyntaxType(leaf.syntax, ['rgb()', 'rgba()', 'hsl()', 'hsla()'])) { const parsed = parseAlternative<CSSColorRGB | CSSColorHSL>( [parseRGBColor, parseHSLColor], `Value ${JSON.stringify( value, )} is not an <rgb()>, <rgba()>, <hsl()>, or <hsla()> color`, )(leaf) return parsed } else if (isNamedSyntaxType(leaf.syntax, ['hex-color', 'named-color'])) { if (leaf.match[0] != null) { const tokenLeaf = leaf.match[0] if (isLexerToken(tokenLeaf)) { const parsed = parseColor(tokenLeaf.token, 'hex-hash-optional') if (isRight(parsed)) { return parsed } else { return left(descriptionParseError(parsed.value)) } } } } return left(descriptionParseError('color is valid, but not supported by utopia')) } return left(arrayIndexNotPresentParseError(0)) } } return left(descriptionParseError('leaf is not color')) } // Curly Braces export function parseCurlyBraces<T>( min: number, max: number, parsers: Array<Parser<T>>, ): Parser<ParsedCurlyBrace<T>> { return function (match: unknown) { if (Array.isArray(match) && match.length >= min && match.length <= max) { const parsed = sequenceEither( match.map((m) => parseAlternative(parsers, 'Match is not valid curly brace value.')(m)), ) return mapEither(parsedCurlyBrace, parsed) } return left(descriptionParseError('Lexer element is not a match')) } } export function parseDoubleBar<T>( max: number, parsers: Array<Parser<T>>, ): Parser<ParsedDoubleBar<T>> { return function (match: unknown) { if (Array.isArray(match) && match.length > 0 && match.length <= max) { const parsed = traverseEither( (m: Array<unknown>) => parseAlternative(parsers, 'Match is not valid double bar value.')(m), match, ) return mapEither(parsedDoubleBar, parsed) } return left(descriptionParseError('Lexer element is not a match')) } } export function parseCSSArray<T>(parsers: Array<Parser<T>>): Parser<Array<T>> { return (match: unknown): ParseResult<Array<T>> => { if (Array.isArray(match) && match.length > 0) { return traverseEither((value) => { return parseAlternative(parsers, 'Match is not valid array value.')(value) }, match) } return left(descriptionParseError('Lexer element is not a match')) } } // Type is very much in flex, if you find it doesn't match the data, fix it please export type LexerToken<T extends string = string> = { syntax: csstreemissing.Syntax.Keyword<T> | null token: string node: csstree.CssNode } function isLexerToken(leaf: unknown): leaf is LexerToken<string> { const anyLeaf = leaf as any return typeof anyLeaf === 'object' && anyLeaf.token != null && anyLeaf.node != null } // Type is very much in flex, if you find it doesn't match the data, fix it please export type LexerMatch< T extends csstreemissing.Syntax.SyntaxItem = csstreemissing.Syntax.SyntaxItem > = { syntax: T match: Array<LexerElement> } export function isLexerMatch(parent: unknown): parent is LexerMatch { const anyParent = parent as any return anyParent.match != null && Array.isArray(anyParent.match) } export type LexerElement = LexerMatch | LexerToken<string> export function isNamedSyntaxType<T extends string>( syntax: csstreemissing.Syntax.SyntaxItem, names: ReadonlyArray<T>, ): syntax is csstreemissing.Syntax.Type<T> { return syntax.type === 'Type' && names.includes(syntax.name as T) } export function isNamedSyntaxProperty<T extends string>( syntax: csstreemissing.Syntax.SyntaxItem, names: ReadonlyArray<T>, ): syntax is csstreemissing.Syntax.Type<T> { return syntax.type === 'Property' && names.includes(syntax.name as T) } export interface PreparsedLayer { type: 'PREPARSED_LAYER' value: string enabled: boolean } export function preparsedLayer(value: string, enabled: boolean): PreparsedLayer { return { type: 'PREPARSED_LAYER', value, enabled, } } export function traverseForPreparsedLayers(toTraverse: string): Array<PreparsedLayer> { let inComment: boolean = false let layers: Array<PreparsedLayer> = [] let workingValue: string = '' let index: number = 0 function addWorkingValue(): void { const trimmedWorkingValue = workingValue.trim() if (trimmedWorkingValue !== '') { layers.push(preparsedLayer(trimmedWorkingValue, !inComment)) } workingValue = '' } while (index < toTraverse.length) { let shiftIndexBy: number = 1 switch (toTraverse[index]) { case '/': { if (toTraverse[index + 1] === '*') { addWorkingValue() inComment = true shiftIndexBy = 2 } else { workingValue = workingValue += '/' } break } case '*': { if (inComment && toTraverse[index + 1] === '/') { addWorkingValue() inComment = false shiftIndexBy = 2 } else { workingValue = workingValue + '*' } break } case ',': { if (!inComment) { addWorkingValue() inComment = false } break } default: { workingValue = workingValue + toTraverse[index] } } index += shiftIndexBy } addWorkingValue() return layers } export function cssValueOnlyContainsComments(cssValue: string): boolean { const layers = traverseForPreparsedLayers(cssValue) return layers.every((l) => l.enabled === false) }
the_stack
/// <reference types="node" /> import * as Stream from "stream"; import { Context as BaseContext, Options as BaseWriterOptions, } from "conventional-changelog-writer"; import { Commit, Options as BaseParserOptions, } from "conventional-commits-parser"; import { Options as RecommendedBumpOptions } from "conventional-recommended-bump"; import { GitOptions as BaseGitRawCommitsOptions } from "git-raw-commits"; import { Package } from "normalize-package-data"; /** * Returns a readable stream. * * @param options * @param context * @param gitRawCommitsOpts * @param parserOpts * @param writerOpts */ // tslint:disable-next-line max-line-length declare function conventionalChangelogCore<TCommit extends Commit = Commit, TContext extends BaseContext = Context>(options?: Options<TCommit, TContext>, context?: Partial<TContext>, gitRawCommitsOpts?: GitRawCommitsOptions, parserOpts?: ParserOptions, writerOpts?: WriterOptions<TCommit, TContext>): Stream.Readable; declare namespace conventionalChangelogCore { interface Context extends BaseContext { /** * The hosting website. Eg: `'https://github.com'` or `'https://bitbucket.org'`. * * @defaults * Normalized host found in `package.json`. */ host?: BaseContext["host"] | undefined; /** * Version number of the up-coming release. If `version` is found in the last * commit before generating logs, it will be overwritten. * * @defaults * Version found in `package.json`. */ version?: BaseContext["version"] | undefined; /** * The owner of the repository. Eg: `'stevemao'`. * * @defaults * Extracted from normalized `package.json` `repository.url` field. */ owner?: BaseContext["owner"] | undefined; /** * The repository name on `host`. Eg: `'conventional-changelog-writer'`. * * @defaults * Extracted from normalized `package.json` `repository.url` field. */ repository?: BaseContext["repository"] | undefined; /** * The whole repository url. Eg: `'https://github.com/conventional-changelog/conventional-changelog-writer'`. * The should be used as a fallback when `context.repository` doesn't exist. * * @defaults * The whole normalized repository url in `package.json`. */ repoUrl?: BaseContext["repoUrl"] | undefined; /** * @defaults * Previous semver tag or the first commit hash if no previous tag. */ previousTag?: string | undefined; /** * @defaults * Current semver tag or `'v'` + version if no current tag. */ currentTag?: string | undefined; /** * Should link to the page that compares current tag with previous tag? * * @defaults * `true` if `previousTag` and `currentTag` are truthy. */ linkCompare?: boolean | undefined; } /** * Please check the available options at http://git-scm.com/docs/git-log. * * There are some defaults: * * @remarks * Single dash arguments are not supported because of https://github.com/sindresorhus/dargs/blob/master/index.js#L5. * * @remarks * For `<revision range>` we can also use `<from>..<to>` pattern, and this * module has the following extra options for shortcut of this pattern: * * * `from` * * `to` * * This module also have the following additions: * * * `format` * * `debug` * * `path` */ interface GitRawCommitsOptions extends BaseGitRawCommitsOptions { /** * @default * '%B%n-hash-%n%H%n-gitTags-%n%d%n-committerDate-%n%ci' */ format?: BaseGitRawCommitsOptions["format"] | undefined; /** * @defaults * Based on `options.releaseCount`. */ from?: BaseGitRawCommitsOptions["from"] | undefined; /** * @defaults * `true` if `options.append` is truthy. */ reverse?: boolean | undefined; /** * A function to get debug information. * * @default * options.debug */ debug?: BaseGitRawCommitsOptions["debug"] | undefined; } type MergedContext<T extends BaseContext = BaseContext> = T & MergedContext.ExtraContext; namespace MergedContext { interface ExtraContext { /** * All git semver tags found in the repository. You can't overwrite this value. */ readonly gitSemverTags?: ReadonlyArray<string> | undefined; /** * Your `package.json` data. You can't overwrite this value. */ readonly packageData?: Readonly<Partial<Package>> | undefined; } } interface Options<TCommit extends Commit = Commit, TContext extends BaseContext = BaseContext> { /** * This should serve as default values for other arguments of * `conventionalChangelogCore` so you don't need to rewrite the same or similar * config across your projects. Any value in this could be overwritten. If this * is a promise (recommended if async), it should resolve with the config. If * this is a function, it expects a node style callback with the config object. * If this is an object, it is the config object. The config object should * include `context`, `gitRawCommitsOpts`, `parserOpts` and `writerOpts`. */ config?: Options.Config<TCommit, TContext> | undefined; pkg?: Options.Pkg | undefined; /** * Should the log be appended to existing data. * * @default * false */ append?: boolean | undefined; /** * How many releases of changelog you want to generate. It counts from the * upcoming release. Useful when you forgot to generate any previous changelog. * Set to `0` to regenerate all. * * @default * 1 */ releaseCount?: number | undefined; /** * If given, unstable tags (e.g. `x.x.x-alpha.1`, `x.x.x-rc.2`) will be skipped. */ skipUnstable?: boolean | undefined; /** * A debug function. EG: `console.debug.bind(console)`. * * @default * function () {} */ debug?: Options.Logger | undefined; /** * A warn function. EG: `grunt.verbose.writeln`. * * @default * options.debug */ warn?: Options.Logger | undefined; /** * A transform function that applies after the parser and before the writer. * * This is the place to modify the parsed commits. */ transform?: Options.Transform<TCommit> | undefined; /** * If this value is `true` and `context.version` equals last release then * `context.version` will be changed to `'Unreleased'`. * * @remarks * You may want to combine this option with `releaseCount` set to `0` to always * overwrite the whole CHANGELOG. `conventional-changelog` only outputs a * CHANGELOG but doesn't read any existing one. * * @defaults * `true` if a different version than last release is given. Otherwise `false`. */ outputUnreleased?: boolean | undefined; /** * Specify a package in lerna-style monorepo that the CHANGELOG should be * generated for. * * Lerna tags releases in the format `foo-package@1.0.0` and assumes that * packages are stored in the directory structure `./packages/foo-package`. * * @default * null */ lernaPackage?: string | null | undefined; /** * Specify a prefix for the git tag that will be taken into account during the * comparison. For instance if your version tag is prefixed by `version/` * instead of `v` you would specify `--tagPrefix=version/`. */ tagPrefix?: string | undefined; } namespace Options { // tslint:disable-next-line max-line-length type Config<TCommit extends Commit = Commit, TContext extends BaseContext = BaseContext> = Promise<Config.Object<TCommit, TContext>> | Config.Function<TCommit, TContext> | Config.Object<TCommit, TContext>; namespace Config { type FunctionType<TCommit extends Commit = Commit, TContext extends BaseContext = BaseContext> = (callback: FunctionType.Callback<TCommit, TContext>) => void; namespace FunctionType { type Callback<TCommit extends Commit = Commit, TContext extends BaseContext = BaseContext> = (error: any, config: ObjectType<TCommit, TContext>) => void; } interface ObjectType<TCommit extends Commit = Commit, TContext extends BaseContext = BaseContext> { context?: Partial<TContext> | undefined; gitRawCommitsOpts?: GitRawCommitsOptions | undefined; parserOpts?: ParserOptions | undefined; recommendedBumpOpts?: RecommendedBumpOptions | undefined; writerOpts?: WriterOptions<TCommit, TContext> | undefined; } export { FunctionType as Function, ObjectType as Object, }; } type Logger = (message?: any) => void; interface Pkg { /** * The location of your "package.json". */ path?: string | undefined; /** * A function that takes `package.json` data as the argument and returns the * modified data. Note this is performed before normalizing package.json data. * Useful when you need to add a leading 'v' to your version or modify your * repository url, etc. * * @defaults * Pass through. */ transform?: ((pkg: Record<string, any>) => Record<string, any>) | undefined; } interface Transform<T extends Commit = Commit> { /** * A transform function that applies after the parser and before the writer. * * This is the place to modify the parsed commits. * * @param commit The commit from conventional-commits-parser. * @param cb Callback when you are done. */ (this: Stream.Transform, commit: Commit, cb: Transform.Callback<T>): void; } namespace Transform { type Callback<T extends Commit = Commit> = (error: any, commit: T) => void; } } interface ParserOptions extends BaseParserOptions { /** * What warn function to use. For example, `console.warn.bind(console)` or * `grunt.log.writeln`. By default, it's a noop. If it is `true`, it will error * if commit cannot be parsed (strict). * * @default * options.warn */ warn?: BaseParserOptions["warn"] | undefined; } interface WriterOptions<TCommit extends Commit = Commit, TContext extends BaseContext = BaseContext> extends BaseWriterOptions<TCommit, MergedContext<TContext>> { /** * Last chance to modify your context before generating a changelog. * * Finalize context is used for generating above context. * * @remarks * If you overwrite this value the above context defaults will be gone. */ finalizeContext?: BaseWriterOptions<TCommit, MergedContext<TContext>>["finalizeContext"] | undefined; /** * A function to get debug information. * * @default * options.debug */ debug?: BaseWriterOptions["debug"] | undefined; /** * The normal order means reverse chronological order. `reverse` order means * chronological order. Are the commits from upstream in the reverse order? You * should only worry about this when generating more than one blocks of logs * based on `generateOn`. If you find the last commit is in the wrong block * inverse this value. * * @default * options.append */ reverse?: BaseWriterOptions["reverse"] | undefined; /** * If `true`, the stream will flush out the last bit of commits (could be empty) * to changelog. * * @default * options.outputUnreleased */ doFlush?: BaseWriterOptions["doFlush"] | undefined; } } type Context = conventionalChangelogCore.Context; type GitRawCommitsOptions = conventionalChangelogCore.GitRawCommitsOptions; type Options<TCommit extends Commit = Commit, TContext extends BaseContext = BaseContext> = conventionalChangelogCore.Options<TCommit, TContext>; type ParserOptions = conventionalChangelogCore.ParserOptions; type WriterOptions<TCommit extends Commit = Commit, TContext extends BaseContext = BaseContext> = conventionalChangelogCore.WriterOptions<TCommit, TContext>; export = conventionalChangelogCore;
the_stack
namespace ts { export function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string { return valueInfoToDeclarationFileText(inspectValue(name, moduleValue), formatSettings); } export function valueInfoToDeclarationFileText(valueInfo: ValueInfo, formatSettings: FormatCodeSettings): string { return textChanges.getNewFileText(toStatements(valueInfo, OutputKind.ExportEquals), ScriptKind.TS, "\n", formatting.getFormatContext(formatSettings)); } const enum OutputKind { ExportEquals, NamedExport, NamespaceMember } function toNamespaceMemberStatements(info: ValueInfo): ReadonlyArray<Statement> { return toStatements(info, OutputKind.NamespaceMember); } function toStatements(info: ValueInfo, kind: OutputKind): ReadonlyArray<Statement> { const isDefault = info.name === InternalSymbolName.Default; const name = isDefault ? "_default" : info.name; if (!isValidIdentifier(name) || isDefault && kind !== OutputKind.NamedExport) return emptyArray; const modifiers = isDefault && info.kind === ValueKind.FunctionOrClass ? [createModifier(SyntaxKind.ExportKeyword), createModifier(SyntaxKind.DefaultKeyword)] : kind === OutputKind.ExportEquals ? [createModifier(SyntaxKind.DeclareKeyword)] : kind === OutputKind.NamedExport ? [createModifier(SyntaxKind.ExportKeyword)] : undefined; const exportEquals = () => kind === OutputKind.ExportEquals ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : emptyArray; const exportDefault = () => isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : emptyArray; switch (info.kind) { case ValueKind.FunctionOrClass: return [...exportEquals(), ...functionOrClassToStatements(modifiers, name, info)]; case ValueKind.Object: const { members } = info; if (kind === OutputKind.ExportEquals) { return flatMap(members, v => toStatements(v, OutputKind.NamedExport)); } if (members.some(m => m.kind === ValueKind.FunctionOrClass)) { // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. return [...exportDefault(), createNamespace(modifiers, name, flatMap(members, toNamespaceMemberStatements))]; } // falls through case ValueKind.Const: case ValueKind.Array: { const comment = info.kind === ValueKind.Const ? info.comment : undefined; const constVar = createVariableStatement(modifiers, createVariableDeclarationList([createVariableDeclaration(name, toType(info))], NodeFlags.Const)); return [...exportEquals(), ...exportDefault(), addComment(constVar, comment)]; } default: return Debug.assertNever(info); } } function exportEqualsOrDefault(name: string, isExportEquals: boolean): ExportAssignment { return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, createIdentifier(name)); } function functionOrClassToStatements(modifiers: Modifiers, name: string, { source, prototypeMembers, namespaceMembers }: ValueInfoFunctionOrClass): ReadonlyArray<Statement> { const fnAst = parseClassOrFunctionBody(source); const { parameters, returnType } = fnAst === undefined ? { parameters: emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst); const instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : emptyArray; const classStaticMembers: ClassElement[] | undefined = instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === SyntaxKind.Constructor ? [] : undefined; const namespaceStatements = flatMap(namespaceMembers, info => { if (!isValidIdentifier(info.name)) return undefined; if (classStaticMembers) { switch (info.kind) { case ValueKind.Object: if (info.members.some(m => m.kind === ValueKind.FunctionOrClass)) { break; } // falls through case ValueKind.Array: case ValueKind.Const: classStaticMembers.push( addComment( createProperty(/*decorators*/ undefined, [createModifier(SyntaxKind.StaticKeyword)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === ValueKind.Const ? info.comment : undefined)); return undefined; case ValueKind.FunctionOrClass: if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. const sig = tryGetMethod(info, [createModifier(SyntaxKind.StaticKeyword)]); if (sig) { classStaticMembers.push(sig); return undefined; } } } } return toStatements(info, OutputKind.NamespaceMember); }); const decl = classStaticMembers ? createClassDeclaration( /*decorators*/ undefined, modifiers, name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, [ ...classStaticMembers, ...(parameters.length ? [createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : emptyArray), ...instanceProperties, // ignore non-functions on the prototype ...mapDefined(prototypeMembers, info => info.kind === ValueKind.FunctionOrClass ? tryGetMethod(info) : undefined), ]) : createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); return [decl, ...(namespaceStatements.length === 0 ? emptyArray : [createNamespace(modifiers && modifiers.map(m => getSynthesizedDeepClone(m)), name, namespaceStatements)])]; } function tryGetMethod({ name, source }: ValueInfoFunctionOrClass, modifiers?: Modifiers): MethodDeclaration | undefined { if (!isValidIdentifier(name)) return undefined; const fnAst = parseClassOrFunctionBody(source); if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === SyntaxKind.Constructor)) return undefined; const sig = getParametersAndReturnType(fnAst); return sig && createMethod( /*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, sig.parameters, sig.returnType, /*body*/ undefined); } function toType(info: ValueInfo): TypeNode { switch (info.kind) { case ValueKind.Const: return createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); case ValueKind.Array: return createArrayTypeNode(toType(info.inner)); case ValueKind.FunctionOrClass: return createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. case ValueKind.Object: return createTypeLiteralNode(info.members.map(m => createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined))); default: return Debug.assertNever(info); } } // Parses assignments to "this.x" in the constructor into class property declarations function getConstructorFunctionInstanceProperties(fnAst: FunctionOrConstructorNode): ReadonlyArray<PropertyDeclaration> { const members: PropertyDeclaration[] = []; forEachOwnNodeOfFunction(fnAst, node => { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && isPropertyAccessExpression(node.left) && node.left.expression.kind === SyntaxKind.ThisKeyword) { const name = node.left.name.text; if (!isJsPrivate(name)) members.push(createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); } }); return members; } interface ParametersAndReturnType { readonly parameters: ReadonlyArray<ParameterDeclaration>; readonly returnType: TypeNode; } function getParametersAndReturnType(fnAst: FunctionOrConstructor): ParametersAndReturnType { if (typeof fnAst === "number") { return { parameters: fill(fnAst, i => makeParameter(`p${i}`, anyType())), returnType: anyType() }; } let usedArguments = false, hasReturn = false; forEachOwnNodeOfFunction(fnAst, node => { usedArguments = usedArguments || isIdentifier(node) && node.text === "arguments"; hasReturn = hasReturn || isReturnStatement(node) && !!node.expression && node.expression.kind !== SyntaxKind.VoidExpression; }); const parameters = [ ...fnAst.parameters.map(p => makeParameter(`${p.name.getText()}`, inferParameterType(fnAst, p))), ...(usedArguments ? [makeRestParameter()] : emptyArray), ]; return { parameters, returnType: hasReturn ? anyType() : createKeywordTypeNode(SyntaxKind.VoidKeyword) }; } function makeParameter(name: string, type: TypeNode): ParameterDeclaration { return createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); } function makeRestParameter(): ParameterDeclaration { return createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, createToken(SyntaxKind.DotDotDotToken), "args", /*questionToken*/ undefined, createArrayTypeNode(anyType())); } type FunctionOrConstructorNode = FunctionExpression | ArrowFunction | ConstructorDeclaration | MethodDeclaration; type FunctionOrConstructor = FunctionOrConstructorNode | number; // number is for native function /** Returns 'undefined' for class with no declared constructor */ function parseClassOrFunctionBody(source: string | number): FunctionOrConstructor | undefined { if (typeof source === "number") return source; const classOrFunction = tryCast(parseExpression(source), (node): node is FunctionExpression | ArrowFunction | ClassExpression => isFunctionExpression(node) || isArrowFunction(node) || isClassExpression(node)); return classOrFunction ? isClassExpression(classOrFunction) ? find(classOrFunction.members, isConstructorDeclaration) : classOrFunction // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. : cast(first(cast(parseExpression(`{ ${source} }`), isObjectLiteralExpression).properties), isMethodDeclaration); } function parseExpression(expr: string): Expression { const text = `const _ = ${expr}`; const srcFile = createSourceFile("test.ts", text, ScriptTarget.Latest, /*setParentNodes*/ true); return first(cast(first(srcFile.statements), isVariableStatement).declarationList.declarations).initializer!; } function inferParameterType(_fn: FunctionOrConstructor, _param: ParameterDeclaration): TypeNode { // TODO: Inspect function body for clues (see inferFromUsage.ts) return anyType(); } // Descends through all nodes in a function, but not in nested functions. function forEachOwnNodeOfFunction(fnAst: FunctionOrConstructorNode, cb: (node: Node) => void) { fnAst.body!.forEachChild(function recur(node) { cb(node); if (!isFunctionLike(node)) node.forEachChild(recur); }); } function isValidIdentifier(name: string): boolean { const keyword = stringToToken(name); return !(keyword && isNonContextualKeyword(keyword)) && isIdentifierText(name, ScriptTarget.ESNext); } type Modifiers = ReadonlyArray<Modifier> | undefined; function addComment<T extends Node>(node: T, comment: string | undefined): T { if (comment !== undefined) addSyntheticLeadingComment(node, SyntaxKind.SingleLineCommentTrivia, comment); return node; } function anyType(): KeywordTypeNode { return createKeywordTypeNode(SyntaxKind.AnyKeyword); } function createNamespace(modifiers: Modifiers, name: string, statements: ReadonlyArray<Statement>): NamespaceDeclaration { return createModuleDeclaration(/*decorators*/ undefined, modifiers, createIdentifier(name), createModuleBlock(statements), NodeFlags.Namespace) as NamespaceDeclaration; } }
the_stack
"use strict"; import APIGatewayWrapper = require("./aws/api-gateway-wrapper"); import CloudFormationWrapper = require("./aws/cloud-formation-wrapper"); import DomainConfig = require("./domain-config"); import Globals from "./globals"; import {CustomDomain, ServerlessInstance, ServerlessOptions} from "./types"; import {getAWSPagedResults, sleep, throttledCall} from "./utils"; const certStatuses = ["PENDING_VALIDATION", "ISSUED", "INACTIVE"]; class ServerlessCustomDomain { // AWS SDK resources public apiGatewayWrapper: APIGatewayWrapper; public route53: any; public acm: any; public cloudFormationWrapper: CloudFormationWrapper; // Serverless specific properties public serverless: ServerlessInstance; public options: ServerlessOptions; public commands: object; public hooks: object; // Domain Manager specific properties public domains: DomainConfig[] = []; constructor(serverless: ServerlessInstance, options: ServerlessOptions) { this.serverless = serverless; Globals.serverless = serverless; this.options = options; Globals.options = options; this.commands = { create_domain: { lifecycleEvents: [ "create", "initialize", ], usage: "Creates a domain using the domain name defined in the serverless file", }, delete_domain: { lifecycleEvents: [ "delete", "initialize", ], usage: "Deletes a domain using the domain name defined in the serverless file", }, }; this.hooks = { "after:deploy:deploy": this.hookWrapper.bind(this, this.setupBasePathMappings), "after:info:info": this.hookWrapper.bind(this, this.domainSummaries), "before:deploy:deploy": this.hookWrapper.bind(this, this.createOrGetDomainForCfOutputs), "before:remove:remove": this.hookWrapper.bind(this, this.removeBasePathMappings), "create_domain:create": this.hookWrapper.bind(this, this.createDomains), "delete_domain:delete": this.hookWrapper.bind(this, this.deleteDomains), }; } /** * Wrapper for lifecycle function, initializes variables and checks if enabled. * @param lifecycleFunc lifecycle function that actually does desired action */ public async hookWrapper(lifecycleFunc: any) { // check if `customDomain` or `customDomains` config exists this.validateConfigExists(); // init config variables this.initializeVariables(); // Validate the domain configurations this.validateDomainConfigs(); // setup AWS resources this.initAWSResources(); return await lifecycleFunc.call(this); } /** * Validate if the plugin config exists */ public validateConfigExists(): void { // Make sure customDomain configuration exists, stop if not const config = this.serverless.service.custom; const domainExists = config && typeof config.customDomain !== "undefined"; const domainsExists = config && typeof config.customDomains !== "undefined"; if (typeof config === "undefined" || (!domainExists && !domainsExists)) { throw new Error(`${Globals.pluginName}: Plugin configuration is missing.`); } } /** * Goes through custom domain property and initializes local variables and cloudformation template */ public initializeVariables(): void { const config = this.serverless.service.custom; const domainConfig = config.customDomain ? [config.customDomain] : []; const domainsConfig = config.customDomains || []; const customDomains: CustomDomain[] = domainConfig.concat(domainsConfig); // Loop over the domain configurations and populate the domains array with DomainConfigs this.domains = []; customDomains.forEach((domain) => { const apiTypes = Object.keys(Globals.apiTypes); const configKeys = Object.keys(domain); // If the key of the item in config is an api type it is using per api type domain structure if (apiTypes.some((apiType) => configKeys.includes(apiType))) { // validate invalid api types const invalidApiTypes = configKeys.filter((configType) => !apiTypes.includes(configType)); if (invalidApiTypes.length) { throw Error(`Invalid API Type(s): ${invalidApiTypes}-${invalidApiTypes.join("; ")}`); } // init config for each type for (const configApiType of configKeys) { const typeConfig = domain[configApiType]; typeConfig.apiType = configApiType; this.domains.push(new DomainConfig(typeConfig)); } } else { // Default to single domain config this.domains.push(new DomainConfig(domain)); } }); // Filter inactive domains this.domains = this.domains.filter((domain) => domain.enabled); } /** * Validates domain configs to make sure they are valid, ie HTTP api cannot be used with EDGE domain */ public validateDomainConfigs() { this.domains.forEach((domain) => { // Show warning if allowPathMatching is set to true if (domain.allowPathMatching) { Globals.logWarning(`"allowPathMatching" is set for ${domain.givenDomainName}. This should only be used when migrating a path to a different API type. e.g. REST to HTTP.`); } if (domain.apiType === Globals.apiTypes.rest) { // Currently no validation for REST API types } else if (domain.apiType === Globals.apiTypes.http) { // Validation for http apis // HTTP Apis do not support edge domains if (domain.endpointType === Globals.endpointTypes.edge) { throw Error(`'edge' endpointType is not compatible with HTTP APIs`); } } else if (domain.apiType === Globals.apiTypes.websocket) { // Validation for WebSocket apis // Websocket Apis do not support edge domains if (domain.endpointType === Globals.endpointTypes.edge) { throw Error(`'edge' endpointType is not compatible with WebSocket APIs`); } } }); } /** * Setup AWS resources */ public initAWSResources(): void { const credentials = this.serverless.providers.aws.getCredentials(); credentials.region = this.serverless.providers.aws.getRegion(); this.apiGatewayWrapper = new APIGatewayWrapper(credentials); this.route53 = new this.serverless.providers.aws.sdk.Route53(credentials); this.cloudFormationWrapper = new CloudFormationWrapper(credentials); } /** * Lifecycle function to create a domain * Wraps creating a domain and resource record set */ public async createDomains(): Promise<void> { await Promise.all(this.domains.map(async (domain) => { await this.createDomain(domain); })); } /** * Lifecycle function to create a domain * Wraps creating a domain and resource record set */ public async createDomain(domain: DomainConfig): Promise<void> { domain.domainInfo = await this.apiGatewayWrapper.getCustomDomainInfo(domain); try { if (!domain.domainInfo) { domain.certificateArn = await this.getCertArn(domain); await this.apiGatewayWrapper.createCustomDomain(domain); await this.changeResourceRecordSet("UPSERT", domain); Globals.logInfo( `Custom domain ${domain.givenDomainName} was created. New domains may take up to 40 minutes to be initialized.`, ); } else { Globals.logInfo(`Custom domain ${domain.givenDomainName} already exists.`); } } catch (err) { Globals.logError(err, domain.givenDomainName); throw new Error(`Unable to create domain ${domain.givenDomainName}`); } } /** * Lifecycle function to delete a domain * Wraps deleting a domain and resource record set */ public async deleteDomains(): Promise<void> { await Promise.all(this.domains.map(async (domain) => { await this.deleteDomain(domain); })); } /** * Wraps deleting a domain and resource record set */ public async deleteDomain(domain: DomainConfig): Promise<void> { domain.domainInfo = await this.apiGatewayWrapper.getCustomDomainInfo(domain); try { if (domain.domainInfo) { await this.apiGatewayWrapper.deleteCustomDomain(domain); await this.changeResourceRecordSet("DELETE", domain); domain.domainInfo = undefined; Globals.logInfo(`Custom domain ${domain.givenDomainName} was deleted.`); } else { Globals.logInfo(`Custom domain ${domain.givenDomainName} does not exist.`); } } catch (err) { Globals.logError(err, domain.givenDomainName); throw new Error(`Unable to delete domain ${domain.givenDomainName}`); } } /** * Lifecycle function to createDomain before deploy and add domain info to the CloudFormation stack's Outputs */ public async createOrGetDomainForCfOutputs(): Promise<void> { await Promise.all(this.domains.map(async (domain) => { const autoDomain = domain.autoDomain; if (autoDomain === true) { Globals.logInfo("Creating domain name before deploy."); await this.createDomain(domain); } domain.domainInfo = await this.apiGatewayWrapper.getCustomDomainInfo(domain); if (autoDomain === true) { const atLeastOneDoesNotExist = () => this.domains.some((d) => !d.domainInfo); const maxWaitFor = parseInt(domain.autoDomainWaitFor, 10) || 120; const pollInterval = 3; for (let i = 0; i * pollInterval < maxWaitFor && atLeastOneDoesNotExist() === true; i++) { Globals.logInfo(` Poll #${i + 1}: polling every ${pollInterval} seconds for domain to exist or until ${maxWaitFor} seconds have elapsed before starting deployment `); await sleep(pollInterval); domain.domainInfo = await this.apiGatewayWrapper.getCustomDomainInfo(domain); } } this.addOutputs(domain); })); } /** * Lifecycle function to create basepath mapping * Wraps creation of basepath mapping and adds domain name info as output to cloudformation stack */ public async setupBasePathMappings(): Promise<void> { await Promise.all(this.domains.map(async (domain) => { try { domain.apiId = await this.getApiId(domain); domain.apiMapping = await this.apiGatewayWrapper.getBasePathMapping(domain); domain.domainInfo = await this.apiGatewayWrapper.getCustomDomainInfo(domain); if (!domain.apiMapping) { await this.apiGatewayWrapper.createBasePathMapping(domain); } else { await this.apiGatewayWrapper.updateBasePathMapping(domain); } } catch (err) { Globals.logError(err, domain.givenDomainName); throw new Error(`Unable to setup base domain mappings for ${domain.givenDomainName}`); } })).then(() => { // Print summary upon completion this.domains.forEach((domain) => { Globals.printDomainSummary(domain); }); }); } /** * Lifecycle function to delete basepath mapping * Wraps deletion of basepath mapping */ public async removeBasePathMappings(): Promise<void> { await Promise.all(this.domains.map(async (domain) => { try { domain.apiId = await this.getApiId(domain); // Unable to find the corresponding API, manual clean up will be required if (!domain.apiId) { Globals.logInfo(`Unable to find corresponding API for ${domain.givenDomainName}, API Mappings may need to be manually removed.`); } else { domain.apiMapping = await this.apiGatewayWrapper.getBasePathMapping(domain); await this.apiGatewayWrapper.deleteBasePathMapping(domain); } } catch (err) { if (err.message.indexOf("Failed to find CloudFormation") > -1) { Globals.logInfo(`Unable to find Cloudformation Stack for ${domain.givenDomainName}, API Mappings may need to be manually removed.`); } else { Globals.logError(err, domain.givenDomainName); Globals.logError( `Unable to remove base path mappings`, domain.givenDomainName, false, ); } } const autoDomain = domain.autoDomain; if (autoDomain === true) { Globals.logInfo("Deleting domain name after removing base path mapping."); await this.deleteDomain(domain); } })); } /** * Lifecycle function to print domain summary * Wraps printing of all domain manager related info */ public async domainSummaries(): Promise<void> { for (const domain of this.domains) { domain.domainInfo = await this.apiGatewayWrapper.getCustomDomainInfo(domain); if (domain.domainInfo) { Globals.printDomainSummary(domain); } else { Globals.logInfo( `Unable to print Serverless Domain Manager Summary for ${domain.givenDomainName}`, ); } } } /** * Gets Certificate ARN that most closely matches domain name OR given Cert ARN if provided */ public async getCertArn(domain: DomainConfig): Promise<string> { if (domain.certificateArn) { Globals.logInfo(`Selected specific certificateArn ${domain.certificateArn}`); return domain.certificateArn; } let certificateArn; // The arn of the selected certificate let certificateName = domain.certificateName; // The certificate name try { const certificates = await getAWSPagedResults( domain.acm, "listCertificates", "CertificateSummaryList", "NextToken", "NextToken", {CertificateStatuses: certStatuses}, ); // The more specific name will be the longest let nameLength = 0; // Checks if a certificate name is given if (certificateName != null) { const foundCertificate = certificates .find((certificate) => (certificate.DomainName === certificateName)); if (foundCertificate != null) { certificateArn = foundCertificate.CertificateArn; } } else { certificateName = domain.givenDomainName; certificates.forEach((certificate) => { let certificateListName = certificate.DomainName; // Looks for wild card and takes it out when checking if (certificateListName[0] === "*") { certificateListName = certificateListName.substr(1); } // Looks to see if the name in the list is within the given domain // Also checks if the name is more specific than previous ones if (certificateName.includes(certificateListName) && certificateListName.length > nameLength) { nameLength = certificateListName.length; certificateArn = certificate.CertificateArn; } }); } } catch (err) { Globals.logError(err, domain.givenDomainName); throw Error(`Could not list certificates in Certificate Manager.\n${err}`); } if (certificateArn == null) { throw Error(`Could not find the certificate ${certificateName}.`); } return certificateArn; } /** * Change A Alias record through Route53 based on given action * @param action: String descriptor of change to be made. Valid actions are ['UPSERT', 'DELETE'] * @param domain: DomainInfo object containing info about custom domain */ public async changeResourceRecordSet(action: string, domain: DomainConfig): Promise<void> { if (action !== "UPSERT" && action !== "DELETE") { throw new Error(`Invalid action "${action}" when changing Route53 Record. Action must be either UPSERT or DELETE.\n`); } const createRoute53Record = domain.createRoute53Record; if (createRoute53Record !== undefined && createRoute53Record === false) { Globals.logInfo(`Skipping ${action === "DELETE" ? "removal" : "creation"} of Route53 record.`); return; } // Set up parameters const route53HostedZoneId = await this.getRoute53HostedZoneId(domain); const Changes = ["A", "AAAA"].map((Type) => ({ Action: action, ResourceRecordSet: { AliasTarget: { DNSName: domain.domainInfo.domainName, EvaluateTargetHealth: false, HostedZoneId: domain.domainInfo.hostedZoneId, }, Name: domain.givenDomainName, Type, }, })); const params = { ChangeBatch: { Changes, Comment: "Record created by serverless-domain-manager", }, HostedZoneId: route53HostedZoneId, }; // Make API call try { await throttledCall(this.route53, "changeResourceRecordSets", params); } catch (err) { Globals.logError(err, domain.givenDomainName); throw new Error(`Failed to ${action} A Alias for ${domain.givenDomainName}\n`); } } /** * Gets Route53 HostedZoneId from user or from AWS */ public async getRoute53HostedZoneId(domain: DomainConfig): Promise<string> { if (domain.hostedZoneId) { Globals.logInfo(`Selected specific hostedZoneId ${domain.hostedZoneId}`); return domain.hostedZoneId; } const filterZone = domain.hostedZonePrivate !== undefined; if (filterZone && domain.hostedZonePrivate) { Globals.logInfo("Filtering to only private zones."); } else if (filterZone && !domain.hostedZonePrivate) { Globals.logInfo("Filtering to only public zones."); } let hostedZoneData; const givenDomainNameReverse = domain.givenDomainName.split(".").reverse(); try { hostedZoneData = await throttledCall(this.route53, "listHostedZones", {}); const targetHostedZone = hostedZoneData.HostedZones .filter((hostedZone) => { let hostedZoneName; if (hostedZone.Name.endsWith(".")) { hostedZoneName = hostedZone.Name.slice(0, -1); } else { hostedZoneName = hostedZone.Name; } if (!filterZone || domain.hostedZonePrivate === hostedZone.Config.PrivateZone) { const hostedZoneNameReverse = hostedZoneName.split(".").reverse(); if (givenDomainNameReverse.length === 1 || (givenDomainNameReverse.length >= hostedZoneNameReverse.length)) { for (let i = 0; i < hostedZoneNameReverse.length; i += 1) { if (givenDomainNameReverse[i] !== hostedZoneNameReverse[i]) { return false; } } return true; } } return false; }) .sort((zone1, zone2) => zone2.Name.length - zone1.Name.length) .shift(); if (targetHostedZone) { const hostedZoneId = targetHostedZone.Id; // Extracts the hostzone Id const startPos = hostedZoneId.indexOf("e/") + 2; const endPos = hostedZoneId.length; return hostedZoneId.substring(startPos, endPos); } } catch (err) { Globals.logError(err, domain.givenDomainName); throw new Error(`Unable to list hosted zones in Route53.\n${err}`); } throw new Error(`Could not find hosted zone "${domain.givenDomainName}"`); } /** * Gets rest API id from existing config or CloudFormation stack */ public async getApiId(domain: DomainConfig): Promise<string> { const apiGateway = this.serverless.service.provider.apiGateway || {}; const apiIdKey = Globals.gatewayAPIIdKeys[domain.apiType]; const apiId = apiGateway[apiIdKey]; if (apiId) { // if string value exists return the value if (typeof apiId === "string") { Globals.logInfo(`Mapping custom domain to existing API ${apiId}.`); return apiId; } // in case object and Fn::ImportValue try to get restApiId from the CloudFormation exports if (typeof apiId === "object" && apiId["Fn::ImportValue"]) { const importName = apiId["Fn::ImportValue"]; let importValues; try { importValues = await this.cloudFormationWrapper.getImportValues([importName]); } catch (err) { Globals.logError(err, domain.givenDomainName); throw new Error(`Failed to find CloudFormation ImportValue by ${importName}\n`); } if (!importValues[importName]) { throw new Error(`CloudFormation ImportValue not found by ${importName}\n`); } return importValues[importName]; } // throw an exception in case not supported restApiId throw new Error("Unsupported apiGateway.restApiId object"); } const stackName = this.serverless.service.provider.stackName || `${this.serverless.service.service}-${domain.stage}`; try { return await this.cloudFormationWrapper.getApiId(domain, stackName); } catch (err) { Globals.logError(err, domain.givenDomainName); throw new Error(`Failed to find CloudFormation resources for ${domain.givenDomainName}\n`); } } /** * Adds the domain name and distribution domain name to the CloudFormation outputs */ public addOutputs(domain: DomainConfig): void { const service = this.serverless.service; if (!service.provider.compiledCloudFormationTemplate.Outputs) { service.provider.compiledCloudFormationTemplate.Outputs = {}; } // Defaults for REST and backwards compatibility let distributionDomainNameOutputKey = "DistributionDomainName"; let domainNameOutputKey = "DomainName"; let hostedZoneIdOutputKey = "HostedZoneId"; if (domain.apiType === Globals.apiTypes.http) { distributionDomainNameOutputKey += "Http"; domainNameOutputKey += "Http"; hostedZoneIdOutputKey += "Http"; } else if (domain.apiType === Globals.apiTypes.websocket) { distributionDomainNameOutputKey += "Websocket"; domainNameOutputKey += "Websocket"; hostedZoneIdOutputKey += "Websocket"; } service.provider.compiledCloudFormationTemplate.Outputs[distributionDomainNameOutputKey] = { Value: domain.domainInfo.domainName, }; service.provider.compiledCloudFormationTemplate.Outputs[domainNameOutputKey] = { Value: domain.givenDomainName, }; if (domain.domainInfo.hostedZoneId) { service.provider.compiledCloudFormationTemplate.Outputs[hostedZoneIdOutputKey] = { Value: domain.domainInfo.hostedZoneId, }; } } } export = ServerlessCustomDomain;
the_stack
import { expect } from '@tanker/test-utils'; import { random } from '../random'; import * as tcrypto from '../tcrypto'; import * as utils from '../utils'; import * as encryptorV1 from '../EncryptionFormats/v1'; import * as encryptorV2 from '../EncryptionFormats/v2'; import * as encryptorV3 from '../EncryptionFormats/v3'; import * as encryptorV5 from '../EncryptionFormats/v5'; import { ready as cryptoReady } from '../ready'; describe('Simple Encryption', () => { const clearData = utils.fromString('this is very secret'); const key = new Uint8Array([ 0x76, 0xd, 0x8e, 0x80, 0x5c, 0xbc, 0xa8, 0xb6, 0xda, 0xea, 0xcf, 0x66, 0x46, 0xca, 0xd7, 0xeb, 0x4f, 0x3a, 0xbc, 0x69, 0xac, 0x9b, 0xce, 0x77, 0x35, 0x8e, 0xa8, 0x31, 0xd7, 0x2f, 0x14, 0xdd, ]); const testVectorV1 = new Uint8Array([ // version 0x01, // encrypted data 0xc9, 0x5d, 0xe6, 0xa, 0x34, 0xb2, 0x89, 0x42, 0x7a, 0x6d, 0xda, 0xd7, 0x7b, 0xa4, 0x58, 0xa7, 0xbf, 0xc8, 0x4f, // mac 0xf5, 0x52, 0x9e, 0x12, 0x4, 0x9d, 0xfc, 0xaa, 0x83, 0xb0, 0x71, 0x59, 0x91, 0xfb, 0xaa, 0xe2, // iv 0x6d, 0x4b, 0x1, 0x7, 0xdc, 0xce, 0xd9, 0xcc, 0xc4, 0xad, 0xdf, 0x89, 0x7b, 0x86, 0xe, 0x14, 0x22, 0x56, 0x3c, 0x43, 0x16, 0x97, 0x9a, 0x68, ]); const testVectorV2 = new Uint8Array([ // version 0x02, // iv 0x32, 0x93, 0xa3, 0xf8, 0x6c, 0xa8, 0x82, 0x25, 0xbc, 0x17, 0x7e, 0xb5, 0x65, 0x9b, 0xee, 0xd, 0xfd, 0xcf, 0xc6, 0x5c, 0x6d, 0xb4, 0x72, 0xe0, // encrypted data 0x5b, 0x33, 0x27, 0x4c, 0x83, 0x84, 0xd1, 0xad, 0xda, 0x5f, 0x86, 0x2, 0x46, 0x42, 0x91, 0x71, 0x30, 0x65, 0x2e, // mac 0x72, 0x47, 0xe6, 0x48, 0x20, 0xa1, 0x86, 0x91, 0x7f, 0x9c, 0xb5, 0x5e, 0x91, 0xb3, 0x65, 0x2d, ]); const testVectorV3 = new Uint8Array([ // version 0x03, // encrypted data 0x37, 0xb5, 0x3d, 0x55, 0x34, 0xb5, 0xc1, 0x3f, 0xe3, 0x72, 0x81, 0x47, 0xf0, 0xca, 0xda, 0x29, 0x99, 0x6e, 0x4, // mac 0xa8, 0x41, 0x81, 0xa0, 0xe0, 0x5e, 0x8e, 0x3a, 0x8, 0xd3, 0x78, 0xfa, 0x5, 0x9f, 0x17, 0xfa, ]); const testVectorV5 = new Uint8Array([ // version 0x05, // resourceId 0xc1, 0x74, 0x53, 0x1e, 0xdd, 0x77, 0x77, 0x87, 0x2c, 0x02, 0x6e, 0xf2, 0x36, 0xdf, 0x28, 0x7e, // iv 0x70, 0xea, 0xb6, 0xe7, 0x72, 0x7d, 0xdd, 0x42, 0x5d, 0xa1, 0xab, 0xb3, 0x6e, 0xd1, 0x8b, 0xea, 0xd7, 0xf5, 0xad, 0x23, 0xc0, 0xbd, 0x8c, 0x1f, // encrypted data 0x68, 0xc7, 0x9e, 0xf2, 0xe9, 0xd8, 0x9e, 0xf9, 0x7e, 0x93, 0xc4, 0x29, 0x0d, 0x96, 0x40, 0x2d, 0xbc, 0xf8, 0x0b, //mac 0xb8, 0x4f, 0xfc, 0x48, 0x9b, 0x83, 0xd1, 0x05, 0x51, 0x40, 0xfc, 0xc2, 0x7f, 0x6e, 0xd9, 0x16, ]); const tamperWith = (data: Uint8Array): Uint8Array => { const bytePosition = Math.floor(Math.random() * data.length); const tamperedData = new Uint8Array(data); tamperedData[bytePosition] = (tamperedData[bytePosition]! + 1) % 256; return tamperedData; }; before(() => cryptoReady); describe('EncryptionFormatV1', () => { it('should unserialize a test vector', () => { const unserializedData = encryptorV1.unserialize(testVectorV1); expect(unserializedData.iv).to.deep.equal(new Uint8Array([0x6d, 0x4b, 0x1, 0x7, 0xdc, 0xce, 0xd9, 0xcc, 0xc4, 0xad, 0xdf, 0x89, 0x7b, 0x86, 0xe, 0x14, 0x22, 0x56, 0x3c, 0x43, 0x16, 0x97, 0x9a, 0x68])); expect(unserializedData.encryptedData).to.deep.equal(new Uint8Array([0xc9, 0x5d, 0xe6, 0xa, 0x34, 0xb2, 0x89, 0x42, 0x7a, 0x6d, 0xda, 0xd7, 0x7b, 0xa4, 0x58, 0xa7, 0xbf, 0xc8, 0x4f, 0xf5, 0x52, 0x9e, 0x12, 0x4, 0x9d, 0xfc, 0xaa, 0x83, 0xb0, 0x71, 0x59, 0x91, 0xfb, 0xaa, 0xe2])); expect(unserializedData.resourceId).to.deep.equal(new Uint8Array([0xc4, 0xad, 0xdf, 0x89, 0x7b, 0x86, 0xe, 0x14, 0x22, 0x56, 0x3c, 0x43, 0x16, 0x97, 0x9a, 0x68])); }); it('should unserialize/serialize a test vector', () => { const reserializedData = encryptorV1.serialize(encryptorV1.unserialize(testVectorV1)); expect(reserializedData).to.deep.equal(testVectorV1); }); it('should throw if trying to decrypt a corrupted buffer v1', () => { expect(() => encryptorV1.decrypt(key, encryptorV1.unserialize(tamperWith(testVectorV1)))).to.throw(); }); it('should encrypt / decrypt a buffer', () => { const encryptedData = encryptorV1.encrypt(key, clearData); const decryptedData = encryptorV1.decrypt(key, encryptedData); expect(decryptedData).to.deep.equal(clearData); }); it('should decrypt a buffer v1', () => { const decryptedData = encryptorV1.decrypt(key, encryptorV1.unserialize(testVectorV1)); expect(decryptedData).to.deep.equal(clearData); }); it('should extract the resource id', () => { const resourceId = encryptorV1.extractResourceId(testVectorV1); expect(resourceId).to.deep.equal(new Uint8Array([0xc4, 0xad, 0xdf, 0x89, 0x7b, 0x86, 0xe, 0x14, 0x22, 0x56, 0x3c, 0x43, 0x16, 0x97, 0x9a, 0x68])); }); it('should output the right resourceId', () => { const encryptedData = encryptorV1.encrypt(key, clearData); const buff = encryptorV1.serialize(encryptedData); expect(encryptorV1.extractResourceId(buff)).to.deep.equal(encryptedData.resourceId); }); it('should compute clear and encrypted sizes', () => { const { overhead, getClearSize, getEncryptedSize } = encryptorV1; const clearSize = getClearSize(testVectorV1.length); const encryptedSize = getEncryptedSize(clearData.length); expect(clearSize).to.equal(clearData.length); expect(encryptedSize).to.equal(testVectorV1.length); expect(encryptedSize - clearSize).to.equal(overhead); }); }); describe('EncryptionFormatV2', () => { it('should unserialize a test vector', () => { const unserializedData = encryptorV2.unserialize(testVectorV2); expect(unserializedData.resourceId).to.deep.equal(new Uint8Array([0x72, 0x47, 0xe6, 0x48, 0x20, 0xa1, 0x86, 0x91, 0x7f, 0x9c, 0xb5, 0x5e, 0x91, 0xb3, 0x65, 0x2d])); expect(unserializedData.iv).to.deep.equal(new Uint8Array([0x32, 0x93, 0xa3, 0xf8, 0x6c, 0xa8, 0x82, 0x25, 0xbc, 0x17, 0x7e, 0xb5, 0x65, 0x9b, 0xee, 0xd, 0xfd, 0xcf, 0xc6, 0x5c, 0x6d, 0xb4, 0x72, 0xe0])); expect(unserializedData.encryptedData).to.deep.equal(new Uint8Array([0x5b, 0x33, 0x27, 0x4c, 0x83, 0x84, 0xd1, 0xad, 0xda, 0x5f, 0x86, 0x2, 0x46, 0x42, 0x91, 0x71, 0x30, 0x65, 0x2e, 0x72, 0x47, 0xe6, 0x48, 0x20, 0xa1, 0x86, 0x91, 0x7f, 0x9c, 0xb5, 0x5e, 0x91, 0xb3, 0x65, 0x2d])); }); it('should unserialize/serialize a test vector', () => { const reserializedData = encryptorV2.serialize(encryptorV2.unserialize(testVectorV2)); expect(reserializedData).to.deep.equal(testVectorV2); }); it('should throw if trying to decrypt a corrupted buffer v2', () => { expect(() => encryptorV2.decrypt(key, encryptorV2.unserialize(tamperWith(testVectorV2)))).to.throw(); }); it('should encrypt / decrypt a buffer', () => { const encryptedData = encryptorV2.encrypt(key, clearData); const decryptedData = encryptorV2.decrypt(key, encryptedData); expect(decryptedData).to.deep.equal(clearData); }); it('should decrypt a buffer v2', () => { const decryptedData = encryptorV2.decrypt(key, encryptorV2.unserialize(testVectorV2)); expect(decryptedData).to.deep.equal(clearData); }); it('should extract the resource id', () => { const resourceId = encryptorV2.extractResourceId(testVectorV2); expect(resourceId).to.deep.equal(new Uint8Array([0x72, 0x47, 0xe6, 0x48, 0x20, 0xa1, 0x86, 0x91, 0x7f, 0x9c, 0xb5, 0x5e, 0x91, 0xb3, 0x65, 0x2d])); }); it('should output the right resourceId', () => { const encryptedData = encryptorV2.encrypt(key, clearData); const buff = encryptorV2.serialize(encryptedData); expect(encryptorV2.extractResourceId(buff)).to.deep.equal(encryptedData.resourceId); }); it('should compute clear and encrypted sizes', () => { const { overhead, getClearSize, getEncryptedSize } = encryptorV2; const clearSize = getClearSize(testVectorV2.length); const encryptedSize = getEncryptedSize(clearData.length); expect(clearSize).to.equal(clearData.length); expect(encryptedSize).to.equal(testVectorV2.length); expect(encryptedSize - clearSize).to.equal(overhead); }); }); describe('EncryptionFormatV3', () => { it('should unserialize a test vector', () => { const unserializedData = encryptorV3.unserialize(testVectorV3); expect(unserializedData.encryptedData).to.deep.equal(new Uint8Array([0x37, 0xb5, 0x3d, 0x55, 0x34, 0xb5, 0xc1, 0x3f, 0xe3, 0x72, 0x81, 0x47, 0xf0, 0xca, 0xda, 0x29, 0x99, 0x6e, 0x4, 0xa8, 0x41, 0x81, 0xa0, 0xe0, 0x5e, 0x8e, 0x3a, 0x8, 0xd3, 0x78, 0xfa, 0x5, 0x9f, 0x17, 0xfa])); expect(unserializedData.resourceId).to.deep.equal(new Uint8Array([0xa8, 0x41, 0x81, 0xa0, 0xe0, 0x5e, 0x8e, 0x3a, 0x8, 0xd3, 0x78, 0xfa, 0x5, 0x9f, 0x17, 0xfa])); expect(unserializedData.iv).to.deep.equal(new Uint8Array(24)); // zeros }); it('should unserialize/serialize a test vector', () => { const reserializedData = encryptorV3.serialize(encryptorV3.unserialize(testVectorV3)); expect(reserializedData).to.deep.equal(testVectorV3); }); it('should throw if trying to decrypt a corrupted buffer v3', () => { expect(() => encryptorV3.decrypt(key, encryptorV3.unserialize(tamperWith(testVectorV3)))).to.throw(); }); it('should encrypt / decrypt a buffer', () => { const encryptedData = encryptorV3.encrypt(key, clearData); const decryptedData = encryptorV3.decrypt(key, encryptedData); expect(decryptedData).to.deep.equal(clearData); }); it('should decrypt a buffer v3', () => { const decryptedData = encryptorV3.decrypt(key, encryptorV3.unserialize(testVectorV3)); expect(decryptedData).to.deep.equal(clearData); }); it('should extract the resource id', () => { const resourceId = encryptorV3.extractResourceId(testVectorV3); expect(resourceId).to.deep.equal(new Uint8Array([0xa8, 0x41, 0x81, 0xa0, 0xe0, 0x5e, 0x8e, 0x3a, 0x8, 0xd3, 0x78, 0xfa, 0x5, 0x9f, 0x17, 0xfa])); }); it('should output the right resourceId', () => { const encryptedData = encryptorV3.encrypt(key, clearData); const buff = encryptorV3.serialize(encryptedData); expect(encryptorV3.extractResourceId(buff)).to.deep.equal(encryptedData.resourceId); }); it('should compute clear and encrypted sizes', () => { const { overhead, getClearSize, getEncryptedSize } = encryptorV3; const clearSize = getClearSize(testVectorV3.length); const encryptedSize = getEncryptedSize(clearData.length); expect(clearSize).to.equal(clearData.length); expect(encryptedSize).to.equal(testVectorV3.length); expect(encryptedSize - clearSize).to.equal(overhead); }); }); describe('EncryptionFormatV5', () => { const resourceId = random(tcrypto.MAC_SIZE); it('should unserialize a test vector', () => { const unserializedData = encryptorV5.unserialize(testVectorV5); expect(unserializedData.encryptedData).to.deep.equal(new Uint8Array([ 0x68, 0xc7, 0x9e, 0xf2, 0xe9, 0xd8, 0x9e, 0xf9, 0x7e, 0x93, 0xc4, 0x29, 0x0d, 0x96, 0x40, 0x2d, 0xbc, 0xf8, 0x0b, 0xb8, 0x4f, 0xfc, 0x48, 0x9b, 0x83, 0xd1, 0x05, 0x51, 0x40, 0xfc, 0xc2, 0x7f, 0x6e, 0xd9, 0x16, ])); expect(unserializedData.resourceId).to.deep.equal(new Uint8Array([ 0xc1, 0x74, 0x53, 0x1e, 0xdd, 0x77, 0x77, 0x87, 0x2c, 0x02, 0x6e, 0xf2, 0x36, 0xdf, 0x28, 0x7e, ])); expect(unserializedData.iv).to.deep.equal(new Uint8Array([ 0x70, 0xea, 0xb6, 0xe7, 0x72, 0x7d, 0xdd, 0x42, 0x5d, 0xa1, 0xab, 0xb3, 0x6e, 0xd1, 0x8b, 0xea, 0xd7, 0xf5, 0xad, 0x23, 0xc0, 0xbd, 0x8c, 0x1f, ])); }); it('should decrypt a test vector v5', () => { const decryptedData = encryptorV5.decrypt(key, encryptorV5.unserialize(testVectorV5)); expect(decryptedData).to.deep.equal(clearData); }); it('should encrypt / decrypt a buffer', () => { const encryptedData = encryptorV5.encrypt(key, clearData, resourceId); const decryptedData = encryptorV5.decrypt(key, encryptedData); expect(decryptedData).to.deep.equal(clearData); }); it('should serialize/unserialize a buffer', () => { const data = encryptorV5.encrypt(key, clearData, resourceId); const buffer = encryptorV5.serialize(data); const unserializedData = encryptorV5.unserialize(buffer); expect(unserializedData.resourceId).to.deep.equal(resourceId); expect(unserializedData.encryptedData).to.deep.equal(data.encryptedData); expect(unserializedData.iv).to.deep.equal(data.iv); }); it('should throw if trying to decrypt a corrupted buffer', () => { const buffer = encryptorV5.serialize(encryptorV5.encrypt(key, clearData, resourceId)); expect(() => encryptorV5.decrypt(key, encryptorV5.unserialize(tamperWith(buffer)))).to.throw(); }); it('should extract the resource id', () => { const extractedResourceId = encryptorV5.extractResourceId(testVectorV5); expect(extractedResourceId).to.deep.equal(new Uint8Array([0xc1, 0x74, 0x53, 0x1e, 0xdd, 0x77, 0x77, 0x87, 0x2c, 0x02, 0x6e, 0xf2, 0x36, 0xdf, 0x28, 0x7e])); }); it('should compute clear and encrypted sizes', () => { const { overhead, getClearSize, getEncryptedSize } = encryptorV5; const clearSize = getClearSize(testVectorV5.length); const encryptedSize = getEncryptedSize(clearData.length); expect(clearSize).to.equal(clearData.length); expect(encryptedSize).to.equal(testVectorV5.length); expect(encryptedSize - clearSize).to.equal(overhead); }); }); });
the_stack
declare namespace llvm { class APInt { public constructor(numBits: number, value: number, isSigned?: boolean); } class APFloat { public constructor(value: number); } namespace LLVMConstants { const DEBUG_METADATA_VERSION: number; } namespace dwarf { namespace LLVMConstants { const DWARF_VERSION: number; } namespace TypeKind { const DW_ATE_address: number; const DW_ATE_boolean: number; const DW_ATE_complex_float: number; const DW_ATE_float: number; const DW_ATE_signed: number; const DW_ATE_signed_char: number; const DW_ATE_unsigned: number; const DW_ATE_unsigned_char: number; const DW_ATE_imaginary_float: number; const DW_ATE_packed_decimal: number; const DW_ATE_numeric_string: number; const DW_ATE_edited: number; const DW_ATE_signed_fixed: number; const DW_ATE_unsigned_fixed: number; const DW_ATE_decimal_float: number; const DW_ATE_UTF: number; const DW_ATE_UCS: number; const DW_ATE_ASCII: number; const DW_ATE_lo_user: number; const DW_ATE_hi_user: number; } namespace SourceLanguage { const DW_LANG_C89: number; const DW_LANG_C: number; const DW_LANG_Ada83: number; const DW_LANG_C_plus_plus: number; const DW_LANG_Cobol74: number; const DW_LANG_Cobol85: number; const DW_LANG_Fortran77: number; const DW_LANG_Fortran90: number; const DW_LANG_Pascal83: number; const DW_LANG_Modula2: number; const DW_LANG_Java: number; const DW_LANG_C99: number; const DW_LANG_Ada95: number; const DW_LANG_Fortran95: number; const DW_LANG_PLI: number; const DW_LANG_ObjC: number; const DW_LANG_ObjC_plus_plus: number; const DW_LANG_UPC: number; const DW_LANG_D: number; const DW_LANG_Python: number; const DW_LANG_OpenCL: number; const DW_LANG_Go: number; const DW_LANG_Modula3: number; const DW_LANG_Haskell: number; const DW_LANG_C_plus_plus_03: number; const DW_LANG_C_plus_plus_11: number; const DW_LANG_OCaml: number; const DW_LANG_Rust: number; const DW_LANG_C11: number; const DW_LANG_Swift: number; const DW_LANG_Julia: number; const DW_LANG_Dylan: number; const DW_LANG_C_plus_plus_14: number; const DW_LANG_Fortran03: number; const DW_LANG_Fortran08: number; const DW_LANG_RenderScript: number; const DW_LANG_BLISS: number; const DW_LANG_lo_user: number; const DW_LANG_hi_user: number; } } function WriteBitcodeToFile(module: Module, filename: string): void; namespace config { const LLVM_DEFAULT_TARGET_TRIPLE: string; const LLVM_HOST_TRIPLE: string; const LLVM_ON_UNIX: number; const LLVM_VERSION_MAJOR: number; const LLVM_VERSION_MINOR: number; const LLVM_VERSION_PATCH: number; const LLVM_VERSION_STRING: string; } class LLVMContext { public constructor(); } class Module { public static readonly ModFlagBehavior: { Error: number; Warning: number; Require: number; Override: number; Append: number; AppendUnique: number; Max: number; ModFlagBehaviorFirstVal: number; ModFlagBehaviorLastVal: number; } public constructor(moduleID: string, context: LLVMContext); public getModuleIdentifier(): string; public getSourceFileName(): string; public getName(): string; public getDataLayoutStr(): string; public getDataLayout(): DataLayout; public getTargetTriple(): string; public setModuleIdentifier(moduleID: string): void; public setSourceFileName(sourceFileName: string): void; public setDataLayout(desc: string): void; public setDataLayout(dataLayout: DataLayout): void; public setTargetTriple(triple: string): void; public getFunction(name: string): Function | null; public getOrInsertFunction(name: string, funcType: FunctionType): FunctionCallee; public getGlobalVariable(name: string, allowInternal?: boolean): GlobalVariable | null; public addModuleFlag(behavior: number, key: string, value: number): void; public empty(): boolean; // customized public print(): string; } class Type { public static readonly TypeID: { HalfTyID: number; BFloatTyID: number; FloatTyID: number; DoubleTyID: number; X86_FP80TyID: number; FP128TyID: number; PPC_FP128TyID: number; VoidTyID: number; LabelTyID: number; MetadataTyID: number; X86_MMXTyID: number; TokenTyID: number; IntegerTyID: number; FunctionTyID: number; PointerTyID: number; StructTyID: number; ArrayTyID: number; FixedVectorTyID: number; ScalableVectorTyID: number; }; public static getVoidTy(context: LLVMContext): Type; public static getLabelTy(context: LLVMContext): Type; public static getHalfTy(context: LLVMContext): Type; public static getBFloatTy(context: LLVMContext): Type; public static getFloatTy(context: LLVMContext): Type; public static getDoubleTy(context: LLVMContext): Type; public static getMetadataTy(context: LLVMContext): Type; public static getX86_FP80Ty(context: LLVMContext): Type; public static getFP128Ty(context: LLVMContext): Type; public static getPPC_FP128Ty(context: LLVMContext): Type; public static getX86_MMXTy(context: LLVMContext): Type; public static getTokenTy(context: LLVMContext): Type; public static getIntNTy(context: LLVMContext, numBits: number): IntegerType; public static getInt1Ty(context: LLVMContext): IntegerType; public static getInt8Ty(context: LLVMContext): IntegerType; public static getInt16Ty(context: LLVMContext): IntegerType; public static getInt32Ty(context: LLVMContext): IntegerType; public static getInt64Ty(context: LLVMContext): IntegerType; public static getInt128Ty(context: LLVMContext): IntegerType; public static getHalfPtrTy(context: LLVMContext, addrSpace?: number): PointerType; public static getBFloatPtrTy(context: LLVMContext, addrSpace?: number): PointerType; public static getFloatPtrTy(context: LLVMContext, addrSpace?: number): PointerType; public static getDoublePtrTy(context: LLVMContext, addrSpace?: number): PointerType; public static getX86_FP80PtrTy(context: LLVMContext, addrSpace?: number): PointerType; public static getFP128PtrTy(context: LLVMContext, addrSpace?: number): PointerType; public static getPPC_FP128PtrTy(context: LLVMContext, addrSpace?: number): PointerType; public static getX86_MMXPtrTy(context: LLVMContext, addrSpace?: number): PointerType; public static getInt1PtrTy(context: LLVMContext, addrSpace?: number): PointerType; public static getInt8PtrTy(context: LLVMContext, addrSpace?: number): PointerType; public static getInt16PtrTy(context: LLVMContext, addrSpace?: number): PointerType; public static getInt32PtrTy(context: LLVMContext, addrSpace?: number): PointerType; public static getInt64PtrTy(context: LLVMContext, addrSpace?: number): PointerType; public getTypeID(): number; public isVoidTy(): boolean; public isHalfTy(): boolean; public isBFloatTy(): boolean; public isFloatTy(): boolean; public isDoubleTy(): boolean; public isX86_FP80Ty(): boolean; public isFP128Ty(): boolean; public isPPC_FP128Ty(): boolean; public isFloatingPointTy(): boolean; public isX86_MMXTy(): boolean; public isLabelTy(): boolean; public isMetadataTy(): boolean; public isTokenTy(): boolean; public isIntegerTy(bitWidth?: number): boolean; public isFunctionTy(): boolean; public isStructTy(): boolean; public isArrayTy(): boolean; public isPointerTy(): boolean; public isVectorTy(): boolean; public isEmptyTy(): boolean; public isFirstClassType(): boolean; public isSingleValueType(): boolean; public isAggregateType(): boolean; public getPointerTo(addrSpace?: number): PointerType; public getPrimitiveSizeInBits(): number; public getPointerElementType(): Type; // extra public static isSameType(type1: Type, type2: Type): boolean; protected constructor(); } class IntegerType extends Type { public static get(context: LLVMContext, numBits: number): IntegerType; // duplicated public isStructTy(): boolean; // duplicated public isIntegerTy(bitWidth?: number): boolean; // duplicated public isVoidTy(): boolean; // duplicated public getTypeID(): number; protected constructor(); } class FunctionType extends Type { public static get(returnType: Type, isVarArg: boolean): FunctionType; public static get(returnType: Type, paramTypes: Type[], isVarArg: boolean): FunctionType; // duplicated public isVoidTy(): boolean; // duplicated public getTypeID(): number; protected constructor(); } class FunctionCallee { public getFunctionType(): FunctionType; public getCallee(): Value; protected constructor(); } class StructType extends Type { public static create(context: LLVMContext, name: string): StructType; public static create(context: LLVMContext, elementTypes: Type[], name: string): StructType; public static get(context: LLVMContext): StructType; public static get(context: LLVMContext, elementTypes: Type[]): StructType; public getTypeByName(name: string): StructType | null; public setBody(elementTypes: Type[]): void; // duplicated public getPointerTo(addrSpace?: number): PointerType; // duplicated public isStructTy(): boolean; // duplicated public isIntegerTy(bitWidth?: number): boolean; // duplicated public isVoidTy(): boolean; // duplicated public getTypeID(): number; protected constructor(); } class ArrayType extends Type { public static get(elemType: Type, numElements: number): ArrayType; public static isValidElementType(elemType: Type): boolean; public getNumElements(): number; public getElementType(): Type; // duplicated public isStructTy(): boolean; // duplicated public isVoidTy(): boolean; // duplicated public getTypeID(): number; protected constructor(); } class VectorType extends Type { // duplicated public isStructTy(): boolean; // duplicated public isVoidTy(): boolean; // duplicated public getTypeID(): number; protected constructor(); } class PointerType extends Type { public static get(elementType: Type, addrSpace: number): PointerType; public static getUnqual(elementType: Type): PointerType; public getElementType(): Type; // duplicated public isPointerTy(): boolean; // duplicated public isStructTy(): boolean; // duplicated public isIntegerTy(bitWidth?: number): boolean; // duplicated public isVoidTy(): boolean; // duplicated public getTypeID(): number; // duplicated public getPointerElementType(): Type; protected constructor(); } class Value { public static MaxAlignmentExponent: number; public static MaximumAlignment: number; public getType(): Type; public hasName(): boolean; public getName(): string; public setName(name: string): void; public deleteValue(): void; public replaceAllUsesWith(newValue: Value): void; public use_empty(): boolean; public user_empty(): boolean; protected constructor(); } class Argument extends Value { public constructor(type: Type, name?: string, func?: Function, argNo?: number); public getParent(): Function; public getArgNo(): number; // duplicated public getType(): Type; // duplicated public setName(name: string): void; } class BasicBlock extends Value { public static Create( context: LLVMContext, name?: string, parent?: Function, insertBefore?: BasicBlock ): BasicBlock; public getParent(): Function | null; public getModule(): Module | null; public getTerminator(): Instruction | null; public getFirstNonPHI(): Instruction | null; public insertInto(parent: Function, insertBefore?: BasicBlock): void; public removeFromParent(): void; // customized public eraseFromParent(): void; // duplicated public use_empty(): boolean; // duplicated public getType(): Type; // extra public deleteSelf(): void; protected constructor(); } class User extends Value { public getOperand(i: number): Value; public setOperand(i: number, value: Value): void; public getNumOperands(): number; // duplicated public getType(): Type; protected constructor(); } class Constant extends User { public static getNullValue(type: Type): Constant; public static getAllOnesValue(type: Type): Constant; public isNullValue(): boolean; public isOneValue(): boolean; public isAllOnesValue(): boolean; // duplicated public getType(): Type; protected constructor(); } class ConstantInt extends Constant { public static get(context: LLVMContext, value: APInt): ConstantInt; public static get(type: IntegerType, value: number, isSigned?: boolean): ConstantInt; public static get(type: Type, value: APInt): Constant; public static get(type: Type, value: number, isSigned?: boolean): Constant; public static getTrue(context: LLVMContext): ConstantInt; public static getFalse(context: LLVMContext): ConstantInt; // duplicated public getType(): IntegerType; protected constructor(); } class ConstantFP extends Constant { public static get(type: Type, value: number): Constant; public static get(type: Type, value: APFloat): Constant; public static get(type: Type, value: string): Constant; public static get(context: LLVMContext, value: APFloat): ConstantFP; public static getNaN(type: Type): Constant // duplicated public getType(): Type; protected constructor(); } class ConstantStruct extends Constant { public static get(type: StructType, values: Constant[]): Constant; // duplicated public getType(): StructType; protected constructor(); } class ConstantPointerNull extends Constant { public static get(type: PointerType): ConstantPointerNull; public getType(): PointerType; protected constructor(); } class ConstantExpr extends Constant { public static getBitCast(constant: Constant, type: Type): Constant; // duplicated public getType(): Type; protected constructor(); } class UndefValue extends Constant { public static get(type: Type): UndefValue; // duplicated public getType(): Type; protected constructor(); } class GlobalValue extends Constant { public static readonly LinkageTypes: { ExternalLinkage: number; AvailableExternallyLinkage: number; LinkOnceAnyLinkage: number; LinkOnceODRLinkage: number; WeakAnyLinkage: number; WeakODRLinkage: number; AppendingLinkage: number; InternalLinkage: number; PrivateLinkage: number; ExternalWeakLinkage: number; CommonLinkage: number; }; public static readonly VisibilityTypes: { DefaultVisibility: number; HiddenVisibility: number; ProtectedVisibility: number; } // duplicated public getType(): PointerType; protected constructor(); } class GlobalObject extends GlobalValue { // duplicated public getType(): PointerType; protected constructor(); } class GlobalVariable extends GlobalObject { // customized public constructor(type: Type, isConstant: boolean, linkage: number, initializer?: Constant | null, name?: string); // customized public constructor(module: Module, type: Type, isConstant: boolean, linkage: number, initializer: Constant | null, name?: string); // duplicated public getType(): PointerType; public removeFromParent(): void; public eraseFromParent(): void; public addDebugInfo(gv: DIGlobalVariableExpression): void; } class Function extends GlobalObject { public static Create(funcType: FunctionType, linkage: number, name?: string, module?: Module): Function; public arg_size(): number; public getArg(i: number): Argument; public getReturnType(): Type; // customized public addBasicBlock(basicBlock: BasicBlock): void; public getEntryBlock(): BasicBlock; // extra public getExitBlock(): BasicBlock; // customized public insertAfter(where: BasicBlock, basicBlock: BasicBlock): void; public deleteBody(): void; public removeFromParent(): void; public eraseFromParent(): void; // duplicated public use_empty(): boolean; // duplicated public user_empty(): boolean; // duplicated public getNumUses(): number; // duplicated public removeDeadConstantUsers(): void; public hasPersonalityFn(): boolean; public setPersonalityFn(fn: Constant): void; public setDoesNotThrow(): void; public setSubprogram(subprogram: DISubprogram): void; public getSubprogram(): DISubprogram; // duplicated public getType(): PointerType; protected constructor(); } class Instruction extends User { public user_back(): Instruction | null; public getParent(): BasicBlock | null; public getModule(): Module | null; public getFunction(): Function | null; // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class AllocaInst extends Instruction { public getAllocatedType(): Type; public getArraySize(): Value; // duplicated public getType(): PointerType; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class LoadInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class StoreInst extends Instruction { public getValueOperand(): Value; public getPointerOperand(): Value; public getPointerOperandType(): Type; // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class FenceInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class AtomicCmpXchgInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class AtomicRMWInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class GetElementPtrInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class ICmpInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class FCmpInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class CallInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class SelectInst extends Instruction { public getCondition(): Value; public getTrueValue(): Value; public getFalseValue(): Value; public setCondition(value: Value): void; public setTrueValue(value: Value): void; public setFalseValue(value: Value): void; // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class VAArgInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class ExtractElementInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class InsertElementInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class ShuffleVectorInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class ExtractValueInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class InsertValueInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class PHINode extends Instruction { public addIncoming(value: Value, basicBlock: BasicBlock): void; // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class LandingPadInst extends Instruction { public setCleanup(value: boolean): void; public addClause(clauseVal: Constant): void; // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class ReturnInst extends Instruction { public getReturnValue(): Value; // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class BranchInst extends Instruction { public isUnconditional(): boolean; public isConditional(): boolean; public getCondition(): Value; public getNumSuccessors(): number; public getSuccessor(i: number): BasicBlock; // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class SwitchInst extends Instruction { public addCase(onVal: ConstantInt, dest: BasicBlock): void; // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class IndirectBrInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class InvokeInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class CallBrInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class ResumeInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class CatchSwitchInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class CleanupPadInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class CatchPadInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class CatchReturnInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class CleanupReturnInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class UnreachableInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class TruncInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class ZExtInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class SExtInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class FPTruncInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class FPExtInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class UIToFPInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class SIToFPInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class FPToUIInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class FPToSIInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class IntToPtrInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class PtrToIntInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class BitCastInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class AddrSpaceCastInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class FreezeInst extends Instruction { // duplicated public getType(): Type; // duplicated public setDebugLoc(location: DebugLoc): void; protected constructor(); } class IRBuilder { public constructor(context: LLVMContext); public constructor(theBB: BasicBlock); public constructor(ip: Instruction); //===--------------------------------------------------------------------===// // Builder configuration methods //===--------------------------------------------------------------------===// public ClearInsertionPoint(): void; public GetInsertBlock(): BasicBlock | null; public SetInsertPoint(basicBlock: BasicBlock): void; public SetInsertPoint(inst: Instruction): void; public saveIP(): IRBuilder.InsertPoint; public saveAndClearIP(): IRBuilder.InsertPoint; public restoreIP(ip: IRBuilder.InsertPoint): void; public SetCurrentDebugLocation(location: DebugLoc): void; // extra public SetCurrentDebugLocation(location: DILocation): void; //===--------------------------------------------------------------------===// // Miscellaneous creation methods. //===--------------------------------------------------------------------===// public CreateGlobalString(str: string, name?: string, addrSpace?: number, module?: Module): GlobalVariable; public getInt1(value: boolean): ConstantInt; public getTrue(): ConstantInt; public getFalse(): ConstantInt; public getInt8(value: number): ConstantInt; public getInt16(value: number): ConstantInt; public getInt32(value: number): ConstantInt; public getInt64(value: number): ConstantInt; public getIntN(numBits: number, value: number): ConstantInt; public getInt(value: APInt): ConstantInt; //===--------------------------------------------------------------------===// // Type creation methods //===--------------------------------------------------------------------===// public getInt1Ty(): IntegerType; public getInt8Ty(): IntegerType; public getInt16Ty(): IntegerType; public getInt32Ty(): IntegerType; public getInt64Ty(): IntegerType; public getInt128Ty(): IntegerType; public getIntNTy(numBits: number): IntegerType; public getHalfTy(): Type; public getBFloatTy(): Type; public getFloatTy(): Type; public getDoubleTy(): Type; public getVoidTy(): Type; public getInt8PtrTy(addrSpace?: number): PointerType; public getIntPtrTy(dataLayout: DataLayout, addrSpace?: number): IntegerType; //===--------------------------------------------------------------------===// // Instruction creation methods: Terminators //===--------------------------------------------------------------------===// public CreateRetVoid(): ReturnInst; public CreateRet(value: Value): ReturnInst; public CreateBr(destBB: BasicBlock): BranchInst; public CreateCondBr(cond: Value, thenBB: BasicBlock, elseBB: BasicBlock): BranchInst; public CreateSwitch(value: Value, dest: BasicBlock, numCases?: number): SwitchInst; public CreateIndirectBr(addr: Value, numDests?: number): IndirectBrInst; // customized public CreateInvoke(callee: Function, normalDest: BasicBlock, unwindDest: BasicBlock, name?: string): InvokeInst; public CreateInvoke(callee: Function, normalDest: BasicBlock, unwindDest: BasicBlock, args: Value[], name?: string): InvokeInst; public CreateInvoke(callee: FunctionCallee, normalDest: BasicBlock, unwindDest: BasicBlock, name?: string): InvokeInst; public CreateInvoke(callee: FunctionCallee, normalDest: BasicBlock, unwindDest: BasicBlock, args: Value[], name?: string): InvokeInst; public CreateInvoke(funcType: FunctionType, callee: Function, normalDest: BasicBlock, unwindDest: BasicBlock, name?: string): InvokeInst; public CreateInvoke(funcType: FunctionType, callee: Function, normalDest: BasicBlock, unwindDest: BasicBlock, args: Value[], name?: string): InvokeInst; public CreateResume(exn: Value): ResumeInst; public CreateUnreachable(): UnreachableInst; //===--------------------------------------------------------------------===// // Instruction creation methods: Binary Operators //===--------------------------------------------------------------------===// public CreateAdd(lhs: Value, rhs: Value, name?: string): Value; public CreateFAdd(lhs: Value, rhs: Value, name?: string): Value; public CreateSub(lhs: Value, rhs: Value, name?: string): Value; public CreateFSub(lhs: Value, rhs: Value, name?: string): Value; public CreateMul(lhs: Value, rhs: Value, name?: string): Value; public CreateFMul(lhs: Value, rhs: Value, name?: string): Value; public CreateSDiv(lhs: Value, rhs: Value, name?: string): Value; public CreateUDiv(lhs: Value, rhs: Value, name?: string): Value; public CreateFDiv(lhs: Value, rhs: Value, name?: string): Value; public CreateSRem(lhs: Value, rhs: Value, name?: string): Value; public CreateURem(lhs: Value, rhs: Value, name?: string): Value; public CreateFRem(lhs: Value, rhs: Value, name?: string): Value; public CreateAnd(lhs: Value, rhs: Value, name?: string): Value; public CreateOr(lhs: Value, rhs: Value, name?: string): Value; public CreateXor(lhs: Value, rhs: Value, name?: string): Value; public CreateShl(lhs: Value, rhs: Value, name?: string): Value; public CreateAShr(lhs: Value, rhs: Value, name?: string): Value; public CreateLShr(lhs: Value, rhs: Value, name?: string): Value; public CreateNeg(value: Value, name?: string): Value; public CreateFNeg(value: Value, name?: string): Value; public CreateNot(value: Value, name?: string): Value; //===--------------------------------------------------------------------===// // Instruction creation methods: Memory Instructions //===--------------------------------------------------------------------===// // customized public CreateAlloca(type: Type, arraySize?: Value | null, name?: string): AllocaInst; public CreateLoad(type: Type, ptr: Value, name?: string): LoadInst; public CreateStore(value: Value, ptr: Value): StoreInst; public CreateGEP(type: Type, ptr: Value, idxList: Value[], name?: string): Value; public CreateGEP(type: Type, ptr: Value, idx: Value, name?: string): Value; public CreateInBoundsGEP(type: Type, ptr: Value, idxList: Value[], name?: string): Value; public CreateInBoundsGEP(type: Type, ptr: Value, idx: Value, name?: string): Value; public CreateGlobalStringPtr(str: string, name?: string, addrSpace?: number, module?: Module): Constant; //===--------------------------------------------------------------------===// // Instruction creation methods: Cast/Conversion Operators //===--------------------------------------------------------------------===// public CreateTrunc(value: Value, destType: Type, name?: string): Value; public CreateZExt(value: Value, destType: Type, name?: string): Value; public CreateSExt(value: Value, destType: Type, name?: string): Value; public CreateZExtOrTrunc(value: Value, destType: Type, name?: string): Value; public CreateSExtOrTrunc(value: Value, destType: Type, name?: string): Value; public CreateFPToUI(value: Value, destType: Type, name?: string): Value; public CreateFPToSI(value: Value, destType: Type, name?: string): Value; public CreateUIToFP(value: Value, destType: Type, name?: string): Value; public CreateSIToFP(value: Value, destType: Type, name?: string): Value; public CreateFPTrunc(value: Value, destType: Type, name?: string): Value; public CreateFPExt(value: Value, destType: Type, name?: string): Value; public CreatePtrToInt(value: Value, destType: Type, name?: string): Value; public CreateIntToPtr(value: Value, destType: Type, name?: string): Value; public CreateBitCast(value: Value, destType: Type, name?: string): Value; public CreateAddrSpaceCast(value: Value, destType: Type, name?: string): Value; public CreateZExtOrBitCast(value: Value, destType: Type, name?: string): Value; public CreateSExtOrBitCast(value: Value, destType: Type, name?: string): Value; public CreateTruncOrBitCast(value: Value, destType: Type, name?: string): Value; public CreatePointerCast(value: Value, destType: Type, name?: string): Value; public CreatePointerBitCastOrAddrSpaceCast(value: Value, destType: Type, name?: string): Value; public CreateIntCast(value: Value, destType: Type, isSigned: boolean, name?: string): Value; public CreateBitOrPointerCast(value: Value, destType: Type, name?: string): Value; public CreateFPCast(value: Value, destType: Type, name?: string): Value; //===--------------------------------------------------------------------===// // Instruction creation methods: Compare Instructions //===--------------------------------------------------------------------===// public CreateICmpEQ(lhs: Value, rhs: Value, name?: string): Value; public CreateICmpNE(lhs: Value, rhs: Value, name?: string): Value; public CreateICmpSGE(lhs: Value, rhs: Value, name?: string): Value; public CreateICmpSGT(lhs: Value, rhs: Value, name?: string): Value; public CreateICmpSLE(lhs: Value, rhs: Value, name?: string): Value; public CreateICmpSLT(lhs: Value, rhs: Value, name?: string): Value; public CreateICmpUGE(lhs: Value, rhs: Value, name?: string): Value; public CreateICmpUGT(lhs: Value, rhs: Value, name?: string): Value; public CreateICmpULE(lhs: Value, rhs: Value, name?: string): Value; public CreateICmpULT(lhs: Value, rhs: Value, name?: string): Value; public CreateFCmpOEQ(lhs: Value, rhs: Value, name?: string): Value; public CreateFCmpONE(lhs: Value, rhs: Value, name?: string): Value; public CreateFCmpOGE(lhs: Value, rhs: Value, name?: string): Value; public CreateFCmpOGT(lhs: Value, rhs: Value, name?: string): Value; public CreateFCmpOLE(lhs: Value, rhs: Value, name?: string): Value; public CreateFCmpOLT(lhs: Value, rhs: Value, name?: string): Value; public CreateFCmpUEQ(lhs: Value, rhs: Value, name?: string): Value; public CreateFCmpUNE(lhs: Value, rhs: Value, name?: string): Value; public CreateFCmpUGE(lhs: Value, rhs: Value, name?: string): Value; public CreateFCmpUGT(lhs: Value, rhs: Value, name?: string): Value; public CreateFCmpULE(lhs: Value, rhs: Value, name?: string): Value; public CreateFCmpULT(lhs: Value, rhs: Value, name?: string): Value; //===--------------------------------------------------------------------===// // Instruction creation methods: Other Instructions //===--------------------------------------------------------------------===// public CreatePHI(type: Type, numReservedValues: number, name?: string): PHINode; // customized public CreateCall(callee: Function, name?: string): CallInst; public CreateCall(callee: Function, args: Value[], name?: string): CallInst; public CreateCall(callee: FunctionCallee, name?: string): CallInst; public CreateCall(callee: FunctionCallee, args: Value[], name?: string): CallInst; public CreateCall(funcType: FunctionType, callee: Value, name?: string): CallInst; public CreateCall(funcType: FunctionType, callee: Value, args: Value[], name?: string): CallInst; public CreateSelect(cond: Value, trueValue: Value, falseValue: Value, name?: string): Value; public CreateExtractValue(agg: Value, idxs: number[], name?: string): Value; public CreateInsertValue(agg: Value, value: Value, idxs: number[], name?: string): Value; public CreateLandingPad(type: Type, numClauses: number, name?: string): LandingPadInst; //===--------------------------------------------------------------------===// // Utility creation methods //===--------------------------------------------------------------------===// public CreateIsNull(value: Value, name?: string): Value; public CreateIsNotNull(value: Value, name?: string): Value; public CreatePtrDiff(lhs: Value, rhs: Value, name?: string): Value; } namespace IRBuilder { export class InsertPoint { protected constructor(); } } class Metadata { protected constructor(); } class MDNode extends Metadata { protected constructor(); } class DebugLoc { public constructor(); } class DITypeRefArray { protected constructor(); } class DINode extends MDNode { public static readonly DIFlags: { FlagZero: number; FlagPrivate: number; FlagProtected: number; FlagPublic: number; FlagFwdDecl: number; FlagAppleBlock: number; FlagReservedBit4: number; FlagVirtual: number; FlagArtificial: number; FlagExplicit: number; FlagPrototyped: number; FlagObjcClassComplete: number; FlagObjectPointer: number; FlagVector: number; FlagStaticMember: number; FlagLValueReference: number; FlagRValueReference: number; FlagExportSymbols: number; FlagSingleInheritance: number; FlagMultipleInheritance: number; FlagVirtualInheritance: number; FlagIntroducedVirtual: number; FlagBitField: number; FlagNoReturn: number; FlagTypePassByValue: number; FlagTypePassByReference: number; FlagEnumClass: number; FlagThunk: number; FlagNonTrivial: number; FlagBigEndian: number; FlagLittleEndian: number; FlagAllCallsDescribed: number; FlagIndirectVirtualBase: number; FlagAccessibility: number; FlagPtrToMemberRep: number; } protected constructor(); } class DIScope extends DINode { protected constructor(); } class DIFile extends DIScope { protected constructor(); } class DIType extends DIScope { protected constructor(); } class DIBasicType extends DIType { protected constructor(); } class DIDerivedType extends DIType { protected constructor(); } class DICompositeType extends DIType { protected constructor(); } class DISubroutineType extends DIType { protected constructor(); } class DICompileUnit extends DIScope { public getFile(): DIFile; protected constructor(); } class DILocalScope extends DIScope { protected constructor(); } class DILocation extends MDNode { public static get(context: LLVMContext, line: number, column: number, metadata: Metadata): DILocation; public static get(context: LLVMContext, line: number, column: number, scope: DILocalScope): DILocation; protected constructor(); } class DISubprogram extends DILocalScope { public static readonly DISPFlags: { SPFlagZero: number; SPFlagVirtual: number; SPFlagPureVirtual: number; SPFlagLocalToUnit: number; SPFlagDefinition: number; SPFlagOptimized: number; SPFlagPure: number; SPFlagElemental: number; SPFlagRecursive: number; SPFlagMainSubprogram: number; SPFlagDeleted: number; SPFlagObjCDirect: number; SPFlagNonvirtual: number; SPFlagVirtuality: number; } protected constructor(); } class DILexicalBlock extends DILocalScope { protected constructor(); } class DINamespace extends DIScope { protected constructor(); } class DIVariable extends DINode { protected constructor(); } class DIExpression extends MDNode { protected constructor(); } class DIGlobalVariableExpression extends MDNode { protected constructor(); } class DILocalVariable extends DIVariable { protected constructor(); } class DIGlobalVariable extends DIVariable { protected constructor(); } class DIBuilder { public constructor(module: Module); public createFile(filename: string, directory: string): DIFile; public createCompileUnit(lang: number, file: DIFile, producer: string, isOptimized: boolean, flags: string, rv: number): DICompileUnit; public createFunction(scope: DIScope, name: string, linkage: string, file: DIFile, line: number, type: DISubroutineType, scopeLine: number, flags: number, spFlags: number): DISubprogram; public createLexicalBlock(scope: DIScope, file: DIFile, line: number, column: number): DILexicalBlock; public createBasicType(name: string, sizeInBits: number, encoding: number): DIBasicType; public getOrCreateTypeArray(elements: (Metadata | null)[]): DITypeRefArray; public createSubroutineType(paramTypes: DITypeRefArray): DISubroutineType; public createExpression(): DIExpression; public createParameterVariable(scope: DIScope, name: string, argNo: number, file: DIFile, line: number, type: DIType, alwaysPreserve?: boolean): DILocalVariable; public createAutoVariable(scope: DIScope, name: string, file: DIFile, line: number, type: DIType | null, alwaysPreserve?: boolean): DILocalVariable; public createGlobalVariableExpression(context: DIScope, name: string, linkage: string, file: DIFile, line: number, type: DIType, IsLocalToUnit: boolean): DIGlobalVariableExpression; public insertDeclare(storage: Value, variable: DILocalVariable, expr: DIExpression, location: DILocation, insertBB: BasicBlock): Instruction; public insertDeclare(storage: Value, variable: DILocalVariable, expr: DIExpression, location: DILocation, insertBefore: Instruction): Instruction; public insertDbgValueIntrinsic(value: Value, variable: DILocalVariable, expr: DIExpression, location: DILocation, insertBB: BasicBlock): Instruction; public insertDbgValueIntrinsic(value: Value, variable: DILocalVariable, expr: DIExpression, location: DILocation, insertBefore: Instruction): Instruction; public finalizeSubprogram(subprogram: DISubprogram): void; public finalize(): void; } class DataLayout { public constructor(desc: string); public getStringRepresentation(): string; public getTypeAllocSize(type: Type): number; } function verifyFunction(func: Function): boolean; function verifyModule(module: Module): boolean; namespace Intrinsic { const abs: number; const addressofreturnaddress: number; const adjust_trampoline: number; const annotation: number; const assume: number; const bitreverse: number; const bswap: number; const call_preallocated_arg: number; const call_preallocated_setup: number; const call_preallocated_teardown: number; const canonicalize: number; const ceil: number; const clear_cache: number; const codeview_annotation: number; const convert_from_fp16: number; const convert_to_fp16: number; const copysign: number; const coro_alloc: number; const coro_alloca_alloc: number; const coro_alloca_free: number; const coro_alloca_get: number; const coro_async_context_alloc: number; const coro_async_context_dealloc: number; const coro_async_resume: number; const coro_begin: number; const coro_destroy: number; const coro_done: number; const coro_end: number; const coro_end_async: number; const coro_frame: number; const coro_free: number; const coro_id: number; const coro_id_async: number; const coro_id_retcon: number; const coro_id_retcon_once: number; const coro_noop: number; const coro_param: number; const coro_prepare_async: number; const coro_prepare_retcon: number; const coro_promise: number; const coro_resume: number; const coro_save: number; const coro_size: number; const coro_subfn_addr: number; const coro_suspend: number; const coro_suspend_async: number; const coro_suspend_retcon: number; const cos: number; const ctlz: number; const ctpop: number; const cttz: number; const dbg_addr: number; const dbg_declare: number; const dbg_label: number; const dbg_value: number; const debugtrap: number; const donothing: number; const eh_dwarf_cfa: number; const eh_exceptioncode: number; const eh_exceptionpointer: number; const eh_recoverfp: number; const eh_return_i32: number; const eh_return_i64: number; const eh_sjlj_callsite: number; const eh_sjlj_functioncontext: number; const eh_sjlj_longjmp: number; const eh_sjlj_lsda: number; const eh_sjlj_setjmp: number; const eh_sjlj_setup_dispatch: number; const eh_typeid_for: number; const eh_unwind_init: number; const exp: number; const exp2: number; const expect: number; const expect_with_probability: number; const fabs: number; const floor: number; const flt_rounds: number; const fma: number; const fmuladd: number; const fptosi_sat: number; const fptoui_sat: number; const frameaddress: number; const fshl: number; const fshr: number; const gcread: number; const gcroot: number; const gcwrite: number; const get_active_lane_mask: number; const get_dynamic_area_offset: number; const hwasan_check_memaccess: number; const hwasan_check_memaccess_shortgranules: number; const icall_branch_funnel: number; const init_trampoline: number; const instrprof_increment: number; const instrprof_increment_step: number; const instrprof_value_profile: number; const invariant_end: number; const invariant_start: number; const is_constant: number; const launder_invariant_group: number; const lifetime_end: number; const lifetime_start: number; const llrint: number; const llround: number; const load_relative: number; const localaddress: number; const localescape: number; const localrecover: number; const log: number; const log10: number; const log2: number; const loop_decrement: number; const loop_decrement_reg: number; const lrint: number; const lround: number; const masked_compressstore: number; const masked_expandload: number; const masked_gather: number; const masked_load: number; const masked_scatter: number; const masked_store: number; const matrix_column_major_load: number; const matrix_column_major_store: number; const matrix_multiply: number; const matrix_transpose: number; const maximum: number; const maxnum: number; const memcpy: number; const memcpy_element_unordered_atomic: number; const memcpy_inline: number; const memmove: number; const memmove_element_unordered_atomic: number; const memset: number; const memset_element_unordered_atomic: number; const minimum: number; const minnum: number; const nearbyint: number; const objc_arc_annotation_bottomup_bbend: number; const objc_arc_annotation_bottomup_bbstart: number; const objc_arc_annotation_topdown_bbend: number; const objc_arc_annotation_topdown_bbstart: number; const objc_autorelease: number; const objc_autoreleasePoolPop: number; const objc_autoreleasePoolPush: number; const objc_autoreleaseReturnValue: number; const objc_clang_arc_use: number; const objc_copyWeak: number; const objc_destroyWeak: number; const objc_initWeak: number; const objc_loadWeak: number; const objc_loadWeakRetained: number; const objc_moveWeak: number; const objc_release: number; const objc_retain: number; const objc_retain_autorelease: number; const objc_retainAutorelease: number; const objc_retainAutoreleaseReturnValue: number; const objc_retainAutoreleasedReturnValue: number; const objc_retainBlock: number; const objc_retainedObject: number; const objc_storeStrong: number; const objc_storeWeak: number; const objc_sync_enter: number; const objc_sync_exit: number; const objc_unretainedObject: number; const objc_unretainedPointer: number; const objc_unsafeClaimAutoreleasedReturnValue: number; const objectsize: number; const pcmarker: number; const pow: number; const powi: number; const prefetch: number; const preserve_array_access_index: number; const preserve_struct_access_index: number; const preserve_union_access_index: number; const pseudoprobe: number; const ptr_annotation: number; const ptrmask: number; const read_register: number; const read_volatile_register: number; const readcyclecounter: number; const returnaddress: number; const rint: number; const round: number; const roundeven: number; const sadd_sat: number; const sadd_with_overflow: number; const sdiv_fix: number; const sdiv_fix_sat: number; const set_loop_iterations: number; const sideeffect: number; const sin: number; const smax: number; const smin: number; const smul_fix: number; const smul_fix_sat: number; const smul_with_overflow: number; const sponentry: number; const sqrt: number; const ssa_copy: number; const sshl_sat: number; const ssub_sat: number; const ssub_with_overflow: number; const stackguard: number; const stackprotector: number; const stackrestore: number; const stacksave: number; const start_loop_iterations: number; const strip_invariant_group: number; const test_set_loop_iterations: number; const thread_pointer: number; const trap: number; const trunc: number; const type_checked_load: number; const type_test: number; const uadd_sat: number; const uadd_with_overflow: number; const ubsantrap: number; const udiv_fix: number; const udiv_fix_sat: number; const umax: number; const umin: number; const umul_fix: number; const umul_fix_sat: number; const umul_with_overflow: number; const ushl_sat: number; const usub_sat: number; const usub_with_overflow: number; const vacopy: number; const vaend: number; const vastart: number; const var_annotation: number; const vector_reduce_add: number; const vector_reduce_and: number; const vector_reduce_fadd: number; const vector_reduce_fmax: number; const vector_reduce_fmin: number; const vector_reduce_fmul: number; const vector_reduce_mul: number; const vector_reduce_or: number; const vector_reduce_smax: number; const vector_reduce_smin: number; const vector_reduce_umax: number; const vector_reduce_umin: number; const vector_reduce_xor: number; const vp_add: number; const vp_and: number; const vp_ashr: number; const vp_lshr: number; const vp_mul: number; const vp_or: number; const vp_sdiv: number; const vp_shl: number; const vp_srem: number; const vp_sub: number; const vp_udiv: number; const vp_urem: number; const vp_xor: number; const vscale: number; const write_register: number; const xray_customevent: number; const xray_typedevent: number; function getDeclaration(module: Module, id: number, types?: Type[]): Function; } function parseIRFile(filename: string, err: SMDiagnostic, context: LLVMContext): Module; class Linker { public constructor(module: Module); public linkInModule(srcModule: Module): boolean; public static linkModules(destModule: Module, srcModule: Module): boolean; } class SMDiagnostic { public constructor(); } class Target { public createTargetMachine(targetTriple: string, cpu: string, features?: string): TargetMachine; public getName(): string; public getShortDescription(): string; protected constructor(); } class TargetRegistry { static lookupTarget(target: string): Target | null; protected constructor(); } class TargetMachine { public createDataLayout(): DataLayout; protected constructor(); } function InitializeAllTargetInfos(): void; function InitializeAllTargets(): void; function InitializeAllTargetMCs(): void; function InitializeAllAsmPrinters(): void; function InitializeAllAsmParsers(): void; function InitializeAllDisassemblers(): void; function InitializeNativeTarget(): boolean; function InitializeNativeTargetAsmPrinter(): boolean; function InitializeNativeTargetAsmParser(): boolean; function InitializeNativeTargetDisassembler(): boolean; } export = llvm; export as namespace llvm;
the_stack
import { renderHook, act } from '@testing-library/react-hooks' import React, { PropsWithChildren } from 'react' import { Observable, of } from 'rxjs' import sinon from 'sinon' import { SettingsCascadeOrError } from '@sourcegraph/shared/src/settings/settings' import { stringify } from '@sourcegraph/shared/src/util/jsonc' import { Settings } from '../../../../../../../schema/settings.schema' import { InsightsApiContext } from '../../../../../core/backend/api-provider' import { createMockInsightAPI } from '../../../../../core/backend/create-insights-api' import { ApiService } from '../../../../../core/backend/types' import { InsightType, LangStatsInsight } from '../../../../../core/types' import { createGlobalSubject, createOrgSubject, createUserSubject } from '../../../../../mocks/settings-cascade' import { useUpdateSettingsSubject } from './use-update-settings-subjects' const DEFAULT_OLD_INSIGHT: LangStatsInsight = { type: InsightType.Extension, title: 'old extension lang stats insight', id: 'codeStatsInsights.insight.oldExtensionLangStatsInsight', visibility: 'personal-subject-id', repository: '', otherThreshold: 3, } const DEFAULT_NEW_INSIGHT: LangStatsInsight = { type: InsightType.Extension, title: 'new extension lang stats insight', id: 'codeStatsInsights.insight.newExtensionLangStatsInsight', visibility: 'org-1-subject-id', repository: '', otherThreshold: 5, } function createAPIContext( settingsCascade: SettingsCascadeOrError<Settings> ): { mockAPI: ApiService; Provider: React.FunctionComponent<{}> } { const mockAPI = createMockInsightAPI({ getSubjectSettings: id => { const subject = settingsCascade.subjects?.find(subject => subject.subject.id === id) if (!subject) { throw new Error('No subject') } return of({ id: 1000, contents: stringify(subject.settings) }) }, }) const Provider: React.FunctionComponent<{}> = props => ( <InsightsApiContext.Provider value={mockAPI}>{props.children}</InsightsApiContext.Provider> ) return { mockAPI, Provider, } } describe('useUpdateSettingsSubject', () => { test("shouldn't update settings if there is no subjects", async () => { // Setup const updateSettingsSpy = sinon.spy<() => Observable<void>>(() => of()) const mockAPI = createMockInsightAPI({ updateSubjectSettings: updateSettingsSpy, getSubjectSettings: () => of({ id: 1000, contents: '' }), }) const wrapper: React.FunctionComponent<PropsWithChildren<{}>> = props => ( <InsightsApiContext.Provider value={mockAPI}>{props.children}</InsightsApiContext.Provider> ) const { result } = renderHook( () => useUpdateSettingsSubject({ platformContext: {} as any, }), { wrapper } ) // Act await act(async () => { await result.current.updateSettingSubjects({ oldInsight: DEFAULT_OLD_INSIGHT, newInsight: DEFAULT_NEW_INSIGHT, settingsCascade: { final: {}, subjects: null, }, }) }) expect(updateSettingsSpy.notCalled).toBe(true) }) describe('when a user transferred (shared) insights', () => { const settingsCascade: SettingsCascadeOrError<Settings> = { final: {}, subjects: [ { subject: createUserSubject('client-subject-id'), settings: { 'codeStatsInsights.insight.oldExtensionLangStatsInsight': DEFAULT_OLD_INSIGHT, 'insights.dashboards': { somePersonalDashboard: { id: 'uuid-personal-dashboard', title: 'Some personal dashboard', // Include personal insight to some personal dashboard for testing // insight dashboard visibility levels insightIds: ['codeStatsInsights.insight.oldExtensionLangStatsInsight'], }, }, }, lastID: 1000, }, { subject: createOrgSubject('org-1-subject-id'), settings: { 'insights.dashboards': { someFirstOrganizationDashboard: { id: 'uuid-first-organization-dashboard', title: 'Some first organization dashboard', insightIds: [], }, }, }, lastID: 1100, }, { subject: createGlobalSubject('global-subject-id'), settings: { 'insights.dashboards': { someGlobalOrganizationDashboard: { id: 'uuid-global-dashboard', title: 'Some global dashboard', insightIds: [], }, }, }, lastID: 1110, }, ], } test('from the personal to some org visibility level', async () => { const oldInsight = { ...DEFAULT_OLD_INSIGHT, visibility: 'client-subject-id' } const newInsight = { ...DEFAULT_NEW_INSIGHT, visibility: 'org-1-subject-id' } const { Provider, mockAPI } = createAPIContext(settingsCascade) const updateSettingsSpy = sinon.stub(mockAPI, 'updateSubjectSettings') updateSettingsSpy.callsFake(() => of()) const { result } = renderHook( () => useUpdateSettingsSubject({ platformContext: {} as any, }), { wrapper: Provider } ) // Act await act(async () => { await result.current.updateSettingSubjects({ oldInsight, newInsight, settingsCascade, }) }) expect(updateSettingsSpy.calledTwice).toBe(true) expect(updateSettingsSpy.firstCall.args).toStrictEqual([ {}, 'client-subject-id', stringify({ 'insights.dashboards': { somePersonalDashboard: { id: 'uuid-personal-dashboard', title: 'Some personal dashboard', insightIds: ['codeStatsInsights.insight.newExtensionLangStatsInsight'], }, }, }), ]) expect(updateSettingsSpy.secondCall.args).toStrictEqual([ {}, 'org-1-subject-id', stringify({ 'insights.dashboards': { someFirstOrganizationDashboard: { id: 'uuid-first-organization-dashboard', title: 'Some first organization dashboard', insightIds: [], }, }, 'codeStatsInsights.insight.newExtensionLangStatsInsight': { title: 'new extension lang stats insight', repository: '', otherThreshold: 5, }, }), ]) }) test('when a user transferred an insight from the personal to global visibility level', async () => { const oldInsight = { ...DEFAULT_OLD_INSIGHT, visibility: 'client-subject-id' } const newInsight = { ...DEFAULT_NEW_INSIGHT, visibility: 'global-subject-id' } const { Provider, mockAPI } = createAPIContext(settingsCascade) const updateSettingsSpy = sinon.stub(mockAPI, 'updateSubjectSettings') updateSettingsSpy.callsFake(() => of()) const { result } = renderHook(() => useUpdateSettingsSubject({ platformContext: {} as any }), { wrapper: Provider, }) // Act await act(async () => { await result.current.updateSettingSubjects({ oldInsight, newInsight, settingsCascade, }) }) expect(updateSettingsSpy.calledTwice).toBe(true) expect(updateSettingsSpy.firstCall.args).toStrictEqual([ {}, 'client-subject-id', stringify({ 'insights.dashboards': { somePersonalDashboard: { id: 'uuid-personal-dashboard', title: 'Some personal dashboard', insightIds: ['codeStatsInsights.insight.newExtensionLangStatsInsight'], }, }, }), ]) expect(updateSettingsSpy.secondCall.args).toStrictEqual([ {}, 'global-subject-id', stringify({ 'insights.dashboards': { someGlobalOrganizationDashboard: { id: 'uuid-global-dashboard', title: 'Some global dashboard', insightIds: [], }, }, 'codeStatsInsights.insight.newExtensionLangStatsInsight': { title: 'new extension lang stats insight', repository: '', otherThreshold: 5, }, }), ]) }) }) describe('when a user moved (make it private) insights', () => { test('from global level to some organization level', async () => { const settingsCascade: SettingsCascadeOrError<Settings> = { final: {}, subjects: [ { subject: createUserSubject('client-subject-id'), settings: { 'insights.dashboards': { somePersonalDashboard: { id: 'uuid-personal-dashboard', title: 'Some personal dashboard', // Include personal insight to some personal dashboard for testing // insight dashboard visibility levels insightIds: ['codeStatsInsights.insight.someAnotherLangInsight'], }, }, }, lastID: 1000, }, { subject: createOrgSubject('org-1-subject-id'), settings: { 'insights.dashboards': { someFirstOrganizationDashboard: { id: 'uuid-first-organization-dashboard', title: 'Some first organization dashboard', insightIds: ['codeStatsInsights.insight.oldExtensionLangStatsInsight'], }, }, }, lastID: 1100, }, { subject: createGlobalSubject('global-subject-id'), settings: { 'codeStatsInsights.insight.oldExtensionLangStatsInsight': DEFAULT_OLD_INSIGHT, 'insights.dashboards': { someGlobalOrganizationDashboard: { id: 'uuid-global-dashboard', title: 'Some global dashboard', insightIds: ['codeStatsInsights.insight.oldExtensionLangStatsInsight'], }, }, }, lastID: 1110, }, ], } const oldInsight = { ...DEFAULT_OLD_INSIGHT, visibility: 'global-subject-id' } const newInsight = { ...DEFAULT_NEW_INSIGHT, visibility: 'client-subject-id' } const { Provider, mockAPI } = createAPIContext(settingsCascade) const updateSettingsSpy = sinon.stub(mockAPI, 'updateSubjectSettings') updateSettingsSpy.callsFake(() => of()) const { result } = renderHook(() => useUpdateSettingsSubject({ platformContext: {} as any }), { wrapper: Provider, }) // Act await act(async () => { await result.current.updateSettingSubjects({ oldInsight, newInsight, settingsCascade, }) }) expect(updateSettingsSpy.callCount).toBe(3) expect(updateSettingsSpy.firstCall.args).toStrictEqual([ {}, 'global-subject-id', stringify({ 'insights.dashboards': { someGlobalOrganizationDashboard: { id: 'uuid-global-dashboard', title: 'Some global dashboard', // Moved insight was removed from global custom dashboard due // it's public insight now insightIds: [], }, }, }), ]) expect(updateSettingsSpy.secondCall.args).toStrictEqual([ {}, 'client-subject-id', stringify({ 'insights.dashboards': { somePersonalDashboard: { id: 'uuid-personal-dashboard', title: 'Some personal dashboard', // Include personal insight to some personal dashboard for testing // insight dashboard visibility levels insightIds: ['codeStatsInsights.insight.someAnotherLangInsight'], }, }, 'codeStatsInsights.insight.newExtensionLangStatsInsight': { title: 'new extension lang stats insight', repository: '', otherThreshold: 5, }, }), ]) expect(updateSettingsSpy.thirdCall.args).toStrictEqual([ {}, 'org-1-subject-id', stringify({ 'insights.dashboards': { someFirstOrganizationDashboard: { id: 'uuid-first-organization-dashboard', title: 'Some first organization dashboard', // Moved insight was removed from global custom dashboard due // it's public insight now insightIds: [], }, }, }), ]) }) test('from on organization level to another organization level', async () => { const settingsCascade: SettingsCascadeOrError<Settings> = { final: {}, subjects: [ { subject: createUserSubject('client-subject-id'), settings: { 'insights.dashboards': { somePersonalDashboard: { id: 'uuid-personal-dashboard', title: 'Some personal dashboard', // Include personal insight to some personal dashboard for testing // insight dashboard visibility levels insightIds: ['codeStatsInsights.insight.someAnotherLangInsight'], }, }, }, lastID: 1000, }, { subject: createOrgSubject('org-1-subject-id'), settings: { 'codeStatsInsights.insight.oldExtensionLangStatsInsight': DEFAULT_OLD_INSIGHT, 'insights.dashboards': { someFirstOrganizationDashboard: { id: 'uuid-first-organization-dashboard', title: 'Some first organization dashboard', insightIds: ['codeStatsInsights.insight.oldExtensionLangStatsInsight'], }, }, }, lastID: 1100, }, { subject: createOrgSubject('org-2-subject-id'), settings: { 'insights.dashboards': { someSecondOrganizationDashboard: { id: 'uuid-second-organization-dashboard', title: 'Some second organization dashboard', insightIds: [], }, }, }, lastID: 1101, }, ], } const oldInsight = { ...DEFAULT_OLD_INSIGHT, visibility: 'org-1-subject-id' } const newInsight = { ...DEFAULT_NEW_INSIGHT, visibility: 'org-2-subject-id' } const { Provider, mockAPI } = createAPIContext(settingsCascade) const updateSettingsSpy = sinon.stub(mockAPI, 'updateSubjectSettings') updateSettingsSpy.callsFake(() => of()) const { result } = renderHook(() => useUpdateSettingsSubject({ platformContext: {} as any }), { wrapper: Provider, }) // Act await act(async () => { await result.current.updateSettingSubjects({ oldInsight, newInsight, settingsCascade, }) }) expect(updateSettingsSpy.callCount).toBe(2) expect(updateSettingsSpy.firstCall.args).toStrictEqual([ {}, 'org-1-subject-id', stringify({ 'insights.dashboards': { someFirstOrganizationDashboard: { id: 'uuid-first-organization-dashboard', title: 'Some first organization dashboard', insightIds: [], }, }, }), ]) expect(updateSettingsSpy.secondCall.args).toStrictEqual([ {}, 'org-2-subject-id', stringify({ 'insights.dashboards': { someSecondOrganizationDashboard: { id: 'uuid-second-organization-dashboard', title: 'Some second organization dashboard', insightIds: [], }, }, 'codeStatsInsights.insight.newExtensionLangStatsInsight': { title: 'new extension lang stats insight', repository: '', otherThreshold: 5, }, }), ]) }) }) })
the_stack
import assert from "assert"; import { EIP1559FeeMarketDatabasePayload, EIP1559FeeMarketDatabaseTx, EIP1559FeeMarketTransaction, EIP2930AccessListDatabasePayload, EIP2930AccessListDatabaseTx, EIP2930AccessListTransaction, LegacyDatabasePayload, LegacyTransaction, TransactionFactory, TransactionType, TypedDatabaseTransaction, TypedRpcTransaction } from "../../transaction"; import Common from "@ethereumjs/common"; import Wallet from "../../ethereum/src/wallet"; import { decode } from "@ganache/rlp"; import { EthereumOptionsConfig } from "../../options"; import { BUFFER_EMPTY, Quantity } from "@ganache/utils"; describe("@ganache/ethereum-transaction", async () => { const common = Common.forCustomChain( "mainnet", { name: "ganache", chainId: 1337, comment: "Local test network", bootstrapNodes: [] }, "london" ); // #region configure accounts and private keys in wallet const privKey = `0x${"46".repeat(32)}`; const privKeyBuf = Quantity.from(privKey).toBuffer(); const options = EthereumOptionsConfig.normalize({ wallet: { accounts: [ { secretKey: privKey, balance: 100n }, { secretKey: `0x${"46".repeat(31)}47`, balance: 100n }, { secretKey: `0x${"46".repeat(31)}48`, balance: 100n } ] } }); const wallet = new Wallet(options.wallet); const [from, to, accessListAcc] = wallet.addresses; // #endregion configure accounts and private keys in wallet // #region configure transaction constants // #region legacy transaction const untypedTx: TypedRpcTransaction = { from: from, to: to, gasPrice: "0xffff" }; const typedLegacyTx: TypedRpcTransaction = { from: from, to: to, type: "0x0", gasPrice: "0xffff" }; const rawLegacyStrTx = "0xf8618082ffff80945a17650be84f28ed583e93e6ed0c99b1d1fc1b348080820a95a0d9c2d3cb65d7079f528d28d782fe752ed698381481f7b91790e067ea335c1dc0a0731131778ae061aa29567cc6b36fe3528092b687fb68c3f529493fca200c711d"; const rawLegacyStrTxChainId1234 = "0xf8618082ffff80945a17650be84f28ed583e93e6ed0c99b1d1fc1b3480808209c8a0c5e728f25ba7e771865291d91fe50945190d81ed2e240a4755370fb87dff349ea014e6102d81eb9a66307c487e662b0f9f91e78b203e06ba853fcf246fa49145db"; const rawLegacyDbTx = decode<LegacyDatabasePayload>( Buffer.from(rawLegacyStrTx.slice(2), "hex") ); // #endregion legacy transaction // #region access list transactions const accessListStorageKey = "0x0000000000000000000000000000000000000000000000000000000000000004"; const accessListTx: TypedRpcTransaction = { from: from, to: to, type: "0x1", gasPrice: "0xffff", accessList: [ { address: accessListAcc, storageKeys: [accessListStorageKey] } ] }; const rawEIP2930StringData = "0x01f89c8205398082ffff80945a17650be84f28ed583e93e6ed0c99b1d1fc1b348080f838f7940efbd0bec0da8dcc0ad442a7d337e9cdc2dd6a54e1a0000000000000000000000000000000000000000000000000000000000000000480a096fe05ce879533fcdc1094e8eb18780024f93b5dec1160b542f396148f4eafdba06e4a230ccf316118fed883ff63bb072e112dbffeae06bb076c95d93ae731341c"; const rawEIP2930StringDataChainId1234 = "0x01f89c8204d28082ffff80945a17650be84f28ed583e93e6ed0c99b1d1fc1b348080f838f7940efbd0bec0da8dcc0ad442a7d337e9cdc2dd6a54e1a0000000000000000000000000000000000000000000000000000000000000000401a02b78e5b29b6820ceb9d936b3144ec0e491c49c4c5923260cac8068e156b45a25a05e0863362858d72afa42ad5f35d2673793c4d1c18d93bc710b3b7212ecaed939"; const eip2930Buf = Buffer.from(rawEIP2930StringData.slice(2), "hex"); const rawEIP2930DBData: EIP2930AccessListDatabaseTx = [ eip2930Buf.slice(0, 1), ...decode<EIP2930AccessListDatabasePayload>(eip2930Buf.slice(1)) ]; // #endregion access list transactions //#region fee market transactions const feeMarketTx: TypedRpcTransaction = { from: from, to: to, type: "0x2", maxPriorityFeePerGas: "0xff", maxFeePerGas: "0xffff", accessList: [ { address: accessListAcc, storageKeys: [accessListStorageKey] } ] }; const rawEIP1559StringData = "0x02f89e8205398081ff82ffff80945a17650be84f28ed583e93e6ed0c99b1d1fc1b348080f838f7940efbd0bec0da8dcc0ad442a7d337e9cdc2dd6a54e1a0000000000000000000000000000000000000000000000000000000000000000480a0274488defb0af8f0dcf1ecf4ff6bb60c0a7584a76db38575e0d57c9ec064c385a01707e5bdd3978be9aaa8375ed70186ea4a01cff5e9fc183855b198c4cb022e4c"; const rawEIP1559StringDataChainId1234 = "0x02f89e8204d28081ff82ffff80945a17650be84f28ed583e93e6ed0c99b1d1fc1b348080f838f7940efbd0bec0da8dcc0ad442a7d337e9cdc2dd6a54e1a0000000000000000000000000000000000000000000000000000000000000000480a0090645667290e86dc0faa28cbcbaa2fcb641a8688010ee1fc74911eba0351e7fa03ebdbed56c38a0991508bd8c2ad1d266e835807a97f8e4ad658f82b8ed6b111a"; const eip1559Buf = Buffer.from(rawEIP1559StringData.slice(2), "hex"); const rawEIP1559DBData: EIP1559FeeMarketDatabaseTx = [ eip1559Buf.slice(0, 1), ...decode<EIP1559FeeMarketDatabasePayload>(eip1559Buf.slice(1)) ]; // #endregion fee market transactions // #endregion configure transaction constants describe("TransactionFactory", () => { describe("LegacyTransaction type from factory", () => { let txFromRpc: LegacyTransaction; it("fails to parse legacy transaction without EIP-155 signature", () => { assert.throws( () => <LegacyTransaction>( TransactionFactory.fromString(rawLegacyStrTxChainId1234, common) ), { message: "Invalid signature v value" } ); }); it("infers legacy transaction if type omitted", () => { txFromRpc = <LegacyTransaction>( TransactionFactory.fromRpc(untypedTx, common) ); assert.strictEqual(txFromRpc.type.toString(), "0x0"); }); it("generates legacy transactions from rpc data", async () => { txFromRpc = <LegacyTransaction>( TransactionFactory.fromRpc(typedLegacyTx, common) ); assert.strictEqual(txFromRpc.type.toString(), "0x0"); }); it("generates legacy transactions from raw buffer data", async () => { const txFromDb = TransactionFactory.fromDatabaseTx( rawLegacyDbTx, common ); assert.strictEqual(txFromDb.type.toString(), "0x0"); }); it("generates legacy transactions from raw string", async () => { const txFromString = TransactionFactory.fromString( rawLegacyStrTx, common ); assert.strictEqual(txFromString.type.toString(), "0x0"); }); it("normalizes an eip-2930 transaction to legacy when access list is omitted", async () => { const tempAccessListTx = JSON.parse(JSON.stringify(accessListTx)); // don't want to alter accessListTx tempAccessListTx.accessList = undefined; const txFromRpc = TransactionFactory.fromRpc(tempAccessListTx, common); assert.strictEqual(txFromRpc.type.toString(), "0x0"); }); }); describe("EIP2930AccessListTransaction type from factory", () => { it("generates eip2930 access list transactions from rpc data", async () => { const txFromRpc = <EIP2930AccessListTransaction>( TransactionFactory.fromRpc(accessListTx, common) ); const key = txFromRpc.accessListJSON[0].storageKeys[0]; assert.strictEqual(txFromRpc.type.toString(), "0x1"); assert.strictEqual(key, accessListStorageKey); }); it("fails to parse EIP-2390 transaction with wrong chainId", async () => { assert.throws( () => <EIP2930AccessListTransaction>( TransactionFactory.fromString( rawEIP2930StringDataChainId1234, common ) ), { message: "Invalid chain id (1234) for chain with id 1337.", code: -32000 } ); }); it("generates eip2930 access list transactions from raw buffer data", async () => { const txFromDb = <EIP2930AccessListTransaction>( TransactionFactory.fromDatabaseTx(rawEIP2930DBData, common) ); const key = txFromDb.accessListJSON[0].storageKeys[0]; assert.strictEqual(txFromDb.type.toString(), "0x1"); assert.strictEqual(key, accessListStorageKey); }); it("generates eip2930 access list transactions from raw string", async () => { const txFromString = <EIP2930AccessListTransaction>( TransactionFactory.fromString(rawEIP2930StringData, common) ); const key = txFromString.accessListJSON[0].storageKeys[0]; assert.strictEqual(txFromString.type.toString(), "0x1"); assert.strictEqual(key, accessListStorageKey); }); }); describe("EIP1559FeeMarketTransaction type from factory", () => { it("generates eip1559 fee market transactions from rpc data", async () => { const txFromRpc = <EIP1559FeeMarketTransaction>( TransactionFactory.fromRpc(feeMarketTx, common) ); const key = txFromRpc.accessListJSON[0].storageKeys[0]; assert.strictEqual(txFromRpc.type.toString(), "0x2"); }); it("generates eip1559 fee market transactions from raw buffer data", async () => { const txFromDb = <EIP1559FeeMarketTransaction>( TransactionFactory.fromDatabaseTx(rawEIP1559DBData, common) ); const key = txFromDb.accessListJSON[0].storageKeys[0]; assert.strictEqual(txFromDb.type.toString(), "0x2"); }); it("fails to parse EIP-1559 transaction with wrong chainId", async () => { assert.throws( () => <EIP1559FeeMarketTransaction>( TransactionFactory.fromString( rawEIP1559StringDataChainId1234, common ) ), { message: "Invalid chain id (1234) for chain with id 1337.", code: -32000 } ); }); it("generates eip1559 fee market transactions from raw string", async () => { const txFromString = <EIP1559FeeMarketTransaction>( TransactionFactory.fromString(rawEIP1559StringData, common) ); assert.strictEqual(txFromString.type.toString(), "0x2"); }); it("normalizes a legacy transaction to eip-1559 when gas price is omitted", async () => { const tempLegacyTx = JSON.parse(JSON.stringify(typedLegacyTx)); // don't want to alter accessListTx tempLegacyTx.gasPrice = undefined; const txFromRpc = TransactionFactory.fromRpc(tempLegacyTx, common); assert.strictEqual(txFromRpc.type.toString(), "0x2"); }); it("normalizes an eip-2930 transaction to eip-1559 when gas price is omitted", async () => { const tempAccessListTx = JSON.parse(JSON.stringify(accessListTx)); // don't want to alter accessListTx tempAccessListTx.gasPrice = undefined; const txFromRpc = TransactionFactory.fromRpc(tempAccessListTx, common); assert.strictEqual(txFromRpc.type.toString(), "0x2"); }); }); }); describe("LegacyTransaction Type", () => { const tx = <LegacyTransaction>( TransactionFactory.fromRpc(typedLegacyTx, common) ); it("can be signed and hashed", () => { assert.strictEqual(tx.hash, undefined); tx.signAndHash(privKeyBuf); assert.strictEqual( tx.hash.toString(), "0x35886e9379da43140070da4b4d39e0e6fa246cc3dec7b5b51107e5dd722f671b" ); }); describe("toVmTransaction", () => { const vmTx = tx.toVmTransaction(); it("has a function to return the hash", () => { assert.notDeepStrictEqual(vmTx.hash().toString(), ""); }); it("has nonce property", () => { assert.strictEqual(vmTx.nonce.toString(), "0"); }); it("has gasPrice property", () => { assert.strictEqual(vmTx.gasPrice.toString(), "65535"); }); it("has gasLimit property", () => { assert.strictEqual(vmTx.gasLimit.toString(), "0"); }); it("has to property", () => { assert.strictEqual("0x" + vmTx.to.buf.toString("hex"), to); }); it("has value property", () => { assert.strictEqual(vmTx.value.toString(), "0"); }); it("has data property", () => { assert.strictEqual(vmTx.data.toString(), ""); }); it("has a function to get sender address", () => { assert.strictEqual( "0x" + vmTx.getSenderAddress().buf.toString("hex"), from ); }); it("has a function to get base fee", () => { assert.strictEqual(vmTx.getBaseFee().toString(), "21000"); }); it("has a function to get base upfront cost", () => { assert.strictEqual(vmTx.getUpfrontCost().toString(), "0"); }); it("has a function to check capability support", () => { assert.strictEqual(vmTx.supports(2930), false); }); }); it("can be converted to JSON", () => { const jsonTx = tx.toJSON(); assert.strictEqual(jsonTx.type, tx.type); assert.strictEqual(jsonTx.hash, tx.hash); assert.strictEqual(jsonTx.nonce, tx.nonce); assert.strictEqual(jsonTx.blockHash, null); assert.strictEqual(jsonTx.blockNumber, null); assert.strictEqual(jsonTx.transactionIndex, null); assert.strictEqual(jsonTx.from, tx.from); assert.strictEqual(jsonTx.to, tx.to); assert.strictEqual(jsonTx.value, tx.value); // when this value is omitted, we set a default assert.strictEqual(jsonTx.value.toString(), "0x0"); assert.strictEqual(jsonTx.gas, tx.gas); assert.strictEqual(jsonTx.gasPrice, tx.gasPrice); assert.strictEqual(jsonTx.input, tx.data); // when this value is omitted, we set a default assert.strictEqual(jsonTx.input.toString(), "0x"); assert.strictEqual(jsonTx.v, tx.v); assert.strictEqual(jsonTx.r, tx.r); assert.strictEqual(jsonTx.s, tx.s); }); }); describe("EIP2930AccessListTransaction Type", () => { const tx = <EIP2930AccessListTransaction>( TransactionFactory.fromRpc(accessListTx, common) ); it("can be signed and hashed", () => { assert.strictEqual(tx.hash, undefined); tx.signAndHash(privKeyBuf); assert.strictEqual( tx.hash.toString(), "0x078395f79508111c9061f9983d387c8b7bfed990dfa098497aa4d34b0e47b265" ); }); describe("toVmTransaction", () => { const vmTx = tx.toVmTransaction(); it("has a function to return the hash", () => { assert.notDeepStrictEqual(vmTx.hash().toString(), ""); }); it("has nonce property", () => { assert.strictEqual(vmTx.nonce.toString(), "0"); }); it("has gasPrice property", () => { assert.strictEqual(vmTx.gasPrice.toString(), "65535"); }); it("has gasLimit property", () => { assert.strictEqual(vmTx.gasLimit.toString(), "0"); }); it("has to property", () => { assert.strictEqual("0x" + vmTx.to.buf.toString("hex"), to); }); it("has value property", () => { assert.strictEqual(vmTx.value.toString(), "0"); }); it("has data property", () => { assert.strictEqual(vmTx.data.toString(), ""); }); it("has a function to get sender address", () => { assert.strictEqual( "0x" + vmTx.getSenderAddress().buf.toString("hex"), from ); }); it("has a function to get base fee", () => { assert.strictEqual(vmTx.getBaseFee().toString(), "25300"); }); it("has a function to get base upfront cost", () => { assert.strictEqual(vmTx.getUpfrontCost().toString(), "0"); }); it("has a function to check capability support", () => { assert.strictEqual(vmTx.supports(2930), true); }); }); it("can be converted to JSON", () => { const jsonTx = tx.toJSON(); //assert.strictEqual(jsonTx.type, txFromRpc.type); assert.strictEqual(jsonTx.hash, tx.hash); assert.strictEqual(jsonTx.nonce, tx.nonce); assert.strictEqual(jsonTx.blockHash, null); assert.strictEqual(jsonTx.blockNumber, null); assert.strictEqual(jsonTx.transactionIndex, null); assert.strictEqual(jsonTx.from, tx.from); assert.strictEqual(jsonTx.to, tx.to); assert.strictEqual(jsonTx.value, tx.value); // when this value is omitted, we set a default assert.strictEqual(jsonTx.value.toString(), "0x0"); assert.strictEqual(jsonTx.gas, tx.gas); assert.strictEqual(jsonTx.gasPrice, tx.gasPrice); assert.strictEqual(jsonTx.input, tx.data); // when this value is omitted, we set a default assert.strictEqual(jsonTx.input.toString(), "0x"); assert.strictEqual(jsonTx.v, tx.v); assert.strictEqual(jsonTx.r, tx.r); assert.strictEqual(jsonTx.s, tx.s); }); }); describe("EIP1559FeeMarketTransaction Type", () => { const tx = <EIP1559FeeMarketTransaction>( TransactionFactory.fromRpc(feeMarketTx, common) ); it("can be signed and hashed", () => { assert.strictEqual(tx.hash, undefined); tx.signAndHash(privKeyBuf); assert.strictEqual( tx.hash.toString(), "0xabe11ba446440bd0ea9b9e9de9eb479ae4555455ec2244a80ef7a72eddf6fe17" ); }); describe("toVmTransaction", () => { const vmTx = tx.toVmTransaction(); it("has a function to return the hash", () => { assert.notDeepStrictEqual(vmTx.hash().toString(), ""); }); it("has nonce property", () => { assert.strictEqual(vmTx.nonce.toString(), "0"); }); it("has maxPriorityFeePerGas property", () => { assert.strictEqual(vmTx.maxPriorityFeePerGas.toString(), "255"); }); it("has maxFeePerGas property", () => { assert.strictEqual(vmTx.maxFeePerGas.toString(), "65535"); }); it("has gasLimit property", () => { assert.strictEqual(vmTx.gasLimit.toString(), "0"); }); it("has to property", () => { assert.strictEqual("0x" + vmTx.to.buf.toString("hex"), to); }); it("has value property", () => { assert.strictEqual(vmTx.value.toString(), "0"); }); it("has data property", () => { assert.strictEqual(vmTx.data.toString(), ""); }); it("has a function to get sender address", () => { assert.strictEqual( "0x" + vmTx.getSenderAddress().buf.toString("hex"), from ); }); it("has a function to get base fee", () => { assert.strictEqual(vmTx.getBaseFee().toString(), "21000"); }); it("has a function to get base upfront cost", () => { assert.strictEqual(vmTx.getUpfrontCost().toString(), "0"); }); it("has a function to check capability support", () => { assert.strictEqual(vmTx.supports(1559), true); }); }); it("can be converted to JSON", () => { const jsonTx = tx.toJSON(); //assert.strictEqual(jsonTx.type, txFromRpc.type); assert.strictEqual(jsonTx.hash, tx.hash); assert.strictEqual(jsonTx.nonce, tx.nonce); assert.strictEqual(jsonTx.blockHash, null); assert.strictEqual(jsonTx.blockNumber, null); assert.strictEqual(jsonTx.transactionIndex, null); assert.strictEqual(jsonTx.from, tx.from); assert.strictEqual(jsonTx.to, tx.to); assert.strictEqual(jsonTx.value, tx.value); // when this value is omitted, we set a default assert.strictEqual(jsonTx.value.toString(), "0x0"); assert.strictEqual(jsonTx.gas, tx.gas); assert.strictEqual(jsonTx.maxPriorityFeePerGas, tx.maxPriorityFeePerGas); assert.strictEqual(jsonTx.maxFeePerGas, tx.maxFeePerGas); assert.strictEqual(jsonTx.gasPrice, tx.effectiveGasPrice); assert.strictEqual(jsonTx.input, tx.data); // when this value is omitted, we set a default assert.strictEqual(jsonTx.input.toString(), "0x"); assert.strictEqual(jsonTx.v, tx.v); assert.strictEqual(jsonTx.r, tx.r); assert.strictEqual(jsonTx.s, tx.s); }); }); describe("Error and helper cases", () => { it("does not allow unsupported tx types from rpc data", async () => { const rpc: TypedRpcTransaction = { from: from, to: to, type: "0x55", gasPrice: "0xffff" }; assert.throws(() => { TransactionFactory.fromRpc(rpc, common); }); }); it("does not allow unsupported tx types from raw buffer data", async () => { const db = [ Buffer.from("0x55"), BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY ]; assert.throws(() => { TransactionFactory.fromDatabaseTx( db as TypedDatabaseTransaction, common ); }); }); it("does not allow unsupported tx types from raw string data", async () => { const str: string = "0x55"; assert.throws(() => { TransactionFactory.fromString(str, common); }); }); it("gets tx type from raw data", async () => { const db = [ BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY, BUFFER_EMPTY ]; assert.strictEqual( TransactionFactory.typeOfRaw(db as TypedDatabaseTransaction), TransactionType.Legacy ); }); describe("checks for hardfork's support of transaction types", () => { describe("pre-berlin checks", () => { const preBerlin = Common.forCustomChain( "mainnet", { name: "ganache", chainId: 1337, comment: "Local test network", bootstrapNodes: [] }, "istanbul" ); it("creates legacy transaction before berlin hardfork", () => { const txFromRpc = TransactionFactory.fromRpc( untypedTx, preBerlin ) as any; assert.strictEqual(txFromRpc.type.toString(), "0x0"); }); it("converts EIP2930AccessList RPC data to LegacyTransaction before berlin hardfork", () => { const txFromRpc = TransactionFactory.fromRpc( accessListTx, preBerlin ) as any; assert.strictEqual(txFromRpc.type.toString(), "0x0"); assert.strictEqual(txFromRpc.accessList, undefined); }); it("does not convert EIP2930AccessList raw database data to LegacyTransaction before berlin hardfork", () => { const txFromDb = TransactionFactory.fromDatabaseTx( rawEIP2930DBData, common ) as any; assert.strictEqual(txFromDb.type.toString(), "0x1"); assert.deepStrictEqual(txFromDb.accessList.length, 1); }); it("does not convert EIP2930AccessList raw string data to LegacyTransaction before berlin hardfork", () => { assert.throws( () => TransactionFactory.fromString( rawEIP2930StringData, preBerlin ) as any, { message: "Could not decode transaction: invalid remainder" } ); }); it("converts EIP1559FeeMarket RPC data to LegacyTransaction before berlin hardfork", () => { const txFromRpc = TransactionFactory.fromRpc( feeMarketTx, preBerlin ) as any; assert.strictEqual(txFromRpc.type.toString(), "0x0"); assert.strictEqual(txFromRpc.accessList, undefined); }); it("does not convert EIP1559FeeMarket raw database data to LegacyTransaction", () => { const txFromDb = TransactionFactory.fromDatabaseTx( rawEIP1559DBData, common ) as any; assert.strictEqual(txFromDb.type.toString(), "0x2"); assert.strictEqual(txFromDb.accessList.length, 1); }); it("does not convert EIP1559FeeMarket raw string data to LegacyTransaction", () => { assert.throws( () => TransactionFactory.fromString(rawEIP1559StringData, preBerlin), { message: "Could not decode transaction: invalid remainder" } ); }); }); describe("pre-london checks", () => { const preLondon = Common.forCustomChain( "mainnet", { name: "ganache", chainId: 1337, comment: "Local test network", bootstrapNodes: [] }, "berlin" ); it("creates legacy transaction before london hardfork", () => { const txFromRpc = TransactionFactory.fromRpc( untypedTx, preLondon ) as any; assert.strictEqual(txFromRpc.type.toString(), "0x0"); }); it("creates eip2930 transaction before london hardfork", () => { const txFromRpc = TransactionFactory.fromRpc( accessListTx, preLondon ) as any; assert.strictEqual(txFromRpc.type.toString(), "0x1"); }); it("throws if eip1559 transaction is sent before london hardfork", () => { assert.throws(() => { TransactionFactory.fromRpc(feeMarketTx, preLondon); }); }); }); }); }); });
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Chart } from '../../../src/chart/chart'; import { LineSeries } from '../../../src/chart/series/line-series'; import { Legend } from '../../../src/chart/legend/legend'; import { DataLabel } from '../../../src/chart/series/data-label'; import { Category } from '../../../src/chart/axis/category-axis'; import { Crosshair } from '../../../src/chart/user-interaction/crosshair'; import { indexedCategoryData } from '../base/data.spec'; import { MouseEvents } from '../base/events.spec'; import { unbindResizeEvents } from '../base/data.spec'; import '../../../node_modules/es6-promise/dist/es6-promise'; import { EmitType } from '@syncfusion/ej2-base'; import { ILoadedEventArgs } from '../../../src/chart/model/chart-interface'; import {profile , inMB, getMemoryProfile} from '../../common.spec'; Chart.Inject(LineSeries, Category, DataLabel, Crosshair, Legend); export interface Arg { chart: Chart; } describe('Chart Control', () => { 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('Indexed Category Axis', () => { let chart: Chart; let ele: HTMLElement; let loaded: EmitType<ILoadedEventArgs>; let element: Element; let trigger: MouseEvents = new MouseEvents(); beforeAll((): void => { ele = createElement('div', { id: 'container' }); document.body.appendChild(ele); chart = new Chart( { primaryXAxis: { valueType: 'Category', isIndexed: true, labelIntersectAction: 'Hide' }, primaryYAxis: { title: 'PrimaryYAxis' }, series: [{ dataSource: indexedCategoryData, xName: 'x', yName: 'y', name: 'Gold', animation: { enable: false } }], height: '400', width: '900', loaded: loaded, legendSettings: { visible: false } }); }); afterAll((): void => { chart.destroy(); ele.remove(); }); it('Checking the single series Labels', (done: Function) => { loaded = (args: Arg): void => { let svg: HTMLElement = document.getElementById('containerAxisLabels0'); expect(svg.childNodes.length == 7).toBe(true); svg = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Monday').toBe(true); svg = document.getElementById('container0_AxisLabel_6'); expect(svg.textContent == 'Monday').toBe(true); expect(args.chart.visibleSeries[0].points[6].xValue == 6).toBe(true); done(); }; chart.loaded = loaded; chart.appendTo('#container'); }); it('Checking indexed false', (done: Function) => { loaded = (args: Arg): void => { let svg: HTMLElement = document.getElementById('containerAxisLabels0'); expect(svg.childNodes.length == 5).toBe(true); expect(args.chart.visibleSeries[0].points[6].xValue == 0).toBe(true); done(); }; chart.loaded = loaded; chart.primaryXAxis.isIndexed = false; chart.refresh(); }); it('Checking the multiple series Labels', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('containerAxisLabels0'); expect(svg.childNodes.length == 7).toBe(true); svg = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Monday, Monday').toBe(true); svg = document.getElementById('container0_AxisLabel_6'); expect(svg.textContent == 'Monday, Monday').toBe(true); done(); }; chart.loaded = loaded; chart.primaryXAxis.isIndexed = true; chart.series = [ { dataSource: indexedCategoryData, xName: 'x', yName: 'y', name: 'Gold', animation: { enable: false } }, { dataSource: indexedCategoryData, xName: 'x', yName: 'y', name: 'silver', animation: { enable: false } } ]; chart.refresh(); }); it('Checking with two rows', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('containerAxisLabels0'); expect(svg.childNodes.length == 7).toBe(true); svg = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Monday, Monday').toBe(true); svg = document.getElementById('container0_AxisLabel_6'); expect(svg.textContent == 'Monday, Monday').toBe(true); done(); }; chart.loaded = loaded; chart.rows = [{ height: '50%' }, { height: '50%' }]; chart.axes = [{ rowIndex: 1, name: 'yAxis' }]; chart.series[0].yAxisName = 'yAxis'; chart.refresh(); }); it('Checking with two columns', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('containerAxisLabels0'); svg = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Monday').toBe(true); done(); }; chart.loaded = loaded; chart.rows = [{}]; chart.columns = [{ width: '50%' }, { width: '50%' }]; chart.axes = [{ columnIndex: 1, name: 'xAxis', valueType: 'Category' }]; chart.series[0].yAxisName = null; chart.series[0].xAxisName = 'xAxis'; chart.refresh(); }); it('Checking with two columns with multiple series and second column is indexed false', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('containerAxisLabels0'); svg = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Monday, Monday').toBe(true); svg = document.getElementById('containerAxisLabels2'); svg = document.getElementById('container2_AxisLabel_0'); expect(svg.textContent == 'Monday').toBe(true); done(); }; chart.loaded = loaded; chart.series = [ { dataSource: indexedCategoryData, xAxisName: 'xAxis', xName: 'x', yName: 'y', name: 'series1', animation: { enable: false } }, { dataSource: indexedCategoryData, xAxisName: 'xAxis', xName: 'x', yName: 'y', name: 'series2', animation: { enable: false } }, { dataSource: indexedCategoryData, xName: 'x', yName: 'y', name: 'series3', animation: { enable: false } }, { dataSource: indexedCategoryData, xName: 'x', yName: 'y', name: 'series4', animation: { enable: false } } ]; chart.refresh(); }); it('Checking with two columns and second column also indexed true', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('containerAxisLabels2'); svg = document.getElementById('container2_AxisLabel_0'); expect(svg.textContent == 'Monday, Monday').toBe(true); done(); }; chart.loaded = loaded; chart.axes[0].labelIntersectAction = 'Hide'; chart.axes[0].isIndexed = true; chart.refresh(); }); it('Checking with two columns and spanning', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('containerAxisLabels2'); svg = document.getElementById('container2_AxisLabel_0'); expect(svg.textContent == 'Monday, Monday').toBe(true); done(); }; chart.loaded = loaded; chart.primaryXAxis.span = 2; chart.refresh(); }); it('Checking axis labels after Legend click', (done: Function) => { loaded = (args: Arg): void => { chart.loaded = null; let legendElement: Element; legendElement = document.getElementById('container_chart_legend_text_2'); trigger.clickEvent(legendElement); expect(chart.series[2].visible).toBe(false); expect(args.chart.axisCollections[0].labels[0] == 'Monday').toBe(true); done(); }; chart.legendSettings = { visible: true }; chart.loaded = loaded; chart.primaryXAxis.span = 1; chart.refresh(); }); it('Checking with multiple axis and oppposed position', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('containerAxisLabels0'); svg = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Monday, Monday').toBe(true); svg = document.getElementById('containerAxisLabels2'); svg = document.getElementById('container2_AxisLabel_0'); expect(svg.textContent == 'Monday').toBe(true); done(); }; chart.loaded = loaded; chart.columns = [{}]; chart.rows = [{ height: '50%' }, { height: '50%' }]; chart.axes = [{ rowIndex: 0, name: 'xAxis', valueType: 'Category', isIndexed: true, opposedPosition: true }, { rowIndex: 0, name: 'xAxis1', valueType: 'Category', isIndexed: true, opposedPosition: false },] chart.series = [ { dataSource: indexedCategoryData, xAxisName: 'xAxis', xName: 'x', yName: 'y', name: 'series1', animation: { enable: false } }, { dataSource: indexedCategoryData, xAxisName: 'xAxis1', xName: 'x', yName: 'y', name: 'series2', animation: { enable: false } }, { dataSource: indexedCategoryData, xName: 'x', yName: 'y', name: 'series3', animation: { enable: false } }, { dataSource: indexedCategoryData, xName: 'x', yName: 'y', name: 'series4', animation: { enable: false } } ]; chart.refresh(); }); }); describe('Indexed Category Axis - Line break label checking', () => { let chart: Chart; let ele: HTMLElement; let loaded: EmitType<ILoadedEventArgs>; let element: Element; let trigger: MouseEvents = new MouseEvents(); beforeAll((): void => { ele = createElement('div', { id: 'container' }); document.body.appendChild(ele); chart = new Chart( { primaryXAxis: { valueType: 'Category', isIndexed: true }, primaryYAxis: {}, series: [{ dataSource: [ { x: 'Monday<br>Monday<br>Monday<br>Monday', y: 50 }, { x: 'Tuesday', y: 40 }, { x: 'Wednesday', y: 70 }, { x: 'Thursday', y: 60 }, { x: 'Friday', y: 50 }, { x: 'Monday<br>Monday<br>Monday<br>Monday', y: 40 }, { x: 'Monday<br>Monday<br>Monday<br>Monday', y: 30 }], xName: 'x', yName: 'y', type: 'Line', animation: { enable: false } }], legendSettings: { visible: false } }, '#container'); }); afterAll((): void => { chart.destroy(); ele.remove(); }); it('line break labels behavior checking', (done: Function) => { loaded = (args: Object): void => { let label: HTMLElement = document.getElementById('containerAxisLabels0'); expect(label.childElementCount == 7).toBe(true); label = document.getElementById('container0_AxisLabel_0'); expect(label.childElementCount == 3).toBe(true); expect(label.childNodes[0].textContent == 'Monday').toBe(true); done(); }; chart.loaded = loaded; chart.refresh(); }); it('line break labels with inversed axis', (done: Function) => { loaded = (args: Object): void => { let label: HTMLElement = document.getElementById('containerAxisLabels0'); expect(label.childElementCount == 7).toBe(true); label= document.getElementById('container0_AxisLabel_6'); expect(label.childElementCount == 3).toBe(true); expect(label.childNodes[0].textContent == 'Monday').toBe(true); done(); }; chart.loaded = loaded; chart.primaryXAxis.isInversed = true; chart.refresh(); }); it('line break labels with opposed position true', (done: Function) => { loaded = (args: Object): void => { let label: HTMLElement = document.getElementById('containerAxisLabels0'); expect(label.childElementCount == 7).toBe(true); label= document.getElementById('container0_AxisLabel_0'); expect(label.childElementCount == 3).toBe(true); expect(label.childNodes[0].textContent == 'Monday').toBe(true); done(); }; chart.loaded = loaded; chart.primaryXAxis.isInversed = false; chart.primaryXAxis.opposedPosition = true; chart.refresh(); }); }); 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 * as path from "path"; import * as vscode from "vscode"; import * as utils from "../utils"; import WebSiteManagementClient = require("azure-arm-website"); import { Component, ComponentType } from "./Interfaces/Component"; import { Provisionable } from "./Interfaces/Provisionable"; import { Deployable } from "./Interfaces/Deployable"; import { AzureFunctionsLanguage, ScaffoldType } from "../constants"; import { ServiceClientCredentials } from "ms-rest"; import { AzureAccount, AzureResourceFilter } from "../azure-account.api"; import { StringDictionary } from "azure-arm-website/lib/models"; import { getExtension, checkExtensionAvailable } from "./Apis"; import { ExtensionName } from "./Interfaces/Api"; import { Guid } from "guid-typescript"; import { AzureComponentConfig, ComponentInfo, DependencyConfig, Dependency, AzureConfigFileHandler } from "./AzureComponentConfig"; import { FileUtility } from "../FileUtility"; import { AzureFunctionsCommands } from "../common/Commands"; import { OperationCanceledError } from "../common/Error/OperationCanceledError"; import { OperationFailedError } from "../common/Error/OperationFailedErrors/OperationFailedError"; import { DependentExtensionNotFoundError } from "../common/Error/OperationFailedErrors/DependentExtensionNotFoundError"; import { ArgumentEmptyOrNullError } from "../common/Error/OperationFailedErrors/ArgumentEmptyOrNullError"; import { AzureConfigNotFoundError } from "../common/Error/SystemErrors/AzureConfigNotFoundErrors"; const importLazy = require("import-lazy"); const azureUtilityModule = importLazy(() => require("./AzureUtility"))(); export class AzureFunctions implements Component, Provisionable, Deployable { dependencies: DependencyConfig[] = []; private componentType: ComponentType; private channel: vscode.OutputChannel; private azureFunctionsPath: string; private azureAccountExtension: AzureAccount | undefined = getExtension(ExtensionName.AzureAccount); private functionLanguage: string | null; private functionFolder: string; private projectRootPath: string; private azureConfigFileHandler: AzureConfigFileHandler; private componentId: string; get id(): string { return this.componentId; } private async getCredentialFromSubscriptionId(subscriptionId: string): Promise<ServiceClientCredentials | undefined> { if (!this.azureAccountExtension) { throw new DependentExtensionNotFoundError("get credential from subscription id", ExtensionName.AzureAccount); } if (!subscriptionId) { throw new ArgumentEmptyOrNullError("get credential from subscription id", "subscription ID"); } const subscriptions: AzureResourceFilter[] = this.azureAccountExtension.filters; for (let i = 0; i < subscriptions.length; i++) { const subscription: AzureResourceFilter = subscriptions[i]; if (subscription.subscription.subscriptionId === subscriptionId) { return subscription.session.credentials; } } return undefined; } constructor( projectRoot: string, azureFunctionsPath: string, functionFolder: string, channel: vscode.OutputChannel, language: string | null = null, dependencyComponents: Dependency[] | null = null ) { this.componentType = ComponentType.AzureFunctions; this.channel = channel; this.azureFunctionsPath = azureFunctionsPath; this.functionLanguage = language; this.functionFolder = functionFolder; this.componentId = Guid.create().toString(); this.projectRootPath = projectRoot; this.azureConfigFileHandler = new AzureConfigFileHandler(this.projectRootPath); if (dependencyComponents && dependencyComponents.length > 0) { dependencyComponents.forEach(dependency => this.dependencies.push({ id: dependency.component.id.toString(), type: dependency.type }) ); } } name = "Azure Functions"; getComponentType(): ComponentType { return this.componentType; } static async isAvailable(): Promise<boolean> { return await checkExtensionAvailable(ExtensionName.AzureFunctions); } async checkPrerequisites(operation: string): Promise<void> { const isFunctionsExtensionAvailable = await AzureFunctions.isAvailable(); if (!isFunctionsExtensionAvailable) { throw new DependentExtensionNotFoundError(operation, ExtensionName.AzureFunctions); } } async load(): Promise<void> { const componentConfig = await this.azureConfigFileHandler.getComponentByFolder( ScaffoldType.Workspace, this.functionFolder ); if (componentConfig) { this.componentId = componentConfig.id; this.dependencies = componentConfig.dependencies; if (componentConfig.componentInfo) { this.functionLanguage = componentConfig.componentInfo.values.functionLanguage; } } } async create(): Promise<void> { const scaffoldType = ScaffoldType.Local; console.log(this.azureFunctionsPath); if (!(await FileUtility.directoryExists(scaffoldType, this.azureFunctionsPath))) { await FileUtility.mkdirRecursively(scaffoldType, this.azureFunctionsPath); } if (!this.functionLanguage) { const picks: vscode.QuickPickItem[] = [ { label: AzureFunctionsLanguage.CSharpScript, description: "" }, { label: AzureFunctionsLanguage.JavaScript, description: "" }, { label: AzureFunctionsLanguage.CSharpLibrary, description: "" } ]; const languageSelection = await vscode.window.showQuickPick(picks, { ignoreFocusOut: true, matchOnDescription: true, matchOnDetail: true, placeHolder: "Select a language for Azure Functions" }); if (!languageSelection) { throw new OperationCanceledError( "Unable to get the language for Azure Functions. Creating project for Azure Functions cancelled." ); } this.functionLanguage = languageSelection.label; } const templateName = utils.getScriptTemplateNameFromLanguage(this.functionLanguage); if (!templateName) { throw new OperationCanceledError( "Unable to get the template for Azure Functions.Creating project for Azure Functions cancelled." ); } if (this.functionLanguage === AzureFunctionsLanguage.CSharpLibrary) { await vscode.commands.executeCommand( AzureFunctionsCommands.CreateNewProject, this.azureFunctionsPath, this.functionLanguage, "~2", false /* openFolder */, templateName, "IoTHubTrigger1", { connection: "eventHubConnectionString", path: "%eventHubConnectionPath%", consumerGroup: "$Default", namespace: "IoTWorkbench" } ); } else { await vscode.commands.executeCommand( AzureFunctionsCommands.CreateNewProject, this.azureFunctionsPath, this.functionLanguage, "~1", false /* openFolder */, templateName, "IoTHubTrigger1", { connection: "eventHubConnectionString", path: "%eventHubConnectionPath%", consumerGroup: "$Default" } ); } await this.updateConfigSettings(scaffoldType, { values: { functionLanguage: this.functionLanguage } }); } async provision(): Promise<boolean> { const subscriptionId = azureUtilityModule.AzureUtility.subscriptionId; if (!subscriptionId) { return false; } let resourceGroup = azureUtilityModule.AzureUtility.resourceGroup; if (!resourceGroup) { return false; } const functionAppId: string | undefined = await vscode.commands.executeCommand<string>( AzureFunctionsCommands.CreateFunctionApp, subscriptionId, resourceGroup ); if (!functionAppId) { throw new OperationFailedError("create function application", "Please check the error log in output window.", ""); } const scaffoldType = ScaffoldType.Workspace; const iotHubId = this.dependencies[0].id; const componentConfig = await this.azureConfigFileHandler.getComponentById(scaffoldType, iotHubId); if (!componentConfig) { throw new AzureConfigNotFoundError(`component of config id ${iotHubId}`); } if (!componentConfig.componentInfo) { throw new AzureConfigNotFoundError(`componentInfo of config id ${iotHubId}`); } const iotHubConnectionString = componentConfig.componentInfo.values.iotHubConnectionString; if (!iotHubConnectionString) { throw new AzureConfigNotFoundError(`iothubConnectionString of config id ${iotHubId}`); } const eventHubConnectionString = componentConfig.componentInfo.values.eventHubConnectionString; const eventHubConnectionPath = componentConfig.componentInfo.values.eventHubConnectionPath; if (!eventHubConnectionString) { throw new AzureConfigNotFoundError(`eventHubConnectionString of config id ${iotHubId}`); } if (!eventHubConnectionPath) { throw new AzureConfigNotFoundError(`evenHubConnectionPath of config id ${iotHubId}`); } const credential = await this.getCredentialFromSubscriptionId(subscriptionId); if (!credential) { throw new OperationFailedError("get credential from subscription id", "", ""); } const resourceGroupMatches = functionAppId.match(/\/resourceGroups\/([^\/]*)/); if (!resourceGroupMatches || resourceGroupMatches.length < 2) { throw new OperationFailedError(`parse resource group from function app ID ${functionAppId}`, "", ""); } resourceGroup = resourceGroupMatches[1]; const siteNameMatches = functionAppId.match(/\/sites\/([^\/]*)/); if (!siteNameMatches || siteNameMatches.length < 2) { throw new OperationFailedError(`parse function app name from function app ID ${functionAppId}`, "", ""); } const siteName = siteNameMatches[1]; const client = new WebSiteManagementClient(credential, subscriptionId); console.log(resourceGroup, siteName); const appSettings: StringDictionary = await client.webApps.listApplicationSettings(resourceGroup, siteName); console.log(appSettings); appSettings.properties = appSettings.properties || {}; // for c# library, use the default setting of ~2. if (this.functionLanguage !== (AzureFunctionsLanguage.CSharpLibrary as string)) { appSettings.properties["FUNCTIONS_EXTENSION_VERSION"] = "~1"; } else { appSettings.properties["FUNCTIONS_EXTENSION_VERSION"] = "~2"; } appSettings.properties["eventHubConnectionString"] = eventHubConnectionString || ""; appSettings.properties["eventHubConnectionPath"] = eventHubConnectionPath || ""; appSettings.properties["iotHubConnectionString"] = iotHubConnectionString || ""; // see detail: // https://github.com/Microsoft/vscode-iot-workbench/issues/436 appSettings.properties["WEBSITE_RUN_FROM_PACKAGE"] = "0"; await client.webApps.updateApplicationSettings(resourceGroup, siteName, appSettings); if (this.functionLanguage) { await this.updateConfigSettings(scaffoldType, { values: { functionLanguage: this.functionLanguage, functionAppId } }); } return true; } async deploy(): Promise<boolean> { let deployPending: NodeJS.Timer | null = null; if (this.channel) { utils.channelShowAndAppendLine(this.channel, "Deploying Azure Functions App..."); deployPending = setInterval(() => { this.channel.append("."); }, 1000); } try { const azureFunctionsPath = this.azureFunctionsPath; const componentConfig = await this.azureConfigFileHandler.getComponentById(ScaffoldType.Workspace, this.id); if (!componentConfig) { throw new AzureConfigNotFoundError(`component of config id ${this.id}`); } if (!componentConfig.componentInfo) { throw new AzureConfigNotFoundError(`componentInfo of config id ${this.id}`); } const functionAppId = componentConfig.componentInfo.values.functionAppId; if (this.functionLanguage !== (AzureFunctionsLanguage.CSharpLibrary as string)) { await vscode.commands.executeCommand(AzureFunctionsCommands.Deploy, azureFunctionsPath, functionAppId); } else { const subPath = path.join(azureFunctionsPath, "bin/Release/netcoreapp2.1/publish"); await vscode.commands.executeCommand(AzureFunctionsCommands.Deploy, subPath, functionAppId); } console.log(azureFunctionsPath, functionAppId); return true; } finally { if (this.channel && deployPending) { clearInterval(deployPending); utils.channelShowAndAppendLine(this.channel, "."); } } } async updateConfigSettings(type: ScaffoldType, componentInfo?: ComponentInfo): Promise<void> { const componentIndex = await this.azureConfigFileHandler.getComponentIndexById(type, this.id); if (componentIndex > -1) { if (!componentInfo) { throw new ArgumentEmptyOrNullError("update config settings of IoTHub", "component info"); } await this.azureConfigFileHandler.updateComponent(type, componentIndex, componentInfo); } else { const newAzureFunctionsConfig: AzureComponentConfig = { id: this.id, folder: this.functionFolder, name: "", dependencies: this.dependencies, type: this.componentType, componentInfo }; await this.azureConfigFileHandler.appendComponent(type, newAzureFunctionsConfig); } } }
the_stack
import { Tapable, MultiHook, SyncHook, SyncBailHook, SyncWaterfallHook, SyncLoopHook, AsyncParallelHook, AsyncParallelBailHook, AsyncSeriesHook, AsyncSeriesBailHook, AsyncSeriesWaterfallHook } from "tapable"; class DllPlugin { apply(compiler: Compiler) { compiler.plugin('doSomething', function (...args: string[]) { console.log(args); }); compiler.plugin(['doSomething', 'doNothing'], function (...args: string[]) { console.log(args); }); } } class Compiler extends Tapable { constructor() { super() } } const compiler = new Compiler(); let callback: Tapable.CallbackFunction = function () { }; compiler.apply(new DllPlugin()); compiler.applyPlugins('doSomething', 'a', 'b'); compiler.applyPlugins0('doSomething'); compiler.applyPlugins1('doSomething', 'a'); compiler.applyPlugins2('doSomething', 'a', 'b'); compiler.applyPluginsWaterfall('doSomething', 'a', 'b'); compiler.applyPluginsWaterfall0('doSomething', 'a'); compiler.applyPluginsBailResult('doSomething', 'a', 'b'); compiler.applyPluginsBailResult1('doSomething', ['a', 'b']); compiler.applyPluginsAsync('doSomething', 'a', 'b'); compiler.applyPluginsAsyncSeries('doSomething', 'a', 'b'); compiler.applyPluginsAsyncSeries1('doSomething', 'a', callback); compiler.applyPluginsAsyncSeriesBailResult('doSomething', 'a', 'b'); compiler.applyPluginsAsyncSeriesBailResult1('doSomething', 'a', callback); compiler.applyPluginsAsyncWaterfall('doSomething', 'a', callback); compiler.applyPluginsParallel('doSomething', 'a', 'b'); compiler.applyPluginsParallelBailResult('doSomething', 'a', 'b'); compiler.applyPluginsParallelBailResult1('doSomething', 'a', callback); const multi = new MultiHook([new SyncHook(['hi'])]); const isNumber = (val: number) => val; const isAny = (val: { a: { n: { y: '!' } } }) => val; const isUndefined = (val: undefined) => val; const isBoolean = (val: boolean) => val; // Without generics (() => { const hooks = { syncHook: new SyncHook(['arg1']), syncBailHook: new SyncBailHook(['arg1']), syncWaterfallHook: new SyncWaterfallHook(['arg1']), syncLoopHook: new SyncLoopHook(['arg1']), asyncParallelHook: new AsyncParallelHook(['arg1']), asyncParallelBailHook: new AsyncParallelBailHook(['arg1']), asyncSeriesHook: new AsyncSeriesHook(['arg1']), asyncSeriesBailHook: new AsyncSeriesBailHook(['arg1']), asyncSeriesWaterfallHook: new AsyncSeriesWaterfallHook(['arg1']), } // Without generics we won't get any information // for the tap interface: hooks.syncHook.tap('AHook', () => ('ReturnValue')); hooks.syncBailHook.tap('AHook', () => ('ReturnValue')); hooks.syncWaterfallHook.tap('AHook', () => ('ReturnValue')); hooks.asyncParallelHook.tapPromise('AHook', async () => ('ReturnValue')); hooks.asyncParallelBailHook.tapPromise('AHook', async () => ('ReturnValue')); hooks.asyncSeriesHook.tapPromise('AHook', async () => ('ReturnValue')); hooks.asyncSeriesBailHook.tapPromise('AHook', async () => ('ReturnValue')); hooks.asyncSeriesWaterfallHook.tapPromise('AHook', async () => ('ReturnValue')); async function getHookResults() { return { syncHook: hooks.syncHook.call({ name: 'sue', age: 34 }), syncBailHook: hooks.syncBailHook.call({ name: 'sue', age: 34 }), syncWaterfallHook: hooks.syncWaterfallHook.call({ name: 'sue', age: 34 }), syncLoopHook: hooks.syncLoopHook.call({ name: 'sue', age: 34 }), asyncParallelHook: await hooks.asyncParallelHook.promise({ name: 'sue', age: 34 }), asyncParallelBailHook: await hooks.asyncParallelBailHook.promise({ name: 'sue', age: 34 }), asyncSeriesHook: await hooks.asyncSeriesHook.promise({ name: 'sue', age: 34 }), asyncSeriesBailHook: await hooks.asyncSeriesBailHook.promise({ name: 'sue', age: 34 }), asyncSeriesWaterfallHook: await hooks.asyncSeriesWaterfallHook.promise({ name: 'sue', age: 34 }), } } getHookResults().then((result) => { // Always undefined: console.log(isUndefined(result.syncHook)); console.log(isUndefined(result.asyncSeriesHook)); console.log(isUndefined(result.asyncParallelHook)); // Possible undefined: console.log(isAny(result.syncBailHook!)); console.log(isAny(result.asyncParallelHook!)); console.log(isAny(result.syncBailHook!)); console.log(isAny(result.asyncParallelHook!)); console.log(isAny(result.asyncSeriesHook!)); console.log(isAny(result.asyncSeriesBailHook!)); // Always defined: console.log(isNumber(result.syncWaterfallHook.age)); console.log(isNumber(result.asyncSeriesWaterfallHook.age)); console.log(isBoolean(hooks.syncHook.isUsed())); console.log(isBoolean(hooks.asyncSeriesHook.isUsed())); console.log(isBoolean(hooks.asyncParallelHook.isUsed())); console.log(isBoolean(hooks.syncBailHook.isUsed())); console.log(isBoolean(hooks.asyncSeriesBailHook.isUsed())); console.log(isBoolean(hooks.syncWaterfallHook.isUsed())); console.log(isBoolean(hooks.asyncSeriesWaterfallHook.isUsed())); }); })(); // With generics (() => { type Person = { name: string, age: number }; const hooks = { syncHook: new SyncHook<Person, undefined, undefined>(['arg1']), syncBailHook: new SyncBailHook<Person, undefined, undefined, number>(['arg1']), syncWaterfallHook: new SyncWaterfallHook<Person, undefined, undefined>(['arg1']), syncLoopHook: new SyncLoopHook<Person, undefined, undefined>(['arg1']), asyncParallelHook: new AsyncParallelHook<Person, undefined, undefined>(['arg1']), asyncParallelBailHook: new AsyncParallelBailHook<Person, undefined, undefined, number>(['arg1']), asyncSeriesHook: new AsyncSeriesHook<Person, undefined, undefined>(['arg1']), asyncSeriesBailHook: new AsyncSeriesBailHook<Person, undefined, undefined, number>(['arg1']), asyncSeriesWaterfallHook: new AsyncSeriesWaterfallHook<Person, undefined, undefined>(['arg1']), } // Without generics we will get information hooks.syncHook.tap('AHook', () => ('Any Return Value')); hooks.syncBailHook.tap('AHook', (person) => person.age); hooks.syncWaterfallHook.tap('AHook', (person) => ({ name: 'sue', age: person.age + 1 })); hooks.asyncParallelHook.tapPromise('AHook', async () => ('ReturnValue')); hooks.asyncParallelBailHook.tapPromise('AHook', async (person) => person.age); hooks.asyncSeriesHook.tapPromise('AHook', async () => ('ReturnValue')); hooks.asyncSeriesBailHook.tapPromise('AHook', async (person) => person.age); hooks.asyncSeriesWaterfallHook.tapPromise('AHook', async (person) => ({ name: 'sue', age: person.age + 1 })); async function getHookResults() { return { syncHook: hooks.syncHook.call({ name: 'sue', age: 34 }), syncBailHook: hooks.syncBailHook.call({ name: 'sue', age: 34 }), syncWaterfallHook: hooks.syncWaterfallHook.call({ name: 'sue', age: 34 }), syncLoopHook: hooks.syncLoopHook.call({ name: 'sue', age: 34 }), asyncParallelHook: await hooks.asyncParallelHook.promise({ name: 'sue', age: 34 }), asyncParallelBailHook: await hooks.asyncParallelBailHook.promise({ name: 'sue', age: 34 }), asyncSeriesHook: await hooks.asyncSeriesHook.promise({ name: 'sue', age: 34 }), asyncSeriesBailHook: await hooks.asyncSeriesBailHook.promise({ name: 'sue', age: 34 }), asyncSeriesWaterfallHook: await hooks.asyncSeriesWaterfallHook.promise({ name: 'sue', age: 34 }), } } getHookResults().then((result) => { // Allways undefined: console.log(isUndefined(result.syncHook)); console.log(isUndefined(result.asyncSeriesHook)); console.log(isUndefined(result.asyncParallelHook)); // Possible undefined: console.log(isNumber(result.syncBailHook!)); console.log(isNumber(result.asyncParallelHook!)); console.log(isNumber(result.syncBailHook!)); console.log(isNumber(result.asyncParallelHook!)); console.log(isNumber(result.asyncSeriesHook!)); console.log(isNumber(result.asyncSeriesBailHook!)); // Allways defined: console.log(isNumber(result.syncWaterfallHook.age)); console.log(isNumber(result.asyncSeriesWaterfallHook.age)); console.log(isBoolean(hooks.syncHook.isUsed())); console.log(isBoolean(hooks.asyncSeriesHook.isUsed())); console.log(isBoolean(hooks.asyncParallelHook.isUsed())); console.log(isBoolean(hooks.syncBailHook.isUsed())); console.log(isBoolean(hooks.asyncSeriesBailHook.isUsed())); console.log(isBoolean(hooks.syncWaterfallHook.isUsed())); console.log(isBoolean(hooks.asyncSeriesWaterfallHook.isUsed())); }); // Test TapOptions // Minimal params hooks.syncHook.tap({ name: 'Hook1', }, () => ('Any Return Value')); // All param types hooks.syncHook.tap({ name: 'Hook2', type: 'sync', before: 'Hook1', context: true, stage: 10, }, () => ('Any Return Value')); hooks.syncHook.tap({ name: 'Hook3', before: ['Hook1', 'Hook2'], }, () => ('Any Return Value')); // No optional params hooks.syncHook.tap({ name: 'Hook4', }, () => ('Any Return Value')); // The `fn` param hooks.syncWaterfallHook.tap({ name: 'SyncHook', fn: (person) => ({ name: 'sue', age: person.age + 1 }), }, (person) => ({ name: 'sue', age: person.age + 1 })); hooks.asyncSeriesWaterfallHook.tapPromise({ name: 'PromiseHook', type: 'promise', fn: async (person) => ({ name: 'sue', age: person.age + 1 }), }, async (person) => ({ name: 'sue', age: person.age + 1 })); })();
the_stack
import { mat4, vec3, vec4 } from 'gl-matrix'; import { m4 } from './gl-matrix-extensions'; import { log, LogLevel, assert, upperPowerOfTwo } from './auxiliaries'; import { Camera } from './camera'; import { GLsizei2, GLsizei4 } from './tuples'; /** * Support Class that wraps the calculation of camera tiling and iteration with various algorithms * by giving access to an adjusted camera which NDC-Coordinates match the current tile index. * Iteration can be done manually (variant: 1) or automatically (variant: 2). * It is intended to be used like: * * tileCameraGenerator = new TileCameraGenerator(); * tileCameraGenerator.sourceCamera = camera; * tileCameraGenerator.sourceViewport = canvasSize; * tileCameraGenerator.tileSize = [128, 128]; * tileCameraGenerator.algorithm = TileCameraGenerator.Algorithm.ScanLine; * let offset: [number, number]; * * iteration variant 1: * for (let i = 0; i < tileCameraGenerator.numberOfTiles(); ++i){ * tileCameraGenerator.tile = i; // property * tileCameraGenerator.update(); * offset = tileCameraGenerator.offset; * "render camera" * } * * iteration variant 2: * while(tileCameraGenerator.nextTile()){ * offset = tileCameraGenerator.offset; * "render" * } * // reset generator * tileCameraGenerator.reset(); * * NOTE: Use `sourceCameraChanged` if the source camera is altered. */ export class TileCameraGenerator { /** @see {@link sourceCamera} */ protected _sourceCamera: Camera | undefined; /** @see {@link sourceViewport} */ protected _sourceViewport: GLsizei2 | undefined; /** @see {@link tileSize} */ protected _tileSize: GLsizei2 = [0, 0]; /** @see {@link padding} */ protected _padding: vec4 = vec4.fromValues(0, 0, 0, 0); /** @see {@link tile} */ protected _tile = -1; /** @see {@link eye} */ protected _camera: Camera | undefined; /** @see {@link algorithm} */ protected _algorithm = TileCameraGenerator.Algorithm.ScanLine; protected _valid: boolean; protected _offset: GLsizei2 = [0, 0]; protected _indices: Uint16Array; /** * Recursively fills the interleaved indices using the Hilbert Curve. This method is not intended to be used * directly. Use generateHilbertIndices {@link generateHilbertIndices} instead. */ protected static hilbertIndices(indices: Uint16Array, numX: number, numY: number, x: number, y: number, xi: number, xj: number, yi: number, yj: number, depth: number, hilbertIndex: number): number { if (depth > 0) { hilbertIndex = this.hilbertIndices(indices, numX, numY, x, y, yi / 2, yj / 2, xi / 2, xj / 2, depth - 1, hilbertIndex); hilbertIndex = this.hilbertIndices(indices, numX, numY, x + xi / 2, y + xj / 2, xi / 2, xj / 2, yi / 2, yj / 2, depth - 1, hilbertIndex); hilbertIndex = this.hilbertIndices(indices, numX, numY, x + xi / 2 + yi / 2, y + xj / 2 + yj / 2, xi / 2, xj / 2, yi / 2, yj / 2, depth - 1, hilbertIndex); hilbertIndex = this.hilbertIndices(indices, numX, numY, x + xi / 2 + yi, y + xj / 2 + yj, -yi / 2, -yj / 2, -xi / 2, -xj / 2, depth - 1, hilbertIndex); return hilbertIndex; } x = x + (xi + yi - 1) / 2; y = y + (xj + yj - 1) / 2; if (x < numX && y < numY) { const i = hilbertIndex * 2; indices[i + 0] = x; indices[i + 1] = y; ++hilbertIndex; } return hilbertIndex; } /** * Fills the iterationAlgorithmIndices with the table indices * from the HilbertCurve-Iteration-Algorithm. */ static generateHilbertIndices(indices: Uint16Array, numX: number, numY: number): void { assert(indices.length === 2 * numX * numY, `expected interleaved indices-array of length ${2 * numX * numY}, given ${indices.length}`); const tableSize = Math.max(numX, numY); const recursionDepth = Math.ceil(Math.log2(tableSize)); const uPow2 = upperPowerOfTwo(tableSize); this.hilbertIndices(indices, numX, numY, 0, 0, uPow2, 0, 0, uPow2, recursionDepth, 0); } /** * Generates interleaved table indices using the ZCurve-Iteration-Algorithm. */ static generateScanLineIndices(indices: Uint16Array, numX: number, numY: number): void { assert(indices.length === 2 * numX * numY, `expected interleaved indices-array of length ${2 * numX * numY}, given ${indices.length}`); for (let y = 0; y < numY; ++y) { for (let x = 0; x < numX; ++x) { const i = (x + y * numX) * 2; indices[i + 0] = x; indices[i + 1] = y; } } } /** * Fills the sequence/array of indices with the table indices from the ZCurve-Iteration-Algorithm. */ static generateZCurveIndices(indices: Uint16Array, numX: number, numY: number): void { assert(indices.length === 2 * numX * numY, `expected interleaved indices-array of length ${2 * numX * numY}, given ${indices.length}`); const tableSize = Math.max(numX, numY); const maxZIndexBitLength = Math.floor(Math.log2(tableSize)) * 2; // iterate over the z-curve until all indices in the tile-range are collected let zIndex = 0; for (let numberOfFoundIndices = 0; numberOfFoundIndices < numX * numY; ++zIndex) { let x = 0; let y = 0; // Bit-Magic that maps the index to table indices (see Definition of Z-Curve for further information) for (let currentBit = 0; currentBit < maxZIndexBitLength; ++currentBit) { const xBit = zIndex >> (currentBit * 2) & 1; x += xBit << currentBit; const yBit = zIndex >> (currentBit * 2 + 1) & 1; y += yBit << currentBit; } // Only add table indices that are within the tile-range. if (x < numX && y < numY) { const i = numberOfFoundIndices * 2; indices[i + 0] = x; indices[i + 1] = y; ++numberOfFoundIndices; } } } protected invalidate(clearIndices: boolean): void { if (clearIndices) { this._indices = new Uint16Array(0); } this._valid = false; } /** * Ensures that the indices are available. If not, indices using the algorithm set will be generated. */ protected ensureValidIterationIndices(): void { if (this._indices.length > 0) { return; } this._indices = new Uint16Array(this.numTiles * 2); switch (this._algorithm) { case TileCameraGenerator.Algorithm.ScanLine: TileCameraGenerator.generateScanLineIndices( this._indices, this.numXTiles, this.numYTiles); break; case TileCameraGenerator.Algorithm.HilbertCurve: TileCameraGenerator.generateHilbertIndices( this._indices, this.numXTiles, this.numYTiles); break; case TileCameraGenerator.Algorithm.ZCurve: TileCameraGenerator.generateZCurveIndices( this._indices, this.numXTiles, this.numYTiles); break; default: TileCameraGenerator.generateScanLineIndices( this._indices, this.numXTiles, this.numYTiles); } } /** * Converts the tile index from the selected Algorithm to table indices. * @returns - The converted tile index. */ protected tableIndices(): GLsizei2 { this.ensureValidIterationIndices(); const i = this.tile * 2; return [this._indices[i + 0], this._indices[i + 1]]; } /** * Returns the padded tileSize. * @returns - The padded tileSize. */ protected getPaddedTileSize(): [number, number] { return [this.padding[1] + this.padding[3] + this.tileSize[0], this.padding[0] + this.padding[2] + this.tileSize[1]]; } /** * Used for Iterator behavior. It sets the tile to 0 (first tile) if the value of tile is negative * and therefore initiates the iteration. * Otherwise it increments the tile and calls update to directly change the camera. * If the tile index would get out of range it returns false to indicate, that all tiles were rendered. * @returns - If the camera has been set to a next tile. */ public nextTile(): boolean { if (this.tile >= this.numTiles - 1) { return false; } if (this.tile < 0) { this.tile = -1; } ++this.tile; this.update(); return true; } /** * Returns if tiles still need to be rendered. */ public hasNextTile(): boolean { return this.tile <= this.numTiles - 1 && this.tile >= 0; } /** * Resets the tile index to prepare the generator for the next rendering. * Should be called after iteration with nextTile(). */ public reset(): void { this.tile = -1; this._offset[0] = 0; this._offset[1] = 0; } /** * Reassigns all values from the source camera to the tile camera, e.g., when the source camera is altered. */ public sourceCameraChanged(): void { assert(this._sourceCamera !== undefined, `expected the unput/source camera to be defined`); this._camera = Object.create(this._sourceCamera!) as Camera; } /** * Updates the camera view frustum to current tile based on * the sourceViewport, tileSize and the padding. * If the tile is less than zero, the camera is set to the first tile. * If the tile is too high, the camera is not updated and remains in the last valid state. * @returns - the offset of the new camera tile. */ public update(): GLsizei2 { // do nothing and return the last offset if no property has changed. if (this._valid) { return this._offset; } // If an invalid index is requested: Do not change the camera and return the last valid tile offset. if (this.numTiles <= this.tile || 0 > this.tile) { log(LogLevel.Warning, `index ${this.tile} is out of bounds ${this.numTiles}, returning first tile`); return this._offset; } assert(this._sourceViewport !== undefined && this._sourceCamera !== undefined, `expected source camera and source viewport to be defined before updating`); this._valid = true; const tableIndices = this.tableIndices(); const viewport = this.sourceViewport!; const paddedTileSize = this.getPaddedTileSize(); // Calculate the padded tile center coordinates in the viewport-space. const paddedTileCenter = [0, 0]; paddedTileCenter[0] = tableIndices[0] * this.tileSize[0] + paddedTileSize[0] / 2; paddedTileCenter[1] = tableIndices[1] * this.tileSize[1] + paddedTileSize[1] / 2; // Calculate the offset which is needed for the return. const offset: [number, number] = [0, 0]; offset[0] = tableIndices[0] * this.tileSize[0]; offset[1] = tableIndices[1] * this.tileSize[1]; // Scale down the padded tile center coordinates to padded tile center NDC coordinates. const paddedTileCenterNDC = [paddedTileCenter[0] * 2 / viewport[0] - 1 , paddedTileCenter[1] * 2 / viewport[1] - 1]; // Create the scale vector that scales up the padded tile to the NDC-range of -1;1. const scaleVec = vec3.fromValues(viewport[0] / paddedTileSize[0], viewport[1] / paddedTileSize[1], 1); // Create the translation vector which shifts the padded tile center NDC into the origin. const translationVec = vec3.fromValues(-paddedTileCenterNDC[0], -paddedTileCenterNDC[1], 0); // Combine the translation ans scale into the matrix. const tileNDCCorrectionMatrix = mat4.scale(m4(), mat4.identity(m4()), scaleVec); const translateMatrix = mat4.translate(m4(), tileNDCCorrectionMatrix, translationVec); // Set the postViewProjection matrix and offset to the new calculated values. this._camera!.postViewProjection = translateMatrix; this._offset = offset; return offset; } get valid(): boolean { return this._camera !== undefined && this._sourceCamera !== undefined && this._valid } /** * Returns the number of tiles along the x-axis based on the number of tiles that fit inside the horizontal extent * of the source camera's viewport. * @returns - The number of tiles along the x-axis. */ get numXTiles(): number { assert(this._sourceViewport !== undefined, `expected the source viewport to be defined`); return Math.ceil(this.sourceViewport![0] / this.tileSize[0]); } /** * Returns the number of tiles along the y-axis based on the number of tiles that fit inside the vertical extent * of the source camera's viewport. * @returns - The number of tiles along the y-axis. */ get numYTiles(): number { assert(this._sourceViewport !== undefined, `expected the source viewport to be defined`); return Math.ceil(this.sourceViewport![1] / this.tileSize[1]); } /** * Returns the total number of tiles * based on the how many of tileSize fit inside the sourceViewport. * @returns - The total number of tiles. */ get numTiles(): number { return this.numXTiles * this.numYTiles; } /** * Returns the offset of the current tile. The padding is not included in the offset. * @returns - Current tile offset. */ get offset(): GLsizei2 { return this._offset; } /** * Read-only access to the tiled camera that has the viewport of the current tile of the input/source camera. * @returns - The reference to the tile viewing camera. */ get camera(): Camera | undefined { return this._camera; } /** * Creates a 4-tuple with x0, y0, and width and height of the viewport for the current tile and camera. * @returns - 4-tuple with [x0, y0, width, height] based on the current tile. */ get viewport(): GLsizei4 { return [this.offset[0], this.offset[1], this.tileSize[0], this.tileSize[1]]; } /** * Returns the sourceCamera which viewport should be divided in tiles. * If the sourceCamera has not been set, it returns a default camera. * @returns - The sourceCamera which viewport should be divided in tiles. */ get sourceCamera(): Camera | undefined { return this._sourceCamera; } /** * Assigns the input camera whose viewport will be divided in tiles. Additionally it creates a deep copy of the * input camera which is used as the tiled camera {@link camera}. * @param camera - The input camera whose viewport will be divided in tiles. */ set sourceCamera(camera: Camera | undefined) { if (camera === undefined) { this._sourceCamera = this._camera = undefined; return; } this._sourceCamera = camera; this._camera = Object.create(camera) as Camera; this.invalidate(false); } /** * Returns the current tile index. * @returns - The current tile index. */ get tile(): number { return this._tile; } /** * Sets the current tile index. * @param index - The new index. */ set tile(index: GLsizei) { if (this._tile === index) { return; } this._tile = index; this.invalidate(false); } /** * Returns the size of the original viewport * which should be divided in tiles based on the tile size. * If the viewport has not been set, it returns [-1, -1]. * @returns - Size of the Viewport. */ get sourceViewport(): GLsizei2 | undefined { return this._sourceViewport; } /** * Sets the size of the viewport from the sourceCamera. * It checks if the sourceViewport is compatible with the selected algorithm * and eventually adjusts the tileSize to match the conditions of the algorithm. */ set sourceViewport(viewport: GLsizei2 | undefined) { if (this._sourceViewport !== undefined && viewport !== undefined && this._sourceViewport[0] === viewport[0] && this._sourceViewport[1] === viewport[1]) { return; } this._sourceViewport = viewport; this.invalidate(true); } /** * Returns the tileSize. * @returns - [-1, -1] as invalid. */ get tileSize(): GLsizei2 { return this._tileSize; } /** * Sets the tileSize. The tileSize eventually changes to match the selected algorithms constraints. */ set tileSize(tileSize: GLsizei2) { if (this._tileSize[0] === tileSize[0] && this._tileSize[1] === tileSize[1]) { return; } this._tileSize = tileSize; this.invalidate(true); } /** * Returns the padding per tile in CSS order: top, right, bottom, left. The standard is (0, 0, 0, 0). */ get padding(): vec4 { return this._padding; } /** * Stets the padding per tile in CSS order: top, right, bottom, left. The standard is (0, 0, 0, 0). */ set padding(padding: vec4) { if (vec4.equals(this._padding, padding)) { return; } this._padding = vec4.clone(padding); this.invalidate(false); } /** * Returns the selected IterationAlgorithm which determines the sequence in which the tiles are rendered. */ get algorithm(): TileCameraGenerator.Algorithm { return this._algorithm; } /** * Sets the selected IterationAlgorithm which determines the order in which the tiles are rendered. The default is * `ScanLine`. If needed, it automatically adjusts the tileSize to match the new algorithm. */ set algorithm(algorithm: TileCameraGenerator.Algorithm) { if (this._algorithm === algorithm) { return; } this._algorithm = algorithm; this.invalidate(true); } } /** * The enum that is used to select one of the different algorithm. */ export namespace TileCameraGenerator { export enum Algorithm { /** * ScanLine conditions: none. */ ScanLine = 'scanline', /** * HilbertCurve conditions: Both numberOfXTiles, numberOfYTiles need to be equal and need to be a power of two. * In the case that the condition is not satisfied the next higher number than numberOfTilesX/Y that is power * of two is calculated. The Iteration will be calculated with this number and tiles that lay outside the * viewport are skipped. */ HilbertCurve = 'hilbertcurve', /** * ZCurve conditions: Both numberOfXTiles, numberOfYTiles need to be equal and need to be a power of two. In * the case that the condition is not satisfied the next higher number than numberOfTilesX/Y that is power of * two is calculated. The Iteration will be calculated with this number and tiles that lay outside the * viewport are skipped. */ ZCurve = 'zcurve', } }
the_stack
import * as vscode from 'vscode'; import { COBOLToken, COBOLTokenStyle } from './cobolsourcescanner'; import { VSCOBOLConfiguration } from './vsconfiguration'; import { VSLogger } from './extension'; import { outlineFlag } from './iconfiguration'; import VSCOBOLSourceScanner from './vscobolscanner'; import { VSPreProc } from './vspreproc'; class SimpleStack<T> { _store: T[] = []; push(val: T) { this._store.push(val); } pop(): T | undefined { return this._store.pop(); } peek(): T | undefined { return this._store[this.size() - 1]; } size(): number { return this._store.length; } } class COBOLDocumentSymbols { protected symbols: vscode.DocumentSymbol[]; constructor(symbols: vscode.DocumentSymbol[]) { this.symbols = symbols; } protected newDocumentSymbol(token: COBOLToken, symKind: vscode.SymbolKind, topLevel: boolean): vscode.DocumentSymbol { const srange = new vscode.Range(new vscode.Position(token.startLine, token.startColumn), new vscode.Position(token.endLine, token.endColumn)); // const sym = new vscode.DocumentSymbol(token.tokenName, token.description, symKind, srange, srange); const sym = new vscode.DocumentSymbol(token.description, "", symKind, srange, srange); if (topLevel) { this.symbols.push(sym); } return sym; } } class ProgramSymbols extends COBOLDocumentSymbols { private symCount = 0; private divCount = 0; private currentDivisionSymbols: vscode.DocumentSymbol[] | undefined; private currentDivisionSymbol: vscode.DocumentSymbol | undefined; private currentSectionSymbols: vscode.DocumentSymbol[] | undefined; constructor(symbols: vscode.DocumentSymbol[], topLevelToken: COBOLToken) { super(symbols); const topLevelSymbol = this.addDivision(topLevelToken); this.currentDivisionSymbols = topLevelSymbol.children; } public addDivision(token: COBOLToken): vscode.DocumentSymbol { const currentDivisionSymbol = super.newDocumentSymbol(token, this.divCount === 0 ? vscode.SymbolKind.Class : vscode.SymbolKind.Method, this.divCount === 0); if (this.divCount !== 0) { this.currentDivisionSymbols?.push(currentDivisionSymbol); } this.divCount++; this.symCount++; this.currentSectionSymbols = undefined; this.currentDivisionSymbol = currentDivisionSymbol; return currentDivisionSymbol; } public addSection(token: COBOLToken) { this.divCount++; this.symCount++; const sym = super.newDocumentSymbol(token, vscode.SymbolKind.Method, false); this.currentDivisionSymbol?.children.push(sym); this.currentSectionSymbols = sym.children; } public addParagraph(token: COBOLToken) { this.symCount++; const sym = super.newDocumentSymbol(token, vscode.SymbolKind.Method, false); if (this.currentSectionSymbols !== undefined) { this.currentSectionSymbols.push(sym); } else { this.currentDivisionSymbols?.push(sym); } } private previousSectionSymbols: vscode.DocumentSymbol[] | undefined; private previousDivisionSymbol: vscode.DocumentSymbol | undefined; private previousDivisionSymbols: vscode.DocumentSymbol[] | undefined; // eslint-disable-next-line @typescript-eslint/no-unused-vars public endDeclarativesSection(token: COBOLToken) { if (this.previousDivisionSymbol !== undefined) { this.currentSectionSymbols = this.previousSectionSymbols; this.currentDivisionSymbol = this.previousDivisionSymbol; this.currentDivisionSymbols = this.previousDivisionSymbols; this.previousDivisionSymbol = undefined; } } public addDeclarativesSection(token: COBOLToken) { this.previousSectionSymbols = this.currentSectionSymbols; this.previousDivisionSymbol = this.currentDivisionSymbol; this.previousDivisionSymbols = this.currentDivisionSymbols; const sym = super.newDocumentSymbol(token, vscode.SymbolKind.Method, false); this.currentDivisionSymbol?.children.push(sym); this.currentDivisionSymbol = sym; } public addProgramId(token: COBOLToken) { const sym = super.newDocumentSymbol(token, vscode.SymbolKind.Class, false); this.currentDivisionSymbols?.push(sym); } private addRawVariable(token: COBOLToken, symbol: vscode.DocumentSymbol): void { if (this.currentGroup !== undefined && token.extraInformation1.substr(0, 2) !== '01') { VSLogger.logMessage(` addRawVariable: ${this.currentGroup?.name} -> ${token.tokenName} -> ${token.extraInformation1}`); this.currentGroup?.children.push(symbol); return; } if (this.currentSectionSymbols !== undefined) { VSLogger.logMessage(` addRawVariable: section -> ${token.tokenName} -> ${token.extraInformation1}`); this.currentSectionSymbols.push(symbol); } else { VSLogger.logMessage(` addRawVariable: division -> ${token.tokenName} -> ${token.extraInformation1}`); this.currentDivisionSymbols?.push(symbol); } } private addGroup(firstTwo: number, token: COBOLToken, addSymbol: vscode.DocumentSymbol): void { if (this.currentGroupLevel === 0) { this.addRawVariable(token, addSymbol); this.currentGroup = addSymbol; this.currentGroupLevel = firstTwo; return; } if (firstTwo > this.currentGroupLevel) { VSLogger.logMessage(`Addgroup: push level, save: ${this.currentGroup?.name}@${this.currentGroupLevel}`); this.currentGroups.push(this.currentGroup); this.currentGroupsLevels.push(this.currentGroupLevel) this.currentGroup?.children.push(addSymbol); this.currentGroup = addSymbol; this.currentGroupLevel = firstTwo; VSLogger.logMessage(`Addgroup: push level, new: ${this.currentGroup?.name}@${this.currentGroupLevel}\n`); return; } if(firstTwo < this.currentGroupLevel) { VSLogger.logMessage(`Addgroup: pop level (top), ${this.currentGroup?.name}@${this.currentGroupLevel}`); const possibleCurrentGroup = this.currentGroups.pop(); if (possibleCurrentGroup !== undefined) { this.currentGroup = possibleCurrentGroup; } const possibleGroupLevel = this.currentGroupsLevels.pop(); if (possibleGroupLevel !== undefined) { this.currentGroupLevel = possibleGroupLevel; } this.currentGroup?.children.push(addSymbol); VSLogger.logMessage(`Addgroup: pop level (bot), ${this.currentGroup?.name}@${this.currentGroupLevel}\n`); return; } if (firstTwo === this.currentGroupLevel) { VSLogger.logMessage(`Addgroup: same level, ${this.currentGroup?.name}@${this.currentGroupLevel}`); const parent = this.currentGroups.peek(); if (parent !== undefined) { VSLogger.logMessage(` Addgroup: parent name, ${parent.name}`); parent.children.push(addSymbol); VSLogger.logMessage(`\n`); // VSLogger.logMessage(`Addgroup: same level, ${this.currentGroup.name}@${this.currentGroupLevel}\n`); } return; } VSLogger.logMessage(`Addgroup: FAIL: ${firstTwo} -> ${token.tokenName} -> ${token.extraInformation1}`); // this.addRawVariable(token, addSymbol); // this.currentGroupLevel = firstTwo; // VSLogger.logMessage(`Addgroup: end: ${firstTwo} -> ${token.tokenName} -> ${token.extraInformation1}\n`); } private currentGroup: vscode.DocumentSymbol | undefined = undefined; // TODO: - need stack to handle nested groups, pop level when is <= current level private currentGroupLevel = 0; private currentGroups = new SimpleStack<vscode.DocumentSymbol | undefined>(); private currentGroupsLevels = new SimpleStack<number>(); public addVariable(token: COBOLToken) { // // drop fillers if (token.tokenNameLower === "filler") { return; } if (token.extraInformation1 === 'fd' || token.extraInformation1 === 'sd' || token.extraInformation1 === 'rd' || token.extraInformation1 === 'select') { const sym = super.newDocumentSymbol(token, vscode.SymbolKind.File, false); this.addRawVariable(token, sym); return; } let addSymbol: vscode.DocumentSymbol; const firstTwo = Number(token.extraInformation1.substr(0, 2).replace(/^0+/, '')); if (firstTwo === 1 || firstTwo === 77 || firstTwo === 88 || firstTwo === 66) { this.currentGroup = undefined; } if (token.extraInformation1.endsWith("-GROUP")) { addSymbol = super.newDocumentSymbol(token, vscode.SymbolKind.Struct, false); } else if (token.extraInformation1.endsWith("88")) { this.currentGroup = undefined; addSymbol = super.newDocumentSymbol(token, vscode.SymbolKind.EnumMember, false); } else if (token.extraInformation1.endsWith("-OCCURS")) { addSymbol = super.newDocumentSymbol(token, vscode.SymbolKind.Array, false); } else { addSymbol = super.newDocumentSymbol(token, vscode.SymbolKind.Field, false); } VSLogger.logMessage(`${firstTwo} -> ${token.tokenName} -> ${token.extraInformation1}`); if (token.extraInformation1.indexOf("GROUP") !== -1) { this.addGroup(firstTwo, token, addSymbol); } // else { // this.addRawVariable(token, addSymbol); // } } } export class CobolDocumentSymbolProvider implements vscode.DocumentSymbolProvider { private getDocumentSymbol(token: COBOLToken, symKind: vscode.SymbolKind): vscode.DocumentSymbol { const srange = new vscode.Range(new vscode.Position(token.startLine, token.startColumn), new vscode.Position(token.endLine, token.endColumn)); return new vscode.DocumentSymbol(token.tokenName, token.description, symKind, srange, srange); } // eslint-disable-next-line @typescript-eslint/no-unused-vars public async provideDocumentSymbols(document: vscode.TextDocument, canceltoken: vscode.CancellationToken): Promise<vscode.DocumentSymbol[]> { const topLevelSymbols: vscode.DocumentSymbol[] = []; const settings = VSCOBOLConfiguration.get(); const outlineLevel = settings.outline; if (outlineLevel === outlineFlag.Off) { return topLevelSymbols; } if (await VSPreProc.areAllPreProcessorsReady(settings) === false) { return topLevelSymbols; } const sf = VSCOBOLSourceScanner.getCachedObject(document, settings); if (sf === undefined) { return topLevelSymbols; } let includePara = true; let includeVars = true; let includeSections = true; if (outlineLevel === outlineFlag.Partial) { includePara = false; } if (outlineLevel === outlineFlag.Skeleton) { includeVars = false; includeSections = false; includePara = false; } const symbols: vscode.DocumentSymbol[] = topLevelSymbols; // let currentLevel: vscode.DocumentSymbol[] = symbols; let currentProgram: ProgramSymbols | undefined = undefined; for (const token of sf.tokensInOrder) { try { if (token.ignoreInOutlineView === false) { switch (token.tokenType) { case COBOLTokenStyle.ClassId: case COBOLTokenStyle.ProgramId: if (currentProgram === undefined) { currentProgram = new ProgramSymbols(symbols, token); } else { currentProgram.addProgramId(token); } break; // case COBOLTokenStyle.EnumId: { // const idSym = this.getDocumentSymbol(token, vscode.SymbolKind.Enum); // symbols.push(idSym); // currentLevel = idSym.children; // } // break; // case COBOLTokenStyle.InterfaceId: { // const idSym = this.getDocumentSymbol(token, vscode.SymbolKind.Interface); // symbols.push(idSym); // currentLevel = idSym.children; // } // break; // case COBOLTokenStyle.ValueTypeId: { // const idSym = this.getDocumentSymbol(token, vscode.SymbolKind.Struct); // symbols.push(idSym); // currentLevel = idSym.children; // } // break; // case COBOLTokenStyle.CopyBook: // case COBOLTokenStyle.CopyBookInOrOf: // case COBOLTokenStyle.File: { // const idSym = this.getDocumentSymbol(token, vscode.SymbolKind.File); // currentLevel.push(idSym); // } // break; case COBOLTokenStyle.Declaratives: if (currentProgram !== undefined) { currentProgram.addDeclarativesSection(token); } break; case COBOLTokenStyle.EndDeclaratives: if (currentProgram !== undefined) { currentProgram.endDeclarativesSection(token); } break; case COBOLTokenStyle.Division: if (currentProgram === undefined) { currentProgram = new ProgramSymbols(symbols, token); } else { currentProgram.addDivision(token); } break; case COBOLTokenStyle.Paragraph: if (includePara && currentProgram !== undefined) { currentProgram.addParagraph(token); } break; case COBOLTokenStyle.Section: if (includeSections && currentProgram !== undefined) { currentProgram.addSection(token); } break; // case COBOLTokenStyle.EntryPoint: // case COBOLTokenStyle.FunctionId: // currentLevel.push(this.getDocumentSymbol(token, vscode.SymbolKind.Function)); // break; case COBOLTokenStyle.Variable: if (includeVars && currentProgram !== undefined) { currentProgram.addVariable(token); } // case COBOLTokenStyle.ConditionName: // if (includeVars === false) { // break; // } // currentLevel.push(this.getDocumentSymbol(token, vscode.SymbolKind.TypeParameter)); // break // case COBOLTokenStyle.Union: // if (includeVars === false) { // break; // } // currentLevel.push(this.getDocumentSymbol(token, vscode.SymbolKind.Struct)); // break; // case COBOLTokenStyle.Constant: // if (includeVars === false) { // break; // } // currentLevel.push(this.getDocumentSymbol(token, vscode.SymbolKind.Constant)); // break; // case COBOLTokenStyle.MethodId: // currentLevel.push(this.getDocumentSymbol(token, vscode.SymbolKind.Method)); // break; // case COBOLTokenStyle.Property: // currentLevel.push(this.getDocumentSymbol(token, vscode.SymbolKind.Property)); // break; // case COBOLTokenStyle.Constructor: // currentLevel.push(this.getDocumentSymbol(token, vscode.SymbolKind.Constructor)); // break; } } } catch (e) { VSLogger.logException("Failed " + e + " on " + JSON.stringify(token), e as Error); } } return topLevelSymbols; } }
the_stack
import { expect, use } from "chai"; import * as calculateKeySlot from "cluster-key-slot"; import { default as Cluster } from "../../../lib/cluster"; import MockServer from "../../helpers/mock_server"; use(require("chai-as-promised")); /* In this suite, foo1 and foo5 are usually served by the same node in a 3-nodes cluster. Instead foo1 and foo2 are usually served by different nodes in a 3-nodes cluster. */ describe("autoPipelining for cluster", function () { function changeSlot(cluster, from, to) { cluster.slots[from] = cluster.slots[to]; cluster._groupsBySlot[from] = cluster._groupsBySlot[to]; } beforeEach(() => { const slotTable = [ [0, 5000, ["127.0.0.1", 30001]], [5001, 9999, ["127.0.0.1", 30002]], [10000, 16383, ["127.0.0.1", 30003]], ]; new MockServer(30001, function (argv) { if (argv[0] === "cluster" && argv[1] === "slots") { return slotTable; } if (argv[0] === "get" && argv[1] === "foo2") { return "bar2"; } if (argv[0] === "get" && argv[1] === "foo6") { return "bar6"; } if (argv[0] === "get" && argv[1] === "baz:foo10") { return "bar10"; } }); new MockServer(30002, function (argv) { if (argv[0] === "cluster" && argv[1] === "slots") { return slotTable; } if (argv[0] === "get" && argv[1] === "foo3") { return "bar3"; } if (argv[0] === "get" && argv[1] === "foo4") { return "bar4"; } }); new MockServer(30003, function (argv) { if (argv[0] === "cluster" && argv[1] === "slots") { return slotTable; } if (argv[0] === "set" && !argv[2]) { return new Error("ERR wrong number of arguments for 'set' command"); } if (argv[0] === "get" && argv[1] === "foo1") { return "bar1"; } if (argv[0] === "get" && argv[1] === "foo5") { return "bar5"; } if (argv[0] === "get" && argv[1] === "baz:foo1") { return "bar1"; } if (argv[0] === "evalsha") { return argv.slice(argv.length - 4); } }); }); const hosts = [ { host: "127.0.0.1", port: 30001, }, { host: "127.0.0.1", port: 30002, }, { host: "127.0.0.1", port: 30003, }, ]; it("should automatic add commands to auto pipelines", async () => { const cluster = new Cluster(hosts, { enableAutoPipelining: true }); await new Promise((resolve) => cluster.once("connect", resolve)); await cluster.set("foo1", "bar1"); expect(cluster.autoPipelineQueueSize).to.eql(0); const promise = cluster.get("foo1"); expect(cluster.autoPipelineQueueSize).to.eql(1); const res = await promise; expect(res).to.eql("bar1"); expect(cluster.autoPipelineQueueSize).to.eql(0); cluster.disconnect(); }); it("should not add non-compatible commands to auto pipelines", async () => { const cluster = new Cluster(hosts, { enableAutoPipelining: true }); await new Promise((resolve) => cluster.once("connect", resolve)); expect(cluster.autoPipelineQueueSize).to.eql(0); const promises = []; promises.push(cluster.subscribe("subscribe").catch(() => {})); promises.push(cluster.unsubscribe("subscribe").catch(() => {})); expect(cluster.autoPipelineQueueSize).to.eql(0); await promises; cluster.disconnect(); }); it("should not add blacklisted commands to auto pipelines", async () => { const cluster = new Cluster(hosts, { enableAutoPipelining: true, autoPipeliningIgnoredCommands: ["hmget"], }); await new Promise((resolve) => cluster.once("connect", resolve)); expect(cluster.autoPipelineQueueSize).to.eql(0); const promise = cluster.hmget("foo1").catch(() => {}); expect(cluster.autoPipelineQueueSize).to.eql(0); await promise; cluster.disconnect(); }); it("should support custom commands", async () => { const cluster = new Cluster(hosts, { enableAutoPipelining: true }); await new Promise((resolve) => cluster.once("connect", resolve)); cluster.defineCommand("echo", { numberOfKeys: 2, lua: "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", }); const promise = cluster.echo("foo1", "foo1", "bar1", "bar2"); expect(cluster.autoPipelineQueueSize).to.eql(1); expect(await promise).to.eql(["foo1", "foo1", "bar1", "bar2"]); await cluster.echo("foo1", "foo1", "bar1", "bar2"); cluster.disconnect(); }); it("should support multiple commands", async () => { const cluster = new Cluster(hosts, { enableAutoPipelining: true }); await new Promise((resolve) => cluster.once("connect", resolve)); await cluster.set("foo1", "bar1"); await cluster.set("foo5", "bar5"); expect( await Promise.all([ cluster.get("foo1"), cluster.get("foo5"), cluster.get("foo1"), cluster.get("foo5"), cluster.get("foo1"), ]) ).to.eql(["bar1", "bar5", "bar1", "bar5", "bar1"]); cluster.disconnect(); }); it("should support building pipelines when a prefix is used", async () => { const cluster = new Cluster(hosts, { enableAutoPipelining: true, keyPrefix: "baz:", }); await new Promise((resolve) => cluster.once("connect", resolve)); await cluster.set("foo1", "bar1"); await cluster.set("foo10", "bar10"); expect( await Promise.all([cluster.get("foo1"), cluster.get("foo10")]) ).to.eql(["bar1", "bar10"]); cluster.disconnect(); }); it("should support building pipelines when a prefix is used with arrays to flatten", async () => { const cluster = new Cluster(hosts, { enableAutoPipelining: true, keyPrefix: "baz:", }); await new Promise((resolve) => cluster.once("connect", resolve)); await cluster.set(["foo1"], "bar1"); await cluster.set(["foo10"], "bar10"); expect( await Promise.all([cluster.get(["foo1"]), cluster.get(["foo10"])]) ).to.eql(["bar1", "bar10"]); cluster.disconnect(); }); it("should support commands queued after a pipeline is already queued for execution", (done) => { const cluster = new Cluster(hosts, { enableAutoPipelining: true }); cluster.once("connect", () => { let value1; expect(cluster.autoPipelineQueueSize).to.eql(0); cluster.set("foo1", "bar1", () => {}); cluster.set("foo5", "bar5", () => {}); cluster.get("foo1", (err, v1) => { expect(err).to.eql(null); value1 = v1; }); process.nextTick(() => { cluster.get("foo5", (err, value2) => { expect(err).to.eql(null); expect(value1).to.eql("bar1"); expect(value2).to.eql("bar5"); expect(cluster.autoPipelineQueueSize).to.eql(0); cluster.disconnect(); done(); }); }); expect(cluster.autoPipelineQueueSize).to.eql(3); }); }); it("should correctly track pipeline length", async () => { const cluster = new Cluster(hosts, { enableAutoPipelining: true }); await new Promise((resolve) => cluster.once("connect", resolve)); expect(cluster.autoPipelineQueueSize).to.eql(0); const promise1 = cluster.set("foo1", "bar"); const promise2 = cluster.set("foo5", "bar"); expect(cluster.autoPipelineQueueSize).to.eql(2); await promise1; await promise2; expect(cluster.autoPipelineQueueSize).to.eql(0); const promise3 = Promise.all([ cluster.get("foo1"), cluster.get("foo5"), cluster.get("foo1"), cluster.get("foo5"), cluster.get("foo1"), ]); expect(cluster.autoPipelineQueueSize).to.eql(5); await promise3; cluster.disconnect(); }); it("should handle rejections", async () => { const cluster = new Cluster(hosts, { enableAutoPipelining: true }); await cluster.set("foo1", "bar"); await expect(cluster.set("foo1")).to.eventually.be.rejectedWith( "ERR wrong number of arguments for 'set' command" ); cluster.disconnect(); }); it("should support callbacks in the happy case", (done) => { const cluster = new Cluster(hosts, { enableAutoPipelining: true }); cluster.once("connect", () => { let value1, value2; function cb() { expect(value1).to.eql("bar1"); expect(value2).to.eql("bar5"); expect(cluster.autoPipelineQueueSize).to.eql(0); cluster.disconnect(); done(); } expect(cluster.autoPipelineQueueSize).to.eql(0); /* In this test, foo1 and foo5 usually (like in the case of 3 nodes scenario) belongs to different nodes group. Therefore we are also testing callback scenario with multiple pipelines fired together. */ cluster.set("foo1", "bar1", () => {}); expect(cluster.autoPipelineQueueSize).to.eql(1); cluster.set("foo5", "bar5", () => { cluster.get("foo1", (err, v1) => { expect(err).to.eql(null); value1 = v1; // This is needed as we cannot really predict which nodes responds first if (value1 && value2) { cb(); } }); expect(cluster.autoPipelineQueueSize).to.eql(1); cluster.get("foo5", (err, v2) => { expect(err).to.eql(null); value2 = v2; // This is needed as we cannot really predict which nodes responds first if (value1 && value2) { cb(); } }); expect(cluster.autoPipelineQueueSize).to.eql(2); }); expect(cluster.autoPipelineQueueSize).to.eql(2); }); }); it("should support callbacks in the failure case", (done) => { const cluster = new Cluster(hosts, { enableAutoPipelining: true }); cluster.once("connect", () => { expect(cluster.autoPipelineQueueSize).to.eql(0); cluster.set("foo1", "bar1", (err) => { expect(err).to.eql(null); }); expect(cluster.autoPipelineQueueSize).to.eql(1); cluster.set("foo5", (err) => { expect(err.message).to.eql( "ERR wrong number of arguments for 'set' command" ); cluster.disconnect(); done(); }); expect(cluster.autoPipelineQueueSize).to.eql(2); }); }); it("should handle callbacks failures", (done) => { const listeners = process.listeners("uncaughtException"); process.removeAllListeners("uncaughtException"); process.once("uncaughtException", (err) => { expect(err.message).to.eql("ERROR"); for (const listener of listeners) { process.on("uncaughtException", listener); } cluster.disconnect(); done(); }); const cluster = new Cluster(hosts, { enableAutoPipelining: true }); cluster.once("connect", () => { expect(cluster.autoPipelineQueueSize).to.eql(0); cluster.set("foo1", "bar1", (err) => { expect(err).to.eql(null); throw new Error("ERROR"); }); cluster.set("foo5", "bar5", (err) => { expect(err).to.eql(null); expect(cluster.autoPipelineQueueSize).to.eql(0); }); expect(cluster.autoPipelineQueueSize).to.eql(2); }); }); it("should handle general pipeline failures", (done) => { const listeners = process.listeners("uncaughtException"); process.removeAllListeners("uncaughtException"); process.once("uncaughtException", (err) => { expect(err.message).to.eql("ERROR"); for (const listener of listeners) { process.on("uncaughtException", listener); } cluster.disconnect(); done(); }); const cluster = new Cluster(hosts, { enableAutoPipelining: true }); cluster.once("connect", () => { expect(cluster.autoPipelineQueueSize).to.eql(0); cluster.set("foo1", "bar1", (err) => { expect(err).to.eql(null); throw new Error("ERROR"); }); cluster.set("foo5", "bar5", (err) => { expect(err).to.eql(null); expect(cluster.autoPipelineQueueSize).to.eql(0); }); expect(cluster.autoPipelineQueueSize).to.eql(2); }); }); it("should handle general pipeline rejections", async () => { const cluster = new Cluster(hosts, { enableAutoPipelining: true }); await new Promise((resolve) => cluster.once("connect", resolve)); const promise1 = cluster.set("foo1", "bar"); const promise2 = cluster.set("foo5", "bar"); const promise3 = cluster.set("foo2", "bar"); const promise4 = cluster.set("foo6", "bar"); // Override slots to induce a failure const key1Slot = calculateKeySlot("foo1"); const key2Slot = calculateKeySlot("foo2"); const key5Slot = calculateKeySlot("foo5"); changeSlot(cluster, key1Slot, key2Slot); changeSlot(cluster, key2Slot, key5Slot); await expect(promise1).to.eventually.be.rejectedWith( "All keys in the pipeline should belong to the same slots allocation group" ); await expect(promise2).to.eventually.be.rejectedWith( "All keys in the pipeline should belong to the same slots allocation group" ); await expect(promise3).to.eventually.be.rejectedWith( "All keys in the pipeline should belong to the same slots allocation group" ); await expect(promise4).to.eventually.be.rejectedWith( "All keys in the pipeline should belong to the same slots allocation group" ); cluster.disconnect(); }); it("should handle general pipeline failures", (done) => { const cluster = new Cluster(hosts, { enableAutoPipelining: true }); cluster.once("connect", () => { let err1, err2, err3, err4; function cb() { expect(err1.message).to.eql( "All keys in the pipeline should belong to the same slots allocation group" ); expect(err2.message).to.eql( "All keys in the pipeline should belong to the same slots allocation group" ); expect(err3.message).to.eql( "All keys in the pipeline should belong to the same slots allocation group" ); expect(err4.message).to.eql( "All keys in the pipeline should belong to the same slots allocation group" ); expect(cluster.autoPipelineQueueSize).to.eql(0); cluster.disconnect(); done(); } expect(cluster.autoPipelineQueueSize).to.eql(0); cluster.set("foo1", "bar1", (err) => { err1 = err; if (err1 && err2 && err3 && err4) { cb(); } }); expect(cluster.autoPipelineQueueSize).to.eql(1); cluster.set("foo2", "bar2", (err) => { err2 = err; if (err1 && err2 && err3 && err4) { cb(); } }); expect(cluster.autoPipelineQueueSize).to.eql(2); cluster.set("foo5", "bar5", (err) => { err3 = err; if (err1 && err2 && err3 && err4) { cb(); } }); expect(cluster.autoPipelineQueueSize).to.eql(3); cluster.set("foo6", "bar6", (err) => { err4 = err; if (err1 && err2 && err3 && err4) { cb(); } }); expect(cluster.autoPipelineQueueSize).to.eql(4); // Override slots to induce a failure const key1Slot = calculateKeySlot("foo1"); const key2Slot = calculateKeySlot("foo2"); const key5Slot = calculateKeySlot("foo5"); changeSlot(cluster, key1Slot, key2Slot); changeSlot(cluster, key2Slot, key5Slot); }); }); it("should handle general pipeline failures callbacks failure", (done) => { const cluster = new Cluster(hosts, { enableAutoPipelining: true }); const listeners = process.listeners("uncaughtException"); process.removeAllListeners("uncaughtException"); cluster.once("connect", () => { let err1, err5; process.once("uncaughtException", (err) => { expect(err.message).to.eql("ERROR"); expect(err1.message).to.eql( "All keys in the pipeline should belong to the same slots allocation group" ); expect(err5.message).to.eql( "All keys in the pipeline should belong to the same slots allocation group" ); for (const listener of listeners) { process.on("uncaughtException", listener); } cluster.disconnect(); done(); }); cluster.set("foo1", "bar1", (err) => { err1 = err; }); cluster.set("foo5", "bar5", (err) => { err5 = err; }); expect(cluster.autoPipelineQueueSize).to.eql(2); cluster.set("foo2", (err) => { throw new Error("ERROR"); }); expect(cluster.autoPipelineQueueSize).to.eql(3); const key1Slot = calculateKeySlot("foo1"); const key2Slot = calculateKeySlot("foo2"); changeSlot(cluster, key1Slot, key2Slot); }); }); it("should support lazyConnect", async () => { const cluster = new Cluster(hosts, { enableAutoPipelining: true, lazyConnect: true, }); await cluster.set("foo1", "bar1"); await cluster.set("foo5", "bar5"); expect( await Promise.all([ cluster.get("foo1"), cluster.get("foo5"), cluster.get("foo1"), cluster.get("foo5"), cluster.get("foo1"), ]) ).to.eql(["bar1", "bar5", "bar1", "bar5", "bar1"]); cluster.disconnect(); }); });
the_stack
import * as ts from 'typescript'; import { analyzeObjectLiteral, ObjectLiteralStruct } from '../jsii/jsii-types'; import { isNamedLikeStruct, isJsiiProtocolType } from '../jsii/jsii-utils'; import { OTree, NO_SYNTAX } from '../o-tree'; import { AstRenderer, AstHandler, nimpl, CommentSyntax } from '../renderer'; import { voidExpressionString } from '../typescript/ast-utils'; import { ImportStatement } from '../typescript/imports'; import { TargetLanguage } from '.'; /** * A basic visitor that applies for most curly-braces-based languages */ export abstract class DefaultVisitor<C> implements AstHandler<C> { public abstract readonly defaultContext: C; public abstract readonly language: TargetLanguage; public abstract mergeContext(old: C, update: C): C; protected statementTerminator = ';'; public commentRange(comment: CommentSyntax, _context: AstRenderer<C>): OTree { return new OTree([comment.isTrailing ? ' ' : '', comment.text, comment.hasTrailingNewLine ? '\n' : '']); } public sourceFile(node: ts.SourceFile, context: AstRenderer<C>): OTree { return new OTree(context.convertAll(node.statements)); } public jsDoc(_node: ts.JSDoc, _context: AstRenderer<C>): OTree { // Already handled by other doc handlers return new OTree([]); } public importStatement(node: ImportStatement, context: AstRenderer<C>): OTree { return this.notImplemented(node.node, context); } public functionDeclaration(node: ts.FunctionDeclaration, children: AstRenderer<C>): OTree { return this.notImplemented(node, children); } public stringLiteral(node: ts.StringLiteral | ts.NoSubstitutionTemplateLiteral, _renderer: AstRenderer<C>): OTree { return new OTree([JSON.stringify(node.text)]); } public numericLiteral(node: ts.NumericLiteral, _children: AstRenderer<C>): OTree { return new OTree([node.text]); } public identifier(node: ts.Identifier, _children: AstRenderer<C>): OTree { return new OTree([node.text]); } public block(node: ts.Block, children: AstRenderer<C>): OTree { return new OTree(['{'], ['\n', ...children.convertAll(node.statements)], { indent: 4, suffix: '}', }); } public parameterDeclaration(node: ts.ParameterDeclaration, children: AstRenderer<C>): OTree { return this.notImplemented(node, children); } public returnStatement(node: ts.ReturnStatement, children: AstRenderer<C>): OTree { return new OTree(['return ', children.convert(node.expression), this.statementTerminator], [], { canBreakLine: true, }); } public binaryExpression(node: ts.BinaryExpression, context: AstRenderer<C>): OTree { const operator = context.textOf(node.operatorToken); if (operator === '??') { context.reportUnsupported(node.operatorToken, undefined); } const operatorToken = this.translateBinaryOperator(operator); return new OTree([context.convert(node.left), ' ', operatorToken, ' ', context.convert(node.right)]); } public prefixUnaryExpression(node: ts.PrefixUnaryExpression, context: AstRenderer<C>): OTree { return new OTree([this.translateUnaryOperator(node.operator), context.convert(node.operand)]); } public translateUnaryOperator(operator: ts.PrefixUnaryOperator) { return UNARY_OPS[operator]; } public translateBinaryOperator(operator: string) { if (operator === '===') { return '=='; } return operator; } public ifStatement(node: ts.IfStatement, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public propertyAccessExpression(node: ts.PropertyAccessExpression, context: AstRenderer<C>): OTree { return new OTree([context.convert(node.expression), '.', context.convert(node.name)]); } /** * Do some work on property accesses to translate common JavaScript-isms to language-specific idioms */ public callExpression(node: ts.CallExpression, context: AstRenderer<C>): OTree { const functionText = context.textOf(node.expression); if (functionText === 'console.log' || functionText === 'console.error') { return this.printStatement(node.arguments, context); } if (functionText === 'super') { return this.superCallExpression(node, context); } return this.regularCallExpression(node, context); } public regularCallExpression(node: ts.CallExpression, context: AstRenderer<C>): OTree { return new OTree([context.convert(node.expression), '(', this.argumentList(node.arguments, context), ')']); } public superCallExpression(node: ts.CallExpression, context: AstRenderer<C>): OTree { return this.regularCallExpression(node, context); } public printStatement(args: ts.NodeArray<ts.Expression>, context: AstRenderer<C>) { return new OTree(['<PRINT>', '(', this.argumentList(args, context), ')']); } public expressionStatement(node: ts.ExpressionStatement, context: AstRenderer<C>): OTree { return new OTree([context.convert(node.expression)], [], { canBreakLine: true, }); } public token<A extends ts.SyntaxKind>(node: ts.Token<A>, context: AstRenderer<C>): OTree { return new OTree([context.textOf(node)]); } /** * An object literal can render as one of three things: * * - Don't know the type (render as an unknown struct) * - Know the type: * - It's a struct (render as known struct) * - It's not a struct (render as key-value map) */ public objectLiteralExpression(node: ts.ObjectLiteralExpression, context: AstRenderer<C>): OTree { // If any of the elements of the objectLiteralExpression are not a literal property // assignment, report them. We can't support those. const unsupported = node.properties.filter( (p) => !ts.isPropertyAssignment(p) && !ts.isShorthandPropertyAssignment(p), ); for (const unsup of unsupported) { context.report(unsup, `Use of ${ts.SyntaxKind[unsup.kind]} in an object literal is not supported.`); } const anyMembersFunctions = node.properties.some((p) => ts.isPropertyAssignment(p) ? isExpressionOfFunctionType(context.typeChecker, p.initializer) : ts.isShorthandPropertyAssignment(p) ? isExpressionOfFunctionType(context.typeChecker, p.name) : false, ); const inferredType = context.inferredTypeOfExpression(node); if ((inferredType && isJsiiProtocolType(context.typeChecker, inferredType)) || anyMembersFunctions) { context.report( node, `You cannot use an object literal to make an instance of an interface. Define a class instead.`, ); } const lit = analyzeObjectLiteral(context.typeChecker, node); switch (lit.kind) { case 'unknown': return this.unknownTypeObjectLiteralExpression(node, context); case 'struct': case 'local-struct': return this.knownStructObjectLiteralExpression(node, lit, context); case 'map': return this.keyValueObjectLiteralExpression(node, context); } } public unknownTypeObjectLiteralExpression(node: ts.ObjectLiteralExpression, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public knownStructObjectLiteralExpression( node: ts.ObjectLiteralExpression, _structType: ObjectLiteralStruct, context: AstRenderer<C>, ): OTree { return this.notImplemented(node, context); } public keyValueObjectLiteralExpression(node: ts.ObjectLiteralExpression, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public newExpression(node: ts.NewExpression, context: AstRenderer<C>): OTree { return new OTree( ['new ', context.convert(node.expression), '(', this.argumentList(node.arguments, context), ')'], [], { canBreakLine: true }, ); } public propertyAssignment(node: ts.PropertyAssignment, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public variableStatement(node: ts.VariableStatement, context: AstRenderer<C>): OTree { return new OTree([context.convert(node.declarationList)], [], { canBreakLine: true, }); } public variableDeclarationList(node: ts.VariableDeclarationList, context: AstRenderer<C>): OTree { return new OTree([], context.convertAll(node.declarations)); } public variableDeclaration(node: ts.VariableDeclaration, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public arrayLiteralExpression(node: ts.ArrayLiteralExpression, context: AstRenderer<C>): OTree { return new OTree(['['], context.convertAll(node.elements), { separator: ', ', suffix: ']', }); } public shorthandPropertyAssignment(node: ts.ShorthandPropertyAssignment, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public forOfStatement(node: ts.ForOfStatement, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public classDeclaration(node: ts.ClassDeclaration, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public constructorDeclaration(node: ts.ConstructorDeclaration, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public propertyDeclaration(node: ts.PropertyDeclaration, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public computedPropertyName(node: ts.Expression, context: AstRenderer<C>): OTree { return context.convert(node); } public methodDeclaration(node: ts.MethodDeclaration, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public interfaceDeclaration(node: ts.InterfaceDeclaration, context: AstRenderer<C>): OTree { if (isNamedLikeStruct(context.textOf(node.name))) { return this.structInterfaceDeclaration(node, context); } return this.regularInterfaceDeclaration(node, context); } public structInterfaceDeclaration(node: ts.InterfaceDeclaration, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public regularInterfaceDeclaration(node: ts.InterfaceDeclaration, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public propertySignature(node: ts.PropertySignature, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public methodSignature(node: ts.MethodSignature, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public asExpression(node: ts.AsExpression, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public spreadElement(node: ts.SpreadElement, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public spreadAssignment(node: ts.SpreadAssignment, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public ellipsis(_node: ts.SpreadElement | ts.SpreadAssignment, _context: AstRenderer<C>): OTree { return new OTree(['...']); } public templateExpression(node: ts.TemplateExpression, context: AstRenderer<C>): OTree { return this.notImplemented(node, context); } public elementAccessExpression(node: ts.ElementAccessExpression, context: AstRenderer<C>): OTree { const expression = context.convert(node.expression); const index = context.convert(node.argumentExpression); return new OTree([expression, '[', index, ']']); } public nonNullExpression(node: ts.NonNullExpression, context: AstRenderer<C>): OTree { // We default we drop the non-null assertion return context.convert(node.expression); } public parenthesizedExpression(node: ts.ParenthesizedExpression, context: AstRenderer<C>): OTree { return new OTree(['(', context.convert(node.expression), ')']); } public maskingVoidExpression(node: ts.VoidExpression, context: AstRenderer<C>): OTree { // Don't render anything by default when nodes are masked const arg = voidExpressionString(node); if (arg === 'block') { return this.commentRange( { pos: context.getPosition(node).start, text: '\n// ...', kind: ts.SyntaxKind.SingleLineCommentTrivia, hasTrailingNewLine: false, }, context, ); } if (arg === '...') { return new OTree(['...']); } return NO_SYNTAX; } protected argumentList(args: readonly ts.Node[] | undefined, context: AstRenderer<C>): OTree { return new OTree([], args ? context.convertAll(args) : [], { separator: ', ', }); } private notImplemented(node: ts.Node, context: AstRenderer<C>) { context.reportUnsupported(node, this.language); return nimpl(node, context); } } const UNARY_OPS: { [op in ts.PrefixUnaryOperator]: string } = { [ts.SyntaxKind.PlusPlusToken]: '++', [ts.SyntaxKind.MinusMinusToken]: '--', [ts.SyntaxKind.PlusToken]: '+', [ts.SyntaxKind.MinusToken]: '-', [ts.SyntaxKind.TildeToken]: '~', [ts.SyntaxKind.ExclamationToken]: '!', }; /** * Whether the given expression evaluates to a value that is of type "function" * * Examples of function types: * * ```ts * // GIVEN * function someFunction() { } * * // THEN * const x = someFunction; // <- function type * const y = () => 42; // <- function type * const z = x; // <- function type * Array.isArray; // <- function type * ``` */ function isExpressionOfFunctionType(typeChecker: ts.TypeChecker, expr: ts.Expression) { const type = typeChecker.getTypeAtLocation(expr).getNonNullableType(); return type.getCallSignatures().length > 0; }
the_stack
import slash from 'slash' import { EventEmitter } from 'events' import { Exception } from '@poppinss/utils' import { ApplicationContract } from '@ioc:Adonis/Core/Application' import { SchemaConstructorContract } from '@ioc:Adonis/Lucid/Schema' import { MigratorOptions, MigratedFileNode, MigratorContract, MigrationListNode, } from '@ioc:Adonis/Lucid/Migrator' import { FileNode, DatabaseContract, QueryClientContract, TransactionClientContract, } from '@ioc:Adonis/Lucid/Database' import { MigrationSource } from './MigrationSource' /** * Migrator exposes the API to execute migrations using the schema files * for a given connection at a time. */ export class Migrator extends EventEmitter implements MigratorContract { private client = this.db.connection(this.options.connectionName || this.db.primaryConnectionName) private config = this.db.getRawConnection(this.client.connectionName)!.config /** * Reference to the migrations config for the given connection */ private migrationsConfig = Object.assign( { tableName: 'adonis_schema', disableTransactions: false, }, this.config.migrations ) /** * Table names for storing schema files and schema versions */ private schemaTableName = this.migrationsConfig.tableName private schemaVersionsTableName = `${this.schemaTableName}_versions` /** * Whether or not the migrator has been booted */ private booted: boolean = false /** * Migration source to collect schema files from the disk */ private migrationSource = new MigrationSource(this.config, this.app) /** * Mode decides in which mode the migrator is executing migrations. The migrator * instance can only run in one mode at a time. * * The value is set when `migrate` or `rollback` method is invoked */ public direction: 'up' | 'down' = this.options.direction /** * Instead of executing migrations, just return the generated SQL queries */ public dryRun: boolean = !!this.options.dryRun /** * An array of files we have successfully migrated. The files are * collected regardless of `up` or `down` methods */ public migratedFiles: { [file: string]: MigratedFileNode } = {} /** * Last error occurred when executing migrations */ public error: null | Error = null /** * Current status of the migrator */ public get status() { return !this.booted ? 'pending' : this.error ? 'error' : Object.keys(this.migratedFiles).length ? 'completed' : 'skipped' } /** * Existing version of migrations. We use versioning to upgrade * existing migrations if we are plan to make a breaking * change. */ public version: number = 2 constructor( private db: DatabaseContract, private app: ApplicationContract, private options: MigratorOptions ) { super() } /** * Returns the client for a given schema file. Schema instructions are * wrapped in a transaction unless transaction is not disabled */ private async getClient(disableTransactions: boolean) { /** * We do not create a transaction when * * 1. Migration itself disables transaction * 2. Transactions are globally disabled * 3. Doing a dry run */ if (disableTransactions || this.migrationsConfig.disableTransactions || this.dryRun) { return this.client } return this.client.transaction() } /** * Roll back the transaction when it's client is a transaction client */ private async rollback(client: QueryClientContract) { if (client.isTransaction) { await (client as TransactionClientContract).rollback() } } /** * Commits a transaction when it's client is a transaction client */ private async commit(client: QueryClientContract) { if (client.isTransaction) { await (client as TransactionClientContract).commit() } } /** * Writes the migrated file to the migrations table. This ensures that * we are not re-running the same migration again */ private async recordMigrated( client: QueryClientContract, name: string, executionResponse: boolean | string[] ) { if (this.dryRun) { this.migratedFiles[name].queries = executionResponse as string[] return } await client.insertQuery().table(this.schemaTableName).insert({ name, batch: this.migratedFiles[name].batch, }) } /** * Removes the migrated file from the migrations table. This allows re-running * the migration */ private async recordRollback( client: QueryClientContract, name: string, executionResponse: boolean | string[] ) { if (this.dryRun) { this.migratedFiles[name].queries = executionResponse as string[] return } await client.query().from(this.schemaTableName).where({ name }).del() } /** * Returns the migration source by ensuring value is a class constructor and * has disableTransactions property. */ private async getMigrationSource( migration: FileNode<unknown> ): Promise<SchemaConstructorContract> { const source = await migration.getSource() if (typeof source === 'function' && 'disableTransactions' in source) { return source } throw new Error(`Invalid schema class exported by "${migration.name}"`) } /** * Executes a given migration node and cleans up any created transactions * in case of failure */ private async executeMigration(migration: FileNode<unknown>) { const Schema = await this.getMigrationSource(migration) const client = await this.getClient(Schema.disableTransactions) try { const schema = new Schema(client, migration.name, this.dryRun) this.emit('migration:start', this.migratedFiles[migration.name]) if (this.direction === 'up') { const response = await schema.execUp() // Handles dry run itself await this.recordMigrated(client, migration.name, response) // Handles dry run itself } else if (this.direction === 'down') { const response = await schema.execDown() // Handles dry run itself await this.recordRollback(client, migration.name, response) // Handles dry run itself } await this.commit(client) this.migratedFiles[migration.name].status = 'completed' this.emit('migration:completed', this.migratedFiles[migration.name]) } catch (error) { this.error = error this.migratedFiles[migration.name].status = 'error' this.emit('migration:error', this.migratedFiles[migration.name]) await this.rollback(client) throw error } } /** * Acquires a lock to disallow concurrent transactions. Only works with * `Mysql`, `PostgreSQL` and `MariaDb` for now. * * Make sure we are acquiring lock outside the transactions, since we want * to block other processes from acquiring the same lock. * * Locks are always acquired in dry run too, since we want to stay close * to the real execution cycle */ private async acquireLock() { if (!this.client.dialect.supportsAdvisoryLocks) { return } const acquired = await this.client.dialect.getAdvisoryLock(1) if (!acquired) { throw new Exception('Unable to acquire lock. Concurrent migrations are not allowed') } this.emit('acquire:lock') } /** * Release a lock once complete the migration process. Only works with * `Mysql`, `PostgreSQL` and `MariaDb` for now. */ private async releaseLock() { if (!this.client.dialect.supportsAdvisoryLocks) { return } const released = await this.client.dialect.releaseAdvisoryLock(1) if (!released) { throw new Exception('Migration completed, but unable to release database lock') } this.emit('release:lock') } /** * Makes the migrations table (if missing). Also created in dry run, since * we always reads from the schema table to find which migrations files to * execute and that cannot done without missing table. */ private async makeMigrationsTable() { const hasTable = await this.client.schema.hasTable(this.schemaTableName) if (hasTable) { return } this.emit('create:schema:table') await this.client.schema.createTable(this.schemaTableName, (table) => { table.increments().notNullable() table.string('name').notNullable() table.integer('batch').notNullable() table.timestamp('migration_time').defaultTo(this.client.getWriteClient().fn.now()) }) } /** * Makes the migrations version table (if missing). */ private async makeMigrationsVersionsTable() { /** * Return early when table already exists */ const hasTable = await this.client.schema.hasTable(this.schemaVersionsTableName) if (hasTable) { return } /** * Create table */ this.emit('create:schema_versions:table') await this.client.schema.createTable(this.schemaVersionsTableName, (table) => { table.integer('version').notNullable() }) } /** * Returns the latest migrations version. If no rows exists * it inserts a new row for version 1 */ private async getLatestVersion() { const rows = await this.client.from(this.schemaVersionsTableName).select('version').limit(1) if (rows.length) { return Number(rows[0].version) } else { await this.client.table(this.schemaVersionsTableName).insert({ version: 1 }) return 1 } } /** * Upgrade migrations name from version 1 to version 2 */ private async upgradeFromOnetoTwo() { const migrations = await this.getMigratedFilesTillBatch(0) const client = await this.getClient(false) try { await Promise.all( migrations.map((migration) => { return client .from(this.schemaTableName) .where('id', migration.id) .update({ name: slash(migration.name), }) }) ) await client.from(this.schemaVersionsTableName).where('version', 1).update({ version: 2 }) await this.commit(client) } catch (error) { this.rollback(client) throw error } } /** * Upgrade migrations version */ private async upgradeVersion(latestVersion: number): Promise<void> { if (latestVersion === 1) { this.emit('upgrade:version', { from: 1, to: 2 }) await this.upgradeFromOnetoTwo() } } /** * Returns the latest batch from the migrations * table */ private async getLatestBatch() { const rows = await this.client.from(this.schemaTableName).max('batch as batch') return Number(rows[0].batch) } /** * Returns an array of files migrated till now */ private async getMigratedFiles() { const rows = await this.client .query<{ name: string }>() .from(this.schemaTableName) .select('name') return new Set(rows.map(({ name }) => name)) } /** * Returns an array of files migrated till now. The latest * migrations are on top */ private async getMigratedFilesTillBatch(batch: number) { return this.client .query<{ name: string; batch: number; migration_time: Date; id: number }>() .from(this.schemaTableName) .select('name', 'batch', 'migration_time', 'id') .where('batch', '>', batch) .orderBy('id', 'desc') } /** * Boot the migrator to perform actions. All boot methods must * work regardless of dryRun is enabled or not. */ private async boot() { this.emit('start') this.booted = true await this.acquireLock() await this.makeMigrationsTable() } /** * Shutdown gracefully */ private async shutdown() { await this.releaseLock() this.emit('end') } /** * Migrate up */ private async runUp() { const batch = await this.getLatestBatch() const existing = await this.getMigratedFiles() const collected = await this.migrationSource.getMigrations() /** * Upfront collecting the files to be executed */ collected.forEach((migration) => { if (!existing.has(migration.name)) { this.migratedFiles[migration.name] = { status: 'pending', queries: [], file: migration, batch: batch + 1, } } }) const filesToMigrate = Object.keys(this.migratedFiles) for (let name of filesToMigrate) { await this.executeMigration(this.migratedFiles[name].file) } } /** * Migrate down (aka rollback) */ private async runDown(batch?: number) { if (this.app.inProduction && this.migrationsConfig.disableRollbacksInProduction) { throw new Error( 'Rollback in production environment is disabled. Check "config/database" file for options.' ) } if (batch === undefined) { batch = (await this.getLatestBatch()) - 1 } const existing = await this.getMigratedFilesTillBatch(batch) const collected = await this.migrationSource.getMigrations() /** * Finding schema files for migrations to rollback. We do not perform * rollback when any of the files are missing */ existing.forEach((file) => { const migration = collected.find(({ name }) => name === file.name) if (!migration) { throw new Exception( `Cannot perform rollback. Schema file {${file.name}} is missing`, 500, 'E_MISSING_SCHEMA_FILES' ) } this.migratedFiles[migration.name] = { status: 'pending', queries: [], file: migration, batch: file.batch, } }) const filesToMigrate = Object.keys(this.migratedFiles) for (let name of filesToMigrate) { await this.executeMigration(this.migratedFiles[name].file) } } public on(event: 'start', callback: () => void): this public on(event: 'end', callback: () => void): this public on(event: 'acquire:lock', callback: () => void): this public on(event: 'release:lock', callback: () => void): this public on(event: 'create:schema:table', callback: () => void): this public on(event: 'create:schema_versions:table', callback: () => void): this public on( event: 'upgrade:version', callback: (payload: { from: number; to: number }) => void ): this public on(event: 'migration:start', callback: (file: MigratedFileNode) => void): this public on(event: 'migration:completed', callback: (file: MigratedFileNode) => void): this public on(event: 'migration:error', callback: (file: MigratedFileNode) => void): this public on(event: string, callback: (...args: any[]) => void): this { return super.on(event, callback) } /** * Returns a merged list of completed and pending migrations */ public async getList(): Promise<MigrationListNode[]> { const existingCollected: Set<string> = new Set() await this.makeMigrationsTable() const existing = await this.getMigratedFilesTillBatch(0) const collected = await this.migrationSource.getMigrations() const list: MigrationListNode[] = collected.map((migration) => { const migrated = existing.find(({ name }) => migration.name === name) /** * Already migrated. We move to an additional list, so that we can later * find the one's which are migrated but now missing on the disk */ if (migrated) { existingCollected.add(migrated.name) return { name: migration.name, batch: migrated.batch, status: 'migrated', migrationTime: migrated.migration_time, } } return { name: migration.name, status: 'pending', } }) /** * These are the one's which were migrated earlier, but now missing * on the disk */ existing.forEach(({ name, batch, migration_time }) => { if (!existingCollected.has(name)) { list.push({ name, batch, migrationTime: migration_time, status: 'corrupt' }) } }) return list } /** * Migrate the database by calling the up method */ public async run() { try { await this.boot() /** * Upgrading migrations (if required) */ await this.makeMigrationsVersionsTable() const latestVersion = await this.getLatestVersion() if (latestVersion < this.version) { await this.upgradeVersion(latestVersion) } if (this.direction === 'up') { await this.runUp() } else if (this.options.direction === 'down') { await this.runDown(this.options.batch) } } catch (error) { this.error = error } await this.shutdown() } /** * Close database connections */ public async close() { await this.db.manager.closeAll(true) } }
the_stack
import * as d3 from "d3"; import { assert } from "chai"; import * as Plottable from "../../src"; import { BarOrientation } from "../../src/plots/barPlot"; import { entityBounds } from "../../src/utils/domUtils"; import * as TestMethods from "../testMethods"; describe("Plots", () => { describe("Bar Plot", () => { describe ("setting orientation", () => { it("rejects invalid orientations", () => { assert.throws(() => new Plottable.Plots.Bar("diagonal" as any), Error); }); it("defaults to vertical", () => { const defaultPlot = new Plottable.Plots.Bar<number, number>(); assert.strictEqual(defaultPlot.orientation(), "vertical", "default Plots.Bar() are vertical"); }); it("sets orientation on construction", () => { const verticalPlot = new Plottable.Plots.Bar<number, number>("vertical"); assert.strictEqual(verticalPlot.orientation(), "vertical", "vertical Plots.Bar()"); const horizontalPlot = new Plottable.Plots.Bar<number, number>("horizontal"); assert.strictEqual(horizontalPlot.orientation(), "horizontal", "horizontal Plots.Bar()"); }); }); const orientations: BarOrientation[] = [BarOrientation.vertical, BarOrientation.horizontal]; orientations.forEach((orientation) => { const isVertical = orientation === BarOrientation.vertical; const basePositionAttr = isVertical ? "x" : "y"; const baseSizeAttr = isVertical ? "width" : "height"; const getDivBaseSizeDimension = (div: d3.Selection<HTMLDivElement, any, any, any>) => { return isVertical ? Plottable.Utils.DOM.elementWidth(div) : Plottable.Utils.DOM.elementHeight(div); }; const valuePositionAttr = isVertical ? "y" : "x"; const valueSizeAttr = isVertical ? "height" : "width"; describe(`rendering when ${orientation}`, () => { const data = [ { base: "A", value: 1 }, { base: "B", value: 0 }, { base: "C", value: -1 }, ]; let div: d3.Selection<HTMLDivElement, any, any, any>; let barPlot: Plottable.Plots.Bar<string | number, number | string>; let baseScale: Plottable.Scales.Category; let valueScale: Plottable.Scales.Linear; let dataset: Plottable.Dataset; beforeEach(() => { div = TestMethods.generateDiv(); barPlot = new Plottable.Plots.Bar<string | number, number | string>(orientation); baseScale = new Plottable.Scales.Category(); valueScale = new Plottable.Scales.Linear(); if (orientation === BarOrientation.vertical) { barPlot.x((d: any) => d.base, baseScale); barPlot.y((d: any) => d.value, valueScale); } else { barPlot.y((d: any) => d.base, baseScale); barPlot.x((d: any) => d.value, valueScale); } dataset = new Plottable.Dataset(data); }); afterEach(function() { if (this.currentTest.state === "passed") { barPlot.destroy(); div.remove(); } }); function assertCorrectRendering() { const baseline = barPlot.content().select(".baseline"); const scaledBaselineValue = valueScale.scale(<number> barPlot.baselineValue()); assert.strictEqual(TestMethods.numAttr(baseline, `${valuePositionAttr}1`), scaledBaselineValue, `baseline ${valuePositionAttr}1 is correct`); assert.strictEqual(TestMethods.numAttr(baseline, `${valuePositionAttr}2`), scaledBaselineValue, `baseline ${valuePositionAttr}2 is correct`); assert.strictEqual(TestMethods.numAttr(baseline, `${basePositionAttr}1`), 0, `baseline ${basePositionAttr}1 is correct`); assert.strictEqual(TestMethods.numAttr(baseline, `${basePositionAttr}2`), getDivBaseSizeDimension(div), `baseline ${basePositionAttr}2 is correct`); const bars = barPlot.content().selectAll<Element, any>("rect"); assert.strictEqual(bars.size(), data.length, "One bar was created per data point"); bars.each(function(datum, index) { const bar = d3.select(this); const baseSize = TestMethods.numAttr(bar, baseSizeAttr); assert.closeTo(baseSize, baseScale.rangeBand(), window.Pixel_CloseTo_Requirement, `bar ${baseSizeAttr} is correct (index ${index})`); const valueSize = TestMethods.numAttr(bar, valueSizeAttr); assert.closeTo(valueSize, Math.abs(valueScale.scale(datum.value) - scaledBaselineValue), window.Pixel_CloseTo_Requirement, `bar ${valueSizeAttr} is correct (index ${index})`); const basePosition = TestMethods.numAttr(bar, basePositionAttr); assert.closeTo(basePosition, baseScale.scale(datum.base) - 0.5 * baseSize, window.Pixel_CloseTo_Requirement, `bar ${basePositionAttr} is correct (index ${index})`); const valuePosition = TestMethods.numAttr(bar, valuePositionAttr); const isShifted = isVertical ? (datum.value > barPlot.baselineValue()) : (datum.value < barPlot.baselineValue()); const expectedValuePosition = isShifted ? scaledBaselineValue - valueSize : scaledBaselineValue; assert.closeTo(valuePosition, expectedValuePosition, window.Pixel_CloseTo_Requirement, `bar ${valuePositionAttr} is correct (index ${index})`); }); } it("renders with no data", () => { assert.doesNotThrow(() => barPlot.renderTo(div), Error); assert.strictEqual(barPlot.width(), Plottable.Utils.DOM.elementWidth(div), "was allocated width"); assert.strictEqual(barPlot.height(), Plottable.Utils.DOM.elementHeight(div), "was allocated height"); }); it("draws bars and baseline in correct positions", () => { barPlot.addDataset(dataset); barPlot.renderTo(div); assertCorrectRendering(); }); it("rerenders correctly when the baseline value is changed", () => { barPlot.addDataset(dataset); barPlot.renderTo(div); barPlot.baselineValue(1); assertCorrectRendering(); }); it("can autorange value scale based on visible points on base scale", () => { const firstTwoBaseValues = [ data[0].base, data[1].base ]; valueScale.padProportion(0); baseScale.domain(firstTwoBaseValues); barPlot.addDataset(dataset); barPlot.autorangeMode(valuePositionAttr); barPlot.renderTo(div); const valueScaleDomain = valueScale.domain(); const expectedValueDomainMin = Math.min(data[0].value, data[1].value); const expectedValueDomainMax = Math.max(data[0].value, data[1].value); assert.strictEqual(valueScaleDomain[0], expectedValueDomainMin, "lower bound of domain set based on visible points"); assert.strictEqual(valueScaleDomain[1], expectedValueDomainMax, "upper bound of domain set based on visible points"); }); it("doesn't show values from outside the base scale's domain", () => { baseScale.domain(["-A"]); barPlot.addDataset(dataset); barPlot.renderTo(div); assert.strictEqual(barPlot.content().selectAll<Element, any>("rect").size(), 0, "draws no bars when the domain contains no data points"); }); }); describe(`autodomaining when ${orientation}`, () => { let div: d3.Selection<HTMLDivElement, any, any, any>; let baseScale: Plottable.Scales.Linear; let valueScale: Plottable.Scales.Linear; let barPlot: Plottable.Plots.Bar<number, number>; const baseAccessor = (d: any) => d.base; const valueAccessor = (d: any) => d.value; beforeEach(() => { div = TestMethods.generateDiv(); barPlot = new Plottable.Plots.Bar<number, number>(orientation); baseScale = new Plottable.Scales.Linear(); valueScale = new Plottable.Scales.Linear(); if (orientation === BarOrientation.vertical) { barPlot.x(baseAccessor, baseScale); barPlot.y(valueAccessor, valueScale); } else { barPlot.y(baseAccessor, baseScale); barPlot.x(valueAccessor, valueScale); } }); afterEach(function() { if (this.currentTest.state === "passed") { barPlot.destroy(); div.remove(); } }); it("computes the base scale domain correctly when there is only one data point", () => { const singlePointData = [ { base: baseScale.domain()[1] + 10, value: 5 }, ]; barPlot.addDataset(new Plottable.Dataset(singlePointData)); barPlot.renderTo(div); const baseScaleDomain = baseScale.domain(); assert.operator(baseScaleDomain[0], "<=", singlePointData[0].base, "lower end of base domain is less than the value"); assert.operator(baseScaleDomain[1], ">=", singlePointData[0].base, "upper end of base domain is greater than the value"); }); it("base scale domain does not change when autoDomain is called more than once", () => { const data = [ { base: 0, value: 1 }, { base: 1, value: 2 }, ]; barPlot.addDataset(new Plottable.Dataset(data)); barPlot.renderTo(div); const baseDomainAfterRendering = baseScale.domain(); baseScale.autoDomain(); const baseDomainAfterAutoDomaining = baseScale.domain(); assert.deepEqual(baseDomainAfterRendering, baseDomainAfterAutoDomaining, "calling autoDomain() again does not change the domain"); }); }); describe(`auto bar width calculation when ${orientation}`, () => { const scaleTypes = ["Linear", "ModifiedLog", "Time"]; scaleTypes.forEach((scaleType) => { describe(`using a ${scaleType} base Scale`, () => { let div: d3.Selection<HTMLDivElement, any, any, any>; let barPlot: Plottable.Plots.Bar<number | Date, number | Date>; let baseScale: Plottable.QuantitativeScale<number | Date>; let valueScale: Plottable.Scales.Linear; let dataset: Plottable.Dataset; beforeEach(() => { div = TestMethods.generateDiv(); barPlot = new Plottable.Plots.Bar<number | Date, number | Date>(orientation); switch (scaleType) { case "Linear": baseScale = new Plottable.Scales.Linear(); break; case "ModifiedLog": baseScale = new Plottable.Scales.ModifiedLog(); break; case "Time": baseScale = new Plottable.Scales.Time(); break; default: throw new Error("unexpected base Scale type"); } valueScale = new Plottable.Scales.Linear(); const baseAccessor = scaleType === "Time" ? (d: any) => new Date(d.base) : (d: any) => d.base; const valueAccessor = (d: any) => d.value; if (orientation === BarOrientation.vertical) { barPlot.x(baseAccessor, baseScale); barPlot.y(valueAccessor, valueScale); } else { barPlot.y(baseAccessor, baseScale); barPlot.x(valueAccessor, valueScale); } dataset = new Plottable.Dataset(); barPlot.addDataset(dataset); barPlot.renderTo(div); }); afterEach(function() { if (this.currentTest.state === "passed") { barPlot.destroy(); div.remove(); } }); it("computes a sensible width", () => { const data = [ { base: 1, value: 5 }, { base: 10, value: 2 }, { base: 100, value: 4 }, ]; dataset.data(data); const closestSeparation = Math.abs(baseScale.scale(data[1].base) - baseScale.scale(data[0].base)); const bars = barPlot.content().selectAll<Element, any>("rect"); assert.strictEqual(bars.size(), data.length, "one bar was drawn per datum"); bars.each(function() { const bar = d3.select(this); const barSize = TestMethods.numAttr(bar, baseSizeAttr); assert.operator(barSize, "<=", closestSeparation, "bar width is less than the closest distance between values"); assert.operator(barSize, ">=", 0.5 * closestSeparation, "bar width is greater than half the closest distance between values"); }); }); it("accounts for the bar width when autoDomaining the base scale", () => { const data = [ { base: 1, value: 5 }, { base: 10, value: 2 }, { base: 100, value: 4 }, ]; dataset.data(data); const bars = barPlot.content().selectAll<Element, any>("rect"); assert.strictEqual(bars.size(), data.length, "one bar was drawn per datum"); const divSize = getDivBaseSizeDimension(div); bars.each(function() { const bar = d3.select(this); const barPosition = TestMethods.numAttr(bar, basePositionAttr); const barSize = TestMethods.numAttr(bar, baseSizeAttr); assert.operator(barPosition, ">=", 0, `bar is within visible area (${basePositionAttr})`); assert.operator(barPosition, "<=", divSize, `bar is within visible area (${basePositionAttr})`); assert.operator(barPosition + barSize, ">=", 0, `bar is within visible area (${baseSizeAttr})`); assert.operator(barPosition + barSize, "<=", divSize, `bar is within visible area (${baseSizeAttr})`); }); }); it("does not crash when given bad data", () => { const badData: any = [ {}, { base: null, value: null }, ]; assert.doesNotThrow(() => dataset.data(badData), Error); }); it("computes a sensible width when given only one datum", () => { const singleDatumData = [ { base: 1, value: 5 }, ]; dataset.data(singleDatumData); const bar = barPlot.content().select("rect"); const barSize = TestMethods.numAttr(bar, baseSizeAttr); const divSize = getDivBaseSizeDimension(div); assert.operator(barSize, ">=", divSize / 4, "bar is larger than 1/4 of the available space"); assert.operator(barSize, "<=", divSize / 2, "bar is smaller than 1/2 of the available space"); }); it("computes a sensible width when given repeated base value", () => { const repeatedBaseData = [ { base: 1, value: 5 }, { base: 1, value: -5 }, ]; dataset.data(repeatedBaseData); const bars = barPlot.content().selectAll<Element, any>("rect"); assert.strictEqual(bars.size(), repeatedBaseData.length, "one bar was drawn per datum"); const divSize = getDivBaseSizeDimension(div); bars.each(function() { const bar = d3.select(this); const barSize = TestMethods.numAttr(bar, baseSizeAttr); assert.operator(barSize, ">=", divSize / 4, "bar is larger than 1/4 of the available space"); assert.operator(barSize, "<=", divSize / 2, "bar is smaller than 1/2 of the available space"); }); }); it("computes a sensible width when given unsorted data", () => { const unsortedData = [ { base: 10, value: 2 }, { base: 1, value: 5 }, { base: 100, value: 4 }, ]; dataset.data(unsortedData); const closestSeparation = Math.abs(baseScale.scale(unsortedData[1].base) - baseScale.scale(unsortedData[0].base)); const bars = barPlot.content().selectAll<Element, any>("rect"); assert.strictEqual(bars.size(), unsortedData.length, "one bar was drawn per datum"); bars.each(function() { const bar = d3.select(this); const barSize = TestMethods.numAttr(bar, baseSizeAttr); assert.operator(barSize, "<=", closestSeparation, "bar width is less than the closest distance between values"); assert.operator(barSize, ">=", 0.5 * closestSeparation, "bar width is greater than half the closest distance between values"); }); }); }); }); }); describe(`labels when ${orientation}`, () => { const data = [ { base: -4, value: -4 }, { base: -2, value: -0.1}, { base: 0, value: 0 }, { base: 2, value: 0.1 }, { base: 4, value: 4 }, ]; const DEFAULT_DOMAIN = [-5, 5]; let div: d3.Selection<HTMLDivElement, any, any, any>; let baseScale: Plottable.Scales.Linear; let valueScale: Plottable.Scales.Linear; let barPlot: Plottable.Plots.Bar<number, number>; let dataset: Plottable.Dataset; beforeEach(() => { div = TestMethods.generateDiv(); barPlot = new Plottable.Plots.Bar<number, number>(orientation); baseScale = new Plottable.Scales.Linear(); baseScale.domain(DEFAULT_DOMAIN); valueScale = new Plottable.Scales.Linear(); valueScale.domain(DEFAULT_DOMAIN); if (orientation === BarOrientation.vertical) { barPlot.x((d: any) => d.base, baseScale); barPlot.y((d: any) => d.value, valueScale); } else { barPlot.y((d: any) => d.base, baseScale); barPlot.x((d: any) => d.value, valueScale); } dataset = new Plottable.Dataset(data); barPlot.addDataset(dataset); barPlot.renderTo(div); }); afterEach(function() { if (this.currentTest.state === "passed") { barPlot.destroy(); div.remove(); } }); function getCenterOfText(textNode: SVGElement) { const plotBoundingClientRect = (<SVGElement> barPlot.background().node()).getBoundingClientRect(); const labelBoundingClientRect = textNode.getBoundingClientRect(); return { x: (labelBoundingClientRect.left + labelBoundingClientRect.right) / 2 - plotBoundingClientRect.left, y: (labelBoundingClientRect.top + labelBoundingClientRect.bottom) / 2 - plotBoundingClientRect.top, }; } it("does not show labels by default", () => { const texts = barPlot.content().selectAll<Element, any>("text"); assert.strictEqual(texts.size(), 0, "by default, no texts are drawn"); }); it("draws one label per datum", () => { barPlot.labelsEnabled(true); const texts = barPlot.content().selectAll<Element, any>("text"); assert.strictEqual(texts.size(), data.length, "one label drawn per datum"); texts.each(function(d, i) { assert.strictEqual(d3.select(this).text(), data[i].value.toString(), `by default, label text is the bar's value (index ${i})`); }); }); it("only draws labels for bars in the viewport", () => { barPlot.labelsEnabled(true); // center on the middle bar baseScale.domain([-0.1, 0.1]); const labels = barPlot.content().selectAll("text"); assert.strictEqual(labels.size(), 1, "only one label"); }); it("hides the labels if bars are too thin to show them", () => { div.style(baseSizeAttr, getDivBaseSizeDimension(div) / 10 + "px"); barPlot.redraw(); barPlot.labelsEnabled(true); const texts = barPlot.content().selectAll<Element, any>("text"); assert.strictEqual(texts.size(), 0, "no labels drawn"); }); it("can apply a formatter to the labels", () => { barPlot.labelsEnabled(true); const formatter = (n: number) => `${n}%`; barPlot.labelFormatter(formatter); const texts = barPlot.content().selectAll<Element, any>("text"); assert.strictEqual(texts.size(), data.length, "one label drawn per datum"); const expectedTexts = data.map((d) => formatter(d.value)); texts.each(function(d, i) { assert.strictEqual(d3.select(this).text(), expectedTexts[i], `formatter is applied to the displayed value (index ${i})`); }); }); it("shows labels inside or outside the bar as appropriate", () => { barPlot.labelsEnabled(true); const labels = barPlot.content().selectAll<SVGElement, any>(".on-bar-label, .off-bar-label"); assert.strictEqual(labels.size(), data.length, "one label drawn per datum"); const bars = barPlot.content().select(".bar-area").selectAll<SVGElement, any>("rect"); labels.each((d, i) => { const labelBoundingClientRect = labels.nodes()[i].getBoundingClientRect(); const barBoundingClientRect = bars.nodes()[i].getBoundingClientRect(); if ((<any> labelBoundingClientRect)[valueSizeAttr] > (<any> barBoundingClientRect)[valueSizeAttr]) { assert.isTrue(d3.select(labels.nodes()[i]).classed("off-bar-label"), `label with index ${i} doesn't fit and carries the off-bar class`); } else { assert.isTrue(d3.select(labels.nodes()[i]).classed("on-bar-label"), `label with index ${i} fits and carries the on-bar class`); } }); }); it("shows labels for bars with value = baseline on the \"positive\" side of the baseline", () => { const zeroOnlyData = [ { base: 0, value: 0 } ]; dataset.data(zeroOnlyData); barPlot.labelsEnabled(true); const label = barPlot.content().select("text"); const labelBoundingRect = (<SVGElement> label.node()).getBoundingClientRect(); const lineBoundingRect = (<SVGElement> barPlot.content().select(".baseline").node()).getBoundingClientRect(); if (isVertical) { const labelPosition = labelBoundingRect.bottom - window.Pixel_CloseTo_Requirement; const linePosition = lineBoundingRect.top; assert.operator(labelPosition, "<=", linePosition, "label with value = baseline is drawn above the baseline"); } else { const labelPosition = labelBoundingRect.left + window.Pixel_CloseTo_Requirement; const linePosition = lineBoundingRect.right; assert.operator(labelPosition, ">=", linePosition, "label with value = baseline is drawn to the right of the baseline"); } }); it("shifts on-bar-label to off-bar-label", () => { barPlot.labelsEnabled(true); const labels = barPlot.content().selectAll<Element, any>(".on-bar-label, .off-bar-label"); const lastLabel = d3.select(labels.nodes()[4]); assert.isDefined(lastLabel.select(".off-bar-label"), "last bar starts on-bar"); const centerOfText = getCenterOfText(<SVGElement> lastLabel.select("text").node()); const centerValue = valueScale.invert(isVertical ? centerOfText.y : centerOfText.x); // shift the plot such that the last bar's on-bar label is cut off valueScale.domain([centerValue, centerValue + (DEFAULT_DOMAIN[1] - DEFAULT_DOMAIN[0])]); const newLabels = barPlot.content().selectAll<Element, any>(".on-bar-label, .off-bar-label"); assert.strictEqual(newLabels.size(), 1, "only one label is drawn now"); assert.isTrue(d3.select(newLabels.nodes()[0]).classed("off-bar-label"), "cut off on-bar label was switched to off-bar"); div.remove(); }); // HACKHACK: This test is a bit hacky, but it seems to be testing for a bug fixed in // https://github.com/palantir/plottable/pull/1240 . Leaving it until we find a better way to test for it. it("removes labels instantly on dataset change", (done) => { barPlot.labelsEnabled(true); let texts = barPlot.content().selectAll<Element, any>("text"); assert.strictEqual(texts.size(), dataset.data().length, "one label drawn per datum"); const originalDrawLabels = (<any> barPlot)._drawLabels; let called = false; (<any> barPlot)._drawLabels = () => { if (!called) { originalDrawLabels.apply(barPlot); texts = barPlot.content().selectAll<Element, any>("text"); assert.strictEqual(texts.size(), dataset.data().length, "texts were repopulated by drawLabels after the update"); called = true; // for some reason, in phantomJS, `done` was being called multiple times and this caused the test to fail. done(); } }; dataset.data(dataset.data()); texts = barPlot.content().selectAll<Element, any>("text"); assert.strictEqual(texts.size(), 0, "texts were immediately removed"); }); }); describe(`retrieving Entities when ${orientation}`, () => { const data = [ { base: -1, value: -1 }, { base: 0, value: 0 }, { base: 1, value: 1 }, ]; const DEFAULT_DOMAIN = [-2, 2]; let div: d3.Selection<HTMLDivElement, any, any, any>; let barPlot: Plottable.Plots.Bar<number, number>; let baseScale: Plottable.Scales.Linear; let valueScale: Plottable.Scales.Linear; let dataset: Plottable.Dataset; beforeEach(() => { div = TestMethods.generateDiv(); barPlot = new Plottable.Plots.Bar<number, number>(orientation); baseScale = new Plottable.Scales.Linear(); baseScale.domain(DEFAULT_DOMAIN); valueScale = new Plottable.Scales.Linear(); valueScale.domain(DEFAULT_DOMAIN); if (orientation === BarOrientation.vertical) { barPlot.x((d: any) => d.base, baseScale); barPlot.y((d: any) => d.value, valueScale); } else { barPlot.y((d: any) => d.base, baseScale); barPlot.x((d: any) => d.value, valueScale); } dataset = new Plottable.Dataset(data); barPlot.addDataset(dataset); barPlot.renderTo(div); }); afterEach(function() { if (this.currentTest.state === "passed") { barPlot.destroy(); div.remove(); } }); it("returns the correct position for each Entity", () => { const entities = barPlot.entities(); entities.forEach((entity, index) => { const xBinding = barPlot.x(); const yBinding = barPlot.y(); const scaledDataX = xBinding.scale.scale(xBinding.accessor(entity.datum, index, dataset)); const scaledDataY = yBinding.scale.scale(yBinding.accessor(entity.datum, index, dataset)); assert.strictEqual(scaledDataX, entity.position.x, "entities().position.x is equal to scaled x value"); assert.strictEqual(scaledDataY, entity.position.y, "entities().position.y is equal to scaled y value"); }); }); function getPointFromBaseAndValuePositions(basePosition: number, valuePosition: number) { return { x: isVertical ? basePosition : valuePosition, y: isVertical ? valuePosition : basePosition, }; } function expectedEntityForIndex(sourceDataIndex: number, visibleElementIndex: number) { const datum = data[sourceDataIndex]; const basePosition = baseScale.scale(datum.base); const valuePosition = valueScale.scale(datum.value); const element = barPlot.content().selectAll<Element, any>("rect").nodes()[visibleElementIndex]; return { datum: datum, index: sourceDataIndex, dataset: dataset, datasetIndex: 0, position: getPointFromBaseAndValuePositions(basePosition, valuePosition), selection: d3.select(element), component: barPlot, bounds: entityBounds(element), }; } describe("retrieving the nearest Entity", () => { function testEntityNearest() { data.forEach((datum, index) => { const expectedEntity = expectedEntityForIndex(index, index); const barBasePosition = baseScale.scale(datum.base); const halfwayValuePosition = valueScale.scale((barPlot.baselineValue() + datum.value) / 2); const pointInsideBar = getPointFromBaseAndValuePositions(barBasePosition, halfwayValuePosition); const nearestInsideBar = barPlot.entityNearest(pointInsideBar); TestMethods.assertPlotEntitiesEqual(nearestInsideBar, expectedEntity, "retrieves the Entity for a bar if inside the bar"); const abovePosition = valueScale.scale(2 * datum.value); const pointAboveBar = getPointFromBaseAndValuePositions(barBasePosition, abovePosition); const nearestAboveBar = barPlot.entityNearest(pointAboveBar); TestMethods.assertPlotEntitiesEqual(nearestAboveBar, expectedEntity, "retrieves the Entity for a bar if beyond the end of the bar"); const belowPosition = valueScale.scale(-datum.value); const pointBelowBar = getPointFromBaseAndValuePositions(barBasePosition, belowPosition); const nearestBelowBar = barPlot.entityNearest(pointBelowBar); TestMethods.assertPlotEntitiesEqual(nearestBelowBar, expectedEntity, "retrieves the Entity for a bar if on the other side of the baseline from the bar"); }); } it("returns the closest by base, then by value", () => { testEntityNearest(); }); it("returns the closest visible bar", () => { const baseValuebetweenBars = (data[0].base + data[1].base) / 2; baseScale.domain([baseValuebetweenBars , DEFAULT_DOMAIN[1]]); // cuts off bar 0 const bar0BasePosition = baseScale.scale(data[0].base); const baselineValuePosition = valueScale.scale(barPlot.baselineValue()); const nearestEntity = barPlot.entityNearest(getPointFromBaseAndValuePositions(bar0BasePosition, baselineValuePosition)); const expectedEntity = expectedEntityForIndex(1, 0); // nearest visible bar TestMethods.assertPlotEntitiesEqual(nearestEntity, expectedEntity, "returned Entity for nearest in-view bar"); }); it("considers bars cut off by the value scale", () => { valueScale.domain([-0.5, 0.5]); testEntityNearest(); }); it("considers bars cut off by the base scale", () => { baseScale.domain([-0.8, 0.8]); testEntityNearest(); }); it("returns undefined if no bars are visible", () => { baseScale.domain([100, 200]); const centerOfPlot = { x: barPlot.width() / 2, y: barPlot.height() / 2, }; const nearestEntity = barPlot.entityNearest(centerOfPlot); assert.isUndefined(nearestEntity, "returns undefined when no bars are in view"); }); }); describe("retrieving the Entities at a given point", () => { it("returns the Entity at a given point, or an empty array if no bars are there", () => { data.forEach((datum, index) => { if (datum.value === barPlot.baselineValue()) { return; // bar has no height } const expectedEntity = expectedEntityForIndex(index, index); const barBasePosition = baseScale.scale(datum.base); const halfwayValuePosition = valueScale.scale((barPlot.baselineValue() + datum.value) / 2); const pointInsideBar = getPointFromBaseAndValuePositions(barBasePosition, halfwayValuePosition); const entitiesAtPointInside = barPlot.entitiesAt(pointInsideBar); assert.lengthOf(entitiesAtPointInside, 1, `exactly 1 Entity was returned (index ${index})`); TestMethods.assertPlotEntitiesEqual(entitiesAtPointInside[0], expectedEntity, `retrieves the Entity for a bar if inside the bar (index ${index})`); }); const pointOutsideBars = { x: -1, y: -1 }; const entitiesAtPointOutside = barPlot.entitiesAt(pointOutsideBars); assert.lengthOf(entitiesAtPointOutside, 0, "no Entities returned if no bars at query point"); }); }); describe("retrieving the Entities in a given range", () => { it("returns the Entities for any bars that intersect the range", () => { const bar0 = barPlot.content().select("rect"); const bar0Edge = TestMethods.numAttr(bar0, basePositionAttr); const bar0FarEdge = TestMethods.numAttr(bar0, basePositionAttr) + TestMethods.numAttr(bar0, baseSizeAttr); const baseRange = { min: bar0Edge, max: bar0FarEdge, }; const fullSizeValueRange = { min: -Infinity, max: Infinity, }; const entitiesInRange = isVertical ? barPlot.entitiesIn(baseRange, fullSizeValueRange) : barPlot.entitiesIn(fullSizeValueRange, baseRange); assert.lengthOf(entitiesInRange, 1, "retrieved two Entities when range intersects one bar"); TestMethods.assertPlotEntitiesEqual(entitiesInRange[0], expectedEntityForIndex(0, 0), "Entity corresponds to bar 0"); }); it("returns the Entity if the range includes any part of the bar", () => { const quarterUpBar0 = valueScale.scale(data[0].value / 4); const halfUpBar0 = valueScale.scale(data[0].value / 2); const valueRange = { min: Math.min(quarterUpBar0, halfUpBar0), max: Math.max(quarterUpBar0, halfUpBar0), }; const fullSizeBaseRange = { min: -Infinity, max: Infinity, }; const entitiesInRange = isVertical ? barPlot.entitiesIn(fullSizeBaseRange, valueRange) : barPlot.entitiesIn(valueRange, fullSizeBaseRange); assert.lengthOf(entitiesInRange, 1, "retrieved one entity when range intersects one bar"); TestMethods.assertPlotEntitiesEqual(entitiesInRange[0], expectedEntityForIndex(0, 0), "Entity corresponds to bar 0"); }); }); }); }); describe("Bar Alignment", () => { const data = [ { x0: 0, x1: 10, y: 10 }, { x0: 10, x1: 30, y: 20 }, { x0: 30, x1: 100, y: 30 }, ]; let div: d3.Selection<HTMLDivElement, any, any, any>; let plot: Plottable.Plots.Bar<number, number>; let xScale: Plottable.Scales.Linear; let yScale: Plottable.Scales.Linear; beforeEach(() => { div = TestMethods.generateDiv(); xScale = new Plottable.Scales.Linear().domain([0, 100]); yScale = new Plottable.Scales.Linear().domain([0, 30]); plot = new Plottable.Plots.Bar<number, number>() .addDataset(new Plottable.Dataset(data)) .x((d) => d.x0, xScale) .y((d) => d.y, yScale) .renderTo(div); }); afterEach(() => { plot.destroy(); div.remove(); }); it("aligns middle by default", () => { const bars = plot.content().select(".bar-area").selectAll<SVGElement, any>("rect").nodes(); assert.lengthOf(bars, 3); assert.equal(bars[0].getAttribute("width"), bars[1].getAttribute("width")); assert.equal(bars[1].getAttribute("width"), bars[2].getAttribute("width")); const domainWidth = xScale.invert(parseInt(bars[0].getAttribute("width"))); assert.closeTo(parseInt(bars[0].getAttribute("x")), xScale.scale(-domainWidth/2), 2); }); it("aligns at start", () => { plot.barAlignment("start"); const bars = plot.content().select(".bar-area").selectAll<SVGElement, any>("rect").nodes(); assert.lengthOf(bars, 3); assert.equal(bars[0].getAttribute("width"), bars[1].getAttribute("width")); assert.equal(bars[1].getAttribute("width"), bars[2].getAttribute("width")); assert.closeTo(parseInt(bars[0].getAttribute("x")), xScale.scale(0), 2); }); it("aligns at end", () => { plot.barAlignment("end"); const bars = plot.content().select(".bar-area").selectAll<SVGElement, any>("rect").nodes(); assert.lengthOf(bars, 3); assert.equal(bars[0].getAttribute("width"), bars[1].getAttribute("width")); assert.equal(bars[1].getAttribute("width"), bars[2].getAttribute("width")); const domainWidth = xScale.invert(parseInt(bars[0].getAttribute("width"))); assert.closeTo(parseInt(bars[0].getAttribute("x")), xScale.scale(-domainWidth), 2); }); }); describe("Bar End", () => { const data = [ { x0: 0, x1: 10, y: 10 }, { x0: 10, x1: 30, y: 20 }, { x0: 30, x1: 100, y: 30 }, ]; let div: d3.Selection<HTMLDivElement, any, any, any>; let plot: Plottable.Plots.Bar<number, number>; let xScale: Plottable.Scales.Linear; let yScale: Plottable.Scales.Linear; beforeEach(() => { div = TestMethods.generateDiv(); xScale = new Plottable.Scales.Linear().domain([0, 100]); yScale = new Plottable.Scales.Linear().domain([0, 30]); plot = new Plottable.Plots.Bar<number, number>() .addDataset(new Plottable.Dataset(data)) .x((d) => d.x0, xScale) .y((d) => d.y, yScale) .barEnd((d) => d.x1) .renderTo(div); }); afterEach(() => { plot.destroy(); div.remove(); }); it("scales width between x and barEnd", () => { const bars = plot.content().select(".bar-area").selectAll<SVGElement, any>("rect").nodes(); assert.lengthOf(bars, 3); assert.closeTo(parseInt(bars[0].getAttribute("width")), xScale.scale(10), 2); assert.closeTo(parseInt(bars[1].getAttribute("width")), xScale.scale(20), 2); assert.closeTo(parseInt(bars[2].getAttribute("width")), xScale.scale(70), 2); }); }); }); });
the_stack
import { DebugElement, Type, } from '@angular/core'; import { ComponentFixture } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { KEYS } from '@terminus/ngx-tools/keycodes'; import { createComponent as createComponentInner, createFakeEvent, createKeyboardEvent, dispatchFakeEvent, } from '@terminus/ngx-tools/testing'; import * as testComponents from '@terminus/ui/chip/testing'; // eslint-disable-next-line no-duplicate-imports import { TsChipTestComponent } from '@terminus/ui/chip/testing'; import { TsChipComponent, TsChipModule, TsChipSelectionChange, } from './chip.module'; describe('Chips', () => { let fixture: ComponentFixture<TsChipTestComponent>; let chipDebugElement: DebugElement; let chipNativeElement: HTMLElement; let chipInstance: TsChipComponent; /** * Create test host component * * @param component */ function createComponent<T>(component: Type<T>): ComponentFixture<T> { const moduleImports = [ TsChipModule, NoopAnimationsModule, ]; return createComponentInner(component, [], moduleImports); } describe('TsChip', () => { let testComponent; /** * Set up for tests * * @param component */ function setup(component: TsChipTestComponent = testComponents.SingleChip) { fixture = createComponent(component as any); fixture.detectChanges(); chipDebugElement = fixture.debugElement.query(By.directive(TsChipComponent)); chipNativeElement = chipDebugElement.nativeElement; chipInstance = chipDebugElement.componentInstance; testComponent = fixture.debugElement.componentInstance; } describe(`basic behaviors`, () => { test('should add the `ts-chip` class', () => { setup(); expect(chipNativeElement.classList).toContain('ts-chip'); }); test(`should allow direct setting of isSelectable`, () => { setup(); expect(chipInstance.isSelectable).toEqual(true); chipInstance.isSelectable = false; expect(chipInstance.isSelectable).toEqual(false); }); test(`should allow the theme to be set`, () => { setup(); expect(chipInstance.theme).toEqual('primary'); chipInstance.theme = 'warn'; fixture.detectChanges(); expect(Array.from(chipNativeElement.classList)).toContain('ts-chip--warn'); }); test(`should fall back to the primary theme`, () => { setup(); chipInstance.theme = 'warn'; fixture.detectChanges(); expect(chipInstance.theme).toEqual('warn'); chipInstance.theme = 'warn'; chipInstance.theme = undefined as any; fixture.detectChanges(); expect(chipInstance.theme).toEqual('primary'); }); test(`should allow selection`, () => { setup(); testComponent.selectionChange = jest.fn(); expect(chipNativeElement.classList).not.toContain('ts-chip--selected'); testComponent.selected = true; fixture.detectChanges(); expect(chipNativeElement.classList).toContain('ts-chip--selected'); expect(testComponent.selectionChange) .toHaveBeenCalledWith({ source: chipInstance, selected: true, }); }); test(`should set id`, () => { setup(); expect(chipInstance.id).toBeTruthy(); chipInstance.id = 'foo'; expect(chipInstance.id).toEqual('foo'); chipInstance.id = null as any; expect(chipInstance.id).toEqual(expect.stringContaining('ts-chip-')); }); test(`should see removal button`, () => { setup(); const chipRemovalButton = fixture.debugElement.query(By.css('.c-chip__remove')); expect(chipRemovalButton).toBeTruthy(); }); test(`should allow removal`, () => { setup(); testComponent.removed = jest.fn(); chipInstance.removeChip(); fixture.detectChanges(); expect(testComponent.removed).toHaveBeenCalled(); }); test('should not dispatch `selectionChange` event when selecting a selected chip', () => { setup(); chipInstance.select(); const spy = jest.fn(); const subscription = chipInstance.selectionChange.subscribe(spy); chipInstance.select(); expect(spy).not.toHaveBeenCalled(); subscription.unsubscribe(); }); test('should not dispatch `selectionChange` through setter if the value did not change', () => { setup(); chipInstance.selected = false; const spy = jest.fn(); const subscription = chipInstance.selectionChange.subscribe(spy); chipInstance.selected = false; expect(spy).not.toHaveBeenCalled(); subscription.unsubscribe(); }); test('should dispatch `selectionChange` event when deselecting a selected chip', () => { setup(); chipInstance.select(); const spy = jest.fn(); const subscription = chipInstance.selectionChange.subscribe(spy); chipInstance.deselect(); expect(spy).toHaveBeenCalled(); subscription.unsubscribe(); }); test('should not dispatch `selectionChange` event when deselecting a non-selected chip', () => { setup(); chipInstance.deselect(); const spy = jest.fn(); const subscription = chipInstance.selectionChange.subscribe(spy); chipInstance.deselect(); expect(spy).not.toHaveBeenCalled(); subscription.unsubscribe(); }); test(`should toggle selected`, () => { setup(); chipInstance.select(); expect(chipInstance.toggleSelected()).toBeFalsy(); chipInstance.deselect(); expect(chipInstance.toggleSelected()).toBeTruthy(); }); test(`should retrieve the value from the DOM if not explicitly set`, () => { setup(testComponents.ChipNoValue); const cInstance = fixture.debugElement.query(By.directive(TsChipComponent)).componentInstance; expect(cInstance.value).toEqual('banana'); }); }); describe(`keyboard events`, () => { describe(`when not disabled`, () => { beforeEach(() => { setup(); chipInstance.isDisabled = false; chipInstance.isRemovable = true; }); test(`should selects/deselects the currently focused chip on SPACE`, () => { const SPACE_EVENT: KeyboardEvent = createKeyboardEvent('keydown', KEYS.SPACE); const CHIP_SELECTED_EVENT: TsChipSelectionChange = { source: chipInstance, selected: true, }; const CHIP_DESELECTED_EVENT: TsChipSelectionChange = { source: chipInstance, selected: false, }; testComponent.selectionChange = jest.fn(); // Use the spacebar to select the chip chipInstance.handleKeydown(SPACE_EVENT); fixture.detectChanges(); expect(chipInstance.selected).toBeTruthy(); expect(testComponent.selectionChange).toHaveBeenCalledTimes(1); expect(testComponent.selectionChange).toHaveBeenCalledWith(CHIP_SELECTED_EVENT); // Use the spacebar to deselect the chip chipInstance.handleKeydown(SPACE_EVENT); fixture.detectChanges(); expect(chipInstance.selected).toBeFalsy(); expect(testComponent.selectionChange).toHaveBeenCalledTimes(2); expect(testComponent.selectionChange).toHaveBeenCalledWith(CHIP_DESELECTED_EVENT); }); test(`should delete chip on BACKSPACE`, () => { const BACKSPACE_EVENT = createKeyboardEvent('keydown', KEYS.BACKSPACE); testComponent.removed = jest.fn(); // Use backspace to remove the chip chipInstance.handleKeydown(BACKSPACE_EVENT); fixture.detectChanges(); expect(testComponent.removed).toHaveBeenCalled(); }); test(`should delete chip on DELETE`, () => { const DELETE_EVENT = createKeyboardEvent('keydown', KEYS.DELETE); testComponent.removed = jest.fn(); // Use delete to remove the chip chipInstance.handleKeydown(DELETE_EVENT); fixture.detectChanges(); expect(testComponent.removed).toHaveBeenCalled(); }); test(`should not dispatch events on other keys`, () => { const A_EVENT = createKeyboardEvent('keydown', KEYS.A); testComponent.removed = jest.fn(); chipInstance.toggleSelected = jest.fn(); A_EVENT.preventDefault = jest.fn(); chipInstance.handleKeydown(A_EVENT); expect(testComponent.removed).not.toHaveBeenCalled(); expect(chipInstance.toggleSelected).not.toHaveBeenCalled(); expect(A_EVENT.preventDefault).toHaveBeenCalled(); }); }); describe(`when disabled`, () => { test(`should do nothing`, () => { setup(); chipInstance.isDisabled = true; const event = createFakeEvent('delete') as KeyboardEvent; event.preventDefault = jest.fn(); fixture.detectChanges(); chipInstance.handleKeydown(event); expect(event.preventDefault).not.toHaveBeenCalled(); }); }); }); describe(`handle click`, () => { test(`should prevent default if is disabled`, () => { setup(); chipInstance.isDisabled = true; const event = dispatchFakeEvent(chipNativeElement, 'click') as MouseEvent; chipInstance.handleClick(event); fixture.detectChanges(); expect(event.defaultPrevented).toBe(true); }); test(`should stop propagate if is not disabled`, () => { setup(); chipInstance.isDisabled = false; const event = dispatchFakeEvent(chipNativeElement, 'click') as MouseEvent; event.stopPropagation = jest.fn(); chipInstance.handleClick(event); fixture.detectChanges(); expect(event.defaultPrevented).toBe(false); expect(event.stopPropagation).toHaveBeenCalled(); }); }); describe(`tsChipBadge`, () => { test(`should disable interactions`, () => { setup(testComponents.ChipBadge); expect(chipInstance.isFocusable).toEqual(false); expect(chipInstance.isSelectable).toEqual(false); expect(chipInstance.isRemovable).toEqual(false); expect(chipNativeElement.classList).toContain('ts-chip--badge'); }); }); }); });
the_stack
import { Rule, RuleResult, RuleFail, RuleContext, RulePotential, RuleManual, RulePass } from "../../../api/IEngine"; import { RPTUtil, NodeWalker } from "../util/legacy"; let a11yRulesStyle: Rule[] = [ { /** * Description: Trigger on all pages containing CSS (trigger once) * Origin: RPT 5.6 */ id: "RPT_Style_Trigger2", context: "dom:style, dom:link, dom:*[style]", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; let nodeName = ruleContext.nodeName.toLowerCase(); if (nodeName === "link" && (!ruleContext.hasAttribute("rel") || ruleContext.getAttribute("rel").toLowerCase() != "stylesheet")) return RulePass("Pass_0"); if (nodeName != "style" && nodeName != "link" && ruleContext.hasAttribute("style") && ruleContext.getAttribute("style").trim().length == 0) return RulePass("Pass_0"); let triggered = RPTUtil.getCache(ruleContext.ownerDocument, "RPT_Style_Trigger2", false); let passed = triggered; // Packages.java.lang.System.out.println(triggered); RPTUtil.setCache(ruleContext.ownerDocument, "RPT_Style_Trigger2", true); if (passed) return RulePass("Pass_0"); if (!passed) return RuleManual("Manual_1"); } }, { /** * Description: Trigger for use of CSS background images * Origin: RPT 5.6 G456 */ id: "RPT_Style_BackgroundImage", context: "dom:style, dom:*[style]", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; let nodeName = ruleContext.nodeName.toLowerCase(); let passed = true; if (nodeName == "link" && ruleContext.hasAttribute("rel") && ruleContext.getAttribute("rel").toLowerCase() == "stylesheet") { // External stylesheet - trigger passed = RPTUtil.triggerOnce(ruleContext, "RPT_Style_BackgroundImage", false); } if (passed && nodeName == "style" || ruleContext.hasAttribute("style")) { let styleText; if (nodeName == "style") styleText = RPTUtil.getInnerText(ruleContext); else styleText = ruleContext.getAttribute("style"); let bgMatches = styleText.match(/background:[^;]*/g); if (bgMatches != null) { for (let i = 0; passed && i < bgMatches.length; ++i) passed = bgMatches[i].indexOf("url(") == -1; } } if (passed) return RulePass("Pass_0"); if (!passed) return RulePotential("Potential_1"); } }, { /** * Description: Trigger when color is used, but has no semantic meaning. * Origin: RPT 5.6 G466 Error */ id: "RPT_Style_ColorSemantics1", context: "dom:style, dom:*[style], dom:font[color], dom:link", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; let nodeName = ruleContext.nodeName.toLowerCase(); let styleText = ""; if (nodeName == "style") { styleText = RPTUtil.getInnerText(ruleContext).toLowerCase(); // check import for (let sIndex = 0; sIndex < ruleContext.ownerDocument.styleSheets.length; sIndex++) { let sheet = ruleContext.ownerDocument.styleSheets[sIndex] as CSSStyleSheet; if (sheet && sheet.ownerNode == ruleContext) { try { let styleRules = sheet.cssRules ? sheet.cssRules : sheet.rules; for (let styleRuleIndex = 0; styleRuleIndex < styleRules.length; styleRuleIndex++) { let styleRule = styleRules[styleRuleIndex]; let styleImportRule: CSSImportRule; if (styleRule.type && styleRule.type === CSSRule.IMPORT_RULE && (styleImportRule = styleRule as CSSImportRule).styleSheet) { let importRules = styleImportRule.styleSheet.cssRules ? styleImportRule.styleSheet.cssRules : styleImportRule.styleSheet.rules; for (let rIndex = 0; rIndex < importRules.length; rIndex++) { let iRule = importRules[rIndex]; styleText += iRule.cssText; } } } } catch (e) { // Silence css access issues } } } } else if (ruleContext.hasAttribute("style")) { styleText = ruleContext.getAttribute("style").toLowerCase(); } else if (nodeName == "link" && //check external styles ruleContext.hasAttribute("rel") && ruleContext.getAttribute("rel").toLowerCase() == "stylesheet" && ruleContext.hasAttribute("href") && ruleContext.getAttribute("href").trim().length !== 0) { for (let sIndex = 0; sIndex < ruleContext.ownerDocument.styleSheets.length; sIndex++) { let sheet = ruleContext.ownerDocument.styleSheets[sIndex] as CSSStyleSheet; if (sheet && sheet.ownerNode === ruleContext) { try { let rules = sheet.cssRules ? sheet.cssRules : sheet.rules; for (let rIndex = 0; rIndex < rules.length; rIndex++) { styleText += rules[rIndex].cssText; } } catch (e) { // Silence css access issues } } } } let passed = true; // Defect 1022: Find uses of 'color' and '*background*' only let isBgUsed = styleText.match(/\bbackground\b/i); let theColorStyleToCheck = styleText.replace(/-color/g, ""); let isColorUsed = theColorStyleToCheck.match(/\bcolor\b/i); if (ruleContext.hasAttribute("color") || isColorUsed || isBgUsed) { let goodTagNames = { "em": "", "strong": "", "cite": "", "dfn": "", "code": "", "samp": "", "kbd": "", "var": "", "abbr": "", "acronym": "" } // Color used � are there semantics involved? passed = nodeName in goodTagNames || RPTUtil.getAncestor(ruleContext, goodTagNames) != null; if (!passed && ruleContext.hasChildNodes()) { let nw = new NodeWalker(ruleContext); while (!passed && nw.nextNode() && nw.node != ruleContext) { passed = nw.node.nodeName.toLowerCase() in goodTagNames; } } } // Trigger only once if (!passed) { let triggered = RPTUtil.getCache(ruleContext.ownerDocument, "RPT_Style_ColorSemantics1", false); passed = triggered; RPTUtil.setCache(ruleContext.ownerDocument, "RPT_Style_ColorSemantics1", true); } if (passed) return RulePass("Pass_0"); if (!passed) return RulePotential("Potential_1"); } }, { /** * Description: Trigger when color is used, but has no semantic meaning. * Origin: Various */ id: "RPT_Style_ExternalStyleSheet", context: "dom:link[rel], dom:style", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; let passed = true; let nodeName = ruleContext.nodeName.toLowerCase(); if (nodeName == "style") { passed = RPTUtil.getInnerText(ruleContext).indexOf("@import url") == -1; } else if (nodeName == "link") { passed = !ruleContext.hasAttribute("rel") || ruleContext.getAttribute("rel").toLowerCase() != "stylesheet"; } return passed ? RulePass("Pass_0") : RulePotential("Potential_1"); } }, { /** * Description: Trigger on CSS that affects the focus box * Origin: RPT 5.6 G506 Error */ id: "RPT_Style_HinderFocus1", context: "dom:style, dom:*[style]", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const validateParams = { skipNodes: { value: ["table"], type: "[string]" }, regex1: { value: /(^|})([^{]*){[^}]*(outline|border)[ \t]*\:/gi, type: "regex" }, regex2: { value: /([a-z]+)[ \t]*(,|$)/gi, type: "regex" } } const ruleContext = context["dom"].node as Element; let skipNodes = validateParams.skipNodes.value; let passed = true; // Note: link to be handled by RPT_Style_ExternalStyleSheet let nodeName = ruleContext.nodeName.toLowerCase(); if (nodeName == "style") { let textValue = RPTUtil.getInnerText(ruleContext); let r = validateParams.regex1.value; r.lastIndex = 0; let m; let m2; while (passed && (m = r.exec(textValue)) != null) { let selector = m[2]; let r2 = validateParams.regex2.value; r2.lastIndex = 0; while (passed && (m2 = r2.exec(selector)) != null) { passed = skipNodes.includes(m2[1].trim().toLowerCase()); } } } else if (!ruleContext.hasAttribute("disabled") || ruleContext.getAttribute("disabled").toLowerCase() == "false") { let textValue = ruleContext.getAttribute('style'); passed = skipNodes.includes(nodeName) || !(/(outline|border)[ \t]*\:/.test(textValue)); } if (passed) return RulePass("Pass_0"); if (!passed) return RulePotential("Potential_1"); } }, { /** * Description: Trigger if :before and :after are used in CSS (Internal and External) with content * Origin: WCAG 2.0 F87 */ id: "WCAG20_Style_BeforeAfter", context: "dom:style, dom:link", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; let passed = true; //check Internal styles if (ruleContext.nodeName.toLowerCase() == "style") { let css = RPTUtil.CSS(ruleContext); for (let i = 0; passed && i < css.length; ++i) { // Guard against bad CSS if (css[i].selector) { passed = (css[i].selector.indexOf(":before") == -1 && css[i].selector.indexOf(":after") == -1) || !("content" in css[i].values) || css[i].values["content"].trim().length == 0 || css[i].values["content"].trim() == "\"\"" || css[i].values["content"].trim() == "\'\'" || css[i].values["content"].trim() == "none" || css[i].values["content"].trim() == "attr(x)" || css[i].values["content"].trim() == "attr(y)"; } } // check special rules in the stylesheets if (passed) { for (let sIndex = 0; sIndex < ruleContext.ownerDocument.styleSheets.length; sIndex++) { let sheet = ruleContext.ownerDocument.styleSheets[sIndex] as CSSStyleSheet; if (sheet.ownerNode === ruleContext) { try { let styleRules = sheet.cssRules ? sheet.cssRules : sheet.rules; if (styleRules) { for (let styleRuleIndex = 0; passed && styleRuleIndex < styleRules.length; styleRuleIndex++) { let styleRule = styleRules[styleRuleIndex]; // check @media rules // // The check 'if (styleRule instanceof CSSMediaRule)' doesn't work when run in Karma(but works in DAP) // so let's access the type directly as a workaround let styleMediaRule: CSSMediaRule; let styleImportRule: CSSImportRule; if (styleRule.type && styleRule.type === CSSRule.MEDIA_RULE) { let styleMediaRule = styleRule as CSSMediaRule; let mediaRules = styleMediaRule.cssRules; if (mediaRules) { for (let rIndex = 0; passed && rIndex < mediaRules.length; rIndex++) { let mRule = mediaRules[rIndex] as any; // selectorText not recognized if (mRule.selectorText !== null && mRule.selectorText !== undefined) { let rule = mRule.selectorText.toLowerCase(); if (rule.indexOf(":before") !== -1 || rule.indexOf(":after") !== -1) { let content = mRule.style['content']; if (content && content.trim().length) { if (content.trim() !== "\"\"" && content.trim() !== "\'\'" && content.trim() !== "none" && content.trim() !== "attr(x)" && content.trim() !== "attr(y)") { passed = false; } } } } } } } // check import rules else if (styleRule.type && styleRule.type === CSSRule.IMPORT_RULE && (styleImportRule = styleRule as CSSImportRule).styleSheet) { let rules = styleImportRule.styleSheet.cssRules ? styleImportRule.styleSheet.cssRules : styleImportRule.styleSheet.rules; if (rules) { for (let rIndex = 0; passed && rIndex < rules.length; rIndex++) { let importedRule = rules[rIndex]; // check @media rules if (importedRule.type && importedRule.type === CSSRule.MEDIA_RULE) { let mediaRules = (importedRule as CSSMediaRule).cssRules; if (mediaRules) { for (let mIndex = 0; mIndex < mediaRules.length; mIndex++) { let mRule = mediaRules[mIndex] as any; // selectorText not recognized if (mRule.selectorText !== null && mRule.selectorText !== undefined) { let rule = mRule.selectorText.toLowerCase(); if (rule.indexOf(":before") !== -1 || rule.indexOf(":after") !== -1) { let content = mRule.style['content']; if (content && content.trim().length) { if (content.trim() !== "\"\"" && content.trim() !== "\'\'" && content.trim() !== "none" && content.trim() !== "attr(x)" && content.trim() !== "attr(y)") { passed = false; } } } } } } } else if ((importedRule as any).selectorText !== null && (importedRule as any).selectorText !== undefined) { let rule = (importedRule as any).selectorText.toLowerCase(); //support both single colon (:) and double colon (::) pseudo if (rule.indexOf(":before") !== -1 || rule.indexOf(":after") !== -1) { let content = (importedRule as any).style['content']; if (content && content.trim().length) { if (content.trim() !== "\"\"" && content.trim() !== "\'\'" && content.trim() !== "none" && content.trim() !== "attr(x)" && content.trim() !== "attr(y)") { passed = false; } } } } } } } } } } catch (e) { // Ignore css access issues } } } } } //check external styles if (ruleContext.nodeName.toLowerCase() == "link" && ruleContext.hasAttribute("rel") && ruleContext.getAttribute("rel").toLowerCase() == "stylesheet" && ruleContext.hasAttribute("href") && ruleContext.getAttribute("href").trim().length !== 0) { for (let sIndex = 0; sIndex < ruleContext.ownerDocument.styleSheets.length; sIndex++) { let sheet = ruleContext.ownerDocument.styleSheets[sIndex] as CSSStyleSheet; if (sheet && sheet.ownerNode === ruleContext) { try { let rules = sheet.cssRules ? sheet.cssRules : sheet.rules; if (rules) { for (let rIndex = 0; passed && rIndex < rules.length; rIndex++) { let ruleFromLink = rules[rIndex]; // check @media rules if (ruleFromLink.type && ruleFromLink.type === CSSRule.MEDIA_RULE) { let mediaRules = (ruleFromLink as CSSMediaRule).cssRules; if (mediaRules) { for (let mIndex = 0; passed && mIndex < mediaRules.length; mIndex++) { let mRule = mediaRules[mIndex] as any; if (mRule.selectorText !== null && mRule.selectorText !== undefined) { let ruleSelTxt = mRule.selectorText.toLowerCase(); if (ruleSelTxt.indexOf(":before") !== -1 || ruleSelTxt.indexOf(":after") !== -1) { let content = mRule.style['content']; if (content && content.trim().length) { if (content.trim() !== "\"\"" && content.trim() !== "\'\'" && content.trim() !== "none" && content.trim() !== "attr(x)" && content.trim() !== "attr(y)") { passed = false; } } } } } } } else if ((rules[rIndex] as any).selectorText !== null && (rules[rIndex] as any).selectorText !== undefined) { let rule = (rules[rIndex] as any).selectorText.toLowerCase(); //support both single colon (:) and double colon (::) pseudo if (rule.indexOf(":before") !== -1 || rule.indexOf(":after") !== -1) { let content = (rules[rIndex] as any).style['content']; if (content && content.trim().length) { if (content.trim() !== "\"\"" && content.trim() !== "\'\'" && content.trim() !== "none" && content.trim() !== "attr(x)" && content.trim() !== "attr(y)") { passed = false; } } } } } } } catch (e) { // Ignore css access issues } } } } if (passed) return RulePass("Pass_0"); if (!passed) return RulePotential("Potential_1"); } }, { /** * Description: Trigger when viewport units are used for font size. * Origin: Various */ id: "WCAG21_Style_Viewport", context: "dom:link, dom:style, dom:*[style]", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; let passed = true; let thePattern = /\d+(vw|vh|vmin|vmax)/gi; let nodeName = ruleContext.nodeName.toLowerCase(); if (nodeName == "style") { for (let sIndex = 0; sIndex < ruleContext.ownerDocument.styleSheets.length; sIndex++) { let sheet = ruleContext.ownerDocument.styleSheets[sIndex] as CSSStyleSheet if (sheet.ownerNode === ruleContext) { try { let styleRules = sheet.cssRules ? sheet.cssRules : sheet.rules; if (styleRules) { for (let styleRuleIndex = 0; passed && styleRuleIndex < styleRules.length; styleRuleIndex++) { let rule = styleRules[styleRuleIndex]; if (rule.type && rule.type === CSSRule.STYLE_RULE) { let styleRule = rule as CSSStyleRule; if (styleRule.style['fontSize']) { let fontSize = styleRule.style['fontSize'].trim(); let found = fontSize.match(thePattern); if (fontSize.length && found) { passed = false; } } } // check import rules else if (rule.type && rule.type === CSSRule.IMPORT_RULE && (rule as CSSImportRule).styleSheet) { let importRule = rule as CSSImportRule; let rules = importRule.styleSheet.cssRules ? importRule.styleSheet.cssRules : importRule.styleSheet.rules; if (rules) { for (let rIndex = 0; passed && rIndex < rules.length; rIndex++) { let importedRule = rules[rIndex] as any if (importedRule.type && importedRule.type === CSSRule.STYLE_RULE) { if (importedRule.style['fontSize']) { let fontSize = importedRule.style['fontSize'].trim(); let found = fontSize.match(thePattern); if (fontSize.length && found) { passed = false; } } } } } } } } } catch (e) { // Ignore css access issues } } } } else if (nodeName == "link") { for (let sIndex = 0; sIndex < ruleContext.ownerDocument.styleSheets.length; sIndex++) { let sheet = ruleContext.ownerDocument.styleSheets[sIndex] as CSSStyleSheet; if (sheet && sheet.ownerNode === ruleContext) { try { let rules = sheet.cssRules ? sheet.cssRules : sheet.rules; if (rules) { for (let rIndex = 0; passed && rIndex < rules.length; rIndex++) { let ruleFromLink = rules[rIndex] as any; // check rules if (ruleFromLink.type && ruleFromLink.type === CSSRule.STYLE_RULE) { if (ruleFromLink.style['fontSize']) { let fontSize = ruleFromLink.style['fontSize'].trim(); let found = fontSize.match(thePattern); if (fontSize.length && found) { passed = false; } } } } } } catch (e) { // Ignore css access issues } } } } else { let styleValue = ruleContext.getAttribute('style'); if (styleValue) { let stylePattern = /font-size:\s*\d+(vw|vh|vmin|vmax)/gi; let found = styleValue.match(stylePattern); if (found) { passed = false; } } } return passed ? RulePass("Pass_0") : RulePotential("Potential_1"); } } ] export { a11yRulesStyle }
the_stack
import {X64} from "../../index"; import { ah, al, ax, bl, bpl, bx, ch, cl, cx, dil, dl, eax, ebx, ecx, esp, r10b, r12, r13, r15, r8b, r9, rax, rbp, rbx, rcx, rdx, rsp, spl } from "../../plugins/x86/operand/generator"; describe('Binary Arithmetic', function() { describe('adcx', function () { it('adcx rcx, rbx', function () { // 66 48 0f 38 f6 cb adcx %rbx,%rcx const _ = X64(); _._('adcx', [rcx, rbx]); const bin = _.compile([]); // console.log(new Buffer(bin)); expect(bin).toEqual([0x66, 0x48, 0x0F, 0x38, 0xF6, 0xCB]); }); it('adcx rax, rax', function () { // 66 48 0f 38 f6 c0 adcx %rax,%rax const _ = X64(); _._('adcx', [rax, rax]); const bin = _.compile([]); expect(bin).toEqual([0x66, 0x48, 0x0F, 0x38, 0xF6, 0xC0]); }); }); describe('adox', function () { it('adox r12, r9', function () { // f3 4d 0f 38 f6 e1 adox %r9,%r12 const _ = X64(); _._('adox', [r12, r9]); const bin = _.compile([]); expect(bin).toEqual([0xF3, 0x4D, 0x0F, 0x38, 0xF6, 0xE1]); }); }); describe('add', function () { it('add rax, 0x19', function () { // 48 83 c0 19 add $0x19,%rax const _ = X64(); _._('add', [rax, 0x19]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x83, 0xC0, 0x19]); }); it('add rax, rax', function () { // 48 01 c0 add %rax,%rax const _ = X64(); _._('add', [rax, rax]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x01, 0xC0]); }); it('add rbx, rsp', function () { // 48 01 e3 add %rsp,%rbx const _ = X64(); _._('add', [rbx, rsp]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x01, 0xE3]); }); it('add rcx, [rbx]', function () { // 48 03 0b add (%rbx),%rcx const _ = X64(); _._('add', [rcx, rbx.ref()]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x03, 0x0B]); }); it('add rcx, [rcx + rdx]', function () { // 48 03 0c 11 add (%rcx,%rdx,1),%rcx const _ = X64(); _._('add', [rcx, rcx.ref().ind(rdx)]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x03, 0x0C, 0x11]); }); it('add rcx, [rcx + rbp * 4]', function () { // 48 03 0c a9 add (%rcx,%rbp,4),%rcx const _ = X64(); _._('add', [rcx, rcx.ref().ind(rbp, 4)]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x03, 0x0C, 0xA9]); }); it('add rcx, [rsp + rbp * 4 + 0x11]', function () { // 48 03 4c ac 11 add 0x11(%rsp,%rbp,4),%rcx const _ = X64(); _._('add', [rcx, rsp.ref().ind(rbp, 4).disp(0x11)]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x03, 0x4C, 0xAC, 0x11]); }); it('add rcx, [rsp + rbp * 4 + -0x11223344]', function () { // 48 03 8c ac bc cc dd ee add -0x11223344(%rsp,%rbp,4),%rcx const _ = X64(); _._('add', [rcx, rsp.ref().ind(rbp, 4).disp(-0x11223344)]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x03, 0x8C, 0xAC, 0xBC, 0xCC, 0xDD, 0xEE]); }); it('add [rsp + rbp * 4 + -0x11223344], rax', function () { // 48 01 84 ac bc cc dd ee add %rax,-0x11223344(%rsp,%rbp,4) const _ = X64(); _._('add', [rsp.ref().ind(rbp, 4).disp(-0x11223344), rax]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x01, 0x84, 0xAC, 0xBC, 0xCC, 0xDD, 0xEE]); }); it('add rbx, 1', function () { // 48 83 c3 01 add $0x1,%rbx const _ = X64(); _._('add', [rbx, 1]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x83, 0xC3, 0x01]); }); it('add rbx, [1]', function () { // 48 03 1c 25 01 00 00 00 add 0x1,%rbx const _ = X64(); _._('add', [rbx, _._('mem', 1)]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x03, 0x1C, 0x25, 0x01, 0, 0, 0]); }); it('add [1], rbx', function () { // 48 01 1c 25 01 00 00 00 add %rbx,0x1 const _ = X64(); _._('add', [_._('mem', 1), rbx]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x01, 0x1C, 0x25, 0x01, 0, 0, 0]); }); it('add al, 0x11', function () { // 04 11 add $0x11,%al const _ = X64(); _._('add', [al, 0x11]); const bin = _.compile([]); expect(bin).toEqual([0x04, 0x11]); }); it('add ax, 0x1122', function () { // 66 05 22 11 add $0x1122,%ax const _ = X64(); _._('add', [ax, 0x1122]); const bin = _.compile([]); expect(bin).toEqual([0x66, 0x05, 0x22, 0x11]); }); it('add eax, 0x11223344', function () { // 05 44 33 22 11 add $0x11223344,%eax const _ = X64(); _._('add', [eax, 0x11223344]); const bin = _.compile([]); expect(bin).toEqual([0x05, 0x44, 0x33, 0x22, 0x11]); }); it('add rax, -0x11223344', function () { // 48 05 bc cc dd ee add $-0x11223344, %rax const _ = X64(); _._('add', [rax, -0x11223344]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x05, 0xbc, 0xcc, 0xdd, 0xee]); }); it('add bl, 0x22', function () { // 80 c3 22 add $0x22,%bl const _ = X64(); _._('add', [bl, 0x22]); const bin = _.compile([]); expect(bin).toEqual([0x80, 0xc3, 0x22]); }); it('add ah, 0x22', function () { // 80 c4 22 add $0x22,%ah const _ = X64(); _._('add', [ah, 0x22]); const bin = _.compile([]); expect(bin).toEqual([0x80, 0xc4, 0x22]); }); it('add bx, 0x1122', function () { // 66 81 c3 22 11 add $0x1122,%bx const _ = X64(); _._('add', [bx, 0x1122]); const bin = _.compile([]); expect(bin).toEqual([0x66, 0x81, 0xC3, 0x22, 0x11]); }); it('add bx, 0x11', function () { // 66 83 c3 11 add $0x11,%bx const _ = X64(); _._('add', [bx, 0x11]); const bin = _.compile([]); expect(bin).toEqual([0x66, 0x83, 0xC3, 0x11]); }); it('add ebx, 0x1122', function () { // 81 c3 22 11 00 00 add $0x1122,%ebx const _ = X64(); _._('add', [ebx, 0x1122]); const bin = _.compile([]); expect(bin).toEqual([0x81, 0xC3, 0x22, 0x11, 0, 0]); }); it('add ch, 0x22', function () { // 80 c5 22 add $0x22,%ch const _ = X64(); _._('add', [ch, 0x22]); const bin = _.compile([]); expect(bin).toEqual([0x80, 0xC5, 0x22]); }); it('add dil, 0x22', function () { // 40 80 c7 22 add $0x22,%dil const _ = X64(); _._('add', [dil, 0x22]); const bin = _.compile([]); expect(bin).toEqual([0x40, 0x80, 0xC7, 0x22]); }); it('add bpl, 0x22', function () { // 40 80 c5 22 add $0x22,%bpl const _ = X64(); _._('add', [bpl, 0x22]);; const bin = _.compile([]); expect(bin).toEqual([0x40, 0x80, 0xC5, 0x22]); }); it('add spl, 0x22', function () { // 40 80 c4 22 add $0x22,%spl const _ = X64(); _._('add', [spl, 0x22]); const bin = _.compile([]); expect(bin).toEqual([0x40, 0x80, 0xC4, 0x22]); }); it('add r8b, 0x22', function () { // 41 80 c0 22 add $0x22,%r8b const _ = X64(); _._('add', [r8b, 0x22]); const bin = _.compile([]); expect(bin).toEqual([0x41, 0x80, 0xC0, 0x22]); }); it('add esp, 0x12', function () { // 83 c4 12 add $0x12,%esp const _ = X64(); _._('add', [esp, 0x12]); const bin = _.compile([]); expect(bin).toEqual([0x83, 0xC4, 0x12]); }); it('add dl, cl', function () { // 00 ca add %cl,%dl const _ = X64(); _._('add', [dl, cl]); const bin = _.compile([]); expect(bin).toEqual([0x00, 0xCA]); }); it('add bx, ax', function () { // 66 01 c3 add %ax,%bx const _ = X64(); _._('add', [bx, ax]); const bin = _.compile([]); expect(bin).toEqual([0x66, 0x01, 0xC3]); }); it('add ecx, eax', function () { // 01 c1 add %eax,%ecx const _ = X64(); _._('add', [ecx, eax]); const bin = _.compile([]); expect(bin).toEqual([0x01, 0xC1]); }); }); describe('adc', function() { it('adc [rbx + rcx * 4 + 0x11], rax', function() {// 48 11 44 8b 11 adc %rax,0x11(%rbx,%rcx,4) const _ = X64(); _._('adc', [rbx.ref().ind(rcx, 4).disp(0x11), rax]); expect(_.compile([])).toEqual([0x48, 0x11, 0x44, 0x8B, 0x11]); }); }); describe('mul', function() { it('mul al', function() {// 400580: f6 e0 mul %al const _ = X64(); _._('mul', al); expect(_.compile([])).toEqual([0xf6, 0xe0]); }); it('mul ax', function() {// 66 f7 e0 mul %ax const _ = X64(); _._('mul', ax); expect(_.compile([])).toEqual([0x66, 0xf7, 0xe0]); }); it('mul eax', function() {// f7 e0 mul %eax const _ = X64(); _._('mul', eax); expect(_.compile([])).toEqual([0xf7, 0xe0]); }); it('mul rax', function() {// 48 f7 e0 mul %rax const _ = X64(); _._('mul', rax); expect(_.compile([])).toEqual([0x48, 0xf7, 0xe0]); }); it('mulq [rax]', function() {// 48 f7 20 mulq (%rax) const _ = X64(); _._('mul', rax.ref(), 64); expect(_.compile([])).toEqual([0x48, 0xf7, 0x20]); }); it('mulq [eax]', function() {// 67 48 f7 20 mulq (%eax) const _ = X64(); _._('mul', eax.ref(), 64); expect(_.compile([])).toEqual([0x67, 0x48, 0xf7, 0x20]); }); it('muld [rax]', function() {// f7 20 mull (%rax) const _ = X64(); _._('mul', rax.ref(), 32); expect(_.compile([])).toEqual([0xf7, 0x20]); }); it('muld [eax]', function() {// 67 f7 20 mull (%eax) const _ = X64(); _._('mul', eax.ref(), 32); expect(_.compile([])).toEqual([0x67, 0xf7, 0x20]); }); it('mulw [rax]', function() {// 66 f7 20 mulw (%rax) const _ = X64(); _._('mul', rax.ref(), 16); expect(_.compile([])).toEqual([0x66, 0xf7, 0x20]); }); it('mulw [eax]', function() {// 67 66 f7 20 mulw (%eax) const _ = X64(); _._('mul', eax.ref(), 16); expect(_.compile([])).toEqual([0x67, 0x66, 0xf7, 0x20]); }); it('mulb [rax]', function() {// f6 20 mulb (%rax) const _ = X64(); _._('mul', rax.ref(), 8); expect(_.compile([])).toEqual([0xf6, 0x20]); }); it('mulb [eax]', function() {// 67 f6 20 mulb (%eax) const _ = X64(); _._('mul', eax.ref(), 8); expect(_.compile([])).toEqual([0x67, 0xf6, 0x20]); }); }); describe('div', function() { it('div bl', function() {// f6 f3 div %bl const _ = X64(); _._('div', bl); expect(_.compile([])).toEqual([0xf6, 0xF3]); }); it('div bx', function() {// 66 f7 f3 div %bx const _ = X64(); _._('div', bx); expect(_.compile([])).toEqual([0x66, 0xf7, 0xF3]); }); it('div ebx', function() {// f7 f3 div %ebx const _ = X64(); _._('div', ebx); expect(_.compile([])).toEqual([0xf7, 0xF3]); }); it('div rbx', function() {// 48 f7 f3 div %rbx const _ = X64(); _._('div', rbx); expect(_.compile([])).toEqual([0x48, 0xf7, 0xF3]); }); }); describe('inc', function() { it('incq rbx', function() { const _ = X64(); _._('inc', rbx, 64); expect(_.compile([])).toEqual([0x48, 0xff, 0xc3]); }); it('incq [rax]', function() { const _ = X64(); _._('inc', rax.ref(), 64); expect(_.compile([])).toEqual([0x48, 0xff, 0x00]); }); it('incq [rbx]', function() { const _ = X64(); _._('inc', rbx.ref(), 64); expect(_.compile([])).toEqual([0x48, 0xff, 0x03]); }); it('incq [rbx + rcx]', function() { const _ = X64(); _._('inc', rbx.ref().ind(rcx), 64); expect(_.compile([])).toEqual([0x48, 0xff, 0x04, 0x0b]); }); it('incq [rbx + rcx * 8]', function() { const _ = X64(); _._('inc', rbx.ref().ind(rcx, 8), 64); expect(_.compile([])).toEqual([0x48, 0xff, 0x04, 0xcb]); }); it('incq [rax + rbx * 8 + 0x11]', function() { const _ = X64(); _._('inc', rax.ref().ind(rbx, 8).disp(0x11), 64); expect(_.compile([])).toEqual([0x48, 0xff, 0x44, 0xd8, 0x11]); }); it('incq [rax + rbx * 8 + -0x11223344]', function() { const _ = X64(); const ins = _._('inc', rax.ref().ind(rbx, 8).disp(-0x11223344), 64); expect(_.compile([])).toEqual([0x48, 0xff, 0x84, 0xd8, 0xbc, 0xcc, 0xdd, 0xee]); }); it('incq [rbx + r15 * 8 + -0x123]', function() { const _ = X64(); const ins = _._('inc', rbx.ref().ind(r15, 8).disp(-0x123), 64); expect(_.compile([])).toEqual([0x4a, 0xff, 0x84, 0xfb, 0xdd, 0xfe, 0xff, 0xff]); }); it('incq [rbp + rbp * 8]', function() { const _ = X64(); const ins = _._('inc', rbp.ref().ind(rbp, 8), 64); expect(_.compile([])).toEqual([0x48, 0xff, 0x44, 0xed, 0x00]); }); it('incq [rbp]', function() { const _ = X64(); const ins = _._('inc', rbp.ref(), 64); expect(_.compile([])).toEqual([0x48, 0xff, 0x45, 0x00]); }); it('incq [rsp]', function() { const _ = X64(); const ins = _._('inc', rsp.ref(), 64); expect(_.compile([])).toEqual([0x48, 0xff, 0x04, 0x24]); }); it('incq [r12]', function() { const _ = X64(); const ins = _._('inc', r12.ref(), 64); expect(_.compile([])).toEqual([0x49, 0xff, 0x04, 0x24]); }); it('incq [r13]', function() { const _ = X64(); const ins = _._('inc', r13.ref(), 64); expect(_.compile([])).toEqual([0x49, 0xff, 0x45, 0x00]); }); it('incq r15', function() { const _ = X64(); const ins = _._('inc', r15, 64); expect(_.compile([])).toEqual([0x49, 0xff, 0xc7]); }); it('incq [0x11]', function() { const _ = X64(); const ins = _._('inc', _._('mem', 0x11), 64); expect(_.compile([])).toEqual([0x48, 0xff, 0x04, 0x25, 0x11, 0x00, 0x00, 0x00]); }); it('incq [0x11223344]', function() { const _ = X64(); const ins = _._('inc', _._('mem', 0x11223344), 64); expect(_.compile([])).toEqual([0x48, 0xff, 0x04, 0x25, 0x44, 0x33, 0x22, 0x11]); }); }); describe('dec', function() { it('decq rbx', function () { const _ = X64(); _._('dec', rax, 64); expect(_.compile([])).toEqual([0x48, 0xff, 0xc8]); }); it('dec r10b', function () { // 41 fe ca dec %r10b const _ = X64(); _._('dec', r10b); expect(_.compile([])).toEqual([0x41, 0xFE, 0xCA]); }); it('dec ax', function () { // 66 ff c8 dec %ax const _ = X64(); _._('dec', ax); expect(_.compile([])).toEqual([0x66, 0xFF, 0xC8]); }); it('dec eax', function () { // ff c8 dec %eax const _ = X64(); _._('dec', eax); expect(_.compile([])).toEqual([0xFF, 0xC8]); }); it('dec rax', function () { // 48 ff c8 dec %rax const _ = X64(); _._('dec', rax); expect(_.compile([])).toEqual([0x48, 0xFF, 0xC8]); }); }); describe('neg', function () { it('neg al', function () { // f6 d8 neg %al const _ = X64(); _._('neg', al); const bin = _.compile([]); expect(bin).toEqual([0xF6, 0xD8]); }); it('neg dil', function () { // 40 f6 df neg %dil const _ = X64(); _._('neg', dil); const bin = _.compile([]); expect(bin).toEqual([0x40, 0xF6, 0xDF]); }); it('neg bx', function () { // 66 f7 db neg %bx const _ = X64(); _._('neg', bx); const bin = _.compile([]); expect(bin).toEqual([0x66, 0xF7, 0xDB]); }); it('neg ecx', function () { // f7 d9 neg %ecx const _ = X64(); _._('neg', ecx); const bin = _.compile([]); expect(bin).toEqual([0xF7, 0xD9]); }); it('neg rdx', function () { // 48 f7 da neg %rdx const _ = X64(); _._('neg', rdx); const bin = _.compile([]); expect(bin).toEqual([0x48, 0xF7, 0xDA]); }); }); describe('cmp', function () { it('cmp al, 0x11', function () { // 3c 11 cmp $0x11,%al const _ = X64(); _._('cmp', [al, 0x11]); const bin = _.compile([]); expect(bin).toEqual([0x3C, 0x11]); }); it('cmp ax, 0x1122', function () { // 66 3d 22 11 cmp $0x1122,%ax const _ = X64(); _._('cmp', [ax, 0x1122]); const bin = _.compile([]); expect(bin).toEqual([0x66, 0x3D, 0x22, 0x11]); }); it('cmp eax, 0x11223344', function () { // 3d 44 33 22 11 cmp $0x11223344,%eax const _ = X64(); _._('cmp', [eax, 0x11223344]); const bin = _.compile([]); expect(bin).toEqual([0x3D, 0x44, 0x33, 0x22, 0x11]); }); it('cmp rax, 0x11223344', function () { // 48 3d 44 33 22 11 cmp $0x11223344,%rax const _ = X64(); _._('cmp', [rax, 0x11223344]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x3D, 0x44, 0x33, 0x22, 0x11]); }); it('cmp bl, 0x11', function () { // 80 fb 11 cmp $0x11,%bl const _ = X64(); _._('cmp', [bl, 0x11]); const bin = _.compile([]); expect(bin).toEqual([0x80, 0xFB, 0x11]); }); it('cmp bx, 0x1122', function () { // 66 81 fb 22 11 cmp $0x1122,%bx const _ = X64(); _._('cmp', [bx, 0x1122]); const bin = _.compile([]); expect(bin).toEqual([0x66, 0x81, 0xFB, 0x22, 0x11]); }); it('cmp ebx, 0x11223344', function () { // 81 fb 44 33 22 11 cmp $0x11223344,%ebx const _ = X64(); _._('cmp', [ebx, 0x11223344]); const bin = _.compile([]); expect(bin).toEqual([0x81, 0xFB, 0x44, 0x33, 0x22, 0x11]); }); it('cmp rbx, 0x11223344', function () { // 48 81 fb 44 33 22 11 cmp $0x11223344,%rbx const _ = X64(); _._('cmp', [rbx, 0x11223344]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x81, 0xFB, 0x44, 0x33, 0x22, 0x11]); }); it('cmp cx, 0x11', function () { // 66 83 f9 11 cmp $0x11,%cx const _ = X64(); _._('cmp', [cx, 0x11]); const bin = _.compile([]); expect(bin).toEqual([0x66, 0x83, 0xF9, 0x11]); }); it('cmp ecx, 0x11', function () { // 83 f9 11 cmp $0x11,%ecx const _ = X64(); _._('cmp', [ecx, 0x11]); const bin = _.compile([]); expect(bin).toEqual([0x83, 0xF9, 0x11]); }); it('cmp rcx, 0x11', function () { // 48 83 f9 11 cmp $0x11,%rcx const _ = X64(); _._('cmp', [rcx, 0x11]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x83, 0xF9, 0x11]); }); it('cmp al, bl', function () { // 38 d8 cmp %bl,%al const _ = X64(); _._('cmp', [al, bl]); const bin = _.compile([]); expect(bin).toEqual([0x38, 0xD8]); }); it('cmp ax, bx', function () { // 66 39 d8 cmp %bx,%ax const _ = X64(); _._('cmp', [ax, bx]); const bin = _.compile([]); expect(bin).toEqual([0x66, 0x39, 0xD8]); }); it('cmp ebx, eax', function () { // 39 c3 cmp %eax,%ebx const _ = X64(); _._('cmp', [ebx, eax]); const bin = _.compile([]); expect(bin).toEqual([0x39, 0xC3]); }); it('cmp rbx, rax', function () { // 48 39 c3 cmp %rax,%rbx const _ = X64(); _._('cmp', [rbx, rax]); const bin = _.compile([]); expect(bin).toEqual([0x48, 0x39, 0xC3]); }); }); });
the_stack
import { Argument } from '../Argument'; import { Expression } from '../Expression'; import { mXparserConstants } from '../mXparserConstants'; import { mXparser } from '../mXparser'; import { ProbabilityDistributions } from './ProbabilityDistributions'; import { MathFunctions } from './MathFunctions'; import { javaemul } from 'j4ts/j4ts'; /** * Calculus - numerical integration, differentiation, etc... * * @author <b>Mariusz Gromada</b><br> * <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * * @version 4.3.0 * @class */ export class Calculus { /** * Derivative type specification */ public static LEFT_DERIVATIVE: number = 1; public static RIGHT_DERIVATIVE: number = 2; public static GENERAL_DERIVATIVE: number = 3; /** * Trapezoid numerical integration * * @param {Expression} f the expression * @param {Argument} x the argument * @param {number} a form a ... * @param {number} b ... to b * @param {number} eps the epsilon (error) * @param {number} maxSteps the maximum number of steps * * @return {number} Integral value as double. * * @see Expression */ public static integralTrapezoid(f: Expression, x: Argument, a: number, b: number, eps: number, maxSteps: number): number { let h: number = 0.5 * (b - a); let s: number = mXparser.getFunctionValue(f, x, a) + mXparser.getFunctionValue(f, x, b) + 2 * mXparser.getFunctionValue(f, x, a + h); let intF: number = s * h * 0.5; let intFprev: number = 0; let t: number = a; let i: number; let j: number; let n: number = 1; for(i = 1; i <= maxSteps; i++) {{ n += n; t = a + 0.5 * h; intFprev = intF; for(j = 1; j <= n; j++) {{ if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; s += 2 * mXparser.getFunctionValue(f, x, t); t += h; };} h *= 0.5; intF = s * h * 0.5; if (Math.abs(intF - intFprev) <= eps)return intF; if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; };} return intF; } /** * Numerical derivative at x = x0 * * @param {Expression} f the expression * @param {Argument} x the argument * @param {number} x0 at point x = x0 * @param {number} derType derivative type (LEFT_DERIVATIVE, RIGHT_DERIVATIVE, * GENERAL_DERIVATIVE * @param {number} eps the epsilon (error) * @param {number} maxSteps the maximum number of steps * * @return {number} Derivative value as double. * * @see Expression */ public static derivative(f: Expression, x: Argument, x0: number, derType: number, eps: number, maxSteps: number): number { const START_DX: number = 0.1; let step: number = 0; let error: number = 2.0 * eps; let y0: number = 0.0; let derF: number = 0.0; let derFprev: number = 0.0; let dx: number = 0.0; if (derType === Calculus.LEFT_DERIVATIVE)dx = -START_DX; else dx = START_DX; let dy: number = 0.0; if ((derType === Calculus.LEFT_DERIVATIVE) || (derType === Calculus.RIGHT_DERIVATIVE)){ y0 = mXparser.getFunctionValue(f, x, x0); dy = mXparser.getFunctionValue(f, x, x0 + dx) - y0; derF = dy / dx; } else derF = (mXparser.getFunctionValue(f, x, x0 + dx) - mXparser.getFunctionValue(f, x, x0 - dx)) / (2.0 * dx); do {{ derFprev = derF; dx = dx / 2.0; if ((derType === Calculus.LEFT_DERIVATIVE) || (derType === Calculus.RIGHT_DERIVATIVE)){ dy = mXparser.getFunctionValue(f, x, x0 + dx) - y0; derF = dy / dx; } else derF = (mXparser.getFunctionValue(f, x, x0 + dx) - mXparser.getFunctionValue(f, x, x0 - dx)) / (2.0 * dx); error = Math.abs(derF - derFprev); step++; if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; }} while(((step < maxSteps) && ((error > eps) || /* isNaN */isNaN(derF)))); return derF; } /** * Numerical n-th derivative at x = x0 (you should avoid calculation * of derivatives with order higher than 2). * * @param {Expression} f the expression * @param {number} n the deriviative order * @param {Argument} x the argument * @param {number} x0 at point x = x0 * @param {number} derType derivative type (LEFT_DERIVATIVE, RIGHT_DERIVATIVE, * GENERAL_DERIVATIVE * @param {number} eps the epsilon (error) * @param {number} maxSteps the maximum number of steps * * @return {number} Derivative value as double. * * @see Expression */ public static derivativeNth(f: Expression, n: number, x: Argument, x0: number, derType: number, eps: number, maxSteps: number): number { n = Math.round(n); let step: number = 0; let error: number = 2 * eps; let derFprev: number = 0; let dx: number = 0.01; let derF: number = 0; if (derType === Calculus.RIGHT_DERIVATIVE)for(let i: number = 1; i <= n; i++) {derF += MathFunctions.binomCoeff$double$double(-1, n - i) * MathFunctions.binomCoeff$double$long(n, i) * mXparser.getFunctionValue(f, x, x0 + i * dx);} else for(let i: number = 1; i <= n; i++) {derF += MathFunctions.binomCoeff$double$long(-1, i) * MathFunctions.binomCoeff$double$long(n, i) * mXparser.getFunctionValue(f, x, x0 - i * dx);} derF = derF / Math.pow(dx, n); do {{ derFprev = derF; dx = dx / 2.0; derF = 0; if (derType === Calculus.RIGHT_DERIVATIVE)for(let i: number = 1; i <= n; i++) {derF += MathFunctions.binomCoeff$double$double(-1, n - i) * MathFunctions.binomCoeff$double$long(n, i) * mXparser.getFunctionValue(f, x, x0 + i * dx);} else for(let i: number = 1; i <= n; i++) {derF += MathFunctions.binomCoeff$double$long(-1, i) * MathFunctions.binomCoeff$double$long(n, i) * mXparser.getFunctionValue(f, x, x0 - i * dx);} derF = derF / Math.pow(dx, n); error = Math.abs(derF - derFprev); step++; if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; }} while(((step < maxSteps) && ((error > eps) || /* isNaN */isNaN(derF)))); return derF; } public static forwardDifference$org_mariuszgromada_math_mxparser_Expression$org_mariuszgromada_math_mxparser_Argument$double(f: Expression, x: Argument, x0: number): number { if (/* isNaN */isNaN(x0))return javaemul.internal.DoubleHelper.NaN; const xb: number = x.getArgumentValue(); const delta: number = mXparser.getFunctionValue(f, x, x0 + 1) - mXparser.getFunctionValue(f, x, x0); x.setArgumentValue(xb); return delta; } public static forwardDifference$org_mariuszgromada_math_mxparser_Expression$org_mariuszgromada_math_mxparser_Argument(f: Expression, x: Argument): number { const xb: number = x.getArgumentValue(); if (/* isNaN */isNaN(xb))return javaemul.internal.DoubleHelper.NaN; const fv: number = f.calculate(); x.setArgumentValue(xb + 1); const delta: number = f.calculate() - fv; x.setArgumentValue(xb); return delta; } public static backwardDifference$org_mariuszgromada_math_mxparser_Expression$org_mariuszgromada_math_mxparser_Argument$double(f: Expression, x: Argument, x0: number): number { if (/* isNaN */isNaN(x0))return javaemul.internal.DoubleHelper.NaN; const xb: number = x.getArgumentValue(); const delta: number = mXparser.getFunctionValue(f, x, x0) - mXparser.getFunctionValue(f, x, x0 - 1); x.setArgumentValue(xb); return delta; } public static backwardDifference$org_mariuszgromada_math_mxparser_Expression$org_mariuszgromada_math_mxparser_Argument(f: Expression, x: Argument): number { const xb: number = x.getArgumentValue(); if (/* isNaN */isNaN(xb))return javaemul.internal.DoubleHelper.NaN; const fv: number = f.calculate(); x.setArgumentValue(xb - 1); const delta: number = fv - f.calculate(); x.setArgumentValue(xb); return delta; } public static forwardDifference$org_mariuszgromada_math_mxparser_Expression$double$org_mariuszgromada_math_mxparser_Argument$double(f: Expression, h: number, x: Argument, x0: number): number { if (/* isNaN */isNaN(x0))return javaemul.internal.DoubleHelper.NaN; const xb: number = x.getArgumentValue(); const delta: number = mXparser.getFunctionValue(f, x, x0 + h) - mXparser.getFunctionValue(f, x, x0); x.setArgumentValue(xb); return delta; } /** * Forward difference(h) operator (at x = x0) * * @param {Expression} f the expression * @param {number} h the difference * @param {Argument} x the argument name * @param {number} x0 x = x0 * * @return {number} Forward difference(h) value calculated at x0. * * @see Expression * @see Argument */ public static forwardDifference(f?: any, h?: any, x?: any, x0?: any): any { if (((f != null && f instanceof <any>Expression) || f === null) && ((typeof h === 'number') || h === null) && ((x != null && x instanceof <any>Argument) || x === null) && ((typeof x0 === 'number') || x0 === null)) { return <any>Calculus.forwardDifference$org_mariuszgromada_math_mxparser_Expression$double$org_mariuszgromada_math_mxparser_Argument$double(f, h, x, x0); } else if (((f != null && f instanceof <any>Expression) || f === null) && ((h != null && h instanceof <any>Argument) || h === null) && ((typeof x === 'number') || x === null) && x0 === undefined) { return <any>Calculus.forwardDifference$org_mariuszgromada_math_mxparser_Expression$org_mariuszgromada_math_mxparser_Argument$double(f, h, x); } else if (((f != null && f instanceof <any>Expression) || f === null) && ((typeof h === 'number') || h === null) && ((x != null && x instanceof <any>Argument) || x === null) && x0 === undefined) { return <any>Calculus.forwardDifference$org_mariuszgromada_math_mxparser_Expression$double$org_mariuszgromada_math_mxparser_Argument(f, h, x); } else if (((f != null && f instanceof <any>Expression) || f === null) && ((h != null && h instanceof <any>Argument) || h === null) && x === undefined && x0 === undefined) { return <any>Calculus.forwardDifference$org_mariuszgromada_math_mxparser_Expression$org_mariuszgromada_math_mxparser_Argument(f, h); } else throw new Error('invalid overload'); } public static forwardDifference$org_mariuszgromada_math_mxparser_Expression$double$org_mariuszgromada_math_mxparser_Argument(f: Expression, h: number, x: Argument): number { const xb: number = x.getArgumentValue(); if (/* isNaN */isNaN(xb))return javaemul.internal.DoubleHelper.NaN; const fv: number = f.calculate(); x.setArgumentValue(xb + h); const delta: number = f.calculate() - fv; x.setArgumentValue(xb); return delta; } public static backwardDifference$org_mariuszgromada_math_mxparser_Expression$double$org_mariuszgromada_math_mxparser_Argument$double(f: Expression, h: number, x: Argument, x0: number): number { if (/* isNaN */isNaN(x0))return javaemul.internal.DoubleHelper.NaN; const xb: number = x.getArgumentValue(); const delta: number = mXparser.getFunctionValue(f, x, x0) - mXparser.getFunctionValue(f, x, x0 - h); x.setArgumentValue(xb); return delta; } /** * Backward difference(h) operator (at x = x0) * * @param {Expression} f the expression * @param {number} h the difference * @param {Argument} x the argument name * @param {number} x0 x = x0 * * @return {number} Backward difference(h) value calculated at x0. * * @see Expression * @see Argument */ public static backwardDifference(f?: any, h?: any, x?: any, x0?: any): any { if (((f != null && f instanceof <any>Expression) || f === null) && ((typeof h === 'number') || h === null) && ((x != null && x instanceof <any>Argument) || x === null) && ((typeof x0 === 'number') || x0 === null)) { return <any>Calculus.backwardDifference$org_mariuszgromada_math_mxparser_Expression$double$org_mariuszgromada_math_mxparser_Argument$double(f, h, x, x0); } else if (((f != null && f instanceof <any>Expression) || f === null) && ((h != null && h instanceof <any>Argument) || h === null) && ((typeof x === 'number') || x === null) && x0 === undefined) { return <any>Calculus.backwardDifference$org_mariuszgromada_math_mxparser_Expression$org_mariuszgromada_math_mxparser_Argument$double(f, h, x); } else if (((f != null && f instanceof <any>Expression) || f === null) && ((typeof h === 'number') || h === null) && ((x != null && x instanceof <any>Argument) || x === null) && x0 === undefined) { return <any>Calculus.backwardDifference$org_mariuszgromada_math_mxparser_Expression$double$org_mariuszgromada_math_mxparser_Argument(f, h, x); } else if (((f != null && f instanceof <any>Expression) || f === null) && ((h != null && h instanceof <any>Argument) || h === null) && x === undefined && x0 === undefined) { return <any>Calculus.backwardDifference$org_mariuszgromada_math_mxparser_Expression$org_mariuszgromada_math_mxparser_Argument(f, h); } else throw new Error('invalid overload'); } public static backwardDifference$org_mariuszgromada_math_mxparser_Expression$double$org_mariuszgromada_math_mxparser_Argument(f: Expression, h: number, x: Argument): number { const xb: number = x.getArgumentValue(); if (/* isNaN */isNaN(xb))return javaemul.internal.DoubleHelper.NaN; const fv: number = f.calculate(); x.setArgumentValue(xb - h); const delta: number = fv - f.calculate(); x.setArgumentValue(xb); return delta; } /** * Brent solver (Brent root finder) * * @param {Expression} f Function given in the Expression form * @param {Argument} x Argument * @param {number} a Left limit * @param {number} b Right limit * @param {number} eps Epsilon value (accuracy) * @param {number} maxSteps Maximum number of iterations * @return {number} Function root - if found, otherwise Double.NaN. */ public static solveBrent(f: Expression, x: Argument, a: number, b: number, eps: number, maxSteps: number): number { let fa: number; let fb: number; let fc: number; let fs: number; let c: number; let c0: number; let c1: number; let c2: number; let tmp: number; let d: number; let s: number; let mflag: boolean; let iter: number; if (b < a){ tmp = a; a = b; b = tmp; } fa = mXparser.getFunctionValue(f, x, a); fb = mXparser.getFunctionValue(f, x, b); if (MathFunctions.abs(fa) <= eps)return a; if (MathFunctions.abs(fb) <= eps)return b; if (b === a)return javaemul.internal.DoubleHelper.NaN; if (fa * fb > 0){ let rndflag: boolean = false; let ap: number; let bp: number; for(let i: number = 0; i < maxSteps; i++) {{ ap = ProbabilityDistributions.rndUniformContinuous$double$double(a, b); bp = ProbabilityDistributions.rndUniformContinuous$double$double(a, b); if (bp < ap){ tmp = ap; ap = bp; bp = tmp; } fa = mXparser.getFunctionValue(f, x, ap); fb = mXparser.getFunctionValue(f, x, bp); if (MathFunctions.abs(fa) <= eps)return ap; if (MathFunctions.abs(fb) <= eps)return bp; if (fa * fb < 0){ rndflag = true; a = ap; b = bp; break; } if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; };} if (rndflag === false)return javaemul.internal.DoubleHelper.NaN; } c = a; d = c; fc = mXparser.getFunctionValue(f, x, c); if (MathFunctions.abs(fa) < MathFunctions.abs(fb)){ tmp = a; a = b; b = tmp; tmp = fa; fa = fb; fb = tmp; } mflag = true; iter = 0; while(((MathFunctions.abs(fb) > eps) && (MathFunctions.abs(b - a) > eps) && (iter < maxSteps))) {{ if ((fa !== fc) && (fb !== fc)){ c0 = (a * fb * fc) / ((fa - fb) * (fa - fc)); c1 = (b * fa * fc) / ((fb - fa) * (fb - fc)); c2 = (c * fa * fb) / ((fc - fa) * (fc - fb)); s = c0 + c1 + c2; } else s = b - (fb * (b - a)) / (fb - fa); if ((s < (3 * (a + b) / 4) || s > b) || ((mflag === true) && MathFunctions.abs(s - b) >= (MathFunctions.abs(b - c) / 2))){ s = (a + b) / 2; mflag = true; } else mflag = true; fs = mXparser.getFunctionValue(f, x, s); d = c; c = b; fc = fb; if ((fa * fs) < 0)b = s; else a = s; if (MathFunctions.abs(fa) < MathFunctions.abs(fb)){ tmp = a; a = b; b = tmp; tmp = fa; fa = fb; fb = tmp; } iter++; if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; }}; return MathFunctions.round(b, MathFunctions.decimalDigitsBefore(eps) - 1); } } Calculus["__class"] = "org.mariuszgromada.math.mxparser.mathcollection.Calculus";
the_stack
import { Animations, AnimationNode } from "./types"; import { DefaultTime } from "../../Utilities"; import * as Constants from "../../Types/Constants"; import { TransitionItem } from "../../Components/Types/TransitionItem"; import { InterpolationInfo } from "../../Components/Types/InterpolationTypes"; import { ChildAnimationDirection, ConfigStaggerFunction, } from "../../Configuration"; import { Dimensions } from "react-native"; /** * * @description Returns tree of interpolation nodes from a parent (animation context) * transition item. This is the function to call from outside when setting up * interpolations. * @param item Root item to build tree from * @returns */ export async function getInterpolationTree( item: TransitionItem, interpolations: Array<InterpolationInfo>, interpolationIds: Array<number>, ): Promise<AnimationNode | undefined> { // Build Tree const tree = createInterpolationNode(item, interpolations); // Flatten tree const nodes: AnimationNode[] = []; flattenNode(tree, nodes); // Resolve metrics await resolveMetrics(nodes); // Resolve stagger resolveStagger(tree); // Get hash of items with interpolation const hash = getInterpolations(interpolationIds, nodes); // Trim tree of nodes to only include those containing interpolations // or having children with interpolation return getReducedInterpolationTree(tree, hash); } const dim = Dimensions.get("window"); function getInterpolations( ids: Array<number>, nodes: AnimationNode[], ): Animations { // Identifiers of interpolation nodes const interpolationIds: { [key: string]: boolean } = {}; ids.forEach(id => { const node = nodes.find(p => p.id === id); if (node) { interpolationIds[id] = // node.metrics.x + node.metrics.width >= 0 && // node.metrics.x < dim.width && node.metrics.y + node.metrics.height >= 0 && node.metrics.y < dim.height; // if (!interpolationIds[id]) { // console.log(node.label); // } } }); return interpolationIds; } /** * * @param root Root node in tree * @param interpolations interpolation id hash map * @returns tree of items with interpolation or undefined if there * are no items with interpolation */ export function getReducedInterpolationTree( root: AnimationNode, interpolations: Animations, ): AnimationNode | undefined { // Removed nodes without interpolations const retVal = reduceSubtree(root, interpolations); if (retVal !== undefined) { resolveAsChildrenDurations(retVal); resolveAsContextDurations(retVal, retVal.subtreeDuration || DefaultTime); } // Calculate offsets return retVal ? calculateOffset(retVal) : undefined; } const flattenNode = (node: AnimationNode, nodeList: Array<AnimationNode>) => { nodeList.push(node); node.children.forEach(c => flattenNode(c, nodeList)); }; const resolveMetrics = async (nodes: AnimationNode[]) => { const metricsPromises: Promise<unknown>[] = []; nodes.forEach(n => { if (n.waitForMetrics) metricsPromises.push(n.waitForMetrics()); }); await Promise.all(metricsPromises); }; const resolveStagger = (node: AnimationNode) => { // resolve stagger for children if necessary if (node.childAnimation === "staggered") { if (node.staggerFunction) { const staggerFunc = node.staggerFunction; const childMetrics = node.children.map(c => c.metrics); const staggerValues = staggerFunc(node.metrics, childMetrics); node.children.forEach((child, index) => { child.stagger = staggerValues[index]; resolveStagger(child); }); } } }; /** * * @description Finds a node by interpolator id in the tree * @param interpolationId interpolator id to find * @param node node to search from */ export function findNodeByInterpolationId( interpolationId: number, node: AnimationNode, ): AnimationNode | undefined { if (node.interpolationId === interpolationId) return node; for (let i = 0; i < node.children.length; i++) { const child = findNodeByInterpolationId(interpolationId, node.children[i]); if (child) return child; } return undefined; } /***********************************************************************/ /** Private functions **/ function calculateOffset(node: AnimationNode) { node.offset = getNodeOffset(node); node.children.forEach(child => calculateOffset(child)); return node; } function reduceSubtree( node: AnimationNode, interpolationIds: { [key: string]: boolean }, ): AnimationNode | undefined { // Map children node.children = node.children .map(child => reduceSubtree(child, interpolationIds)) .filter(child => child !== undefined) as Array<AnimationNode>; if (interpolationIds[node.id] || node.children.length > 0) { // calculate duration if (node.children.length > 0) { const subtreeDuration = getSubtreeDuration(node); node.subtreeDuration = Math.max( subtreeDuration, interpolationIds[node.id] ? node.duration + node.delay : -1, ); } else { node.subtreeDuration = node.duration + node.delay; } return node; } return undefined; } function resolveAsChildrenDurations( node: AnimationNode, inheritedDuration: number = DefaultTime, ) { if ( node.subtreeDuration === Constants.AsGroup || node.subtreeDuration === -1 ) { node.duration = inheritedDuration; } node.children.forEach(child => resolveAsChildrenDurations( child, node.subtreeDuration === -1 ? inheritedDuration : node.subtreeDuration, ), ); } function resolveAsContextDurations( node: AnimationNode, contextDuration: number, ) { if (node.subtreeDuration === Constants.AsContext) { node.duration = contextDuration; } node.children.forEach(child => resolveAsContextDurations(child, contextDuration), ); } const getSortedChildren = ( children: AnimationNode[], childDirection?: ChildAnimationDirection, ): AnimationNode[] => { if (childDirection === ChildAnimationDirection.Forward) { // TODO: Add support for sorting children by position! return children; } else if (childDirection === ChildAnimationDirection.Backward) { return children.slice().reverse(); } else { // Check for other types of child sorting - metrics etc. const hasMetrics = children.filter(s => s.metrics.x === -1).length === 0; if (!hasMetrics) { return children; } return children; } }; function getNodeOffset(node: AnimationNode): number { const parent = node.parent; if (!parent) { return node.delay; } // Index in parent const currentOffset = node.parent ? node.parent.offset : 0; const index = parent.children.indexOf(node); switch (parent.childAnimation) { case "parallel": return currentOffset + node.delay; case "sequential": return parent.children.reduce((acc, c, i) => { return acc + (i < index ? c.subtreeDuration || 0 : 0); }, currentOffset); case "staggered": if (parent.staggerFunction) return node.stagger; return parent.children.reduce((acc, _, i) => { return i < index ? acc + node.stagger : acc; }, currentOffset); } } function getSubtreeDuration(node: AnimationNode): number { const children = node.children.filter(c => c.duration >= 0); if (children.length === 0) return Constants.AsGroup; switch (node.childAnimation) { case "parallel": return children.reduce( (acc, c) => Math.max(c.subtreeDuration || 0, acc), 0, ); case "sequential": return children.reduce((acc, c) => (c.subtreeDuration || 0) + acc, 0); case "staggered": return children.reduce( (accObj, c) => { return { offset: accObj.offset + (c.stagger > 0 ? c.stagger : node.stagger), value: Math.max( accObj.value, accObj.offset + (c.subtreeDuration || 0), ), }; }, { value: 0, offset: 0 }, ).value; } } function createInterpolationNode( item: TransitionItem, interpolations: Array<InterpolationInfo>, parent?: AnimationNode, childDirection?: ChildAnimationDirection, ): AnimationNode { // Find interpolations belonging to this element const itemInterpolations = interpolations.filter(i => i.itemId === item.id); const singleInterpolation = itemInterpolations.length === 1 ? itemInterpolations[0] : undefined; const configuration = item.configuration(); // Calculate stagger and child animation type const resolvedChildAnimation = configuration.childAnimation || { type: "parallel", }; const resolvedChildDirection = (configuration.childAnimation && configuration.childAnimation.direction) || childDirection || "forward"; const resolvedStagger = configuration.childAnimation && configuration.childAnimation.type === "staggered" && configuration.childAnimation.stagger && !(typeof configuration.childAnimation.stagger === "function") ? (configuration.childAnimation.stagger as number) : Constants.DefaultStaggerMs; const resolvedStaggerFunction = configuration.childAnimation && configuration.childAnimation.type === "staggered" && typeof configuration.childAnimation.stagger === "function" ? (configuration.childAnimation.stagger as ConfigStaggerFunction) : undefined; const node: AnimationNode = { id: item.id, label: item.label, parent, children: [], metrics: item.metrics(), offset: -1, isHidden: false, stagger: resolvedStagger, childAnimation: resolvedChildAnimation.type, childDirection: resolvedChildDirection, staggerFunction: resolvedStaggerFunction, waitForMetrics: item.waitForMetrics, duration: (singleInterpolation && singleInterpolation.animationType && singleInterpolation.animationType.type === "timing" && singleInterpolation.animationType.duration) || DefaultTime, delay: (singleInterpolation && singleInterpolation.animationType && singleInterpolation.animationType.delay) || 0, interpolationId: singleInterpolation !== undefined ? singleInterpolation.id : -1, }; const children = singleInterpolation ? [] : itemInterpolations.map(ip => ({ id: item.id, parent: node, label: item.label, children: [], metrics: item.metrics(), offset: -1, childAnimation: "-", childDirection: "-", stagger: 0, isHidden: false, interpolationId: ip.id, duration: (ip.animationType && ip.animationType.type === "timing" && ip.animationType.duration) || 0, delay: (ip.animationType && ip.animationType.delay) || 0, animation: ip.animationType, })); node.children = getSortedChildren( item .children() .map(i => createInterpolationNode( i, interpolations, node, resolvedChildDirection, ), ) .concat(children as Array<AnimationNode>), resolvedChildDirection, ); return node; }
the_stack
declare type sqlite3_default = typeof sqlite3.dbapi2 declare type tkinter_default = typeof tkinter.constants declare module base64 { var _ /** * Encode the bytes-like object s using Base64 and return a bytes object. * * Optional altchars should be a byte string of length 2 which specifies an * alternative alphabet for the '+' and '/' characters. This allows an * application to e.g. generate url or filesystem safe Base64 strings. * */ function b64encode(s, altchars?): Promise<any> function b64encode$({ s, altchars }: { s, altchars?}): Promise<any> /** * Decode the Base64 encoded bytes-like object or ASCII string s. * * Optional altchars must be a bytes-like object or ASCII string of length 2 * which specifies the alternative alphabet used instead of the '+' and '/' * characters. * * The result is returned as a bytes object. A binascii.Error is raised if * s is incorrectly padded. * * If validate is False (the default), characters that are neither in the * normal base-64 alphabet nor the alternative alphabet are discarded prior * to the padding check. If validate is True, these non-alphabet characters * in the input result in a binascii.Error. * */ function b64decode(s, altchars?, validate?: boolean): Promise<any> function b64decode$({ s, altchars, validate }: { s, altchars?, validate?}): Promise<any> /** * Encode bytes-like object s using the standard Base64 alphabet. * * The result is returned as a bytes object. * */ function standard_b64encode(s): Promise<any> function standard_b64encode$({ s }): Promise<any> /** * Decode bytes encoded with the standard Base64 alphabet. * * Argument s is a bytes-like object or ASCII string to decode. The result * is returned as a bytes object. A binascii.Error is raised if the input * is incorrectly padded. Characters that are not in the standard alphabet * are discarded prior to the padding check. * */ function standard_b64decode(s): Promise<any> function standard_b64decode$({ s }): Promise<any> /** * Encode bytes using the URL- and filesystem-safe Base64 alphabet. * * Argument s is a bytes-like object to encode. The result is returned as a * bytes object. The alphabet uses '-' instead of '+' and '_' instead of * '/'. * */ function urlsafe_b64encode(s): Promise<any> function urlsafe_b64encode$({ s }): Promise<any> /** * Decode bytes using the URL- and filesystem-safe Base64 alphabet. * * Argument s is a bytes-like object or ASCII string to decode. The result * is returned as a bytes object. A binascii.Error is raised if the input * is incorrectly padded. Characters that are not in the URL-safe base-64 * alphabet, and are not a plus '+' or slash '/', are discarded prior to the * padding check. * * The alphabet uses '-' instead of '+' and '_' instead of '/'. * */ function urlsafe_b64decode(s): Promise<any> function urlsafe_b64decode$({ s }): Promise<any> function b32encode(s): Promise<any> function b32encode$({ s }): Promise<any> function b32decode(s, casefold?: boolean, map01?): Promise<any> function b32decode$({ s, casefold, map01 }: { s, casefold?, map01?}): Promise<any> function b32hexencode(s): Promise<any> function b32hexencode$({ s }): Promise<any> function b32hexdecode(s, casefold?: boolean): Promise<any> function b32hexdecode$({ s, casefold }: { s, casefold?}): Promise<any> /** * Encode the bytes-like object s using Base16 and return a bytes object. * */ function b16encode(s): Promise<any> function b16encode$({ s }): Promise<any> /** * Decode the Base16 encoded bytes-like object or ASCII string s. * * Optional casefold is a flag specifying whether a lowercase alphabet is * acceptable as input. For security purposes, the default is False. * * The result is returned as a bytes object. A binascii.Error is raised if * s is incorrectly padded or if there are non-alphabet characters present * in the input. * */ function b16decode(s, casefold?: boolean): Promise<any> function b16decode$({ s, casefold }: { s, casefold?}): Promise<any> /** * Encode bytes-like object b using Ascii85 and return a bytes object. * * foldspaces is an optional flag that uses the special short sequence 'y' * instead of 4 consecutive spaces (ASCII 0x20) as supported by 'btoa'. This * feature is not supported by the "standard" Adobe encoding. * * wrapcol controls whether the output should have newline (b'\n') characters * added to it. If this is non-zero, each output line will be at most this * many characters long. * * pad controls whether the input is padded to a multiple of 4 before * encoding. Note that the btoa implementation always pads. * * adobe controls whether the encoded byte sequence is framed with <~ and ~>, * which is used by the Adobe implementation. * */ function a85encode(b): Promise<any> function a85encode$({ b }): Promise<any> /** * Decode the Ascii85 encoded bytes-like object or ASCII string b. * * foldspaces is a flag that specifies whether the 'y' short sequence should be * accepted as shorthand for 4 consecutive spaces (ASCII 0x20). This feature is * not supported by the "standard" Adobe encoding. * * adobe controls whether the input sequence is in Adobe Ascii85 format (i.e. * is framed with <~ and ~>). * * ignorechars should be a byte string containing characters to ignore from the * input. This should only contain whitespace characters, and by default * contains all whitespace characters in ASCII. * * The result is returned as a bytes object. * */ function a85decode(b): Promise<any> function a85decode$({ b }): Promise<any> /** * Encode bytes-like object b in base85 format and return a bytes object. * * If pad is true, the input is padded with b'\0' so its length is a multiple of * 4 bytes before encoding. * */ function b85encode(b, pad?: boolean): Promise<any> function b85encode$({ b, pad }: { b, pad?}): Promise<any> /** * Decode the base85-encoded bytes-like object or ASCII string b * * The result is returned as a bytes object. * */ function b85decode(b): Promise<any> function b85decode$({ b }): Promise<any> /** * Encode a file; input and output are binary files. */ function encode(input, output): Promise<any> function encode$({ input, output }): Promise<any> /** * Decode a file; input and output are binary files. */ function decode(input, output): Promise<any> function decode$({ input, output }): Promise<any> /** * Encode a bytestring into a bytes object containing multiple lines * of base-64 data. */ function encodebytes(s): Promise<any> function encodebytes$({ s }): Promise<any> /** * Decode a bytestring of base-64 data into a bytes object. */ function decodebytes(s): Promise<any> function decodebytes$({ s }): Promise<any> /** * Small main program */ function main(): Promise<any> function main$($: {}): Promise<any> function test(): Promise<any> function test$($: {}): Promise<any> let bytes_types: Promise<any> let MAXLINESIZE: Promise<any> let MAXBINSIZE: Promise<any> } declare module codecs { var _ /** * Open an encoded file using the given mode and return * a wrapped version providing transparent encoding/decoding. * * Note: The wrapped version will only accept the object format * defined by the codecs, i.e. Unicode objects for most builtin * codecs. Output is also codec dependent and will usually be * Unicode as well. * * Underlying encoded files are always opened in binary mode. * The default file mode is 'r', meaning to open the file in read mode. * * encoding specifies the encoding which is to be used for the * file. * * errors may be given to define the error handling. It defaults * to 'strict' which causes ValueErrors to be raised in case an * encoding error occurs. * * buffering has the same meaning as for the builtin open() API. * It defaults to -1 which means that the default buffer size will * be used. * * The returned wrapped file object provides an extra attribute * .encoding which allows querying the used encoding. This * attribute is only available if an encoding was specified as * parameter. * * */ function open(filename, mode?, encoding?, errors?, buffering?): Promise<any> function open$({ filename, mode, encoding, errors, buffering }: { filename, mode?, encoding?, errors?, buffering?}): Promise<any> /** * Return a wrapped version of file which provides transparent * encoding translation. * * Data written to the wrapped file is decoded according * to the given data_encoding and then encoded to the underlying * file using file_encoding. The intermediate data type * will usually be Unicode but depends on the specified codecs. * * Bytes read from the file are decoded using file_encoding and then * passed back to the caller encoded using data_encoding. * * If file_encoding is not given, it defaults to data_encoding. * * errors may be given to define the error handling. It defaults * to 'strict' which causes ValueErrors to be raised in case an * encoding error occurs. * * The returned wrapped file object provides two extra attributes * .data_encoding and .file_encoding which reflect the given * parameters of the same name. The attributes can be used for * introspection by Python programs. * * */ function EncodedFile(file, data_encoding, file_encoding?, errors?): Promise<any> function EncodedFile$({ file, data_encoding, file_encoding, errors }: { file, data_encoding, file_encoding?, errors?}): Promise<any> /** * Lookup up the codec for the given encoding and return * its encoder function. * * Raises a LookupError in case the encoding cannot be found. * * */ function getencoder(encoding): Promise<any> function getencoder$({ encoding }): Promise<any> /** * Lookup up the codec for the given encoding and return * its decoder function. * * Raises a LookupError in case the encoding cannot be found. * * */ function getdecoder(encoding): Promise<any> function getdecoder$({ encoding }): Promise<any> /** * Lookup up the codec for the given encoding and return * its IncrementalEncoder class or factory function. * * Raises a LookupError in case the encoding cannot be found * or the codecs doesn't provide an incremental encoder. * * */ function getincrementalencoder(encoding): Promise<any> function getincrementalencoder$({ encoding }): Promise<any> /** * Lookup up the codec for the given encoding and return * its IncrementalDecoder class or factory function. * * Raises a LookupError in case the encoding cannot be found * or the codecs doesn't provide an incremental decoder. * * */ function getincrementaldecoder(encoding): Promise<any> function getincrementaldecoder$({ encoding }): Promise<any> /** * Lookup up the codec for the given encoding and return * its StreamReader class or factory function. * * Raises a LookupError in case the encoding cannot be found. * * */ function getreader(encoding): Promise<any> function getreader$({ encoding }): Promise<any> /** * Lookup up the codec for the given encoding and return * its StreamWriter class or factory function. * * Raises a LookupError in case the encoding cannot be found. * * */ function getwriter(encoding): Promise<any> function getwriter$({ encoding }): Promise<any> /** * * Encoding iterator. * * Encodes the input strings from the iterator using an IncrementalEncoder. * * errors and kwargs are passed through to the IncrementalEncoder * constructor. * */ function iterencode(iterator, encoding, errors?): Promise<any> function iterencode$({ iterator, encoding, errors }: { iterator, encoding, errors?}): Promise<any> /** * * Decoding iterator. * * Decodes the input strings from the iterator using an IncrementalDecoder. * * errors and kwargs are passed through to the IncrementalDecoder * constructor. * */ function iterdecode(iterator, encoding, errors?): Promise<any> function iterdecode$({ iterator, encoding, errors }: { iterator, encoding, errors?}): Promise<any> /** * make_identity_dict(rng) -> dict * * Return a dictionary where elements of the rng sequence are * mapped to themselves. * * */ function make_identity_dict(rng): Promise<any> function make_identity_dict$({ rng }): Promise<any> /** * Creates an encoding map from a decoding map. * * If a target mapping in the decoding map occurs multiple * times, then that target is mapped to None (undefined mapping), * causing an exception when encountered by the charmap codec * during translation. * * One example where this happens is cp875.py which decodes * multiple character to \u001a. * * */ function make_encoding_map(decoding_map): Promise<any> function make_encoding_map$({ decoding_map }): Promise<any> /** * Codec details when looking up the codec registry */ interface ICodecInfo { } /** * Defines the interface for stateless encoders/decoders. * * The .encode()/.decode() methods may use different error * handling schemes by providing the errors argument. These * string values are predefined: * * 'strict' - raise a ValueError error (or a subclass) * 'ignore' - ignore the character and continue with the next * 'replace' - replace with a suitable replacement character; * Python will use the official U+FFFD REPLACEMENT * CHARACTER for the builtin Unicode codecs on * decoding and '?' on encoding. * 'surrogateescape' - replace with private code points U+DCnn. * 'xmlcharrefreplace' - Replace with the appropriate XML * character reference (only for encoding). * 'backslashreplace' - Replace with backslashed escape sequences. * 'namereplace' - Replace with \N{...} escape sequences * (only for encoding). * * The set of allowed values can be extended via register_error. * * */ interface ICodec { /** * Encodes the object input and returns a tuple (output * object, length consumed). * * errors defines the error handling to apply. It defaults to * 'strict' handling. * * The method may not store state in the Codec instance. Use * StreamWriter for codecs which have to keep state in order to * make encoding efficient. * * The encoder must be able to handle zero length input and * return an empty object of the output object type in this * situation. * * */ encode(input, errors?): Promise<any> encode$({ input, errors }: { input, errors?}): Promise<any> /** * Decodes the object input and returns a tuple (output * object, length consumed). * * input must be an object which provides the bf_getreadbuf * buffer slot. Python strings, buffer objects and memory * mapped files are examples of objects providing this slot. * * errors defines the error handling to apply. It defaults to * 'strict' handling. * * The method may not store state in the Codec instance. Use * StreamReader for codecs which have to keep state in order to * make decoding efficient. * * The decoder must be able to handle zero length input and * return an empty object of the output object type in this * situation. * * */ decode(input, errors?): Promise<any> decode$({ input, errors }: { input, errors?}): Promise<any> } /** * * An IncrementalEncoder encodes an input in multiple steps. The input can * be passed piece by piece to the encode() method. The IncrementalEncoder * remembers the state of the encoding process between calls to encode(). * */ /** * * Creates an IncrementalEncoder instance. * * The IncrementalEncoder may use different error handling schemes by * providing the errors keyword argument. See the module docstring * for a list of possible values. * */ function IncrementalEncoder(errors?): Promise<IIncrementalEncoder> function IncrementalEncoder$({ errors }: { errors?}): Promise<IIncrementalEncoder> interface IIncrementalEncoder { /** * * Encodes input and returns the resulting object. * */ encode(input, final?: boolean): Promise<any> encode$({ input, final }: { input, final?}): Promise<any> /** * * Resets the encoder to the initial state. * */ reset(): Promise<any> reset$($: {}): Promise<any> /** * * Return the current state of the encoder. * */ getstate(): Promise<any> getstate$($: {}): Promise<any> /** * * Set the current state of the encoder. state must have been * returned by getstate(). * */ setstate(state): Promise<any> setstate$({ state }): Promise<any> } /** * * This subclass of IncrementalEncoder can be used as the baseclass for an * incremental encoder if the encoder must keep some of the output in a * buffer between calls to encode(). * */ function BufferedIncrementalEncoder(errors?): Promise<IBufferedIncrementalEncoder> function BufferedIncrementalEncoder$({ errors }: { errors?}): Promise<IBufferedIncrementalEncoder> interface IBufferedIncrementalEncoder extends IIncrementalEncoder { encode(input, final?: boolean): Promise<any> encode$({ input, final }: { input, final?}): Promise<any> reset(): Promise<any> reset$($: {}): Promise<any> getstate(): Promise<any> getstate$($: {}): Promise<any> setstate(state): Promise<any> setstate$({ state }): Promise<any> } /** * * An IncrementalDecoder decodes an input in multiple steps. The input can * be passed piece by piece to the decode() method. The IncrementalDecoder * remembers the state of the decoding process between calls to decode(). * */ /** * * Create an IncrementalDecoder instance. * * The IncrementalDecoder may use different error handling schemes by * providing the errors keyword argument. See the module docstring * for a list of possible values. * */ function IncrementalDecoder(errors?): Promise<IIncrementalDecoder> function IncrementalDecoder$({ errors }: { errors?}): Promise<IIncrementalDecoder> interface IIncrementalDecoder { /** * * Decode input and returns the resulting object. * */ decode(input, final?: boolean): Promise<any> decode$({ input, final }: { input, final?}): Promise<any> /** * * Reset the decoder to the initial state. * */ reset(): Promise<any> reset$($: {}): Promise<any> /** * * Return the current state of the decoder. * * This must be a (buffered_input, additional_state_info) tuple. * buffered_input must be a bytes object containing bytes that * were passed to decode() that have not yet been converted. * additional_state_info must be a non-negative integer * representing the state of the decoder WITHOUT yet having * processed the contents of buffered_input. In the initial state * and after reset(), getstate() must return (b"", 0). * */ getstate(): Promise<any> getstate$($: {}): Promise<any> /** * * Set the current state of the decoder. * * state must have been returned by getstate(). The effect of * setstate((b"", 0)) must be equivalent to reset(). * */ setstate(state): Promise<any> setstate$({ state }): Promise<any> } /** * * This subclass of IncrementalDecoder can be used as the baseclass for an * incremental decoder if the decoder must be able to handle incomplete * byte sequences. * */ function BufferedIncrementalDecoder(errors?): Promise<IBufferedIncrementalDecoder> function BufferedIncrementalDecoder$({ errors }: { errors?}): Promise<IBufferedIncrementalDecoder> interface IBufferedIncrementalDecoder extends IIncrementalDecoder { decode(input, final?: boolean): Promise<any> decode$({ input, final }: { input, final?}): Promise<any> reset(): Promise<any> reset$($: {}): Promise<any> getstate(): Promise<any> getstate$($: {}): Promise<any> setstate(state): Promise<any> setstate$({ state }): Promise<any> } /** * Creates a StreamWriter instance. * * stream must be a file-like object open for writing. * * The StreamWriter may use different error handling * schemes by providing the errors keyword argument. These * parameters are predefined: * * 'strict' - raise a ValueError (or a subclass) * 'ignore' - ignore the character and continue with the next * 'replace'- replace with a suitable replacement character * 'xmlcharrefreplace' - Replace with the appropriate XML * character reference. * 'backslashreplace' - Replace with backslashed escape * sequences. * 'namereplace' - Replace with \N{...} escape sequences. * * The set of allowed parameter values can be extended via * register_error. * */ function StreamWriter(stream, errors?): Promise<IStreamWriter> function StreamWriter$({ stream, errors }: { stream, errors?}): Promise<IStreamWriter> interface IStreamWriter extends ICodec { /** * Writes the object's contents encoded to self.stream. * */ write(object): Promise<any> write$({ object }): Promise<any> /** * Writes the concatenated list of strings to the stream * using .write(). * */ writelines(list): Promise<any> writelines$({ list }): Promise<any> /** * Resets the codec buffers used for keeping internal state. * * Calling this method should ensure that the data on the * output is put into a clean state, that allows appending * of new fresh data without having to rescan the whole * stream to recover state. * * */ reset(): Promise<any> reset$($: {}): Promise<any> seek(offset, whence?): Promise<any> seek$({ offset, whence }: { offset, whence?}): Promise<any> } /** * Creates a StreamReader instance. * * stream must be a file-like object open for reading. * * The StreamReader may use different error handling * schemes by providing the errors keyword argument. These * parameters are predefined: * * 'strict' - raise a ValueError (or a subclass) * 'ignore' - ignore the character and continue with the next * 'replace'- replace with a suitable replacement character * 'backslashreplace' - Replace with backslashed escape sequences; * * The set of allowed parameter values can be extended via * register_error. * */ function StreamReader(stream, errors?): Promise<IStreamReader> function StreamReader$({ stream, errors }: { stream, errors?}): Promise<IStreamReader> interface IStreamReader extends ICodec { decode(input, errors?): Promise<any> decode$({ input, errors }: { input, errors?}): Promise<any> /** * Decodes data from the stream self.stream and returns the * resulting object. * * chars indicates the number of decoded code points or bytes to * return. read() will never return more data than requested, * but it might return less, if there is not enough available. * * size indicates the approximate maximum number of decoded * bytes or code points to read for decoding. The decoder * can modify this setting as appropriate. The default value * -1 indicates to read and decode as much as possible. size * is intended to prevent having to decode huge files in one * step. * * If firstline is true, and a UnicodeDecodeError happens * after the first line terminator in the input only the first line * will be returned, the rest of the input will be kept until the * next call to read(). * * The method should use a greedy read strategy, meaning that * it should read as much data as is allowed within the * definition of the encoding and the given size, e.g. if * optional encoding endings or state markers are available * on the stream, these should be read too. * */ read(size?, chars?, firstline?: boolean): Promise<any> read$({ size, chars, firstline }: { size?, chars?, firstline?}): Promise<any> /** * Read one line from the input stream and return the * decoded data. * * size, if given, is passed as size argument to the * read() method. * * */ readline(size?, keepends?: boolean): Promise<any> readline$({ size, keepends }: { size?, keepends?}): Promise<any> /** * Read all lines available on the input stream * and return them as a list. * * Line breaks are implemented using the codec's decoder * method and are included in the list entries. * * sizehint, if given, is ignored since there is no efficient * way to finding the true end-of-line. * * */ readlines(sizehint?, keepends?: boolean): Promise<any> readlines$({ sizehint, keepends }: { sizehint?, keepends?}): Promise<any> /** * Resets the codec buffers used for keeping internal state. * * Note that no stream repositioning should take place. * This method is primarily intended to be able to recover * from decoding errors. * * */ reset(): Promise<any> reset$($: {}): Promise<any> /** * Set the input stream's current position. * * Resets the codec buffers used for keeping state. * */ seek(offset, whence?): Promise<any> seek$({ offset, whence }: { offset, whence?}): Promise<any> charbuffertype } /** * StreamReaderWriter instances allow wrapping streams which * work in both read and write modes. * * The design is such that one can use the factory functions * returned by the codec.lookup() function to construct the * instance. * * */ /** * Creates a StreamReaderWriter instance. * * stream must be a Stream-like object. * * Reader, Writer must be factory functions or classes * providing the StreamReader, StreamWriter interface resp. * * Error handling is done in the same way as defined for the * StreamWriter/Readers. * * */ function StreamReaderWriter(stream, Reader, Writer, errors?): Promise<IStreamReaderWriter> function StreamReaderWriter$({ stream, Reader, Writer, errors }: { stream, Reader, Writer, errors?}): Promise<IStreamReaderWriter> interface IStreamReaderWriter { read(size?): Promise<any> read$({ size }: { size?}): Promise<any> readline(size?): Promise<any> readline$({ size }: { size?}): Promise<any> readlines(sizehint?): Promise<any> readlines$({ sizehint }: { sizehint?}): Promise<any> write(data): Promise<any> write$({ data }): Promise<any> writelines(list): Promise<any> writelines$({ list }): Promise<any> reset(): Promise<any> reset$($: {}): Promise<any> seek(offset, whence?): Promise<any> seek$({ offset, whence }: { offset, whence?}): Promise<any> encoding } /** * StreamRecoder instances translate data from one encoding to another. * * They use the complete set of APIs returned by the * codecs.lookup() function to implement their task. * * Data written to the StreamRecoder is first decoded into an * intermediate format (depending on the "decode" codec) and then * written to the underlying stream using an instance of the provided * Writer class. * * In the other direction, data is read from the underlying stream using * a Reader instance and then encoded and returned to the caller. * * */ /** * Creates a StreamRecoder instance which implements a two-way * conversion: encode and decode work on the frontend (the * data visible to .read() and .write()) while Reader and Writer * work on the backend (the data in stream). * * You can use these objects to do transparent * transcodings from e.g. latin-1 to utf-8 and back. * * stream must be a file-like object. * * encode and decode must adhere to the Codec interface; Reader and * Writer must be factory functions or classes providing the * StreamReader and StreamWriter interfaces resp. * * Error handling is done in the same way as defined for the * StreamWriter/Readers. * * */ function StreamRecoder(stream, encode, decode, Reader, Writer, errors?): Promise<IStreamRecoder> function StreamRecoder$({ stream, encode, decode, Reader, Writer, errors }: { stream, encode, decode, Reader, Writer, errors?}): Promise<IStreamRecoder> interface IStreamRecoder { read(size?): Promise<any> read$({ size }: { size?}): Promise<any> readline(size?): Promise<any> readline$({ size }: { size?}): Promise<any> readlines(sizehint?): Promise<any> readlines$({ sizehint }: { sizehint?}): Promise<any> write(data): Promise<any> write$({ data }): Promise<any> writelines(list): Promise<any> writelines$({ list }): Promise<any> reset(): Promise<any> reset$($: {}): Promise<any> seek(offset, whence?): Promise<any> seek$({ offset, whence }: { offset, whence?}): Promise<any> data_encoding file_encoding } let BOM_UTF8: Promise<any> let BOM_LE: Promise<any> let BOM_UTF16_LE: Promise<any> let BOM_BE: Promise<any> let BOM_UTF16_BE: Promise<any> let BOM_UTF32_LE: Promise<any> let BOM_UTF32_BE: Promise<any> let BOM: Promise<any> let BOM_UTF16: Promise<any> let BOM_UTF32: Promise<any> let BOM32_LE: Promise<any> let BOM32_BE: Promise<any> let BOM64_LE: Promise<any> let BOM64_BE: Promise<any> let strict_errors: Promise<any> let ignore_errors: Promise<any> let replace_errors: Promise<any> let xmlcharrefreplace_errors: Promise<any> let backslashreplace_errors: Promise<any> let namereplace_errors: Promise<any> } declare module colorsys { var _ function rgb_to_yiq(r, g, b): Promise<any> function rgb_to_yiq$({ r, g, b }): Promise<any> function yiq_to_rgb(y, i, q): Promise<any> function yiq_to_rgb$({ y, i, q }): Promise<any> function rgb_to_hls(r, g, b): Promise<any> function rgb_to_hls$({ r, g, b }): Promise<any> function hls_to_rgb(h, l, s): Promise<any> function hls_to_rgb$({ h, l, s }): Promise<any> function rgb_to_hsv(r, g, b): Promise<any> function rgb_to_hsv$({ r, g, b }): Promise<any> function hsv_to_rgb(h, s, v): Promise<any> function hsv_to_rgb$({ h, s, v }): Promise<any> let ONE_THIRD: Promise<any> let ONE_SIXTH: Promise<any> let TWO_THIRD: Promise<any> } declare module crypt { var _ /** * Generate a salt for the specified method. * * If not specified, the strongest available method will be used. * * */ function mksalt(method?): Promise<any> function mksalt$({ method }: { method?}): Promise<any> /** * Return a string representing the one-way hash of a password, with a salt * prepended. * * If ``salt`` is not specified or is ``None``, the strongest * available method will be selected and a salt generated. Otherwise, * ``salt`` may be one of the ``crypt.METHOD_*`` values, or a string as * returned by ``crypt.mksalt()``. * * */ function crypt(word, salt?): Promise<any> function crypt$({ word, salt }: { word, salt?}): Promise<any> /** * Class representing a salt method per the Modular Crypt Format or the * legacy 2-character crypt method. */ interface I_Method { } let methods: Promise<any> } declare module decimal { var _ } declare module email { module base64mime { var _ /** * Return the length of s when it is encoded with base64. */ function header_length(bytearray): Promise<any> function header_length$({ bytearray }): Promise<any> /** * Encode a single header line with Base64 encoding in a given charset. * * charset names the character set to use to encode the header. It defaults * to iso-8859-1. Base64 encoding is defined in RFC 2045. * */ function header_encode(header_bytes, charset?): Promise<any> function header_encode$({ header_bytes, charset }: { header_bytes, charset?}): Promise<any> /** * Encode a string with base64. * * Each line will be wrapped at, at most, maxlinelen characters (defaults to * 76 characters). * * Each line of encoded text will end with eol, which defaults to "\n". Set * this to "\r\n" if you will be using the result of this function directly * in an email. * */ function body_encode(s, maxlinelen?, eol?): Promise<any> function body_encode$({ s, maxlinelen, eol }: { s, maxlinelen?, eol?}): Promise<any> /** * Decode a raw base64 string, returning a bytes object. * * This function does not parse a full MIME header value encoded with * base64 (like =?iso-8859-1?b?bmloISBuaWgh?=) -- please use the high * level email.header class for that functionality. * */ function decode(string): Promise<any> function decode$({ string }): Promise<any> let CRLF: Promise<any> let NL: Promise<any> let EMPTYSTRING: Promise<any> let MISC_LEN: Promise<any> let body_decode: Promise<any> let decodestring: Promise<any> } } declare module encodings { module base64_codec { var _ function base64_encode(input, errors?): Promise<any> function base64_encode$({ input, errors }: { input, errors?}): Promise<any> function base64_decode(input, errors?): Promise<any> function base64_decode$({ input, errors }: { input, errors?}): Promise<any> function getregentry(): Promise<any> function getregentry$($: {}): Promise<any> interface ICodec { encode(input, errors?): Promise<any> encode$({ input, errors }: { input, errors?}): Promise<any> decode(input, errors?): Promise<any> decode$({ input, errors }: { input, errors?}): Promise<any> } interface IIncrementalEncoder { encode(input, final?: boolean): Promise<any> encode$({ input, final }: { input, final?}): Promise<any> } interface IIncrementalDecoder { decode(input, final?: boolean): Promise<any> decode$({ input, final }: { input, final?}): Promise<any> } interface IStreamWriter extends ICodec { charbuffertype } interface IStreamReader extends ICodec { } } module bz2_codec { var _ function bz2_encode(input, errors?): Promise<any> function bz2_encode$({ input, errors }: { input, errors?}): Promise<any> function bz2_decode(input, errors?): Promise<any> function bz2_decode$({ input, errors }: { input, errors?}): Promise<any> function getregentry(): Promise<any> function getregentry$($: {}): Promise<any> interface ICodec { encode(input, errors?): Promise<any> encode$({ input, errors }: { input, errors?}): Promise<any> decode(input, errors?): Promise<any> decode$({ input, errors }: { input, errors?}): Promise<any> } function IncrementalEncoder(errors?): Promise<IIncrementalEncoder> function IncrementalEncoder$({ errors }: { errors?}): Promise<IIncrementalEncoder> interface IIncrementalEncoder { encode(input, final?: boolean): Promise<any> encode$({ input, final }: { input, final?}): Promise<any> reset(): Promise<any> reset$($: {}): Promise<any> } function IncrementalDecoder(errors?): Promise<IIncrementalDecoder> function IncrementalDecoder$({ errors }: { errors?}): Promise<IIncrementalDecoder> interface IIncrementalDecoder { decode(input, final?: boolean): Promise<any> decode$({ input, final }: { input, final?}): Promise<any> reset(): Promise<any> reset$($: {}): Promise<any> } interface IStreamWriter extends ICodec { charbuffertype } interface IStreamReader extends ICodec { } } module hex_codec { var _ function hex_encode(input, errors?): Promise<any> function hex_encode$({ input, errors }: { input, errors?}): Promise<any> function hex_decode(input, errors?): Promise<any> function hex_decode$({ input, errors }: { input, errors?}): Promise<any> function getregentry(): Promise<any> function getregentry$($: {}): Promise<any> interface ICodec { encode(input, errors?): Promise<any> encode$({ input, errors }: { input, errors?}): Promise<any> decode(input, errors?): Promise<any> decode$({ input, errors }: { input, errors?}): Promise<any> } interface IIncrementalEncoder { encode(input, final?: boolean): Promise<any> encode$({ input, final }: { input, final?}): Promise<any> } interface IIncrementalDecoder { decode(input, final?: boolean): Promise<any> decode$({ input, final }: { input, final?}): Promise<any> } interface IStreamWriter extends ICodec { charbuffertype } interface IStreamReader extends ICodec { } } module palmos { var _ function getregentry(): Promise<any> function getregentry$($: {}): Promise<any> interface ICodec { encode(input, errors?): Promise<any> encode$({ input, errors }: { input, errors?}): Promise<any> decode(input, errors?): Promise<any> decode$({ input, errors }: { input, errors?}): Promise<any> } interface IIncrementalEncoder { encode(input, final?: boolean): Promise<any> encode$({ input, final }: { input, final?}): Promise<any> } interface IIncrementalDecoder { decode(input, final?: boolean): Promise<any> decode$({ input, final }: { input, final?}): Promise<any> } interface IStreamWriter extends ICodec { } interface IStreamReader extends ICodec { } let decoding_table: Promise<any> let encoding_table: Promise<any> } module quopri_codec { var _ function quopri_encode(input, errors?): Promise<any> function quopri_encode$({ input, errors }: { input, errors?}): Promise<any> function quopri_decode(input, errors?): Promise<any> function quopri_decode$({ input, errors }: { input, errors?}): Promise<any> function getregentry(): Promise<any> function getregentry$($: {}): Promise<any> interface ICodec { encode(input, errors?): Promise<any> encode$({ input, errors }: { input, errors?}): Promise<any> decode(input, errors?): Promise<any> decode$({ input, errors }: { input, errors?}): Promise<any> } interface IIncrementalEncoder { encode(input, final?: boolean): Promise<any> encode$({ input, final }: { input, final?}): Promise<any> } interface IIncrementalDecoder { decode(input, final?: boolean): Promise<any> decode$({ input, final }: { input, final?}): Promise<any> } interface IStreamWriter extends ICodec { charbuffertype } interface IStreamReader extends ICodec { } } module uu_codec { var _ function uu_encode(input, errors?, filename?, mode?): Promise<any> function uu_encode$({ input, errors, filename, mode }: { input, errors?, filename?, mode?}): Promise<any> function uu_decode(input, errors?): Promise<any> function uu_decode$({ input, errors }: { input, errors?}): Promise<any> function getregentry(): Promise<any> function getregentry$($: {}): Promise<any> interface ICodec { encode(input, errors?): Promise<any> encode$({ input, errors }: { input, errors?}): Promise<any> decode(input, errors?): Promise<any> decode$({ input, errors }: { input, errors?}): Promise<any> } interface IIncrementalEncoder { encode(input, final?: boolean): Promise<any> encode$({ input, final }: { input, final?}): Promise<any> } interface IIncrementalDecoder { decode(input, final?: boolean): Promise<any> decode$({ input, final }: { input, final?}): Promise<any> } interface IStreamWriter extends ICodec { charbuffertype } interface IStreamReader extends ICodec { } } module zlib_codec { var _ function zlib_encode(input, errors?): Promise<any> function zlib_encode$({ input, errors }: { input, errors?}): Promise<any> function zlib_decode(input, errors?): Promise<any> function zlib_decode$({ input, errors }: { input, errors?}): Promise<any> function getregentry(): Promise<any> function getregentry$($: {}): Promise<any> interface ICodec { encode(input, errors?): Promise<any> encode$({ input, errors }: { input, errors?}): Promise<any> decode(input, errors?): Promise<any> decode$({ input, errors }: { input, errors?}): Promise<any> } function IncrementalEncoder(errors?): Promise<IIncrementalEncoder> function IncrementalEncoder$({ errors }: { errors?}): Promise<IIncrementalEncoder> interface IIncrementalEncoder { encode(input, final?: boolean): Promise<any> encode$({ input, final }: { input, final?}): Promise<any> reset(): Promise<any> reset$($: {}): Promise<any> } function IncrementalDecoder(errors?): Promise<IIncrementalDecoder> function IncrementalDecoder$({ errors }: { errors?}): Promise<IIncrementalDecoder> interface IIncrementalDecoder { decode(input, final?: boolean): Promise<any> decode$({ input, final }: { input, final?}): Promise<any> reset(): Promise<any> reset$($: {}): Promise<any> } interface IStreamWriter extends ICodec { charbuffertype } interface IStreamReader extends ICodec { } } } declare module export { var _ function export_json(tree, pretty_print ?: boolean): Promise < any > function export_json$({ tree, pretty_print }: { tree, pretty_print?}): Promise<any> function export_dict(tree): Promise<any> function export_dict$({ tree }): Promise<any> interface IDictExportVisitor { visit(node): Promise<any> visit$({ node }): Promise<any> default_visit(node): Promise<any> default_visit$({ node }): Promise<any> default_visit_field(val): Promise<any> default_visit_field$({ val }): Promise<any> visit_str(val): Promise<any> visit_str$({ val }): Promise<any> visit_Bytes(val): Promise<any> visit_Bytes$({ val }): Promise<any> visit_NoneType(val): Promise<any> visit_NoneType$({ val }): Promise<any> visit_field_NameConstant_value(val): Promise<any> visit_field_NameConstant_value$({ val }): Promise<any> visit_field_Num_n(val): Promise<any> visit_field_Num_n$({ val }): Promise<any> ast_type_field } } declare module gzip { var _ /** * Open a gzip-compressed file in binary or text mode. * * The filename argument can be an actual filename (a str or bytes object), or * an existing file object to read from or write to. * * The mode argument can be "r", "rb", "w", "wb", "x", "xb", "a" or "ab" for * binary mode, or "rt", "wt", "xt" or "at" for text mode. The default mode is * "rb", and the default compresslevel is 9. * * For binary mode, this function is equivalent to the GzipFile constructor: * GzipFile(filename, mode, compresslevel). In this case, the encoding, errors * and newline arguments must not be provided. * * For text mode, a GzipFile object is created, and wrapped in an * io.TextIOWrapper instance with the specified encoding, error handling * behavior, and line ending(s). * * */ function open(filename, mode?, compresslevel?, encoding?, errors?, newline?): Promise<any> function open$({ filename, mode, compresslevel, encoding, errors, newline }: { filename, mode?, compresslevel?, encoding?, errors?, newline?}): Promise<any> function write32u(output, value): Promise<any> function write32u$({ output, value }): Promise<any> /** * Compress data in one shot and return the compressed string. * Optional argument is the compression level, in range of 0-9. * */ function compress(data, compresslevel?): Promise<any> function compress$({ data, compresslevel }: { data, compresslevel?}): Promise<any> /** * Decompress a gzip compressed string in one shot. * Return the decompressed string. * */ function decompress(data): Promise<any> function decompress$({ data }): Promise<any> function main(): Promise<any> function main$($: {}): Promise<any> /** * Minimal read-only file object that prepends a string to the contents * of an actual file. Shouldn't be used outside of gzip.py, as it lacks * essential functionality. */ interface I_PaddedFile { read(size): Promise<any> read$({ size }): Promise<any> prepend(prepend?): Promise<any> prepend$({ prepend }: { prepend?}): Promise<any> seek(off): Promise<any> seek$({ off }): Promise<any> seekable(): Promise<any> seekable$($: {}): Promise<any> } /** * Exception raised in some cases for invalid gzip files. */ interface IBadGzipFile { } /** * The GzipFile class simulates most of the methods of a file object with * the exception of the truncate() method. * * This class only supports opening files in binary mode. If you need to open a * compressed file in text mode, use the gzip.open() function. * * */ /** * Constructor for the GzipFile class. * * At least one of fileobj and filename must be given a * non-trivial value. * * The new class instance is based on fileobj, which can be a regular * file, an io.BytesIO object, or any other object which simulates a file. * It defaults to None, in which case filename is opened to provide * a file object. * * When fileobj is not None, the filename argument is only used to be * included in the gzip file header, which may include the original * filename of the uncompressed file. It defaults to the filename of * fileobj, if discernible; otherwise, it defaults to the empty string, * and in this case the original filename is not included in the header. * * The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', 'wb', 'x', or * 'xb' depending on whether the file will be read or written. The default * is the mode of fileobj if discernible; otherwise, the default is 'rb'. * A mode of 'r' is equivalent to one of 'rb', and similarly for 'w' and * 'wb', 'a' and 'ab', and 'x' and 'xb'. * * The compresslevel argument is an integer from 0 to 9 controlling the * level of compression; 1 is fastest and produces the least compression, * and 9 is slowest and produces the most compression. 0 is no compression * at all. The default is 9. * * The mtime argument is an optional numeric timestamp to be written * to the last modification time field in the stream when compressing. * If omitted or None, the current time is used. * * */ function GzipFile(filename?, mode?, compresslevel?, fileobj?, mtime?): Promise<IGzipFile> function GzipFile$({ filename, mode, compresslevel, fileobj, mtime }: { filename?, mode?, compresslevel?, fileobj?, mtime?}): Promise<IGzipFile> interface IGzipFile { filename(): Promise<any> filename$($: {}): Promise<any> /** * Last modification time read from stream, or None */ mtime(): Promise<any> mtime$($: {}): Promise<any> write(data): Promise<any> write$({ data }): Promise<any> read(size?): Promise<any> read$({ size }: { size?}): Promise<any> /** * Implements BufferedIOBase.read1() * * Reads up to a buffer's worth of data if size is negative. */ read1(size?): Promise<any> read1$({ size }: { size?}): Promise<any> peek(n): Promise<any> peek$({ n }): Promise<any> closed(): Promise<any> closed$($: {}): Promise<any> close(): Promise<any> close$($: {}): Promise<any> flush(zlib_mode?): Promise<any> flush$({ zlib_mode }: { zlib_mode?}): Promise<any> /** * Invoke the underlying file object's fileno() method. * * This will raise AttributeError if the underlying file object * doesn't support fileno(). * */ fileno(): Promise<any> fileno$($: {}): Promise<any> /** * Return the uncompressed stream file position indicator to the * beginning of the file */ rewind(): Promise<any> rewind$($: {}): Promise<any> readable(): Promise<any> readable$($: {}): Promise<any> writable(): Promise<any> writable$($: {}): Promise<any> seekable(): Promise<any> seekable$($: {}): Promise<any> seek(offset, whence?): Promise<any> seek$({ offset, whence }: { offset, whence?}): Promise<any> readline(size?): Promise<any> readline$({ size }: { size?}): Promise<any> myfileobj } interface I_GzipReader { read(size?): Promise<any> read$({ size }: { size?}): Promise<any> } } declare module hashlib { var _ let algorithms_guaranteed: Promise<any> let algorithms_available: Promise<any> let new$: Promise<any> } declare module idlelib { module codecontext { var _ /** * Extract the beginning whitespace and first word from codeline. */ function get_spaces_firstword(codeline, c?): Promise<any> function get_spaces_firstword$({ codeline, c }: { codeline, c?}): Promise<any> /** * Return tuple of (line indent value, codeline, block start keyword). * * The indentation of empty lines (or comment lines) is INFINITY. * If the line does not start a block, the keyword value is False. * */ function get_line_info(codeline): Promise<any> function get_line_info$({ codeline }): Promise<any> /** * Display block context above the edit window. */ /** * Initialize settings for context block. * * editwin is the Editor window for the context block. * self.text is the editor window text widget. * * self.context displays the code context text above the editor text. * Initially None, it is toggled via <<toggle-code-context>>. * self.topvisible is the number of the top text line displayed. * self.info is a list of (line number, indent level, line text, * block keyword) tuples for the block structure above topvisible. * self.info[0] is initialized with a 'dummy' line which * starts the toplevel 'block' of the module. * * self.t1 and self.t2 are two timer events on the editor text widget to * monitor for changes to the context text or editor font. * */ function CodeContext(editwin): Promise<ICodeContext> function CodeContext$({ editwin }): Promise<ICodeContext> interface ICodeContext { /** * Load class variables from config. */ reload(): Promise<any> reload$($: {}): Promise<any> /** * Toggle code context display. * * If self.context doesn't exist, create it to match the size of the editor * window text (toggle on). If it does exist, destroy it (toggle off). * Return 'break' to complete the processing of the binding. * */ toggle_code_context_event(event?): Promise<any> toggle_code_context_event$({ event }: { event?}): Promise<any> /** * Return a list of block line tuples and the 'last' indent. * * The tuple fields are (linenum, indent, text, opener). * The list represents header lines from new_topvisible back to * stopline with successively shorter indents > stopindent. * The list is returned ordered by line number. * Last indent returned is the smallest indent observed. * */ get_context(new_topvisible, stopline?, stopindent?): Promise<any> get_context$({ new_topvisible, stopline, stopindent }: { new_topvisible, stopline?, stopindent?}): Promise<any> /** * Update context information and lines visible in the context pane. * * No update is done if the text hasn't been scrolled. If the text * was scrolled, the lines that should be shown in the context will * be retrieved and the context area will be updated with the code, * up to the number of maxlines. * */ update_code_context(): Promise<any> update_code_context$($: {}): Promise<any> /** * Show clicked context line at top of editor. * * If a selection was made, don't jump; allow copying. * If no visible context, show the top line of the file. * */ jumptoline(event?): Promise<any> jumptoline$({ event }: { event?}): Promise<any> /** * Event on editor text widget triggered every UPDATEINTERVAL ms. */ timer_event(): Promise<any> timer_event$($: {}): Promise<any> update_font(): Promise<any> update_font$($: {}): Promise<any> update_highlight_colors(): Promise<any> update_highlight_colors$($: {}): Promise<any> UPDATEINTERVAL } let BLOCKOPENERS: Promise<any> } module statusbar { var _ function MultiStatusBar(master): Promise<IMultiStatusBar> function MultiStatusBar$({ master }): Promise<IMultiStatusBar> interface IMultiStatusBar { set_label(name, text?, side?, width?): Promise<any> set_label$({ name, text, side, width }: { name, text?, side?, width?}): Promise<any> } } } declare module os { var _ /** * makedirs(name [, mode=0o777][, exist_ok=False]) * * Super-mkdir; create a leaf directory and all intermediate ones. Works like * mkdir, except that any intermediate path segment (not just the rightmost) * will be created if it does not exist. If the target directory already * exists, raise an OSError if exist_ok is False. Otherwise no exception is * raised. This is recursive. * * */ function makedirs(name, mode?, exist_ok?: boolean): Promise<any> function makedirs$({ name, mode, exist_ok }: { name, mode?, exist_ok?}): Promise<any> /** * removedirs(name) * * Super-rmdir; remove a leaf directory and all empty intermediate * ones. Works like rmdir except that, if the leaf directory is * successfully removed, directories corresponding to rightmost path * segments will be pruned away until either the whole path is * consumed or an error occurs. Errors during this latter phase are * ignored -- they generally mean that a directory was not empty. * * */ function removedirs(name): Promise<any> function removedirs$({ name }): Promise<any> /** * renames(old, new) * * Super-rename; create directories as necessary and delete any left * empty. Works like rename, except creation of any intermediate * directories needed to make the new pathname good is attempted * first. After the rename, directories corresponding to rightmost * path segments of the old name will be pruned until either the * whole path is consumed or a nonempty directory is found. * * Note: this function can fail with the new directory structure made * if you lack permissions needed to unlink the leaf directory or * file. * * */ function renames(old, New): Promise<any> function renames$({ old, New }): Promise<any> /** * Directory tree generator. * * For each directory in the directory tree rooted at top (including top * itself, but excluding '.' and '..'), yields a 3-tuple * * dirpath, dirnames, filenames * * dirpath is a string, the path to the directory. dirnames is a list of * the names of the subdirectories in dirpath (excluding '.' and '..'). * filenames is a list of the names of the non-directory files in dirpath. * Note that the names in the lists are just names, with no path components. * To get a full path (which begins with top) to a file or directory in * dirpath, do os.path.join(dirpath, name). * * If optional arg 'topdown' is true or not specified, the triple for a * directory is generated before the triples for any of its subdirectories * (directories are generated top down). If topdown is false, the triple * for a directory is generated after the triples for all of its * subdirectories (directories are generated bottom up). * * When topdown is true, the caller can modify the dirnames list in-place * (e.g., via del or slice assignment), and walk will only recurse into the * subdirectories whose names remain in dirnames; this can be used to prune the * search, or to impose a specific order of visiting. Modifying dirnames when * topdown is false has no effect on the behavior of os.walk(), since the * directories in dirnames have already been generated by the time dirnames * itself is generated. No matter the value of topdown, the list of * subdirectories is retrieved before the tuples for the directory and its * subdirectories are generated. * * By default errors from the os.scandir() call are ignored. If * optional arg 'onerror' is specified, it should be a function; it * will be called with one argument, an OSError instance. It can * report the error to continue with the walk, or raise the exception * to abort the walk. Note that the filename is available as the * filename attribute of the exception object. * * By default, os.walk does not follow symbolic links to subdirectories on * systems that support them. In order to get this functionality, set the * optional argument 'followlinks' to true. * * Caution: if you pass a relative pathname for top, don't change the * current working directory between resumptions of walk. walk never * changes the current directory, and assumes that the client doesn't * either. * * Example: * * import os * from os.path import join, getsize * for root, dirs, files in os.walk('python/Lib/email'): * print(root, "consumes", end="") * print(sum(getsize(join(root, name)) for name in files), end="") * print("bytes in", len(files), "non-directory files") * if 'CVS' in dirs: * dirs.remove('CVS') # don't visit CVS directories * * */ function walk(top, topdown?: boolean, onerror?, followlinks?: boolean): Promise<any> function walk$({ top, topdown, onerror, followlinks }: { top, topdown?, onerror?, followlinks?}): Promise<any> /** * Directory tree generator. * * This behaves exactly like walk(), except that it yields a 4-tuple * * dirpath, dirnames, filenames, dirfd * * `dirpath`, `dirnames` and `filenames` are identical to walk() output, * and `dirfd` is a file descriptor referring to the directory `dirpath`. * * The advantage of fwalk() over walk() is that it's safe against symlink * races (when follow_symlinks is False). * * If dir_fd is not None, it should be a file descriptor open to a directory, * and top should be relative; top will then be relative to that directory. * (dir_fd is always supported for fwalk.) * * Caution: * Since fwalk() yields file descriptors, those are only valid until the * next iteration step, so you should dup() them if you want to keep them * for a longer period. * * Example: * * import os * for root, dirs, files, rootfd in os.fwalk('python/Lib/email'): * print(root, "consumes", end="") * print(sum(os.stat(name, dir_fd=rootfd).st_size for name in files), * end="") * print("bytes in", len(files), "non-directory files") * if 'CVS' in dirs: * dirs.remove('CVS') # don't visit CVS directories * */ function fwalk(top?, topdown?: boolean, onerror?): Promise<any> function fwalk$({ top, topdown, onerror }: { top?, topdown?, onerror?}): Promise<any> /** * execl(file, *args) * * Execute the executable file with argument list args, replacing the * current process. */ function execl(file): Promise<any> function execl$({ file }): Promise<any> /** * execle(file, *args, env) * * Execute the executable file with argument list args and * environment env, replacing the current process. */ function execle(file): Promise<any> function execle$({ file }): Promise<any> /** * execlp(file, *args) * * Execute the executable file (which is searched for along $PATH) * with argument list args, replacing the current process. */ function execlp(file): Promise<any> function execlp$({ file }): Promise<any> /** * execlpe(file, *args, env) * * Execute the executable file (which is searched for along $PATH) * with argument list args and environment env, replacing the current * process. */ function execlpe(file): Promise<any> function execlpe$({ file }): Promise<any> /** * execvp(file, args) * * Execute the executable file (which is searched for along $PATH) * with argument list args, replacing the current process. * args may be a list or tuple of strings. */ function execvp(file, args): Promise<any> function execvp$({ file, args }): Promise<any> /** * execvpe(file, args, env) * * Execute the executable file (which is searched for along $PATH) * with argument list args and environment env, replacing the * current process. * args may be a list or tuple of strings. */ function execvpe(file, args, env): Promise<any> function execvpe$({ file, args, env }): Promise<any> /** * Returns the sequence of directories that will be searched for the * named executable (similar to a shell) when launching a process. * * *env* must be an environment variable dict or None. If *env* is None, * os.environ will be used. * */ function get_exec_path(env?): Promise<any> function get_exec_path$({ env }: { env?}): Promise<any> /** * Get an environment variable, return None if it doesn't exist. * The optional second argument can specify an alternate default. * key, default and the result are str. */ function getenv(key, def?): Promise<any> function getenv$({ key, def }: { key, def?}): Promise<any> /** * Get an environment variable, return None if it doesn't exist. * The optional second argument can specify an alternate default. * key, default and the result are bytes. */ function getenvb(key, def?): Promise<any> function getenvb$({ key, def }: { key, def?}): Promise<any> /** * spawnv(mode, file, args) -> integer * * Execute file with arguments from args in a subprocess. * If mode == P_NOWAIT return the pid of the process. * If mode == P_WAIT return the process's exit code if it exits normally; * otherwise return -SIG, where SIG is the signal that killed it. */ function spawnv(mode, file, args): Promise<any> function spawnv$({ mode, file, args }): Promise<any> /** * spawnve(mode, file, args, env) -> integer * * Execute file with arguments from args in a subprocess with the * specified environment. * If mode == P_NOWAIT return the pid of the process. * If mode == P_WAIT return the process's exit code if it exits normally; * otherwise return -SIG, where SIG is the signal that killed it. */ function spawnve(mode, file, args, env): Promise<any> function spawnve$({ mode, file, args, env }): Promise<any> /** * spawnvp(mode, file, args) -> integer * * Execute file (which is looked for along $PATH) with arguments from * args in a subprocess. * If mode == P_NOWAIT return the pid of the process. * If mode == P_WAIT return the process's exit code if it exits normally; * otherwise return -SIG, where SIG is the signal that killed it. */ function spawnvp(mode, file, args): Promise<any> function spawnvp$({ mode, file, args }): Promise<any> /** * spawnvpe(mode, file, args, env) -> integer * * Execute file (which is looked for along $PATH) with arguments from * args in a subprocess with the supplied environment. * If mode == P_NOWAIT return the pid of the process. * If mode == P_WAIT return the process's exit code if it exits normally; * otherwise return -SIG, where SIG is the signal that killed it. */ function spawnvpe(mode, file, args, env): Promise<any> function spawnvpe$({ mode, file, args, env }): Promise<any> /** * spawnl(mode, file, *args) -> integer * * Execute file with arguments from args in a subprocess. * If mode == P_NOWAIT return the pid of the process. * If mode == P_WAIT return the process's exit code if it exits normally; * otherwise return -SIG, where SIG is the signal that killed it. */ function spawnl(mode, file): Promise<any> function spawnl$({ mode, file }): Promise<any> /** * spawnle(mode, file, *args, env) -> integer * * Execute file with arguments from args in a subprocess with the * supplied environment. * If mode == P_NOWAIT return the pid of the process. * If mode == P_WAIT return the process's exit code if it exits normally; * otherwise return -SIG, where SIG is the signal that killed it. */ function spawnle(mode, file): Promise<any> function spawnle$({ mode, file }): Promise<any> /** * spawnlp(mode, file, *args) -> integer * * Execute file (which is looked for along $PATH) with arguments from * args in a subprocess with the supplied environment. * If mode == P_NOWAIT return the pid of the process. * If mode == P_WAIT return the process's exit code if it exits normally; * otherwise return -SIG, where SIG is the signal that killed it. */ function spawnlp(mode, file): Promise<any> function spawnlp$({ mode, file }): Promise<any> /** * spawnlpe(mode, file, *args, env) -> integer * * Execute file (which is looked for along $PATH) with arguments from * args in a subprocess with the supplied environment. * If mode == P_NOWAIT return the pid of the process. * If mode == P_WAIT return the process's exit code if it exits normally; * otherwise return -SIG, where SIG is the signal that killed it. */ function spawnlpe(mode, file): Promise<any> function spawnlpe$({ mode, file }): Promise<any> function popen(cmd, mode?, buffering?): Promise<any> function popen$({ cmd, mode, buffering }: { cmd, mode?, buffering?}): Promise<any> function fdopen(fd, mode?, buffering?, encoding?): Promise<any> function fdopen$({ fd, mode, buffering, encoding }: { fd, mode?, buffering?, encoding?}): Promise<any> /** * Add a path to the DLL search path. * * This search path is used when resolving dependencies for imported * extension modules (the module itself is resolved through sys.path), * and also by ctypes. * * Remove the directory by calling close() on the returned object or * using it in a with statement. * */ function add_dll_directory(path): Promise<any> function add_dll_directory$({ path }): Promise<any> interface I_Environ { copy(): Promise<any> copy$($: {}): Promise<any> setdefault(key, value): Promise<any> setdefault$({ key, value }): Promise<any> } interface I_wrap_close { close(): Promise<any> close$($: {}): Promise<any> } /** * Abstract base class for implementing the file system path protocol. */ interface IPathLike { } interface I_AddedDllDirectory { close(): Promise<any> close$($: {}): Promise<any> } let GenericAlias: Promise<any> let name: Promise<any> let linesep: Promise<any> let supports_dir_fd: Promise<any> let supports_effective_ids: Promise<any> let supports_fd: Promise<any> let supports_follow_symlinks: Promise<any> let SEEK_SET: Promise<any> let SEEK_CUR: Promise<any> let SEEK_END: Promise<any> let environ: Promise<any> let supports_bytes_environ: Promise<any> let environb: Promise<any> let P_WAIT: Promise<any> let P_NOWAIT: Promise<any> let P_NOWAITO: Promise<any> let fspath: Promise<any> } declare module platform { var _ /** * Tries to determine the libc version that the file executable * (which defaults to the Python interpreter) is linked against. * * Returns a tuple of strings (lib,version) which default to the * given parameters in case the lookup fails. * * Note that the function has intimate knowledge of how different * libc versions add symbols to the executable and thus is probably * only usable for executables compiled using gcc. * * The file is read and scanned in chunks of chunksize bytes. * * */ function libc_ver(executable?, lib?, version?, chunksize?): Promise<any> function libc_ver$({ executable, lib, version, chunksize }: { executable?, lib?, version?, chunksize?}): Promise<any> function win32_is_iot(): Promise<any> function win32_is_iot$($: {}): Promise<any> function win32_edition(): Promise<any> function win32_edition$($: {}): Promise<any> function win32_ver(release?, version?, csd?, ptype?): Promise<any> function win32_ver$({ release, version, csd, ptype }: { release?, version?, csd?, ptype?}): Promise<any> /** * Get macOS version information and return it as tuple (release, * versioninfo, machine) with versioninfo being a tuple (version, * dev_stage, non_release_version). * * Entries which cannot be determined are set to the parameter values * which default to ''. All tuple entries are strings. * */ function mac_ver(release?, versioninfo?, machine?): Promise<any> function mac_ver$({ release, versioninfo, machine }: { release?, versioninfo?, machine?}): Promise<any> /** * Version interface for Jython. * * Returns a tuple (release, vendor, vminfo, osinfo) with vminfo being * a tuple (vm_name, vm_release, vm_vendor) and osinfo being a * tuple (os_name, os_version, os_arch). * * Values which cannot be determined are set to the defaults * given as parameters (which all default to ''). * * */ function java_ver(release?, vendor?, vminfo?, osinfo?): Promise<any> function java_ver$({ release, vendor, vminfo, osinfo }: { release?, vendor?, vminfo?, osinfo?}): Promise<any> /** * Returns (system, release, version) aliased to common * marketing names used for some systems. * * It also does some reordering of the information in some cases * where it would otherwise cause confusion. * * */ function system_alias(system, release, version): Promise<any> function system_alias$({ system, release, version }): Promise<any> /** * Queries the given executable (defaults to the Python interpreter * binary) for various architecture information. * * Returns a tuple (bits, linkage) which contains information about * the bit architecture and the linkage format used for the * executable. Both values are returned as strings. * * Values that cannot be determined are returned as given by the * parameter presets. If bits is given as '', the sizeof(pointer) * (or sizeof(long) on Python version < 1.5.2) is used as * indicator for the supported pointer size. * * The function relies on the system's "file" command to do the * actual work. This is available on most if not all Unix * platforms. On some non-Unix platforms where the "file" command * does not exist and the executable is set to the Python interpreter * binary defaults from _default_architecture are used. * * */ function architecture(executable?, bits?, linkage?): Promise<any> function architecture$({ executable, bits, linkage }: { executable?, bits?, linkage?}): Promise<any> /** * Fairly portable uname interface. Returns a tuple * of strings (system, node, release, version, machine, processor) * identifying the underlying platform. * * Note that unlike the os.uname function this also returns * possible processor information as an additional tuple entry. * * Entries which cannot be determined are set to ''. * * */ function uname(): Promise<any> function uname$($: {}): Promise<any> /** * Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'. * * An empty string is returned if the value cannot be determined. * * */ function system(): Promise<any> function system$($: {}): Promise<any> /** * Returns the computer's network name (which may not be fully * qualified) * * An empty string is returned if the value cannot be determined. * * */ function node(): Promise<any> function node$($: {}): Promise<any> /** * Returns the system's release, e.g. '2.2.0' or 'NT' * * An empty string is returned if the value cannot be determined. * * */ function release(): Promise<any> function release$($: {}): Promise<any> /** * Returns the system's release version, e.g. '#3 on degas' * * An empty string is returned if the value cannot be determined. * * */ function version(): Promise<any> function version$($: {}): Promise<any> /** * Returns the machine type, e.g. 'i386' * * An empty string is returned if the value cannot be determined. * * */ function machine(): Promise<any> function machine$($: {}): Promise<any> /** * Returns the (true) processor name, e.g. 'amdk6' * * An empty string is returned if the value cannot be * determined. Note that many platforms do not provide this * information or simply return the same value as for machine(), * e.g. NetBSD does this. * * */ function processor(): Promise<any> function processor$($: {}): Promise<any> /** * Returns a string identifying the Python implementation. * * Currently, the following implementations are identified: * 'CPython' (C implementation of Python), * 'IronPython' (.NET implementation of Python), * 'Jython' (Java implementation of Python), * 'PyPy' (Python implementation of Python). * * */ function python_implementation(): Promise<any> function python_implementation$($: {}): Promise<any> /** * Returns the Python version as string 'major.minor.patchlevel' * * Note that unlike the Python sys.version, the returned value * will always include the patchlevel (it defaults to 0). * * */ function python_version(): Promise<any> function python_version$($: {}): Promise<any> /** * Returns the Python version as tuple (major, minor, patchlevel) * of strings. * * Note that unlike the Python sys.version, the returned value * will always include the patchlevel (it defaults to 0). * * */ function python_version_tuple(): Promise<any> function python_version_tuple$($: {}): Promise<any> /** * Returns a string identifying the Python implementation * branch. * * For CPython this is the SCM branch from which the * Python binary was built. * * If not available, an empty string is returned. * * */ function python_branch(): Promise<any> function python_branch$($: {}): Promise<any> /** * Returns a string identifying the Python implementation * revision. * * For CPython this is the SCM revision from which the * Python binary was built. * * If not available, an empty string is returned. * * */ function python_revision(): Promise<any> function python_revision$($: {}): Promise<any> /** * Returns a tuple (buildno, builddate) stating the Python * build number and date as strings. * * */ function python_build(): Promise<any> function python_build$($: {}): Promise<any> /** * Returns a string identifying the compiler used for compiling * Python. * * */ function python_compiler(): Promise<any> function python_compiler$($: {}): Promise<any> /** * Returns a single string identifying the underlying platform * with as much useful information as possible (but no more :). * * The output is intended to be human readable rather than * machine parseable. It may look different on different * platforms and this is intended. * * If "aliased" is true, the function will use aliases for * various platforms that report system names which differ from * their common names, e.g. SunOS will be reported as * Solaris. The system_alias() function is used to implement * this. * * Setting terse to true causes the function to return only the * absolute minimum information needed to identify the platform. * * */ function platform(aliased?, terse?): Promise<any> function platform$({ aliased, terse }: { aliased?, terse?}): Promise<any> /** * Return operation system identification from freedesktop.org os-release * */ function freedesktop_os_release(): Promise<any> function freedesktop_os_release$($: {}): Promise<any> interface I_Processor { get(): Promise<any> get$($: {}): Promise<any> get_win32(): Promise<any> get_win32$($: {}): Promise<any> get_OpenVMS(): Promise<any> get_OpenVMS$($: {}): Promise<any> /** * * Fall back to `uname -p` * */ from_subprocess(): Promise<any> from_subprocess$($: {}): Promise<any> } /** * * A uname_result that's largely compatible with a * simple namedtuple except that 'processor' is * resolved late and cached to avoid calling "uname" * except when needed. * */ interface Iuname_result { processor(): Promise<any> processor$($: {}): Promise<any> } let terse: Promise<any> let aliased: Promise<any> } declare module pstats { var _ function func_strip_path(func_name): Promise<any> function func_strip_path$({ func_name }): Promise<any> function func_get_function_name(func): Promise<any> function func_get_function_name$({ func }): Promise<any> function func_std_string(func_name): Promise<any> function func_std_string$({ func_name }): Promise<any> /** * Add together all the stats for two profile entries. */ function add_func_stats(target, source): Promise<any> function add_func_stats$({ target, source }): Promise<any> /** * Combine two caller lists in a single list. */ function add_callers(target, source): Promise<any> function add_callers$({ target, source }): Promise<any> /** * Sum the caller statistics to get total number of calls received. */ function count_calls(callers): Promise<any> function count_calls$({ callers }): Promise<any> function f8(x): Promise<any> function f8$({ x }): Promise<any> interface ISortKey { CALLS CUMULATIVE FILENAME LINE NAME NFL PCALLS STDNAME TIME } interface IFunctionProfile { } /** * Class for keeping track of an item in inventory. */ interface IStatsProfile { } /** * This class is used for creating reports from data generated by the * Profile class. It is a "friend" of that class, and imports data either * by direct access to members of Profile class, or by reading in a dictionary * that was emitted (via marshal) from the Profile class. * * The big change from the previous Profiler (in terms of raw functionality) * is that an "add()" method has been provided to combine Stats from * several distinct profile runs. Both the constructor and the add() * method now take arbitrarily many file names as arguments. * * All the print methods now take an argument that indicates how many lines * to print. If the arg is a floating point number between 0 and 1.0, then * it is taken as a decimal percentage of the available lines to be printed * (e.g., .1 means print 10% of all available lines). If it is an integer, * it is taken to mean the number of lines of data that you wish to have * printed. * * The sort_stats() method now processes some additional options (i.e., in * addition to the old -1, 0, 1, or 2 that are respectively interpreted as * 'stdname', 'calls', 'time', and 'cumulative'). It takes either an * arbitrary number of quoted strings or SortKey enum to select the sort * order. * * For example sort_stats('time', 'name') or sort_stats(SortKey.TIME, * SortKey.NAME) sorts on the major key of 'internal function time', and on * the minor key of 'the name of the function'. Look at the two tables in * sort_stats() and get_sort_arg_defs(self) for more examples. * * All methods return self, so you can string together commands like: * Stats('foo', 'goo').strip_dirs().sort_stats('calls'). print_stats(5).print_callers(5) * */ function Stats(): Promise<IStats> function Stats$({ }): Promise<IStats> interface IStats { init(arg): Promise<any> init$({ arg }): Promise<any> load_stats(arg): Promise<any> load_stats$({ arg }): Promise<any> get_top_level_stats(): Promise<any> get_top_level_stats$($: {}): Promise<any> add(): Promise<any> add$($: {}): Promise<any> /** * Write the profile data to a file we know how to load back. */ dump_stats(filename): Promise<any> dump_stats$({ filename }): Promise<any> /** * Expand all abbreviations that are unique. */ get_sort_arg_defs(): Promise<any> get_sort_arg_defs$($: {}): Promise<any> sort_stats(): Promise<any> sort_stats$($: {}): Promise<any> reverse_order(): Promise<any> reverse_order$($: {}): Promise<any> strip_dirs(): Promise<any> strip_dirs$($: {}): Promise<any> calc_callees(): Promise<any> calc_callees$($: {}): Promise<any> eval_print_amount(sel, list, msg): Promise<any> eval_print_amount$({ sel, list, msg }): Promise<any> /** * This method returns an instance of StatsProfile, which contains a mapping * of function names to instances of FunctionProfile. Each FunctionProfile * instance holds information related to the function's profile such as how * long the function took to run, how many times it was called, etc... * */ get_stats_profile(): Promise<any> get_stats_profile$($: {}): Promise<any> get_print_list(sel_list): Promise<any> get_print_list$({ sel_list }): Promise<any> print_stats(): Promise<any> print_stats$($: {}): Promise<any> print_callees(): Promise<any> print_callees$($: {}): Promise<any> print_callers(): Promise<any> print_callers$($: {}): Promise<any> print_call_heading(name_size, column_title): Promise<any> print_call_heading$({ name_size, column_title }): Promise<any> print_call_line(name_size, source, call_dict, arrow?): Promise<any> print_call_line$({ name_size, source, call_dict, arrow }: { name_size, source, call_dict, arrow?}): Promise<any> print_title(): Promise<any> print_title$($: {}): Promise<any> print_line(func): Promise<any> print_line$({ func }): Promise<any> sort_arg_dict_default } /** * This class provides a generic function for comparing any two tuples. * Each instance records a list of tuple-indices (from most significant * to least significant), and sort direction (ascending or descending) for * each tuple-index. The compare functions can then be used as the function * argument to the system sort() function when a list of tuples need to be * sorted in the instances order. */ function TupleComp(comp_select_list): Promise<ITupleComp> function TupleComp$({ comp_select_list }): Promise<ITupleComp> interface ITupleComp { compare(left, right): Promise<any> compare$({ left, right }): Promise<any> } function ProfileBrowser(profile?): Promise<IProfileBrowser> function ProfileBrowser$({ profile }: { profile?}): Promise<IProfileBrowser> interface IProfileBrowser { generic(fn, line): Promise<any> generic$({ fn, line }): Promise<any> generic_help(): Promise<any> generic_help$($: {}): Promise<any> do_add(line): Promise<any> do_add$({ line }): Promise<any> help_add(): Promise<any> help_add$($: {}): Promise<any> do_callees(line): Promise<any> do_callees$({ line }): Promise<any> help_callees(): Promise<any> help_callees$($: {}): Promise<any> do_callers(line): Promise<any> do_callers$({ line }): Promise<any> help_callers(): Promise<any> help_callers$($: {}): Promise<any> do_EOF(line): Promise<any> do_EOF$({ line }): Promise<any> help_EOF(): Promise<any> help_EOF$($: {}): Promise<any> do_quit(line): Promise<any> do_quit$({ line }): Promise<any> help_quit(): Promise<any> help_quit$($: {}): Promise<any> do_read(line): Promise<any> do_read$({ line }): Promise<any> help_read(): Promise<any> help_read$($: {}): Promise<any> do_reverse(line): Promise<any> do_reverse$({ line }): Promise<any> help_reverse(): Promise<any> help_reverse$($: {}): Promise<any> do_sort(line): Promise<any> do_sort$({ line }): Promise<any> help_sort(): Promise<any> help_sort$($: {}): Promise<any> complete_sort(text): Promise<any> complete_sort$({ text }): Promise<any> do_stats(line): Promise<any> do_stats$({ line }): Promise<any> help_stats(): Promise<any> help_stats$($: {}): Promise<any> do_strip(line): Promise<any> do_strip$({ line }): Promise<any> help_strip(): Promise<any> help_strip$($: {}): Promise<any> help_help(): Promise<any> help_help$($: {}): Promise<any> postcmd(stop, line): Promise<any> postcmd$({ stop, line }): Promise<any> } let initprofile: Promise<any> let browser: Promise<any> } declare module signal { var _ function signal(signalnum, handler): Promise<any> function signal$({ signalnum, handler }): Promise<any> function getsignal(signalnum): Promise<any> function getsignal$({ signalnum }): Promise<any> function pthread_sigmask(how, mask): Promise<any> function pthread_sigmask$({ how, mask }): Promise<any> function sigpending(): Promise<any> function sigpending$($: {}): Promise<any> function sigwait(sigset): Promise<any> function sigwait$({ sigset }): Promise<any> function valid_signals(): Promise<any> function valid_signals$($: {}): Promise<any> } declare module socket { var _ /** * fromfd(fd, family, type[, proto]) -> socket object * * Create a socket object from a duplicate of the given file * descriptor. The remaining arguments are the same as for socket(). * */ function fromfd(fd, family, type, proto?): Promise<any> function fromfd$({ fd, family, type, proto }: { fd, family, type, proto?}): Promise<any> /** * send_fds(sock, buffers, fds[, flags[, address]]) -> integer * * Send the list of file descriptors fds over an AF_UNIX socket. * */ function send_fds(sock, buffers, fds, flags?, address?): Promise<any> function send_fds$({ sock, buffers, fds, flags, address }: { sock, buffers, fds, flags?, address?}): Promise<any> /** * recv_fds(sock, bufsize, maxfds[, flags]) -> (data, list of file * descriptors, msg_flags, address) * * Receive up to maxfds file descriptors returning the message * data and a list containing the descriptors. * */ function recv_fds(sock, bufsize, maxfds, flags?): Promise<any> function recv_fds$({ sock, bufsize, maxfds, flags }: { sock, bufsize, maxfds, flags?}): Promise<any> /** * fromshare(info) -> socket object * * Create a socket object from the bytes object returned by * socket.share(pid). * */ function fromshare(info): Promise<any> function fromshare$({ info }): Promise<any> /** * socketpair([family[, type[, proto]]]) -> (socket object, socket object) * * Create a pair of socket objects from the sockets returned by the platform * socketpair() function. * The arguments are the same as for socket() except the default family is * AF_UNIX if defined on the platform; otherwise, the default is AF_INET. * */ function socketpair(family?, type?, proto?): Promise<any> function socketpair$({ family, type, proto }: { family?, type?, proto?}): Promise<any> function socketpair(family?, type?, proto?): Promise<any> function socketpair$({ family, type, proto }: { family?, type?, proto?}): Promise<any> /** * Get fully qualified domain name from name. * * An empty argument is interpreted as meaning the local host. * * First the hostname returned by gethostbyaddr() is checked, then * possibly existing aliases. In case no FQDN is available, hostname * from gethostname() is returned. * */ function getfqdn(name?): Promise<any> function getfqdn$({ name }: { name?}): Promise<any> /** * Connect to *address* and return the socket object. * * Convenience function. Connect to *address* (a 2-tuple ``(host, * port)``) and return the socket object. Passing the optional * *timeout* parameter will set the timeout on the socket instance * before attempting to connect. If no *timeout* is supplied, the * global default timeout setting returned by :func:`getdefaulttimeout` * is used. If *source_address* is set it must be a tuple of (host, port) * for the socket to bind as a source address before making the connection. * A host of '' or port 0 tells the OS to use the default. * */ function create_connection(address, timeout?, source_address?): Promise<any> function create_connection$({ address, timeout, source_address }: { address, timeout?, source_address?}): Promise<any> /** * Return True if the platform supports creating a SOCK_STREAM socket * which can handle both AF_INET and AF_INET6 (IPv4 / IPv6) connections. * */ function has_dualstack_ipv6(): Promise<any> function has_dualstack_ipv6$($: {}): Promise<any> /** * Convenience function which creates a SOCK_STREAM type socket * bound to *address* (a 2-tuple (host, port)) and return the socket * object. * * *family* should be either AF_INET or AF_INET6. * *backlog* is the queue size passed to socket.listen(). * *reuse_port* dictates whether to use the SO_REUSEPORT socket option. * *dualstack_ipv6*: if true and the platform supports it, it will * create an AF_INET6 socket able to accept both IPv4 or IPv6 * connections. When false it will explicitly disable this option on * platforms that enable it by default (e.g. Linux). * * >>> with create_server(('', 8000)) as server: * ... while True: * ... conn, addr = server.accept() * ... # handle new connection * */ function create_server(address): Promise<any> function create_server$({ address }): Promise<any> /** * Resolve host and port into list of address info entries. * * Translate the host/port argument into a sequence of 5-tuples that contain * all the necessary arguments for creating a socket connected to that service. * host is a domain name, a string representation of an IPv4/v6 address or * None. port is a string service name such as 'http', a numeric port number or * None. By passing None as the value of host and port, you can pass NULL to * the underlying C API. * * The family, type and proto arguments can be optionally specified in order to * narrow the list of addresses returned. Passing zero as a value for each of * these arguments selects the full range of results. * */ function getaddrinfo(host, port, family?, type?, proto?, flags?): Promise<any> function getaddrinfo$({ host, port, family, type, proto, flags }: { host, port, family?, type?, proto?, flags?}): Promise<any> interface I_GiveupOnSendfile { } /** * A subclass of _socket.socket adding the makefile() method. */ function socket(family?, type?, proto?, fileno?): Promise<Isocket> function socket$({ family, type, proto, fileno }: { family?, type?, proto?, fileno?}): Promise<Isocket> interface Isocket { /** * dup() -> socket object * * Duplicate the socket. Return a new socket object connected to the same * system resource. The new socket is non-inheritable. * */ dup(): Promise<any> dup$($: {}): Promise<any> /** * accept() -> (socket object, address info) * * Wait for an incoming connection. Return a new socket * representing the connection, and the address of the client. * For IP sockets, the address info is a pair (hostaddr, port). * */ accept(): Promise<any> accept$($: {}): Promise<any> /** * makefile(...) -> an I/O stream connected to the socket * * The arguments are as for io.open() after the filename, except the only * supported mode values are 'r' (default), 'w' and 'b'. * */ makefile(mode?, buffering?): Promise<any> makefile$({ mode, buffering }: { mode?, buffering?}): Promise<any> /** * sendfile(file[, offset[, count]]) -> sent * * Send a file until EOF is reached by using high-performance * os.sendfile() and return the total number of bytes which * were sent. * *file* must be a regular file object opened in binary mode. * If os.sendfile() is not available (e.g. Windows) or file is * not a regular file socket.send() will be used instead. * *offset* tells from where to start reading the file. * If specified, *count* is the total number of bytes to transmit * as opposed to sending the file until EOF is reached. * File position is updated on return or also in case of error in * which case file.tell() can be used to figure out the number of * bytes which were sent. * The socket must be of SOCK_STREAM type. * Non-blocking sockets are not supported. * */ sendfile(file, offset?, count?): Promise<any> sendfile$({ file, offset, count }: { file, offset?, count?}): Promise<any> close(): Promise<any> close$($: {}): Promise<any> /** * detach() -> file descriptor * * Close the socket object without closing the underlying file descriptor. * The object cannot be used after this call, but the file descriptor * can be reused for other purposes. The file descriptor is returned. * */ detach(): Promise<any> detach$($: {}): Promise<any> /** * Read-only access to the address family for this socket. * */ family(): Promise<any> family$($: {}): Promise<any> /** * Read-only access to the socket type. * */ type(): Promise<any> type$($: {}): Promise<any> } /** * Raw I/O implementation for stream sockets. * * This class supports the makefile() method on sockets. It provides * the raw I/O interface on top of a socket object. * */ function SocketIO(sock, mode): Promise<ISocketIO> function SocketIO$({ sock, mode }): Promise<ISocketIO> interface ISocketIO { /** * Read up to len(b) bytes into the writable buffer *b* and return * the number of bytes read. If the socket is non-blocking and no bytes * are available, None is returned. * * If *b* is non-empty, a 0 return value indicates that the connection * was shutdown at the other end. * */ readinto(b): Promise<any> readinto$({ b }): Promise<any> /** * Write the given bytes or bytearray object *b* to the socket * and return the number of bytes written. This can be less than * len(b) if not all data could be written. If the socket is * non-blocking and no bytes could be written None is returned. * */ write(b): Promise<any> write$({ b }): Promise<any> /** * True if the SocketIO is open for reading. * */ readable(): Promise<any> readable$($: {}): Promise<any> /** * True if the SocketIO is open for writing. * */ writable(): Promise<any> writable$($: {}): Promise<any> /** * True if the SocketIO is open for seeking. * */ seekable(): Promise<any> seekable$($: {}): Promise<any> /** * Return the file descriptor of the underlying socket. * */ fileno(): Promise<any> fileno$($: {}): Promise<any> name(): Promise<any> name$($: {}): Promise<any> mode(): Promise<any> mode$($: {}): Promise<any> /** * Close the SocketIO object. This doesn't close the underlying * socket, except if all references to it have disappeared. * */ close(): Promise<any> close$($: {}): Promise<any> } let EBADF: Promise<any> let EAGAIN: Promise<any> let EWOULDBLOCK: Promise<any> let errorTab: Promise<any> } declare module socketserver { var _ /** * Base class for server classes. * * Methods for the caller: * * - __init__(server_address, RequestHandlerClass) * - serve_forever(poll_interval=0.5) * - shutdown() * - handle_request() # if you do not use serve_forever() * - fileno() -> int # for selector * * Methods that may be overridden: * * - server_bind() * - server_activate() * - get_request() -> request, client_address * - handle_timeout() * - verify_request(request, client_address) * - server_close() * - process_request(request, client_address) * - shutdown_request(request) * - close_request(request) * - service_actions() * - handle_error() * * Methods for derived classes: * * - finish_request(request, client_address) * * Class variables that may be overridden by derived classes or * instances: * * - timeout * - address_family * - socket_type * - allow_reuse_address * * Instance variables: * * - RequestHandlerClass * - socket * * */ /** * Constructor. May be extended, do not override. */ function BaseServer(server_address, RequestHandlerClass): Promise<IBaseServer> function BaseServer$({ server_address, RequestHandlerClass }): Promise<IBaseServer> interface IBaseServer { /** * Called by constructor to activate the server. * * May be overridden. * * */ server_activate(): Promise<any> server_activate$($: {}): Promise<any> /** * Handle one request at a time until shutdown. * * Polls for shutdown every poll_interval seconds. Ignores * self.timeout. If you need to do periodic tasks, do them in * another thread. * */ serve_forever(poll_interval?): Promise<any> serve_forever$({ poll_interval }: { poll_interval?}): Promise<any> /** * Stops the serve_forever loop. * * Blocks until the loop has finished. This must be called while * serve_forever() is running in another thread, or it will * deadlock. * */ shutdown(): Promise<any> shutdown$($: {}): Promise<any> /** * Called by the serve_forever() loop. * * May be overridden by a subclass / Mixin to implement any code that * needs to be run during the loop. * */ service_actions(): Promise<any> service_actions$($: {}): Promise<any> /** * Handle one request, possibly blocking. * * Respects self.timeout. * */ handle_request(): Promise<any> handle_request$($: {}): Promise<any> /** * Called if no new request arrives within self.timeout. * * Overridden by ForkingMixIn. * */ handle_timeout(): Promise<any> handle_timeout$($: {}): Promise<any> /** * Verify the request. May be overridden. * * Return True if we should proceed with this request. * * */ verify_request(request, client_address): Promise<any> verify_request$({ request, client_address }): Promise<any> /** * Call finish_request. * * Overridden by ForkingMixIn and ThreadingMixIn. * * */ process_request(request, client_address): Promise<any> process_request$({ request, client_address }): Promise<any> /** * Called to clean-up the server. * * May be overridden. * * */ server_close(): Promise<any> server_close$($: {}): Promise<any> /** * Finish one request by instantiating RequestHandlerClass. */ finish_request(request, client_address): Promise<any> finish_request$({ request, client_address }): Promise<any> /** * Called to shutdown and close an individual request. */ shutdown_request(request): Promise<any> shutdown_request$({ request }): Promise<any> /** * Called to clean up an individual request. */ close_request(request): Promise<any> close_request$({ request }): Promise<any> /** * Handle an error gracefully. May be overridden. * * The default is to print a traceback and continue. * * */ handle_error(request, client_address): Promise<any> handle_error$({ request, client_address }): Promise<any> timeout } /** * Base class for various socket-based server classes. * * Defaults to synchronous IP stream (i.e., TCP). * * Methods for the caller: * * - __init__(server_address, RequestHandlerClass, bind_and_activate=True) * - serve_forever(poll_interval=0.5) * - shutdown() * - handle_request() # if you don't use serve_forever() * - fileno() -> int # for selector * * Methods that may be overridden: * * - server_bind() * - server_activate() * - get_request() -> request, client_address * - handle_timeout() * - verify_request(request, client_address) * - process_request(request, client_address) * - shutdown_request(request) * - close_request(request) * - handle_error() * * Methods for derived classes: * * - finish_request(request, client_address) * * Class variables that may be overridden by derived classes or * instances: * * - timeout * - address_family * - socket_type * - request_queue_size (only for stream sockets) * - allow_reuse_address * * Instance variables: * * - server_address * - RequestHandlerClass * - socket * * */ /** * Constructor. May be extended, do not override. */ function TCPServer(server_address, RequestHandlerClass, bind_and_activate?: boolean): Promise<ITCPServer> function TCPServer$({ server_address, RequestHandlerClass, bind_and_activate }: { server_address, RequestHandlerClass, bind_and_activate?}): Promise<ITCPServer> interface ITCPServer extends IBaseServer { /** * Called by constructor to bind the socket. * * May be overridden. * * */ server_bind(): Promise<any> server_bind$($: {}): Promise<any> /** * Called by constructor to activate the server. * * May be overridden. * * */ server_activate(): Promise<any> server_activate$($: {}): Promise<any> /** * Called to clean-up the server. * * May be overridden. * * */ server_close(): Promise<any> server_close$($: {}): Promise<any> /** * Return socket file number. * * Interface required by selector. * * */ fileno(): Promise<any> fileno$($: {}): Promise<any> /** * Get the request and client address from the socket. * * May be overridden. * * */ get_request(): Promise<any> get_request$($: {}): Promise<any> /** * Called to shutdown and close an individual request. */ shutdown_request(request): Promise<any> shutdown_request$({ request }): Promise<any> /** * Called to clean up an individual request. */ close_request(request): Promise<any> close_request$({ request }): Promise<any> address_family socket_type request_queue_size allow_reuse_address } /** * UDP server class. */ interface IUDPServer extends ITCPServer { get_request(): Promise<any> get_request$($: {}): Promise<any> server_activate(): Promise<any> server_activate$($: {}): Promise<any> shutdown_request(request): Promise<any> shutdown_request$({ request }): Promise<any> close_request(request): Promise<any> close_request$({ request }): Promise<any> max_packet_size } /** * Mix-in class to handle each request in a new process. */ interface IForkingMixIn { /** * Internal routine to wait for children that have exited. */ collect_children(): Promise<any> collect_children$($: {}): Promise<any> /** * Wait for zombies after self.timeout seconds of inactivity. * * May be extended, do not override. * */ handle_timeout(): Promise<any> handle_timeout$($: {}): Promise<any> /** * Collect the zombie child processes regularly in the ForkingMixIn. * * service_actions is called in the BaseServer's serve_forever loop. * */ service_actions(): Promise<any> service_actions$($: {}): Promise<any> /** * Fork a new subprocess to process the request. */ process_request(request, client_address): Promise<any> process_request$({ request, client_address }): Promise<any> server_close(): Promise<any> server_close$($: {}): Promise<any> active_children max_children block_on_close } /** * * Joinable list of all non-daemon threads. * */ interface I_Threads { append(thread): Promise<any> append$({ thread }): Promise<any> pop_all(): Promise<any> pop_all$($: {}): Promise<any> join(): Promise<any> join$($: {}): Promise<any> reap(): Promise<any> reap$($: {}): Promise<any> } /** * * Degenerate version of _Threads. * */ interface I_NoThreads { append(thread): Promise<any> append$({ thread }): Promise<any> join(): Promise<any> join$($: {}): Promise<any> } /** * Mix-in class to handle each request in a new thread. */ interface IThreadingMixIn { /** * Same as in BaseServer but as a thread. * * In addition, exception handling is done here. * * */ process_request_thread(request, client_address): Promise<any> process_request_thread$({ request, client_address }): Promise<any> /** * Start a new thread to process the request. */ process_request(request, client_address): Promise<any> process_request$({ request, client_address }): Promise<any> server_close(): Promise<any> server_close$($: {}): Promise<any> daemon_threads } interface IForkingUDPServer extends IForkingMixIn, IUDPServer { } interface IForkingTCPServer extends IForkingMixIn, ITCPServer { } interface IThreadingUDPServer extends IThreadingMixIn, IUDPServer { } interface IThreadingTCPServer extends IThreadingMixIn, ITCPServer { } interface IUnixStreamServer extends ITCPServer { } interface IUnixDatagramServer extends IUDPServer { } interface IThreadingUnixStreamServer extends IThreadingMixIn, IUnixStreamServer { } interface IThreadingUnixDatagramServer extends IThreadingMixIn, IUnixDatagramServer { } /** * Base class for request handler classes. * * This class is instantiated for each request to be handled. The * constructor sets the instance variables request, client_address * and server, and then calls the handle() method. To implement a * specific service, all you need to do is to derive a class which * defines a handle() method. * * The handle() method can find the request as self.request, the * client address as self.client_address, and the server (in case it * needs access to per-server information) as self.server. Since a * separate instance is created for each request, the handle() method * can define other arbitrary instance variables. * * */ function BaseRequestHandler(request, client_address, server): Promise<IBaseRequestHandler> function BaseRequestHandler$({ request, client_address, server }): Promise<IBaseRequestHandler> interface IBaseRequestHandler { setup(): Promise<any> setup$($: {}): Promise<any> handle(): Promise<any> handle$($: {}): Promise<any> finish(): Promise<any> finish$($: {}): Promise<any> } /** * Define self.rfile and self.wfile for stream sockets. */ interface IStreamRequestHandler extends IBaseRequestHandler { setup(): Promise<any> setup$($: {}): Promise<any> finish(): Promise<any> finish$($: {}): Promise<any> rbufsize wbufsize disable_nagle_algorithm } /** * Simple writable BufferedIOBase implementation for a socket * * Does not hold data in a buffer, avoiding any need to call flush(). */ interface I_SocketWriter { writable(): Promise<any> writable$($: {}): Promise<any> write(b): Promise<any> write$({ b }): Promise<any> fileno(): Promise<any> fileno$($: {}): Promise<any> } /** * Define self.rfile and self.wfile for datagram sockets. */ interface IDatagramRequestHandler extends IBaseRequestHandler { setup(): Promise<any> setup$($: {}): Promise<any> finish(): Promise<any> finish$($: {}): Promise<any> } } declare module sqlite3 { var _ module dbapi2 { var _ function DateFromTicks(ticks): Promise<any> function DateFromTicks$({ ticks }): Promise<any> function TimeFromTicks(ticks): Promise<any> function TimeFromTicks$({ ticks }): Promise<any> function TimestampFromTicks(ticks): Promise<any> function TimestampFromTicks$({ ticks }): Promise<any> function register_adapters_and_converters(): Promise<any> function register_adapters_and_converters$($: {}): Promise<any> function enable_shared_cache(enable): Promise<any> function enable_shared_cache$({ enable }): Promise<any> let paramstyle: Promise<any> let threadsafety: Promise<any> let apilevel: Promise<any> let Date: Promise<any> let Time: Promise<any> let Timestamp: Promise<any> let version_info: Promise<any> let sqlite_version_info: Promise<any> let Binary: Promise<any> } module dump { var _ } } declare module stat { var _ /** * Return the portion of the file's mode that can be set by * os.chmod(). * */ function S_IMODE(mode): Promise<any> function S_IMODE$({ mode }): Promise<any> /** * Return the portion of the file's mode that describes the * file type. * */ function S_IFMT(mode): Promise<any> function S_IFMT$({ mode }): Promise<any> /** * Return True if mode is from a directory. */ function S_ISDIR(mode): Promise<any> function S_ISDIR$({ mode }): Promise<any> /** * Return True if mode is from a character special device file. */ function S_ISCHR(mode): Promise<any> function S_ISCHR$({ mode }): Promise<any> /** * Return True if mode is from a block special device file. */ function S_ISBLK(mode): Promise<any> function S_ISBLK$({ mode }): Promise<any> /** * Return True if mode is from a regular file. */ function S_ISREG(mode): Promise<any> function S_ISREG$({ mode }): Promise<any> /** * Return True if mode is from a FIFO (named pipe). */ function S_ISFIFO(mode): Promise<any> function S_ISFIFO$({ mode }): Promise<any> /** * Return True if mode is from a symbolic link. */ function S_ISLNK(mode): Promise<any> function S_ISLNK$({ mode }): Promise<any> /** * Return True if mode is from a socket. */ function S_ISSOCK(mode): Promise<any> function S_ISSOCK$({ mode }): Promise<any> /** * Return True if mode is from a door. */ function S_ISDOOR(mode): Promise<any> function S_ISDOOR$({ mode }): Promise<any> /** * Return True if mode is from an event port. */ function S_ISPORT(mode): Promise<any> function S_ISPORT$({ mode }): Promise<any> /** * Return True if mode is from a whiteout. */ function S_ISWHT(mode): Promise<any> function S_ISWHT$({ mode }): Promise<any> /** * Convert a file's mode to a string of the form '-rwxrwxrwx'. */ function filemode(mode): Promise<any> function filemode$({ mode }): Promise<any> let ST_MODE: Promise<any> let ST_INO: Promise<any> let ST_DEV: Promise<any> let ST_NLINK: Promise<any> let ST_UID: Promise<any> let ST_GID: Promise<any> let ST_SIZE: Promise<any> let ST_ATIME: Promise<any> let ST_MTIME: Promise<any> let ST_CTIME: Promise<any> let S_IFDIR: Promise<any> let S_IFCHR: Promise<any> let S_IFBLK: Promise<any> let S_IFREG: Promise<any> let S_IFIFO: Promise<any> let S_IFLNK: Promise<any> let S_IFSOCK: Promise<any> let S_IFDOOR: Promise<any> let S_IFPORT: Promise<any> let S_IFWHT: Promise<any> let S_ISUID: Promise<any> let S_ISGID: Promise<any> let S_ENFMT: Promise<any> let S_ISVTX: Promise<any> let S_IREAD: Promise<any> let S_IWRITE: Promise<any> let S_IEXEC: Promise<any> let S_IRWXU: Promise<any> let S_IRUSR: Promise<any> let S_IWUSR: Promise<any> let S_IXUSR: Promise<any> let S_IRWXG: Promise<any> let S_IRGRP: Promise<any> let S_IWGRP: Promise<any> let S_IXGRP: Promise<any> let S_IRWXO: Promise<any> let S_IROTH: Promise<any> let S_IWOTH: Promise<any> let S_IXOTH: Promise<any> let UF_NODUMP: Promise<any> let UF_IMMUTABLE: Promise<any> let UF_APPEND: Promise<any> let UF_OPAQUE: Promise<any> let UF_NOUNLINK: Promise<any> let UF_COMPRESSED: Promise<any> let UF_HIDDEN: Promise<any> let SF_ARCHIVED: Promise<any> let SF_IMMUTABLE: Promise<any> let SF_APPEND: Promise<any> let SF_NOUNLINK: Promise<any> let SF_SNAPSHOT: Promise<any> let FILE_ATTRIBUTE_ARCHIVE: Promise<any> let FILE_ATTRIBUTE_COMPRESSED: Promise<any> let FILE_ATTRIBUTE_DEVICE: Promise<any> let FILE_ATTRIBUTE_DIRECTORY: Promise<any> let FILE_ATTRIBUTE_ENCRYPTED: Promise<any> let FILE_ATTRIBUTE_HIDDEN: Promise<any> let FILE_ATTRIBUTE_INTEGRITY_STREAM: Promise<any> let FILE_ATTRIBUTE_NORMAL: Promise<any> let FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: Promise<any> let FILE_ATTRIBUTE_NO_SCRUB_DATA: Promise<any> let FILE_ATTRIBUTE_OFFLINE: Promise<any> let FILE_ATTRIBUTE_READONLY: Promise<any> let FILE_ATTRIBUTE_REPARSE_POINT: Promise<any> let FILE_ATTRIBUTE_SPARSE_FILE: Promise<any> let FILE_ATTRIBUTE_SYSTEM: Promise<any> let FILE_ATTRIBUTE_TEMPORARY: Promise<any> let FILE_ATTRIBUTE_VIRTUAL: Promise<any> } declare module statistics { var _ /** * Return the sample arithmetic mean of data. * * >>> mean([1, 2, 3, 4, 4]) * 2.8 * * >>> from fractions import Fraction as F * >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)]) * Fraction(13, 21) * * >>> from decimal import Decimal as D * >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")]) * Decimal('0.5625') * * If ``data`` is empty, StatisticsError will be raised. * */ function mean(data): Promise<any> function mean$({ data }): Promise<any> /** * Convert data to floats and compute the arithmetic mean. * * This runs faster than the mean() function and it always returns a float. * If the input dataset is empty, it raises a StatisticsError. * * >>> fmean([3.5, 4.0, 5.25]) * 4.25 * */ function fmean(data, weights?): Promise<any> function fmean$({ data, weights }: { data, weights?}): Promise<any> /** * Convert data to floats and compute the geometric mean. * * Raises a StatisticsError if the input dataset is empty, * if it contains a zero, or if it contains a negative value. * * No special efforts are made to achieve exact results. * (However, this may change in the future.) * * >>> round(geometric_mean([54, 24, 36]), 9) * 36.0 * */ function geometric_mean(data): Promise<any> function geometric_mean$({ data }): Promise<any> /** * Return the harmonic mean of data. * * The harmonic mean is the reciprocal of the arithmetic mean of the * reciprocals of the data. It can be used for averaging ratios or * rates, for example speeds. * * Suppose a car travels 40 km/hr for 5 km and then speeds-up to * 60 km/hr for another 5 km. What is the average speed? * * >>> harmonic_mean([40, 60]) * 48.0 * * Suppose a car travels 40 km/hr for 5 km, and when traffic clears, * speeds-up to 60 km/hr for the remaining 30 km of the journey. What * is the average speed? * * >>> harmonic_mean([40, 60], weights=[5, 30]) * 56.0 * * If ``data`` is empty, or any element is less than zero, * ``harmonic_mean`` will raise ``StatisticsError``. * */ function harmonic_mean(data, weights?): Promise<any> function harmonic_mean$({ data, weights }: { data, weights?}): Promise<any> /** * Return the median (middle value) of numeric data. * * When the number of data points is odd, return the middle data point. * When the number of data points is even, the median is interpolated by * taking the average of the two middle values: * * >>> median([1, 3, 5]) * 3 * >>> median([1, 3, 5, 7]) * 4.0 * * */ function median(data): Promise<any> function median$({ data }): Promise<any> /** * Return the low median of numeric data. * * When the number of data points is odd, the middle value is returned. * When it is even, the smaller of the two middle values is returned. * * >>> median_low([1, 3, 5]) * 3 * >>> median_low([1, 3, 5, 7]) * 3 * * */ function median_low(data): Promise<any> function median_low$({ data }): Promise<any> /** * Return the high median of data. * * When the number of data points is odd, the middle value is returned. * When it is even, the larger of the two middle values is returned. * * >>> median_high([1, 3, 5]) * 3 * >>> median_high([1, 3, 5, 7]) * 5 * * */ function median_high(data): Promise<any> function median_high$({ data }): Promise<any> /** * Return the 50th percentile (median) of grouped continuous data. * * >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5]) * 3.7 * >>> median_grouped([52, 52, 53, 54]) * 52.5 * * This calculates the median as the 50th percentile, and should be * used when your data is continuous and grouped. In the above example, * the values 1, 2, 3, etc. actually represent the midpoint of classes * 0.5-1.5, 1.5-2.5, 2.5-3.5, etc. The middle value falls somewhere in * class 3.5-4.5, and interpolation is used to estimate it. * * Optional argument ``interval`` represents the class interval, and * defaults to 1. Changing the class interval naturally will change the * interpolated 50th percentile value: * * >>> median_grouped([1, 3, 3, 5, 7], interval=1) * 3.25 * >>> median_grouped([1, 3, 3, 5, 7], interval=2) * 3.5 * * This function does not check whether the data points are at least * ``interval`` apart. * */ function median_grouped(data, interval?): Promise<any> function median_grouped$({ data, interval }: { data, interval?}): Promise<any> /** * Return the most common data point from discrete or nominal data. * * ``mode`` assumes discrete data, and returns a single value. This is the * standard treatment of the mode as commonly taught in schools: * * >>> mode([1, 1, 2, 3, 3, 3, 3, 4]) * 3 * * This also works with nominal (non-numeric) data: * * >>> mode(["red", "blue", "blue", "red", "green", "red", "red"]) * 'red' * * If there are multiple modes with same frequency, return the first one * encountered: * * >>> mode(['red', 'red', 'green', 'blue', 'blue']) * 'red' * * If *data* is empty, ``mode``, raises StatisticsError. * * */ function mode(data): Promise<any> function mode$({ data }): Promise<any> /** * Return a list of the most frequently occurring values. * * Will return more than one result if there are multiple modes * or an empty list if *data* is empty. * * >>> multimode('aabbbbbbbbcc') * ['b'] * >>> multimode('aabbbbccddddeeffffgg') * ['b', 'd', 'f'] * >>> multimode('') * [] * */ function multimode(data): Promise<any> function multimode$({ data }): Promise<any> /** * Divide *data* into *n* continuous intervals with equal probability. * * Returns a list of (n - 1) cut points separating the intervals. * * Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles. * Set *n* to 100 for percentiles which gives the 99 cuts points that * separate *data* in to 100 equal sized groups. * * The *data* can be any iterable containing sample. * The cut points are linearly interpolated between data points. * * If *method* is set to *inclusive*, *data* is treated as population * data. The minimum value is treated as the 0th percentile and the * maximum value is treated as the 100th percentile. * */ function quantiles(data): Promise<any> function quantiles$({ data }): Promise<any> /** * Return the sample variance of data. * * data should be an iterable of Real-valued numbers, with at least two * values. The optional argument xbar, if given, should be the mean of * the data. If it is missing or None, the mean is automatically calculated. * * Use this function when your data is a sample from a population. To * calculate the variance from the entire population, see ``pvariance``. * * Examples: * * >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] * >>> variance(data) * 1.3720238095238095 * * If you have already calculated the mean of your data, you can pass it as * the optional second argument ``xbar`` to avoid recalculating it: * * >>> m = mean(data) * >>> variance(data, m) * 1.3720238095238095 * * This function does not check that ``xbar`` is actually the mean of * ``data``. Giving arbitrary values for ``xbar`` may lead to invalid or * impossible results. * * Decimals and Fractions are supported: * * >>> from decimal import Decimal as D * >>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")]) * Decimal('31.01875') * * >>> from fractions import Fraction as F * >>> variance([F(1, 6), F(1, 2), F(5, 3)]) * Fraction(67, 108) * * */ function variance(data, xbar?): Promise<any> function variance$({ data, xbar }: { data, xbar?}): Promise<any> /** * Return the population variance of ``data``. * * data should be a sequence or iterable of Real-valued numbers, with at least one * value. The optional argument mu, if given, should be the mean of * the data. If it is missing or None, the mean is automatically calculated. * * Use this function to calculate the variance from the entire population. * To estimate the variance from a sample, the ``variance`` function is * usually a better choice. * * Examples: * * >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25] * >>> pvariance(data) * 1.25 * * If you have already calculated the mean of the data, you can pass it as * the optional second argument to avoid recalculating it: * * >>> mu = mean(data) * >>> pvariance(data, mu) * 1.25 * * Decimals and Fractions are supported: * * >>> from decimal import Decimal as D * >>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")]) * Decimal('24.815') * * >>> from fractions import Fraction as F * >>> pvariance([F(1, 4), F(5, 4), F(1, 2)]) * Fraction(13, 72) * * */ function pvariance(data, mu?): Promise<any> function pvariance$({ data, mu }: { data, mu?}): Promise<any> /** * Return the square root of the sample variance. * * See ``variance`` for arguments and other details. * * >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75]) * 1.0810874155219827 * * */ function stdev(data, xbar?): Promise<any> function stdev$({ data, xbar }: { data, xbar?}): Promise<any> /** * Return the square root of the population variance. * * See ``pvariance`` for arguments and other details. * * >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75]) * 0.986893273527251 * * */ function pstdev(data, mu?): Promise<any> function pstdev$({ data, mu }: { data, mu?}): Promise<any> /** * Covariance * * Return the sample covariance of two inputs *x* and *y*. Covariance * is a measure of the joint variability of two inputs. * * >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9] * >>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3] * >>> covariance(x, y) * 0.75 * >>> z = [9, 8, 7, 6, 5, 4, 3, 2, 1] * >>> covariance(x, z) * -7.5 * >>> covariance(z, x) * -7.5 * * */ function covariance(x, y): Promise<any> function covariance$({ x, y }): Promise<any> /** * Pearson's correlation coefficient * * Return the Pearson's correlation coefficient for two inputs. Pearson's * correlation coefficient *r* takes values between -1 and +1. It measures the * strength and direction of the linear relationship, where +1 means very * strong, positive linear relationship, -1 very strong, negative linear * relationship, and 0 no linear relationship. * * >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9] * >>> y = [9, 8, 7, 6, 5, 4, 3, 2, 1] * >>> correlation(x, x) * 1.0 * >>> correlation(x, y) * -1.0 * * */ function correlation(x, y): Promise<any> function correlation$({ x, y }): Promise<any> /** * Slope and intercept for simple linear regression. * * Return the slope and intercept of simple linear regression * parameters estimated using ordinary least squares. Simple linear * regression describes relationship between an independent variable * *x* and a dependent variable *y* in terms of linear function: * * y = slope * x + intercept + noise * * where *slope* and *intercept* are the regression parameters that are * estimated, and noise represents the variability of the data that was * not explained by the linear regression (it is equal to the * difference between predicted and actual values of the dependent * variable). * * The parameters are returned as a named tuple. * * >>> x = [1, 2, 3, 4, 5] * >>> noise = NormalDist().samples(5, seed=42) * >>> y = [3 * x[i] + 2 + noise[i] for i in range(5)] * >>> linear_regression(x, y) #doctest: +ELLIPSIS * LinearRegression(slope=3.09078914170..., intercept=1.75684970486...) * * */ function linear_regression(x, y): Promise<any> function linear_regression$({ x, y }): Promise<any> interface IStatisticsError { } /** * Normal distribution of a random variable */ /** * NormalDist where mu is the mean and sigma is the standard deviation. */ function NormalDist(mu?, sigma?): Promise<INormalDist> function NormalDist$({ mu, sigma }: { mu?, sigma?}): Promise<INormalDist> interface INormalDist { /** * Make a normal distribution instance from sample data. */ from_samples(data): Promise<any> from_samples$({ data }): Promise<any> /** * Generate *n* samples for a given mean and standard deviation. */ samples(n): Promise<any> samples$({ n }): Promise<any> /** * Probability density function. P(x <= X < x+dx) / dx */ pdf(x): Promise<any> pdf$({ x }): Promise<any> /** * Cumulative distribution function. P(X <= x) */ cdf(x): Promise<any> cdf$({ x }): Promise<any> /** * Inverse cumulative distribution function. x : P(X <= x) = p * * Finds the value of the random variable such that the probability of * the variable being less than or equal to that value equals the given * probability. * * This function is also called the percent point function or quantile * function. * */ inv_cdf(p): Promise<any> inv_cdf$({ p }): Promise<any> /** * Divide into *n* continuous intervals with equal probability. * * Returns a list of (n - 1) cut points separating the intervals. * * Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles. * Set *n* to 100 for percentiles which gives the 99 cuts points that * separate the normal distribution in to 100 equal sized groups. * */ quantiles(n?): Promise<any> quantiles$({ n }: { n?}): Promise<any> /** * Compute the overlapping coefficient (OVL) between two normal distributions. * * Measures the agreement between two normal probability distributions. * Returns a value between 0.0 and 1.0 giving the overlapping area in * the two underlying probability density functions. * * >>> N1 = NormalDist(2.4, 1.6) * >>> N2 = NormalDist(3.2, 2.0) * >>> N1.overlap(N2) * 0.8035050657330205 * */ overlap(other): Promise<any> overlap$({ other }): Promise<any> /** * Compute the Standard Score. (x - mean) / stdev * * Describes *x* in terms of the number of standard deviations * above or below the mean of the normal distribution. * */ zscore(x): Promise<any> zscore$({ x }): Promise<any> /** * Arithmetic mean of the normal distribution. */ mean(): Promise<any> mean$($: {}): Promise<any> /** * Return the median of the normal distribution */ median(): Promise<any> median$($: {}): Promise<any> /** * Return the mode of the normal distribution * * The mode is the value x where which the probability density * function (pdf) takes its maximum value. * */ mode(): Promise<any> mode$($: {}): Promise<any> /** * Standard deviation of the normal distribution. */ stdev(): Promise<any> stdev$($: {}): Promise<any> /** * Square of the standard deviation. */ variance(): Promise<any> variance$($: {}): Promise<any> } let LinearRegression: Promise<any> } declare module tarfile { var _ /** * Convert a string to a null-terminated bytes object. * */ function stn(s, length, encoding, errors): Promise<any> function stn$({ s, length, encoding, errors }): Promise<any> /** * Convert a null-terminated bytes object to a string. * */ function nts(s, encoding, errors): Promise<any> function nts$({ s, encoding, errors }): Promise<any> /** * Convert a number field to a python number. * */ function nti(s): Promise<any> function nti$({ s }): Promise<any> /** * Convert a python number to a number field. * */ function itn(n, digits?, format?): Promise<any> function itn$({ n, digits, format }: { n, digits?, format?}): Promise<any> /** * Calculate the checksum for a member's header by summing up all * characters except for the chksum field which is treated as if * it was filled with spaces. According to the GNU tar sources, * some tars (Sun and NeXT) calculate chksum with signed char, * which will be different if there are chars in the buffer with * the high bit set. So we calculate two checksums, unsigned and * signed. * */ function calc_chksums(buf): Promise<any> function calc_chksums$({ buf }): Promise<any> /** * Copy length bytes from fileobj src to fileobj dst. * If length is None, copy the entire content. * */ function copyfileobj(src, dst, length?, exception?, bufsize?): Promise<any> function copyfileobj$({ src, dst, length, exception, bufsize }: { src, dst, length?, exception?, bufsize?}): Promise<any> /** * Return True if name points to a tar archive that we * are able to handle, else return False. * * 'name' should be a string, file, or file-like object. * */ function is_tarfile(name): Promise<any> function is_tarfile$({ name }): Promise<any> function main(): Promise<any> function main$($: {}): Promise<any> /** * Base exception. */ interface ITarError { } /** * General exception for extract errors. */ interface IExtractError extends ITarError { } /** * Exception for unreadable tar archives. */ interface IReadError extends ITarError { } /** * Exception for unavailable compression methods. */ interface ICompressionError extends ITarError { } /** * Exception for unsupported operations on stream-like TarFiles. */ interface IStreamError extends ITarError { } /** * Base exception for header errors. */ interface IHeaderError extends ITarError { } /** * Exception for empty headers. */ interface IEmptyHeaderError extends IHeaderError { } /** * Exception for truncated headers. */ interface ITruncatedHeaderError extends IHeaderError { } /** * Exception for end of file headers. */ interface IEOFHeaderError extends IHeaderError { } /** * Exception for invalid headers. */ interface IInvalidHeaderError extends IHeaderError { } /** * Exception for missing and invalid extended headers. */ interface ISubsequentHeaderError extends IHeaderError { } /** * Low-level file object. Supports reading and writing. * It is used instead of a regular file object for streaming * access. * */ interface I_LowLevelFile { close(): Promise<any> close$($: {}): Promise<any> read(size): Promise<any> read$({ size }): Promise<any> write(s): Promise<any> write$({ s }): Promise<any> } /** * Class that serves as an adapter between TarFile and * a stream-like object. The stream-like object only * needs to have a read() or write() method and is accessed * blockwise. Use of gzip or bzip2 compression is possible. * A stream-like object could be for example: sys.stdin, * sys.stdout, a socket, a tape device etc. * * _Stream is intended to be used only internally. * */ interface I_Stream { /** * Write string s to the stream. * */ write(s): Promise<any> write$({ s }): Promise<any> /** * Close the _Stream object. No operation should be * done on it afterwards. * */ close(): Promise<any> close$($: {}): Promise<any> /** * Return the stream's file pointer position. * */ tell(): Promise<any> tell$($: {}): Promise<any> /** * Set the stream's file pointer to pos. Negative seeking * is forbidden. * */ seek(pos?): Promise<any> seek$({ pos }: { pos?}): Promise<any> /** * Return the next size number of bytes from the stream. */ read(size): Promise<any> read$({ size }): Promise<any> } /** * Small proxy class that enables transparent compression * detection for the Stream interface (mode 'r|*'). * */ interface I_StreamProxy { read(size): Promise<any> read$({ size }): Promise<any> getcomptype(): Promise<any> getcomptype$($: {}): Promise<any> close(): Promise<any> close$($: {}): Promise<any> } /** * A thin wrapper around an existing file object that * provides a part of its data as an individual file * object. * */ interface I_FileInFile { flush(): Promise<any> flush$($: {}): Promise<any> readable(): Promise<any> readable$($: {}): Promise<any> writable(): Promise<any> writable$($: {}): Promise<any> seekable(): Promise<any> seekable$($: {}): Promise<any> /** * Return the current file position. * */ tell(): Promise<any> tell$($: {}): Promise<any> /** * Seek to a position in the file. * */ seek(position, whence?): Promise<any> seek$({ position, whence }: { position, whence?}): Promise<any> /** * Read data from the file. * */ read(size?): Promise<any> read$({ size }: { size?}): Promise<any> readinto(b): Promise<any> readinto$({ b }): Promise<any> close(): Promise<any> close$($: {}): Promise<any> } function ExFileObject(tarfile, tarinfo): Promise<IExFileObject> function ExFileObject$({ tarfile, tarinfo }): Promise<IExFileObject> interface IExFileObject { } /** * Informational class which holds the details about an * archive member given by a tar header block. * TarInfo objects are returned by TarFile.getmember(), * TarFile.getmembers() and TarFile.gettarinfo() and are * usually created internally. * */ /** * Construct a TarInfo object. name is the optional name * of the member. * */ function TarInfo(name?): Promise<ITarInfo> function TarInfo$({ name }: { name?}): Promise<ITarInfo> interface ITarInfo { /** * In pax headers, "name" is called "path". */ path(): Promise<any> path$($: {}): Promise<any> path(name): Promise<any> path$({ name }): Promise<any> /** * In pax headers, "linkname" is called "linkpath". */ linkpath(): Promise<any> linkpath$($: {}): Promise<any> linkpath(linkname): Promise<any> linkpath$({ linkname }): Promise<any> /** * Return the TarInfo's attributes as a dictionary. * */ get_info(): Promise<any> get_info$($: {}): Promise<any> /** * Return a tar header as a string of 512 byte blocks. * */ tobuf(format?, encoding?, errors?): Promise<any> tobuf$({ format, encoding, errors }: { format?, encoding?, errors?}): Promise<any> /** * Return the object as a ustar header block. * */ create_ustar_header(info, encoding, errors): Promise<any> create_ustar_header$({ info, encoding, errors }): Promise<any> /** * Return the object as a GNU header block sequence. * */ create_gnu_header(info, encoding, errors): Promise<any> create_gnu_header$({ info, encoding, errors }): Promise<any> /** * Return the object as a ustar header block. If it cannot be * represented this way, prepend a pax extended header sequence * with supplement information. * */ create_pax_header(info, encoding): Promise<any> create_pax_header$({ info, encoding }): Promise<any> /** * Return the object as a pax global header block sequence. * */ create_pax_global_header(pax_headers): Promise<any> create_pax_global_header$({ pax_headers }): Promise<any> /** * Construct a TarInfo object from a 512 byte bytes object. * */ frombuf(buf, encoding, errors): Promise<any> frombuf$({ buf, encoding, errors }): Promise<any> /** * Return the next TarInfo object from TarFile object * tarfile. * */ fromtarfile(tarfile): Promise<any> fromtarfile$({ tarfile }): Promise<any> /** * Return True if the Tarinfo object is a regular file. */ isreg(): Promise<any> isreg$($: {}): Promise<any> /** * Return True if the Tarinfo object is a regular file. */ isfile(): Promise<any> isfile$($: {}): Promise<any> /** * Return True if it is a directory. */ isdir(): Promise<any> isdir$($: {}): Promise<any> /** * Return True if it is a symbolic link. */ issym(): Promise<any> issym$($: {}): Promise<any> /** * Return True if it is a hard link. */ islnk(): Promise<any> islnk$($: {}): Promise<any> /** * Return True if it is a character device. */ ischr(): Promise<any> ischr$($: {}): Promise<any> /** * Return True if it is a block device. */ isblk(): Promise<any> isblk$($: {}): Promise<any> /** * Return True if it is a FIFO. */ isfifo(): Promise<any> isfifo$($: {}): Promise<any> issparse(): Promise<any> issparse$($: {}): Promise<any> /** * Return True if it is one of character device, block device or FIFO. */ isdev(): Promise<any> isdev$($: {}): Promise<any> } /** * The TarFile Class provides an interface to tar archives. * */ /** * Open an (uncompressed) tar archive `name'. `mode' is either 'r' to * read from an existing archive, 'a' to append data to an existing * file or 'w' to create a new file overwriting an existing one. `mode' * defaults to 'r'. * If `fileobj' is given, it is used for reading or writing data. If it * can be determined, `mode' is overridden by `fileobj's mode. * `fileobj' is not closed, when TarFile is closed. * */ function TarFile(name?, mode?, fileobj?, format?, tarinfo?, dereference?, ignore_zeros?, encoding?, errors?, pax_headers?, debug?, errorlevel?, copybufsize?): Promise<ITarFile> function TarFile$({ name, mode, fileobj, format, tarinfo, dereference, ignore_zeros, encoding, errors, pax_headers, debug, errorlevel, copybufsize }: { name?, mode?, fileobj?, format?, tarinfo?, dereference?, ignore_zeros?, encoding?, errors?, pax_headers?, debug?, errorlevel?, copybufsize?}): Promise<ITarFile> interface ITarFile { /** * Open a tar archive for reading, writing or appending. Return * an appropriate TarFile class. * * mode: * 'r' or 'r:*' open for reading with transparent compression * 'r:' open for reading exclusively uncompressed * 'r:gz' open for reading with gzip compression * 'r:bz2' open for reading with bzip2 compression * 'r:xz' open for reading with lzma compression * 'a' or 'a:' open for appending, creating the file if necessary * 'w' or 'w:' open for writing without compression * 'w:gz' open for writing with gzip compression * 'w:bz2' open for writing with bzip2 compression * 'w:xz' open for writing with lzma compression * * 'x' or 'x:' create a tarfile exclusively without compression, raise * an exception if the file is already created * 'x:gz' create a gzip compressed tarfile, raise an exception * if the file is already created * 'x:bz2' create a bzip2 compressed tarfile, raise an exception * if the file is already created * 'x:xz' create an lzma compressed tarfile, raise an exception * if the file is already created * * 'r|*' open a stream of tar blocks with transparent compression * 'r|' open an uncompressed stream of tar blocks for reading * 'r|gz' open a gzip compressed stream of tar blocks * 'r|bz2' open a bzip2 compressed stream of tar blocks * 'r|xz' open an lzma compressed stream of tar blocks * 'w|' open an uncompressed stream for writing * 'w|gz' open a gzip compressed stream for writing * 'w|bz2' open a bzip2 compressed stream for writing * 'w|xz' open an lzma compressed stream for writing * */ open(name?, mode?, fileobj?, bufsize?): Promise<any> open$({ name, mode, fileobj, bufsize }: { name?, mode?, fileobj?, bufsize?}): Promise<any> /** * Open uncompressed tar archive name for reading or writing. * */ taropen(name, mode?, fileobj?): Promise<any> taropen$({ name, mode, fileobj }: { name, mode?, fileobj?}): Promise<any> /** * Open gzip compressed tar archive name for reading or writing. * Appending is not allowed. * */ gzopen(name, mode?, fileobj?, compresslevel?): Promise<any> gzopen$({ name, mode, fileobj, compresslevel }: { name, mode?, fileobj?, compresslevel?}): Promise<any> /** * Open bzip2 compressed tar archive name for reading or writing. * Appending is not allowed. * */ bz2open(name, mode?, fileobj?, compresslevel?): Promise<any> bz2open$({ name, mode, fileobj, compresslevel }: { name, mode?, fileobj?, compresslevel?}): Promise<any> /** * Open lzma compressed tar archive name for reading or writing. * Appending is not allowed. * */ xzopen(name, mode?, fileobj?, preset?): Promise<any> xzopen$({ name, mode, fileobj, preset }: { name, mode?, fileobj?, preset?}): Promise<any> /** * Close the TarFile. In write-mode, two finishing zero blocks are * appended to the archive. * */ close(): Promise<any> close$($: {}): Promise<any> /** * Return a TarInfo object for member `name'. If `name' can not be * found in the archive, KeyError is raised. If a member occurs more * than once in the archive, its last occurrence is assumed to be the * most up-to-date version. * */ getmember(name): Promise<any> getmember$({ name }): Promise<any> /** * Return the members of the archive as a list of TarInfo objects. The * list has the same order as the members in the archive. * */ getmembers(): Promise<any> getmembers$($: {}): Promise<any> /** * Return the members of the archive as a list of their names. It has * the same order as the list returned by getmembers(). * */ getnames(): Promise<any> getnames$($: {}): Promise<any> /** * Create a TarInfo object from the result of os.stat or equivalent * on an existing file. The file is either named by `name', or * specified as a file object `fileobj' with a file descriptor. If * given, `arcname' specifies an alternative name for the file in the * archive, otherwise, the name is taken from the 'name' attribute of * 'fileobj', or the 'name' argument. The name should be a text * string. * */ gettarinfo(name?, arcname?, fileobj?): Promise<any> gettarinfo$({ name, arcname, fileobj }: { name?, arcname?, fileobj?}): Promise<any> /** * Print a table of contents to sys.stdout. If `verbose' is False, only * the names of the members are printed. If it is True, an `ls -l'-like * output is produced. `members' is optional and must be a subset of the * list returned by getmembers(). * */ list(verbose?: boolean): Promise<any> list$({ verbose }: { verbose?}): Promise<any> /** * Add the file `name' to the archive. `name' may be any type of file * (directory, fifo, symbolic link, etc.). If given, `arcname' * specifies an alternative name for the file in the archive. * Directories are added recursively by default. This can be avoided by * setting `recursive' to False. `filter' is a function * that expects a TarInfo object argument and returns the changed * TarInfo object, if it returns None the TarInfo object will be * excluded from the archive. * */ add(name, arcname?, recursive?: boolean): Promise<any> add$({ name, arcname, recursive }: { name, arcname?, recursive?}): Promise<any> /** * Add the TarInfo object `tarinfo' to the archive. If `fileobj' is * given, it should be a binary file, and tarinfo.size bytes are read * from it and added to the archive. You can create TarInfo objects * directly, or by using gettarinfo(). * */ addfile(tarinfo, fileobj?): Promise<any> addfile$({ tarinfo, fileobj }: { tarinfo, fileobj?}): Promise<any> /** * Extract all members from the archive to the current working * directory and set owner, modification time and permissions on * directories afterwards. `path' specifies a different directory * to extract to. `members' is optional and must be a subset of the * list returned by getmembers(). If `numeric_owner` is True, only * the numbers for user/group names are used and not the names. * */ extractall(path?, members?): Promise<any> extractall$({ path, members }: { path?, members?}): Promise<any> /** * Extract a member from the archive to the current working directory, * using its full name. Its file information is extracted as accurately * as possible. `member' may be a filename or a TarInfo object. You can * specify a different directory using `path'. File attributes (owner, * mtime, mode) are set unless `set_attrs' is False. If `numeric_owner` * is True, only the numbers for user/group names are used and not * the names. * */ extract(member, path?, set_attrs?: boolean): Promise<any> extract$({ member, path, set_attrs }: { member, path?, set_attrs?}): Promise<any> /** * Extract a member from the archive as a file object. `member' may be * a filename or a TarInfo object. If `member' is a regular file or * a link, an io.BufferedReader object is returned. For all other * existing members, None is returned. If `member' does not appear * in the archive, KeyError is raised. * */ extractfile(member): Promise<any> extractfile$({ member }): Promise<any> /** * Make a directory called targetpath. * */ makedir(tarinfo, targetpath): Promise<any> makedir$({ tarinfo, targetpath }): Promise<any> /** * Make a file called targetpath. * */ makefile(tarinfo, targetpath): Promise<any> makefile$({ tarinfo, targetpath }): Promise<any> /** * Make a file from a TarInfo object with an unknown type * at targetpath. * */ makeunknown(tarinfo, targetpath): Promise<any> makeunknown$({ tarinfo, targetpath }): Promise<any> /** * Make a fifo called targetpath. * */ makefifo(tarinfo, targetpath): Promise<any> makefifo$({ tarinfo, targetpath }): Promise<any> /** * Make a character or block device called targetpath. * */ makedev(tarinfo, targetpath): Promise<any> makedev$({ tarinfo, targetpath }): Promise<any> /** * Make a (symbolic) link called targetpath. If it cannot be created * (platform limitation), we try to make a copy of the referenced file * instead of a link. * */ makelink(tarinfo, targetpath): Promise<any> makelink$({ tarinfo, targetpath }): Promise<any> /** * Set owner of targetpath according to tarinfo. If numeric_owner * is True, use .gid/.uid instead of .gname/.uname. If numeric_owner * is False, fall back to .gid/.uid when the search based on name * fails. * */ chown(tarinfo, targetpath, numeric_owner): Promise<any> chown$({ tarinfo, targetpath, numeric_owner }): Promise<any> /** * Set file permissions of targetpath according to tarinfo. * */ chmod(tarinfo, targetpath): Promise<any> chmod$({ tarinfo, targetpath }): Promise<any> /** * Set modification time of targetpath according to tarinfo. * */ utime(tarinfo, targetpath): Promise<any> utime$({ tarinfo, targetpath }): Promise<any> /** * Return the next member of the archive as a TarInfo object, when * TarFile is opened for reading. Return None if there is no more * available. * */ next(): Promise<any> next$($: {}): Promise<any> debug dereference ignore_zeros errorlevel format encoding errors tarinfo fileobject OPEN_METH } let version: Promise<any> let symlink_exception: Promise<any> let NUL: Promise<any> let BLOCKSIZE: Promise<any> let RECORDSIZE: Promise<any> let GNU_MAGIC: Promise<any> let POSIX_MAGIC: Promise<any> let LENGTH_NAME: Promise<any> let LENGTH_LINK: Promise<any> let LENGTH_PREFIX: Promise<any> let REGTYPE: Promise<any> let AREGTYPE: Promise<any> let LNKTYPE: Promise<any> let SYMTYPE: Promise<any> let CHRTYPE: Promise<any> let BLKTYPE: Promise<any> let DIRTYPE: Promise<any> let FIFOTYPE: Promise<any> let CONTTYPE: Promise<any> let GNUTYPE_LONGNAME: Promise<any> let GNUTYPE_LONGLINK: Promise<any> let GNUTYPE_SPARSE: Promise<any> let XHDTYPE: Promise<any> let XGLTYPE: Promise<any> let SOLARIS_XHDTYPE: Promise<any> let USTAR_FORMAT: Promise<any> let GNU_FORMAT: Promise<any> let PAX_FORMAT: Promise<any> let DEFAULT_FORMAT: Promise<any> let SUPPORTED_TYPES: Promise<any> let REGULAR_TYPES: Promise<any> let GNU_TYPES: Promise<any> let PAX_FIELDS: Promise<any> let PAX_NAME_FIELDS: Promise<any> let PAX_NUMBER_FIELDS: Promise<any> let ENCODING: Promise<any> } declare module threading { var _ /** * Set a profile function for all threads started from the threading module. * * The func will be passed to sys.setprofile() for each thread, before its * run() method is called. * * */ function setprofile(func): Promise<any> function setprofile$({ func }): Promise<any> /** * Get the profiler function as set by threading.setprofile(). */ function getprofile(): Promise<any> function getprofile$($: {}): Promise<any> /** * Set a trace function for all threads started from the threading module. * * The func will be passed to sys.settrace() for each thread, before its run() * method is called. * * */ function settrace(func): Promise<any> function settrace$({ func }): Promise<any> /** * Get the trace function as set by threading.settrace(). */ function gettrace(): Promise<any> function gettrace$($: {}): Promise<any> /** * Factory function that returns a new reentrant lock. * * A reentrant lock must be released by the thread that acquired it. Once a * thread has acquired a reentrant lock, the same thread may acquire it again * without blocking; the thread must release it once for each time it has * acquired it. * * */ function RLock(): Promise<any> function RLock$($: {}): Promise<any> /** * Return the current Thread object, corresponding to the caller's thread of control. * * If the caller's thread of control was not created through the threading * module, a dummy thread object with limited functionality is returned. * * */ function current_thread(): Promise<any> function current_thread$($: {}): Promise<any> /** * Return the current Thread object, corresponding to the caller's thread of control. * * This function is deprecated, use current_thread() instead. * * */ function currentThread(): Promise<any> function currentThread$($: {}): Promise<any> /** * Return the number of Thread objects currently alive. * * The returned count is equal to the length of the list returned by * enumerate(). * * */ function active_count(): Promise<any> function active_count$($: {}): Promise<any> /** * Return the number of Thread objects currently alive. * * This function is deprecated, use active_count() instead. * * */ function activeCount(): Promise<any> function activeCount$($: {}): Promise<any> /** * Return a list of all Thread objects currently alive. * * The list includes daemonic threads, dummy thread objects created by * current_thread(), and the main thread. It excludes terminated threads and * threads that have not yet been started. * * */ function enumerate(): Promise<any> function enumerate$($: {}): Promise<any> /** * Return the main thread object. * * In normal conditions, the main thread is the thread from which the * Python interpreter was started. * */ function main_thread(): Promise<any> function main_thread$($: {}): Promise<any> /** * This class implements reentrant lock objects. * * A reentrant lock must be released by the thread that acquired it. Once a * thread has acquired a reentrant lock, the same thread may acquire it * again without blocking; the thread must release it once for each time it * has acquired it. * * */ interface I_RLock { /** * Acquire a lock, blocking or non-blocking. * * When invoked without arguments: if this thread already owns the lock, * increment the recursion level by one, and return immediately. Otherwise, * if another thread owns the lock, block until the lock is unlocked. Once * the lock is unlocked (not owned by any thread), then grab ownership, set * the recursion level to one, and return. If more than one thread is * blocked waiting until the lock is unlocked, only one at a time will be * able to grab ownership of the lock. There is no return value in this * case. * * When invoked with the blocking argument set to true, do the same thing * as when called without arguments, and return true. * * When invoked with the blocking argument set to false, do not block. If a * call without an argument would block, return false immediately; * otherwise, do the same thing as when called without arguments, and * return true. * * When invoked with the floating-point timeout argument set to a positive * value, block for at most the number of seconds specified by timeout * and as long as the lock cannot be acquired. Return true if the lock has * been acquired, false if the timeout has elapsed. * * */ acquire(blocking?: boolean, timeout?): Promise<any> acquire$({ blocking, timeout }: { blocking?, timeout?}): Promise<any> /** * Release a lock, decrementing the recursion level. * * If after the decrement it is zero, reset the lock to unlocked (not owned * by any thread), and if any other threads are blocked waiting for the * lock to become unlocked, allow exactly one of them to proceed. If after * the decrement the recursion level is still nonzero, the lock remains * locked and owned by the calling thread. * * Only call this method when the calling thread owns the lock. A * RuntimeError is raised if this method is called when the lock is * unlocked. * * There is no return value. * * */ release(): Promise<any> release$($: {}): Promise<any> } /** * Class that implements a condition variable. * * A condition variable allows one or more threads to wait until they are * notified by another thread. * * If the lock argument is given and not None, it must be a Lock or RLock * object, and it is used as the underlying lock. Otherwise, a new RLock object * is created and used as the underlying lock. * * */ function Condition(lock?): Promise<ICondition> function Condition$({ lock }: { lock?}): Promise<ICondition> interface ICondition { /** * Wait until notified or until a timeout occurs. * * If the calling thread has not acquired the lock when this method is * called, a RuntimeError is raised. * * This method releases the underlying lock, and then blocks until it is * awakened by a notify() or notify_all() call for the same condition * variable in another thread, or until the optional timeout occurs. Once * awakened or timed out, it re-acquires the lock and returns. * * When the timeout argument is present and not None, it should be a * floating point number specifying a timeout for the operation in seconds * (or fractions thereof). * * When the underlying lock is an RLock, it is not released using its * release() method, since this may not actually unlock the lock when it * was acquired multiple times recursively. Instead, an internal interface * of the RLock class is used, which really unlocks it even when it has * been recursively acquired several times. Another internal interface is * then used to restore the recursion level when the lock is reacquired. * * */ wait(timeout?): Promise<any> wait$({ timeout }: { timeout?}): Promise<any> /** * Wait until a condition evaluates to True. * * predicate should be a callable which result will be interpreted as a * boolean value. A timeout may be provided giving the maximum time to * wait. * * */ wait_for(predicate, timeout?): Promise<any> wait_for$({ predicate, timeout }: { predicate, timeout?}): Promise<any> /** * Wake up one or more threads waiting on this condition, if any. * * If the calling thread has not acquired the lock when this method is * called, a RuntimeError is raised. * * This method wakes up at most n of the threads waiting for the condition * variable; it is a no-op if no threads are waiting. * * */ notify(n?): Promise<any> notify$({ n }: { n?}): Promise<any> /** * Wake up all threads waiting on this condition. * * If the calling thread has not acquired the lock when this method * is called, a RuntimeError is raised. * * */ notify_all(): Promise<any> notify_all$($: {}): Promise<any> /** * Wake up all threads waiting on this condition. * * This method is deprecated, use notify_all() instead. * * */ notifyAll(): Promise<any> notifyAll$($: {}): Promise<any> } /** * This class implements semaphore objects. * * Semaphores manage a counter representing the number of release() calls minus * the number of acquire() calls, plus an initial value. The acquire() method * blocks if necessary until it can return without making the counter * negative. If not given, value defaults to 1. * * */ function Semaphore(value?): Promise<ISemaphore> function Semaphore$({ value }: { value?}): Promise<ISemaphore> interface ISemaphore { /** * Acquire a semaphore, decrementing the internal counter by one. * * When invoked without arguments: if the internal counter is larger than * zero on entry, decrement it by one and return immediately. If it is zero * on entry, block, waiting until some other thread has called release() to * make it larger than zero. This is done with proper interlocking so that * if multiple acquire() calls are blocked, release() will wake exactly one * of them up. The implementation may pick one at random, so the order in * which blocked threads are awakened should not be relied on. There is no * return value in this case. * * When invoked with blocking set to true, do the same thing as when called * without arguments, and return true. * * When invoked with blocking set to false, do not block. If a call without * an argument would block, return false immediately; otherwise, do the * same thing as when called without arguments, and return true. * * When invoked with a timeout other than None, it will block for at * most timeout seconds. If acquire does not complete successfully in * that interval, return false. Return true otherwise. * * */ acquire(blocking?: boolean, timeout?): Promise<any> acquire$({ blocking, timeout }: { blocking?, timeout?}): Promise<any> /** * Release a semaphore, incrementing the internal counter by one or more. * * When the counter is zero on entry and another thread is waiting for it * to become larger than zero again, wake up that thread. * * */ release(n?): Promise<any> release$({ n }: { n?}): Promise<any> } /** * Implements a bounded semaphore. * * A bounded semaphore checks to make sure its current value doesn't exceed its * initial value. If it does, ValueError is raised. In most situations * semaphores are used to guard resources with limited capacity. * * If the semaphore is released too many times it's a sign of a bug. If not * given, value defaults to 1. * * Like regular semaphores, bounded semaphores manage a counter representing * the number of release() calls minus the number of acquire() calls, plus an * initial value. The acquire() method blocks if necessary until it can return * without making the counter negative. If not given, value defaults to 1. * * */ function BoundedSemaphore(value?): Promise<IBoundedSemaphore> function BoundedSemaphore$({ value }: { value?}): Promise<IBoundedSemaphore> interface IBoundedSemaphore extends ISemaphore { /** * Release a semaphore, incrementing the internal counter by one or more. * * When the counter is zero on entry and another thread is waiting for it * to become larger than zero again, wake up that thread. * * If the number of releases exceeds the number of acquires, * raise a ValueError. * * */ release(n?): Promise<any> release$({ n }: { n?}): Promise<any> } /** * Class implementing event objects. * * Events manage a flag that can be set to true with the set() method and reset * to false with the clear() method. The wait() method blocks until the flag is * true. The flag is initially false. * * */ function Event(): Promise<IEvent> function Event$({ }): Promise<IEvent> interface IEvent { /** * Return true if and only if the internal flag is true. */ is_set(): Promise<any> is_set$($: {}): Promise<any> /** * Return true if and only if the internal flag is true. * * This method is deprecated, use notify_all() instead. * * */ isSet(): Promise<any> isSet$($: {}): Promise<any> /** * Set the internal flag to true. * * All threads waiting for it to become true are awakened. Threads * that call wait() once the flag is true will not block at all. * * */ set(): Promise<any> set$($: {}): Promise<any> /** * Reset the internal flag to false. * * Subsequently, threads calling wait() will block until set() is called to * set the internal flag to true again. * * */ clear(): Promise<any> clear$($: {}): Promise<any> /** * Block until the internal flag is true. * * If the internal flag is true on entry, return immediately. Otherwise, * block until another thread calls set() to set the flag to true, or until * the optional timeout occurs. * * When the timeout argument is present and not None, it should be a * floating point number specifying a timeout for the operation in seconds * (or fractions thereof). * * This method returns the internal flag on exit, so it will always return * True except if a timeout is given and the operation times out. * * */ wait(timeout?): Promise<any> wait$({ timeout }: { timeout?}): Promise<any> } /** * Implements a Barrier. * * Useful for synchronizing a fixed number of threads at known synchronization * points. Threads block on 'wait()' and are simultaneously awoken once they * have all made that call. * * */ /** * Create a barrier, initialised to 'parties' threads. * * 'action' is a callable which, when supplied, will be called by one of * the threads after they have all entered the barrier and just prior to * releasing them all. If a 'timeout' is provided, it is used as the * default for all subsequent 'wait()' calls. * * */ function Barrier(parties, action?, timeout?): Promise<IBarrier> function Barrier$({ parties, action, timeout }: { parties, action?, timeout?}): Promise<IBarrier> interface IBarrier { /** * Wait for the barrier. * * When the specified number of threads have started waiting, they are all * simultaneously awoken. If an 'action' was provided for the barrier, one * of the threads will have executed that callback prior to returning. * Returns an individual index number from 0 to 'parties-1'. * * */ wait(timeout?): Promise<any> wait$({ timeout }: { timeout?}): Promise<any> /** * Reset the barrier to the initial state. * * Any threads currently waiting will get the BrokenBarrier exception * raised. * * */ reset(): Promise<any> reset$($: {}): Promise<any> /** * Place the barrier into a 'broken' state. * * Useful in case of error. Any currently waiting threads and threads * attempting to 'wait()' will have BrokenBarrierError raised. * * */ abort(): Promise<any> abort$($: {}): Promise<any> /** * Return the number of threads required to trip the barrier. */ parties(): Promise<any> parties$($: {}): Promise<any> /** * Return the number of threads currently waiting at the barrier. */ n_waiting(): Promise<any> n_waiting$($: {}): Promise<any> /** * Return True if the barrier is in a broken state. */ broken(): Promise<any> broken$($: {}): Promise<any> } interface IBrokenBarrierError { } /** * A class that represents a thread of control. * * This class can be safely subclassed in a limited fashion. There are two ways * to specify the activity: by passing a callable object to the constructor, or * by overriding the run() method in a subclass. * * */ /** * This constructor should always be called with keyword arguments. Arguments are: * * *group* should be None; reserved for future extension when a ThreadGroup * class is implemented. * * *target* is the callable object to be invoked by the run() * method. Defaults to None, meaning nothing is called. * * *name* is the thread name. By default, a unique name is constructed of * the form "Thread-N" where N is a small decimal number. * * *args* is the argument tuple for the target invocation. Defaults to (). * * *kwargs* is a dictionary of keyword arguments for the target * invocation. Defaults to {}. * * If a subclass overrides the constructor, it must make sure to invoke * the base class constructor (Thread.__init__()) before doing anything * else to the thread. * * */ function Thread(group?, target?, name?, args?, kwargs?): Promise<IThread> function Thread$({ group, target, name, args, kwargs }: { group?, target?, name?, args?, kwargs?}): Promise<IThread> interface IThread { /** * Start the thread's activity. * * It must be called at most once per thread object. It arranges for the * object's run() method to be invoked in a separate thread of control. * * This method will raise a RuntimeError if called more than once on the * same thread object. * * */ start(): Promise<any> start$($: {}): Promise<any> /** * Method representing the thread's activity. * * You may override this method in a subclass. The standard run() method * invokes the callable object passed to the object's constructor as the * target argument, if any, with sequential and keyword arguments taken * from the args and kwargs arguments, respectively. * * */ run(): Promise<any> run$($: {}): Promise<any> /** * Wait until the thread terminates. * * This blocks the calling thread until the thread whose join() method is * called terminates -- either normally or through an unhandled exception * or until the optional timeout occurs. * * When the timeout argument is present and not None, it should be a * floating point number specifying a timeout for the operation in seconds * (or fractions thereof). As join() always returns None, you must call * is_alive() after join() to decide whether a timeout happened -- if the * thread is still alive, the join() call timed out. * * When the timeout argument is not present or None, the operation will * block until the thread terminates. * * A thread can be join()ed many times. * * join() raises a RuntimeError if an attempt is made to join the current * thread as that would cause a deadlock. It is also an error to join() a * thread before it has been started and attempts to do so raises the same * exception. * * */ join(timeout?): Promise<any> join$({ timeout }: { timeout?}): Promise<any> /** * A string used for identification purposes only. * * It has no semantics. Multiple threads may be given the same name. The * initial name is set by the constructor. * * */ name(): Promise<any> name$($: {}): Promise<any> name(name): Promise<any> name$({ name }): Promise<any> /** * Thread identifier of this thread or None if it has not been started. * * This is a nonzero integer. See the get_ident() function. Thread * identifiers may be recycled when a thread exits and another thread is * created. The identifier is available even after the thread has exited. * * */ ident(): Promise<any> ident$($: {}): Promise<any> /** * Return whether the thread is alive. * * This method returns True just before the run() method starts until just * after the run() method terminates. See also the module function * enumerate(). * * */ is_alive(): Promise<any> is_alive$($: {}): Promise<any> /** * A boolean value indicating whether this thread is a daemon thread. * * This must be set before start() is called, otherwise RuntimeError is * raised. Its initial value is inherited from the creating thread; the * main thread is not a daemon thread and therefore all threads created in * the main thread default to daemon = False. * * The entire Python program exits when only daemon threads are left. * * */ daemon(): Promise<any> daemon$($: {}): Promise<any> daemon(daemonic): Promise<any> daemon$({ daemonic }): Promise<any> /** * Return whether this thread is a daemon. * * This method is deprecated, use the daemon attribute instead. * * */ isDaemon(): Promise<any> isDaemon$($: {}): Promise<any> /** * Set whether this thread is a daemon. * * This method is deprecated, use the .daemon property instead. * * */ setDaemon(daemonic): Promise<any> setDaemon$({ daemonic }): Promise<any> /** * Return a string used for identification purposes only. * * This method is deprecated, use the name attribute instead. * * */ getName(): Promise<any> getName$($: {}): Promise<any> /** * Set the name string for this thread. * * This method is deprecated, use the name attribute instead. * * */ setName(name): Promise<any> setName$({ name }): Promise<any> } /** * Call a function after a specified number of seconds: * * t = Timer(30.0, f, args=None, kwargs=None) * t.start() * t.cancel() # stop the timer's action if it's still waiting * * */ function Timer(interval, func, args?, kwargs?): Promise<ITimer> function Timer$({ interval, func, args, kwargs }: { interval, func, args?, kwargs?}): Promise<ITimer> interface ITimer extends IThread { /** * Stop the timer if it hasn't finished yet. */ cancel(): Promise<any> cancel$($: {}): Promise<any> run(): Promise<any> run$($: {}): Promise<any> } interface I_MainThread extends IThread { } interface I_DummyThread extends IThread { is_alive(): Promise<any> is_alive$($: {}): Promise<any> join(timeout?): Promise<any> join$({ timeout }: { timeout?}): Promise<any> } let get_ident: Promise<any> let get_native_id: Promise<any> let ThreadError: Promise<any> let TIMEOUT_MAX: Promise<any> let Lock: Promise<any> } declare module tkinter { var _ /** * Inhibit setting of default root window. * * Call this function to inhibit that the first instance of * Tk is used for windows without an explicit parent window. * */ function NoDefaultRoot(): Promise<any> function NoDefaultRoot$($: {}): Promise<any> /** * Run the main loop of Tcl. */ function mainloop(n?): Promise<any> function mainloop$({ n }: { n?}): Promise<any> /** * Convert Tcl object to True or False. */ function getboolean(s): Promise<any> function getboolean$({ s }): Promise<any> function Tcl(screenName?, baseName?, className?, useTk?: boolean): Promise<any> function Tcl$({ screenName, baseName, className, useTk }: { screenName?, baseName?, className?, useTk?}): Promise<any> function image_names(): Promise<any> function image_names$($: {}): Promise<any> function image_types(): Promise<any> function image_types$($: {}): Promise<any> interface IEventType { KeyPress Key KeyRelease ButtonPress Button ButtonRelease Motion Enter Leave FocusIn FocusOut Keymap Expose GraphicsExpose NoExpose Visibility Create Destroy Unmap Map MapRequest Reparent Configure ConfigureRequest Gravity ResizeRequest Circulate CirculateRequest Property SelectionClear SelectionRequest Selection Colormap ClientMessage Mapping VirtualEvent Activate Deactivate MouseWheel } /** * Container for the properties of an event. * * Instances of this type are generated if one of the following events occurs: * * KeyPress, KeyRelease - for keyboard events * ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events * Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate, * Colormap, Gravity, Reparent, Property, Destroy, Activate, * Deactivate - for window events. * * If a callback function for one of these events is registered * using bind, bind_all, bind_class, or tag_bind, the callback is * called with an Event as first argument. It will have the * following attributes (in braces are the event types for which * the attribute is valid): * * serial - serial number of event * num - mouse button pressed (ButtonPress, ButtonRelease) * focus - whether the window has the focus (Enter, Leave) * height - height of the exposed window (Configure, Expose) * width - width of the exposed window (Configure, Expose) * keycode - keycode of the pressed key (KeyPress, KeyRelease) * state - state of the event as a number (ButtonPress, ButtonRelease, * Enter, KeyPress, KeyRelease, * Leave, Motion) * state - state as a string (Visibility) * time - when the event occurred * x - x-position of the mouse * y - y-position of the mouse * x_root - x-position of the mouse on the screen * (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion) * y_root - y-position of the mouse on the screen * (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion) * char - pressed character (KeyPress, KeyRelease) * send_event - see X/Windows documentation * keysym - keysym of the event as a string (KeyPress, KeyRelease) * keysym_num - keysym of the event as a number (KeyPress, KeyRelease) * type - type of the event as a number * widget - widget in which the event occurred * delta - delta of wheel movement (MouseWheel) * */ interface IEvent { } /** * Class to define value holders for e.g. buttons. * * Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations * that constrain the type of the value returned from get(). */ /** * Construct a variable * * MASTER can be given as master widget. * VALUE is an optional value (defaults to "") * NAME is an optional Tcl name (defaults to PY_VARnum). * * If NAME matches an existing variable and VALUE is omitted * then the existing value is retained. * */ function Variable(master?, value?, name?): Promise<IVariable> function Variable$({ master, value, name }: { master?, value?, name?}): Promise<IVariable> interface IVariable { /** * Set the variable to VALUE. */ set(value): Promise<any> set$({ value }): Promise<any> /** * Return value of variable. */ get(): Promise<any> get$($: {}): Promise<any> /** * Define a trace callback for the variable. * * Mode is one of "read", "write", "unset", or a list or tuple of * such strings. * Callback must be a function which is called when the variable is * read, written or unset. * * Return the name of the callback. * */ trace_add(mode, callback): Promise<any> trace_add$({ mode, callback }): Promise<any> /** * Delete the trace callback for a variable. * * Mode is one of "read", "write", "unset" or a list or tuple of * such strings. Must be same as were specified in trace_add(). * cbname is the name of the callback returned from trace_add(). * */ trace_remove(mode, cbname): Promise<any> trace_remove$({ mode, cbname }): Promise<any> /** * Return all trace callback information. */ trace_info(): Promise<any> trace_info$($: {}): Promise<any> /** * Define a trace callback for the variable. * * MODE is one of "r", "w", "u" for read, write, undefine. * CALLBACK must be a function which is called when * the variable is read, written or undefined. * * Return the name of the callback. * * This deprecated method wraps a deprecated Tcl method that will * likely be removed in the future. Use trace_add() instead. * */ trace_variable(mode, callback): Promise<any> trace_variable$({ mode, callback }): Promise<any> /** * Delete the trace callback for a variable. * * MODE is one of "r", "w", "u" for read, write, undefine. * CBNAME is the name of the callback returned from trace_variable or trace. * * This deprecated method wraps a deprecated Tcl method that will * likely be removed in the future. Use trace_remove() instead. * */ trace_vdelete(mode, cbname): Promise<any> trace_vdelete$({ mode, cbname }): Promise<any> /** * Return all trace callback information. * * This deprecated method wraps a deprecated Tcl method that will * likely be removed in the future. Use trace_info() instead. * */ trace_vinfo(): Promise<any> trace_vinfo$($: {}): Promise<any> initialize trace } /** * Value holder for strings variables. */ /** * Construct a string variable. * * MASTER can be given as master widget. * VALUE is an optional value (defaults to "") * NAME is an optional Tcl name (defaults to PY_VARnum). * * If NAME matches an existing variable and VALUE is omitted * then the existing value is retained. * */ function StringVar(master?, value?, name?): Promise<IStringVar> function StringVar$({ master, value, name }: { master?, value?, name?}): Promise<IStringVar> interface IStringVar extends IVariable { /** * Return value of variable as string. */ get(): Promise<any> get$($: {}): Promise<any> } /** * Value holder for integer variables. */ /** * Construct an integer variable. * * MASTER can be given as master widget. * VALUE is an optional value (defaults to 0) * NAME is an optional Tcl name (defaults to PY_VARnum). * * If NAME matches an existing variable and VALUE is omitted * then the existing value is retained. * */ function IntVar(master?, value?, name?): Promise<IIntVar> function IntVar$({ master, value, name }: { master?, value?, name?}): Promise<IIntVar> interface IIntVar extends IVariable { /** * Return the value of the variable as an integer. */ get(): Promise<any> get$($: {}): Promise<any> } /** * Value holder for float variables. */ /** * Construct a float variable. * * MASTER can be given as master widget. * VALUE is an optional value (defaults to 0.0) * NAME is an optional Tcl name (defaults to PY_VARnum). * * If NAME matches an existing variable and VALUE is omitted * then the existing value is retained. * */ function DoubleVar(master?, value?, name?): Promise<IDoubleVar> function DoubleVar$({ master, value, name }: { master?, value?, name?}): Promise<IDoubleVar> interface IDoubleVar extends IVariable { /** * Return the value of the variable as a float. */ get(): Promise<any> get$($: {}): Promise<any> } /** * Value holder for boolean variables. */ /** * Construct a boolean variable. * * MASTER can be given as master widget. * VALUE is an optional value (defaults to False) * NAME is an optional Tcl name (defaults to PY_VARnum). * * If NAME matches an existing variable and VALUE is omitted * then the existing value is retained. * */ function BooleanVar(master?, value?, name?): Promise<IBooleanVar> function BooleanVar$({ master, value, name }: { master?, value?, name?}): Promise<IBooleanVar> interface IBooleanVar extends IVariable { /** * Set the variable to VALUE. */ set(value): Promise<any> set$({ value }): Promise<any> /** * Return the value of the variable as a bool. */ get(): Promise<any> get$($: {}): Promise<any> } /** * Internal class. * * Base class which defines methods common for interior widgets. */ interface IMisc { /** * Internal function. * * Delete all Tcl commands created for * this widget in the Tcl interpreter. */ destroy(): Promise<any> destroy$($: {}): Promise<any> /** * Internal function. * * Delete the Tcl command provided in NAME. */ deletecommand(name): Promise<any> deletecommand$({ name }): Promise<any> /** * Set Tcl internal variable, whether the look and feel * should adhere to Motif. * * A parameter of 1 means adhere to Motif (e.g. no color * change if mouse passes over slider). * Returns the set value. */ tk_strictMotif(boolean?): Promise<any> tk_strictMotif$({ boolean }: { boolean?}): Promise<any> /** * Change the color scheme to light brown as used in Tk 3.6 and before. */ tk_bisque(): Promise<any> tk_bisque$($: {}): Promise<any> /** * Set a new color scheme for all widget elements. * * A single color as argument will cause that all colors of Tk * widget elements are derived from this. * Alternatively several keyword parameters and its associated * colors can be given. The following keywords are valid: * activeBackground, foreground, selectColor, * activeForeground, highlightBackground, selectBackground, * background, highlightColor, selectForeground, * disabledForeground, insertBackground, troughColor. */ tk_setPalette(): Promise<any> tk_setPalette$($: {}): Promise<any> /** * Wait until the variable is modified. * * A parameter of type IntVar, StringVar, DoubleVar or * BooleanVar must be given. */ wait_variable(name?): Promise<any> wait_variable$({ name }: { name?}): Promise<any> /** * Wait until a WIDGET is destroyed. * * If no parameter is given self is used. */ wait_window(window?): Promise<any> wait_window$({ window }: { window?}): Promise<any> /** * Wait until the visibility of a WIDGET changes * (e.g. it appears). * * If no parameter is given self is used. */ wait_visibility(window?): Promise<any> wait_visibility$({ window }: { window?}): Promise<any> /** * Set Tcl variable NAME to VALUE. */ setvar(name?, value?): Promise<any> setvar$({ name, value }: { name?, value?}): Promise<any> /** * Return value of Tcl variable NAME. */ getvar(name?): Promise<any> getvar$({ name }: { name?}): Promise<any> getint(s): Promise<any> getint$({ s }): Promise<any> getdouble(s): Promise<any> getdouble$({ s }): Promise<any> /** * Return a boolean value for Tcl boolean values true and false given as parameter. */ getboolean(s): Promise<any> getboolean$({ s }): Promise<any> /** * Direct input focus to this widget. * * If the application currently does not have the focus * this widget will get the focus if the application gets * the focus through the window manager. */ focus_set(): Promise<any> focus_set$($: {}): Promise<any> /** * Direct input focus to this widget even if the * application does not have the focus. Use with * caution! */ focus_force(): Promise<any> focus_force$($: {}): Promise<any> /** * Return the widget which has currently the focus in the * application. * * Use focus_displayof to allow working with several * displays. Return None if application does not have * the focus. */ focus_get(): Promise<any> focus_get$($: {}): Promise<any> /** * Return the widget which has currently the focus on the * display where this widget is located. * * Return None if the application does not have the focus. */ focus_displayof(): Promise<any> focus_displayof$($: {}): Promise<any> /** * Return the widget which would have the focus if top level * for this widget gets the focus from the window manager. */ focus_lastfor(): Promise<any> focus_lastfor$($: {}): Promise<any> /** * The widget under mouse will get automatically focus. Can not * be disabled easily. */ tk_focusFollowsMouse(): Promise<any> tk_focusFollowsMouse$($: {}): Promise<any> /** * Return the next widget in the focus order which follows * widget which has currently the focus. * * The focus order first goes to the next child, then to * the children of the child recursively and then to the * next sibling which is higher in the stacking order. A * widget is omitted if it has the takefocus resource set * to 0. */ tk_focusNext(): Promise<any> tk_focusNext$($: {}): Promise<any> /** * Return previous widget in the focus order. See tk_focusNext for details. */ tk_focusPrev(): Promise<any> tk_focusPrev$($: {}): Promise<any> /** * Call function once after given time. * * MS specifies the time in milliseconds. FUNC gives the * function which shall be called. Additional parameters * are given as parameters to the function call. Return * identifier to cancel scheduling with after_cancel. */ after(ms, func?): Promise<any> after$({ ms, func }: { ms, func?}): Promise<any> /** * Call FUNC once if the Tcl main loop has no event to * process. * * Return an identifier to cancel the scheduling with * after_cancel. */ after_idle(func): Promise<any> after_idle$({ func }): Promise<any> /** * Cancel scheduling of function identified with ID. * * Identifier returned by after or after_idle must be * given as first parameter. * */ after_cancel(id): Promise<any> after_cancel$({ id }): Promise<any> /** * Ring a display's bell. */ bell(displayof?): Promise<any> bell$({ displayof }: { displayof?}): Promise<any> /** * Retrieve data from the clipboard on window's display. * * The window keyword defaults to the root window of the Tkinter * application. * * The type keyword specifies the form in which the data is * to be returned and should be an atom name such as STRING * or FILE_NAME. Type defaults to STRING, except on X11, where the default * is to try UTF8_STRING and fall back to STRING. * * This command is equivalent to: * * selection_get(CLIPBOARD) * */ clipboard_get(): Promise<any> clipboard_get$($: {}): Promise<any> /** * Clear the data in the Tk clipboard. * * A widget specified for the optional displayof keyword * argument specifies the target display. */ clipboard_clear(): Promise<any> clipboard_clear$($: {}): Promise<any> /** * Append STRING to the Tk clipboard. * * A widget specified at the optional displayof keyword * argument specifies the target display. The clipboard * can be retrieved with selection_get. */ clipboard_append(string): Promise<any> clipboard_append$({ string }): Promise<any> /** * Return widget which has currently the grab in this application * or None. */ grab_current(): Promise<any> grab_current$($: {}): Promise<any> /** * Release grab for this widget if currently set. */ grab_release(): Promise<any> grab_release$($: {}): Promise<any> /** * Set grab for this widget. * * A grab directs all events to this and descendant * widgets in the application. */ grab_set(): Promise<any> grab_set$($: {}): Promise<any> /** * Set global grab for this widget. * * A global grab directs all events to this and * descendant widgets on the display. Use with caution - * other applications do not get events anymore. */ grab_set_global(): Promise<any> grab_set_global$($: {}): Promise<any> /** * Return None, "local" or "global" if this widget has * no, a local or a global grab. */ grab_status(): Promise<any> grab_status$($: {}): Promise<any> /** * Set a VALUE (second parameter) for an option * PATTERN (first parameter). * * An optional third parameter gives the numeric priority * (defaults to 80). */ option_add(pattern, value, priority?): Promise<any> option_add$({ pattern, value, priority }: { pattern, value, priority?}): Promise<any> /** * Clear the option database. * * It will be reloaded if option_add is called. */ option_clear(): Promise<any> option_clear$($: {}): Promise<any> /** * Return the value for an option NAME for this widget * with CLASSNAME. * * Values with higher priority override lower values. */ option_get(name, className): Promise<any> option_get$({ name, className }): Promise<any> /** * Read file FILENAME into the option database. * * An optional second parameter gives the numeric * priority. */ option_readfile(fileName, priority?): Promise<any> option_readfile$({ fileName, priority }: { fileName, priority?}): Promise<any> /** * Clear the current X selection. */ selection_clear(): Promise<any> selection_clear$($: {}): Promise<any> /** * Return the contents of the current X selection. * * A keyword parameter selection specifies the name of * the selection and defaults to PRIMARY. A keyword * parameter displayof specifies a widget on the display * to use. A keyword parameter type specifies the form of data to be * fetched, defaulting to STRING except on X11, where UTF8_STRING is tried * before STRING. */ selection_get(): Promise<any> selection_get$($: {}): Promise<any> /** * Specify a function COMMAND to call if the X * selection owned by this widget is queried by another * application. * * This function must return the contents of the * selection. The function will be called with the * arguments OFFSET and LENGTH which allows the chunking * of very long selections. The following keyword * parameters can be provided: * selection - name of the selection (default PRIMARY), * type - type of the selection (e.g. STRING, FILE_NAME). */ selection_handle(command): Promise<any> selection_handle$({ command }): Promise<any> /** * Become owner of X selection. * * A keyword parameter selection specifies the name of * the selection (default PRIMARY). */ selection_own(): Promise<any> selection_own$($: {}): Promise<any> /** * Return owner of X selection. * * The following keyword parameter can * be provided: * selection - name of the selection (default PRIMARY), * type - type of the selection (e.g. STRING, FILE_NAME). */ selection_own_get(): Promise<any> selection_own_get$($: {}): Promise<any> /** * Send Tcl command CMD to different interpreter INTERP to be executed. */ send(interp, cmd): Promise<any> send$({ interp, cmd }): Promise<any> /** * Lower this widget in the stacking order. */ lower(belowThis?): Promise<any> lower$({ belowThis }: { belowThis?}): Promise<any> /** * Raise this widget in the stacking order. */ tkraise(aboveThis?): Promise<any> tkraise$({ aboveThis }: { aboveThis?}): Promise<any> /** * Return integer which represents atom NAME. */ winfo_atom(name, displayof?): Promise<any> winfo_atom$({ name, displayof }: { name, displayof?}): Promise<any> /** * Return name of atom with identifier ID. */ winfo_atomname(id, displayof?): Promise<any> winfo_atomname$({ id, displayof }: { id, displayof?}): Promise<any> /** * Return number of cells in the colormap for this widget. */ winfo_cells(): Promise<any> winfo_cells$($: {}): Promise<any> /** * Return a list of all widgets which are children of this widget. */ winfo_children(): Promise<any> winfo_children$($: {}): Promise<any> /** * Return window class name of this widget. */ winfo_class(): Promise<any> winfo_class$($: {}): Promise<any> /** * Return True if at the last color request the colormap was full. */ winfo_colormapfull(): Promise<any> winfo_colormapfull$($: {}): Promise<any> /** * Return the widget which is at the root coordinates ROOTX, ROOTY. */ winfo_containing(rootX, rootY, displayof?): Promise<any> winfo_containing$({ rootX, rootY, displayof }: { rootX, rootY, displayof?}): Promise<any> /** * Return the number of bits per pixel. */ winfo_depth(): Promise<any> winfo_depth$($: {}): Promise<any> /** * Return true if this widget exists. */ winfo_exists(): Promise<any> winfo_exists$($: {}): Promise<any> /** * Return the number of pixels for the given distance NUMBER * (e.g. "3c") as float. */ winfo_fpixels(number): Promise<any> winfo_fpixels$({ number }): Promise<any> /** * Return geometry string for this widget in the form "widthxheight+X+Y". */ winfo_geometry(): Promise<any> winfo_geometry$($: {}): Promise<any> /** * Return height of this widget. */ winfo_height(): Promise<any> winfo_height$($: {}): Promise<any> /** * Return identifier ID for this widget. */ winfo_id(): Promise<any> winfo_id$($: {}): Promise<any> /** * Return the name of all Tcl interpreters for this display. */ winfo_interps(displayof?): Promise<any> winfo_interps$({ displayof }: { displayof?}): Promise<any> /** * Return true if this widget is mapped. */ winfo_ismapped(): Promise<any> winfo_ismapped$($: {}): Promise<any> /** * Return the window manager name for this widget. */ winfo_manager(): Promise<any> winfo_manager$($: {}): Promise<any> /** * Return the name of this widget. */ winfo_name(): Promise<any> winfo_name$($: {}): Promise<any> /** * Return the name of the parent of this widget. */ winfo_parent(): Promise<any> winfo_parent$($: {}): Promise<any> /** * Return the pathname of the widget given by ID. */ winfo_pathname(id, displayof?): Promise<any> winfo_pathname$({ id, displayof }: { id, displayof?}): Promise<any> /** * Rounded integer value of winfo_fpixels. */ winfo_pixels(number): Promise<any> winfo_pixels$({ number }): Promise<any> /** * Return the x coordinate of the pointer on the root window. */ winfo_pointerx(): Promise<any> winfo_pointerx$($: {}): Promise<any> /** * Return a tuple of x and y coordinates of the pointer on the root window. */ winfo_pointerxy(): Promise<any> winfo_pointerxy$($: {}): Promise<any> /** * Return the y coordinate of the pointer on the root window. */ winfo_pointery(): Promise<any> winfo_pointery$($: {}): Promise<any> /** * Return requested height of this widget. */ winfo_reqheight(): Promise<any> winfo_reqheight$($: {}): Promise<any> /** * Return requested width of this widget. */ winfo_reqwidth(): Promise<any> winfo_reqwidth$($: {}): Promise<any> /** * Return a tuple of integer RGB values in range(65536) for color in this widget. */ winfo_rgb(color): Promise<any> winfo_rgb$({ color }): Promise<any> /** * Return x coordinate of upper left corner of this widget on the * root window. */ winfo_rootx(): Promise<any> winfo_rootx$($: {}): Promise<any> /** * Return y coordinate of upper left corner of this widget on the * root window. */ winfo_rooty(): Promise<any> winfo_rooty$($: {}): Promise<any> /** * Return the screen name of this widget. */ winfo_screen(): Promise<any> winfo_screen$($: {}): Promise<any> /** * Return the number of the cells in the colormap of the screen * of this widget. */ winfo_screencells(): Promise<any> winfo_screencells$($: {}): Promise<any> /** * Return the number of bits per pixel of the root window of the * screen of this widget. */ winfo_screendepth(): Promise<any> winfo_screendepth$($: {}): Promise<any> /** * Return the number of pixels of the height of the screen of this widget * in pixel. */ winfo_screenheight(): Promise<any> winfo_screenheight$($: {}): Promise<any> /** * Return the number of pixels of the height of the screen of * this widget in mm. */ winfo_screenmmheight(): Promise<any> winfo_screenmmheight$($: {}): Promise<any> /** * Return the number of pixels of the width of the screen of * this widget in mm. */ winfo_screenmmwidth(): Promise<any> winfo_screenmmwidth$($: {}): Promise<any> /** * Return one of the strings directcolor, grayscale, pseudocolor, * staticcolor, staticgray, or truecolor for the default * colormodel of this screen. */ winfo_screenvisual(): Promise<any> winfo_screenvisual$($: {}): Promise<any> /** * Return the number of pixels of the width of the screen of * this widget in pixel. */ winfo_screenwidth(): Promise<any> winfo_screenwidth$($: {}): Promise<any> /** * Return information of the X-Server of the screen of this widget in * the form "XmajorRminor vendor vendorVersion". */ winfo_server(): Promise<any> winfo_server$($: {}): Promise<any> /** * Return the toplevel widget of this widget. */ winfo_toplevel(): Promise<any> winfo_toplevel$($: {}): Promise<any> /** * Return true if the widget and all its higher ancestors are mapped. */ winfo_viewable(): Promise<any> winfo_viewable$($: {}): Promise<any> /** * Return one of the strings directcolor, grayscale, pseudocolor, * staticcolor, staticgray, or truecolor for the * colormodel of this widget. */ winfo_visual(): Promise<any> winfo_visual$($: {}): Promise<any> /** * Return the X identifier for the visual for this widget. */ winfo_visualid(): Promise<any> winfo_visualid$($: {}): Promise<any> /** * Return a list of all visuals available for the screen * of this widget. * * Each item in the list consists of a visual name (see winfo_visual), a * depth and if includeids is true is given also the X identifier. */ winfo_visualsavailable(includeids?: boolean): Promise<any> winfo_visualsavailable$({ includeids }: { includeids?}): Promise<any> /** * Return the height of the virtual root window associated with this * widget in pixels. If there is no virtual root window return the * height of the screen. */ winfo_vrootheight(): Promise<any> winfo_vrootheight$($: {}): Promise<any> /** * Return the width of the virtual root window associated with this * widget in pixel. If there is no virtual root window return the * width of the screen. */ winfo_vrootwidth(): Promise<any> winfo_vrootwidth$($: {}): Promise<any> /** * Return the x offset of the virtual root relative to the root * window of the screen of this widget. */ winfo_vrootx(): Promise<any> winfo_vrootx$($: {}): Promise<any> /** * Return the y offset of the virtual root relative to the root * window of the screen of this widget. */ winfo_vrooty(): Promise<any> winfo_vrooty$($: {}): Promise<any> /** * Return the width of this widget. */ winfo_width(): Promise<any> winfo_width$($: {}): Promise<any> /** * Return the x coordinate of the upper left corner of this widget * in the parent. */ winfo_x(): Promise<any> winfo_x$($: {}): Promise<any> /** * Return the y coordinate of the upper left corner of this widget * in the parent. */ winfo_y(): Promise<any> winfo_y$($: {}): Promise<any> /** * Enter event loop until all pending events have been processed by Tcl. */ update(): Promise<any> update$($: {}): Promise<any> /** * Enter event loop until all idle callbacks have been called. This * will update the display of windows but not process events caused by * the user. */ update_idletasks(): Promise<any> update_idletasks$($: {}): Promise<any> /** * Set or get the list of bindtags for this widget. * * With no argument return the list of all bindtags associated with * this widget. With a list of strings as argument the bindtags are * set to this list. The bindtags determine in which order events are * processed (see bind). */ bindtags(tagList?): Promise<any> bindtags$({ tagList }: { tagList?}): Promise<any> /** * Bind to this widget at event SEQUENCE a call to function FUNC. * * SEQUENCE is a string of concatenated event * patterns. An event pattern is of the form * <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one * of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4, * Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3, * B3, Alt, Button4, B4, Double, Button5, B5 Triple, * Mod1, M1. TYPE is one of Activate, Enter, Map, * ButtonPress, Button, Expose, Motion, ButtonRelease * FocusIn, MouseWheel, Circulate, FocusOut, Property, * Colormap, Gravity Reparent, Configure, KeyPress, Key, * Unmap, Deactivate, KeyRelease Visibility, Destroy, * Leave and DETAIL is the button number for ButtonPress, * ButtonRelease and DETAIL is the Keysym for KeyPress and * KeyRelease. Examples are * <Control-Button-1> for pressing Control and mouse button 1 or * <Alt-A> for pressing A and the Alt key (KeyPress can be omitted). * An event pattern can also be a virtual event of the form * <<AString>> where AString can be arbitrary. This * event can be generated by event_generate. * If events are concatenated they must appear shortly * after each other. * * FUNC will be called if the event sequence occurs with an * instance of Event as argument. If the return value of FUNC is * "break" no further bound function is invoked. * * An additional boolean parameter ADD specifies whether FUNC will * be called additionally to the other bound function or whether * it will replace the previous function. * * Bind will return an identifier to allow deletion of the bound function with * unbind without memory leak. * * If FUNC or SEQUENCE is omitted the bound function or list * of bound events are returned. */ bind(sequence?, func?, add?): Promise<any> bind$({ sequence, func, add }: { sequence?, func?, add?}): Promise<any> /** * Unbind for this widget for event SEQUENCE the * function identified with FUNCID. */ unbind(sequence, funcid?): Promise<any> unbind$({ sequence, funcid }: { sequence, funcid?}): Promise<any> /** * Bind to all widgets at an event SEQUENCE a call to function FUNC. * An additional boolean parameter ADD specifies whether FUNC will * be called additionally to the other bound function or whether * it will replace the previous function. See bind for the return value. */ bind_all(sequence?, func?, add?): Promise<any> bind_all$({ sequence, func, add }: { sequence?, func?, add?}): Promise<any> /** * Unbind for all widgets for event SEQUENCE all functions. */ unbind_all(sequence): Promise<any> unbind_all$({ sequence }): Promise<any> /** * Bind to widgets with bindtag CLASSNAME at event * SEQUENCE a call of function FUNC. An additional * boolean parameter ADD specifies whether FUNC will be * called additionally to the other bound function or * whether it will replace the previous function. See bind for * the return value. */ bind_class(className, sequence?, func?, add?): Promise<any> bind_class$({ className, sequence, func, add }: { className, sequence?, func?, add?}): Promise<any> /** * Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE * all functions. */ unbind_class(className, sequence): Promise<any> unbind_class$({ className, sequence }): Promise<any> /** * Call the mainloop of Tk. */ mainloop(n?): Promise<any> mainloop$({ n }: { n?}): Promise<any> /** * Quit the Tcl interpreter. All widgets will be destroyed. */ quit(): Promise<any> quit$($: {}): Promise<any> /** * Return the Tkinter instance of a widget identified by * its Tcl name NAME. */ nametowidget(name): Promise<any> nametowidget$({ name }): Promise<any> /** * Configure resources of a widget. * * The values for resources are specified as keyword * arguments. To get an overview about * the allowed keyword arguments call the method keys. * */ configure(cnf?): Promise<any> configure$({ cnf }: { cnf?}): Promise<any> /** * Return the resource value for a KEY given as string. */ cget(key): Promise<any> cget$({ key }): Promise<any> /** * Return a list of all resource names of this widget. */ keys(): Promise<any> keys$($: {}): Promise<any> /** * Set or get the status for propagation of geometry information. * * A boolean argument specifies whether the geometry information * of the slaves will determine the size of this widget. If no argument * is given the current setting will be returned. * */ pack_propagate(flag?): Promise<any> pack_propagate$({ flag }: { flag?}): Promise<any> /** * Return a list of all slaves of this widget * in its packing order. */ pack_slaves(): Promise<any> pack_slaves$($: {}): Promise<any> /** * Return a list of all slaves of this widget * in its packing order. */ place_slaves(): Promise<any> place_slaves$($: {}): Promise<any> /** * The anchor value controls how to place the grid within the * master when no row/column has any weight. * * The default anchor is nw. */ grid_anchor(anchor?): Promise<any> grid_anchor$({ anchor }: { anchor?}): Promise<any> /** * Return a tuple of integer coordinates for the bounding * box of this widget controlled by the geometry manager grid. * * If COLUMN, ROW is given the bounding box applies from * the cell with row and column 0 to the specified * cell. If COL2 and ROW2 are given the bounding box * starts at that cell. * * The returned integers specify the offset of the upper left * corner in the master widget and the width and height. * */ grid_bbox(column?, row?, col2?, row2?): Promise<any> grid_bbox$({ column, row, col2, row2 }: { column?, row?, col2?, row2?}): Promise<any> /** * Configure column INDEX of a grid. * * Valid resources are minsize (minimum size of the column), * weight (how much does additional space propagate to this column) * and pad (how much space to let additionally). */ grid_columnconfigure(index, cnf?): Promise<any> grid_columnconfigure$({ index, cnf }: { index, cnf?}): Promise<any> /** * Return a tuple of column and row which identify the cell * at which the pixel at position X and Y inside the master * widget is located. */ grid_location(x, y): Promise<any> grid_location$({ x, y }): Promise<any> /** * Set or get the status for propagation of geometry information. * * A boolean argument specifies whether the geometry information * of the slaves will determine the size of this widget. If no argument * is given, the current setting will be returned. * */ grid_propagate(flag?): Promise<any> grid_propagate$({ flag }: { flag?}): Promise<any> /** * Configure row INDEX of a grid. * * Valid resources are minsize (minimum size of the row), * weight (how much does additional space propagate to this row) * and pad (how much space to let additionally). */ grid_rowconfigure(index, cnf?): Promise<any> grid_rowconfigure$({ index, cnf }: { index, cnf?}): Promise<any> /** * Return a tuple of the number of column and rows in the grid. */ grid_size(): Promise<any> grid_size$($: {}): Promise<any> /** * Return a list of all slaves of this widget * in its packing order. */ grid_slaves(row?, column?): Promise<any> grid_slaves$({ row, column }: { row?, column?}): Promise<any> /** * Bind a virtual event VIRTUAL (of the form <<Name>>) * to an event SEQUENCE such that the virtual event is triggered * whenever SEQUENCE occurs. */ event_add(virtual): Promise<any> event_add$({ virtual }): Promise<any> /** * Unbind a virtual event VIRTUAL from SEQUENCE. */ event_delete(virtual): Promise<any> event_delete$({ virtual }): Promise<any> /** * Generate an event SEQUENCE. Additional * keyword arguments specify parameter of the event * (e.g. x, y, rootx, rooty). */ event_generate(sequence): Promise<any> event_generate$({ sequence }): Promise<any> /** * Return a list of all virtual events or the information * about the SEQUENCE bound to the virtual event VIRTUAL. */ event_info(virtual?): Promise<any> event_info$({ virtual }: { virtual?}): Promise<any> /** * Return a list of all existing image names. */ image_names(): Promise<any> image_names$($: {}): Promise<any> /** * Return a list of all available image types (e.g. photo bitmap). */ image_types(): Promise<any> image_types$($: {}): Promise<any> waitvar focus lift register config propagate slaves anchor bbox columnconfigure rowconfigure size } /** * Internal class. Stores function to call when some user * defined Tcl function is called e.g. after an event occurred. */ /** * Store FUNC, SUBST and WIDGET as members. */ function CallWrapper(func, subst, widget): Promise<ICallWrapper> function CallWrapper$({ func, subst, widget }): Promise<ICallWrapper> interface ICallWrapper { } /** * Mix-in class for querying and changing the horizontal position * of a widget's window. */ interface IXView { /** * Query and change the horizontal position of the view. */ xview(): Promise<any> xview$($: {}): Promise<any> /** * Adjusts the view in the window so that FRACTION of the * total width of the canvas is off-screen to the left. */ xview_moveto(fraction): Promise<any> xview_moveto$({ fraction }): Promise<any> /** * Shift the x-view according to NUMBER which is measured in "units" * or "pages" (WHAT). */ xview_scroll(number, what): Promise<any> xview_scroll$({ number, what }): Promise<any> } /** * Mix-in class for querying and changing the vertical position * of a widget's window. */ interface IYView { /** * Query and change the vertical position of the view. */ yview(): Promise<any> yview$($: {}): Promise<any> /** * Adjusts the view in the window so that FRACTION of the * total height of the canvas is off-screen to the top. */ yview_moveto(fraction): Promise<any> yview_moveto$({ fraction }): Promise<any> /** * Shift the y-view according to NUMBER which is measured in * "units" or "pages" (WHAT). */ yview_scroll(number, what): Promise<any> yview_scroll$({ number, what }): Promise<any> } /** * Provides functions for the communication with the window manager. */ interface IWm { /** * Instruct the window manager to set the aspect ratio (width/height) * of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple * of the actual values if no argument is given. */ wm_aspect(minNumer?, minDenom?, maxNumer?, maxDenom?): Promise<any> wm_aspect$({ minNumer, minDenom, maxNumer, maxDenom }: { minNumer?, minDenom?, maxNumer?, maxDenom?}): Promise<any> /** * This subcommand returns or sets platform specific attributes * * The first form returns a list of the platform specific flags and * their values. The second form returns the value for the specific * option. The third form sets one or more of the values. The values * are as follows: * * On Windows, -disabled gets or sets whether the window is in a * disabled state. -toolwindow gets or sets the style of the window * to toolwindow (as defined in the MSDN). -topmost gets or sets * whether this is a topmost window (displays above all other * windows). * * On Macintosh, XXXXX * * On Unix, there are currently no special attribute values. * */ wm_attributes(): Promise<any> wm_attributes$($: {}): Promise<any> /** * Store NAME in WM_CLIENT_MACHINE property of this widget. Return * current value. */ wm_client(name?): Promise<any> wm_client$({ name }: { name?}): Promise<any> /** * Store list of window names (WLIST) into WM_COLORMAPWINDOWS property * of this widget. This list contains windows whose colormaps differ from their * parents. Return current list of widgets if WLIST is empty. */ wm_colormapwindows(): Promise<any> wm_colormapwindows$($: {}): Promise<any> /** * Store VALUE in WM_COMMAND property. It is the command * which shall be used to invoke the application. Return current * command if VALUE is None. */ wm_command(value?): Promise<any> wm_command$({ value }: { value?}): Promise<any> /** * Deiconify this widget. If it was never mapped it will not be mapped. * On Windows it will raise this widget and give it the focus. */ wm_deiconify(): Promise<any> wm_deiconify$($: {}): Promise<any> /** * Set focus model to MODEL. "active" means that this widget will claim * the focus itself, "passive" means that the window manager shall give * the focus. Return current focus model if MODEL is None. */ wm_focusmodel(model?): Promise<any> wm_focusmodel$({ model }: { model?}): Promise<any> /** * The window will be unmapped from the screen and will no longer * be managed by wm. toplevel windows will be treated like frame * windows once they are no longer managed by wm, however, the menu * option configuration will be remembered and the menus will return * once the widget is managed again. */ wm_forget(window): Promise<any> wm_forget$({ window }): Promise<any> /** * Return identifier for decorative frame of this widget if present. */ wm_frame(): Promise<any> wm_frame$($: {}): Promise<any> /** * Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return * current value if None is given. */ wm_geometry(newGeometry?): Promise<any> wm_geometry$({ newGeometry }: { newGeometry?}): Promise<any> /** * Instruct the window manager that this widget shall only be * resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and * height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the * number of grid units requested in Tk_GeometryRequest. */ wm_grid(baseWidth?, baseHeight?, widthInc?, heightInc?): Promise<any> wm_grid$({ baseWidth, baseHeight, widthInc, heightInc }: { baseWidth?, baseHeight?, widthInc?, heightInc?}): Promise<any> /** * Set the group leader widgets for related widgets to PATHNAME. Return * the group leader of this widget if None is given. */ wm_group(pathName?): Promise<any> wm_group$({ pathName }: { pathName?}): Promise<any> /** * Set bitmap for the iconified widget to BITMAP. Return * the bitmap if None is given. * * Under Windows, the DEFAULT parameter can be used to set the icon * for the widget and any descendents that don't have an icon set * explicitly. DEFAULT can be the relative path to a .ico file * (example: root.iconbitmap(default='myicon.ico') ). See Tk * documentation for more information. */ wm_iconbitmap(bitmap?, def?): Promise<any> wm_iconbitmap$({ bitmap, def }: { bitmap?, def?}): Promise<any> /** * Display widget as icon. */ wm_iconify(): Promise<any> wm_iconify$($: {}): Promise<any> /** * Set mask for the icon bitmap of this widget. Return the * mask if None is given. */ wm_iconmask(bitmap?): Promise<any> wm_iconmask$({ bitmap }: { bitmap?}): Promise<any> /** * Set the name of the icon for this widget. Return the name if * None is given. */ wm_iconname(newName?): Promise<any> wm_iconname$({ newName }: { newName?}): Promise<any> /** * Sets the titlebar icon for this window based on the named photo * images passed through args. If default is True, this is applied to * all future created toplevels as well. * * The data in the images is taken as a snapshot at the time of * invocation. If the images are later changed, this is not reflected * to the titlebar icons. Multiple images are accepted to allow * different images sizes to be provided. The window manager may scale * provided icons to an appropriate size. * * On Windows, the images are packed into a Windows icon structure. * This will override an icon specified to wm_iconbitmap, and vice * versa. * * On X, the images are arranged into the _NET_WM_ICON X property, * which most modern window managers support. An icon specified by * wm_iconbitmap may exist simultaneously. * * On Macintosh, this currently does nothing. */ wm_iconphoto(def?: boolean): Promise<any> wm_iconphoto$({ def }: { def?}): Promise<any> /** * Set the position of the icon of this widget to X and Y. Return * a tuple of the current values of X and X if None is given. */ wm_iconposition(x?, y?): Promise<any> wm_iconposition$({ x, y }: { x?, y?}): Promise<any> /** * Set widget PATHNAME to be displayed instead of icon. Return the current * value if None is given. */ wm_iconwindow(pathName?): Promise<any> wm_iconwindow$({ pathName }: { pathName?}): Promise<any> /** * The widget specified will become a stand alone top-level window. * The window will be decorated with the window managers title bar, * etc. */ wm_manage(widget): Promise<any> wm_manage$({ widget }): Promise<any> /** * Set max WIDTH and HEIGHT for this widget. If the window is gridded * the values are given in grid units. Return the current values if None * is given. */ wm_maxsize(width?, height?): Promise<any> wm_maxsize$({ width, height }: { width?, height?}): Promise<any> /** * Set min WIDTH and HEIGHT for this widget. If the window is gridded * the values are given in grid units. Return the current values if None * is given. */ wm_minsize(width?, height?): Promise<any> wm_minsize$({ width, height }: { width?, height?}): Promise<any> /** * Instruct the window manager to ignore this widget * if BOOLEAN is given with 1. Return the current value if None * is given. */ wm_overrideredirect(boolean?): Promise<any> wm_overrideredirect$({ boolean }: { boolean?}): Promise<any> /** * Instruct the window manager that the position of this widget shall * be defined by the user if WHO is "user", and by its own policy if WHO is * "program". */ wm_positionfrom(who?): Promise<any> wm_positionfrom$({ who }: { who?}): Promise<any> /** * Bind function FUNC to command NAME for this widget. * Return the function bound to NAME if None is given. NAME could be * e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW". */ wm_protocol(name?, func?): Promise<any> wm_protocol$({ name, func }: { name?, func?}): Promise<any> /** * Instruct the window manager whether this width can be resized * in WIDTH or HEIGHT. Both values are boolean values. */ wm_resizable(width?, height?): Promise<any> wm_resizable$({ width, height }: { width?, height?}): Promise<any> /** * Instruct the window manager that the size of this widget shall * be defined by the user if WHO is "user", and by its own policy if WHO is * "program". */ wm_sizefrom(who?): Promise<any> wm_sizefrom$({ who }: { who?}): Promise<any> /** * Query or set the state of this widget as one of normal, icon, * iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only). */ wm_state(newstate?): Promise<any> wm_state$({ newstate }: { newstate?}): Promise<any> /** * Set the title of this widget. */ wm_title(string?): Promise<any> wm_title$({ string }: { string?}): Promise<any> /** * Instruct the window manager that this widget is transient * with regard to widget MASTER. */ wm_transient(master?): Promise<any> wm_transient$({ master }: { master?}): Promise<any> /** * Withdraw this widget from the screen such that it is unmapped * and forgotten by the window manager. Re-draw it with wm_deiconify. */ wm_withdraw(): Promise<any> wm_withdraw$($: {}): Promise<any> aspect attributes client colormapwindows command deiconify focusmodel forget frame geometry grid group iconbitmap iconify iconmask iconname iconphoto iconposition iconwindow manage maxsize minsize overrideredirect positionfrom protocol resizable sizefrom state title transient withdraw } /** * Toplevel widget of Tk which represents mostly the main window * of an application. It has an associated Tcl interpreter. */ /** * Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will * be created. BASENAME will be used for the identification of the profile file (see * readprofile). * It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME * is the name of the widget class. */ function Tk(screenName?, baseName?, className?, useTk?: boolean, sync?: boolean, use?): Promise<ITk> function Tk$({ screenName, baseName, className, useTk, sync, use }: { screenName?, baseName?, className?, useTk?, sync?, use?}): Promise<ITk> interface ITk extends IMisc, IWm { loadtk(): Promise<any> loadtk$($: {}): Promise<any> /** * Destroy this and all descendants widgets. This will * end the application of this Tcl interpreter. */ destroy(): Promise<any> destroy$($: {}): Promise<any> /** * Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into * the Tcl Interpreter and calls exec on the contents of BASENAME.py and * CLASSNAME.py if such a file exists in the home directory. */ readprofile(baseName, className): Promise<any> readprofile$({ baseName, className }): Promise<any> /** * Report callback exception on sys.stderr. * * Applications may want to override this internal function, and * should when sys.stderr is None. */ report_callback_exception(exc, val, tb): Promise<any> report_callback_exception$({ exc, val, tb }): Promise<any> } /** * Geometry manager Pack. * * Base class to use the methods pack_* in every widget. */ interface IPack { /** * Pack a widget in the parent widget. Use as options: * after=widget - pack it after you have packed widget * anchor=NSEW (or subset) - position widget according to * given direction * before=widget - pack it before you will pack widget * expand=bool - expand widget if parent size grows * fill=NONE or X or Y or BOTH - fill widget if widget grows * in=master - use master to contain this widget * in_=master - see 'in' option description * ipadx=amount - add internal padding in x direction * ipady=amount - add internal padding in y direction * padx=amount - add padding in x direction * pady=amount - add padding in y direction * side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget. * */ pack_configure(cnf?): Promise<any> pack_configure$({ cnf }: { cnf?}): Promise<any> /** * Unmap this widget and do not use it for the packing order. */ pack_forget(): Promise<any> pack_forget$($: {}): Promise<any> /** * Return information about the packing options * for this widget. */ pack_info(): Promise<any> pack_info$($: {}): Promise<any> pack info } /** * Geometry manager Place. * * Base class to use the methods place_* in every widget. */ interface IPlace { /** * Place a widget in the parent widget. Use as options: * in=master - master relative to which the widget is placed * in_=master - see 'in' option description * x=amount - locate anchor of this widget at position x of master * y=amount - locate anchor of this widget at position y of master * relx=amount - locate anchor of this widget between 0.0 and 1.0 * relative to width of master (1.0 is right edge) * rely=amount - locate anchor of this widget between 0.0 and 1.0 * relative to height of master (1.0 is bottom edge) * anchor=NSEW (or subset) - position anchor according to given direction * width=amount - width of this widget in pixel * height=amount - height of this widget in pixel * relwidth=amount - width of this widget between 0.0 and 1.0 * relative to width of master (1.0 is the same width * as the master) * relheight=amount - height of this widget between 0.0 and 1.0 * relative to height of master (1.0 is the same * height as the master) * bordermode="inside" or "outside" - whether to take border width of * master widget into account * */ place_configure(cnf?): Promise<any> place_configure$({ cnf }: { cnf?}): Promise<any> /** * Unmap this widget. */ place_forget(): Promise<any> place_forget$($: {}): Promise<any> /** * Return information about the placing options * for this widget. */ place_info(): Promise<any> place_info$($: {}): Promise<any> place } /** * Geometry manager Grid. * * Base class to use the methods grid_* in every widget. */ interface IGrid { /** * Position a widget in the parent widget in a grid. Use as options: * column=number - use cell identified with given column (starting with 0) * columnspan=number - this widget will span several columns * in=master - use master to contain this widget * in_=master - see 'in' option description * ipadx=amount - add internal padding in x direction * ipady=amount - add internal padding in y direction * padx=amount - add padding in x direction * pady=amount - add padding in y direction * row=number - use cell identified with given row (starting with 0) * rowspan=number - this widget will span several rows * sticky=NSEW - if cell is larger on which sides will this * widget stick to the cell boundary * */ grid_configure(cnf?): Promise<any> grid_configure$({ cnf }: { cnf?}): Promise<any> /** * Unmap this widget. */ grid_forget(): Promise<any> grid_forget$($: {}): Promise<any> /** * Unmap this widget but remember the grid options. */ grid_remove(): Promise<any> grid_remove$($: {}): Promise<any> /** * Return information about the options * for positioning this widget in a grid. */ grid_info(): Promise<any> grid_info$($: {}): Promise<any> location } /** * Internal class. */ /** * Construct a widget with the parent widget MASTER, a name WIDGETNAME * and appropriate options. */ function BaseWidget(master, widgetName, cnf?, kw?, extra?): Promise<IBaseWidget> function BaseWidget$({ master, widgetName, cnf, kw, extra }: { master, widgetName, cnf?, kw?, extra?}): Promise<IBaseWidget> interface IBaseWidget extends IMisc { /** * Destroy this and all descendants widgets. */ destroy(): Promise<any> destroy$($: {}): Promise<any> } /** * Internal class. * * Base class for a widget which can be positioned with the geometry managers * Pack, Place or Grid. */ interface IWidget extends IBaseWidget, IPack, IPlace, IGrid { } /** * Toplevel widget, e.g. for dialogs. */ /** * Construct a toplevel widget with the parent MASTER. * * Valid resource names: background, bd, bg, borderwidth, class, * colormap, container, cursor, height, highlightbackground, * highlightcolor, highlightthickness, menu, relief, screen, takefocus, * use, visual, width. */ function Toplevel(master?, cnf?): Promise<IToplevel> function Toplevel$({ master, cnf }: { master?, cnf?}): Promise<IToplevel> interface IToplevel extends IBaseWidget, IWm { } /** * Button widget. */ /** * Construct a button widget with the parent MASTER. * * STANDARD OPTIONS * * activebackground, activeforeground, anchor, * background, bitmap, borderwidth, cursor, * disabledforeground, font, foreground * highlightbackground, highlightcolor, * highlightthickness, image, justify, * padx, pady, relief, repeatdelay, * repeatinterval, takefocus, text, * textvariable, underline, wraplength * * WIDGET-SPECIFIC OPTIONS * * command, compound, default, height, * overrelief, state, width * */ function Button(master?, cnf?): Promise<IButton> function Button$({ master, cnf }: { master?, cnf?}): Promise<IButton> interface IButton extends IWidget { /** * Flash the button. * * This is accomplished by redisplaying * the button several times, alternating between active and * normal colors. At the end of the flash the button is left * in the same normal/active state as when the command was * invoked. This command is ignored if the button's state is * disabled. * */ flash(): Promise<any> flash$($: {}): Promise<any> /** * Invoke the command associated with the button. * * The return value is the return value from the command, * or an empty string if there is no command associated with * the button. This command is ignored if the button's state * is disabled. * */ invoke(): Promise<any> invoke$($: {}): Promise<any> } /** * Canvas widget to display graphical elements like lines or text. */ /** * Construct a canvas widget with the parent MASTER. * * Valid resource names: background, bd, bg, borderwidth, closeenough, * confine, cursor, height, highlightbackground, highlightcolor, * highlightthickness, insertbackground, insertborderwidth, * insertofftime, insertontime, insertwidth, offset, relief, * scrollregion, selectbackground, selectborderwidth, selectforeground, * state, takefocus, width, xscrollcommand, xscrollincrement, * yscrollcommand, yscrollincrement. */ function Canvas(master?, cnf?): Promise<ICanvas> function Canvas$({ master, cnf }: { master?, cnf?}): Promise<ICanvas> interface ICanvas extends IWidget, IXView, IYView { /** * Internal function. */ addtag(): Promise<any> addtag$($: {}): Promise<any> /** * Add tag NEWTAG to all items above TAGORID. */ addtag_above(newtag, tagOrId): Promise<any> addtag_above$({ newtag, tagOrId }): Promise<any> /** * Add tag NEWTAG to all items. */ addtag_all(newtag): Promise<any> addtag_all$({ newtag }): Promise<any> /** * Add tag NEWTAG to all items below TAGORID. */ addtag_below(newtag, tagOrId): Promise<any> addtag_below$({ newtag, tagOrId }): Promise<any> /** * Add tag NEWTAG to item which is closest to pixel at X, Y. * If several match take the top-most. * All items closer than HALO are considered overlapping (all are * closests). If START is specified the next below this tag is taken. */ addtag_closest(newtag, x, y, halo?, start?): Promise<any> addtag_closest$({ newtag, x, y, halo, start }: { newtag, x, y, halo?, start?}): Promise<any> /** * Add tag NEWTAG to all items in the rectangle defined * by X1,Y1,X2,Y2. */ addtag_enclosed(newtag, x1, y1, x2, y2): Promise<any> addtag_enclosed$({ newtag, x1, y1, x2, y2 }): Promise<any> /** * Add tag NEWTAG to all items which overlap the rectangle * defined by X1,Y1,X2,Y2. */ addtag_overlapping(newtag, x1, y1, x2, y2): Promise<any> addtag_overlapping$({ newtag, x1, y1, x2, y2 }): Promise<any> /** * Add tag NEWTAG to all items with TAGORID. */ addtag_withtag(newtag, tagOrId): Promise<any> addtag_withtag$({ newtag, tagOrId }): Promise<any> /** * Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle * which encloses all items with tags specified as arguments. */ bbox(): Promise<any> bbox$($: {}): Promise<any> /** * Unbind for all items with TAGORID for event SEQUENCE the * function identified with FUNCID. */ tag_unbind(tagOrId, sequence, funcid?): Promise<any> tag_unbind$({ tagOrId, sequence, funcid }: { tagOrId, sequence, funcid?}): Promise<any> /** * Bind to all items with TAGORID at event SEQUENCE a call to function FUNC. * * An additional boolean parameter ADD specifies whether FUNC will be * called additionally to the other bound function or whether it will * replace the previous function. See bind for the return value. */ tag_bind(tagOrId, sequence?, func?, add?): Promise<any> tag_bind$({ tagOrId, sequence, func, add }: { tagOrId, sequence?, func?, add?}): Promise<any> /** * Return the canvas x coordinate of pixel position SCREENX rounded * to nearest multiple of GRIDSPACING units. */ canvasx(screenx, gridspacing?): Promise<any> canvasx$({ screenx, gridspacing }: { screenx, gridspacing?}): Promise<any> /** * Return the canvas y coordinate of pixel position SCREENY rounded * to nearest multiple of GRIDSPACING units. */ canvasy(screeny, gridspacing?): Promise<any> canvasy$({ screeny, gridspacing }: { screeny, gridspacing?}): Promise<any> /** * Return a list of coordinates for the item given in ARGS. */ coords(): Promise<any> coords$($: {}): Promise<any> /** * Create arc shaped region with coordinates x1,y1,x2,y2. */ create_arc(): Promise<any> create_arc$($: {}): Promise<any> /** * Create bitmap with coordinates x1,y1. */ create_bitmap(): Promise<any> create_bitmap$($: {}): Promise<any> /** * Create image item with coordinates x1,y1. */ create_image(): Promise<any> create_image$($: {}): Promise<any> /** * Create line with coordinates x1,y1,...,xn,yn. */ create_line(): Promise<any> create_line$($: {}): Promise<any> /** * Create oval with coordinates x1,y1,x2,y2. */ create_oval(): Promise<any> create_oval$($: {}): Promise<any> /** * Create polygon with coordinates x1,y1,...,xn,yn. */ create_polygon(): Promise<any> create_polygon$($: {}): Promise<any> /** * Create rectangle with coordinates x1,y1,x2,y2. */ create_rectangle(): Promise<any> create_rectangle$($: {}): Promise<any> /** * Create text with coordinates x1,y1. */ create_text(): Promise<any> create_text$($: {}): Promise<any> /** * Create window with coordinates x1,y1,x2,y2. */ create_window(): Promise<any> create_window$($: {}): Promise<any> /** * Delete characters of text items identified by tag or id in ARGS (possibly * several times) from FIRST to LAST character (including). */ dchars(): Promise<any> dchars$($: {}): Promise<any> /** * Delete items identified by all tag or ids contained in ARGS. */ delete(): Promise<any> delete$($: {}): Promise<any> /** * Delete tag or id given as last arguments in ARGS from items * identified by first argument in ARGS. */ dtag(): Promise<any> dtag$($: {}): Promise<any> /** * Internal function. */ find(): Promise<any> find$($: {}): Promise<any> /** * Return items above TAGORID. */ find_above(tagOrId): Promise<any> find_above$({ tagOrId }): Promise<any> /** * Return all items. */ find_all(): Promise<any> find_all$($: {}): Promise<any> /** * Return all items below TAGORID. */ find_below(tagOrId): Promise<any> find_below$({ tagOrId }): Promise<any> /** * Return item which is closest to pixel at X, Y. * If several match take the top-most. * All items closer than HALO are considered overlapping (all are * closest). If START is specified the next below this tag is taken. */ find_closest(x, y, halo?, start?): Promise<any> find_closest$({ x, y, halo, start }: { x, y, halo?, start?}): Promise<any> /** * Return all items in rectangle defined * by X1,Y1,X2,Y2. */ find_enclosed(x1, y1, x2, y2): Promise<any> find_enclosed$({ x1, y1, x2, y2 }): Promise<any> /** * Return all items which overlap the rectangle * defined by X1,Y1,X2,Y2. */ find_overlapping(x1, y1, x2, y2): Promise<any> find_overlapping$({ x1, y1, x2, y2 }): Promise<any> /** * Return all items with TAGORID. */ find_withtag(tagOrId): Promise<any> find_withtag$({ tagOrId }): Promise<any> /** * Set focus to the first item specified in ARGS. */ focus(): Promise<any> focus$($: {}): Promise<any> /** * Return tags associated with the first item specified in ARGS. */ gettags(): Promise<any> gettags$($: {}): Promise<any> /** * Set cursor at position POS in the item identified by TAGORID. * In ARGS TAGORID must be first. */ icursor(): Promise<any> icursor$($: {}): Promise<any> /** * Return position of cursor as integer in item specified in ARGS. */ index(): Promise<any> index$($: {}): Promise<any> /** * Insert TEXT in item TAGORID at position POS. ARGS must * be TAGORID POS TEXT. */ insert(): Promise<any> insert$($: {}): Promise<any> /** * Return the resource value for an OPTION for item TAGORID. */ itemcget(tagOrId, option): Promise<any> itemcget$({ tagOrId, option }): Promise<any> /** * Configure resources of an item TAGORID. * * The values for resources are specified as keyword * arguments. To get an overview about * the allowed keyword arguments call the method without arguments. * */ itemconfigure(tagOrId, cnf?): Promise<any> itemconfigure$({ tagOrId, cnf }: { tagOrId, cnf?}): Promise<any> /** * Lower an item TAGORID given in ARGS * (optional below another item). */ tag_lower(): Promise<any> tag_lower$($: {}): Promise<any> /** * Move an item TAGORID given in ARGS. */ move(): Promise<any> move$($: {}): Promise<any> /** * Move the items given by TAGORID in the canvas coordinate * space so that the first coordinate pair of the bottommost * item with tag TAGORID is located at position (X,Y). * X and Y may be the empty string, in which case the * corresponding coordinate will be unchanged. All items matching * TAGORID remain in the same positions relative to each other. */ moveto(tagOrId, x?, y?): Promise<any> moveto$({ tagOrId, x, y }: { tagOrId, x?, y?}): Promise<any> /** * Print the contents of the canvas to a postscript * file. Valid options: colormap, colormode, file, fontmap, * height, pageanchor, pageheight, pagewidth, pagex, pagey, * rotate, width, x, y. */ postscript(cnf?): Promise<any> postscript$({ cnf }: { cnf?}): Promise<any> /** * Raise an item TAGORID given in ARGS * (optional above another item). */ tag_raise(): Promise<any> tag_raise$($: {}): Promise<any> /** * Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE. */ scale(): Promise<any> scale$($: {}): Promise<any> /** * Remember the current X, Y coordinates. */ scan_mark(x, y): Promise<any> scan_mark$({ x, y }): Promise<any> /** * Adjust the view of the canvas to GAIN times the * difference between X and Y and the coordinates given in * scan_mark. */ scan_dragto(x, y, gain?): Promise<any> scan_dragto$({ x, y, gain }: { x, y, gain?}): Promise<any> /** * Adjust the end of the selection near the cursor of an item TAGORID to index. */ select_adjust(tagOrId, index): Promise<any> select_adjust$({ tagOrId, index }): Promise<any> /** * Clear the selection if it is in this widget. */ select_clear(): Promise<any> select_clear$($: {}): Promise<any> /** * Set the fixed end of a selection in item TAGORID to INDEX. */ select_from(tagOrId, index): Promise<any> select_from$({ tagOrId, index }): Promise<any> /** * Return the item which has the selection. */ select_item(): Promise<any> select_item$($: {}): Promise<any> /** * Set the variable end of a selection in item TAGORID to INDEX. */ select_to(tagOrId, index): Promise<any> select_to$({ tagOrId, index }): Promise<any> /** * Return the type of the item TAGORID. */ type(tagOrId): Promise<any> type$({ tagOrId }): Promise<any> itemconfig } /** * Checkbutton widget which is either in on- or off-state. */ /** * Construct a checkbutton widget with the parent MASTER. * * Valid resource names: activebackground, activeforeground, anchor, * background, bd, bg, bitmap, borderwidth, command, cursor, * disabledforeground, fg, font, foreground, height, * highlightbackground, highlightcolor, highlightthickness, image, * indicatoron, justify, offvalue, onvalue, padx, pady, relief, * selectcolor, selectimage, state, takefocus, text, textvariable, * underline, variable, width, wraplength. */ function Checkbutton(master?, cnf?): Promise<ICheckbutton> function Checkbutton$({ master, cnf }: { master?, cnf?}): Promise<ICheckbutton> interface ICheckbutton extends IWidget { /** * Put the button in off-state. */ deselect(): Promise<any> deselect$($: {}): Promise<any> /** * Flash the button. */ flash(): Promise<any> flash$($: {}): Promise<any> /** * Toggle the button and invoke a command if given as resource. */ invoke(): Promise<any> invoke$($: {}): Promise<any> /** * Put the button in on-state. */ select(): Promise<any> select$($: {}): Promise<any> /** * Toggle the button. */ toggle(): Promise<any> toggle$($: {}): Promise<any> } /** * Entry widget which allows displaying simple text. */ /** * Construct an entry widget with the parent MASTER. * * Valid resource names: background, bd, bg, borderwidth, cursor, * exportselection, fg, font, foreground, highlightbackground, * highlightcolor, highlightthickness, insertbackground, * insertborderwidth, insertofftime, insertontime, insertwidth, * invalidcommand, invcmd, justify, relief, selectbackground, * selectborderwidth, selectforeground, show, state, takefocus, * textvariable, validate, validatecommand, vcmd, width, * xscrollcommand. */ function Entry(master?, cnf?): Promise<IEntry> function Entry$({ master, cnf }: { master?, cnf?}): Promise<IEntry> interface IEntry extends IWidget, IXView { /** * Delete text from FIRST to LAST (not included). */ delete(first, last?): Promise<any> delete$({ first, last }: { first, last?}): Promise<any> /** * Return the text. */ get(): Promise<any> get$($: {}): Promise<any> /** * Insert cursor at INDEX. */ icursor(index): Promise<any> icursor$({ index }): Promise<any> /** * Return position of cursor. */ index(index): Promise<any> index$({ index }): Promise<any> /** * Insert STRING at INDEX. */ insert(index, string): Promise<any> insert$({ index, string }): Promise<any> /** * Remember the current X, Y coordinates. */ scan_mark(x): Promise<any> scan_mark$({ x }): Promise<any> /** * Adjust the view of the canvas to 10 times the * difference between X and Y and the coordinates given in * scan_mark. */ scan_dragto(x): Promise<any> scan_dragto$({ x }): Promise<any> /** * Adjust the end of the selection near the cursor to INDEX. */ selection_adjust(index): Promise<any> selection_adjust$({ index }): Promise<any> /** * Clear the selection if it is in this widget. */ selection_clear(): Promise<any> selection_clear$($: {}): Promise<any> /** * Set the fixed end of a selection to INDEX. */ selection_from(index): Promise<any> selection_from$({ index }): Promise<any> /** * Return True if there are characters selected in the entry, False * otherwise. */ selection_present(): Promise<any> selection_present$($: {}): Promise<any> /** * Set the selection from START to END (not included). */ selection_range(start, end): Promise<any> selection_range$({ start, end }): Promise<any> /** * Set the variable end of a selection to INDEX. */ selection_to(index): Promise<any> selection_to$({ index }): Promise<any> select_present select_range } /** * Frame widget which may contain other widgets and can have a 3D border. */ /** * Construct a frame widget with the parent MASTER. * * Valid resource names: background, bd, bg, borderwidth, class, * colormap, container, cursor, height, highlightbackground, * highlightcolor, highlightthickness, relief, takefocus, visual, width. */ function Frame(master?, cnf?): Promise<IFrame> function Frame$({ master, cnf }: { master?, cnf?}): Promise<IFrame> interface IFrame extends IWidget { } /** * Label widget which can display text and bitmaps. */ /** * Construct a label widget with the parent MASTER. * * STANDARD OPTIONS * * activebackground, activeforeground, anchor, * background, bitmap, borderwidth, cursor, * disabledforeground, font, foreground, * highlightbackground, highlightcolor, * highlightthickness, image, justify, * padx, pady, relief, takefocus, text, * textvariable, underline, wraplength * * WIDGET-SPECIFIC OPTIONS * * height, state, width * * */ function Label(master?, cnf?): Promise<ILabel> function Label$({ master, cnf }: { master?, cnf?}): Promise<ILabel> interface ILabel extends IWidget { } /** * Listbox widget which can display a list of strings. */ /** * Construct a listbox widget with the parent MASTER. * * Valid resource names: background, bd, bg, borderwidth, cursor, * exportselection, fg, font, foreground, height, highlightbackground, * highlightcolor, highlightthickness, relief, selectbackground, * selectborderwidth, selectforeground, selectmode, setgrid, takefocus, * width, xscrollcommand, yscrollcommand, listvariable. */ function Listbox(master?, cnf?): Promise<IListbox> function Listbox$({ master, cnf }: { master?, cnf?}): Promise<IListbox> interface IListbox extends IWidget, IXView, IYView { /** * Activate item identified by INDEX. */ activate(index): Promise<any> activate$({ index }): Promise<any> /** * Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle * which encloses the item identified by the given index. */ bbox(index): Promise<any> bbox$({ index }): Promise<any> /** * Return the indices of currently selected item. */ curselection(): Promise<any> curselection$($: {}): Promise<any> /** * Delete items from FIRST to LAST (included). */ delete(first, last?): Promise<any> delete$({ first, last }: { first, last?}): Promise<any> /** * Get list of items from FIRST to LAST (included). */ get(first, last?): Promise<any> get$({ first, last }: { first, last?}): Promise<any> /** * Return index of item identified with INDEX. */ index(index): Promise<any> index$({ index }): Promise<any> /** * Insert ELEMENTS at INDEX. */ insert(index): Promise<any> insert$({ index }): Promise<any> /** * Get index of item which is nearest to y coordinate Y. */ nearest(y): Promise<any> nearest$({ y }): Promise<any> /** * Remember the current X, Y coordinates. */ scan_mark(x, y): Promise<any> scan_mark$({ x, y }): Promise<any> /** * Adjust the view of the listbox to 10 times the * difference between X and Y and the coordinates given in * scan_mark. */ scan_dragto(x, y): Promise<any> scan_dragto$({ x, y }): Promise<any> /** * Scroll such that INDEX is visible. */ see(index): Promise<any> see$({ index }): Promise<any> /** * Set the fixed end oft the selection to INDEX. */ selection_anchor(index): Promise<any> selection_anchor$({ index }): Promise<any> /** * Clear the selection from FIRST to LAST (included). */ selection_clear(first, last?): Promise<any> selection_clear$({ first, last }: { first, last?}): Promise<any> /** * Return True if INDEX is part of the selection. */ selection_includes(index): Promise<any> selection_includes$({ index }): Promise<any> /** * Set the selection from FIRST to LAST (included) without * changing the currently selected elements. */ selection_set(first, last?): Promise<any> selection_set$({ first, last }: { first, last?}): Promise<any> /** * Return the number of elements in the listbox. */ size(): Promise<any> size$($: {}): Promise<any> /** * Return the resource value for an ITEM and an OPTION. */ itemcget(index, option): Promise<any> itemcget$({ index, option }): Promise<any> /** * Configure resources of an ITEM. * * The values for resources are specified as keyword arguments. * To get an overview about the allowed keyword arguments * call the method without arguments. * Valid resource names: background, bg, foreground, fg, * selectbackground, selectforeground. */ itemconfigure(index, cnf?): Promise<any> itemconfigure$({ index, cnf }: { index, cnf?}): Promise<any> select_anchor select_includes select_set } /** * Menu widget which allows displaying menu bars, pull-down menus and pop-up menus. */ /** * Construct menu widget with the parent MASTER. * * Valid resource names: activebackground, activeborderwidth, * activeforeground, background, bd, bg, borderwidth, cursor, * disabledforeground, fg, font, foreground, postcommand, relief, * selectcolor, takefocus, tearoff, tearoffcommand, title, type. */ function Menu(master?, cnf?): Promise<IMenu> function Menu$({ master, cnf }: { master?, cnf?}): Promise<IMenu> interface IMenu extends IWidget { /** * Post the menu at position X,Y with entry ENTRY. */ tk_popup(x, y, entry?): Promise<any> tk_popup$({ x, y, entry }: { x, y, entry?}): Promise<any> /** * Activate entry at INDEX. */ activate(index): Promise<any> activate$({ index }): Promise<any> /** * Internal function. */ add(itemType, cnf?): Promise<any> add$({ itemType, cnf }: { itemType, cnf?}): Promise<any> /** * Add hierarchical menu item. */ add_cascade(cnf?): Promise<any> add_cascade$({ cnf }: { cnf?}): Promise<any> /** * Add checkbutton menu item. */ add_checkbutton(cnf?): Promise<any> add_checkbutton$({ cnf }: { cnf?}): Promise<any> /** * Add command menu item. */ add_command(cnf?): Promise<any> add_command$({ cnf }: { cnf?}): Promise<any> /** * Addd radio menu item. */ add_radiobutton(cnf?): Promise<any> add_radiobutton$({ cnf }: { cnf?}): Promise<any> /** * Add separator. */ add_separator(cnf?): Promise<any> add_separator$({ cnf }: { cnf?}): Promise<any> /** * Internal function. */ insert(index, itemType, cnf?): Promise<any> insert$({ index, itemType, cnf }: { index, itemType, cnf?}): Promise<any> /** * Add hierarchical menu item at INDEX. */ insert_cascade(index, cnf?): Promise<any> insert_cascade$({ index, cnf }: { index, cnf?}): Promise<any> /** * Add checkbutton menu item at INDEX. */ insert_checkbutton(index, cnf?): Promise<any> insert_checkbutton$({ index, cnf }: { index, cnf?}): Promise<any> /** * Add command menu item at INDEX. */ insert_command(index, cnf?): Promise<any> insert_command$({ index, cnf }: { index, cnf?}): Promise<any> /** * Addd radio menu item at INDEX. */ insert_radiobutton(index, cnf?): Promise<any> insert_radiobutton$({ index, cnf }: { index, cnf?}): Promise<any> /** * Add separator at INDEX. */ insert_separator(index, cnf?): Promise<any> insert_separator$({ index, cnf }: { index, cnf?}): Promise<any> /** * Delete menu items between INDEX1 and INDEX2 (included). */ delete(index1, index2?): Promise<any> delete$({ index1, index2 }: { index1, index2?}): Promise<any> /** * Return the resource value of a menu item for OPTION at INDEX. */ entrycget(index, option): Promise<any> entrycget$({ index, option }): Promise<any> /** * Configure a menu item at INDEX. */ entryconfigure(index, cnf?): Promise<any> entryconfigure$({ index, cnf }: { index, cnf?}): Promise<any> /** * Return the index of a menu item identified by INDEX. */ index(index): Promise<any> index$({ index }): Promise<any> /** * Invoke a menu item identified by INDEX and execute * the associated command. */ invoke(index): Promise<any> invoke$({ index }): Promise<any> /** * Display a menu at position X,Y. */ post(x, y): Promise<any> post$({ x, y }): Promise<any> /** * Return the type of the menu item at INDEX. */ type(index): Promise<any> type$({ index }): Promise<any> /** * Unmap a menu. */ unpost(): Promise<any> unpost$($: {}): Promise<any> /** * Return the x-position of the leftmost pixel of the menu item * at INDEX. */ xposition(index): Promise<any> xposition$({ index }): Promise<any> /** * Return the y-position of the topmost pixel of the menu item at INDEX. */ yposition(index): Promise<any> yposition$({ index }): Promise<any> entryconfig } /** * Menubutton widget, obsolete since Tk8.0. */ function Menubutton(master?, cnf?): Promise<IMenubutton> function Menubutton$({ master, cnf }: { master?, cnf?}): Promise<IMenubutton> interface IMenubutton extends IWidget { } /** * Message widget to display multiline text. Obsolete since Label does it too. */ function Message(master?, cnf?): Promise<IMessage> function Message$({ master, cnf }: { master?, cnf?}): Promise<IMessage> interface IMessage extends IWidget { } /** * Radiobutton widget which shows only one of several buttons in on-state. */ /** * Construct a radiobutton widget with the parent MASTER. * * Valid resource names: activebackground, activeforeground, anchor, * background, bd, bg, bitmap, borderwidth, command, cursor, * disabledforeground, fg, font, foreground, height, * highlightbackground, highlightcolor, highlightthickness, image, * indicatoron, justify, padx, pady, relief, selectcolor, selectimage, * state, takefocus, text, textvariable, underline, value, variable, * width, wraplength. */ function Radiobutton(master?, cnf?): Promise<IRadiobutton> function Radiobutton$({ master, cnf }: { master?, cnf?}): Promise<IRadiobutton> interface IRadiobutton extends IWidget { /** * Put the button in off-state. */ deselect(): Promise<any> deselect$($: {}): Promise<any> /** * Flash the button. */ flash(): Promise<any> flash$($: {}): Promise<any> /** * Toggle the button and invoke a command if given as resource. */ invoke(): Promise<any> invoke$($: {}): Promise<any> /** * Put the button in on-state. */ select(): Promise<any> select$($: {}): Promise<any> } /** * Scale widget which can display a numerical scale. */ /** * Construct a scale widget with the parent MASTER. * * Valid resource names: activebackground, background, bigincrement, bd, * bg, borderwidth, command, cursor, digits, fg, font, foreground, from, * highlightbackground, highlightcolor, highlightthickness, label, * length, orient, relief, repeatdelay, repeatinterval, resolution, * showvalue, sliderlength, sliderrelief, state, takefocus, * tickinterval, to, troughcolor, variable, width. */ function Scale(master?, cnf?): Promise<IScale> function Scale$({ master, cnf }: { master?, cnf?}): Promise<IScale> interface IScale extends IWidget { /** * Get the current value as integer or float. */ get(): Promise<any> get$($: {}): Promise<any> /** * Set the value to VALUE. */ set(value): Promise<any> set$({ value }): Promise<any> /** * Return a tuple (X,Y) of the point along the centerline of the * trough that corresponds to VALUE or the current value if None is * given. */ coords(value?): Promise<any> coords$({ value }: { value?}): Promise<any> /** * Return where the point X,Y lies. Valid return values are "slider", * "though1" and "though2". */ identify(x, y): Promise<any> identify$({ x, y }): Promise<any> } /** * Scrollbar widget which displays a slider at a certain position. */ /** * Construct a scrollbar widget with the parent MASTER. * * Valid resource names: activebackground, activerelief, * background, bd, bg, borderwidth, command, cursor, * elementborderwidth, highlightbackground, * highlightcolor, highlightthickness, jump, orient, * relief, repeatdelay, repeatinterval, takefocus, * troughcolor, width. */ function Scrollbar(master?, cnf?): Promise<IScrollbar> function Scrollbar$({ master, cnf }: { master?, cnf?}): Promise<IScrollbar> interface IScrollbar extends IWidget { /** * Marks the element indicated by index as active. * The only index values understood by this method are "arrow1", * "slider", or "arrow2". If any other value is specified then no * element of the scrollbar will be active. If index is not specified, * the method returns the name of the element that is currently active, * or None if no element is active. */ activate(index?): Promise<any> activate$({ index }: { index?}): Promise<any> /** * Return the fractional change of the scrollbar setting if it * would be moved by DELTAX or DELTAY pixels. */ delta(deltax, deltay): Promise<any> delta$({ deltax, deltay }): Promise<any> /** * Return the fractional value which corresponds to a slider * position of X,Y. */ fraction(x, y): Promise<any> fraction$({ x, y }): Promise<any> /** * Return the element under position X,Y as one of * "arrow1","slider","arrow2" or "". */ identify(x, y): Promise<any> identify$({ x, y }): Promise<any> /** * Return the current fractional values (upper and lower end) * of the slider position. */ get(): Promise<any> get$($: {}): Promise<any> /** * Set the fractional values of the slider position (upper and * lower ends as value between 0 and 1). */ set(first, last): Promise<any> set$({ first, last }): Promise<any> } /** * Text widget which can display text in various forms. */ /** * Construct a text widget with the parent MASTER. * * STANDARD OPTIONS * * background, borderwidth, cursor, * exportselection, font, foreground, * highlightbackground, highlightcolor, * highlightthickness, insertbackground, * insertborderwidth, insertofftime, * insertontime, insertwidth, padx, pady, * relief, selectbackground, * selectborderwidth, selectforeground, * setgrid, takefocus, * xscrollcommand, yscrollcommand, * * WIDGET-SPECIFIC OPTIONS * * autoseparators, height, maxundo, * spacing1, spacing2, spacing3, * state, tabs, undo, width, wrap, * * */ function Text(master?, cnf?): Promise<IText> function Text$({ master, cnf }: { master?, cnf?}): Promise<IText> interface IText extends IWidget, IXView, IYView { /** * Return a tuple of (x,y,width,height) which gives the bounding * box of the visible part of the character at the given index. */ bbox(index): Promise<any> bbox$({ index }): Promise<any> /** * Return whether between index INDEX1 and index INDEX2 the * relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=. */ compare(index1, op, index2): Promise<any> compare$({ index1, op, index2 }): Promise<any> /** * Counts the number of relevant things between the two indices. * If index1 is after index2, the result will be a negative number * (and this holds for each of the possible options). * * The actual items which are counted depends on the options given by * args. The result is a list of integers, one for the result of each * counting option given. Valid counting options are "chars", * "displaychars", "displayindices", "displaylines", "indices", * "lines", "xpixels" and "ypixels". There is an additional possible * option "update", which if given then all subsequent options ensure * that any possible out of date information is recalculated. */ count(index1, index2): Promise<any> count$({ index1, index2 }): Promise<any> /** * Turn on the internal consistency checks of the B-Tree inside the text * widget according to BOOLEAN. */ debug(boolean?): Promise<any> debug$({ boolean }: { boolean?}): Promise<any> /** * Delete the characters between INDEX1 and INDEX2 (not included). */ delete(index1, index2?): Promise<any> delete$({ index1, index2 }: { index1, index2?}): Promise<any> /** * Return tuple (x,y,width,height,baseline) giving the bounding box * and baseline position of the visible part of the line containing * the character at INDEX. */ dlineinfo(index): Promise<any> dlineinfo$({ index }): Promise<any> /** * Return the contents of the widget between index1 and index2. * * The type of contents returned in filtered based on the keyword * parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are * given and true, then the corresponding items are returned. The result * is a list of triples of the form (key, value, index). If none of the * keywords are true then 'all' is used by default. * * If the 'command' argument is given, it is called once for each element * of the list of triples, with the values of each triple serving as the * arguments to the function. In this case the list is not returned. */ dump(index1, index2?, command?): Promise<any> dump$({ index1, index2, command }: { index1, index2?, command?}): Promise<any> /** * Internal method * * This method controls the undo mechanism and * the modified flag. The exact behavior of the * command depends on the option argument that * follows the edit argument. The following forms * of the command are currently supported: * * edit_modified, edit_redo, edit_reset, edit_separator * and edit_undo * * */ edit(): Promise<any> edit$($: {}): Promise<any> /** * Get or Set the modified flag * * If arg is not specified, returns the modified * flag of the widget. The insert, delete, edit undo and * edit redo commands or the user can set or clear the * modified flag. If boolean is specified, sets the * modified flag of the widget to arg. * */ edit_modified(arg?): Promise<any> edit_modified$({ arg }: { arg?}): Promise<any> /** * Redo the last undone edit * * When the undo option is true, reapplies the last * undone edits provided no other edits were done since * then. Generates an error when the redo stack is empty. * Does nothing when the undo option is false. * */ edit_redo(): Promise<any> edit_redo$($: {}): Promise<any> /** * Clears the undo and redo stacks * */ edit_reset(): Promise<any> edit_reset$($: {}): Promise<any> /** * Inserts a separator (boundary) on the undo stack. * * Does nothing when the undo option is false * */ edit_separator(): Promise<any> edit_separator$($: {}): Promise<any> /** * Undoes the last edit action * * If the undo option is true. An edit action is defined * as all the insert and delete commands that are recorded * on the undo stack in between two separators. Generates * an error when the undo stack is empty. Does nothing * when the undo option is false * */ edit_undo(): Promise<any> edit_undo$($: {}): Promise<any> /** * Return the text from INDEX1 to INDEX2 (not included). */ get(index1, index2?): Promise<any> get$({ index1, index2 }: { index1, index2?}): Promise<any> /** * Return the value of OPTION of an embedded image at INDEX. */ image_cget(index, option): Promise<any> image_cget$({ index, option }): Promise<any> /** * Configure an embedded image at INDEX. */ image_configure(index, cnf?): Promise<any> image_configure$({ index, cnf }: { index, cnf?}): Promise<any> /** * Create an embedded image at INDEX. */ image_create(index, cnf?): Promise<any> image_create$({ index, cnf }: { index, cnf?}): Promise<any> /** * Return all names of embedded images in this widget. */ image_names(): Promise<any> image_names$($: {}): Promise<any> /** * Return the index in the form line.char for INDEX. */ index(index): Promise<any> index$({ index }): Promise<any> /** * Insert CHARS before the characters at INDEX. An additional * tag can be given in ARGS. Additional CHARS and tags can follow in ARGS. */ insert(index, chars): Promise<any> insert$({ index, chars }): Promise<any> /** * Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT). * Return the current value if None is given for DIRECTION. */ mark_gravity(markName, direction?): Promise<any> mark_gravity$({ markName, direction }: { markName, direction?}): Promise<any> /** * Return all mark names. */ mark_names(): Promise<any> mark_names$($: {}): Promise<any> /** * Set mark MARKNAME before the character at INDEX. */ mark_set(markName, index): Promise<any> mark_set$({ markName, index }): Promise<any> /** * Delete all marks in MARKNAMES. */ mark_unset(): Promise<any> mark_unset$($: {}): Promise<any> /** * Return the name of the next mark after INDEX. */ mark_next(index): Promise<any> mark_next$({ index }): Promise<any> /** * Return the name of the previous mark before INDEX. */ mark_previous(index): Promise<any> mark_previous$({ index }): Promise<any> /** * Creates a peer text widget with the given newPathName, and any * optional standard configuration options. By default the peer will * have the same start and end line as the parent widget, but * these can be overridden with the standard configuration options. */ peer_create(newPathName, cnf?): Promise<any> peer_create$({ newPathName, cnf }: { newPathName, cnf?}): Promise<any> /** * Returns a list of peers of this widget (this does not include * the widget itself). */ peer_names(): Promise<any> peer_names$($: {}): Promise<any> /** * Replaces the range of characters between index1 and index2 with * the given characters and tags specified by args. * * See the method insert for some more information about args, and the * method delete for information about the indices. */ replace(index1, index2, chars): Promise<any> replace$({ index1, index2, chars }): Promise<any> /** * Remember the current X, Y coordinates. */ scan_mark(x, y): Promise<any> scan_mark$({ x, y }): Promise<any> /** * Adjust the view of the text to 10 times the * difference between X and Y and the coordinates given in * scan_mark. */ scan_dragto(x, y): Promise<any> scan_dragto$({ x, y }): Promise<any> /** * Search PATTERN beginning from INDEX until STOPINDEX. * Return the index of the first character of a match or an * empty string. */ search(pattern, index, stopindex?, forwards?, backwards?, exact?, regexp?, nocase?, count?, elide?): Promise<any> search$({ pattern, index, stopindex, forwards, backwards, exact, regexp, nocase, count, elide }: { pattern, index, stopindex?, forwards?, backwards?, exact?, regexp?, nocase?, count?, elide?}): Promise<any> /** * Scroll such that the character at INDEX is visible. */ see(index): Promise<any> see$({ index }): Promise<any> /** * Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS. * Additional pairs of indices may follow in ARGS. */ tag_add(tagName, index1): Promise<any> tag_add$({ tagName, index1 }): Promise<any> /** * Unbind for all characters with TAGNAME for event SEQUENCE the * function identified with FUNCID. */ tag_unbind(tagName, sequence, funcid?): Promise<any> tag_unbind$({ tagName, sequence, funcid }: { tagName, sequence, funcid?}): Promise<any> /** * Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC. * * An additional boolean parameter ADD specifies whether FUNC will be * called additionally to the other bound function or whether it will * replace the previous function. See bind for the return value. */ tag_bind(tagName, sequence, func, add?): Promise<any> tag_bind$({ tagName, sequence, func, add }: { tagName, sequence, func, add?}): Promise<any> /** * Return the value of OPTION for tag TAGNAME. */ tag_cget(tagName, option): Promise<any> tag_cget$({ tagName, option }): Promise<any> /** * Configure a tag TAGNAME. */ tag_configure(tagName, cnf?): Promise<any> tag_configure$({ tagName, cnf }: { tagName, cnf?}): Promise<any> /** * Delete all tags in TAGNAMES. */ tag_delete(): Promise<any> tag_delete$($: {}): Promise<any> /** * Change the priority of tag TAGNAME such that it is lower * than the priority of BELOWTHIS. */ tag_lower(tagName, belowThis?): Promise<any> tag_lower$({ tagName, belowThis }: { tagName, belowThis?}): Promise<any> /** * Return a list of all tag names. */ tag_names(index?): Promise<any> tag_names$({ index }: { index?}): Promise<any> /** * Return a list of start and end index for the first sequence of * characters between INDEX1 and INDEX2 which all have tag TAGNAME. * The text is searched forward from INDEX1. */ tag_nextrange(tagName, index1, index2?): Promise<any> tag_nextrange$({ tagName, index1, index2 }: { tagName, index1, index2?}): Promise<any> /** * Return a list of start and end index for the first sequence of * characters between INDEX1 and INDEX2 which all have tag TAGNAME. * The text is searched backwards from INDEX1. */ tag_prevrange(tagName, index1, index2?): Promise<any> tag_prevrange$({ tagName, index1, index2 }: { tagName, index1, index2?}): Promise<any> /** * Change the priority of tag TAGNAME such that it is higher * than the priority of ABOVETHIS. */ tag_raise(tagName, aboveThis?): Promise<any> tag_raise$({ tagName, aboveThis }: { tagName, aboveThis?}): Promise<any> /** * Return a list of ranges of text which have tag TAGNAME. */ tag_ranges(tagName): Promise<any> tag_ranges$({ tagName }): Promise<any> /** * Remove tag TAGNAME from all characters between INDEX1 and INDEX2. */ tag_remove(tagName, index1, index2?): Promise<any> tag_remove$({ tagName, index1, index2 }: { tagName, index1, index2?}): Promise<any> /** * Return the value of OPTION of an embedded window at INDEX. */ window_cget(index, option): Promise<any> window_cget$({ index, option }): Promise<any> /** * Configure an embedded window at INDEX. */ window_configure(index, cnf?): Promise<any> window_configure$({ index, cnf }: { index, cnf?}): Promise<any> /** * Create a window at INDEX. */ window_create(index, cnf?): Promise<any> window_create$({ index, cnf }: { index, cnf?}): Promise<any> /** * Return all names of embedded windows in this widget. */ window_names(): Promise<any> window_names$($: {}): Promise<any> /** * Obsolete function, use see. */ yview_pickplace(): Promise<any> yview_pickplace$($: {}): Promise<any> tag_config window_config } /** * Internal class. It wraps the command in the widget OptionMenu. */ interface I_setit { } /** * OptionMenu which allows the user to select a value from a menu. */ /** * Construct an optionmenu widget with the parent MASTER, with * the resource textvariable set to VARIABLE, the initially selected * value VALUE, the other menu values VALUES and an additional * keyword argument command. */ function OptionMenu(master, variable, value): Promise<IOptionMenu> function OptionMenu$({ master, variable, value }): Promise<IOptionMenu> interface IOptionMenu extends IMenubutton { /** * Destroy this widget and the associated menu. */ destroy(): Promise<any> destroy$($: {}): Promise<any> } /** * Base class for images. */ function Image(imgtype, name?, cnf?, master?): Promise<IImage> function Image$({ imgtype, name, cnf, master }: { imgtype, name?, cnf?, master?}): Promise<IImage> interface IImage { /** * Configure the image. */ configure(): Promise<any> configure$($: {}): Promise<any> /** * Return the height of the image. */ height(): Promise<any> height$($: {}): Promise<any> /** * Return the type of the image, e.g. "photo" or "bitmap". */ type(): Promise<any> type$($: {}): Promise<any> /** * Return the width of the image. */ width(): Promise<any> width$($: {}): Promise<any> } /** * Widget which can display images in PGM, PPM, GIF, PNG format. */ /** * Create an image with NAME. * * Valid resource names: data, format, file, gamma, height, palette, * width. */ function PhotoImage(name?, cnf?, master?): Promise<IPhotoImage> function PhotoImage$({ name, cnf, master }: { name?, cnf?, master?}): Promise<IPhotoImage> interface IPhotoImage extends IImage { /** * Display a transparent image. */ blank(): Promise<any> blank$($: {}): Promise<any> /** * Return the value of OPTION. */ cget(option): Promise<any> cget$({ option }): Promise<any> /** * Return a new PhotoImage with the same image as this widget. */ copy(): Promise<any> copy$($: {}): Promise<any> /** * Return a new PhotoImage with the same image as this widget * but zoom it with a factor of x in the X direction and y in the Y * direction. If y is not given, the default value is the same as x. * */ zoom(x, y?): Promise<any> zoom$({ x, y }: { x, y?}): Promise<any> /** * Return a new PhotoImage based on the same image as this widget * but use only every Xth or Yth pixel. If y is not given, the * default value is the same as x. * */ subsample(x, y?): Promise<any> subsample$({ x, y }: { x, y?}): Promise<any> /** * Return the color (red, green, blue) of the pixel at X,Y. */ get(x, y): Promise<any> get$({ x, y }): Promise<any> /** * Put row formatted colors to image starting from * position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6)) */ put(data, to?): Promise<any> put$({ data, to }: { data, to?}): Promise<any> /** * Write image to file FILENAME in FORMAT starting from * position FROM_COORDS. */ write(filename, format?, from_coords?): Promise<any> write$({ filename, format, from_coords }: { filename, format?, from_coords?}): Promise<any> /** * Return True if the pixel at x,y is transparent. */ transparency_get(x, y): Promise<any> transparency_get$({ x, y }): Promise<any> /** * Set the transparency of the pixel at x,y. */ transparency_set(x, y, boolean): Promise<any> transparency_set$({ x, y, boolean }): Promise<any> } /** * Widget which can display images in XBM format. */ /** * Create a bitmap with NAME. * * Valid resource names: background, data, file, foreground, maskdata, maskfile. */ function BitmapImage(name?, cnf?, master?): Promise<IBitmapImage> function BitmapImage$({ name, cnf, master }: { name?, cnf?, master?}): Promise<IBitmapImage> interface IBitmapImage extends IImage { } /** * spinbox widget. */ /** * Construct a spinbox widget with the parent MASTER. * * STANDARD OPTIONS * * activebackground, background, borderwidth, * cursor, exportselection, font, foreground, * highlightbackground, highlightcolor, * highlightthickness, insertbackground, * insertborderwidth, insertofftime, * insertontime, insertwidth, justify, relief, * repeatdelay, repeatinterval, * selectbackground, selectborderwidth * selectforeground, takefocus, textvariable * xscrollcommand. * * WIDGET-SPECIFIC OPTIONS * * buttonbackground, buttoncursor, * buttondownrelief, buttonuprelief, * command, disabledbackground, * disabledforeground, format, from, * invalidcommand, increment, * readonlybackground, state, to, * validate, validatecommand values, * width, wrap, * */ function Spinbox(master?, cnf?): Promise<ISpinbox> function Spinbox$({ master, cnf }: { master?, cnf?}): Promise<ISpinbox> interface ISpinbox extends IWidget, IXView { /** * Return a tuple of X1,Y1,X2,Y2 coordinates for a * rectangle which encloses the character given by index. * * The first two elements of the list give the x and y * coordinates of the upper-left corner of the screen * area covered by the character (in pixels relative * to the widget) and the last two elements give the * width and height of the character, in pixels. The * bounding box may refer to a region outside the * visible area of the window. * */ bbox(index): Promise<any> bbox$({ index }): Promise<any> /** * Delete one or more elements of the spinbox. * * First is the index of the first character to delete, * and last is the index of the character just after * the last one to delete. If last isn't specified it * defaults to first+1, i.e. a single character is * deleted. This command returns an empty string. * */ delete(first, last?): Promise<any> delete$({ first, last }: { first, last?}): Promise<any> /** * Returns the spinbox's string */ get(): Promise<any> get$($: {}): Promise<any> /** * Alter the position of the insertion cursor. * * The insertion cursor will be displayed just before * the character given by index. Returns an empty string * */ icursor(index): Promise<any> icursor$({ index }): Promise<any> /** * Returns the name of the widget at position x, y * * Return value is one of: none, buttondown, buttonup, entry * */ identify(x, y): Promise<any> identify$({ x, y }): Promise<any> /** * Returns the numerical index corresponding to index * */ index(index): Promise<any> index$({ index }): Promise<any> /** * Insert string s at index * * Returns an empty string. * */ insert(index, s): Promise<any> insert$({ index, s }): Promise<any> /** * Causes the specified element to be invoked * * The element could be buttondown or buttonup * triggering the action associated with it. * */ invoke(element): Promise<any> invoke$({ element }): Promise<any> /** * Internal function. */ scan(): Promise<any> scan$($: {}): Promise<any> /** * Records x and the current view in the spinbox window; * * used in conjunction with later scan dragto commands. * Typically this command is associated with a mouse button * press in the widget. It returns an empty string. * */ scan_mark(x): Promise<any> scan_mark$({ x }): Promise<any> /** * Compute the difference between the given x argument * and the x argument to the last scan mark command * * It then adjusts the view left or right by 10 times the * difference in x-coordinates. This command is typically * associated with mouse motion events in the widget, to * produce the effect of dragging the spinbox at high speed * through the window. The return value is an empty string. * */ scan_dragto(x): Promise<any> scan_dragto$({ x }): Promise<any> /** * Internal function. */ selection(): Promise<any> selection$($: {}): Promise<any> /** * Locate the end of the selection nearest to the character * given by index, * * Then adjust that end of the selection to be at index * (i.e including but not going beyond index). The other * end of the selection is made the anchor point for future * select to commands. If the selection isn't currently in * the spinbox, then a new selection is created to include * the characters between index and the most recent selection * anchor point, inclusive. * */ selection_adjust(index): Promise<any> selection_adjust$({ index }): Promise<any> /** * Clear the selection * * If the selection isn't in this widget then the * command has no effect. * */ selection_clear(): Promise<any> selection_clear$($: {}): Promise<any> /** * Sets or gets the currently selected element. * * If a spinbutton element is specified, it will be * displayed depressed. * */ selection_element(element?): Promise<any> selection_element$({ element }: { element?}): Promise<any> /** * Set the fixed end of a selection to INDEX. */ selection_from(index): Promise<any> selection_from$({ index }): Promise<any> /** * Return True if there are characters selected in the spinbox, False * otherwise. */ selection_present(): Promise<any> selection_present$($: {}): Promise<any> /** * Set the selection from START to END (not included). */ selection_range(start, end): Promise<any> selection_range$({ start, end }): Promise<any> /** * Set the variable end of a selection to INDEX. */ selection_to(index): Promise<any> selection_to$({ index }): Promise<any> } /** * labelframe widget. */ /** * Construct a labelframe widget with the parent MASTER. * * STANDARD OPTIONS * * borderwidth, cursor, font, foreground, * highlightbackground, highlightcolor, * highlightthickness, padx, pady, relief, * takefocus, text * * WIDGET-SPECIFIC OPTIONS * * background, class, colormap, container, * height, labelanchor, labelwidget, * visual, width * */ function LabelFrame(master?, cnf?): Promise<ILabelFrame> function LabelFrame$({ master, cnf }: { master?, cnf?}): Promise<ILabelFrame> interface ILabelFrame extends IWidget { } /** * panedwindow widget. */ /** * Construct a panedwindow widget with the parent MASTER. * * STANDARD OPTIONS * * background, borderwidth, cursor, height, * orient, relief, width * * WIDGET-SPECIFIC OPTIONS * * handlepad, handlesize, opaqueresize, * sashcursor, sashpad, sashrelief, * sashwidth, showhandle, * */ function PanedWindow(master?, cnf?): Promise<IPanedWindow> function PanedWindow$({ master, cnf }: { master?, cnf?}): Promise<IPanedWindow> interface IPanedWindow extends IWidget { /** * Add a child widget to the panedwindow in a new pane. * * The child argument is the name of the child widget * followed by pairs of arguments that specify how to * manage the windows. The possible options and values * are the ones accepted by the paneconfigure method. * */ add(child): Promise<any> add$({ child }): Promise<any> /** * Remove the pane containing child from the panedwindow * * All geometry management options for child will be forgotten. * */ remove(child): Promise<any> remove$({ child }): Promise<any> /** * Identify the panedwindow component at point x, y * * If the point is over a sash or a sash handle, the result * is a two element list containing the index of the sash or * handle, and a word indicating whether it is over a sash * or a handle, such as {0 sash} or {2 handle}. If the point * is over any other part of the panedwindow, the result is * an empty list. * */ identify(x, y): Promise<any> identify$({ x, y }): Promise<any> /** * Internal function. */ proxy(): Promise<any> proxy$($: {}): Promise<any> /** * Return the x and y pair of the most recent proxy location * */ proxy_coord(): Promise<any> proxy_coord$($: {}): Promise<any> /** * Remove the proxy from the display. * */ proxy_forget(): Promise<any> proxy_forget$($: {}): Promise<any> /** * Place the proxy at the given x and y coordinates. * */ proxy_place(x, y): Promise<any> proxy_place$({ x, y }): Promise<any> /** * Internal function. */ sash(): Promise<any> sash$($: {}): Promise<any> /** * Return the current x and y pair for the sash given by index. * * Index must be an integer between 0 and 1 less than the * number of panes in the panedwindow. The coordinates given are * those of the top left corner of the region containing the sash. * pathName sash dragto index x y This command computes the * difference between the given coordinates and the coordinates * given to the last sash coord command for the given sash. It then * moves that sash the computed difference. The return value is the * empty string. * */ sash_coord(index): Promise<any> sash_coord$({ index }): Promise<any> /** * Records x and y for the sash given by index; * * Used in conjunction with later dragto commands to move the sash. * */ sash_mark(index): Promise<any> sash_mark$({ index }): Promise<any> /** * Place the sash given by index at the given coordinates * */ sash_place(index, x, y): Promise<any> sash_place$({ index, x, y }): Promise<any> /** * Query a management option for window. * * Option may be any value allowed by the paneconfigure subcommand * */ panecget(child, option): Promise<any> panecget$({ child, option }): Promise<any> /** * Query or modify the management options for window. * * If no option is specified, returns a list describing all * of the available options for pathName. If option is * specified with no value, then the command returns a list * describing the one named option (this list will be identical * to the corresponding sublist of the value returned if no * option is specified). If one or more option-value pairs are * specified, then the command modifies the given widget * option(s) to have the given value(s); in this case the * command returns an empty string. The following options * are supported: * * after window * Insert the window after the window specified. window * should be the name of a window already managed by pathName. * before window * Insert the window before the window specified. window * should be the name of a window already managed by pathName. * height size * Specify a height for the window. The height will be the * outer dimension of the window including its border, if * any. If size is an empty string, or if -height is not * specified, then the height requested internally by the * window will be used initially; the height may later be * adjusted by the movement of sashes in the panedwindow. * Size may be any value accepted by Tk_GetPixels. * minsize n * Specifies that the size of the window cannot be made * less than n. This constraint only affects the size of * the widget in the paned dimension -- the x dimension * for horizontal panedwindows, the y dimension for * vertical panedwindows. May be any value accepted by * Tk_GetPixels. * padx n * Specifies a non-negative value indicating how much * extra space to leave on each side of the window in * the X-direction. The value may have any of the forms * accepted by Tk_GetPixels. * pady n * Specifies a non-negative value indicating how much * extra space to leave on each side of the window in * the Y-direction. The value may have any of the forms * accepted by Tk_GetPixels. * sticky style * If a window's pane is larger than the requested * dimensions of the window, this option may be used * to position (or stretch) the window within its pane. * Style is a string that contains zero or more of the * characters n, s, e or w. The string can optionally * contains spaces or commas, but they are ignored. Each * letter refers to a side (north, south, east, or west) * that the window will "stick" to. If both n and s * (or e and w) are specified, the window will be * stretched to fill the entire height (or width) of * its cavity. * width size * Specify a width for the window. The width will be * the outer dimension of the window including its * border, if any. If size is an empty string, or * if -width is not specified, then the width requested * internally by the window will be used initially; the * width may later be adjusted by the movement of sashes * in the panedwindow. Size may be any value accepted by * Tk_GetPixels. * * */ paneconfigure(tagOrId, cnf?): Promise<any> paneconfigure$({ tagOrId, cnf }: { tagOrId, cnf?}): Promise<any> /** * Returns an ordered list of the child panes. */ panes(): Promise<any> panes$($: {}): Promise<any> paneconfig } let TclError: Promise<any> let wantobjects: Promise<any> let TkVersion: Promise<any> let TclVersion: Promise<any> let READABLE: Promise<any> let WRITABLE: Promise<any> let EXCEPTION: Promise<any> module colorchooser { var _ /** * Display dialog window for selection of a color. * * Convenience wrapper for the Chooser class. Displays the color * chooser dialog with color as the initial value. * */ function askcolor(color?): Promise<any> function askcolor$({ color }: { color?}): Promise<any> /** * Create a dialog for the tk_chooseColor command. * * Args: * master: The master widget for this dialog. If not provided, * defaults to options['parent'] (if defined). * options: Dictionary of options for the tk_chooseColor call. * initialcolor: Specifies the selected color when the * dialog is first displayed. This can be a tk color * string or a 3-tuple of ints in the range (0, 255) * for an RGB triplet. * parent: The parent window of the color dialog. The * color dialog is displayed on top of this. * title: A string for the title of the dialog box. * */ interface IChooser { command } } module commondialog { var _ function Dialog(master?): Promise<IDialog> function Dialog$({ master }: { master?}): Promise<IDialog> interface IDialog { show(): Promise<any> show$($: {}): Promise<any> command } } module constants { var _ let NO: Promise<any> let FALSE: Promise<any> let OFF: Promise<any> let YES: Promise<any> let TRUE: Promise<any> let ON: Promise<any> let N: Promise<any> let S: Promise<any> let W: Promise<any> let E: Promise<any> let NW: Promise<any> let SW: Promise<any> let NE: Promise<any> let SE: Promise<any> let NS: Promise<any> let EW: Promise<any> let NSEW: Promise<any> let CENTER: Promise<any> let NONE: Promise<any> let X: Promise<any> let Y: Promise<any> let BOTH: Promise<any> let LEFT: Promise<any> let TOP: Promise<any> let RIGHT: Promise<any> let BOTTOM: Promise<any> let RAISED: Promise<any> let SUNKEN: Promise<any> let FLAT: Promise<any> let RIDGE: Promise<any> let GROOVE: Promise<any> let SOLID: Promise<any> let HORIZONTAL: Promise<any> let VERTICAL: Promise<any> let NUMERIC: Promise<any> let CHAR: Promise<any> let WORD: Promise<any> let BASELINE: Promise<any> let INSIDE: Promise<any> let OUTSIDE: Promise<any> let SEL: Promise<any> let SEL_FIRST: Promise<any> let SEL_LAST: Promise<any> let END: Promise<any> let INSERT: Promise<any> let CURRENT: Promise<any> let ANCHOR: Promise<any> let ALL: Promise<any> let NORMAL: Promise<any> let DISABLED: Promise<any> let ACTIVE: Promise<any> let HIDDEN: Promise<any> let CASCADE: Promise<any> let CHECKBUTTON: Promise<any> let COMMAND: Promise<any> let RADIOBUTTON: Promise<any> let SEPARATOR: Promise<any> let SINGLE: Promise<any> let BROWSE: Promise<any> let MULTIPLE: Promise<any> let EXTENDED: Promise<any> let DOTBOX: Promise<any> let UNDERLINE: Promise<any> let PIESLICE: Promise<any> let CHORD: Promise<any> let ARC: Promise<any> let FIRST: Promise<any> let LAST: Promise<any> let BUTT: Promise<any> let PROJECTING: Promise<any> let ROUND: Promise<any> let BEVEL: Promise<any> let MITER: Promise<any> let MOVETO: Promise<any> let SCROLL: Promise<any> let UNITS: Promise<any> let PAGES: Promise<any> } module dialog { var _ function Dialog(master?, cnf?): Promise<IDialog> function Dialog$({ master, cnf }: { master?, cnf?}): Promise<IDialog> interface IDialog { destroy(): Promise<any> destroy$($: {}): Promise<any> } let DIALOG_ICON: Promise<any> let t: Promise<any> let q: Promise<any> } module dnd { var _ function dnd_start(source, event): Promise<any> function dnd_start$({ source, event }): Promise<any> function test(): Promise<any> function test$($: {}): Promise<any> function DndHandler(source, event): Promise<IDndHandler> function DndHandler$({ source, event }): Promise<IDndHandler> interface IDndHandler { on_motion(event): Promise<any> on_motion$({ event }): Promise<any> on_release(event): Promise<any> on_release$({ event }): Promise<any> cancel(event?): Promise<any> cancel$({ event }: { event?}): Promise<any> finish(event, commit?): Promise<any> finish$({ event, commit }: { event, commit?}): Promise<any> root } function Icon(name): Promise<IIcon> function Icon$({ name }): Promise<IIcon> interface IIcon { attach(canvas, x?, y?): Promise<any> attach$({ canvas, x, y }: { canvas, x?, y?}): Promise<any> detach(): Promise<any> detach$($: {}): Promise<any> press(event): Promise<any> press$({ event }): Promise<any> move(event): Promise<any> move$({ event }): Promise<any> putback(): Promise<any> putback$($: {}): Promise<any> where(canvas, event): Promise<any> where$({ canvas, event }): Promise<any> dnd_end(target, event): Promise<any> dnd_end$({ target, event }): Promise<any> } function Tester(root): Promise<ITester> function Tester$({ root }): Promise<ITester> interface ITester { dnd_accept(source, event): Promise<any> dnd_accept$({ source, event }): Promise<any> dnd_enter(source, event): Promise<any> dnd_enter$({ source, event }): Promise<any> dnd_motion(source, event): Promise<any> dnd_motion$({ source, event }): Promise<any> dnd_leave(source, event): Promise<any> dnd_leave$({ source, event }): Promise<any> dnd_commit(source, event): Promise<any> dnd_commit$({ source, event }): Promise<any> } } module filedialog { var _ /** * Ask for a filename to open */ function askopenfilename(): Promise<any> function askopenfilename$($: {}): Promise<any> /** * Ask for a filename to save as */ function asksaveasfilename(): Promise<any> function asksaveasfilename$($: {}): Promise<any> /** * Ask for multiple filenames to open * * Returns a list of filenames or empty list if * cancel button selected * */ function askopenfilenames(): Promise<any> function askopenfilenames$($: {}): Promise<any> /** * Ask for a filename to open, and returned the opened file */ function askopenfile(mode?): Promise<any> function askopenfile$({ mode }: { mode?}): Promise<any> /** * Ask for multiple filenames and return the open file * objects * * returns a list of open file objects or an empty list if * cancel selected * */ function askopenfiles(mode?): Promise<any> function askopenfiles$({ mode }: { mode?}): Promise<any> /** * Ask for a filename to save as, and returned the opened file */ function asksaveasfile(mode?): Promise<any> function asksaveasfile$({ mode }: { mode?}): Promise<any> /** * Ask for a directory, and return the file name */ function askdirectory(): Promise<any> function askdirectory$($: {}): Promise<any> /** * Simple test program. */ function test(): Promise<any> function test$($: {}): Promise<any> /** * Standard file selection dialog -- no checks on selected file. * * Usage: * * d = FileDialog(master) * fname = d.go(dir_or_file, pattern, default, key) * if fname is None: ...canceled... * else: ...open file... * * All arguments to go() are optional. * * The 'key' argument specifies a key in the global dictionary * 'dialogstates', which keeps track of the values for the directory * and pattern arguments, overriding the values passed in (it does * not keep track of the default argument!). If no key is specified, * the dialog keeps no memory of previous state. Note that memory is * kept even when the dialog is canceled. (All this emulates the * behavior of the Macintosh file selection dialogs.) * * */ function FileDialog(master, title?): Promise<IFileDialog> function FileDialog$({ master, title }: { master, title?}): Promise<IFileDialog> interface IFileDialog { go(dir_or_file?, pattern?, def?, key?): Promise<any> go$({ dir_or_file, pattern, def, key }: { dir_or_file?, pattern?, def?, key?}): Promise<any> quit(how?): Promise<any> quit$({ how }: { how?}): Promise<any> dirs_double_event(event): Promise<any> dirs_double_event$({ event }): Promise<any> dirs_select_event(event): Promise<any> dirs_select_event$({ event }): Promise<any> files_double_event(event): Promise<any> files_double_event$({ event }): Promise<any> files_select_event(event): Promise<any> files_select_event$({ event }): Promise<any> ok_event(event): Promise<any> ok_event$({ event }): Promise<any> ok_command(): Promise<any> ok_command$($: {}): Promise<any> filter_command(event?): Promise<any> filter_command$({ event }: { event?}): Promise<any> get_filter(): Promise<any> get_filter$($: {}): Promise<any> get_selection(): Promise<any> get_selection$($: {}): Promise<any> cancel_command(event?): Promise<any> cancel_command$({ event }: { event?}): Promise<any> set_filter(dir, pat): Promise<any> set_filter$({ dir, pat }): Promise<any> set_selection(file): Promise<any> set_selection$({ file }): Promise<any> title } /** * File selection dialog which checks that the file exists. */ interface ILoadFileDialog extends IFileDialog { ok_command(): Promise<any> ok_command$($: {}): Promise<any> } /** * File selection dialog which checks that the file may be created. */ interface ISaveFileDialog extends IFileDialog { ok_command(): Promise<any> ok_command$($: {}): Promise<any> } interface I_Dialog { } /** * Ask for a filename to open */ interface IOpen extends I_Dialog { command } /** * Ask for a filename to save as */ interface ISaveAs extends I_Dialog { } /** * Ask for a directory */ interface IDirectory { } let dialogstates: Promise<any> } module font { var _ /** * Given the name of a tk named font, returns a Font representation. * */ function nametofont(name, root?): Promise<any> function nametofont$({ name, root }: { name, root?}): Promise<any> /** * Get font families (as a tuple) */ function families(root?, displayof?): Promise<any> function families$({ root, displayof }: { root?, displayof?}): Promise<any> /** * Get names of defined fonts (as a tuple) */ function names(root?): Promise<any> function names$({ root }: { root?}): Promise<any> /** * Represents a named font. * * Constructor options are: * * font -- font specifier (name, system font, or (family, size, style)-tuple) * name -- name to use for this font configuration (defaults to a unique name) * exists -- does a named font by this name already exist? * Creates a new named font if False, points to the existing font if True. * Raises _tkinter.TclError if the assertion is false. * * the following are ignored if font is specified: * * family -- font 'family', e.g. Courier, Times, Helvetica * size -- font size in points * weight -- font thickness: NORMAL, BOLD * slant -- font slant: ROMAN, ITALIC * underline -- font underlining: false (0), true (1) * overstrike -- font strikeout: false (0), true (1) * * */ function Font(root?, font?, name?, exists?: boolean): Promise<IFont> function Font$({ root, font, name, exists }: { root?, font?, name?, exists?}): Promise<IFont> interface IFont { /** * Return a distinct copy of the current font */ copy(): Promise<any> copy$($: {}): Promise<any> /** * Return actual font attributes */ actual(option?, displayof?): Promise<any> actual$({ option, displayof }: { option?, displayof?}): Promise<any> /** * Get font attribute */ cget(option): Promise<any> cget$({ option }): Promise<any> /** * Modify font attributes */ config(): Promise<any> config$($: {}): Promise<any> /** * Return text width */ measure(text, displayof?): Promise<any> measure$({ text, displayof }: { text, displayof?}): Promise<any> /** * Return font metrics. * * For best performance, create a dummy widget * using this font before calling this method. */ metrics(): Promise<any> metrics$($: {}): Promise<any> counter configure } let NORMAL: Promise<any> let ROMAN: Promise<any> let BOLD: Promise<any> let ITALIC: Promise<any> let root: Promise<any> let f: Promise<any> let w: Promise<any> let fb: Promise<any> } module messagebox { var _ /** * Show an info message */ function showinfo(title?, message?): Promise<any> function showinfo$({ title, message }: { title?, message?}): Promise<any> /** * Show a warning message */ function showwarning(title?, message?): Promise<any> function showwarning$({ title, message }: { title?, message?}): Promise<any> /** * Show an error message */ function showerror(title?, message?): Promise<any> function showerror$({ title, message }: { title?, message?}): Promise<any> /** * Ask a question */ function askquestion(title?, message?): Promise<any> function askquestion$({ title, message }: { title?, message?}): Promise<any> /** * Ask if operation should proceed; return true if the answer is ok */ function askokcancel(title?, message?): Promise<any> function askokcancel$({ title, message }: { title?, message?}): Promise<any> /** * Ask a question; return true if the answer is yes */ function askyesno(title?, message?): Promise<any> function askyesno$({ title, message }: { title?, message?}): Promise<any> /** * Ask a question; return true if the answer is yes, None if cancelled. */ function askyesnocancel(title?, message?): Promise<any> function askyesnocancel$({ title, message }: { title?, message?}): Promise<any> /** * Ask if operation should be retried; return true if the answer is yes */ function askretrycancel(title?, message?): Promise<any> function askretrycancel$({ title, message }: { title?, message?}): Promise<any> /** * A message box */ interface IMessage { command } let ERROR: Promise<any> let INFO: Promise<any> let QUESTION: Promise<any> let WARNING: Promise<any> let ABORTRETRYIGNORE: Promise<any> let OK: Promise<any> let OKCANCEL: Promise<any> let RETRYCANCEL: Promise<any> let YESNO: Promise<any> let YESNOCANCEL: Promise<any> let ABORT: Promise<any> let RETRY: Promise<any> let IGNORE: Promise<any> let CANCEL: Promise<any> let YES: Promise<any> let NO: Promise<any> } module scrolledtext { var _ function example(): Promise<any> function example$($: {}): Promise<any> function ScrolledText(master?): Promise<IScrolledText> function ScrolledText$({ master }: { master?}): Promise<IScrolledText> interface IScrolledText { } } module simpledialog { var _ /** * get an integer from the user * * Arguments: * * title -- the dialog title * prompt -- the label text * **kw -- see SimpleDialog class * * Return value is an integer * */ function askinteger(title, prompt): Promise<any> function askinteger$({ title, prompt }): Promise<any> /** * get a float from the user * * Arguments: * * title -- the dialog title * prompt -- the label text * **kw -- see SimpleDialog class * * Return value is a float * */ function askfloat(title, prompt): Promise<any> function askfloat$({ title, prompt }): Promise<any> /** * get a string from the user * * Arguments: * * title -- the dialog title * prompt -- the label text * **kw -- see SimpleDialog class * * Return value is a string * */ function askstring(title, prompt): Promise<any> function askstring$({ title, prompt }): Promise<any> function test(): Promise<any> function test$($: {}): Promise<any> function SimpleDialog(master, text?, buttons?, def?, cancel?, title?, class_?): Promise<ISimpleDialog> function SimpleDialog$({ master, text, buttons, def, cancel, title, class_ }: { master, text?, buttons?, def?, cancel?, title?, class_?}): Promise<ISimpleDialog> interface ISimpleDialog { go(): Promise<any> go$($: {}): Promise<any> return_event(event): Promise<any> return_event$({ event }): Promise<any> wm_delete_window(): Promise<any> wm_delete_window$($: {}): Promise<any> done(num): Promise<any> done$({ num }): Promise<any> } /** * Class to open dialogs. * * This class is intended as a base class for custom dialogs * */ /** * Initialize a dialog. * * Arguments: * * parent -- a parent window (the application window) * * title -- the dialog title * */ function Dialog(parent, title?): Promise<IDialog> function Dialog$({ parent, title }: { parent, title?}): Promise<IDialog> interface IDialog { /** * Destroy the window */ destroy(): Promise<any> destroy$($: {}): Promise<any> /** * create dialog body. * * return widget that should have initial focus. * This method should be overridden, and is called * by the __init__ method. * */ body(master): Promise<any> body$({ master }): Promise<any> /** * add standard button box. * * override if you do not want the standard buttons * */ buttonbox(): Promise<any> buttonbox$($: {}): Promise<any> ok(event?): Promise<any> ok$({ event }: { event?}): Promise<any> cancel(event?): Promise<any> cancel$({ event }: { event?}): Promise<any> /** * validate the data * * This method is called automatically to validate the data before the * dialog is destroyed. By default, it always validates OK. * */ validate(): Promise<any> validate$($: {}): Promise<any> /** * process the data * * This method is called automatically to process the data, *after* * the dialog is destroyed. By default, it does nothing. * */ apply(): Promise<any> apply$($: {}): Promise<any> } interface I_QueryDialog extends IDialog { destroy(): Promise<any> destroy$($: {}): Promise<any> body(master): Promise<any> body$({ master }): Promise<any> validate(): Promise<any> validate$($: {}): Promise<any> } interface I_QueryInteger extends I_QueryDialog { getresult(): Promise<any> getresult$($: {}): Promise<any> errormessage } interface I_QueryFloat extends I_QueryDialog { getresult(): Promise<any> getresult$($: {}): Promise<any> } interface I_QueryString extends I_QueryDialog { body(master): Promise<any> body$({ master }): Promise<any> getresult(): Promise<any> getresult$($: {}): Promise<any> } } module tix { var _ /** * Returns the qualified path name for the widget. Normally used to set * default options for subwidgets. See tixwidgets.py */ function OptionName(widget): Promise<any> function OptionName$({ widget }): Promise<any> function FileTypeList(dict): Promise<any> function FileTypeList$({ dict }): Promise<any> /** * The tix commands provide access to miscellaneous elements * of Tix's internal state and the Tix application context. * Most of the information manipulated by these commands pertains * to the application as a whole, or to a screen or * display, rather than to a particular window. * * This is a mixin class, assumed to be mixed to Tkinter.Tk * that supports the self.tk.call method. * */ interface ItixCommand { /** * Tix maintains a list of directories under which * the tix_getimage and tix_getbitmap commands will * search for image files. The standard bitmap directory * is $TIX_LIBRARY/bitmaps. The addbitmapdir command * adds directory into this list. By using this * command, the image files of an applications can * also be located using the tix_getimage or tix_getbitmap * command. * */ tix_addbitmapdir(directory): Promise<any> tix_addbitmapdir$({ directory }): Promise<any> /** * Returns the current value of the configuration * option given by option. Option may be any of the * options described in the CONFIGURATION OPTIONS section. * */ tix_cget(option): Promise<any> tix_cget$({ option }): Promise<any> /** * Query or modify the configuration options of the Tix application * context. If no option is specified, returns a dictionary all of the * available options. If option is specified with no value, then the * command returns a list describing the one named option (this list * will be identical to the corresponding sublist of the value * returned if no option is specified). If one or more option-value * pairs are specified, then the command modifies the given option(s) * to have the given value(s); in this case the command returns an * empty string. Option may be any of the configuration options. * */ tix_configure(cnf?): Promise<any> tix_configure$({ cnf }: { cnf?}): Promise<any> /** * Returns the file selection dialog that may be shared among * different calls from this application. This command will create a * file selection dialog widget when it is called the first time. This * dialog will be returned by all subsequent calls to tix_filedialog. * An optional dlgclass parameter can be passed to specified what type * of file selection dialog widget is desired. Possible options are * tix FileSelectDialog or tixExFileSelectDialog. * */ tix_filedialog(dlgclass?): Promise<any> tix_filedialog$({ dlgclass }: { dlgclass?}): Promise<any> /** * Locates a bitmap file of the name name.xpm or name in one of the * bitmap directories (see the tix_addbitmapdir command above). By * using tix_getbitmap, you can avoid hard coding the pathnames of the * bitmap files in your application. When successful, it returns the * complete pathname of the bitmap file, prefixed with the character * '@'. The returned value can be used to configure the -bitmap * option of the TK and Tix widgets. * */ tix_getbitmap(name): Promise<any> tix_getbitmap$({ name }): Promise<any> /** * Locates an image file of the name name.xpm, name.xbm or name.ppm * in one of the bitmap directories (see the addbitmapdir command * above). If more than one file with the same name (but different * extensions) exist, then the image type is chosen according to the * depth of the X display: xbm images are chosen on monochrome * displays and color images are chosen on color displays. By using * tix_ getimage, you can avoid hard coding the pathnames of the * image files in your application. When successful, this command * returns the name of the newly created image, which can be used to * configure the -image option of the Tk and Tix widgets. * */ tix_getimage(name): Promise<any> tix_getimage$({ name }): Promise<any> /** * Gets the options maintained by the Tix * scheme mechanism. Available options include: * * active_bg active_fg bg * bold_font dark1_bg dark1_fg * dark2_bg dark2_fg disabled_fg * fg fixed_font font * inactive_bg inactive_fg input1_bg * input2_bg italic_font light1_bg * light1_fg light2_bg light2_fg * menu_font output1_bg output2_bg * select_bg select_fg selector * */ tix_option_get(name): Promise<any> tix_option_get$({ name }): Promise<any> /** * Resets the scheme and fontset of the Tix application to * newScheme and newFontSet, respectively. This affects only those * widgets created after this call. Therefore, it is best to call the * resetoptions command before the creation of any widgets in a Tix * application. * * The optional parameter newScmPrio can be given to reset the * priority level of the Tk options set by the Tix schemes. * * Because of the way Tk handles the X option database, after Tix has * been has imported and inited, it is not possible to reset the color * schemes and font sets using the tix config command. Instead, the * tix_resetoptions command must be used. * */ tix_resetoptions(newScheme, newFontSet, newScmPrio?): Promise<any> tix_resetoptions$({ newScheme, newFontSet, newScmPrio }: { newScheme, newFontSet, newScmPrio?}): Promise<any> } /** * Toplevel widget of Tix which represents mostly the main window * of an application. It has an associated Tcl interpreter. */ function Tk(screenName?, baseName?, className?): Promise<ITk> function Tk$({ screenName, baseName, className }: { screenName?, baseName?, className?}): Promise<ITk> interface ITk extends ItixCommand { destroy(): Promise<any> destroy$($: {}): Promise<any> } /** * The Tix Form geometry manager * * Widgets can be arranged by specifying attachments to other widgets. * See Tix documentation for complete details */ interface IForm { config(cnf?): Promise<any> config$({ cnf }: { cnf?}): Promise<any> check(): Promise<any> check$($: {}): Promise<any> forget(): Promise<any> forget$($: {}): Promise<any> grid(xsize?, ysize?): Promise<any> grid$({ xsize, ysize }: { xsize?, ysize?}): Promise<any> info(option?): Promise<any> info$({ option }: { option?}): Promise<any> slaves(): Promise<any> slaves$($: {}): Promise<any> form } /** * A TixWidget class is used to package all (or most) Tix widgets. * * Widget initialization is extended in two ways: * 1) It is possible to give a list of options which must be part of * the creation command (so called Tix 'static' options). These cannot be * given as a 'config' command later. * 2) It is possible to give the name of an existing TK widget. These are * child widgets created automatically by a Tix mega-widget. The Tk call * to create these widgets is therefore bypassed in TixWidget.__init__ * * Both options are for use by subclasses only. * */ function TixWidget(master?, widgetName?, static_options?, cnf?, kw?): Promise<ITixWidget> function TixWidget$({ master, widgetName, static_options, cnf, kw }: { master?, widgetName?, static_options?, cnf?, kw?}): Promise<ITixWidget> interface ITixWidget { /** * Set a variable without calling its action routine */ set_silent(value): Promise<any> set_silent$({ value }): Promise<any> /** * Return the named subwidget (which must have been created by * the sub-class). */ subwidget(name): Promise<any> subwidget$({ name }): Promise<any> /** * Return all subwidgets. */ subwidgets_all(): Promise<any> subwidgets_all$($: {}): Promise<any> /** * Set configuration options for all subwidgets (and self). */ config_all(option, value): Promise<any> config_all$({ option, value }): Promise<any> image_create(imgtype, cnf?, master?): Promise<any> image_create$({ imgtype, cnf, master }: { imgtype, cnf?, master?}): Promise<any> image_delete(imgname): Promise<any> image_delete$({ imgname }): Promise<any> } /** * Subwidget class. * * This is used to mirror child widgets automatically created * by Tix/Tk as part of a mega-widget in Python (which is not informed * of this) */ function TixSubWidget(master, name, destroy_physically?, check_intermediate?): Promise<ITixSubWidget> function TixSubWidget$({ master, name, destroy_physically, check_intermediate }: { master, name, destroy_physically?, check_intermediate?}): Promise<ITixSubWidget> interface ITixSubWidget extends ITixWidget { destroy(): Promise<any> destroy$($: {}): Promise<any> } /** * DisplayStyle - handle configuration options shared by * (multiple) Display Items */ function DisplayStyle(itemtype, cnf?): Promise<IDisplayStyle> function DisplayStyle$({ itemtype, cnf }: { itemtype, cnf?}): Promise<IDisplayStyle> interface IDisplayStyle { delete(): Promise<any> delete$($: {}): Promise<any> config(cnf?): Promise<any> config$({ cnf }: { cnf?}): Promise<any> } /** * Balloon help widget. * * Subwidget Class * --------- ----- * label Label * message Message */ function Balloon(master?, cnf?): Promise<IBalloon> function Balloon$({ master, cnf }: { master?, cnf?}): Promise<IBalloon> interface IBalloon extends ITixWidget { /** * Bind balloon widget to another. * One balloon widget may be bound to several widgets at the same time */ bind_widget(widget, cnf?): Promise<any> bind_widget$({ widget, cnf }: { widget, cnf?}): Promise<any> unbind_widget(widget): Promise<any> unbind_widget$({ widget }): Promise<any> } /** * ButtonBox - A container for pushbuttons. * Subwidgets are the buttons added with the add method. * */ function ButtonBox(master?, cnf?): Promise<IButtonBox> function ButtonBox$({ master, cnf }: { master?, cnf?}): Promise<IButtonBox> interface IButtonBox extends ITixWidget { /** * Add a button with given name to box. */ add(name, cnf?): Promise<any> add$({ name, cnf }: { name, cnf?}): Promise<any> invoke(name): Promise<any> invoke$({ name }): Promise<any> } /** * ComboBox - an Entry field with a dropdown menu. The user can select a * choice by either typing in the entry subwidget or selecting from the * listbox subwidget. * * Subwidget Class * --------- ----- * entry Entry * arrow Button * slistbox ScrolledListBox * tick Button * cross Button : present if created with the fancy option */ function ComboBox(master?, cnf?): Promise<IComboBox> function ComboBox$({ master, cnf }: { master?, cnf?}): Promise<IComboBox> interface IComboBox extends ITixWidget { add_history(str): Promise<any> add_history$({ str }): Promise<any> append_history(str): Promise<any> append_history$({ str }): Promise<any> insert(index, str): Promise<any> insert$({ index, str }): Promise<any> pick(index): Promise<any> pick$({ index }): Promise<any> } /** * Control - An entry field with value change arrows. The user can * adjust the value by pressing the two arrow buttons or by entering * the value directly into the entry. The new value will be checked * against the user-defined upper and lower limits. * * Subwidget Class * --------- ----- * incr Button * decr Button * entry Entry * label Label */ function Control(master?, cnf?): Promise<IControl> function Control$({ master, cnf }: { master?, cnf?}): Promise<IControl> interface IControl extends ITixWidget { decrement(): Promise<any> decrement$($: {}): Promise<any> increment(): Promise<any> increment$($: {}): Promise<any> invoke(): Promise<any> invoke$($: {}): Promise<any> update(): Promise<any> update$($: {}): Promise<any> } /** * DirList - displays a list view of a directory, its previous * directories and its sub-directories. The user can choose one of * the directories displayed in the list or change to another directory. * * Subwidget Class * --------- ----- * hlist HList * hsb Scrollbar * vsb Scrollbar */ function DirList(master, cnf?): Promise<IDirList> function DirList$({ master, cnf }: { master, cnf?}): Promise<IDirList> interface IDirList extends ITixWidget { chdir(dir): Promise<any> chdir$({ dir }): Promise<any> } /** * DirTree - Directory Listing in a hierarchical view. * Displays a tree view of a directory, its previous directories and its * sub-directories. The user can choose one of the directories displayed * in the list or change to another directory. * * Subwidget Class * --------- ----- * hlist HList * hsb Scrollbar * vsb Scrollbar */ function DirTree(master, cnf?): Promise<IDirTree> function DirTree$({ master, cnf }: { master, cnf?}): Promise<IDirTree> interface IDirTree extends ITixWidget { chdir(dir): Promise<any> chdir$({ dir }): Promise<any> } /** * DirSelectBox - Motif style file select box. * It is generally used for * the user to choose a file. FileSelectBox stores the files mostly * recently selected into a ComboBox widget so that they can be quickly * selected again. * * Subwidget Class * --------- ----- * selection ComboBox * filter ComboBox * dirlist ScrolledListBox * filelist ScrolledListBox */ function DirSelectBox(master, cnf?): Promise<IDirSelectBox> function DirSelectBox$({ master, cnf }: { master, cnf?}): Promise<IDirSelectBox> interface IDirSelectBox extends ITixWidget { } /** * ExFileSelectBox - MS Windows style file select box. * It provides a convenient method for the user to select files. * * Subwidget Class * --------- ----- * cancel Button * ok Button * hidden Checkbutton * types ComboBox * dir ComboBox * file ComboBox * dirlist ScrolledListBox * filelist ScrolledListBox */ function ExFileSelectBox(master, cnf?): Promise<IExFileSelectBox> function ExFileSelectBox$({ master, cnf }: { master, cnf?}): Promise<IExFileSelectBox> interface IExFileSelectBox extends ITixWidget { filter(): Promise<any> filter$($: {}): Promise<any> invoke(): Promise<any> invoke$($: {}): Promise<any> } /** * The DirSelectDialog widget presents the directories in the file * system in a dialog window. The user can use this dialog window to * navigate through the file system to select the desired directory. * * Subwidgets Class * ---------- ----- * dirbox DirSelectDialog */ function DirSelectDialog(master, cnf?): Promise<IDirSelectDialog> function DirSelectDialog$({ master, cnf }: { master, cnf?}): Promise<IDirSelectDialog> interface IDirSelectDialog extends ITixWidget { popup(): Promise<any> popup$($: {}): Promise<any> popdown(): Promise<any> popdown$($: {}): Promise<any> } /** * ExFileSelectDialog - MS Windows style file select dialog. * It provides a convenient method for the user to select files. * * Subwidgets Class * ---------- ----- * fsbox ExFileSelectBox */ function ExFileSelectDialog(master, cnf?): Promise<IExFileSelectDialog> function ExFileSelectDialog$({ master, cnf }: { master, cnf?}): Promise<IExFileSelectDialog> interface IExFileSelectDialog extends ITixWidget { popup(): Promise<any> popup$($: {}): Promise<any> popdown(): Promise<any> popdown$($: {}): Promise<any> } /** * ExFileSelectBox - Motif style file select box. * It is generally used for * the user to choose a file. FileSelectBox stores the files mostly * recently selected into a ComboBox widget so that they can be quickly * selected again. * * Subwidget Class * --------- ----- * selection ComboBox * filter ComboBox * dirlist ScrolledListBox * filelist ScrolledListBox */ function FileSelectBox(master, cnf?): Promise<IFileSelectBox> function FileSelectBox$({ master, cnf }: { master, cnf?}): Promise<IFileSelectBox> interface IFileSelectBox extends ITixWidget { apply_filter(): Promise<any> apply_filter$($: {}): Promise<any> invoke(): Promise<any> invoke$($: {}): Promise<any> } /** * FileSelectDialog - Motif style file select dialog. * * Subwidgets Class * ---------- ----- * btns StdButtonBox * fsbox FileSelectBox */ function FileSelectDialog(master, cnf?): Promise<IFileSelectDialog> function FileSelectDialog$({ master, cnf }: { master, cnf?}): Promise<IFileSelectDialog> interface IFileSelectDialog extends ITixWidget { popup(): Promise<any> popup$($: {}): Promise<any> popdown(): Promise<any> popdown$($: {}): Promise<any> } /** * FileEntry - Entry field with button that invokes a FileSelectDialog. * The user can type in the filename manually. Alternatively, the user can * press the button widget that sits next to the entry, which will bring * up a file selection dialog. * * Subwidgets Class * ---------- ----- * button Button * entry Entry */ function FileEntry(master, cnf?): Promise<IFileEntry> function FileEntry$({ master, cnf }: { master, cnf?}): Promise<IFileEntry> interface IFileEntry extends ITixWidget { invoke(): Promise<any> invoke$($: {}): Promise<any> file_dialog(): Promise<any> file_dialog$($: {}): Promise<any> } /** * HList - Hierarchy display widget can be used to display any data * that have a hierarchical structure, for example, file system directory * trees. The list entries are indented and connected by branch lines * according to their places in the hierarchy. * * Subwidgets - None */ function HList(master?, cnf?): Promise<IHList> function HList$({ master, cnf }: { master?, cnf?}): Promise<IHList> interface IHList extends ITixWidget { add(entry, cnf?): Promise<any> add$({ entry, cnf }: { entry, cnf?}): Promise<any> add_child(parent?, cnf?): Promise<any> add_child$({ parent, cnf }: { parent?, cnf?}): Promise<any> anchor_set(entry): Promise<any> anchor_set$({ entry }): Promise<any> anchor_clear(): Promise<any> anchor_clear$($: {}): Promise<any> column_width(col?, width?, chars?): Promise<any> column_width$({ col, width, chars }: { col?, width?, chars?}): Promise<any> delete_all(): Promise<any> delete_all$($: {}): Promise<any> delete_entry(entry): Promise<any> delete_entry$({ entry }): Promise<any> delete_offsprings(entry): Promise<any> delete_offsprings$({ entry }): Promise<any> delete_siblings(entry): Promise<any> delete_siblings$({ entry }): Promise<any> dragsite_set(index): Promise<any> dragsite_set$({ index }): Promise<any> dragsite_clear(): Promise<any> dragsite_clear$($: {}): Promise<any> dropsite_set(index): Promise<any> dropsite_set$({ index }): Promise<any> dropsite_clear(): Promise<any> dropsite_clear$($: {}): Promise<any> header_create(col, cnf?): Promise<any> header_create$({ col, cnf }: { col, cnf?}): Promise<any> header_configure(col, cnf?): Promise<any> header_configure$({ col, cnf }: { col, cnf?}): Promise<any> header_cget(col, opt): Promise<any> header_cget$({ col, opt }): Promise<any> header_exists(col): Promise<any> header_exists$({ col }): Promise<any> header_delete(col): Promise<any> header_delete$({ col }): Promise<any> header_size(col): Promise<any> header_size$({ col }): Promise<any> hide_entry(entry): Promise<any> hide_entry$({ entry }): Promise<any> indicator_create(entry, cnf?): Promise<any> indicator_create$({ entry, cnf }: { entry, cnf?}): Promise<any> indicator_configure(entry, cnf?): Promise<any> indicator_configure$({ entry, cnf }: { entry, cnf?}): Promise<any> indicator_cget(entry, opt): Promise<any> indicator_cget$({ entry, opt }): Promise<any> indicator_exists(entry): Promise<any> indicator_exists$({ entry }): Promise<any> indicator_delete(entry): Promise<any> indicator_delete$({ entry }): Promise<any> indicator_size(entry): Promise<any> indicator_size$({ entry }): Promise<any> info_anchor(): Promise<any> info_anchor$($: {}): Promise<any> info_bbox(entry): Promise<any> info_bbox$({ entry }): Promise<any> info_children(entry?): Promise<any> info_children$({ entry }: { entry?}): Promise<any> info_data(entry): Promise<any> info_data$({ entry }): Promise<any> info_dragsite(): Promise<any> info_dragsite$($: {}): Promise<any> info_dropsite(): Promise<any> info_dropsite$($: {}): Promise<any> info_exists(entry): Promise<any> info_exists$({ entry }): Promise<any> info_hidden(entry): Promise<any> info_hidden$({ entry }): Promise<any> info_next(entry): Promise<any> info_next$({ entry }): Promise<any> info_parent(entry): Promise<any> info_parent$({ entry }): Promise<any> info_prev(entry): Promise<any> info_prev$({ entry }): Promise<any> info_selection(): Promise<any> info_selection$($: {}): Promise<any> item_cget(entry, col, opt): Promise<any> item_cget$({ entry, col, opt }): Promise<any> item_configure(entry, col, cnf?): Promise<any> item_configure$({ entry, col, cnf }: { entry, col, cnf?}): Promise<any> item_create(entry, col, cnf?): Promise<any> item_create$({ entry, col, cnf }: { entry, col, cnf?}): Promise<any> item_exists(entry, col): Promise<any> item_exists$({ entry, col }): Promise<any> item_delete(entry, col): Promise<any> item_delete$({ entry, col }): Promise<any> entrycget(entry, opt): Promise<any> entrycget$({ entry, opt }): Promise<any> entryconfigure(entry, cnf?): Promise<any> entryconfigure$({ entry, cnf }: { entry, cnf?}): Promise<any> nearest(y): Promise<any> nearest$({ y }): Promise<any> see(entry): Promise<any> see$({ entry }): Promise<any> selection_clear(cnf?): Promise<any> selection_clear$({ cnf }: { cnf?}): Promise<any> selection_includes(entry): Promise<any> selection_includes$({ entry }): Promise<any> selection_set(first, last?): Promise<any> selection_set$({ first, last }: { first, last?}): Promise<any> show_entry(entry): Promise<any> show_entry$({ entry }): Promise<any> header_exist } /** * InputOnly - Invisible widget. Unix only. * * Subwidgets - None */ function InputOnly(master?, cnf?): Promise<IInputOnly> function InputOnly$({ master, cnf }: { master?, cnf?}): Promise<IInputOnly> interface IInputOnly extends ITixWidget { } /** * LabelEntry - Entry field with label. Packages an entry widget * and a label into one mega widget. It can be used to simplify the creation * of ``entry-form'' type of interface. * * Subwidgets Class * ---------- ----- * label Label * entry Entry */ function LabelEntry(master?, cnf?): Promise<ILabelEntry> function LabelEntry$({ master, cnf }: { master?, cnf?}): Promise<ILabelEntry> interface ILabelEntry extends ITixWidget { } /** * LabelFrame - Labelled Frame container. Packages a frame widget * and a label into one mega widget. To create widgets inside a * LabelFrame widget, one creates the new widgets relative to the * frame subwidget and manage them inside the frame subwidget. * * Subwidgets Class * ---------- ----- * label Label * frame Frame */ function LabelFrame(master?, cnf?): Promise<ILabelFrame> function LabelFrame$({ master, cnf }: { master?, cnf?}): Promise<ILabelFrame> interface ILabelFrame extends ITixWidget { } /** * A ListNoteBook widget is very similar to the TixNoteBook widget: * it can be used to display many windows in a limited space using a * notebook metaphor. The notebook is divided into a stack of pages * (windows). At one time only one of these pages can be shown. * The user can navigate through these pages by * choosing the name of the desired page in the hlist subwidget. */ function ListNoteBook(master, cnf?): Promise<IListNoteBook> function ListNoteBook$({ master, cnf }: { master, cnf?}): Promise<IListNoteBook> interface IListNoteBook extends ITixWidget { add(name, cnf?): Promise<any> add$({ name, cnf }: { name, cnf?}): Promise<any> page(name): Promise<any> page$({ name }): Promise<any> pages(): Promise<any> pages$($: {}): Promise<any> raise_page(name): Promise<any> raise_page$({ name }): Promise<any> } /** * The Meter widget can be used to show the progress of a background * job which may take a long time to execute. * */ function Meter(master?, cnf?): Promise<IMeter> function Meter$({ master, cnf }: { master?, cnf?}): Promise<IMeter> interface IMeter extends ITixWidget { } /** * NoteBook - Multi-page container widget (tabbed notebook metaphor). * * Subwidgets Class * ---------- ----- * nbframe NoteBookFrame * <pages> page widgets added dynamically with the add method */ function NoteBook(master?, cnf?): Promise<INoteBook> function NoteBook$({ master, cnf }: { master?, cnf?}): Promise<INoteBook> interface INoteBook extends ITixWidget { add(name, cnf?): Promise<any> add$({ name, cnf }: { name, cnf?}): Promise<any> delete(name): Promise<any> delete$({ name }): Promise<any> page(name): Promise<any> page$({ name }): Promise<any> pages(): Promise<any> pages$($: {}): Promise<any> raise_page(name): Promise<any> raise_page$({ name }): Promise<any> raised(): Promise<any> raised$($: {}): Promise<any> } interface INoteBookFrame extends ITixWidget { } /** * OptionMenu - creates a menu button of options. * * Subwidget Class * --------- ----- * menubutton Menubutton * menu Menu */ function OptionMenu(master, cnf?): Promise<IOptionMenu> function OptionMenu$({ master, cnf }: { master, cnf?}): Promise<IOptionMenu> interface IOptionMenu extends ITixWidget { add_command(name, cnf?): Promise<any> add_command$({ name, cnf }: { name, cnf?}): Promise<any> add_separator(name, cnf?): Promise<any> add_separator$({ name, cnf }: { name, cnf?}): Promise<any> delete(name): Promise<any> delete$({ name }): Promise<any> disable(name): Promise<any> disable$({ name }): Promise<any> enable(name): Promise<any> enable$({ name }): Promise<any> } /** * PanedWindow - Multi-pane container widget * allows the user to interactively manipulate the sizes of several * panes. The panes can be arranged either vertically or horizontally.The * user changes the sizes of the panes by dragging the resize handle * between two panes. * * Subwidgets Class * ---------- ----- * <panes> g/p widgets added dynamically with the add method. */ function PanedWindow(master, cnf?): Promise<IPanedWindow> function PanedWindow$({ master, cnf }: { master, cnf?}): Promise<IPanedWindow> interface IPanedWindow extends ITixWidget { add(name, cnf?): Promise<any> add$({ name, cnf }: { name, cnf?}): Promise<any> delete(name): Promise<any> delete$({ name }): Promise<any> forget(name): Promise<any> forget$({ name }): Promise<any> panecget(entry, opt): Promise<any> panecget$({ entry, opt }): Promise<any> paneconfigure(entry, cnf?): Promise<any> paneconfigure$({ entry, cnf }: { entry, cnf?}): Promise<any> panes(): Promise<any> panes$($: {}): Promise<any> } /** * PopupMenu widget can be used as a replacement of the tk_popup command. * The advantage of the Tix PopupMenu widget is it requires less application * code to manipulate. * * * Subwidgets Class * ---------- ----- * menubutton Menubutton * menu Menu */ function PopupMenu(master, cnf?): Promise<IPopupMenu> function PopupMenu$({ master, cnf }: { master, cnf?}): Promise<IPopupMenu> interface IPopupMenu extends ITixWidget { bind_widget(widget): Promise<any> bind_widget$({ widget }): Promise<any> unbind_widget(widget): Promise<any> unbind_widget$({ widget }): Promise<any> post_widget(widget, x, y): Promise<any> post_widget$({ widget, x, y }): Promise<any> } /** * Internal widget to draw resize handles on Scrolled widgets. */ function ResizeHandle(master, cnf?): Promise<IResizeHandle> function ResizeHandle$({ master, cnf }: { master, cnf?}): Promise<IResizeHandle> interface IResizeHandle extends ITixWidget { attach_widget(widget): Promise<any> attach_widget$({ widget }): Promise<any> detach_widget(widget): Promise<any> detach_widget$({ widget }): Promise<any> hide(widget): Promise<any> hide$({ widget }): Promise<any> show(widget): Promise<any> show$({ widget }): Promise<any> } /** * ScrolledHList - HList with automatic scrollbars. */ function ScrolledHList(master, cnf?): Promise<IScrolledHList> function ScrolledHList$({ master, cnf }: { master, cnf?}): Promise<IScrolledHList> interface IScrolledHList extends ITixWidget { } /** * ScrolledListBox - Listbox with automatic scrollbars. */ function ScrolledListBox(master, cnf?): Promise<IScrolledListBox> function ScrolledListBox$({ master, cnf }: { master, cnf?}): Promise<IScrolledListBox> interface IScrolledListBox extends ITixWidget { } /** * ScrolledText - Text with automatic scrollbars. */ function ScrolledText(master, cnf?): Promise<IScrolledText> function ScrolledText$({ master, cnf }: { master, cnf?}): Promise<IScrolledText> interface IScrolledText extends ITixWidget { } /** * ScrolledTList - TList with automatic scrollbars. */ function ScrolledTList(master, cnf?): Promise<IScrolledTList> function ScrolledTList$({ master, cnf }: { master, cnf?}): Promise<IScrolledTList> interface IScrolledTList extends ITixWidget { } /** * ScrolledWindow - Window with automatic scrollbars. */ function ScrolledWindow(master, cnf?): Promise<IScrolledWindow> function ScrolledWindow$({ master, cnf }: { master, cnf?}): Promise<IScrolledWindow> interface IScrolledWindow extends ITixWidget { } /** * Select - Container of button subwidgets. It can be used to provide * radio-box or check-box style of selection options for the user. * * Subwidgets are buttons added dynamically using the add method. */ function Select(master, cnf?): Promise<ISelect> function Select$({ master, cnf }: { master, cnf?}): Promise<ISelect> interface ISelect extends ITixWidget { add(name, cnf?): Promise<any> add$({ name, cnf }: { name, cnf?}): Promise<any> invoke(name): Promise<any> invoke$({ name }): Promise<any> } /** * Toplevel window. * * Subwidgets - None */ function Shell(master?, cnf?): Promise<IShell> function Shell$({ master, cnf }: { master?, cnf?}): Promise<IShell> interface IShell extends ITixWidget { } /** * Toplevel window, with popup popdown and center methods. * It tells the window manager that it is a dialog window and should be * treated specially. The exact treatment depends on the treatment of * the window manager. * * Subwidgets - None */ function DialogShell(master?, cnf?): Promise<IDialogShell> function DialogShell$({ master, cnf }: { master?, cnf?}): Promise<IDialogShell> interface IDialogShell extends ITixWidget { popdown(): Promise<any> popdown$($: {}): Promise<any> popup(): Promise<any> popup$($: {}): Promise<any> center(): Promise<any> center$($: {}): Promise<any> } /** * StdButtonBox - Standard Button Box (OK, Apply, Cancel and Help) */ function StdButtonBox(master?, cnf?): Promise<IStdButtonBox> function StdButtonBox$({ master, cnf }: { master?, cnf?}): Promise<IStdButtonBox> interface IStdButtonBox extends ITixWidget { invoke(name): Promise<any> invoke$({ name }): Promise<any> } /** * TList - Hierarchy display widget which can be * used to display data in a tabular format. The list entries of a TList * widget are similar to the entries in the Tk listbox widget. The main * differences are (1) the TList widget can display the list entries in a * two dimensional format and (2) you can use graphical images as well as * multiple colors and fonts for the list entries. * * Subwidgets - None */ function TList(master?, cnf?): Promise<ITList> function TList$({ master, cnf }: { master?, cnf?}): Promise<ITList> interface ITList extends ITixWidget { active_set(index): Promise<any> active_set$({ index }): Promise<any> active_clear(): Promise<any> active_clear$($: {}): Promise<any> anchor_set(index): Promise<any> anchor_set$({ index }): Promise<any> anchor_clear(): Promise<any> anchor_clear$($: {}): Promise<any> delete(from_, to?): Promise<any> delete$({ from_, to }: { from_, to?}): Promise<any> dragsite_set(index): Promise<any> dragsite_set$({ index }): Promise<any> dragsite_clear(): Promise<any> dragsite_clear$($: {}): Promise<any> dropsite_set(index): Promise<any> dropsite_set$({ index }): Promise<any> dropsite_clear(): Promise<any> dropsite_clear$($: {}): Promise<any> insert(index, cnf?): Promise<any> insert$({ index, cnf }: { index, cnf?}): Promise<any> info_active(): Promise<any> info_active$($: {}): Promise<any> info_anchor(): Promise<any> info_anchor$($: {}): Promise<any> info_down(index): Promise<any> info_down$({ index }): Promise<any> info_left(index): Promise<any> info_left$({ index }): Promise<any> info_right(index): Promise<any> info_right$({ index }): Promise<any> info_selection(): Promise<any> info_selection$($: {}): Promise<any> info_size(): Promise<any> info_size$($: {}): Promise<any> info_up(index): Promise<any> info_up$({ index }): Promise<any> nearest(x, y): Promise<any> nearest$({ x, y }): Promise<any> see(index): Promise<any> see$({ index }): Promise<any> selection_clear(cnf?): Promise<any> selection_clear$({ cnf }: { cnf?}): Promise<any> selection_includes(index): Promise<any> selection_includes$({ index }): Promise<any> selection_set(first, last?): Promise<any> selection_set$({ first, last }: { first, last?}): Promise<any> } /** * Tree - The tixTree widget can be used to display hierarchical * data in a tree form. The user can adjust * the view of the tree by opening or closing parts of the tree. */ function Tree(master?, cnf?): Promise<ITree> function Tree$({ master, cnf }: { master?, cnf?}): Promise<ITree> interface ITree extends ITixWidget { /** * This command calls the setmode method for all the entries in this * Tree widget: if an entry has no child entries, its mode is set to * none. Otherwise, if the entry has any hidden child entries, its mode is * set to open; otherwise its mode is set to close. */ autosetmode(): Promise<any> autosetmode$($: {}): Promise<any> /** * Close the entry given by entryPath if its mode is close. */ close(entrypath): Promise<any> close$({ entrypath }): Promise<any> /** * Returns the current mode of the entry given by entryPath. */ getmode(entrypath): Promise<any> getmode$({ entrypath }): Promise<any> /** * Open the entry given by entryPath if its mode is open. */ open(entrypath): Promise<any> open$({ entrypath }): Promise<any> /** * This command is used to indicate whether the entry given by * entryPath has children entries and whether the children are visible. mode * must be one of open, close or none. If mode is set to open, a (+) * indicator is drawn next the entry. If mode is set to close, a (-) * indicator is drawn next the entry. If mode is set to none, no * indicators will be drawn for this entry. The default mode is none. The * open mode indicates the entry has hidden children and this entry can be * opened by the user. The close mode indicates that all the children of the * entry are now visible and the entry can be closed by the user. */ setmode(entrypath, mode?): Promise<any> setmode$({ entrypath, mode }: { entrypath, mode?}): Promise<any> } /** * The CheckList widget * displays a list of items to be selected by the user. CheckList acts * similarly to the Tk checkbutton or radiobutton widgets, except it is * capable of handling many more items than checkbuttons or radiobuttons. * */ function CheckList(master?, cnf?): Promise<ICheckList> function CheckList$({ master, cnf }: { master?, cnf?}): Promise<ICheckList> interface ICheckList extends ITixWidget { /** * This command calls the setmode method for all the entries in this * Tree widget: if an entry has no child entries, its mode is set to * none. Otherwise, if the entry has any hidden child entries, its mode is * set to open; otherwise its mode is set to close. */ autosetmode(): Promise<any> autosetmode$($: {}): Promise<any> /** * Close the entry given by entryPath if its mode is close. */ close(entrypath): Promise<any> close$({ entrypath }): Promise<any> /** * Returns the current mode of the entry given by entryPath. */ getmode(entrypath): Promise<any> getmode$({ entrypath }): Promise<any> /** * Open the entry given by entryPath if its mode is open. */ open(entrypath): Promise<any> open$({ entrypath }): Promise<any> /** * Returns a list of items whose status matches status. If status is * not specified, the list of items in the "on" status will be returned. * Mode can be on, off, default */ getselection(mode?): Promise<any> getselection$({ mode }: { mode?}): Promise<any> /** * Returns the current status of entryPath. */ getstatus(entrypath): Promise<any> getstatus$({ entrypath }): Promise<any> /** * Sets the status of entryPath to be status. A bitmap will be * displayed next to the entry its status is on, off or default. */ setstatus(entrypath, mode?): Promise<any> setstatus$({ entrypath, mode }: { entrypath, mode?}): Promise<any> } interface I_dummyButton extends ITixSubWidget { } interface I_dummyCheckbutton extends ITixSubWidget { } interface I_dummyEntry extends ITixSubWidget { } interface I_dummyFrame extends ITixSubWidget { } interface I_dummyLabel extends ITixSubWidget { } interface I_dummyListbox extends ITixSubWidget { } interface I_dummyMenu extends ITixSubWidget { } interface I_dummyMenubutton extends ITixSubWidget { } interface I_dummyScrollbar extends ITixSubWidget { } interface I_dummyText extends ITixSubWidget { } interface I_dummyScrolledListBox extends IScrolledListBox, ITixSubWidget { } interface I_dummyHList extends IHList, ITixSubWidget { } interface I_dummyScrolledHList extends IScrolledHList, ITixSubWidget { } interface I_dummyTList extends ITList, ITixSubWidget { } interface I_dummyComboBox extends IComboBox, ITixSubWidget { } interface I_dummyDirList extends IDirList, ITixSubWidget { } interface I_dummyDirSelectBox extends IDirSelectBox, ITixSubWidget { } interface I_dummyExFileSelectBox extends IExFileSelectBox, ITixSubWidget { } interface I_dummyFileSelectBox extends IFileSelectBox, ITixSubWidget { } interface I_dummyFileComboBox extends IComboBox, ITixSubWidget { } interface I_dummyStdButtonBox extends IStdButtonBox, ITixSubWidget { } interface I_dummyNoteBookFrame extends INoteBookFrame, ITixSubWidget { } interface I_dummyPanedWindow extends IPanedWindow, ITixSubWidget { } /** * This file implements the Canvas Object View widget. This is a base * class of IconView. It implements automatic placement/adjustment of the * scrollbars according to the canvas objects inside the canvas subwidget. * The scrollbars are adjusted so that the canvas is just large enough * to see all the objects. * */ interface ICObjView extends ITixWidget { } /** * The Tix Grid command creates a new window and makes it into a * tixGrid widget. Additional options, may be specified on the command * line or in the option database to configure aspects such as its cursor * and relief. * * A Grid widget displays its contents in a two dimensional grid of cells. * Each cell may contain one Tix display item, which may be in text, * graphics or other formats. See the DisplayStyle class for more information * about Tix display items. Individual cells, or groups of cells, can be * formatted with a wide range of attributes, such as its color, relief and * border. * * Subwidgets - None */ function Grid(master?, cnf?): Promise<IGrid> function Grid$({ master, cnf }: { master?, cnf?}): Promise<IGrid> interface IGrid extends ITixWidget { /** * Removes the selection anchor. */ anchor_clear(): Promise<any> anchor_clear$($: {}): Promise<any> /** * Get the (x,y) coordinate of the current anchor cell */ anchor_get(): Promise<any> anchor_get$($: {}): Promise<any> /** * Set the selection anchor to the cell at (x, y). */ anchor_set(x, y): Promise<any> anchor_set$({ x, y }): Promise<any> /** * Delete rows between from_ and to inclusive. * If to is not provided, delete only row at from_ */ delete_row(from_, to?): Promise<any> delete_row$({ from_, to }: { from_, to?}): Promise<any> /** * Delete columns between from_ and to inclusive. * If to is not provided, delete only column at from_ */ delete_column(from_, to?): Promise<any> delete_column$({ from_, to }: { from_, to?}): Promise<any> /** * If any cell is being edited, de-highlight the cell and applies * the changes. */ edit_apply(): Promise<any> edit_apply$($: {}): Promise<any> /** * Highlights the cell at (x, y) for editing, if the -editnotify * command returns True for this cell. */ edit_set(x, y): Promise<any> edit_set$({ x, y }): Promise<any> /** * Get the option value for cell at (x,y) */ entrycget(x, y, option): Promise<any> entrycget$({ x, y, option }): Promise<any> entryconfigure(x, y, cnf?): Promise<any> entryconfigure$({ x, y, cnf }: { x, y, cnf?}): Promise<any> /** * Return True if display item exists at (x,y) */ info_exists(x, y): Promise<any> info_exists$({ x, y }): Promise<any> info_bbox(x, y): Promise<any> info_bbox$({ x, y }): Promise<any> /** * Moves the range of columns from position FROM through TO by * the distance indicated by OFFSET. For example, move_column(2, 4, 1) * moves the columns 2,3,4 to columns 3,4,5. */ move_column(from_, to, offset): Promise<any> move_column$({ from_, to, offset }): Promise<any> /** * Moves the range of rows from position FROM through TO by * the distance indicated by OFFSET. * For example, move_row(2, 4, 1) moves the rows 2,3,4 to rows 3,4,5. */ move_row(from_, to, offset): Promise<any> move_row$({ from_, to, offset }): Promise<any> /** * Return coordinate of cell nearest pixel coordinate (x,y) */ nearest(x, y): Promise<any> nearest$({ x, y }): Promise<any> set(x, y, itemtype?): Promise<any> set$({ x, y, itemtype }: { x, y, itemtype?}): Promise<any> /** * Queries or sets the size of the column given by * INDEX. INDEX may be any non-negative * integer that gives the position of a given column. * INDEX can also be the string "default"; in this case, this command * queries or sets the default size of all columns. * When no option-value pair is given, this command returns a tuple * containing the current size setting of the given column. When * option-value pairs are given, the corresponding options of the * size setting of the given column are changed. Options may be one * of the following: * pad0 pixels * Specifies the paddings to the left of a column. * pad1 pixels * Specifies the paddings to the right of a column. * size val * Specifies the width of a column. Val may be: * "auto" -- the width of the column is set to the * width of the widest cell in the column; * a valid Tk screen distance unit; * or a real number following by the word chars * (e.g. 3.4chars) that sets the width of the column to the * given number of characters. */ size_column(index): Promise<any> size_column$({ index }): Promise<any> /** * Queries or sets the size of the row given by * INDEX. INDEX may be any non-negative * integer that gives the position of a given row . * INDEX can also be the string "default"; in this case, this command * queries or sets the default size of all rows. * When no option-value pair is given, this command returns a list con- * taining the current size setting of the given row . When option-value * pairs are given, the corresponding options of the size setting of the * given row are changed. Options may be one of the following: * pad0 pixels * Specifies the paddings to the top of a row. * pad1 pixels * Specifies the paddings to the bottom of a row. * size val * Specifies the height of a row. Val may be: * "auto" -- the height of the row is set to the * height of the highest cell in the row; * a valid Tk screen distance unit; * or a real number following by the word chars * (e.g. 3.4chars) that sets the height of the row to the * given number of characters. */ size_row(index): Promise<any> size_row$({ index }): Promise<any> /** * Clears the cell at (x, y) by removing its display item. */ unset(x, y): Promise<any> unset$({ x, y }): Promise<any> } /** * Scrolled Grid widgets */ function ScrolledGrid(master?, cnf?): Promise<IScrolledGrid> function ScrolledGrid$({ master, cnf }: { master?, cnf?}): Promise<IScrolledGrid> interface IScrolledGrid extends IGrid { } let WINDOW: Promise<any> let TEXT: Promise<any> let STATUS: Promise<any> let IMMEDIATE: Promise<any> let IMAGE: Promise<any> let IMAGETEXT: Promise<any> let BALLOON: Promise<any> let AUTO: Promise<any> let ACROSSTOP: Promise<any> let ASCII: Promise<any> let CELL: Promise<any> let COLUMN: Promise<any> let DECREASING: Promise<any> let INCREASING: Promise<any> let INTEGER: Promise<any> let MAIN: Promise<any> let MAX: Promise<any> let REAL: Promise<any> let ROW: Promise<any> let S_REGION: Promise<any> let X_REGION: Promise<any> let Y_REGION: Promise<any> let TCL_DONT_WAIT: Promise<any> let TCL_WINDOW_EVENTS: Promise<any> let TCL_FILE_EVENTS: Promise<any> let TCL_TIMER_EVENTS: Promise<any> let TCL_IDLE_EVENTS: Promise<any> let TCL_ALL_EVENTS: Promise<any> } module ttk { var _ /** * Returns adict with its values converted from Tcl objects to Python * objects. */ function tclobjs_to_py(adict): Promise<any> function tclobjs_to_py$({ adict }): Promise<any> /** * If master is not None, itself is returned. If master is None, * the default master is returned if there is one, otherwise a new * master is created and returned. * * If it is not allowed to use the default root and master is None, * RuntimeError is raised. */ function setup_master(master?): Promise<any> function setup_master$({ master }: { master?}): Promise<any> /** * Manipulate style database. */ function Style(master?): Promise<IStyle> function Style$({ master }: { master?}): Promise<IStyle> interface IStyle { /** * Query or sets the default value of the specified option(s) in * style. * * Each key in kw is an option and each value is either a string or * a sequence identifying the value for that option. */ configure(style, query_opt?): Promise<any> configure$({ style, query_opt }: { style, query_opt?}): Promise<any> /** * Query or sets dynamic values of the specified option(s) in * style. * * Each key in kw is an option and each value should be a list or a * tuple (usually) containing statespecs grouped in tuples, or list, * or something else of your preference. A statespec is compound of * one or more states and then a value. */ map(style, query_opt?): Promise<any> map$({ style, query_opt }: { style, query_opt?}): Promise<any> /** * Returns the value specified for option in style. * * If state is specified it is expected to be a sequence of one * or more states. If the default argument is set, it is used as * a fallback value in case no specification for option is found. */ lookup(style, option, state?, def?): Promise<any> lookup$({ style, option, state, def }: { style, option, state?, def?}): Promise<any> /** * Define the widget layout for given style. If layoutspec is * omitted, return the layout specification for given style. * * layoutspec is expected to be a list or an object different than * None that evaluates to False if you want to "turn off" that style. * If it is a list (or tuple, or something else), each item should be * a tuple where the first item is the layout name and the second item * should have the format described below: * * LAYOUTS * * A layout can contain the value None, if takes no options, or * a dict of options specifying how to arrange the element. * The layout mechanism uses a simplified version of the pack * geometry manager: given an initial cavity, each element is * allocated a parcel. Valid options/values are: * * side: whichside * Specifies which side of the cavity to place the * element; one of top, right, bottom or left. If * omitted, the element occupies the entire cavity. * * sticky: nswe * Specifies where the element is placed inside its * allocated parcel. * * children: [sublayout... ] * Specifies a list of elements to place inside the * element. Each element is a tuple (or other sequence) * where the first item is the layout name, and the other * is a LAYOUT. */ layout(style, layoutspec?): Promise<any> layout$({ style, layoutspec }: { style, layoutspec?}): Promise<any> /** * Create a new element in the current theme of given etype. */ element_create(elementname, etype): Promise<any> element_create$({ elementname, etype }): Promise<any> /** * Returns the list of elements defined in the current theme. */ element_names(): Promise<any> element_names$($: {}): Promise<any> /** * Return the list of elementname's options. */ element_options(elementname): Promise<any> element_options$({ elementname }): Promise<any> /** * Creates a new theme. * * It is an error if themename already exists. If parent is * specified, the new theme will inherit styles, elements and * layouts from the specified parent theme. If settings are present, * they are expected to have the same syntax used for theme_settings. */ theme_create(themename, parent?, settings?): Promise<any> theme_create$({ themename, parent, settings }: { themename, parent?, settings?}): Promise<any> /** * Temporarily sets the current theme to themename, apply specified * settings and then restore the previous theme. * * Each key in settings is a style and each value may contain the * keys 'configure', 'map', 'layout' and 'element create' and they * are expected to have the same format as specified by the methods * configure, map, layout and element_create respectively. */ theme_settings(themename, settings): Promise<any> theme_settings$({ themename, settings }): Promise<any> /** * Returns a list of all known themes. */ theme_names(): Promise<any> theme_names$($: {}): Promise<any> /** * If themename is None, returns the theme in use, otherwise, set * the current theme to themename, refreshes all widgets and emits * a <<ThemeChanged>> event. */ theme_use(themename?): Promise<any> theme_use$({ themename }: { themename?}): Promise<any> } /** * Base class for Tk themed widgets. */ /** * Constructs a Ttk Widget with the parent master. * * STANDARD OPTIONS * * class, cursor, takefocus, style * * SCROLLABLE WIDGET OPTIONS * * xscrollcommand, yscrollcommand * * LABEL WIDGET OPTIONS * * text, textvariable, underline, image, compound, width * * WIDGET STATES * * active, disabled, focus, pressed, selected, background, * readonly, alternate, invalid * */ function Widget(master, widgetname, kw?): Promise<IWidget> function Widget$({ master, widgetname, kw }: { master, widgetname, kw?}): Promise<IWidget> interface IWidget { /** * Returns the name of the element at position x, y, or the empty * string if the point does not lie within any element. * * x and y are pixel coordinates relative to the widget. */ identify(x, y): Promise<any> identify$({ x, y }): Promise<any> /** * Test the widget's state. * * If callback is not specified, returns True if the widget state * matches statespec and False otherwise. If callback is specified, * then it will be invoked with *args, **kw if the widget state * matches statespec. statespec is expected to be a sequence. */ instate(statespec, callback?): Promise<any> instate$({ statespec, callback }: { statespec, callback?}): Promise<any> /** * Modify or inquire widget state. * * Widget state is returned if statespec is None, otherwise it is * set according to the statespec flags and then a new state spec * is returned indicating which flags were changed. statespec is * expected to be a sequence. */ state(statespec?): Promise<any> state$({ statespec }: { statespec?}): Promise<any> } /** * Ttk Button widget, displays a textual label and/or image, and * evaluates a command when pressed. */ /** * Construct a Ttk Button widget with the parent master. * * STANDARD OPTIONS * * class, compound, cursor, image, state, style, takefocus, * text, textvariable, underline, width * * WIDGET-SPECIFIC OPTIONS * * command, default, width * */ function Button(master?): Promise<IButton> function Button$({ master }: { master?}): Promise<IButton> interface IButton extends IWidget { /** * Invokes the command associated with the button. */ invoke(): Promise<any> invoke$($: {}): Promise<any> } /** * Ttk Checkbutton widget which is either in on- or off-state. */ /** * Construct a Ttk Checkbutton widget with the parent master. * * STANDARD OPTIONS * * class, compound, cursor, image, state, style, takefocus, * text, textvariable, underline, width * * WIDGET-SPECIFIC OPTIONS * * command, offvalue, onvalue, variable * */ function Checkbutton(master?): Promise<ICheckbutton> function Checkbutton$({ master }: { master?}): Promise<ICheckbutton> interface ICheckbutton extends IWidget { /** * Toggles between the selected and deselected states and * invokes the associated command. If the widget is currently * selected, sets the option variable to the offvalue option * and deselects the widget; otherwise, sets the option variable * to the option onvalue. * * Returns the result of the associated command. */ invoke(): Promise<any> invoke$($: {}): Promise<any> } /** * Ttk Entry widget displays a one-line text string and allows that * string to be edited by the user. */ /** * Constructs a Ttk Entry widget with the parent master. * * STANDARD OPTIONS * * class, cursor, style, takefocus, xscrollcommand * * WIDGET-SPECIFIC OPTIONS * * exportselection, invalidcommand, justify, show, state, * textvariable, validate, validatecommand, width * * VALIDATION MODES * * none, key, focus, focusin, focusout, all * */ function Entry(master?, widget?): Promise<IEntry> function Entry$({ master, widget }: { master?, widget?}): Promise<IEntry> interface IEntry extends IWidget { /** * Return a tuple of (x, y, width, height) which describes the * bounding box of the character given by index. */ bbox(index): Promise<any> bbox$({ index }): Promise<any> /** * Returns the name of the element at position x, y, or the * empty string if the coordinates are outside the window. */ identify(x, y): Promise<any> identify$({ x, y }): Promise<any> /** * Force revalidation, independent of the conditions specified * by the validate option. Returns False if validation fails, True * if it succeeds. Sets or clears the invalid state accordingly. */ validate(): Promise<any> validate$($: {}): Promise<any> } /** * Ttk Combobox widget combines a text field with a pop-down list of * values. */ /** * Construct a Ttk Combobox widget with the parent master. * * STANDARD OPTIONS * * class, cursor, style, takefocus * * WIDGET-SPECIFIC OPTIONS * * exportselection, justify, height, postcommand, state, * textvariable, values, width * */ function Combobox(master?): Promise<ICombobox> function Combobox$({ master }: { master?}): Promise<ICombobox> interface ICombobox extends IEntry { /** * If newindex is supplied, sets the combobox value to the * element at position newindex in the list of values. Otherwise, * returns the index of the current value in the list of values * or -1 if the current value does not appear in the list. */ current(newindex?): Promise<any> current$({ newindex }: { newindex?}): Promise<any> /** * Sets the value of the combobox to value. */ set(value): Promise<any> set$({ value }): Promise<any> } /** * Ttk Frame widget is a container, used to group other widgets * together. */ /** * Construct a Ttk Frame with parent master. * * STANDARD OPTIONS * * class, cursor, style, takefocus * * WIDGET-SPECIFIC OPTIONS * * borderwidth, relief, padding, width, height * */ function Frame(master?): Promise<IFrame> function Frame$({ master }: { master?}): Promise<IFrame> interface IFrame extends IWidget { } /** * Ttk Label widget displays a textual label and/or image. */ /** * Construct a Ttk Label with parent master. * * STANDARD OPTIONS * * class, compound, cursor, image, style, takefocus, text, * textvariable, underline, width * * WIDGET-SPECIFIC OPTIONS * * anchor, background, font, foreground, justify, padding, * relief, text, wraplength * */ function Label(master?): Promise<ILabel> function Label$({ master }: { master?}): Promise<ILabel> interface ILabel extends IWidget { } /** * Ttk Labelframe widget is a container used to group other widgets * together. It has an optional label, which may be a plain text string * or another widget. */ /** * Construct a Ttk Labelframe with parent master. * * STANDARD OPTIONS * * class, cursor, style, takefocus * * WIDGET-SPECIFIC OPTIONS * labelanchor, text, underline, padding, labelwidget, width, * height * */ function Labelframe(master?): Promise<ILabelframe> function Labelframe$({ master }: { master?}): Promise<ILabelframe> interface ILabelframe extends IWidget { } /** * Ttk Menubutton widget displays a textual label and/or image, and * displays a menu when pressed. */ /** * Construct a Ttk Menubutton with parent master. * * STANDARD OPTIONS * * class, compound, cursor, image, state, style, takefocus, * text, textvariable, underline, width * * WIDGET-SPECIFIC OPTIONS * * direction, menu * */ function Menubutton(master?): Promise<IMenubutton> function Menubutton$({ master }: { master?}): Promise<IMenubutton> interface IMenubutton extends IWidget { } /** * Ttk Notebook widget manages a collection of windows and displays * a single one at a time. Each child window is associated with a tab, * which the user may select to change the currently-displayed window. */ /** * Construct a Ttk Notebook with parent master. * * STANDARD OPTIONS * * class, cursor, style, takefocus * * WIDGET-SPECIFIC OPTIONS * * height, padding, width * * TAB OPTIONS * * state, sticky, padding, text, image, compound, underline * * TAB IDENTIFIERS (tab_id) * * The tab_id argument found in several methods may take any of * the following forms: * * * An integer between zero and the number of tabs * * The name of a child window * * A positional specification of the form "@x,y", which * defines the tab * * The string "current", which identifies the * currently-selected tab * * The string "end", which returns the number of tabs (only * valid for method index) * */ function Notebook(master?): Promise<INotebook> function Notebook$({ master }: { master?}): Promise<INotebook> interface INotebook extends IWidget { /** * Adds a new tab to the notebook. * * If window is currently managed by the notebook but hidden, it is * restored to its previous position. */ add(child): Promise<any> add$({ child }): Promise<any> /** * Removes the tab specified by tab_id, unmaps and unmanages the * associated window. */ forget(tab_id): Promise<any> forget$({ tab_id }): Promise<any> /** * Hides the tab specified by tab_id. * * The tab will not be displayed, but the associated window remains * managed by the notebook and its configuration remembered. Hidden * tabs may be restored with the add command. */ hide(tab_id): Promise<any> hide$({ tab_id }): Promise<any> /** * Returns the name of the tab element at position x, y, or the * empty string if none. */ identify(x, y): Promise<any> identify$({ x, y }): Promise<any> /** * Returns the numeric index of the tab specified by tab_id, or * the total number of tabs if tab_id is the string "end". */ index(tab_id): Promise<any> index$({ tab_id }): Promise<any> /** * Inserts a pane at the specified position. * * pos is either the string end, an integer index, or the name of * a managed child. If child is already managed by the notebook, * moves it to the specified position. */ insert(pos, child): Promise<any> insert$({ pos, child }): Promise<any> /** * Selects the specified tab. * * The associated child window will be displayed, and the * previously-selected window (if different) is unmapped. If tab_id * is omitted, returns the widget name of the currently selected * pane. */ select(tab_id?): Promise<any> select$({ tab_id }: { tab_id?}): Promise<any> /** * Query or modify the options of the specific tab_id. * * If kw is not given, returns a dict of the tab option values. If option * is specified, returns the value of that option. Otherwise, sets the * options to the corresponding values. */ tab(tab_id, option?): Promise<any> tab$({ tab_id, option }: { tab_id, option?}): Promise<any> /** * Returns a list of windows managed by the notebook. */ tabs(): Promise<any> tabs$($: {}): Promise<any> /** * Enable keyboard traversal for a toplevel window containing * this notebook. * * This will extend the bindings for the toplevel window containing * this notebook as follows: * * Control-Tab: selects the tab following the currently selected * one * * Shift-Control-Tab: selects the tab preceding the currently * selected one * * Alt-K: where K is the mnemonic (underlined) character of any * tab, will select that tab. * * Multiple notebooks in a single toplevel may be enabled for * traversal, including nested notebooks. However, notebook traversal * only works properly if all panes are direct children of the * notebook. */ enable_traversal(): Promise<any> enable_traversal$($: {}): Promise<any> } /** * Ttk Panedwindow widget displays a number of subwindows, stacked * either vertically or horizontally. */ /** * Construct a Ttk Panedwindow with parent master. * * STANDARD OPTIONS * * class, cursor, style, takefocus * * WIDGET-SPECIFIC OPTIONS * * orient, width, height * * PANE OPTIONS * * weight * */ function Panedwindow(master?): Promise<IPanedwindow> function Panedwindow$({ master }: { master?}): Promise<IPanedwindow> interface IPanedwindow extends IWidget { /** * Inserts a pane at the specified positions. * * pos is either the string end, and integer index, or the name * of a child. If child is already managed by the paned window, * moves it to the specified position. */ insert(pos, child): Promise<any> insert$({ pos, child }): Promise<any> /** * Query or modify the options of the specified pane. * * pane is either an integer index or the name of a managed subwindow. * If kw is not given, returns a dict of the pane option values. If * option is specified then the value for that option is returned. * Otherwise, sets the options to the corresponding values. */ pane(pane, option?): Promise<any> pane$({ pane, option }: { pane, option?}): Promise<any> /** * If newpos is specified, sets the position of sash number index. * * May adjust the positions of adjacent sashes to ensure that * positions are monotonically increasing. Sash positions are further * constrained to be between 0 and the total size of the widget. * * Returns the new position of sash number index. */ sashpos(index, newpos?): Promise<any> sashpos$({ index, newpos }: { index, newpos?}): Promise<any> } /** * Ttk Progressbar widget shows the status of a long-running * operation. They can operate in two modes: determinate mode shows the * amount completed relative to the total amount of work to be done, and * indeterminate mode provides an animated display to let the user know * that something is happening. */ /** * Construct a Ttk Progressbar with parent master. * * STANDARD OPTIONS * * class, cursor, style, takefocus * * WIDGET-SPECIFIC OPTIONS * * orient, length, mode, maximum, value, variable, phase * */ function Progressbar(master?): Promise<IProgressbar> function Progressbar$({ master }: { master?}): Promise<IProgressbar> interface IProgressbar extends IWidget { /** * Begin autoincrement mode: schedules a recurring timer event * that calls method step every interval milliseconds. * * interval defaults to 50 milliseconds (20 steps/second) if omitted. */ start(interval?): Promise<any> start$({ interval }: { interval?}): Promise<any> /** * Increments the value option by amount. * * amount defaults to 1.0 if omitted. */ step(amount?): Promise<any> step$({ amount }: { amount?}): Promise<any> /** * Stop autoincrement mode: cancels any recurring timer event * initiated by start. */ stop(): Promise<any> stop$($: {}): Promise<any> } /** * Ttk Radiobutton widgets are used in groups to show or change a * set of mutually-exclusive options. */ /** * Construct a Ttk Radiobutton with parent master. * * STANDARD OPTIONS * * class, compound, cursor, image, state, style, takefocus, * text, textvariable, underline, width * * WIDGET-SPECIFIC OPTIONS * * command, value, variable * */ function Radiobutton(master?): Promise<IRadiobutton> function Radiobutton$({ master }: { master?}): Promise<IRadiobutton> interface IRadiobutton extends IWidget { /** * Sets the option variable to the option value, selects the * widget, and invokes the associated command. * * Returns the result of the command, or an empty string if * no command is specified. */ invoke(): Promise<any> invoke$($: {}): Promise<any> } /** * Ttk Scale widget is typically used to control the numeric value of * a linked variable that varies uniformly over some range. */ /** * Construct a Ttk Scale with parent master. * * STANDARD OPTIONS * * class, cursor, style, takefocus * * WIDGET-SPECIFIC OPTIONS * * command, from, length, orient, to, value, variable * */ function Scale(master?): Promise<IScale> function Scale$({ master }: { master?}): Promise<IScale> interface IScale extends IWidget { /** * Modify or query scale options. * * Setting a value for any of the "from", "from_" or "to" options * generates a <<RangeChanged>> event. */ configure(cnf?): Promise<any> configure$({ cnf }: { cnf?}): Promise<any> /** * Get the current value of the value option, or the value * corresponding to the coordinates x, y if they are specified. * * x and y are pixel coordinates relative to the scale widget * origin. */ get(x?, y?): Promise<any> get$({ x, y }: { x?, y?}): Promise<any> } /** * Ttk Scrollbar controls the viewport of a scrollable widget. */ /** * Construct a Ttk Scrollbar with parent master. * * STANDARD OPTIONS * * class, cursor, style, takefocus * * WIDGET-SPECIFIC OPTIONS * * command, orient * */ function Scrollbar(master?): Promise<IScrollbar> function Scrollbar$({ master }: { master?}): Promise<IScrollbar> interface IScrollbar extends IWidget { } /** * Ttk Separator widget displays a horizontal or vertical separator * bar. */ /** * Construct a Ttk Separator with parent master. * * STANDARD OPTIONS * * class, cursor, style, takefocus * * WIDGET-SPECIFIC OPTIONS * * orient * */ function Separator(master?): Promise<ISeparator> function Separator$({ master }: { master?}): Promise<ISeparator> interface ISeparator extends IWidget { } /** * Ttk Sizegrip allows the user to resize the containing toplevel * window by pressing and dragging the grip. */ /** * Construct a Ttk Sizegrip with parent master. * * STANDARD OPTIONS * * class, cursor, state, style, takefocus * */ function Sizegrip(master?): Promise<ISizegrip> function Sizegrip$({ master }: { master?}): Promise<ISizegrip> interface ISizegrip extends IWidget { } /** * Ttk Spinbox is an Entry with increment and decrement arrows * * It is commonly used for number entry or to select from a list of * string values. * */ /** * Construct a Ttk Spinbox widget with the parent master. * * STANDARD OPTIONS * * class, cursor, style, takefocus, validate, * validatecommand, xscrollcommand, invalidcommand * * WIDGET-SPECIFIC OPTIONS * * to, from_, increment, values, wrap, format, command * */ function Spinbox(master?): Promise<ISpinbox> function Spinbox$({ master }: { master?}): Promise<ISpinbox> interface ISpinbox extends IEntry { /** * Sets the value of the Spinbox to value. */ set(value): Promise<any> set$({ value }): Promise<any> } /** * Ttk Treeview widget displays a hierarchical collection of items. * * Each item has a textual label, an optional image, and an optional list * of data values. The data values are displayed in successive columns * after the tree label. */ /** * Construct a Ttk Treeview with parent master. * * STANDARD OPTIONS * * class, cursor, style, takefocus, xscrollcommand, * yscrollcommand * * WIDGET-SPECIFIC OPTIONS * * columns, displaycolumns, height, padding, selectmode, show * * ITEM OPTIONS * * text, image, values, open, tags * * TAG OPTIONS * * foreground, background, font, image * */ function Treeview(master?): Promise<ITreeview> function Treeview$({ master }: { master?}): Promise<ITreeview> interface ITreeview extends IWidget { /** * Returns the bounding box (relative to the treeview widget's * window) of the specified item in the form x y width height. * * If column is specified, returns the bounding box of that cell. * If the item is not visible (i.e., if it is a descendant of a * closed item or is scrolled offscreen), returns an empty string. */ bbox(item, column?): Promise<any> bbox$({ item, column }: { item, column?}): Promise<any> /** * Returns a tuple of children belonging to item. * * If item is not specified, returns root children. */ get_children(item?): Promise<any> get_children$({ item }: { item?}): Promise<any> /** * Replaces item's child with newchildren. * * Children present in item that are not present in newchildren * are detached from tree. No items in newchildren may be an * ancestor of item. */ set_children(item): Promise<any> set_children$({ item }): Promise<any> /** * Query or modify the options for the specified column. * * If kw is not given, returns a dict of the column option values. If * option is specified then the value for that option is returned. * Otherwise, sets the options to the corresponding values. */ column(column, option?): Promise<any> column$({ column, option }: { column, option?}): Promise<any> /** * Delete all specified items and all their descendants. The root * item may not be deleted. */ delete(): Promise<any> delete$($: {}): Promise<any> /** * Unlinks all of the specified items from the tree. * * The items and all of their descendants are still present, and may * be reinserted at another point in the tree, but will not be * displayed. The root item may not be detached. */ detach(): Promise<any> detach$($: {}): Promise<any> /** * Returns True if the specified item is present in the tree, * False otherwise. */ exists(item): Promise<any> exists$({ item }): Promise<any> /** * If item is specified, sets the focus item to item. Otherwise, * returns the current focus item, or '' if there is none. */ focus(item?): Promise<any> focus$({ item }: { item?}): Promise<any> /** * Query or modify the heading options for the specified column. * * If kw is not given, returns a dict of the heading option values. If * option is specified then the value for that option is returned. * Otherwise, sets the options to the corresponding values. * * Valid options/values are: * text: text * The text to display in the column heading * image: image_name * Specifies an image to display to the right of the column * heading * anchor: anchor * Specifies how the heading text should be aligned. One of * the standard Tk anchor values * command: callback * A callback to be invoked when the heading label is * pressed. * * To configure the tree column heading, call this with column = "#0" */ heading(column, option?): Promise<any> heading$({ column, option }: { column, option?}): Promise<any> /** * Returns a description of the specified component under the * point given by x and y, or the empty string if no such component * is present at that position. */ identify(component, x, y): Promise<any> identify$({ component, x, y }): Promise<any> /** * Returns the item ID of the item at position y. */ identify_row(y): Promise<any> identify_row$({ y }): Promise<any> /** * Returns the data column identifier of the cell at position x. * * The tree column has ID #0. */ identify_column(x): Promise<any> identify_column$({ x }): Promise<any> /** * Returns one of: * * heading: Tree heading area. * separator: Space between two columns headings; * tree: The tree area. * cell: A data cell. * * * Availability: Tk 8.6 */ identify_region(x, y): Promise<any> identify_region$({ x, y }): Promise<any> /** * Returns the element at position x, y. * * * Availability: Tk 8.6 */ identify_element(x, y): Promise<any> identify_element$({ x, y }): Promise<any> /** * Returns the integer index of item within its parent's list * of children. */ index(item): Promise<any> index$({ item }): Promise<any> /** * Creates a new item and return the item identifier of the newly * created item. * * parent is the item ID of the parent item, or the empty string * to create a new top-level item. index is an integer, or the value * end, specifying where in the list of parent's children to insert * the new item. If index is less than or equal to zero, the new node * is inserted at the beginning, if index is greater than or equal to * the current number of children, it is inserted at the end. If iid * is specified, it is used as the item identifier, iid must not * already exist in the tree. Otherwise, a new unique identifier * is generated. */ insert(parent, index, iid?): Promise<any> insert$({ parent, index, iid }: { parent, index, iid?}): Promise<any> /** * Query or modify the options for the specified item. * * If no options are given, a dict with options/values for the item * is returned. If option is specified then the value for that option * is returned. Otherwise, sets the options to the corresponding * values as given by kw. */ item(item, option?): Promise<any> item$({ item, option }: { item, option?}): Promise<any> /** * Moves item to position index in parent's list of children. * * It is illegal to move an item under one of its descendants. If * index is less than or equal to zero, item is moved to the * beginning, if greater than or equal to the number of children, * it is moved to the end. If item was detached it is reattached. */ move(item, parent, index): Promise<any> move$({ item, parent, index }): Promise<any> /** * Returns the identifier of item's next sibling, or '' if item * is the last child of its parent. */ next(item): Promise<any> next$({ item }): Promise<any> /** * Returns the ID of the parent of item, or '' if item is at the * top level of the hierarchy. */ parent(item): Promise<any> parent$({ item }): Promise<any> /** * Returns the identifier of item's previous sibling, or '' if * item is the first child of its parent. */ prev(item): Promise<any> prev$({ item }): Promise<any> /** * Ensure that item is visible. * * Sets all of item's ancestors open option to True, and scrolls * the widget if necessary so that item is within the visible * portion of the tree. */ see(item): Promise<any> see$({ item }): Promise<any> /** * Returns the tuple of selected items. */ selection(): Promise<any> selection$($: {}): Promise<any> /** * The specified items becomes the new selection. */ selection_set(): Promise<any> selection_set$($: {}): Promise<any> /** * Add all of the specified items to the selection. */ selection_add(): Promise<any> selection_add$($: {}): Promise<any> /** * Remove all of the specified items from the selection. */ selection_remove(): Promise<any> selection_remove$($: {}): Promise<any> /** * Toggle the selection state of each specified item. */ selection_toggle(): Promise<any> selection_toggle$($: {}): Promise<any> /** * Query or set the value of given item. * * With one argument, return a dictionary of column/value pairs * for the specified item. With two arguments, return the current * value of the specified column. With three arguments, set the * value of given column in given item to the specified value. */ set(item, column?, value?): Promise<any> set$({ item, column, value }: { item, column?, value?}): Promise<any> /** * Bind a callback for the given event sequence to the tag tagname. * When an event is delivered to an item, the callbacks for each * of the item's tags option are called. */ tag_bind(tagname, sequence?, callback?): Promise<any> tag_bind$({ tagname, sequence, callback }: { tagname, sequence?, callback?}): Promise<any> /** * Query or modify the options for the specified tagname. * * If kw is not given, returns a dict of the option settings for tagname. * If option is specified, returns the value for that option for the * specified tagname. Otherwise, sets the options to the corresponding * values for the given tagname. */ tag_configure(tagname, option?): Promise<any> tag_configure$({ tagname, option }: { tagname, option?}): Promise<any> /** * If item is specified, returns 1 or 0 depending on whether the * specified item has the given tagname. Otherwise, returns a list of * all items which have the specified tag. * * * Availability: Tk 8.6 */ tag_has(tagname, item?): Promise<any> tag_has$({ tagname, item }: { tagname, item?}): Promise<any> reattach } /** * A Ttk Scale widget with a Ttk Label widget indicating its * current value. * * The Ttk Scale can be accessed through instance.scale, and Ttk Label * can be accessed through instance.label */ /** * Construct a horizontal LabeledScale with parent master, a * variable to be associated with the Ttk Scale widget and its range. * If variable is not specified, a tkinter.IntVar is created. * * WIDGET-SPECIFIC OPTIONS * * compound: 'top' or 'bottom' * Specifies how to display the label relative to the scale. * Defaults to 'top'. * */ function LabeledScale(master?, variable?, from_?, to?): Promise<ILabeledScale> function LabeledScale$({ master, variable, from_, to }: { master?, variable?, from_?, to?}): Promise<ILabeledScale> interface ILabeledScale extends IFrame { /** * Destroy this widget and possibly its associated variable. */ destroy(): Promise<any> destroy$($: {}): Promise<any> /** * Return current scale value. */ value(): Promise<any> value$($: {}): Promise<any> /** * Set new scale value. */ value(val): Promise<any> value$({ val }): Promise<any> } /** * Themed OptionMenu, based after tkinter's OptionMenu, which allows * the user to select a value from a menu. */ /** * Construct a themed OptionMenu widget with master as the parent, * the resource textvariable set to variable, the initially selected * value specified by the default parameter, the menu values given by * *values and additional keywords. * * WIDGET-SPECIFIC OPTIONS * * style: stylename * Menubutton style. * direction: 'above', 'below', 'left', 'right', or 'flush' * Menubutton direction. * command: callback * A callback that will be invoked after selecting an item. * */ function OptionMenu(master, variable, def?): Promise<IOptionMenu> function OptionMenu$({ master, variable, def }: { master, variable, def?}): Promise<IOptionMenu> interface IOptionMenu extends IMenubutton { /** * Build a new menu of radiobuttons with *values and optionally * a default value. */ set_menu(def?): Promise<any> set_menu$({ def }: { def?}): Promise<any> /** * Destroy this widget and its associated variable. */ destroy(): Promise<any> destroy$($: {}): Promise<any> } let LabelFrame: Promise<any> let PanedWindow: Promise<any> } } declare module turtledemo { module chaos { var _ function f(x): Promise<any> function f$({ x }): Promise<any> function g(x): Promise<any> function g$({ x }): Promise<any> function h(x): Promise<any> function h$({ x }): Promise<any> function jumpto(x, y): Promise<any> function jumpto$({ x, y }): Promise<any> function line(x1, y1, x2, y2): Promise<any> function line$({ x1, y1, x2, y2 }): Promise<any> function coosys(): Promise<any> function coosys$($: {}): Promise<any> function plot(fun, start, color): Promise<any> function plot$({ fun, start, color }): Promise<any> function main(): Promise<any> function main$($: {}): Promise<any> let N: Promise<any> } } declare module uuid { var _ /** * Get the hardware address as a 48-bit positive integer. * * The first time this runs, it may launch a separate program, which could * be quite slow. If all attempts to obtain the hardware address fail, we * choose a random 48-bit number with its eighth bit set to 1 as recommended * in RFC 4122. * */ function getnode(): Promise<any> function getnode$($: {}): Promise<any> /** * Generate a UUID from a host ID, sequence number, and the current time. * If 'node' is not given, getnode() is used to obtain the hardware * address. If 'clock_seq' is given, it is used as the sequence number; * otherwise a random 14-bit sequence number is chosen. */ function uuid1(node?, clock_seq?): Promise<any> function uuid1$({ node, clock_seq }: { node?, clock_seq?}): Promise<any> /** * Generate a UUID from the MD5 hash of a namespace UUID and a name. */ function uuid3(namespace, name): Promise<any> function uuid3$({ namespace, name }): Promise<any> /** * Generate a random UUID. */ function uuid4(): Promise<any> function uuid4$($: {}): Promise<any> /** * Generate a UUID from the SHA-1 hash of a namespace UUID and a name. */ function uuid5(namespace, name): Promise<any> function uuid5$({ namespace, name }): Promise<any> interface ISafeUUID { safe unsafe unknown } /** * Instances of the UUID class represent UUIDs as specified in RFC 4122. * UUID objects are immutable, hashable, and usable as dictionary keys. * Converting a UUID to a string with str() yields something in the form * '12345678-1234-1234-1234-123456789abc'. The UUID constructor accepts * five possible forms: a similar string of hexadecimal digits, or a tuple * of six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and * 48-bit values respectively) as an argument named 'fields', or a string * of 16 bytes (with all the integer fields in big-endian order) as an * argument named 'bytes', or a string of 16 bytes (with the first three * fields in little-endian order) as an argument named 'bytes_le', or a * single 128-bit integer as an argument named 'int'. * * UUIDs have these read-only attributes: * * bytes the UUID as a 16-byte string (containing the six * integer fields in big-endian byte order) * * bytes_le the UUID as a 16-byte string (with time_low, time_mid, * and time_hi_version in little-endian byte order) * * fields a tuple of the six integer fields of the UUID, * which are also available as six individual attributes * and two derived attributes: * * time_low the first 32 bits of the UUID * time_mid the next 16 bits of the UUID * time_hi_version the next 16 bits of the UUID * clock_seq_hi_variant the next 8 bits of the UUID * clock_seq_low the next 8 bits of the UUID * node the last 48 bits of the UUID * * time the 60-bit timestamp * clock_seq the 14-bit sequence number * * hex the UUID as a 32-character hexadecimal string * * int the UUID as a 128-bit integer * * urn the UUID as a URN as specified in RFC 4122 * * variant the UUID variant (one of the constants RESERVED_NCS, * RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE) * * version the UUID version number (1 through 5, meaningful only * when the variant is RFC_4122) * * is_safe An enum indicating whether the UUID has been generated in * a way that is safe for multiprocessing applications, via * uuid_generate_time_safe(3). * */ /** * Create a UUID from either a string of 32 hexadecimal digits, * a string of 16 bytes as the 'bytes' argument, a string of 16 bytes * in little-endian order as the 'bytes_le' argument, a tuple of six * integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, * 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as * the 'fields' argument, or a single 128-bit integer as the 'int' * argument. When a string of hex digits is given, curly braces, * hyphens, and a URN prefix are all optional. For example, these * expressions all yield the same UUID: * * UUID('{12345678-1234-5678-1234-567812345678}') * UUID('12345678123456781234567812345678') * UUID('urn:uuid:12345678-1234-5678-1234-567812345678') * UUID(bytes='\x12\x34\x56\x78'*4) * UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' + * '\x12\x34\x56\x78\x12\x34\x56\x78') * UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)) * UUID(int=0x12345678123456781234567812345678) * * Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must * be given. The 'version' argument is optional; if given, the resulting * UUID will have its variant and version set according to RFC 4122, * overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'. * * is_safe is an enum exposed as an attribute on the instance. It * indicates whether the UUID has been generated in a way that is safe * for multiprocessing applications, via uuid_generate_time_safe(3). * */ function UUID(hex?, bytes?, bytes_le?, fields?, int?, version?): Promise<IUUID> function UUID$({ hex, bytes, bytes_le, fields, int, version }: { hex?, bytes?, bytes_le?, fields?, int?, version?}): Promise<IUUID> interface IUUID { bytes(): Promise<any> bytes$($: {}): Promise<any> bytes_le(): Promise<any> bytes_le$($: {}): Promise<any> fields(): Promise<any> fields$($: {}): Promise<any> time_low(): Promise<any> time_low$($: {}): Promise<any> time_mid(): Promise<any> time_mid$($: {}): Promise<any> time_hi_version(): Promise<any> time_hi_version$($: {}): Promise<any> clock_seq_hi_variant(): Promise<any> clock_seq_hi_variant$($: {}): Promise<any> clock_seq_low(): Promise<any> clock_seq_low$($: {}): Promise<any> time(): Promise<any> time$($: {}): Promise<any> clock_seq(): Promise<any> clock_seq$($: {}): Promise<any> node(): Promise<any> node$($: {}): Promise<any> hex(): Promise<any> hex$($: {}): Promise<any> urn(): Promise<any> urn$($: {}): Promise<any> variant(): Promise<any> variant$($: {}): Promise<any> version(): Promise<any> version$($: {}): Promise<any> } let int_: Promise<any> let bytes_: Promise<any> let NAMESPACE_DNS: Promise<any> let NAMESPACE_URL: Promise<any> let NAMESPACE_OID: Promise<any> let NAMESPACE_X500: Promise<any> } declare module zipfile { var _ /** * Quickly see if a file is a ZIP file by checking the magic number. * * The filename argument may be a file or file-like object too. * */ function is_zipfile(filename): Promise<any> function is_zipfile$({ filename }): Promise<any> function main(args?): Promise<any> function main$({ args }: { args?}): Promise<any> interface IBadZipFile { } /** * * Raised when writing a zipfile, the zipfile requires ZIP64 extensions * and those extensions are disabled. * */ interface ILargeZipFile { } /** * Class with attributes describing each file in the ZIP archive. */ function ZipInfo(filename?, date_time?): Promise<IZipInfo> function ZipInfo$({ filename, date_time }: { filename?, date_time?}): Promise<IZipInfo> interface IZipInfo { /** * Return the per-file header as a bytes object. */ FileHeader(zip64?): Promise<any> FileHeader$({ zip64 }: { zip64?}): Promise<any> /** * Construct an appropriate ZipInfo for a file on the filesystem. * * filename should be the path to a file or directory on the filesystem. * * arcname is the name which it will have within the archive (by default, * this will be the same as filename, but without a drive letter and with * leading path separators removed). * */ from_file(filename, arcname?): Promise<any> from_file$({ filename, arcname }: { filename, arcname?}): Promise<any> /** * Return True if this archive member is a directory. */ is_dir(): Promise<any> is_dir$($: {}): Promise<any> } function LZMACompressor(): Promise<ILZMACompressor> function LZMACompressor$({ }): Promise<ILZMACompressor> interface ILZMACompressor { compress(data): Promise<any> compress$({ data }): Promise<any> flush(): Promise<any> flush$($: {}): Promise<any> } function LZMADecompressor(): Promise<ILZMADecompressor> function LZMADecompressor$({ }): Promise<ILZMADecompressor> interface ILZMADecompressor { decompress(data): Promise<any> decompress$({ data }): Promise<any> } interface I_SharedFile { seek(offset, whence?): Promise<any> seek$({ offset, whence }: { offset, whence?}): Promise<any> read(n?): Promise<any> read$({ n }: { n?}): Promise<any> close(): Promise<any> close$($: {}): Promise<any> } interface I_Tellable { write(data): Promise<any> write$({ data }): Promise<any> tell(): Promise<any> tell$($: {}): Promise<any> flush(): Promise<any> flush$($: {}): Promise<any> close(): Promise<any> close$($: {}): Promise<any> } /** * File-like object for reading an archive member. * Is returned by ZipFile.open(). * */ function ZipExtFile(fileobj, mode, zipinfo, pwd?, close_fileobj?: boolean): Promise<IZipExtFile> function ZipExtFile$({ fileobj, mode, zipinfo, pwd, close_fileobj }: { fileobj, mode, zipinfo, pwd?, close_fileobj?}): Promise<IZipExtFile> interface IZipExtFile { /** * Read and return a line from the stream. * * If limit is specified, at most limit bytes will be read. * */ readline(limit?): Promise<any> readline$({ limit }: { limit?}): Promise<any> /** * Returns buffered bytes without advancing the position. */ peek(n?): Promise<any> peek$({ n }: { n?}): Promise<any> readable(): Promise<any> readable$($: {}): Promise<any> /** * Read and return up to n bytes. * If the argument is omitted, None, or negative, data is read and returned until EOF is reached. * */ read(n?): Promise<any> read$({ n }: { n?}): Promise<any> /** * Read up to n bytes with at most one read() system call. */ read1(n): Promise<any> read1$({ n }): Promise<any> close(): Promise<any> close$($: {}): Promise<any> seekable(): Promise<any> seekable$($: {}): Promise<any> seek(offset, whence?): Promise<any> seek$({ offset, whence }: { offset, whence?}): Promise<any> tell(): Promise<any> tell$($: {}): Promise<any> MAX_N MIN_READ_SIZE MAX_SEEK_READ } interface I_ZipWriteFile { writable(): Promise<any> writable$($: {}): Promise<any> write(data): Promise<any> write$({ data }): Promise<any> close(): Promise<any> close$($: {}): Promise<any> } /** * Class with methods to open, read, write, close, list zip files. * * z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True, * compresslevel=None) * * file: Either the path to the file, or a file-like object. * If it is a path, the file will be opened and closed by ZipFile. * mode: The mode can be either read 'r', write 'w', exclusive create 'x', * or append 'a'. * compression: ZIP_STORED (no compression), ZIP_DEFLATED (requires zlib), * ZIP_BZIP2 (requires bz2) or ZIP_LZMA (requires lzma). * allowZip64: if True ZipFile will create files with ZIP64 extensions when * needed, otherwise it will raise an exception when this would * be necessary. * compresslevel: None (default for the given compression type) or an integer * specifying the level to pass to the compressor. * When using ZIP_STORED or ZIP_LZMA this keyword has no effect. * When using ZIP_DEFLATED integers 0 through 9 are accepted. * When using ZIP_BZIP2 integers 1 through 9 are accepted. * * */ /** * Open the ZIP file with mode read 'r', write 'w', exclusive create 'x', * or append 'a'. */ function ZipFile(file, mode?, compression?, allowZip64?: boolean, compresslevel?): Promise<IZipFile> function ZipFile$({ file, mode, compression, allowZip64, compresslevel }: { file, mode?, compression?, allowZip64?, compresslevel?}): Promise<IZipFile> interface IZipFile { /** * Return a list of file names in the archive. */ namelist(): Promise<any> namelist$($: {}): Promise<any> /** * Return a list of class ZipInfo instances for files in the * archive. */ infolist(): Promise<any> infolist$($: {}): Promise<any> /** * Print a table of contents for the zip file. */ printdir(file?): Promise<any> printdir$({ file }: { file?}): Promise<any> /** * Read all the files and check the CRC. */ testzip(): Promise<any> testzip$($: {}): Promise<any> /** * Return the instance of ZipInfo given 'name'. */ getinfo(name): Promise<any> getinfo$({ name }): Promise<any> /** * Set default password for encrypted files. */ setpassword(pwd): Promise<any> setpassword$({ pwd }): Promise<any> /** * The comment text associated with the ZIP file. */ comment(): Promise<any> comment$($: {}): Promise<any> comment(comment): Promise<any> comment$({ comment }): Promise<any> /** * Return file bytes for name. */ read(name, pwd?): Promise<any> read$({ name, pwd }: { name, pwd?}): Promise<any> /** * Return file-like object for 'name'. * * name is a string for the file name within the ZIP file, or a ZipInfo * object. * * mode should be 'r' to read a file already in the ZIP file, or 'w' to * write to a file newly added to the archive. * * pwd is the password to decrypt files (only used for reading). * * When writing, if the file size is not known in advance but may exceed * 2 GiB, pass force_zip64 to use the ZIP64 format, which can handle large * files. If the size is known in advance, it is best to pass a ZipInfo * instance for name, with zinfo.file_size set. * */ open(name, mode?, pwd?): Promise<any> open$({ name, mode, pwd }: { name, mode?, pwd?}): Promise<any> /** * Extract a member from the archive to the current working directory, * using its full name. Its file information is extracted as accurately * as possible. `member' may be a filename or a ZipInfo object. You can * specify a different directory using `path'. * */ extract(member, path?, pwd?): Promise<any> extract$({ member, path, pwd }: { member, path?, pwd?}): Promise<any> /** * Extract all members from the archive to the current working * directory. `path' specifies a different directory to extract to. * `members' is optional and must be a subset of the list returned * by namelist(). * */ extractall(path?, members?, pwd?): Promise<any> extractall$({ path, members, pwd }: { path?, members?, pwd?}): Promise<any> /** * Put the bytes from filename into the archive under the name * arcname. */ write(filename, arcname?, compress_type?, compresslevel?): Promise<any> write$({ filename, arcname, compress_type, compresslevel }: { filename, arcname?, compress_type?, compresslevel?}): Promise<any> /** * Write a file into the archive. The contents is 'data', which * may be either a 'str' or a 'bytes' instance; if it is a 'str', * it is encoded as UTF-8 first. * 'zinfo_or_arcname' is either a ZipInfo instance or * the name of the file in the archive. */ writestr(zinfo_or_arcname, data, compress_type?, compresslevel?): Promise<any> writestr$({ zinfo_or_arcname, data, compress_type, compresslevel }: { zinfo_or_arcname, data, compress_type?, compresslevel?}): Promise<any> /** * Close the file, and for mode 'w', 'x' and 'a' write the ending * records. */ close(): Promise<any> close$($: {}): Promise<any> fp } /** * Class to create ZIP archives with Python library files and packages. */ function PyZipFile(file, mode?, compression?, allowZip64?: boolean, optimize?): Promise<IPyZipFile> function PyZipFile$({ file, mode, compression, allowZip64, optimize }: { file, mode?, compression?, allowZip64?, optimize?}): Promise<IPyZipFile> interface IPyZipFile extends IZipFile { /** * Add all files from "pathname" to the ZIP archive. * * If pathname is a package directory, search the directory and * all package subdirectories recursively for all *.py and enter * the modules into the archive. If pathname is a plain * directory, listdir *.py and enter all modules. Else, pathname * must be a Python *.py file and the module will be put into the * archive. Added modules are always module.pyc. * This method will compile the module.py into module.pyc if * necessary. * If filterfunc(pathname) is given, it is called with every argument. * When it is False, the file or directory is skipped. * */ writepy(pathname, basename?, filterfunc?): Promise<any> writepy$({ pathname, basename, filterfunc }: { pathname, basename?, filterfunc?}): Promise<any> } /** * * A ZipFile subclass that ensures that implied directories * are always included in the namelist. * */ interface ICompleteDirs extends IZipFile { namelist(): Promise<any> namelist$($: {}): Promise<any> /** * * If the name represents a directory, return that name * as a directory (with the trailing slash). * */ resolve_dir(name): Promise<any> resolve_dir$({ name }): Promise<any> /** * * Given a source (filename or zipfile), return an * appropriate CompleteDirs subclass. * */ make(source): Promise<any> make$({ source }): Promise<any> } /** * * ZipFile subclass to ensure implicit * dirs exist and are resolved rapidly. * */ interface IFastLookup extends ICompleteDirs { namelist(): Promise<any> namelist$($: {}): Promise<any> } /** * * A pathlib-compatible interface for zip files. * * Consider a zip file with this structure:: * * . * ├── a.txt * └── b * ├── c.txt * └── d * └── e.txt * * >>> data = io.BytesIO() * >>> zf = ZipFile(data, 'w') * >>> zf.writestr('a.txt', 'content of a') * >>> zf.writestr('b/c.txt', 'content of c') * >>> zf.writestr('b/d/e.txt', 'content of e') * >>> zf.filename = 'mem/abcde.zip' * * Path accepts the zipfile object itself or a filename * * >>> root = Path(zf) * * From there, several path operations are available. * * Directory iteration (including the zip file itself): * * >>> a, b = root.iterdir() * >>> a * Path('mem/abcde.zip', 'a.txt') * >>> b * Path('mem/abcde.zip', 'b/') * * name property: * * >>> b.name * 'b' * * join with divide operator: * * >>> c = b / 'c.txt' * >>> c * Path('mem/abcde.zip', 'b/c.txt') * >>> c.name * 'c.txt' * * Read text: * * >>> c.read_text() * 'content of c' * * existence: * * >>> c.exists() * True * >>> (b / 'missing.txt').exists() * False * * Coercion to string: * * >>> import os * >>> str(c).replace(os.sep, posixpath.sep) * 'mem/abcde.zip/b/c.txt' * * At the root, ``name``, ``filename``, and ``parent`` * resolve to the zipfile. Note these attributes are not * valid and will raise a ``ValueError`` if the zipfile * has no filename. * * >>> root.name * 'abcde.zip' * >>> str(root.filename).replace(os.sep, posixpath.sep) * 'mem/abcde.zip' * >>> str(root.parent) * 'mem' * */ /** * * Construct a Path from a ZipFile or filename. * * Note: When the source is an existing ZipFile object, * its type (__class__) will be mutated to a * specialized type. If the caller wishes to retain the * original type, the caller should either create a * separate ZipFile object or pass a filename. * */ function Path(root, at?): Promise<IPath> function Path$({ root, at }: { root, at?}): Promise<IPath> interface IPath { /** * * Open this entry as text or binary following the semantics * of ``pathlib.Path.open()`` by passing arguments through * to io.TextIOWrapper(). * */ open(mode?): Promise<any> open$({ mode }: { mode?}): Promise<any> name(): Promise<any> name$($: {}): Promise<any> suffix(): Promise<any> suffix$($: {}): Promise<any> suffixes(): Promise<any> suffixes$($: {}): Promise<any> stem(): Promise<any> stem$($: {}): Promise<any> filename(): Promise<any> filename$($: {}): Promise<any> read_text(): Promise<any> read_text$($: {}): Promise<any> read_bytes(): Promise<any> read_bytes$($: {}): Promise<any> is_dir(): Promise<any> is_dir$($: {}): Promise<any> is_file(): Promise<any> is_file$($: {}): Promise<any> exists(): Promise<any> exists$($: {}): Promise<any> iterdir(): Promise<any> iterdir$($: {}): Promise<any> joinpath(): Promise<any> joinpath$($: {}): Promise<any> parent(): Promise<any> parent$($: {}): Promise<any> } let crc32: Promise<any> let error: Promise<any> let BadZipfile: Promise<any> let ZIP64_LIMIT: Promise<any> let ZIP_FILECOUNT_LIMIT: Promise<any> let ZIP_MAX_COMMENT: Promise<any> let ZIP_STORED: Promise<any> let ZIP_DEFLATED: Promise<any> let ZIP_BZIP2: Promise<any> let ZIP_LZMA: Promise<any> let DEFAULT_VERSION: Promise<any> let ZIP64_VERSION: Promise<any> let BZIP2_VERSION: Promise<any> let LZMA_VERSION: Promise<any> let MAX_EXTRACT_VERSION: Promise<any> let structEndArchive: Promise<any> let stringEndArchive: Promise<any> let sizeEndCentDir: Promise<any> let structCentralDir: Promise<any> let stringCentralDir: Promise<any> let sizeCentralDir: Promise<any> let structFileHeader: Promise<any> let stringFileHeader: Promise<any> let sizeFileHeader: Promise<any> let structEndArchive64Locator: Promise<any> let stringEndArchive64Locator: Promise<any> let sizeEndCentDir64Locator: Promise<any> let structEndArchive64: Promise<any> let stringEndArchive64: Promise<any> let sizeEndCentDir64: Promise<any> let compressor_names: Promise<any> } type PyObjectType<T> = T extends "astexport" ? typeof astexport : T extends "base64" ? typeof base64 : T extends "codecs" ? typeof codecs : T extends "colorsys" ? typeof colorsys : T extends "crypt" ? typeof crypt : T extends "decimal" ? typeof decimal : T extends "email.base64mime" ? typeof email.base64mime : T extends "encodings.base64_codec" ? typeof encodings.base64_codec : T extends "encodings.bz2_codec" ? typeof encodings.bz2_codec : T extends "encodings.hex_codec" ? typeof encodings.hex_codec : T extends "encodings.palmos" ? typeof encodings.palmos : T extends "encodings.quopri_codec" ? typeof encodings.quopri_codec : T extends "encodings.uu_codec" ? typeof encodings.uu_codec : T extends "encodings.zlib_codec" ? typeof encodings.zlib_codec : T extends "export" ? typeof export : T extends "gzip" ? typeof gzip : T extends "hashlib" ? typeof hashlib : T extends "idlelib.codecontext" ? typeof idlelib.codecontext : T extends "idlelib.statusbar" ? typeof idlelib.statusbar : T extends "os" ? typeof os : T extends "platform" ? typeof platform : T extends "pstats" ? typeof pstats : T extends "signal" ? typeof signal : T extends "socket" ? typeof socket : T extends "socketserver" ? typeof socketserver : T extends "sqlite3.dbapi2" ? typeof sqlite3.dbapi2 : T extends "sqlite3.dump" ? typeof sqlite3.dump : T extends "stat" ? typeof stat : T extends "statistics" ? typeof statistics : T extends "tarfile" ? typeof tarfile : T extends "threading" ? typeof threading : T extends "tkinter.colorchooser" ? typeof tkinter.colorchooser : T extends "tkinter.commondialog" ? typeof tkinter.commondialog : T extends "tkinter.constants" ? typeof tkinter.constants : T extends "tkinter.dialog" ? typeof tkinter.dialog : T extends "tkinter.dnd" ? typeof tkinter.dnd : T extends "tkinter.filedialog" ? typeof tkinter.filedialog : T extends "tkinter.font" ? typeof tkinter.font : T extends "tkinter.messagebox" ? typeof tkinter.messagebox : T extends "tkinter.scrolledtext" ? typeof tkinter.scrolledtext : T extends "tkinter.simpledialog" ? typeof tkinter.simpledialog : T extends "tkinter.tix" ? typeof tkinter.tix : T extends "tkinter.ttk" ? typeof tkinter.ttk : T extends "turtledemo.chaos" ? typeof turtledemo.chaos : T extends "uuid" ? typeof uuid : T extends "zipfile" ? typeof zipfile : T extends "sqlite3" ? typeof sqlite3 : T extends "tkinter" ? typeof tkinter : object; type PyTypeName = "astexport" | "base64" | "codecs" | "colorsys" | "crypt" | "decimal" | "email.base64mime" | "encodings.base64_codec" | "encodings.bz2_codec" | "encodings.hex_codec" | "encodings.palmos" | "encodings.quopri_codec" | "encodings.uu_codec" | "encodings.zlib_codec" | "export" | "gzip" | "hashlib" | "idlelib.codecontext" | "idlelib.statusbar" | "os" | "platform" | "pstats" | "signal" | "socket" | "socketserver" | "sqlite3.dbapi2" | "sqlite3.dump" | "stat" | "statistics" | "tarfile" | "threading" | "tkinter.colorchooser" | "tkinter.commondialog" | "tkinter.constants" | "tkinter.dialog" | "tkinter.dnd" | "tkinter.filedialog" | "tkinter.font" | "tkinter.messagebox" | "tkinter.scrolledtext" | "tkinter.simpledialog" | "tkinter.tix" | "tkinter.ttk" | "turtledemo.chaos" | "uuid" | "zipfile" | "sqlite3" | "tkinter";
the_stack
import { TestBed } from '@angular/core/testing'; import { WindowRef } from '@spartacus/core'; import { Observable, of } from 'rxjs'; import { BREAKPOINT, LayoutConfig } from '../config/layout-config'; import { BreakpointService } from './breakpoint.service'; class MockWindowRef { nativeWindow = { innerWidth: 1000, }; get resize$(): Observable<any> { return of(); } } const MockWindow = { target: { innerWidth: 0, }, }; // unordered config const mockConfig: LayoutConfig = { breakpoints: {}, }; describe('BreakpointService', () => { let service: BreakpointService; let config: LayoutConfig; let windowRef: WindowRef; beforeEach(() => { TestBed.configureTestingModule({ providers: [ { provide: WindowRef, useClass: MockWindowRef }, { provide: LayoutConfig, useValue: mockConfig }, BreakpointService, ], }); config = TestBed.inject(LayoutConfig); windowRef = TestBed.inject(WindowRef); }); it('should be created', () => { service = TestBed.inject(BreakpointService); expect(service).toBeTruthy(); }); describe('resolve sorted breakpoints from config', () => { it('should resolve [xs,sm,md,lg,xl] from config', () => { config.breakpoints = { xl: { min: 1200, }, sm: { min: 576, max: 768, }, lg: { max: 1200, }, md: 992, xs: 576, }; service = TestBed.inject(BreakpointService); expect(service.breakpoints).toEqual([ BREAKPOINT.xs, BREAKPOINT.sm, BREAKPOINT.md, BREAKPOINT.lg, BREAKPOINT.xl, ]); }); it('should resolve [sm,xl] by numeric values', () => { config.breakpoints = { xl: 1200, sm: 768, }; service = TestBed.inject(BreakpointService); expect(service.breakpoints).toEqual([BREAKPOINT.sm, BREAKPOINT.xl]); }); it('should resolve [sm,xl] by min values', () => { config.breakpoints = { xl: { min: 1200, }, sm: { min: 576, }, }; service = TestBed.inject(BreakpointService); expect(service.breakpoints).toEqual([BREAKPOINT.sm, BREAKPOINT.xl]); }); it('should resolve [sm,xl] by min and max', () => { config.breakpoints = { xl: { min: 1200, }, sm: { max: 768, }, }; service = TestBed.inject(BreakpointService); expect(service.breakpoints).toEqual([BREAKPOINT.sm, BREAKPOINT.xl]); }); it('should resolve [sm,xl] by min and numeric', () => { config.breakpoints = { xl: { min: 1200, }, sm: 768, }; service = TestBed.inject(BreakpointService); expect(service.breakpoints).toEqual([BREAKPOINT.sm, BREAKPOINT.xl]); }); it('should resolve [xs,lg] by bin and default values', () => { config.breakpoints = config.breakpoints = { xs: 576, lg: { min: 992, }, }; service = TestBed.inject(BreakpointService); expect(service.breakpoints).toEqual(['xs', 'lg'] as any); }); it('should resolve any screen', () => { // type augmentation allows for this config.breakpoints = { screen: { min: 1200, }, any: 768, } as any; service = TestBed.inject(BreakpointService); expect(service.breakpoints).toEqual(['any', 'screen'] as any); }); }); describe('breakpoint size', () => { beforeEach(() => { config.breakpoints = { xs: 576, sm: { max: 768, }, md: { min: 768, max: 992, }, lg: { min: 992, }, xl: { min: 1200, }, }; service = TestBed.inject(BreakpointService); }); it('should return maximum 576 for XS', () => { const size = service.getSize(BREAKPOINT.xs); expect(size).toEqual(576); }); it('should return maximum 768 for SM', () => { const size = service.getSize(BREAKPOINT.sm); expect(size).toEqual(768); }); it('should return maximum 992 for MD', () => { const size = service.getSize(BREAKPOINT.md); expect(size).toEqual(992); }); it('should return maximum 1200 for LG', () => { const size = service.getSize(BREAKPOINT.lg); expect(size).toEqual(1200); }); it('should return falsy for XL', () => { const size = service.getSize(BREAKPOINT.xl); expect(size).toBeFalsy(); }); it('should return falsy for unknown screen', () => { const size = service.getSize('unknown' as any); expect(size).toBeFalsy(); }); }); describe('with current window size', () => { beforeEach(() => { config.breakpoints = { xs: 576, sm: 768, md: 992, lg: 1200, xl: { min: 1200, }, }; }); it('should return xs for < 576', () => { MockWindow.target.innerWidth = 575; spyOnProperty(windowRef, 'resize$').and.returnValue(of(MockWindow)); service = TestBed.inject(BreakpointService); let result: BREAKPOINT; service.breakpoint$.subscribe((br) => (result = br)).unsubscribe(); expect(result).toEqual(BREAKPOINT.xs); }); it('should return sm for < 768', () => { MockWindow.target.innerWidth = 767; spyOnProperty(windowRef, 'resize$').and.returnValue(of(MockWindow)); service = TestBed.inject(BreakpointService); let result: BREAKPOINT; service.breakpoint$.subscribe((br) => (result = br)).unsubscribe(); expect(result).toEqual(BREAKPOINT.sm); }); it('should return md for < 992', () => { MockWindow.target.innerWidth = 991; spyOnProperty(windowRef, 'resize$').and.returnValue(of(MockWindow)); service = TestBed.inject(BreakpointService); let result: BREAKPOINT; service.breakpoint$.subscribe((br) => (result = br)).unsubscribe(); expect(result).toEqual(BREAKPOINT.md); }); it('should return lg for < 1200', () => { MockWindow.target.innerWidth = 1199; spyOnProperty(windowRef, 'resize$').and.returnValue(of(MockWindow)); service = TestBed.inject(BreakpointService); let result: BREAKPOINT; service.breakpoint$.subscribe((br) => (result = br)).unsubscribe(); expect(result).toEqual(BREAKPOINT.lg); }); it('should return xl for >= 1201', () => { MockWindow.target.innerWidth = 1201; spyOnProperty(windowRef, 'resize$').and.returnValue(of(MockWindow)); service = TestBed.inject(BreakpointService); let result: BREAKPOINT; service.breakpoint$.subscribe((br) => (result = br)).unsubscribe(); expect(result).toEqual(BREAKPOINT.xl); }); }); describe('match size', () => { beforeEach(() => { config.breakpoints = { xs: 500, // xs = > 500 sm: 700, // sm = 501 - 700 md: 900, // md = 701 - 900 lg: 1200, // lg = 901 - 1200 xl: { min: 1200, }, }; }); describe('isEqual', () => { const isEqual = (screenSize: number, breakpoint: BREAKPOINT): boolean => { MockWindow.target.innerWidth = screenSize; spyOnProperty(windowRef, 'resize$').and.returnValue(of(MockWindow)); service = TestBed.inject(BreakpointService); let result: boolean; service .isEqual(breakpoint) .subscribe((br) => (result = br)) .unsubscribe(); return result; }; it('should return true if current screen size is 0', () => { expect(isEqual(0, BREAKPOINT.xs)).toBeTruthy(); }); it('should return equals for xs on largest size', () => { expect(isEqual(500 - 1, BREAKPOINT.xs)).toBeTruthy(); }); it('should return true if current screen size equals sm', () => { expect(isEqual(700 - 1, BREAKPOINT.sm)).toBeTruthy(); }); it('should return true if current screen size equals md', () => { expect(isEqual(900 - 1, BREAKPOINT.md)).toBeTruthy(); }); it('should return true if current screen size equals lg', () => { expect(isEqual(1200 - 1, BREAKPOINT.lg)).toBeTruthy(); }); it('should return true if current screen size equals xl', () => { expect(isEqual(1300, BREAKPOINT.xl)).toBeTruthy(); }); it('should return false if current screen is larger than xs', () => { expect(isEqual(500, BREAKPOINT.xs)).toBeFalsy(); }); it('should return false if current screen is larger than sm', () => { expect(isEqual(700, BREAKPOINT.sm)).toBeFalsy(); }); it('should return false if current screen is larger than md', () => { expect(isEqual(900, BREAKPOINT.md)).toBeFalsy(); }); it('should return false if current screen is larger than lg', () => { expect(isEqual(1200, BREAKPOINT.lg)).toBeFalsy(); }); }); describe('isDown', () => { const isDown = (screenSize: number, breakpoint: BREAKPOINT): boolean => { MockWindow.target.innerWidth = screenSize; spyOnProperty(windowRef, 'resize$').and.returnValue(of(MockWindow)); service = TestBed.inject(BreakpointService); let result: boolean; service .isDown(breakpoint) .subscribe((br) => (result = br)) .unsubscribe(); return result; }; it('should return true if window width < xs', () => { expect(isDown(500 - 1, BREAKPOINT.xs)).toBeTruthy(); }); it('should return true if window width < sm', () => { expect(isDown(700 - 1, BREAKPOINT.sm)).toBeTruthy(); }); it('should return true if window width < md', () => { expect(isDown(900 - 1, BREAKPOINT.md)).toBeTruthy(); }); it('should return true if window width < lg', () => { expect(isDown(1200 - 1, BREAKPOINT.lg)).toBeTruthy(); }); it('should return false if window width >= xs', () => { expect(isDown(500, BREAKPOINT.xs)).toBeFalsy(); }); it('should return false if window width >= sm', () => { expect(isDown(700, BREAKPOINT.sm)).toBeFalsy(); }); it('should return false if window width >= md', () => { expect(isDown(900, BREAKPOINT.md)).toBeFalsy(); }); it('should return falsy if window width >= lg', () => { expect(isDown(1200, BREAKPOINT.lg)).toBeFalsy(); }); }); describe('isUp', () => { const isUp = (screenSize: number, breakpoint: BREAKPOINT): boolean => { MockWindow.target.innerWidth = screenSize; spyOnProperty(windowRef, 'resize$').and.returnValue(of(MockWindow)); service = TestBed.inject(BreakpointService); let result: boolean; service .isUp(breakpoint) .subscribe((br) => (result = br)) .unsubscribe(); return result; }; it('should return true for xs', () => { expect(isUp(1, BREAKPOINT.xs)).toBeTruthy(); }); it('should return false if window width < sm', () => { expect(isUp(500 - 1, BREAKPOINT.sm)).toBeFalsy(); }); it('should return false if window width < md', () => { expect(isUp(700 - 1, BREAKPOINT.md)).toBeFalsy(); }); it('should return false if window width < lg', () => { expect(isUp(900 - 1, BREAKPOINT.lg)).toBeFalsy(); }); it('should return false if window width < xl', () => { expect(isUp(1200 - 1, BREAKPOINT.xl)).toBeFalsy(); }); it('should return true if window width > xs', () => { expect(isUp(1, BREAKPOINT.xs)).toBeTruthy(); }); it('should return true if window width > sm', () => { expect(isUp(500 + 1, BREAKPOINT.sm)).toBeTruthy(); }); it('should return true if window width > md', () => { expect(isUp(700 + 1, BREAKPOINT.md)).toBeTruthy(); }); it('should return true if window width > lg', () => { expect(isUp(900 + 1, BREAKPOINT.lg)).toBeTruthy(); }); it('should return true if window width > xl', () => { expect(isUp(1200 + 1, BREAKPOINT.xl)).toBeTruthy(); }); }); }); });
the_stack
import ITimerListener = etch.engine.ITimerListener; declare var requestAnimFrame: any; declare module etch.engine { class ClockTimer { private _Listeners; private _LastTime; RegisterTimer(listener: ITimerListener): void; UnregisterTimer(listener: ITimerListener): void; private _DoTick(); private _RequestAnimationTick(); } } declare module etch.primitives { class Vector { x: number; y: number; constructor(x: number, y: number); Get(): Vector; Set(x: number, y: number): void; Add(v: Vector): void; static Add(v1: Vector, v2: Vector): Vector; Clone(): Vector; static LERP(start: Vector, end: Vector, p: number): Vector; Sub(v: Vector): void; static Sub(v1: Vector, v2: Vector): Vector; Mult(n: number): void; static Mult(v1: Vector, v2: Vector): Vector; static MultN(v1: Vector, n: number): Vector; Div(n: number): void; static Div(v1: Vector, v2: Vector): Vector; static DivN(v1: Vector, n: number): Vector; Mag(): number; MagSq(): number; Normalize(): void; Limit(max: number): void; Heading(): number; static Random2D(): Vector; static FromAngle(angle: number): Vector; ToPoint(): Point; } } declare module etch.exceptions { class Exception { Message: string; constructor(message: string); toString(): string; } class ArgumentException extends Exception { constructor(message: string); } class ArgumentNullException extends Exception { constructor(message: string); } class InvalidOperationException extends Exception { constructor(message: string); } class NotSupportedException extends Exception { constructor(message: string); } class IndexOutOfRangeException extends Exception { constructor(index: number); } class ArgumentOutOfRangeException extends Exception { constructor(msg: string); } class AttachException extends Exception { Data: any; constructor(message: string, data: any); } class InvalidJsonException extends Exception { JsonText: string; InnerException: Error; constructor(jsonText: string, innerException: Error); } class TargetInvocationException extends Exception { InnerException: Exception; constructor(message: string, innerException: Exception); } class UnknownTypeException extends Exception { FullTypeName: string; constructor(fullTypeName: string); } class FormatException extends Exception { constructor(message: string); } } import INotifyCollectionChanged = etch.events.INotifyCollectionChanged; declare module etch.collections { class ObservableCollection<T> implements nullstone.IEnumerable<T>, nullstone.ICollection<T>, INotifyCollectionChanged, INotifyPropertyChanged { private _ht; getEnumerator(): nullstone.IEnumerator<T>; CollectionChanged: nullstone.Event<CollectionChangedEventArgs>; PropertyChanged: nullstone.Event<PropertyChangedEventArgs>; Count: number; ToArray(): T[]; GetValueAt(index: number): T; SetValueAt(index: number, value: T): void; Add(value: T): void; AddRange(values: T[]): void; Insert(index: number, value: T): void; IndexOf(value: T): number; Contains(value: T): boolean; Remove(value: T): boolean; RemoveAt(index: number): void; Clear(): void; private _RaisePropertyChanged(propertyName); } } /// <reference path="Engine/ClockTimer.d.ts" /> /// <reference path="Primitives/Vector.d.ts" /> /// <reference path="Exceptions/Exceptions.d.ts" /> /// <reference path="Collections/ObservableCollection.d.ts" /> declare module etch.collections { class PropertyChangedEventArgs implements nullstone.IEventArgs { PropertyName: string; constructor(propertyName: string); } interface INotifyPropertyChanged { PropertyChanged: nullstone.Event<PropertyChangedEventArgs>; } var INotifyPropertyChanged_: nullstone.Interface<INotifyPropertyChanged>; } import Size = minerva.Size; declare module etch.drawing { class Canvas implements IDisplayContext { HTMLElement: HTMLCanvasElement; IsCached: boolean; constructor(); Ctx: CanvasRenderingContext2D; Width: number; Height: number; Size: Size; Style: any; } } declare module etch.drawing { class DisplayObject implements IDisplayObject { private _DisplayList; DeltaTime: number; FrameCount: number; Height: number; IsCached: boolean; IsInitialised: boolean; IsPaused: boolean; IsVisible: boolean; LastVisualTick: number; Position: Point; DrawFrom: IDisplayContext; DrawTo: IDisplayContext; Width: number; ZIndex: number; Init(drawTo: IDisplayContext, drawFrom?: IDisplayContext): void; Ctx: CanvasRenderingContext2D; CanvasWidth: number; CanvasHeight: number; DisplayList: DisplayObjectCollection<IDisplayObject>; Setup(): void; Update(): void; Draw(): void; IsFirstFrame(): boolean; Dispose(): void; Play(): void; Pause(): void; Resize(): void; Show(): void; Hide(): void; } } import ObservableCollection = etch.collections.ObservableCollection; declare module etch.drawing { class DisplayObjectCollection<T extends IDisplayObject> extends ObservableCollection<T> { constructor(); Swap(obj1: T, obj2: T): void; ToFront(obj: T): void; ToBack(obj: T): void; SetIndex(obj: T, index: number): void; Bottom: T; Top: T; } } declare module etch.drawing { interface IDisplayContext { Ctx: CanvasRenderingContext2D; Width: number; Height: number; IsCached: boolean; } } import DisplayObjectCollection = etch.drawing.DisplayObjectCollection; import IDisplayContext = etch.drawing.IDisplayContext; import Point = etch.primitives.Point; declare module etch.drawing { interface IDisplayObject extends IDisplayContext { CanvasHeight: number; CanvasWidth: number; Ctx: CanvasRenderingContext2D; DeltaTime: number; DisplayList: DisplayObjectCollection<IDisplayObject>; Draw(): void; DrawFrom: IDisplayContext; DrawTo: IDisplayContext; FrameCount: number; Height: number; Hide(): void; Init(drawTo: IDisplayContext, drawFrom?: IDisplayContext): void; IsInitialised: boolean; IsPaused: boolean; IsVisible: boolean; LastVisualTick: number; Pause(): void; Play(): void; Position: Point; Resize(): void; Setup(): void; Show(): void; Update(): void; Width: number; ZIndex: number; } } import ClockTimer = etch.engine.ClockTimer; import DisplayObject = etch.drawing.DisplayObject; import IDisplayObject = etch.drawing.IDisplayObject; declare module etch.drawing { class Stage extends DisplayObject implements ITimerListener { private _MaxDelta; DeltaTime: number; LastVisualTick: number; Timer: ClockTimer; Updated: nullstone.Event<number>; Drawn: nullstone.Event<number>; constructor(maxDelta?: number); Init(drawTo: IDisplayContext): void; OnTicked(lastTime: number, nowTime: number): void; UpdateDisplayList(displayList: DisplayObjectCollection<IDisplayObject>): void; DrawDisplayList(displayList: DisplayObjectCollection<IDisplayObject>): void; ResizeDisplayList(displayList: DisplayObjectCollection<IDisplayObject>): void; Resize(): void; } } declare module etch.engine { interface ITimerListener { OnTicked(lastTime: number, nowTime: number): any; } } declare module etch.events { enum CollectionChangedAction { Add = 1, Remove = 2, Replace = 3, Reset = 4, } class CollectionChangedEventArgs implements nullstone.IEventArgs { Action: CollectionChangedAction; OldStartingIndex: number; NewStartingIndex: number; OldItems: any[]; NewItems: any[]; static Reset(allValues: any[]): CollectionChangedEventArgs; static Replace(newValue: any, oldValue: any, index: number): CollectionChangedEventArgs; static Add(newValue: any, index: number): CollectionChangedEventArgs; static AddRange(newValues: any[], index: number): CollectionChangedEventArgs; static Remove(oldValue: any, index: number): CollectionChangedEventArgs; } } import CollectionChangedEventArgs = etch.events.CollectionChangedEventArgs; declare module etch.events { interface INotifyCollectionChanged { CollectionChanged: nullstone.Event<CollectionChangedEventArgs>; } var INotifyCollectionChanged_: nullstone.Interface<INotifyCollectionChanged>; } declare module etch.events { class PropertyChangedEventArgs implements nullstone.IEventArgs { PropertyName: string; constructor(propertyName: string); } interface INotifyPropertyChanged { PropertyChanged: nullstone.Event<PropertyChangedEventArgs>; } var INotifyPropertyChanged_: nullstone.Interface<INotifyPropertyChanged>; } import RoutedEventArgs = etch.events.RoutedEventArgs; declare module etch.events { class RoutedEvent<T extends RoutedEventArgs> extends nullstone.Event<T> { } } declare module etch.events { class RoutedEventArgs implements nullstone.IEventArgs { Handled: boolean; Source: any; OriginalSource: any; } } declare module etch.primitives { class Point extends minerva.Point { Clone(): Point; ToVector(): Vector; } }
the_stack
import { Component, OnInit, Inject } from '@angular/core'; import { Http, RequestOptions, Headers } from '@angular/http'; import { Question } from '../models/Question'; import { User } from '../models/User'; import * as microsoftTeams from '@microsoft/teams-js' import * as AdaptiveCards from "adaptivecards"; import * as markdownit from "markdown-it"; import * as moment from 'moment-timezone'; import { AppService } from '../app.service'; import { ActivatedRoute, Router } from '@angular/router'; import { AuthService } from '../auth.service'; import { environment } from 'src/environments/environment'; @Component({ selector: 'home', templateUrl: './home.component.html' }) export class HomeComponent implements OnInit { appService: AppService; route: ActivatedRoute; questions: Question[]; unansweredQuestions: Question[]; answeredQuestions: Question[]; currentUser: User; currentTopic: string; answeredContentVisible: boolean = true; unansweredContentVisible: boolean = true; isIframe: boolean; constructor(appService: AppService, route: ActivatedRoute, public authService: AuthService) { this.authService.onAuthUpdate(this.populateQuestions.bind(this)); this.appService = appService; this.route = route; this.isIframe = window !== window.parent && !window.opener; var upnParam = this.route.snapshot.queryParamMap.get("upn"); if (upnParam) environment.upn = upnParam //console.log("upn: " + upn); var tidParam = this.route.snapshot.queryParamMap.get("tid"); if (tidParam) environment.tid = tidParam //console.log("tid: " + tid); var gidParam = this.route.snapshot.queryParamMap.get("gid"); if (gidParam) environment.gid = gidParam //console.log("gid: " + gid); var cnameParam = this.route.snapshot.queryParamMap.get("cname"); if (cnameParam) environment.cname = cnameParam //console.log("cname: " + cname); authService.getToken(); } ngOnInit(): void { // get teams context // initialize teams } populateQuestions() { //alert("loggedIn: " + this.authService.loggedIn); this.appService.setHeaders(); this.appService.getUserByUpn(environment.upn).subscribe(result => { this.currentUser = result; }, error => console.error(error)); // get questions this.appService.getQuestionsByGroup(environment.gid).subscribe(result => { this.questions = result; if (environment.cname.toLowerCase() == "general") { this.currentTopic = "All"; } else { this.currentTopic = environment.cname; this.questions = result.filter(x => x.topic.trim().toLowerCase() == this.currentTopic.toLowerCase()); } this.unansweredQuestions = this.questions .filter(x => x.questionStatus.trim() == "unanswered") .sort((a, b) => { return new Date(b.questionSubmitted).getTime() - new Date(a.questionSubmitted).getTime(); }); this.answeredQuestions = this.questions .filter(x => x.questionStatus.trim() == "answered") .sort((a, b) => { return new Date(b.questionAnswered).getTime() - new Date(a.questionAnswered).getTime(); }); // create cards --- performance?? var cardHolderDiv; /*** UNANSWERED ***/ var unansweredFragment = document.createDocumentFragment(); if (this.unansweredQuestions.length > 0) { // iterate over questions this.unansweredQuestions.forEach(q => { cardHolderDiv = document.createElement("div"); cardHolderDiv.setAttribute("id", "unansweredCardHolder"); cardHolderDiv.setAttribute("class", "cardHolder"); cardHolderDiv.appendChild(this.createCard(q)); unansweredFragment.appendChild(cardHolderDiv); }); } else { cardHolderDiv = document.createElement("div"); cardHolderDiv.setAttribute("class", "cardHolder"); cardHolderDiv.innerHTML = "<div style=\"padding: 10px;\">There are no unanswered questions.</div>"; unansweredFragment.appendChild(cardHolderDiv); } // And finally insert it somewhere in your page: document.getElementById("unansweredCardDiv").appendChild(unansweredFragment); /*** ANSWERED ***/ var answeredFragment = document.createDocumentFragment(); if (this.answeredQuestions.length > 0) { // iterate over questions this.answeredQuestions.forEach(q => { cardHolderDiv = document.createElement("div"); cardHolderDiv.setAttribute("id", "answeredCardHolder") cardHolderDiv.setAttribute("class", "cardHolder") cardHolderDiv.appendChild(this.createCard(q)); answeredFragment.appendChild(cardHolderDiv); }); } else { cardHolderDiv = document.createElement("div"); cardHolderDiv.setAttribute("class", "cardHolder"); cardHolderDiv.innerHTML = "<div style=\"padding: 10px;\">There are no answered questions.</div>"; answeredFragment.appendChild(cardHolderDiv); } // And finally insert it somewhere in your page: document.getElementById("answeredCardDiv").appendChild(answeredFragment); }, error => console.error(error)); } createCard(question: Question): any { let answerPosterName = ""; if (question.answerPoster != null) answerPosterName = question.answerPoster.fullName; var cardUnanswered = { "$schema": "https://adaptivecards.io/schemas/adaptive-card.json", "type": "AdaptiveCard", "version": "1.0", "style": "emphasis", "body": [ { "type": "Container", "items": [ { "type": "ColumnSet", "columns": [ { "type": "Column", "width": "stretch", "items": [ { "type": "TextBlock", "text": question.topic, "size": "medium" }, { "type": "TextBlock", "text": question.questionText, "weight": "bolder", "wrap": true, "size": "medium" }, { "type": "TextBlock", "text": question.answerText, "weight": "bolder", "wrap": true, "size": "medium", "color": "good" } ] }, { "type": "Column", "width": "auto", "items": [ { "type": "ColumnSet", "columns": [ { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "text": "Submitted: ", "weight": "bolder", "wrap": true } ] }, { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "text": question.originalPoster.fullName, "weight": "bolder", "wrap": true }, { "type": "TextBlock", "spacing": "none", "text": moment.utc(question.questionSubmitted).local().format("DD MMM YYYY, hh:mm a"), "isSubtle": true, "wrap": true } ] } ] } ] } ] } ] } ], "actions": [ { "type": "Action.OpenUrl", "title": "View Conversation", "url": question.link } ] } var cardAnswered = { "$schema": "https://adaptivecards.io/schemas/adaptive-card.json", "type": "AdaptiveCard", "version": "1.0", "style": "emphasis", "body": [ { "type": "Container", "items": [ { "type": "ColumnSet", "columns": [ { "type": "Column", "width": "stretch", "items": [ { "type": "TextBlock", "text": question.topic, "size": "medium" }, { "type": "TextBlock", "text": question.questionText, "weight": "bolder", "wrap": true, "size": "medium" }, { "type": "TextBlock", "text": question.answerText, "weight": "bolder", "wrap": true, "size": "medium", "color": "good" } ] }, { "type": "Column", "width": "auto", "items": [ { "type": "ColumnSet", "columns": [ { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "text": "Submitted: ", "weight": "bolder", "wrap": true } ] }, { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "text": question.originalPoster.fullName, "weight": "bolder", "wrap": true }, { "type": "TextBlock", "spacing": "none", "text": moment.utc(question.questionSubmitted).local().format("DD MMM YYYY, hh:mm a"), "isSubtle": true, "wrap": true } ] } ] }, { "type": "ColumnSet", "columns": [ { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "text": "Answered: ", "weight": "bolder", "wrap": true } ] }, { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "text": answerPosterName, "weight": "bolder", "wrap": true }, { "type": "TextBlock", "spacing": "none", "text": moment.utc(question.questionAnswered).local().format("DD MMM YYYY, hh:mm a"), "isSubtle": true, "wrap": true } ] } ] } ] } ] } ] } ], "actions": [ { "type": "Action.OpenUrl", "title": "View Conversation", "url": question.link } ] } var cardUnansweredMobile = { "$schema": "https://adaptivecards.io/schemas/adaptive-card.json", "type": "AdaptiveCard", "version": "1.0", "style": "emphasis", "body": [ { "type": "Container", "items": [ { "type": "TextBlock", "text": question.questionText, "weight": "bolder", "wrap": true, "size": "small" }, { "type": "TextBlock", "text": question.answerText, "wrap": true, "size": "small", "color": "good" }, { "type": "ColumnSet", "columns": [ { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "text": "Submitted: ", "weight": "bolder", "size": "small", "wrap": true } ] }, { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "text": question.originalPoster.fullName, "size": "small", "wrap": true } ] }, { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "spacing": "none", "size": "small", "text": moment.utc(question.questionSubmitted).local().format("DD MMM YYYY, hh:mm a"), "isSubtle": true, "wrap": true } ] } ] } ] } ], "actions": [ { "type": "Action.OpenUrl", "title": "View Conversation", "url": question.link } ] } var cardAnsweredMobile = { "$schema": "https://adaptivecards.io/schemas/adaptive-card.json", "type": "AdaptiveCard", "version": "1.0", "style": "emphasis", "body": [ { "type": "TextBlock", "text": question.questionText, "weight": "bolder", "wrap": true, "size": "small" }, { "type": "TextBlock", "text": question.answerText, "wrap": true, "size": "small", "color": "good" }, { "type": "ColumnSet", "columns": [ { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "text": "Submitted: ", "weight": "bolder", "size": "small", "wrap": true } ] }, { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "text": question.originalPoster.fullName, "size": "small", "wrap": true } ] }, { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "spacing": "none", "size": "small", "text": moment.utc(question.questionSubmitted).local().format("DD MMM YYYY, hh:mm a"), "isSubtle": true, "wrap": true } ] } ] }, { "type": "ColumnSet", "columns": [ { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "text": "Answered: ", "weight": "bolder", "size": "small", "wrap": true } ] }, { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "text": answerPosterName, "size": "small", "wrap": true } ] }, { "type": "Column", "width": "auto", "items": [ { "type": "TextBlock", "spacing": "none", "size": "small", "text": moment.utc(question.questionAnswered).local().format("DD MMM YYYY, hh:mm a"), "isSubtle": true, "wrap": true } ] } ] } ], "actions": [ { "type": "Action.OpenUrl", "title": "View Conversation", "url": question.link } ] } // Create an AdaptiveCard instance var adaptiveCard = new AdaptiveCards.AdaptiveCard(); // Set its hostConfig property unless you want to use the default Host Config // Host Config defines the style and behavior of a card adaptiveCard.hostConfig = new AdaptiveCards.HostConfig({ "choiceSetInputValueSeparator": ",", "supportsInteractivity": true, "fontFamily": "Segoe UI", "spacing": { "small": 3, "default": 8, "medium": 20, "large": 30, "extraLarge": 40, "padding": 20 }, "separator": { "lineThickness": 1, "lineColor": "#EEEEEE" }, "fontSizes": { "small": 12, "default": 14, "medium": 17, "large": 21, "extraLarge": 26 }, "fontWeights": { "lighter": 200, "default": 400, "bolder": 600 }, "imageSizes": { "small": 40, "medium": 80, "large": 160 }, "containerStyles": { "default": { "foregroundColors": { "default": { "default": "#333333", "subtle": "#EE333333" }, "dark": { "default": "#000000", "subtle": "#66000000" }, "light": { "default": "#FFFFFF", "subtle": "#33000000" }, "accent": { "default": "#2E89FC", "subtle": "#882E89FC" }, "good": { "default": "#54a254", "subtle": "#DD54a254" }, "warning": { "default": "#e69500", "subtle": "#DDe69500" }, "attention": { "default": "#cc3300", "subtle": "#DDcc3300" } }, "backgroundColor": "#00000000" }, "emphasis": { "foregroundColors": { "default": { "default": "#333333", "subtle": "#EE333333" }, "dark": { "default": "#000000", "subtle": "#66000000" }, "light": { "default": "#FFFFFF", "subtle": "#33000000" }, "accent": { "default": "#2E89FC", "subtle": "#882E89FC" }, "good": { "default": "#54a254", "subtle": "#DD54a254" }, "warning": { "default": "#e69500", "subtle": "#DDe69500" }, "attention": { "default": "#cc3300", "subtle": "#DDcc3300" } }, "backgroundColor": "#08000000" } }, "actions": { "maxActions": 5, "spacing": "Default", "buttonSpacing": 10, "showCard": { "actionMode": "Inline", "inlineTopMargin": 16, "style": "emphasis" }, "preExpandSingleShowCardAction": false, "actionsOrientation": "Horizontal", "actionAlignment": "Right" }, "adaptiveCard": { "allowCustomStyle": false }, "imageSet": { "imageSize": "Medium", "maxImageHeight": 100 }, "factSet": { "title": { "size": "Default", "color": "Default", "isSubtle": false, "weight": "Bolder", "warp": true }, "value": { "size": "Default", "color": "Default", "isSubtle": false, "weight": "Default", "warp": true }, "spacing": 10 } // More host config options }); // Set the adaptive card's event handlers. onExecuteAction is invoked // whenever an action is clicked in the card adaptiveCard.onExecuteAction = function (action: AdaptiveCards.OpenUrlAction) { window.open(action.url, "_blank"); } // For markdown support AdaptiveCards.AdaptiveCard.onProcessMarkdown = function (text) { return markdownit().render(text); } // get screen size let width = (window.screen.width); if (width < 750) { // Parse the card payload if (question.questionAnswered) adaptiveCard.parse(cardAnsweredMobile); else adaptiveCard.parse(cardUnansweredMobile); } else { // Parse the card payload if (question.questionAnswered) adaptiveCard.parse(cardAnswered); else adaptiveCard.parse(cardUnanswered); } // Render the card to an HTML element: var renderedCard = adaptiveCard.render(); return renderedCard; } showHideUnanswered(event: any) { this.unansweredContentVisible = !this.unansweredContentVisible; } showHideAnswered(event: any) { this.answeredContentVisible = !this.answeredContentVisible; } public SignIn(event: any) { this.authService.signIn(); } public SignOut(event: any) { this.authService.signOut(); } }
the_stack
import { eventAttributes } from './definitions'; import { colorKeyWords, systemColor, x11Colors } from './enum'; export const createValList = (pattern: string, n: number, m: number) => `${pattern}(?:\\s*${pattern}){${n - 1},${m - 1}}`; // 符合官方定义的 token // https://drafts.csswg.org/css-syntax-3 // 是否支持 unicode let supportUnicode = true; try { supportUnicode = /\u{20BB7}/u.test('𠮷'); } catch { supportUnicode = false; } const uModifier = supportUnicode ? 'u' : ''; // definition export const commaWsp = '(?:\\s*,\\s*|\\s*)'; const semi = '\\s*;\\s*'; const paren = '\\s*\\(\\s*'; const rParen = '\\s*\\)'; // name token // https://www.w3.org/TR/xml/#NT-Name const NameStartChar = `:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD${supportUnicode ? '\\u{10000}-\\u{EFFFF}' : ''}`; const NameChar = `${NameStartChar}\\-\\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040`; const Name = `[${NameStartChar}][${NameChar}]*`; // css syntax // https://drafts.csswg.org/css-syntax-3/#non-ascii-code-point const cssNameStartChar = `A-Za-z_\\u0080-\\uFFFF${supportUnicode ? '\\u{10000}-\\u{EFFFF}' : ''}`; const cssNameChar = `${cssNameStartChar}\\-0-9`; const cssName = `[${cssNameStartChar}][${cssNameChar}]*`; export const nameFullMatch = new RegExp(`^${Name}$`, uModifier); export const cssNameFullMatch = new RegExp(`^${cssName}$`, uModifier); export const cssNameSpaceSeparatedFullMatch = new RegExp(`^${cssName}(?:\\s+${cssName})*$`, uModifier); // number token // https://www.w3.org/TR/css3-values/#length-value // https://www.w3.org/TR/css-syntax-3/#number-token-diagram // https://www.w3.org/TR/css-syntax-3/#percentage-token-diagram const numberBase = '(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?'; export const numberPattern = `[+-]?${numberBase}`; const zero = '[+-]?(?:0+\\.)?0+(?:[eE][+-]?\\d+)?'; export const nonNegativeFullMatch = new RegExp(`^\\+?${numberBase}$`); export const numberSequence = `${numberPattern}(?:${commaWsp}${numberPattern})*`; export const numberFullMatch = new RegExp(`^${numberPattern}$`); const numberPair = `${numberPattern}${commaWsp}${numberPattern}`; const numberPairSequence = `${numberPair}(?:${commaWsp}${numberPair})*`; const numberPairDouble = `${numberPair}${commaWsp}${numberPair}`; const numberPairTriplet = `${numberPair}(?:${commaWsp}${numberPair}){2}`; export const numberGlobal = new RegExp(numberPattern, 'g'); export const numberOptionalFullMatch = new RegExp(`^${numberPattern}(?:\\s*${numberPattern})?$`); export const numberListFullMatch = new RegExp(`^${numberSequence}$`); export const numberSemiSepatatedFullMatch = new RegExp(`^${numberPattern}(?:${semi}${numberPattern})*(?:${semi})?$`); export const integerFullMatch = /^[+-]?(?:\d+|(?:\d*\.)?\d+[eE][+-]?\d+)$/; export const pureNumOrWithPx = new RegExp(`^${numberPattern}(?:px)?$`); export const pureNumOrWithPxList = new RegExp(`^${numberPattern}(?:px)?(?:${commaWsp}${numberPattern}(?:px)?)*$`); // https://www.w3.org/TR/css-values-3/#angle-value export const angel = 'deg|grad|rad|turn'; export const angelFullMatch = new RegExp(`^${numberPattern}(?:${angel})?$`); const controlPoint = `${numberPattern}${commaWsp}${numberPattern}${commaWsp}${numberPattern}${commaWsp}${numberPattern}`; export const controlPointsFullMatch = new RegExp(`^${controlPoint}(?:${semi}${controlPoint})*(?:${semi})?$`); const Units = '(?:em|ex|ch|rem|vx|vw|vmin|vmax|cm|mm|Q|in|pt|pc|px)'; export const percentageFullMatch = new RegExp(`^${numberPattern}%$`); const length = `${numberPattern}${Units}?`; export const lengthPercentage = `(?:${length}|${numberPattern}%)`; const lengthPair = `${length}${commaWsp}${length}`; export const lengthFullMatch = new RegExp(`^${length}$`); export const lengthPairFullMatch = new RegExp(`^${lengthPair}$`); export const lengthPairListFullMatch = new RegExp(`^${lengthPair}(?:${semi}${lengthPair})*$`); export const lengthPercentageFullMatch = new RegExp(`^${lengthPercentage}$`); export const lengthPercentageListFullMatch = new RegExp(`^${lengthPercentage}(?:${commaWsp}${lengthPercentage})*$`); export const viewBoxFullMatch = new RegExp(`^${controlPoint}$`); // time token // https://svgwg.org/specs/animations/#BeginValueListSyntax const timeCountValue = '\\d+(?:\\.\\d+)?(?:h|min|s|ms)?'; const timeValue = '(?:\\d+:)?[0-5]\\d:[0-5]\\d(?:\\.\\d+)?'; const clockValue = `(?:${timeCountValue}|${timeValue})`; const offsetValue = `(?:\\s*[+-]\\s*)?${clockValue}`; const syncbaseValue = `${Name}\\.(?:begin|end)(?:${offsetValue})?`; const eventValue = `(?:${Name}\\.)?(?:${eventAttributes.join('|')})(?:${offsetValue})?`; const repeatValue = `(?:${Name}\\.)?repeat\\(\\d+\\)(?:${offsetValue})?`; const accessKeyValue = `accessKey\\(.\\)(?:${offsetValue})?`; const wallclockSyncValue = 'wallclock\\(\\d+\\)'; const timePattern = `(?:${offsetValue}|${syncbaseValue}|${eventValue}|${repeatValue}|${accessKeyValue}|${wallclockSyncValue}|indefinite)`; export const clockFullMatch = new RegExp(`^${clockValue}$`); export const timeListFullMatch = new RegExp(`^${timePattern}(\\s*;\\s*${timePattern})*$`, uModifier); // transform token // https://drafts.csswg.org/css-transforms/#svg-comma const translate = `translate${paren}${numberPattern}(?:${commaWsp}?${numberPattern})?${rParen}`; const scale = `scale${paren}${numberPattern}(?:${commaWsp}?${numberPattern})?${rParen}`; const rotate = `rotate${paren}${numberPattern}(?:${commaWsp}?${numberPattern}${commaWsp}?${numberPattern})?${rParen}`; const skewX = `skewX${paren}${numberPattern}${rParen}`; const skewY = `skewY${paren}${numberPattern}${rParen}`; const matrix = `matrix${paren}${numberPattern}(?:${commaWsp}?${numberPattern}){5}${rParen}`; export const transformListFullMatch = new RegExp(`^(?:\\s*(?:${translate}|${scale}|${rotate}|${skewX}|${skewY}|${matrix})\\s*)*$`); // uri token // http://www.ietf.org/rfc/rfc3986.txt export const URIFullMatch = /^(?:[^:/?#]+:)?(?:\/\/[^/?#]*)?(?:[^?#]*)(?:\?[^#]*)?(?:#.*)?$/; // https://tools.ietf.org/html/bcp47#section-2.1 export const langFullMatch = /^[a-zA-Z]{2,}(?:-[a-zA-Z0-9%]+)*$/; // https://drafts.csswg.org/css-syntax-3/#typedef-ident-token const hexDigit = '0-9a-fA-F'; const newLine = '\\r\\n'; const escape = `\\\\(?:[^${hexDigit}${newLine}]|[${hexDigit}]{1,6}\\s?)`; const indentToken = `(?:--|-?(?:[${cssNameStartChar}]|${escape}))(?:[${cssNameChar}]|${escape})*`; export const indentFullMatch = new RegExp(`^${indentToken}$`, uModifier); // https://svgwg.org/svg2-draft/paths.html#PathDataBNF const pathZ = '[zZ]'; const pathMToStrict = `[mM]\\s*${numberPairSequence}${pathZ}?`; const pathMTo = `[mM]\\s*${numberSequence}`; const pathTo = `[lLhHvVcCsSqQtTaA]\\s*${numberSequence}`; const pathLToStrict = `[lL]\\s*(?:${numberPairSequence}|${pathZ})`; const pathHVToStrict = `[hHvV]\\s*${numberSequence}`; const pathCToStrict = `[cC]\\s*(?:${numberPairTriplet}(?:${commaWsp}${numberPairTriplet})*|(?:${numberPairSequence})?${pathZ})`; const pathSQToStrict = `[sSqQ]\\s*(?:${numberPairDouble}(?:${commaWsp}${numberPairDouble})*|(?:${numberPairSequence})?${pathZ})`; const pathTToStrict = `[tT]\\s*(?:${numberPairSequence}|${pathZ})`; const pathA = `${numberPattern}${commaWsp}${numberPattern}${commaWsp}${numberPattern}${commaWsp}[01]${commaWsp}[01]${commaWsp}${numberPair}`; const pathASequence = `${pathA}(?:${commaWsp}${pathA})*`; const pathATo = `[aA]\\s*(?:${pathASequence}|(?:${pathASequence})?${pathZ})`; const pathPatternStrict = `(?:${pathMToStrict}|${pathZ}|${pathLToStrict}|${pathHVToStrict}|${pathCToStrict}|${pathSQToStrict}|${pathTToStrict}|${pathATo})`; const pathPattern = `(?:${pathMTo}|${pathZ}|${pathTo})`; export const pathFullMatchStrict = new RegExp(`^${pathMToStrict}(?:${commaWsp}${pathPatternStrict})*$`); export const pathFullMatch = new RegExp(`^${pathMTo}(?:${commaWsp}${pathPattern})*$`); export const preservAspectRatioFullMatch = /^(?:none|xMinYMin|xMidYMin|xMaxYMin|xMinYMid|xMidYMid|xMaxYMid|xMinYMax|xMidYMax|xMaxYMax)(?:\s+(?:meet|slice))?$/; // IRI export const funcIRIToID = /^url\((["']?)#(.+)\1\)$/; const url = 'url\\([^\\)]+\\)'; export const funcIRIFullMatch = new RegExp(`^${url}$`); export const IRIFullMatch = /^#(.+)$/; export const mediaTypeFullMatch = /^(?:image|audio|video|application|text|multipart|message)\/[^/]+$/; // properties 相关 const lengthOrAuto = `(?:${length}|auto)`; export const clipPathRect = new RegExp(`^rect\\(\\s*${lengthOrAuto}${commaWsp}${lengthOrAuto}${commaWsp}${lengthOrAuto}${commaWsp}${lengthOrAuto}\\s*\\)$`); export const lengthPercentage1_4 = createValList(lengthPercentage, 1, 4); export const lengthPercentage1_4FullMatch = new RegExp(`^${lengthPercentage1_4}$`); export const borderRadiusFullMatch = new RegExp(`^${lengthPercentage1_4}\\s*\\/\\s*${lengthPercentage1_4}$`); // TODO 这个正则不够严谨,未来考虑 use-func export const basicShapeFullMatch = /^(?:inset|circle|ellipse|polygon)\([^()]+\)$/; // color const rgb = `rgba?${paren}(?:${numberPattern}(%?)${commaWsp}${numberPattern}\\1${commaWsp}${numberPattern}\\1(?:${commaWsp}${numberPattern}%?)?)${rParen}`; const hsl = `hsla?${paren}${numberPattern}${commaWsp}${numberPattern}%${commaWsp}${numberPattern}%(?:${commaWsp}${numberPattern}%?)?${rParen}`; const hexColor = '#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})'; export const colorFullMatch = new RegExp(`^(?:${rgb}|${hsl}|${hexColor})$`); const iccColor = `icc-color${paren}${Name}(?:${commaWsp}${numberPattern})+${rParen}`; export const stopColorFullMatch = new RegExp(`^(?:${rgb}|${hsl}|${hexColor}|${colorKeyWords}|${systemColor}|${x11Colors})(?:${iccColor})?$`, uModifier); const cursorStr = 'auto|default|none|context-menu|help|pointer|progress|wait|cell|crosshair|text|vertical-text|alias|copy|move|no-drop|not-allowed|grab|grabbing|e-resize|n-resize|ne-resize|nw-resize|s-resize|se-resize|sw-resize|w-resize|ew-resize|ns-resize|nesw-resize|nwse-resize|col-resize|row-resize|all-scroll|zoom-in|zoom-out'; export const cursorFullMatch = new RegExp(`^(?:${url}\\s*(?:${numberPattern}\\s*${numberPattern})?${commaWsp})*(?:${cursorStr})$`); // filter const blur = `blur${paren}(?:${length})?${rParen}`; const filterFuncNumberPercentage = `(?:brightness|contrast|grayscale|invert|opacity|saturate|sepia)${paren}(?:${numberPattern}%?)?${rParen}`; const dropShadow = `drop-shadow${paren}(?:(?:${rgb}|${hsl}|${hexColor}|${colorKeyWords}|${systemColor}|${x11Colors})?${commaWsp}(?:${length}|${numberPattern}%){2,3})?${rParen}`; const hueRotate = `hue-rotate${paren}(?:${angel}|${zero})?${rParen}`; const filterFunc = `(?:${blur}|${filterFuncNumberPercentage}|${dropShadow}|${hueRotate})`; export const filterListFullMatch = new RegExp(`(?:(?:${filterFunc}|${url})${commaWsp})+`); export const strokeDasharrayFullMatch = new RegExp(`^${lengthPercentage}(?:${commaWsp}${lengthPercentage})+$`); export const vectorEffectFullMatch = /^(?:non-scaling-stroke|non-scaling-size|non-rotation|fixed-position)+(?:viewport|screen)?$/;
the_stack
import { createBundle, createPack, createPackMultiple, Fixture, getTokenBalance, mint, setupFixtures, } from './fixtures'; import {BigNumber} from 'ethers'; import {AddressZero} from '@ethersproject/constants'; import {expect} from 'chai'; import {toWei, waitFor} from '../../utils'; import {ethers} from 'hardhat'; import {defaultAbiCoder} from 'ethers/lib/utils'; const ZERO = BigNumber.from(0); describe('PolygonBundleSandSale.sol', function () { let fixtures: Fixture; beforeEach(async function () { fixtures = await setupFixtures(); }); it('should fail to deploy with a zero receiving wallet', async function () { await expect( fixtures.deployPolygonBundleSandSale(AddressZero) ).to.be.revertedWith('need a wallet to receive funds'); }); it( 'assuming that the medianizer return the price in u$s * 1e18 and usdAmount is also in u$s * 1e18. ' + 'There is no need to round up at most you loose 1e-18 u$s.', async function () { // fixtures.ethUsdPrice == 171.415e18 // The error is 1e-18 u$s max expect(await fixtures.contract.getEtherAmountWithUSD(171)).to.be.equal(0); expect(await fixtures.contract.getEtherAmountWithUSD(172)).to.be.equal(1); expect( await fixtures.contract.getEtherAmountWithUSD(fixtures.ethUsdPrice) ).to.be.equal(toWei(1)); expect( await fixtures.contract.getEtherAmountWithUSD( fixtures.ethUsdPrice.add(171) ) ).to.be.equal(toWei(1)); expect( await fixtures.contract.getEtherAmountWithUSD( fixtures.ethUsdPrice.add(172) ) ).to.be.equal(toWei(1).add(1)); } ); describe('setReceivingWallet', function () { it('should fail to setReceivingWallet if not admin', async function () { const contractWithOtherSigner = await ethers.getContract( 'PolygonBundleSandSale', fixtures.otherUsers[2] ); await expect( contractWithOtherSigner.setReceivingWallet(fixtures.otherUsers[3]) ).to.be.revertedWith('ADMIN_ONLY'); }); it('should fail if address is zero', async function () { await expect( fixtures.contract.setReceivingWallet(AddressZero) ).to.be.revertedWith('receiving wallet cannot be zero address'); }); it('admin should success to setReceivingWallet', async function () { await fixtures.contract.setReceivingWallet(fixtures.otherUsers[3]); // TODO: Need a getter in the contract to be able to check the result. }); }); it('onERC1155Received should fail if called directly', async function () { await expect( fixtures.contract.onERC1155Received( fixtures.otherUsers[3], fixtures.sandBeneficiary, 1, 1, [1] ) ).to.be.revertedWith('only accept asset as sender'); }); describe('create Sale', function () { it("NFT can't be used with numPacks > 1 ?", async function () { const packId = 123; const numPacks = 4; const supply = 1; const sandAmountPerPack = 10; const priceUSDPerPack = 12; await waitFor( fixtures.sandContract.approve( fixtures.contract.address, sandAmountPerPack * numPacks ) ); const tokenId = await mint(fixtures, packId, supply); // createBundle(fixtures, contract, numPacks, sandAmountPerPack, priceUSDPerPack, tokenId, supply) const data = defaultAbiCoder.encode( [ 'uint256 numPacks', 'uint256 sandAmountPerPack', 'uint256 priceUSDPerPack', ], [numPacks, sandAmountPerPack, priceUSDPerPack] ); await expect( fixtures.assetContract[ 'safeTransferFrom(address,address,uint256,uint256,bytes)' ]( fixtures.sandBeneficiary, fixtures.contract.address, tokenId, supply, data ) ).to.be.revertedWith('invalid amounts, not divisible by numPacks'); }); it('NFT can be used with numPacks == 1 ', async function () { const packId = 123; const numPacks = 1; const supply = 1; const sandAmountPerPack = 10; const priceUSDPerPack = 12; await waitFor( fixtures.sandContract.approve( fixtures.contract.address, sandAmountPerPack * numPacks ) ); const tokenId = await mint(fixtures, packId, supply); const saleId = await createBundle( fixtures, numPacks, sandAmountPerPack, priceUSDPerPack, tokenId, supply ); const info = await fixtures.contract.getSaleInfo(saleId); expect(info.priceUSD).to.be.equal(BigNumber.from(priceUSDPerPack)); expect(info.numPacksLeft).to.be.equal(BigNumber.from(numPacks)); }); it('single sale', async function () { const packId = 123; const numPacks = 4; const supply = 11 * numPacks; const sandAmountPerPack = 10; const priceUSDPerPack = 12; await waitFor( fixtures.sandContract.approve( fixtures.contract.address, sandAmountPerPack * numPacks ) ); const tokenId = await mint(fixtures, packId, supply); const saleId = await createBundle( fixtures, numPacks, sandAmountPerPack, priceUSDPerPack, tokenId, supply ); const info = await fixtures.contract.getSaleInfo(saleId); expect(info.priceUSD).to.be.equal(BigNumber.from(priceUSDPerPack)); expect(info.numPacksLeft).to.be.equal(BigNumber.from(numPacks)); }); it('multiple/batch sale', async function () { const packId = 123; const numPacks = 4; const supplies = [12, 44, 43, 12, 13]; const sandAmountPerPack = 10; const priceUSDPerPack = 12; const {saleId} = await createPackMultiple( fixtures, packId, numPacks, supplies, sandAmountPerPack, priceUSDPerPack ); const info = await fixtures.contract.getSaleInfo(saleId); expect(info.priceUSD).to.be.equal(BigNumber.from(priceUSDPerPack)); expect(info.numPacksLeft).to.be.equal(BigNumber.from(numPacks)); }); }); describe('Withdraw', function () { it('withdraw', async function () { const someUser = fixtures.otherUsers[7]; const {saleId, tokenIds, tokensPre, balancePre} = await createPack( fixtures ); await fixtures.contract.withdrawSale(saleId, someUser); const infoPos = await fixtures.contract.getSaleInfo(saleId); expect(infoPos.numPacksLeft).to.be.equal(ZERO); // Sand withdraw expect( await fixtures.sandContract.balanceOf(fixtures.contract.address) ).to.be.equal(ZERO); expect(await fixtures.sandContract.balanceOf(someUser)).to.be.equal( balancePre ); // Token withdraw expect(await getTokenBalance(fixtures, someUser, tokenIds)).to.eql( tokensPre ); const balancePos = await getTokenBalance( fixtures, fixtures.contract.address, tokenIds ); balancePos.forEach((b) => expect(b).to.be.equal(ZERO)); }); it('should fail to withdraw if not admin', async function () { const priceUSDPerPack = 156; const numPacks = 4; const {saleId} = await createPackMultiple( fixtures, 123, numPacks, [12, 44, 43, 12, 13], 123, priceUSDPerPack ); const someUser = fixtures.otherUsers[7]; const contractWithOtherSigner = await ethers.getContract( 'PolygonBundleSandSale', fixtures.otherUsers[2] ); await expect( contractWithOtherSigner.withdrawSale(saleId, someUser) ).to.revertedWith('ADMIN_ONLY'); }); }); describe('Buy packs with DAI', function () { it('should fail with the wrong saleId', async function () { await expect( fixtures.contract.buyBundleWithDai(0, 1, fixtures.otherUsers[4]) ).to.revertedWith('invalid saleId'); }); it('should fail if not enough packs', async function () { const {saleId, numPacks} = await createPack(fixtures); await expect( fixtures.contract.buyBundleWithDai( saleId, numPacks * 2, fixtures.otherUsers[4] ) ).to.revertedWith('not enough packs on sale'); }); it('should fail if not enough DAI', async function () { const someUser = fixtures.otherUsers[7]; const {saleId, priceUSDPerPack} = await createPack(fixtures); const numPacksToBuy = 2; const daiRequired = numPacksToBuy * priceUSDPerPack; // It will fail because of the -1 await fixtures.daiContract.approve( fixtures.contract.address, daiRequired - 1 ); const contractAsDaiBeneficiary = await ethers.getContract( 'PolygonBundleSandSale', fixtures.daiBeneficiary ); await expect( contractAsDaiBeneficiary.buyBundleWithDai( saleId, numPacksToBuy, someUser ) ).to.revertedWith('Not enough funds allowed'); }); it('buy with DAI, obs: buyer != to', async function () { const someUser = fixtures.otherUsers[7]; const { saleId, tokenIds, tokensPre, balancePre, priceUSDPerPack, numPacks, sandAmountPerPack, suppliesPerPack, } = await createPack(fixtures); const numPacksToBuy = 3; const daiRequired = numPacksToBuy * priceUSDPerPack; const daiBalancePre = BigNumber.from( await fixtures.daiContract.balanceOf(fixtures.daiBeneficiary) ); await fixtures.daiContract.approve( fixtures.contract.address, daiRequired ); const contractAsDaiBeneficiary = await ethers.getContract( 'PolygonBundleSandSale', fixtures.daiBeneficiary ); // BUY numPacksToBuy!!! await contractAsDaiBeneficiary.buyBundleWithDai( saleId, numPacksToBuy, someUser ); const infoPos = await fixtures.contract.getSaleInfo(saleId); const numPacksLeft = numPacks - numPacksToBuy; expect(infoPos.numPacksLeft).to.be.equal(numPacksLeft); // Dai Balance expect( await fixtures.daiContract.balanceOf(fixtures.receivingWallet) ).to.be.equal(BigNumber.from(numPacksToBuy * priceUSDPerPack)); expect( await fixtures.daiContract.balanceOf(fixtures.daiBeneficiary) ).to.be.equal(daiBalancePre.sub(numPacksToBuy * priceUSDPerPack)); // Sand balance expect(await fixtures.sandContract.balanceOf(someUser)).to.be.equal( sandAmountPerPack * numPacksToBuy ); expect( await fixtures.sandContract.balanceOf(fixtures.contract.address) ).to.be.equal(balancePre.sub(sandAmountPerPack * numPacksToBuy)); // Token balance expect(await getTokenBalance(fixtures, someUser, tokenIds)).to.eql( suppliesPerPack.map((s) => BigNumber.from(numPacksToBuy * s)) ); expect( await getTokenBalance(fixtures, fixtures.contract.address, tokenIds) ).to.eql( tokensPre.map((x, i) => x.sub(numPacksToBuy * suppliesPerPack[i])) ); }); describe('Buy packs with ETH', function () { it('should fail with the wrong saleId', async function () { await expect( fixtures.contract.buyBundleWithEther(0, 1, fixtures.otherUsers[4]) ).to.revertedWith('invalid saleId'); }); it('should fail if not enough packs', async function () { const {saleId, numPacks} = await createPack(fixtures); await expect( fixtures.contract.buyBundleWithEther( saleId, numPacks * 2, fixtures.otherUsers[4] ) ).to.revertedWith('not enough packs on sale'); }); it('should fail if not enough ETH', async function () { const buyer = fixtures.otherUsers[7]; const to = fixtures.otherUsers[8]; const {saleId, priceUSDPerPack} = await createPack(fixtures); const numPacksToBuy = 2; const usdRequired = BigNumber.from(numPacksToBuy * priceUSDPerPack); // Will fail because of sub(1) const ethRequired = usdRequired .mul(toWei(1)) .div(fixtures.ethUsdPrice) .sub(1); const contractAsBuyer = await ethers.getContract( 'PolygonBundleSandSale', buyer ); await expect( contractAsBuyer.buyBundleWithEther(saleId, numPacksToBuy, to, { value: ethRequired, }) ).to.revertedWith('not enough ether sent'); }); it('buy with ETH, obs: buyer != to', async function () { const buyer = fixtures.otherUsers[7]; const to = fixtures.otherUsers[8]; const { saleId, tokenIds, tokensPre, balancePre, priceUSDPerPack, numPacks, sandAmountPerPack, suppliesPerPack, } = await createPack(fixtures); const numPacksToBuy = 3; const leftOver = 567; const usdRequired = BigNumber.from(numPacksToBuy * priceUSDPerPack); const ethRequired = usdRequired.mul(toWei(1)).div(fixtures.ethUsdPrice); const contractAsBuyer = await ethers.getContract( 'PolygonBundleSandSale', buyer ); const ethBalancePre = BigNumber.from( await ethers.provider.getBalance(fixtures.receivingWallet) ); const buyerEthBalancePre = BigNumber.from( await ethers.provider.getBalance(buyer) ); // BUY numPacksToBuy!!! const tx = await contractAsBuyer.buyBundleWithEther( saleId, numPacksToBuy, to, { value: ethRequired.add(leftOver), } ); const receipt = await tx.wait(); const infoPos = await fixtures.contract.getSaleInfo(saleId); const numPacksLeft = numPacks - numPacksToBuy; expect(infoPos.numPacksLeft).to.be.equal(numPacksLeft); // ETH Balance expect( await ethers.provider.getBalance(fixtures.receivingWallet) ).to.be.equal(ethBalancePre.add(ethRequired)); expect(await ethers.provider.getBalance(buyer)).to.be.equal( buyerEthBalancePre .sub(ethRequired) .sub(receipt.gasUsed.mul(tx.gasPrice)) ); // Sand balance expect(await fixtures.sandContract.balanceOf(to)).to.be.equal( sandAmountPerPack * numPacksToBuy ); expect( await fixtures.sandContract.balanceOf(fixtures.contract.address) ).to.be.equal(balancePre.sub(sandAmountPerPack * numPacksToBuy)); // Token balance expect(await getTokenBalance(fixtures, to, tokenIds)).to.eql( suppliesPerPack.map((s) => BigNumber.from(numPacksToBuy * s)) ); expect( await getTokenBalance(fixtures, fixtures.contract.address, tokenIds) ).to.eql( tokensPre.map((x, i) => x.sub(numPacksToBuy * suppliesPerPack[i])) ); }); }); }); });
the_stack
import { Router } from '@angular/router'; import { environment } from './../../environments/environment'; import * as fromTripActions from './../actions/trips.action'; import * as fromRoot from './../reducers/index'; import { Store } from '@ngrx/store'; import { Observable, Subject } from 'rxjs'; import { Trip } from './../models/trip'; import { Http, Headers, Response } from '@angular/http'; import { Injectable } from '@angular/core'; import { SlimLoadingBarService } from 'ng2-slim-loading-bar'; import { ToastyService } from 'ng2-toasty'; import { ServerAuthService } from './server-auth.service'; import { getSelectedTrip } from '../reducers/index'; import { TripsLoadedAction } from '../actions/trips.action'; import { Comment } from '../models/comment'; @Injectable() export class TripsService { private trips: Trip[] = []; private apiLink: string = environment.API_ENDPOINT; // "http://localhost:3000"; public total_pages: number; public loading = new Subject(); // trips: Trip[]; constructor( private http: Http, private store: Store<fromRoot.State>, private slimLoadingBarService: SlimLoadingBarService, private toastyService: ToastyService, private authSerive: ServerAuthService, private router: Router ) { } getUserAuthToken() { let user_data = JSON.parse(localStorage.getItem('user')); if (user_data) { return user_data.auth_token; } } /** * Get details of a particular trip * @method getTrip * @param {String} Trip id * @return {Boolean} CS:? */ getTrip(id: string): boolean { let subs = this.store.select(getSelectedTrip) .do(trip => { if (!trip) { const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': this.getUserAuthToken() // use Restangular which creates interceptor }); this.http.get(`${this.apiLink}/trips/${id}`, { headers: headers }) .map((data: Response) => data.json()) .map(trip => this.store.dispatch(new fromTripActions.TripsLoadedAction([trip]))) .subscribe(); } this.store.dispatch(new fromTripActions.SelectTripAction(id)); }).subscribe(); subs.unsubscribe(); return true; // TODO: first fetch trip from store, if trip is not found, then make an // backend api request and store it, then resolve this request. // Pivotal tracker link: https://www.pivotaltracker.com/story/show/135508621 // this.store.select(fromRoot.getSelectedTripId) // .filter((data) => data!= null) // .map((data) => { // let trip$ = this.store.select(fromRoot.getSelectedTrip); // trip$.subscribe(data => { // if (typeof(data) !== typeof({})) { // console.log("before"); // this.loadTripApi(id) // .then(data => { // console.log("inside"); // this.store.dispatch(new fromTripActions.TripsLoadedAction(data)); // }) // console.log("after"); // } // }) // }).subscribe(); } /** * Get all trips for dashboard page * @method getTrips * @param * @return {Observable} Observable of array of trips */ getTrips(pageParams): Observable<Trip[]> | Observable<String> { this.slimLoadingBarService.start(); const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': this.getUserAuthToken() // use Restangular which creates interceptor }); let url: string; switch (pageParams['tripsType']) { case "feeds": url = `${this.apiLink}/trips.json/?page=${pageParams['page']}`; break; case "trending": url = `${this.apiLink}/trending/trips.json/?page=${pageParams['page']}`; break; } // Loading Trips this.loading.next(true); return this.http.get(url, { headers: headers }) .map((data: Response) => { this.loading.next(false); let trips_data = data.json(); this.total_pages = trips_data.total_pages; return trips_data.trips; }) .catch((res: Response) => this.catchError(res)) .finally(() => this.slimLoadingBarService.complete()); } /** * Get all trips for dashboard page * @method getTrendingTrips * @param * @return {Observable} Observable of array of trips */ getTrendingTrips(pageParams): Observable<Trip[]> | Observable<String> { this.slimLoadingBarService.start(); return this.http.get(`${this.apiLink}/trending/trips.json/?page=${pageParams['page']}`) .map((data: Response) => { let trips_data = data.json(); this.total_pages = trips_data.total_pages; return trips_data.trips; }) .catch((res: Response) => this.catchError(res)) .finally(() => this.slimLoadingBarService.complete()); } /** * Get all trips for search page * @method searchTrips * @param * @return {Observable} Observable of array of trips */ searchTrips(searchQuery): Observable<Trip[]> | Observable<String> { this.slimLoadingBarService.start(); this.loading.next(true); return this.http.post(`${this.apiLink}/trips/search`, { keywords: searchQuery }) .map((data: Response) => { this.loading.next(false); return data.json() }) .catch((res: Response) => this.catchError(res)) .finally(() => this.slimLoadingBarService.complete()); } /** * Get all trips of a particular user * @method getUserTrip * @param {String} user id * @return {Observable} Observable with array of user trip objects */ getUserTrips(id: string): Observable<Trip[]> | Observable<String> { this.slimLoadingBarService.start(); const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': this.getUserAuthToken() // use Restangular which creates interceptor }); this.loading.next(true); return this.http.get(`${this.apiLink}/users/${id}/trips.json`, { headers: headers }) .map((data: Response) => { console.log("check"); this.loading.next(false); return data.json() }) .catch((res: Response) => this.catchError(res)) .finally(() => this.slimLoadingBarService.complete()) } /** * Save a trip * @method saveTrip * @param {Trip} Trip object to be saved * @return {Observable} Observable with created trip object */ saveTrip(trip: Trip) { const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': this.getUserAuthToken() // use Restangular which creates interceptor }); this.slimLoadingBarService.start(); return this.http.post(`${this.apiLink}/trips.json`, JSON.stringify({ trip: trip }), { headers: headers } ) .map((data: Response) => { let trip = data.json(); this.store.dispatch(new fromTripActions.SaveTripSuccessAction(trip)); this.router.navigate(['/user', (trip.user_id)]); }) .catch((res: Response) => this.catchError(res)) .finally(() => this.slimLoadingBarService.complete()); } /** * Update trip data * @method udpateTrip * @param {Trip} trip object to be updated * @return {Observable} Observable with updated trip object */ updateTrip(trip: Trip): Observable<Trip> | Observable<String> { const tripId = trip.id; const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': this.getUserAuthToken() // use Restangular which creates interceptor }); this.slimLoadingBarService.start(); return this.http.patch(`${this.apiLink}/trips/${tripId}.json`, JSON.stringify({ trip: trip }), { headers: headers } ) .map((data: Response) => { let trip = data.json(); this.store.dispatch(new fromTripActions.UpdateTripSuccessAction(trip)); this.router.navigate(['/user', (trip.user_id)]); }) .catch((res: Response) => this.catchError(res)) .finally(() => this.slimLoadingBarService.complete()); } /** * User Like/Dislikes trip * @method likeTrip * @param {string} tripId of trip * @return {Observable} Observable with updated trip object */ likeTrip(tripId: string): Observable<Trip> | Observable<String> { const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': this.getUserAuthToken() // use Restangular which creates interceptor }); return this.http.post(`${this.apiLink}/trips/like.json`, { id: tripId }, { headers: headers } ) .map((data: Response) => data.json()) .catch((res: Response) => this.catchError(res)); } /** * Get Trip Comments * @method getComments * @param {string} tripId of trip * @return {Observable} Observable with Comments */ getComments(tripId: string): Observable<any> { return this.http.get(`${this.apiLink}/trips/${tripId}/comments`) .map((data: Response) => data.json()) .catch((res: Response) => this.catchError(res)); } /** * Add Comment * @method addComment * @param {Comment} comment * @return {Observable} Observable with Comment */ addComment(comment: Comment): Observable<any> { const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': this.getUserAuthToken() // use Restangular which creates interceptor }); return this.http.post( `${this.apiLink}/trips/add_comments`, { comment: comment }, { headers: headers } ) .map((data: Response) => data.json()) .catch((res: Response) => this.catchError(res)); } /** * Delete Comment * @method deleteComment * @param {Comment} comment * @return {Observable} Observable with Comment */ deleteComment(comment: Comment): Observable<any> { const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': this.getUserAuthToken() // use Restangular which creates interceptor }); return this.http.post( `${this.apiLink}/trips/comments`, { id: comment.id, user_id: comment.user_id }, { headers: headers } ) .map((data: Response) => comment) .catch((res: Response) => this.catchError(res)); } /** * Increase trip view count * @method increase_view_count * @param {string} id * @return {Observable} Observable with status */ increase_view_count(id: any): Observable<any> { const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': this.getUserAuthToken() // use Restangular which creates interceptor }); return this.http.post( `${this.apiLink}/trips/increase_view_count`, { id: id }, { headers: headers } ) .map((data: Response) => data.status) .catch((res: Response) => this.catchError(res)); } get_graph_data_for_trip(id: any): Observable<any> { const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': this.getUserAuthToken() // use Restangular which creates interceptor }); return this.http.post( `${this.apiLink}/graph_data_for_trip`, { id: id }, { headers: headers } ) .map((data: Response) => data.json()) .catch((res: Response) => this.catchError(res)); } catchError(response: Response): Observable<String> { if (response.status == 401) { this.authSerive.redirectToLogin(); this.toastyService.warning({ title: "Login", msg: "You need to login." }); } else { this.toastyService.error({ title: "Server Error", msg: "Something went wrong !!!" }); } console.log('in catch error method'); // not returning throw as it raises an error on the parent observable // MORE INFO at https://youtu.be/3LKMwkuK0ZE?t=24m29s return Observable.of('server error'); } }
the_stack
import { buildValidation, SchemaBlockGroup } from 'ember-osf-web/packages/registration-schema'; import { module, test } from 'qunit'; module('Unit | Packages | registration-schema | validations', () => { test('validate text inputs', assert => { const groups: SchemaBlockGroup[] = [ { labelBlock: { blockType: 'section-heading', displayText: 'Test for Text Inputs', index: 0, }, groupType: 'section-heading', }, // Short Text Inputs { labelBlock: { blockType: 'question-label', displayText: 'Short Text: Required', index: 1, schemaBlockGroupKey: 'q1', }, inputBlock: { blockType: 'short-text-input', index: 2, schemaBlockGroupKey: 'q1', registrationResponseKey: 'q1ShortTextRequired', required: true, }, schemaBlockGroupKey: 'q1', registrationResponseKey: 'q1ShortTextRequired', groupType: 'short-text-input', }, { labelBlock: { blockType: 'question-label', displayText: 'Short Text: Optional', index: 3, schemaBlockGroupKey: 'q2', }, inputBlock: { blockType: 'short-text-input', index: 4, schemaBlockGroupKey: 'q2', registrationResponseKey: 'q2ShortTextOptional', required: false, }, schemaBlockGroupKey: 'q2', registrationResponseKey: 'q2ShortTextOptional', groupType: 'short-text-input', }, // Long Text Inputs { labelBlock: { blockType: 'question-label', displayText: 'Long Text: Required', index: 5, schemaBlockGroupKey: 'q3', }, inputBlock: { blockType: 'long-text-input', index: 6, schemaBlockGroupKey: 'q3', registrationResponseKey: 'q3LongTextRequired', required: true, }, schemaBlockGroupKey: 'q3', registrationResponseKey: 'q3LongTextRequired', groupType: 'long-text-input', }, { labelBlock: { blockType: 'question-label', displayText: 'Long Text: Optional', index: 7, schemaBlockGroupKey: 'q4', }, inputBlock: { blockType: 'long-text-input', index: 8, schemaBlockGroupKey: 'q4', registrationResponseKey: 'q4LongTextOptional', required: false, }, schemaBlockGroupKey: 'q4', registrationResponseKey: 'q4LongTextOptional', groupType: 'long-text-input', }, ]; const result = buildValidation(groups); assert.equal(result[groups[1].registrationResponseKey!].length, 1, 'has 1 validation for required short text input'); assert.equal(result[groups[2].registrationResponseKey!].length, 0, 'has 0 validations for optional short text input'); assert.equal(result[groups[3].registrationResponseKey!].length, 1, 'has 1 validation for required long text input'); assert.equal(result[groups[4].registrationResponseKey!].length, 0, 'has 0 validations for optional long text input'); }); // test('validate contributor inputs', assert => { // const groups: SchemaBlockGroup[] = [ // { // labelBlock: { // blockType: 'section-heading', // displayText: 'Test for Contributor Inputs', // index: 0, // }, // groupType: 'section-heading', // }, // { // labelBlock: { // blockType: 'question-label', // displayText: 'Contributors: Required', // index: 1, // schemaBlockGroupKey: 'q1', // }, // inputBlock: { // blockType: 'contributors-input', // index: 2, // schemaBlockGroupKey: 'q1', // registrationResponseKey: 'q1ContributorsRequired', // required: true, // }, // schemaBlockGroupKey: 'q1', // registrationResponseKey: 'q1ContributorsRequired', // groupType: 'contributors-input', // }, // { // labelBlock: { // blockType: 'question-label', // displayText: 'Contributors: Optional', // index: 3, // schemaBlockGroupKey: 'q2', // }, // inputBlock: { // blockType: 'contributors-input', // index: 4, // schemaBlockGroupKey: 'q2', // registrationResponseKey: 'q2ContributorsOptional', // required: false, // }, // schemaBlockGroupKey: 'q2', // registrationResponseKey: 'q2ContributorsOptional', // groupType: 'contributors-input', // }, // ]; // const result = buildValidation(groups); // assert.equal(result[groups[1].registrationResponseKey!].length, 2, // 'has 2 validation for required contributor input'); // assert.equal(result[groups[2].registrationResponseKey!].length, 1, // 'has 1 validations for optional contributor input'); // }); test('validate file inputs', assert => { const groups: SchemaBlockGroup[] = [ { labelBlock: { blockType: 'section-heading', displayText: 'Test for File Inputs', index: 0, }, groupType: 'section-heading', }, { labelBlock: { blockType: 'question-label', displayText: 'File: Required', index: 1, schemaBlockGroupKey: 'q1', }, inputBlock: { blockType: 'file-input', index: 2, schemaBlockGroupKey: 'q1', registrationResponseKey: 'q1FileRequired', required: true, }, schemaBlockGroupKey: 'q1', registrationResponseKey: 'q1FileRequired', groupType: 'file-input', }, { labelBlock: { blockType: 'question-label', displayText: 'File: Optional', index: 3, schemaBlockGroupKey: 'q2', }, inputBlock: { blockType: 'file-input', index: 4, schemaBlockGroupKey: 'q2', registrationResponseKey: 'q2FileOptional', required: false, }, schemaBlockGroupKey: 'q2', registrationResponseKey: 'q2FileOptional', groupType: 'file-input', }, ]; const result = buildValidation(groups); assert.equal(result[groups[1].registrationResponseKey!].length, 2, 'has 2 validation for required file input'); assert.equal(result[groups[2].registrationResponseKey!].length, 1, 'has 1 validations for optional file input'); }); test('validate select inputs', assert => { const groups: SchemaBlockGroup[] = [ { labelBlock: { blockType: 'section-heading', displayText: 'Test for Select Inputs', index: 0, }, groupType: 'section-heading', }, // Single Select: Required { labelBlock: { blockType: 'question-label', displayText: 'Single Select: Required', index: 1, schemaBlockGroupKey: 'q1', }, inputBlock: { blockType: 'single-select-input', index: 2, schemaBlockGroupKey: 'q1', registrationResponseKey: 'q1SingleSelectRequired', required: true, }, optionBlocks: [ { blockType: 'select-input-option', index: 3, schemaBlockGroupKey: 'q1', displayText: 'option1 required single select', }, { blockType: 'select-input-option', index: 4, schemaBlockGroupKey: 'q1', displayText: 'option2 required single-select', }, ], schemaBlockGroupKey: 'q1', registrationResponseKey: 'q1SingleSelectRequired', groupType: 'single-select-input', }, // Single Select: Optional { labelBlock: { blockType: 'question-label', displayText: 'Single Select: Optional', index: 5, schemaBlockGroupKey: 'q2', }, inputBlock: { blockType: 'single-select-input', index: 6, schemaBlockGroupKey: 'q2', registrationResponseKey: 'q2SingleSelectOptional', required: false, }, optionBlocks: [ { blockType: 'select-input-option', index: 7, schemaBlockGroupKey: 'q2', displayText: 'option1 optional single-select', }, { blockType: 'select-input-option', index: 8, schemaBlockGroupKey: 'q2', displayText: 'option2 optional single-select', }, ], schemaBlockGroupKey: 'q2', registrationResponseKey: 'q2SingleSelectOptional', groupType: 'single-select-input', }, // Multiple Select: Required { labelBlock: { blockType: 'question-label', displayText: 'Multi Select: Required', index: 9, schemaBlockGroupKey: 'q3', }, inputBlock: { blockType: 'multi-select-input', index: 9, schemaBlockGroupKey: 'q3', registrationResponseKey: 'q3MultiSelectRequired', required: true, }, optionBlocks: [ { blockType: 'select-input-option', index: 10, schemaBlockGroupKey: 'q3', displayText: 'option1 required multi select', }, { blockType: 'select-input-option', index: 11, schemaBlockGroupKey: 'q3', displayText: 'option2 required multi-select', }, ], schemaBlockGroupKey: 'q3', registrationResponseKey: 'q3MultiSelectRequired', groupType: 'multi-select-input', }, // Multi Select: Optional { labelBlock: { blockType: 'question-label', displayText: 'Multi Select: Optional', index: 12, schemaBlockGroupKey: 'q4', }, inputBlock: { blockType: 'multi-select-input', index: 13, schemaBlockGroupKey: 'q4', registrationResponseKey: 'q4MultiSelectOptional', required: false, }, optionBlocks: [ { blockType: 'select-input-option', index: 14, schemaBlockGroupKey: 'q4', displayText: 'option1 optional multi-select', }, { blockType: 'select-input-option', index: 15, schemaBlockGroupKey: 'q4', displayText: 'option2 optional multi-select', }, ], schemaBlockGroupKey: 'q4', registrationResponseKey: 'q4MultiSelectOptional', groupType: 'single-select-input', }, ]; const result = buildValidation(groups); assert.equal(result[groups[1].registrationResponseKey!].length, 1, 'has 1 validation for required Single-Selector input'); assert.equal(result[groups[2].registrationResponseKey!].length, 0, 'has 0 validations for optional Single-Select input'); assert.equal(result[groups[3].registrationResponseKey!].length, 1, 'has 1 validation for required Multi-Select input'); assert.equal(result[groups[4].registrationResponseKey!].length, 0, 'has 0 validations for optional Multi-Select input'); }); });
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { AmpClient } from "./AmpClient"; import { CreateAlertManagerDefinitionCommand, CreateAlertManagerDefinitionCommandInput, CreateAlertManagerDefinitionCommandOutput, } from "./commands/CreateAlertManagerDefinitionCommand"; import { CreateRuleGroupsNamespaceCommand, CreateRuleGroupsNamespaceCommandInput, CreateRuleGroupsNamespaceCommandOutput, } from "./commands/CreateRuleGroupsNamespaceCommand"; import { CreateWorkspaceCommand, CreateWorkspaceCommandInput, CreateWorkspaceCommandOutput, } from "./commands/CreateWorkspaceCommand"; import { DeleteAlertManagerDefinitionCommand, DeleteAlertManagerDefinitionCommandInput, DeleteAlertManagerDefinitionCommandOutput, } from "./commands/DeleteAlertManagerDefinitionCommand"; import { DeleteRuleGroupsNamespaceCommand, DeleteRuleGroupsNamespaceCommandInput, DeleteRuleGroupsNamespaceCommandOutput, } from "./commands/DeleteRuleGroupsNamespaceCommand"; import { DeleteWorkspaceCommand, DeleteWorkspaceCommandInput, DeleteWorkspaceCommandOutput, } from "./commands/DeleteWorkspaceCommand"; import { DescribeAlertManagerDefinitionCommand, DescribeAlertManagerDefinitionCommandInput, DescribeAlertManagerDefinitionCommandOutput, } from "./commands/DescribeAlertManagerDefinitionCommand"; import { DescribeRuleGroupsNamespaceCommand, DescribeRuleGroupsNamespaceCommandInput, DescribeRuleGroupsNamespaceCommandOutput, } from "./commands/DescribeRuleGroupsNamespaceCommand"; import { DescribeWorkspaceCommand, DescribeWorkspaceCommandInput, DescribeWorkspaceCommandOutput, } from "./commands/DescribeWorkspaceCommand"; import { ListRuleGroupsNamespacesCommand, ListRuleGroupsNamespacesCommandInput, ListRuleGroupsNamespacesCommandOutput, } from "./commands/ListRuleGroupsNamespacesCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { ListWorkspacesCommand, ListWorkspacesCommandInput, ListWorkspacesCommandOutput, } from "./commands/ListWorkspacesCommand"; import { PutAlertManagerDefinitionCommand, PutAlertManagerDefinitionCommandInput, PutAlertManagerDefinitionCommandOutput, } from "./commands/PutAlertManagerDefinitionCommand"; import { PutRuleGroupsNamespaceCommand, PutRuleGroupsNamespaceCommandInput, PutRuleGroupsNamespaceCommandOutput, } from "./commands/PutRuleGroupsNamespaceCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { UpdateWorkspaceAliasCommand, UpdateWorkspaceAliasCommandInput, UpdateWorkspaceAliasCommandOutput, } from "./commands/UpdateWorkspaceAliasCommand"; /** * Amazon Managed Service for Prometheus */ export class Amp extends AmpClient { /** * Create an alert manager definition. */ public createAlertManagerDefinition( args: CreateAlertManagerDefinitionCommandInput, options?: __HttpHandlerOptions ): Promise<CreateAlertManagerDefinitionCommandOutput>; public createAlertManagerDefinition( args: CreateAlertManagerDefinitionCommandInput, cb: (err: any, data?: CreateAlertManagerDefinitionCommandOutput) => void ): void; public createAlertManagerDefinition( args: CreateAlertManagerDefinitionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateAlertManagerDefinitionCommandOutput) => void ): void; public createAlertManagerDefinition( args: CreateAlertManagerDefinitionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateAlertManagerDefinitionCommandOutput) => void), cb?: (err: any, data?: CreateAlertManagerDefinitionCommandOutput) => void ): Promise<CreateAlertManagerDefinitionCommandOutput> | void { const command = new CreateAlertManagerDefinitionCommand(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); } } /** * Create a rule group namespace. */ public createRuleGroupsNamespace( args: CreateRuleGroupsNamespaceCommandInput, options?: __HttpHandlerOptions ): Promise<CreateRuleGroupsNamespaceCommandOutput>; public createRuleGroupsNamespace( args: CreateRuleGroupsNamespaceCommandInput, cb: (err: any, data?: CreateRuleGroupsNamespaceCommandOutput) => void ): void; public createRuleGroupsNamespace( args: CreateRuleGroupsNamespaceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateRuleGroupsNamespaceCommandOutput) => void ): void; public createRuleGroupsNamespace( args: CreateRuleGroupsNamespaceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateRuleGroupsNamespaceCommandOutput) => void), cb?: (err: any, data?: CreateRuleGroupsNamespaceCommandOutput) => void ): Promise<CreateRuleGroupsNamespaceCommandOutput> | void { const command = new CreateRuleGroupsNamespaceCommand(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); } } /** * Creates a new AMP workspace. */ public createWorkspace( args: CreateWorkspaceCommandInput, options?: __HttpHandlerOptions ): Promise<CreateWorkspaceCommandOutput>; public createWorkspace( args: CreateWorkspaceCommandInput, cb: (err: any, data?: CreateWorkspaceCommandOutput) => void ): void; public createWorkspace( args: CreateWorkspaceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateWorkspaceCommandOutput) => void ): void; public createWorkspace( args: CreateWorkspaceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateWorkspaceCommandOutput) => void), cb?: (err: any, data?: CreateWorkspaceCommandOutput) => void ): Promise<CreateWorkspaceCommandOutput> | void { const command = new CreateWorkspaceCommand(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); } } /** * Deletes an alert manager definition. */ public deleteAlertManagerDefinition( args: DeleteAlertManagerDefinitionCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteAlertManagerDefinitionCommandOutput>; public deleteAlertManagerDefinition( args: DeleteAlertManagerDefinitionCommandInput, cb: (err: any, data?: DeleteAlertManagerDefinitionCommandOutput) => void ): void; public deleteAlertManagerDefinition( args: DeleteAlertManagerDefinitionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteAlertManagerDefinitionCommandOutput) => void ): void; public deleteAlertManagerDefinition( args: DeleteAlertManagerDefinitionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteAlertManagerDefinitionCommandOutput) => void), cb?: (err: any, data?: DeleteAlertManagerDefinitionCommandOutput) => void ): Promise<DeleteAlertManagerDefinitionCommandOutput> | void { const command = new DeleteAlertManagerDefinitionCommand(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); } } /** * Delete a rule groups namespace. */ public deleteRuleGroupsNamespace( args: DeleteRuleGroupsNamespaceCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteRuleGroupsNamespaceCommandOutput>; public deleteRuleGroupsNamespace( args: DeleteRuleGroupsNamespaceCommandInput, cb: (err: any, data?: DeleteRuleGroupsNamespaceCommandOutput) => void ): void; public deleteRuleGroupsNamespace( args: DeleteRuleGroupsNamespaceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteRuleGroupsNamespaceCommandOutput) => void ): void; public deleteRuleGroupsNamespace( args: DeleteRuleGroupsNamespaceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteRuleGroupsNamespaceCommandOutput) => void), cb?: (err: any, data?: DeleteRuleGroupsNamespaceCommandOutput) => void ): Promise<DeleteRuleGroupsNamespaceCommandOutput> | void { const command = new DeleteRuleGroupsNamespaceCommand(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); } } /** * Deletes an AMP workspace. */ public deleteWorkspace( args: DeleteWorkspaceCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteWorkspaceCommandOutput>; public deleteWorkspace( args: DeleteWorkspaceCommandInput, cb: (err: any, data?: DeleteWorkspaceCommandOutput) => void ): void; public deleteWorkspace( args: DeleteWorkspaceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteWorkspaceCommandOutput) => void ): void; public deleteWorkspace( args: DeleteWorkspaceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteWorkspaceCommandOutput) => void), cb?: (err: any, data?: DeleteWorkspaceCommandOutput) => void ): Promise<DeleteWorkspaceCommandOutput> | void { const command = new DeleteWorkspaceCommand(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); } } /** * Describes an alert manager definition. */ public describeAlertManagerDefinition( args: DescribeAlertManagerDefinitionCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeAlertManagerDefinitionCommandOutput>; public describeAlertManagerDefinition( args: DescribeAlertManagerDefinitionCommandInput, cb: (err: any, data?: DescribeAlertManagerDefinitionCommandOutput) => void ): void; public describeAlertManagerDefinition( args: DescribeAlertManagerDefinitionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeAlertManagerDefinitionCommandOutput) => void ): void; public describeAlertManagerDefinition( args: DescribeAlertManagerDefinitionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeAlertManagerDefinitionCommandOutput) => void), cb?: (err: any, data?: DescribeAlertManagerDefinitionCommandOutput) => void ): Promise<DescribeAlertManagerDefinitionCommandOutput> | void { const command = new DescribeAlertManagerDefinitionCommand(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); } } /** * Describe a rule groups namespace. */ public describeRuleGroupsNamespace( args: DescribeRuleGroupsNamespaceCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeRuleGroupsNamespaceCommandOutput>; public describeRuleGroupsNamespace( args: DescribeRuleGroupsNamespaceCommandInput, cb: (err: any, data?: DescribeRuleGroupsNamespaceCommandOutput) => void ): void; public describeRuleGroupsNamespace( args: DescribeRuleGroupsNamespaceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeRuleGroupsNamespaceCommandOutput) => void ): void; public describeRuleGroupsNamespace( args: DescribeRuleGroupsNamespaceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeRuleGroupsNamespaceCommandOutput) => void), cb?: (err: any, data?: DescribeRuleGroupsNamespaceCommandOutput) => void ): Promise<DescribeRuleGroupsNamespaceCommandOutput> | void { const command = new DescribeRuleGroupsNamespaceCommand(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); } } /** * Describes an existing AMP workspace. */ public describeWorkspace( args: DescribeWorkspaceCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeWorkspaceCommandOutput>; public describeWorkspace( args: DescribeWorkspaceCommandInput, cb: (err: any, data?: DescribeWorkspaceCommandOutput) => void ): void; public describeWorkspace( args: DescribeWorkspaceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeWorkspaceCommandOutput) => void ): void; public describeWorkspace( args: DescribeWorkspaceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeWorkspaceCommandOutput) => void), cb?: (err: any, data?: DescribeWorkspaceCommandOutput) => void ): Promise<DescribeWorkspaceCommandOutput> | void { const command = new DescribeWorkspaceCommand(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); } } /** * Lists rule groups namespaces. */ public listRuleGroupsNamespaces( args: ListRuleGroupsNamespacesCommandInput, options?: __HttpHandlerOptions ): Promise<ListRuleGroupsNamespacesCommandOutput>; public listRuleGroupsNamespaces( args: ListRuleGroupsNamespacesCommandInput, cb: (err: any, data?: ListRuleGroupsNamespacesCommandOutput) => void ): void; public listRuleGroupsNamespaces( args: ListRuleGroupsNamespacesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListRuleGroupsNamespacesCommandOutput) => void ): void; public listRuleGroupsNamespaces( args: ListRuleGroupsNamespacesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListRuleGroupsNamespacesCommandOutput) => void), cb?: (err: any, data?: ListRuleGroupsNamespacesCommandOutput) => void ): Promise<ListRuleGroupsNamespacesCommandOutput> | void { const command = new ListRuleGroupsNamespacesCommand(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); } } /** * Lists the tags you have assigned to the resource. */ 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); } } /** * Lists all AMP workspaces, including workspaces being created or deleted. */ public listWorkspaces( args: ListWorkspacesCommandInput, options?: __HttpHandlerOptions ): Promise<ListWorkspacesCommandOutput>; public listWorkspaces( args: ListWorkspacesCommandInput, cb: (err: any, data?: ListWorkspacesCommandOutput) => void ): void; public listWorkspaces( args: ListWorkspacesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListWorkspacesCommandOutput) => void ): void; public listWorkspaces( args: ListWorkspacesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListWorkspacesCommandOutput) => void), cb?: (err: any, data?: ListWorkspacesCommandOutput) => void ): Promise<ListWorkspacesCommandOutput> | void { const command = new ListWorkspacesCommand(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); } } /** * Update an alert manager definition. */ public putAlertManagerDefinition( args: PutAlertManagerDefinitionCommandInput, options?: __HttpHandlerOptions ): Promise<PutAlertManagerDefinitionCommandOutput>; public putAlertManagerDefinition( args: PutAlertManagerDefinitionCommandInput, cb: (err: any, data?: PutAlertManagerDefinitionCommandOutput) => void ): void; public putAlertManagerDefinition( args: PutAlertManagerDefinitionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutAlertManagerDefinitionCommandOutput) => void ): void; public putAlertManagerDefinition( args: PutAlertManagerDefinitionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutAlertManagerDefinitionCommandOutput) => void), cb?: (err: any, data?: PutAlertManagerDefinitionCommandOutput) => void ): Promise<PutAlertManagerDefinitionCommandOutput> | void { const command = new PutAlertManagerDefinitionCommand(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); } } /** * Update a rule groups namespace. */ public putRuleGroupsNamespace( args: PutRuleGroupsNamespaceCommandInput, options?: __HttpHandlerOptions ): Promise<PutRuleGroupsNamespaceCommandOutput>; public putRuleGroupsNamespace( args: PutRuleGroupsNamespaceCommandInput, cb: (err: any, data?: PutRuleGroupsNamespaceCommandOutput) => void ): void; public putRuleGroupsNamespace( args: PutRuleGroupsNamespaceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutRuleGroupsNamespaceCommandOutput) => void ): void; public putRuleGroupsNamespace( args: PutRuleGroupsNamespaceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutRuleGroupsNamespaceCommandOutput) => void), cb?: (err: any, data?: PutRuleGroupsNamespaceCommandOutput) => void ): Promise<PutRuleGroupsNamespaceCommandOutput> | void { const command = new PutRuleGroupsNamespaceCommand(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); } } /** * Creates tags for the specified resource. */ 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); } } /** * Deletes tags from the specified resource. */ 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); } } /** * Updates an AMP workspace alias. */ public updateWorkspaceAlias( args: UpdateWorkspaceAliasCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateWorkspaceAliasCommandOutput>; public updateWorkspaceAlias( args: UpdateWorkspaceAliasCommandInput, cb: (err: any, data?: UpdateWorkspaceAliasCommandOutput) => void ): void; public updateWorkspaceAlias( args: UpdateWorkspaceAliasCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateWorkspaceAliasCommandOutput) => void ): void; public updateWorkspaceAlias( args: UpdateWorkspaceAliasCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateWorkspaceAliasCommandOutput) => void), cb?: (err: any, data?: UpdateWorkspaceAliasCommandOutput) => void ): Promise<UpdateWorkspaceAliasCommandOutput> | void { const command = new UpdateWorkspaceAliasCommand(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 { createSelector, defaultMemoize, defaultEqualityCheck, createSelectorCreator, createStructuredSelector, ParametricSelector, OutputSelector, SelectorResultArray, Selector } from '../src' import microMemoize from 'micro-memoize' import memoizeOne from 'memoize-one' import { createSlice, configureStore } from '@reduxjs/toolkit' import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux' export function expectType<T>(t: T): T { return t } type Exact<A, B> = (<T>() => T extends A ? 1 : 0) extends <T>() => T extends B ? 1 : 0 ? A extends B ? B extends A ? unknown : never : never : never export declare type IsAny<T, True, False = never> = true | false extends ( T extends never ? true : false ) ? True : False export declare type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False type Equals<T, U> = IsAny< T, never, IsAny<U, never, [T] extends [U] ? ([U] extends [T] ? any : never) : never> > export function expectExactType<T>(t: T) { return <U extends Equals<T, U>>(u: U) => {} } interface StateA { a: number } interface StateAB { a: number b: number } interface StateSub { sub: { a: number } } // Test exporting export const testExportBasic = createSelector( (state: StateA) => state.a, a => a ) // Test for exporting declaration of created selector creator export const testExportStructured = createSelectorCreator( defaultMemoize, (a, b) => typeof a === typeof b ) function testSelector() { type State = { foo: string } const selector = createSelector( (state: State) => state.foo, foo => foo ) const res = selector.resultFunc('test') selector.recomputations() selector.resetRecomputations() const foo: string = selector({ foo: 'bar' }) // @ts-expect-error selector({ foo: 'bar' }, { prop: 'value' }) // @ts-expect-error const num: number = selector({ foo: 'bar' }) // allows heterogeneous parameter type input selectors createSelector( (state: { foo: string }) => state.foo, (state: { bar: number }) => state.bar, (foo, bar) => 1 ) const selectorWithUnions = createSelector( (state: State, val: string | number) => state.foo, (state: State, val: string | number) => val, (foo, val) => val ) } function testNestedSelector() { type State = { foo: string; bar: number; baz: boolean } const selector = createSelector( createSelector( (state: State) => state.foo, (state: State) => state.bar, (foo, bar) => ({ foo, bar }) ), (state: State) => state.baz, ({ foo, bar }, baz) => { const foo1: string = foo // @ts-expect-error const foo2: number = foo const bar1: number = bar // @ts-expect-error const bar2: string = bar const baz1: boolean = baz // @ts-expect-error const baz2: string = baz } ) } function testSelectorAsCombiner() { type SubState = { foo: string } type State = { bar: SubState } const subSelector = createSelector( (state: SubState) => state.foo, foo => foo ) const selector = createSelector((state: State) => state.bar, subSelector) // @ts-expect-error selector({ foo: '' }) // @ts-expect-error const n: number = selector({ bar: { foo: '' } }) const s: string = selector({ bar: { foo: '' } }) } type Component<P> = (props: P) => any declare function connect<S, P, R>( selector: ParametricSelector<S, P, R> ): (component: Component<P & R>) => Component<P> function testConnect() { connect( createSelector( (state: { foo: string }) => state.foo, foo => ({ foo }) ) )(props => { // @ts-expect-error props.bar const foo: string = props.foo }) const selector2 = createSelector( (state: { foo: string }) => state.foo, (state: { baz: number }, props: { bar: number }) => props.bar, (foo, bar) => ({ foo, baz: bar }) ) const connected = connect(selector2)(props => { const foo: string = props.foo const bar: number = props.bar const baz: number = props.baz // @ts-expect-error props.fizz }) connected({ bar: 42 }) // @ts-expect-error connected({ bar: 42, baz: 123 }) } function testInvalidTypeInCombinator() { // @ts-expect-error createSelector( (state: { foo: string }) => state.foo, (foo: number) => foo ) createSelector( (state: { foo: string; bar: number; baz: boolean }) => state.foo, (state: any) => state.bar, (state: any) => state.baz, // @ts-expect-error (foo: string, bar: number, baz: boolean, fizz: string) => {} ) // does not allow heterogeneous parameter type // selectors when the combinator function is typed differently // @ts-expect-error createSelector( (state: { testString: string }) => state.testString, (state: { testNumber: number }) => state.testNumber, (state: { testBoolean: boolean }) => state.testBoolean, (state: { testString: string }) => state.testString, (state: { testString: string }) => state.testString, (state: { testString: string }) => state.testString, (state: { testString: string }) => state.testString, (state: { testNumber: string }) => state.testNumber, (state: { testStringArray: string[] }) => state.testStringArray, ( foo1: string, foo2: number, foo3: boolean, foo4: string, foo5: string, foo6: string, foo7: string, foo8: number, foo9: string[] ) => { return { foo1, foo2, foo3, foo4, foo5, foo6, foo7, foo8, foo9 } } ) // does not allow a large array of heterogeneous parameter type // selectors when the combinator function is typed differently // @ts-expect-error createSelector( [ (state: { testString: string }) => state.testString, (state: { testNumber: number }) => state.testNumber, (state: { testBoolean: boolean }) => state.testBoolean, (state: { testString: string }) => state.testString, (state: { testString: string }) => state.testString, (state: { testString: string }) => state.testString, (state: { testString: string }) => state.testString, (state: { testNumber: string }) => state.testNumber, (state: { testStringArray: string[] }) => state.testStringArray ], ( foo1: string, foo2: number, foo3: boolean, foo4: string, foo5: string, foo6: string, foo7: string, foo8: number, foo9: string[] ) => { return { foo1, foo2, foo3, foo4, foo5, foo6, foo7, foo8, foo9 } } ) } function testParametricSelector() { type State = { foo: string } type Props = { bar: number } // allows heterogeneous parameter type selectors const selector1 = createSelector( (state: { testString: string }) => state.testString, (state: { testNumber: number }) => state.testNumber, (state: { testBoolean: boolean }) => state.testBoolean, (state: { testString: string }) => state.testString, (state: { testString: string }) => state.testString, (state: { testString: string }) => state.testString, (state: { testString: string }) => state.testString, (state: { testString: string }) => state.testString, (state: { testStringArray: string[] }) => state.testStringArray, ( foo1: string, foo2: number, foo3: boolean, foo4: string, foo5: string, foo6: string, foo7: string, foo8: string, foo9: string[] ) => { return { foo1, foo2, foo3, foo4, foo5, foo6, foo7, foo8, foo9 } } ) const res1 = selector1({ testString: 'a', testNumber: 42, testBoolean: true, testStringArray: ['b', 'c'] }) const selector = createSelector( (state: State) => state.foo, (state: State, props: Props) => props.bar, (foo, bar) => ({ foo, bar }) ) // @ts-expect-error selector({ foo: 'fizz' }) // @ts-expect-error selector({ foo: 'fizz' }, { bar: 'baz' }) const ret = selector({ foo: 'fizz' }, { bar: 42 }) const foo: string = ret.foo const bar: number = ret.bar const selector2 = createSelector( (state: State) => state.foo, (state: State) => state.foo, (state: State) => state.foo, (state: State) => state.foo, (state: State) => state.foo, (state: State, props: Props) => props.bar, (foo1, foo2, foo3, foo4, foo5, bar) => ({ foo1, foo2, foo3, foo4, foo5, bar }) ) selector2({ foo: 'fizz' }, { bar: 42 }) const selector3 = createSelector( (s: State) => s.foo, (s: State, x: string) => x, (s: State, y: number) => y, (v, x) => { return x + v } ) // @ts-expect-error selector3({ foo: 'fizz' }, 42) const selector4 = createSelector( (s: State, val: number) => s.foo, (s: State, val: string | number) => val, (foo, val) => { return val } ) selector4({ foo: 'fizz' }, 42) } function testArrayArgument() { const selector = createSelector( [ (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }, props: { bar: number }) => props.bar ], (foo1, foo2, bar) => ({ foo1, foo2, bar }) ) const ret = selector({ foo: 'fizz' }, { bar: 42 }) const foo1: string = ret.foo1 const foo2: string = ret.foo2 const bar: number = ret.bar // @ts-expect-error createSelector([(state: { foo: string }) => state.foo]) // @ts-expect-error createSelector( [ (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo ], (foo: string, bar: number) => {} ) createSelector( [ (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo ], ( foo1: string, foo2: string, foo3: string, foo4: string, foo5: string, foo6: string, foo7: string, foo8: string, foo9: string, foo10: string ) => {} ) // @ts-expect-error createSelector( [ (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo ], (foo1, foo2, foo3, foo4, foo5, foo6, foo7, foo8: number, foo9, foo10) => {} ) // @ts-expect-error createSelector( [ (state: { foo: string }) => state.foo, // @ts-expect-error state => state.foo, // @ts-expect-error state => state.foo, // @ts-expect-error state => state.foo, // @ts-expect-error state => state.foo, // @ts-expect-error state => state.foo, // @ts-expect-error state => state.foo, // @ts-expect-error state => state.foo, 1 ], // We expect an error here, but the error differs between TS versions // @ts-ignore (foo1, foo2, foo3, foo4, foo5, foo6, foo7, foo8, foo9) => {} ) const selector2 = createSelector( [ (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo ], ( foo1: string, foo2: string, foo3: string, foo4: string, foo5: string, foo6: string, foo7: string, foo8: string, foo9: string ) => { return { foo1, foo2, foo3, foo4, foo5, foo6, foo7, foo8, foo9 } } ) { const ret = selector2({ foo: 'fizz' }) const foo1: string = ret.foo1 const foo2: string = ret.foo2 const foo3: string = ret.foo3 const foo4: string = ret.foo4 const foo5: string = ret.foo5 const foo6: string = ret.foo6 const foo7: string = ret.foo7 const foo8: string = ret.foo8 const foo9: string = ret.foo9 // @ts-expect-error ret.foo10 } // @ts-expect-error selector2({ foo: 'fizz' }, { bar: 42 }) const parametric = createSelector( [ (state: { foo: string }, props: { bar: number }) => props.bar, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo, (state: { foo: string }) => state.foo ], ( bar: number, foo1: string, foo2: string, foo3: string, foo4: string, foo5: string, foo6: string, foo7: string, foo8: string ) => { return { foo1, foo2, foo3, foo4, foo5, foo6, foo7, foo8, bar } } ) // allows a large array of heterogeneous parameter type selectors const correctlyTypedArraySelector = createSelector( [ (state: { testString: string }) => state.testString, (state: { testNumber: number }) => state.testNumber, (state: { testBoolean: boolean }) => state.testBoolean, (state: { testString: string }) => state.testString, (state: { testString: string }) => state.testString, (state: { testString: string }) => state.testString, (state: { testString: string }) => state.testString, (state: { testString: string }) => state.testString, (state: { testStringArray: string[] }) => state.testStringArray ], ( foo1: string, foo2: number, foo3: boolean, foo4: string, foo5: string, foo6: string, foo7: string, foo8: string, foo9: string[] ) => { return { foo1, foo2, foo3, foo4, foo5, foo6, foo7, foo8, foo9 } } ) // @ts-expect-error parametric({ foo: 'fizz' }) { const ret = parametric({ foo: 'fizz' }, { bar: 42 }) const foo1: string = ret.foo1 const foo2: string = ret.foo2 const foo3: string = ret.foo3 const foo4: string = ret.foo4 const foo5: string = ret.foo5 const foo6: string = ret.foo6 const foo7: string = ret.foo7 const foo8: string = ret.foo8 const bar: number = ret.bar // @ts-expect-error ret.foo9 } } function testOptionalArgumentsConflicting() { type State = { foo: string; bar: number; baz: boolean } const selector = createSelector( (state: State) => state.baz, (state: State, arg: string) => arg, (state: State, arg: number) => arg, (baz) => { const baz1: boolean = baz // @ts-expect-error const baz2: number = baz } ) // @ts-expect-error the selector above has inconsistent conflicting arguments so usage should error selector({} as State) // @ts-expect-error selector({} as State, 'string') // @ts-expect-error selector({} as State, 1) const selector2 = createSelector( (state: State, prefix: any) => prefix + state.foo, (str) => str ) // @ts-expect-error here we require one argument which can be anything so error if there are no arguments selector2({} as State) // no error passing anything in selector2({} as State, 'blach') selector2({} as State, 1) // here the argument is optional so it should be possible to omit the argument or pass anything const selector3 = createSelector( (state: State, prefix?: any) => prefix + state.foo, (str) => str ) selector3({} as State) selector3({} as State, 1) selector3({} as State, 'blach') // https://github.com/reduxjs/reselect/issues/563 const selector4 = createSelector( (state: State, prefix: string, suffix: any) => prefix + state.foo + String(suffix), (str) => str ) // @ts-expect-error selector4({} as State) // @ts-expect-error selector4({} as State, 'blach') selector4({} as State, 'blach', 4) // as above but a unknown 2nd argument const selector5 = createSelector( (state: State, prefix: string, suffix: unknown) => prefix + state.foo + String(suffix), (str) => str ) // @ts-expect-error selector5({} as State) // @ts-expect-error selector5({} as State, 'blach') selector5({} as State, 'blach', 4) // @ts-expect-error It would be great to delete this, it is not correct. // Due to what must be a TS bug? if the default parameter is used, we lose the type for prefix // and it is impossible to type the selector without typing prefix const selector6 = createSelector( (state: State, prefix = '') => prefix + state.foo, (str: string) => str ) // because the suppressed error above, selector6 has broken typings and doesn't allow a passed parameter selector6({} as State) // @ts-expect-error would be great if we can delete this, it should not error selector6({} as State, 'blach') // @ts-expect-error wrong type selector6({} as State, 1) // this is an example fixing selector6. We have to add a un-necessary typing in and magically the types are correct const selector7 = createSelector( ( state: State, // eslint-disable-next-line @typescript-eslint/no-inferrable-types prefix: string = 'a' ) => prefix + state.foo, (str: string) => str ) selector7({} as State) selector7({} as State, 'blach') // @ts-expect-error wrong type selector7({} as State, 1) const selector8 = createSelector( (state: State, prefix: unknown) => prefix, (str) => str ) // @ts-expect-error needs a argument selector8({} as State) // allowed to pass anything as the type is unknown selector8({} as State, 'blach') selector8({} as State, 2) } function testDefaultMemoize() { const func = (a: string) => +a const memoized = defaultMemoize(func) const ret0: number = memoized('42') // @ts-expect-error const ret1: string = memoized('42') const memoized2 = defaultMemoize( (str: string, arr: string[]): { str: string; arr: string[] } => ({ str, arr }), <T>(a: T, b: T) => { return `${a}` === `${b}` } ) const ret2 = memoized2('', ['1', '2']) const str: string = ret2.str const arr: string[] = ret2.arr } function testCreateSelectorCreator() { const defaultCreateSelector = createSelectorCreator(defaultMemoize) const selector = defaultCreateSelector( (state: { foo: string }) => state.foo, foo => foo ) const value: string = selector({ foo: 'fizz' }) // @ts-expect-error selector({ foo: 'fizz' }, { bar: 42 }) // clearCache should exist because of defaultMemoize selector.clearCache() const parametric = defaultCreateSelector( (state: { foo: string }) => state.foo, (state: { foo: string }, props: { bar: number }) => props.bar, (foo, bar) => ({ foo, bar }) ) // @ts-expect-error parametric({ foo: 'fizz' }) const ret = parametric({ foo: 'fizz' }, { bar: 42 }) const foo: string = ret.foo const bar: number = ret.bar // @ts-expect-error createSelectorCreator(defaultMemoize, 1) createSelectorCreator(defaultMemoize, <T>(a: T, b: T) => { return `${a}` === `${b}` }) } function testCreateStructuredSelector() { const oneParamSelector = createStructuredSelector({ foo: (state: StateAB) => state.a, bar: (state: StateAB) => state.b }) const threeParamSelector = createStructuredSelector({ foo: (state: StateAB, c: number, d: string) => state.a, bar: (state: StateAB, c: number, d: string) => state.b }) const selector = createStructuredSelector< { foo: string }, { foo: string bar: number } >({ foo: state => state.foo, bar: state => +state.foo }) const res1 = selector({ foo: '42' }) const foo: string = res1.foo const bar: number = res1.bar // @ts-expect-error selector({ bar: '42' }) // @ts-expect-error selector({ foo: '42' }, { bar: 42 }) createStructuredSelector<{ foo: string }, { bar: number }>({ // @ts-expect-error bar: (state: { baz: boolean }) => 1 }) createStructuredSelector<{ foo: string }, { bar: number }>({ // @ts-expect-error bar: state => state.foo }) createStructuredSelector<{ foo: string }, { bar: number }>({ // @ts-expect-error baz: state => state.foo }) // Test automatic inference of types for createStructuredSelector via overload type State = { foo: string } const FooSelector = (state: State, a: number, b: string) => state.foo const BarSelector = (state: State, a: number, b: string) => +state.foo const selector2 = createStructuredSelector({ foo: FooSelector, bar: BarSelector }) const selectorGenerics = createStructuredSelector<{ foo: typeof FooSelector bar: typeof BarSelector }>({ foo: state => state.foo, bar: state => +state.foo }) type ExpectedResult = { foo: string bar: number } const resOneParam = oneParamSelector({ a: 1, b: 2 }) const resThreeParams = threeParamSelector({ a: 1, b: 2 }, 99, 'blah') const res2: ExpectedResult = selector({ foo: '42' }) const res3: ExpectedResult = selector2({ foo: '42' }, 99, 'test') const resGenerics: ExpectedResult = selectorGenerics( { foo: '42' }, 99, 'test' ) //@ts-expect-error selector2({ bar: '42' }) // @ts-expect-error selectorGenerics({ bar: '42' }) } function testDynamicArrayArgument() { interface Elem { val1: string val2: string } const data: ReadonlyArray<Elem> = [ { val1: 'a', val2: 'aa' }, { val1: 'b', val2: 'bb' } ] createSelector( data.map(obj => () => obj.val1), (...vals) => vals.join(',') ) createSelector( data.map(obj => () => obj.val1), // @ts-expect-error vals => vals.join(',') ) createSelector( data.map(obj => () => obj.val1), (...vals: string[]) => 0 ) // @ts-expect-error createSelector( data.map(obj => () => obj.val1), (...vals: number[]) => 0 ) const s = createSelector( data.map(obj => (state: StateA, fld: keyof Elem) => obj[fld]), (...vals) => vals.join(',') ) s({ a: 42 }, 'val1') s({ a: 42 }, 'val2') // @ts-expect-error s({ a: 42 }, 'val3') } function testStructuredSelectorTypeParams() { type GlobalState = { foo: string bar: number } const selectFoo = (state: GlobalState) => state.foo const selectBar = (state: GlobalState) => state.bar // Output state should be the same as input, if not provided // @ts-expect-error createStructuredSelector<GlobalState>({ foo: selectFoo // bar: selectBar, // ^^^ because this is missing, an error is thrown }) // This works createStructuredSelector<GlobalState>({ foo: selectFoo, bar: selectBar }) // So does this createStructuredSelector<GlobalState, Omit<GlobalState, 'bar'>>({ foo: selectFoo }) } function multiArgMemoize<F extends (...args: any[]) => any>( func: F, a: number, b: string, equalityCheck = defaultEqualityCheck ): F { // @ts-ignore return () => {} } // #384: check for defaultMemoize import { isEqual, groupBy } from 'lodash' import { GetStateFromSelectors } from '../src/types' { interface Transaction { transactionId: string } const toId = (transaction: Transaction) => transaction.transactionId const transactionsIds = (transactions: Transaction[]) => transactions.map(toId) const collectionsEqual = (ts1: Transaction[], ts2: Transaction[]) => isEqual(transactionsIds(ts1), transactionsIds(ts2)) const createTransactionsSelector = createSelectorCreator( defaultMemoize, collectionsEqual ) const createMultiMemoizeArgSelector = createSelectorCreator( multiArgMemoize, 42, 'abcd', defaultEqualityCheck ) const select = createMultiMemoizeArgSelector( (state: { foo: string }) => state.foo, foo => foo + '!' ) // @ts-expect-error - not using defaultMemoize, so clearCache shouldn't exist select.clearCache() const createMultiMemoizeArgSelector2 = createSelectorCreator( multiArgMemoize, 42, // @ts-expect-error defaultEqualityCheck ) const groupTransactionsByLabel = defaultMemoize( (transactions: Transaction[]) => groupBy(transactions, item => item.transactionId), collectionsEqual ) } // #445 function issue445() { interface TestState { someNumber: number | null someString: string | null } interface Object1 { str: string } interface Object2 { num: number } const getNumber = (state: TestState) => state.someNumber const getString = (state: TestState) => state.someString function generateObject1(str: string): Object1 { return { str } } function generateObject2(num: number): Object2 { return { num } } function generateComplexObject( num: number, subObject: Object1, subObject2: Object2 ): boolean { return true } // ################ Tests ################ // Compact selector examples // Should error because generateObject1 can't take null // @ts-expect-error const getObject1 = createSelector([getString], generateObject1) // Should error because generateObject2 can't take null // @ts-expect-error const getObject2 = createSelector([getNumber], generateObject2) // Should error because mismatch of params // @ts-expect-error const getComplexObjectTest1 = createSelector( [getObject1], generateComplexObject ) // Does error, but error is really weird and talks about "Object1 is not assignable to type number" // @ts-expect-error const getComplexObjectTest2 = createSelector( [getNumber, getObject1], generateComplexObject ) // Should error because number can't be null // @ts-expect-error const getComplexObjectTest3 = createSelector( [getNumber, getObject1, getObject2], generateComplexObject ) // Does error, but error is really weird and talks about "Object1 is not assignable to type number" // @ts-expect-error const getComplexObjectTest4 = createSelector( [getObject1, getNumber, getObject2], generateComplexObject ) // Verbose selector examples // Errors correctly, says str can't be null const getVerboseObject1 = createSelector([getString], str => // @ts-expect-error generateObject1(str) ) // Errors correctly, says num can't be null const getVerboseObject2 = createSelector([getNumber], num => // @ts-expect-error generateObject2(num) ) // Errors correctly const getVerboseComplexObjectTest1 = createSelector([getObject1], obj1 => // @ts-expect-error generateComplexObject(obj1) ) // Errors correctly const getVerboseComplexObjectTest2 = createSelector( [getNumber, getObject1], // @ts-expect-error (num, obj1) => generateComplexObject(num, obj1) ) // Errors correctly const getVerboseComplexObjectTest3 = createSelector( [getNumber, getObject1, getObject2], // @ts-expect-error (num, obj1, obj2) => generateComplexObject(num, obj1, obj2) ) // Errors correctly const getVerboseComplexObjectTest4 = createSelector( [getObject1, getNumber, getObject2], // @ts-expect-error (num, obj1, obj2) => generateComplexObject(num, obj1, obj2) ) } // #492 function issue492() { const fooPropSelector = (_: {}, ownProps: { foo: string }) => ownProps.foo const fooBarPropsSelector = ( _: {}, ownProps: { foo: string; bar: string } ) => [ownProps.foo, ownProps.bar] const combinedSelector = createSelector( fooPropSelector, fooBarPropsSelector, (foo, fooBar) => fooBar ) } function customMemoizationOptionTypes() { const customMemoize = ( f: (...args: any[]) => any, a: string, b: number, c: boolean ) => { return f } const customSelectorCreatorCustomMemoizeWorking = createSelectorCreator( customMemoize, 'a', 42, true ) // @ts-expect-error const customSelectorCreatorCustomMemoizeMissingArg = createSelectorCreator( customMemoize, 'a', true ) } // createSelector config options function createSelectorConfigOptions() { const defaultMemoizeAcceptsFirstArgDirectly = createSelector( (state: StateAB) => state.a, (state: StateAB) => state.b, (a, b) => a + b, { memoizeOptions: (a, b) => a === b } ) const defaultMemoizeAcceptsFirstArgAsObject = createSelector( (state: StateAB) => state.a, (state: StateAB) => state.b, (a, b) => a + b, { memoizeOptions: { equalityCheck: (a, b) => a === b } } ) const defaultMemoizeAcceptsArgsAsArray = createSelector( (state: StateAB) => state.a, (state: StateAB) => state.b, (a, b) => a + b, { memoizeOptions: [(a, b) => a === b] } ) const customSelectorCreatorMicroMemoize = createSelectorCreator( microMemoize, { maxSize: 42 } ) customSelectorCreatorMicroMemoize( (state: StateAB) => state.a, (state: StateAB) => state.b, (a, b) => a + b, { memoizeOptions: [ { maxSize: 42 } ] } ) const customSelectorCreatorMemoizeOne = createSelectorCreator(memoizeOne) customSelectorCreatorMemoizeOne( (state: StateAB) => state.a, (state: StateAB) => state.b, (a, b) => a + b, { memoizeOptions: (a, b) => a === b } ) } // Verify more than 12 selectors are accepted // Issue #525 const withLotsOfInputSelectors = createSelector( (_state: StateA) => 1, (_state: StateA) => 2, (_state: StateA) => 3, (_state: StateA) => 4, (_state: StateA) => 5, (_state: StateA) => 6, (_state: StateA) => 7, (_state: StateA) => 8, (_state: StateA) => 9, (_state: StateA) => 10, (_state: StateA) => 11, (_state: StateA) => 12, (_state: StateA) => 13, (_state: StateA) => 14, (_state: StateA) => 15, (_state: StateA) => 16, (_state: StateA) => 17, (_state: StateA) => 18, (_state: StateA) => 19, (_state: StateA) => 20, (_state: StateA) => 21, (_state: StateA) => 22, (_state: StateA) => 23, (_state: StateA) => 24, (_state: StateA) => 25, (_state: StateA) => 26, (_state: StateA) => 27, (_state: StateA) => 28, (...args) => args.length ) type SelectorArray29 = [ (_state: StateA) => 1, (_state: StateA) => 2, (_state: StateA) => 3, (_state: StateA) => 4, (_state: StateA) => 5, (_state: StateA) => 6, (_state: StateA) => 7, (_state: StateA) => 8, (_state: StateA) => 9, (_state: StateA) => 10, (_state: StateA) => 11, (_state: StateA) => 12, (_state: StateA) => 13, (_state: StateA) => 14, (_state: StateA) => 15, (_state: StateA) => 16, (_state: StateA) => 17, (_state: StateA) => 18, (_state: StateA) => 19, (_state: StateA) => 20, (_state: StateA) => 21, (_state: StateA) => 22, (_state: StateA) => 23, (_state: StateA) => 24, (_state: StateA) => 25, (_state: StateA) => 26, (_state: StateA) => 27, (_state: StateA) => 28, (_state: StateA) => 29 ] type Results = SelectorResultArray<SelectorArray29> type State = GetStateFromSelectors<SelectorArray29> // Ensure that input functions with mismatched states raise errors { const input1 = (state: string) => 1 const input2 = (state: number) => 2 const selector = createSelector(input1, input2, (...args) => 0) // @ts-expect-error selector('foo') // @ts-expect-error selector(5) } { const selector = createSelector( (state: { foo: string }) => 1, (state: { bar: string }) => 2, (...args) => 0 ) selector({ foo: '', bar: '' }) // @ts-expect-error selector({ foo: '' }) // @ts-expect-error selector({ bar: '' }) } { const selector = createSelector( (state: { foo: string }) => 1, (state: { foo: string }) => 2, (...args) => 0 ) // @ts-expect-error selector({ foo: '', bar: '' }) selector({ foo: '' }) // @ts-expect-error selector({ bar: '' }) } // Issue #526 function testInputSelectorWithUndefinedReturn() { type Input = { field: number | undefined } type Output = string type SelectorType = (input: Input) => Output const input = ({ field }: Input) => field const result = (out: number | undefined): Output => 'test' // Make sure the selector type is honored const selector: SelectorType = createSelector( ({ field }: Input) => field, args => 'test' ) // even when memoizeOptions are passed const selector2: SelectorType = createSelector( ({ field }: Input) => field, args => 'test', { memoizeOptions: { maxSize: 42 } } ) // Make sure inference of functions works... const selector3: SelectorType = createSelector(input, result) const selector4: SelectorType = createSelector(input, result, { memoizeOptions: { maxSize: 42 } }) } function deepNesting() { type State = { foo: string } const readOne = (state: State) => state.foo const selector0 = createSelector(readOne, one => one) const selector1 = createSelector(selector0, s => s) const selector2 = createSelector(selector1, s => s) const selector3 = createSelector(selector2, s => s) const selector4 = createSelector(selector3, s => s) const selector5 = createSelector(selector4, s => s) const selector6 = createSelector(selector5, s => s) const selector7 = createSelector(selector6, s => s) const selector8: Selector<State, string, never> = createSelector( selector7, s => s ) const selector9 = createSelector(selector8, s => s) const selector10 = createSelector(selector9, s => s) const selector11 = createSelector(selector10, s => s) const selector12 = createSelector(selector11, s => s) const selector13 = createSelector(selector12, s => s) const selector14 = createSelector(selector13, s => s) const selector15 = createSelector(selector14, s => s) const selector16 = createSelector(selector15, s => s) const selector17: OutputSelector< [(state: State) => string], ReturnType<typeof selector16>, (s: string) => string, never > = createSelector(selector16, s => s) const selector18 = createSelector(selector17, s => s) const selector19 = createSelector(selector18, s => s) const selector20 = createSelector(selector19, s => s) const selector21 = createSelector(selector20, s => s) const selector22 = createSelector(selector21, s => s) const selector23 = createSelector(selector22, s => s) const selector24 = createSelector(selector23, s => s) const selector25 = createSelector(selector24, s => s) const selector26: Selector< typeof selector25 extends Selector<infer S> ? S : never, ReturnType<typeof selector25>, never > = createSelector(selector25, s => s) const selector27 = createSelector(selector26, s => s) const selector28 = createSelector(selector27, s => s) const selector29 = createSelector(selector28, s => s) } function issue540() { const input1 = ( _: StateA, { testNumber }: { testNumber: number }, c: number, d: string ) => testNumber const input2 = ( _: StateA, { testString }: { testString: string }, c: number | string ) => testString const input3 = ( _: StateA, { testBoolean }: { testBoolean: boolean }, c: number | string, d: string ) => testBoolean const input4 = (_: StateA, { testString2 }: { testString2: string }) => testString2 const testSelector = createSelector( input1, input2, input3, input4, (testNumber, testString, testBoolean) => testNumber + testString ) const state: StateA = { a: 42 } const test = testSelector( state, { testNumber: 1, testString: '10', testBoolean: true, testString2: 'blah' }, 42, 'blah' ) // #541 const selectProp1 = createSelector( [ (state: StateA) => state, (state: StateA, props: { prop1: number }) => props ], (state, { prop1 }) => [state, prop1] ) const selectProp2 = createSelector( [selectProp1, (state, props: { prop2: number }) => props], (state, { prop2 }) => [state, prop2] ) selectProp1({ a: 42 }, { prop1: 1 }) // @ts-expect-error selectProp2({ a: 42 }, { prop2: 2 }) } function issue548() { interface State { value: Record<string, any> | null loading: boolean } interface Props { currency: string } const isLoading = createSelector( (state: State) => state, (_: State, props: Props) => props.currency, ({ loading }, currency) => loading ) const mapData = createStructuredSelector({ isLoading, test2: (state: State) => 42 }) const result = mapData({ value: null, loading: false }, { currency: 'EUR' }) } function issue550() { const some = createSelector( (a: number) => a, (_a: number, b: number) => b, (a, b) => a + b ) const test = some(1, 2) } function rtkIssue1750() { const slice = createSlice({ name: 'test', initialState: 0, reducers: {} }) interface Pokemon { name: string } // Define a service using a base URL and expected endpoints const pokemonApi = createApi({ reducerPath: 'pokemonApi', baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }), endpoints: builder => ({ getPokemonByName: builder.query<Pokemon, string>({ query: name => `pokemon/${name}` }) }) }) const store = configureStore({ reducer: { test: slice.reducer, [pokemonApi.reducerPath]: pokemonApi.reducer }, middleware: getDefaultMiddleware => getDefaultMiddleware().concat(pokemonApi.middleware) }) type RootState = ReturnType<typeof store.getState> const selectTest = createSelector( (state: RootState) => state.test, test => test ) const useAppSelector: TypedUseSelectorHook<RootState> = useSelector // Selector usage should compile correctly const testItem = selectTest(store.getState()) function App() { const test = useAppSelector(selectTest) return null } } function handleNestedIncompatTypes() { // Incompatible parameters should force errors even for nested fields. // One-level-deep fields get stripped to empty objects, so they // should be replaced with `never`. // Deeper fields should get caught by TS. // Playground: https://tsplay.dev/wg6X0W const input1a = (_: StateA, param: { b: number }) => param.b const input1b = (_: StateA, param: { b: string }) => param.b const testSelector1 = createSelector(input1a, input1b, () => ({})) // @ts-expect-error testSelector1({ a: 42 }, { b: 99 }) // should not compile const input2a = (_: StateA, param: { b: { c: number } }) => param.b.c const input2b = (_: StateA, param: { b: { c: string } }) => param.b.c const testSelector2 = createSelector(input2a, input2b, (c1, c2) => {}) // @ts-expect-error testSelector2({ a: 42 }, { b: { c: 99 } }) } function issue554a() { interface State { foo: string bar: number } const initialState: State = { foo: 'This is Foo', bar: 1 } const getFoo = (state: State) => { return state.foo } getFoo(initialState) const getBar = (state: State) => { return state.bar } getBar(initialState) const simple = createSelector(getFoo, getBar, (foo, bar) => { return `${foo} => ${bar}` }) simple(initialState) // Input selectors with positional args const firstInput = (_: State, first: string) => first // Skip the first arg and return only the second. const secondInput = (_: State, _first: string, second: number) => second const complexOne = createSelector( getFoo, getBar, firstInput, (foo, bar, first) => { return `${foo} => ${bar} || ${first}` } ) complexOne(initialState, 'first') const complexTwo = createSelector( getFoo, getBar, firstInput, secondInput, (foo, bar, first, second) => { return `${foo} => ${bar} || ${first} and ${second}` } ) // TS should complain since 'second' should be `number` // @ts-expect-error complexTwo(initialState, 'first', 'second') } function issue554b() { interface State { counter1: number counter2: number } const selectTest = createSelector( (state: State, numberA?: number) => numberA, (state: State) => state.counter2, (numberA, counter2) => (numberA ? numberA + counter2 : counter2) ) type selectTestParams = Parameters<typeof selectTest> const p1: selectTestParams = [{ counter1: 1, counter2: 2 }, 42] expectExactType<[State, number?]>(p1) const result = selectTest({ counter1: 1, counter2: 2 }, 42) } function issue554c() { interface State { counter1: number counter2: number } const selectTest = createSelector( (state: State, numberA?: number) => numberA, // `numberA` is optional (state: State) => state.counter2, (numberA, counter2) => (numberA ? numberA + counter2 : counter2) ) // @ts-expect-error const value = selectTest({ counter1: 0, counter2: 0 }, 'what?') const selectTest2 = createSelector( (state: State, numberA: number) => numberA, // `numberA` is not optional anymore (state: State) => state.counter2, (numberA, counter2) => (numberA ? numberA + counter2 : counter2) ) // @ts-expect-error const value2 = selectTest2({ counter1: 0, counter2: 0 }, 'what?') } function issue555() { type IReduxState = { ui: { x: string y: string } } const someSelector1 = createSelector( (state: IReduxState, param: 'x' | 'y' | undefined) => param !== undefined ? state.ui[param] : null, (a: string | null) => a ) const someSelector2 = createSelector( (state: IReduxState, param?: 'x' | 'y') => param !== undefined ? state.ui[param] : null, (a: string | null) => a ) const someSelector3 = createSelector( (state: IReduxState, param: 'x' | 'y' | null) => param !== null ? state.ui[param] : null, (a: string | null) => a ) const state = { ui: { x: '1', y: '2' } } const selectorResult1 = someSelector1(state, undefined) const selectorResult2 = someSelector2(state, undefined) const selectorResult3 = someSelector3(state, null) }
the_stack
import mongoose from 'mongoose'; import { IncomingWebhookSendArguments } from '@slack/webhook'; import { ChatPostMessageArguments, WebClient } from '@slack/web-api'; import { generateWebClient, GrowiCommand, InteractionPayloadAccessor, markdownSectionBlock, SlackbotType, RespondUtil, GrowiBotEvent, } from '@growi/slack'; import loggerFactory from '~/utils/logger'; import S2sMessage from '../models/vo/s2s-message'; import ConfigManager from './config-manager'; import { S2sMessagingService } from './s2s-messaging/base'; import { S2sMessageHandlable } from './s2s-messaging/handlable'; import { SlackCommandHandlerError } from '../models/vo/slack-command-handler-error'; import { LinkSharedEventHandler } from './slack-event-handler/link-shared'; import { EventActionsPermission } from '../interfaces/slack-integration/events'; const logger = loggerFactory('growi:service:SlackBotService'); const OFFICIAL_SLACKBOT_PROXY_URI = 'https://slackbot-proxy.growi.org'; type S2sMessageForSlackIntegration = S2sMessage & { updatedAt: Date }; export class SlackIntegrationService implements S2sMessageHandlable { crowi!: any; configManager!: ConfigManager; s2sMessagingService!: S2sMessagingService; lastLoadedAt?: Date; linkSharedHandler!: LinkSharedEventHandler; constructor(crowi) { this.crowi = crowi; this.configManager = crowi.configManager; this.s2sMessagingService = crowi.s2sMessagingService; this.linkSharedHandler = new LinkSharedEventHandler(crowi); this.initialize(); } initialize() { this.lastLoadedAt = new Date(); } /** * @inheritdoc */ shouldHandleS2sMessage(s2sMessage: S2sMessageForSlackIntegration): boolean { const { eventName, updatedAt } = s2sMessage; if (eventName !== 'slackIntegrationServiceUpdated' || updatedAt == null) { return false; } return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt); } /** * @inheritdoc */ async handleS2sMessage(): Promise<void> { const { configManager } = this.crowi; logger.info('Reset slack bot by pubsub notification'); await configManager.loadConfigs(); this.initialize(); } async publishUpdatedMessage(): Promise<void> { const { s2sMessagingService } = this; if (s2sMessagingService != null) { const s2sMessage = new S2sMessage('slackIntegrationServiceUpdated', { updatedAt: new Date() }); try { await s2sMessagingService.publish(s2sMessage); } catch (e) { logger.error('Failed to publish update message with S2sMessagingService: ', e.message); } } } get isSlackConfigured(): boolean { return this.isSlackbotConfigured || this.isSlackLegacyConfigured; } get isSlackbotConfigured(): boolean { const hasSlackbotType = !!this.configManager.getConfig('crowi', 'slackbot:currentBotType'); return hasSlackbotType; } get isSlackLegacyConfigured(): boolean { // for legacy util const hasSlackToken = !!this.configManager.getConfig('notification', 'slack:token'); const hasSlackIwhUrl = !!this.configManager.getConfig('notification', 'slack:incomingWebhookUrl'); return hasSlackToken || hasSlackIwhUrl; } private isCheckTypeValid(): boolean { const currentBotType = this.configManager.getConfig('crowi', 'slackbot:currentBotType'); if (currentBotType == null) { throw new Error('The config \'SLACKBOT_TYPE\'(ns: \'crowi\', key: \'slackbot:currentBotType\') must be set.'); } return true; } get proxyUriForCurrentType(): string { const currentBotType = this.configManager.getConfig('crowi', 'slackbot:currentBotType'); // TODO assert currentBotType is not null and CUSTOM_WITHOUT_PROXY let proxyUri: string; switch (currentBotType) { case SlackbotType.OFFICIAL: proxyUri = OFFICIAL_SLACKBOT_PROXY_URI; break; default: proxyUri = this.configManager.getConfig('crowi', 'slackbot:proxyUri'); break; } return proxyUri; } /** * generate WebClient instance for CUSTOM_WITHOUT_PROXY type */ async generateClientForCustomBotWithoutProxy(): Promise<WebClient> { this.isCheckTypeValid(); const token = this.configManager.getConfig('crowi', 'slackbot:withoutProxy:botToken'); if (token == null) { throw new Error('The config \'SLACK_BOT_TOKEN\'(ns: \'crowi\', key: \'slackbot:withoutProxy:botToken\') must be set.'); } return generateWebClient(token); } /** * generate WebClient instance by tokenPtoG * @param tokenPtoG */ async generateClientByTokenPtoG(tokenPtoG: string): Promise<WebClient> { this.isCheckTypeValid(); const SlackAppIntegration = mongoose.model('SlackAppIntegration'); const slackAppIntegration = await SlackAppIntegration.findOne({ tokenPtoG }); if (slackAppIntegration == null) { throw new Error('No SlackAppIntegration exists that corresponds to the tokenPtoG specified.'); } return this.generateClientBySlackAppIntegration(slackAppIntegration as unknown as { tokenGtoP: string; }); } /** * generate WebClient instance by tokenPtoG * @param tokenPtoG */ async generateClientForPrimaryWorkspace(): Promise<WebClient> { this.isCheckTypeValid(); const currentBotType = this.configManager.getConfig('crowi', 'slackbot:currentBotType'); if (currentBotType === SlackbotType.CUSTOM_WITHOUT_PROXY) { return this.generateClientForCustomBotWithoutProxy(); } // retrieve primary SlackAppIntegration const SlackAppIntegration = mongoose.model('SlackAppIntegration'); const slackAppIntegration = await SlackAppIntegration.findOne({ isPrimary: true }); if (slackAppIntegration == null) { throw new Error('None of the primary SlackAppIntegration exists.'); } return this.generateClientBySlackAppIntegration(slackAppIntegration as unknown as { tokenGtoP: string; }); } /** * generate WebClient instance by SlackAppIntegration * @param slackAppIntegration */ async generateClientBySlackAppIntegration(slackAppIntegration: { tokenGtoP: string }): Promise<WebClient> { this.isCheckTypeValid(); // connect to proxy const serverUri = new URL('/g2s', this.proxyUriForCurrentType); const headers = { 'x-growi-gtop-tokens': slackAppIntegration.tokenGtoP, }; return generateWebClient(undefined, serverUri.toString(), headers); } async postMessage(messageArgs: ChatPostMessageArguments, slackAppIntegration?: { tokenGtoP: string; }): Promise<void> { // use legacy slack configuration if (this.isSlackLegacyConfigured && !this.isSlackbotConfigured) { return this.postMessageWithLegacyUtil(messageArgs); } const client = slackAppIntegration == null ? await this.generateClientForPrimaryWorkspace() : await this.generateClientBySlackAppIntegration(slackAppIntegration); try { await client.chat.postMessage(messageArgs); } catch (error) { logger.debug('Post error', error); logger.debug('Sent data to slack is:', messageArgs); throw error; } } private async postMessageWithLegacyUtil(messageArgs: ChatPostMessageArguments | IncomingWebhookSendArguments): Promise<void> { const slackLegacyUtil = require('../util/slack-legacy')(this.crowi); try { await slackLegacyUtil.postMessage(messageArgs); } catch (error) { logger.debug('Post error', error); logger.debug('Sent data to slack is:', messageArgs); throw error; } } /** * Handle /commands endpoint */ async handleCommandRequest(growiCommand: GrowiCommand, client, body, respondUtil: RespondUtil): Promise<void> { const { growiCommandType } = growiCommand; const module = `./slack-command-handler/${growiCommandType}`; let handler; try { handler = require(module)(this.crowi); } catch (err) { const text = `*No command.*\n \`command: ${growiCommand.text}\``; logger.error(err); throw new SlackCommandHandlerError(text, { respondBody: { text, blocks: [ markdownSectionBlock('*No command.*\n Hint\n `/growi [command] [keyword]`'), ], }, }); } // Do not wrap with try-catch. Errors thrown by slack-command-handler modules will be handled in router. return handler.handleCommand(growiCommand, client, body, respondUtil); } async handleBlockActionsRequest( client, interactionPayload: any, interactionPayloadAccessor: InteractionPayloadAccessor, respondUtil: RespondUtil, ): Promise<void> { const { actionId } = interactionPayloadAccessor.getActionIdAndCallbackIdFromPayLoad(); const commandName = actionId.split(':')[0]; const handlerMethodName = actionId.split(':')[1]; const module = `./slack-command-handler/${commandName}`; let handler; try { handler = require(module)(this.crowi); } catch (err) { throw new SlackCommandHandlerError(`No interaction.\n \`actionId: ${actionId}\``); } // Do not wrap with try-catch. Errors thrown by slack-command-handler modules will be handled in router. return handler.handleInteractions(client, interactionPayload, interactionPayloadAccessor, handlerMethodName, respondUtil); } async handleViewSubmissionRequest( client, interactionPayload: any, interactionPayloadAccessor: InteractionPayloadAccessor, respondUtil: RespondUtil, ): Promise<void> { const { callbackId } = interactionPayloadAccessor.getActionIdAndCallbackIdFromPayLoad(); const commandName = callbackId.split(':')[0]; const handlerMethodName = callbackId.split(':')[1]; const module = `./slack-command-handler/${commandName}`; let handler; try { handler = require(module)(this.crowi); } catch (err) { throw new SlackCommandHandlerError(`No interaction.\n \`callbackId: ${callbackId}\``); } // Do not wrap with try-catch. Errors thrown by slack-command-handler modules will be handled in router. return handler.handleInteractions(client, interactionPayload, interactionPayloadAccessor, handlerMethodName, respondUtil); } async handleEventsRequest(client: WebClient, growiBotEvent: GrowiBotEvent<any>, permission: EventActionsPermission, data?: any): Promise<void> { const { eventType } = growiBotEvent; const { channel = '' } = growiBotEvent.event; // only channelId if (this.linkSharedHandler.shouldHandle(eventType, permission, channel)) { return this.linkSharedHandler.handleEvent(client, growiBotEvent, data); } logger.error(`Any event actions are not permitted, or, a handler for '${eventType}' event is not implemented`); } }
the_stack
import { faker } from '@faker-js/faker'; import ObjectId from 'bson-objectid'; import { format as dateFormat } from 'date-fns'; import { HelperOptions, SafeString } from 'handlebars'; import { EOL } from 'os'; import { FromBase64, fromSafeString, numberFromSafeString, RandomInt, ToBase64 } from '../utils'; /** * Handlebars may insert its own `options` object as the last argument. * Be careful when retrieving `defaultValue` or any other last param. * * use: * if (typeof defaultValue === 'object') { * defaultValue = ''; * } * * or: * args[args.length - 1] */ export const Helpers = { repeat: function (...args: any[]) { let content = ''; let count = 0; const options = args[args.length - 1]; const data = { ...options }; if (arguments.length === 3) { // If given two numbers then pick a random one between the two count = RandomInt(args[0], args[1]); } else if (arguments.length === 2) { count = args[0]; } else { throw new Error('The repeat helper requires a numeric param'); } for (let i = 0; i < count; i++) { // You can access these in your template using @index, @total, @first, @last data.index = i; data.total = count; data.first = i === 0; data.last = i === count - 1; // By using 'this' as the context the repeat block will inherit the current scope content = content + options.fn(this, { data }); if (options.hash.comma !== false) { // Trim any whitespace left by handlebars and add a comma if it doesn't already exist, // also trim any trailing commas that might be at the end of the loop content = content.trimRight(); if (i < count - 1 && content.charAt(content.length - 1) !== ',') { content += ','; } else if ( i === count - 1 && content.charAt(content.length - 1) === ',' ) { content = content.slice(0, -1); } content += EOL; } } return content; }, // return one random item oneOf: function (itemList: string[]) { return itemList[RandomInt(0, itemList.length - 1)]; }, // return some random item as an array (to be used in triple braces) or as a string someOf: function ( itemList: string[], min: number, max: number, asArray = false ) { const randomItems = itemList .sort(() => 0.5 - Math.random()) .slice(0, RandomInt(min, max)); if (asArray === true) { return `["${randomItems.join('","')}"]`; } return randomItems; }, // create an array array: function (...args: any[]) { // remove last item (handlebars options argument) return args.slice(0, args.length - 1); }, // switch cases switch: function (value: any, options: HelperOptions) { options.data.found = false; options.data.switchValue = fromSafeString(value); return options.fn(options); }, // case helper for switch case: function (...args: any[]) { let value = ''; let options; if (args.length >= 2) { value = args[0]; options = args[args.length - 1]; } if (value === options.data.switchValue && !options.data.found) { // check switch value to simulate break options.data.found = true; return options.fn(options); } }, // default helper for switch default: function (options: HelperOptions) { // if there is still a switch value show default content if (!options.data.found) { delete options.data.switchValue; return options.fn(options); } return ''; }, // provide current time with format now: function (format: any) { return dateFormat( new Date(), typeof format === 'string' ? format : "yyyy-MM-dd'T'HH:mm:ss.SSSxxx", { useAdditionalWeekYearTokens: true, useAdditionalDayOfYearTokens: true } ); }, // converts the input to a base64 string base64: function (...args: any[]) { const hbsOptions: HelperOptions & hbs.AST.Node = args[args.length - 1]; let content: string; if (args.length === 1) { content = hbsOptions.fn(hbsOptions); } else { content = args[0]; } // convert content toString in case we pass a SafeString from another helper return new SafeString(ToBase64(content.toString())); }, // convert base64 to a string base64Decode: function (...args: any[]) { const hbsOptions: HelperOptions & hbs.AST.Node = args[args.length - 1]; let content: string; if (args.length === 1) { content = hbsOptions.fn(hbsOptions); } else { content = args[0]; } // convert content toString in case we pass a SafeString from another helper return new SafeString(FromBase64(content.toString())); }, // adds a newline to the output newline: function () { return '\n'; }, // returns a compatible ObjectId // * if value is undefined or null returns a random ObjectId // * if value is defined is used a seed, can be a string, number or Buffer objectId: function (defaultValue: any) { if (typeof defaultValue === 'object') { defaultValue = undefined; } return new ObjectId(defaultValue).toHexString(); }, // concat multiple string and/or variables (like @index) concat: function (...args: any[]) { // remove handlebars options const toConcat = args.slice(0, args.length - 1); return toConcat.join(''); }, // Shift a date and time by a specified ammount. dateTimeShift: function (options: HelperOptions) { let date: undefined | Date | string; let format: undefined | string; if (typeof options === 'object' && options.hash) { date = fromSafeString(options.hash['date']); format = fromSafeString(options.hash['format']); } // If no date is specified, default to now. If a string is specified, then parse it to a date. const dateToShift: Date = date === undefined ? new Date() : typeof date === 'string' ? new Date(date) : date; if (typeof options === 'object' && options !== null && options.hash) { const days = numberFromSafeString(options.hash['days']); const months = numberFromSafeString(options.hash['months']); const years = numberFromSafeString(options.hash['years']); const hours = numberFromSafeString(options.hash['hours']); const minutes = numberFromSafeString(options.hash['minutes']); const seconds = numberFromSafeString(options.hash['seconds']); if (!isNaN(days)) { dateToShift.setDate(dateToShift.getDate() + days); } if (!isNaN(months)) { dateToShift.setMonth(dateToShift.getMonth() + months); } if (!isNaN(years)) { dateToShift.setFullYear(dateToShift.getFullYear() + years); } if (!isNaN(hours)) { dateToShift.setHours(dateToShift.getHours() + hours); } if (!isNaN(minutes)) { dateToShift.setMinutes(dateToShift.getMinutes() + minutes); } if (!isNaN(seconds)) { dateToShift.setSeconds(dateToShift.getSeconds() + seconds); } } return dateFormat( dateToShift, typeof format === 'string' ? format : "yyyy-MM-dd'T'HH:mm:ss.SSSxxx", { useAdditionalWeekYearTokens: true, useAdditionalDayOfYearTokens: true } ); }, // Get's the index of a search string within another string. indexOf: function ( data: string | SafeString | HelperOptions, search: string | SafeString | HelperOptions | undefined, position?: number | string | SafeString | HelperOptions | undefined ) { data = typeof data === 'object' && !(data instanceof SafeString) ? '' : data.toString(); search = (typeof search === 'object' || typeof search === 'undefined') && !(search instanceof SafeString) ? '' : search.toString(); position = (typeof position === 'object' || typeof position === 'undefined') && !(position instanceof SafeString) ? undefined : Number(position.toString()); if (typeof position === 'number') { return data.indexOf(search, position); } else { return data.indexOf(search); } }, // Returns if the provided search string is contained in the data string. includes: function ( data: string | SafeString | HelperOptions, search: string | SafeString | HelperOptions | undefined ) { data = (typeof data === 'object' || typeof data == 'undefined') && !(data instanceof SafeString) ? '' : data.toString(); search = (typeof search === 'object' || typeof search == 'undefined') && !(search instanceof SafeString) ? '' : search.toString(); return data.includes(search); }, // Returns the substring of a string based on the passed in starting index and length. substr: function ( data: string | SafeString | HelperOptions, from: number | string | SafeString | HelperOptions | undefined, length: number | string | SafeString | HelperOptions | undefined ) { data = typeof data === 'object' && !(data instanceof SafeString) ? '' : data.toString(); const fromValue = (typeof from === 'object' || typeof from == 'undefined') && !(from instanceof SafeString) ? 0 : Number(from.toString()); const lengthValue = (typeof length === 'object' || typeof length == 'undefined') && !(length instanceof SafeString) ? undefined : Number(length.toString()); if (typeof lengthValue !== 'undefined') { return data.substr(fromValue, lengthValue); } else { return data.substr(fromValue); } }, // Split a string, default separator is " " split: function (...args: any[]) { const parameters = args.slice(0, -1); if (parameters.length === 0) { return ''; } // make it compatible with SafeString (from queryParam, etc) const data = fromSafeString(parameters[0]); let separator; if (parameters.length >= 2) { separator = parameters[1]; } if (!separator || typeof separator !== 'string') { separator = ' '; } if (!data || typeof data !== 'string') { return ''; } return data.split(separator); }, lowercase: function (...args: any[]) { const parameters = args.slice(0, -1); if (parameters.length === 0) { return ''; } // make it compatible with SafeString (from queryParam, etc) const text = fromSafeString(parameters[0]); return text.toLowerCase(); }, uppercase: function (...args: any[]) { const parameters = args.slice(0, -1); if (parameters.length === 0) { return ''; } // make it compatible with SafeString (from queryParam, etc) const text = fromSafeString(parameters[0]); return text.toUpperCase(); }, // Joins Array Values as String with separator join: function (arr: string[], sep: string) { if (!arr || !(arr instanceof Array)) { return arr; } return arr.join(typeof sep !== 'string' ? ', ' : sep); }, slice: function ( arr: Array<unknown>, sliceFrom: number, sliceTo?: number | unknown ) { if (!(arr instanceof Array)) { return ''; } return typeof sliceTo === 'number' ? arr.slice(sliceFrom, sliceTo) : arr.slice(sliceFrom); }, // Returns array length or string length len: function (arr: Array<unknown> | string) { return typeof arr !== 'string' && !Array.isArray(arr) ? 0 : arr.length; }, eq: function (num1: number | string, num2: number | string) { const number1 = Number(num1); const number2 = Number(num2); if (Number.isNaN(number1) || Number.isNaN(number2)) { return false; } return number1 === number2; }, gt: function (num1: number | string, num2: number | string) { const number1 = Number(num1); const number2 = Number(num2); if (Number.isNaN(number1) || Number.isNaN(number2)) { return false; } return number1 > number2; }, gte: function (num1: number | string, num2: number | string) { const number1 = Number(num1); const number2 = Number(num2); if (Number.isNaN(number1) || Number.isNaN(number2)) { return false; } return number1 >= number2; }, lt: function (num1: number | string, num2: number | string) { const number1 = Number(num1); const number2 = Number(num2); if (Number.isNaN(number1) || Number.isNaN(number2)) { return false; } return number1 < number2; }, lte: function (num1: number | string, num2: number | string) { const number1 = Number(num1); const number2 = Number(num2); if (Number.isNaN(number1) || Number.isNaN(number2)) { return false; } return number1 <= number2; }, // set a variable to be used in the template setVar: function (name: string, value: unknown) { if (typeof name === 'object') { return; } // return if not all parameters have been provided if (arguments.length < 3) { return; } this[name] = value; }, int: function (...args: any[]) { const options: { min?: number; max?: number; precision?: number } = { precision: 1 }; if (args.length >= 2 && typeof args[0] === 'number') { options.min = args[0]; } if (args.length >= 3 && typeof args[1] === 'number') { options.max = args[1]; } return faker.datatype.number(options); }, float: function (...args: any[]) { const options: { min?: number; max?: number; precision?: number } = { precision: Math.pow(10, -10) }; if (args.length >= 2 && typeof args[0] === 'number') { options.min = args[0]; } if (args.length >= 3 && typeof args[1] === 'number') { options.max = args[1]; } return faker.datatype.number(options); }, date: function (...args: any[]) { let from, to, format; if ( args.length >= 3 && typeof args[0] === 'string' && typeof args[1] === 'string' ) { from = args[0]; to = args[1]; const randomDate = faker.date.between(from, to); if (args.length === 4 && typeof args[2] === 'string') { format = args[2]; return dateFormat(randomDate, format, { useAdditionalWeekYearTokens: true, useAdditionalDayOfYearTokens: true }); } return randomDate.toString(); } return ''; }, time: function (...args: any[]) { let from, to, format; if ( args.length >= 3 && typeof args[0] === 'string' && typeof args[1] === 'string' ) { from = `1970-01-01T${args[0]}`; to = `1970-01-01T${args[1]}`; if (args.length === 4 && typeof args[2] === 'string') { format = args[2]; } return dateFormat(faker.date.between(from, to), format || 'HH:mm', { useAdditionalWeekYearTokens: true, useAdditionalDayOfYearTokens: true }); } return ''; }, boolean: function () { return faker.datatype.boolean(); }, title: function () { return faker.name.prefix(); }, firstName: function () { return faker.name.firstName(); }, lastName: function () { return faker.name.lastName(); }, company: function () { return faker.company.companyName(); }, domain: function () { return faker.internet.domainName(); }, tld: function () { return faker.internet.domainSuffix(); }, email: function () { return faker.internet.email(); }, street: function () { return faker.address.streetAddress(); }, city: function () { return faker.address.city(); }, country: function () { return faker.address.country(); }, countryCode: function () { return faker.address.countryCode(); }, zipcode: function () { return faker.address.zipCode(); }, postcode: function () { return faker.address.zipCode(); }, lat: function () { return faker.address.latitude(); }, long: function () { return faker.address.longitude(); }, phone: function () { return faker.phone.phoneNumber(); }, color: function () { return faker.commerce.color(); }, hexColor: function () { return Math.floor( faker.datatype.number({ min: 0, max: 1, precision: Math.pow(10, -16) }) * 16777215 ).toString(16); }, guid: function () { return faker.datatype.uuid(); }, ipv4: function () { return faker.internet.ip(); }, ipv6: function () { return faker.internet.ipv6(); }, lorem: function (...args: any[]) { let count: number | undefined; if (args.length >= 2 && typeof args[0] === 'number') { count = args[0]; } return faker.lorem.sentence(count); }, // Handlebars hook when a helper is missing helperMissing: function () { return ''; }, // Maths helpers add: function (...args: any[]) { // Check if there are parameters if (args.length === 1) { return ''; } return args.reduce((sum, item, index) => { if (!isNaN(Number(fromSafeString(item))) && index !== args.length - 1) { return Number(sum) + Number(item); } else { return Number(sum); } }); }, subtract: function (...args: any[]) { // Check if there are parameters if (args.length === 1) { return ''; } return args.reduce((sum, item, index) => { if (!isNaN(Number(fromSafeString(item))) && index !== args.length - 1) { return Number(sum) - Number(item); } else { return Number(sum); } }); }, multiply: function (...args: any[]) { // Check if there are parameters if (args.length === 1) { return ''; } return args.reduce((sum, item, index) => { if (!isNaN(Number(fromSafeString(item))) && index !== args.length - 1) { return Number(sum) * Number(item); } else { return Number(sum); } }); }, divide: function (...args: any[]) { // Check if there are parameters if (args.length === 1) { return ''; } return args.reduce((sum, item, index) => { if ( !isNaN(Number(fromSafeString(item))) && index !== args.length - 1 && Number(item) !== 0 ) { return Number(sum) / Number(item); } else { return Number(sum); } }); }, modulo: function (...args: any[]) { const parameters = args.slice(0, -1); // Check if there are parameters or if attempting to compute modulo 0 if (parameters.length <= 1 || Number(parameters[1]) === 0) { return ''; } return Number(parameters[0]) % Number(parameters[1]); }, ceil: function (...args: any[]) { const parameters = args.slice(0, -1); // Check if there are parameters if (parameters.length === 0) { return ''; } return Math.ceil(Number(parameters[0])); }, floor: function (...args: any[]) { const parameters = args.slice(0, -1); // Check if there are parameters if (parameters.length === 0) { return ''; } return Math.floor(Number(parameters[0])); }, round: function (...args: any[]) { const parameters = args.slice(0, -1); // Check if there are parameters if (parameters.length === 0) { return ''; } return Math.round(Number(parameters[0])); }, toFixed: function (number: number, digits: number) { if (Number.isNaN(Number(number))) { number = 0; } if (Number.isNaN(Number(digits))) { digits = 0; } return Number(number).toFixed(digits); }, // Returns Objects as formatted JSON String stringify: function (data: unknown, options: HelperOptions) { if (!options) { return; } if (data && typeof data === 'object') { return JSON.stringify(data, null, 2); } else { return data; } } };
the_stack
import * as assert from "assert" import { ScorerCache } from "../../../src/Services/Search/Scorer/QuickOpenScorer" import { filter, processSearchTerm } from "./../../../src/Services/Menu/Filter/VSCodeFilter" describe("processSearchTerm", () => { let cache: ScorerCache beforeEach(() => { cache = {} }) it("Correctly matches word.", async () => { const testString = "src" const testList = [ { label: "index.ts", detail: "browser/src" }, { label: "index.ts", detail: "browser/test" }, ] const result = processSearchTerm(testString, testList, cache) const filteredResult = result.filter(r => r.score !== 0) // Remove the score since it can change if we updated the // module. As long as its not 0 that is enough here. assert.equal(result[0].score > 0, true) delete result[0].score const expectedResult = [ { label: "index.ts", labelHighlights: [] as number[], detail: "browser/src", detailHighlights: [8, 9, 10], }, ] assert.deepEqual(filteredResult, expectedResult) }) it("Correctly score case-match higher", async () => { const testString = "SRC" const testList = [ { label: "index.ts", detail: "browser/src" }, { label: "index.ts", detail: "browser/SRC" }, ] const result = processSearchTerm(testString, testList, cache) // Check the exact case match scores higher const lowercase = result.find(r => r.detail === "browser/src") const uppercase = result.find(r => r.detail === "browser/SRC") assert.equal(uppercase.score > lowercase.score, true) // Both should be highlighted though assert.deepEqual(uppercase.detailHighlights, [8, 9, 10]) assert.deepEqual(lowercase.detailHighlights, [8, 9, 10]) }) it("Correctly returns no matches.", async () => { const testString = "zzz" const testList = [ { label: "index.ts", detail: "browser/src" }, { label: "index.ts", detail: "browser/test" }, ] const result = processSearchTerm(testString, testList, cache) const filteredResult = result.filter(r => r.score !== 0) assert.deepEqual(filteredResult, []) }) }) describe("vsCodeFilter", () => { it("Correctly matches string.", async () => { const testString = "index" const testList = [ { label: "index.ts", detail: "browser/src" }, { label: "main.ts", detail: "browser/src" }, { label: "index.ts", detail: "browser/test" }, ] const result = filter(testList, testString) // Remove the score since it can change if we updated the // module. // However, the score should be equal due to an exact match on both. assert.equal(result[0].score === result[1].score, true) delete result[0].score delete result[1].score const expectedResult = [ { label: "index.ts", labelHighlights: [0, 1, 2, 3, 4], detail: "browser/src", detailHighlights: [] as number[], }, { label: "index.ts", labelHighlights: [0, 1, 2, 3, 4], detail: "browser/test", detailHighlights: [] as number[], }, ] assert.deepEqual(result, expectedResult) }) it("Correctly matches string with extension.", async () => { const testString = "index.ts" const testList = [ { label: "index.ts", detail: "browser/src" }, { label: "main.ts", detail: "browser/src" }, { label: "index.ts", detail: "browser/test" }, ] const result = filter(testList, testString) // Remove the score since it can change if we updated the // module. // However, the score should be equal due to an exact match on both. assert.equal(result[0].score === result[1].score, true) delete result[0].score delete result[1].score const expectedResult = [ { label: "index.ts", labelHighlights: [0, 1, 2, 3, 4, 5, 6, 7], detail: "browser/src", detailHighlights: [] as number[], }, { label: "index.ts", labelHighlights: [0, 1, 2, 3, 4, 5, 6, 7], detail: "browser/test", detailHighlights: [] as number[], }, ] assert.deepEqual(result, expectedResult) }) it("Correctly splits and matches string.", async () => { const testString = "index src" const testList = [ { label: "index.ts", detail: "browser/src" }, { label: "index.ts", detail: "browser/test" }, ] const result = filter(testList, testString) // Remove the score since it can change if we updated the // module. As long as its not 0 that is enough here. assert.equal(result[0].score > 0, true) delete result[0].score const expectedResult = [ { label: "index.ts", labelHighlights: [0, 1, 2, 3, 4], detail: "browser/src", detailHighlights: [8, 9, 10], }, ] assert.deepEqual(result, expectedResult) }) it("Correctly matches long split string.", async () => { const testString = "index src service quickopen" const testList = [ { label: "index.ts", detail: "browser/src/services/menu" }, { label: "index.ts", detail: "browser/src/services/quickopen" }, ] const result = filter(testList, testString) // Remove the score since it can change if we updated the // module. As long as its not 0 that is enough here. // Similarly, the highlights has been tested elsewhere, // and its long here, so just check lengths. assert.equal(result[0].score > 0, true) assert.equal(result[0].labelHighlights.length === 5, true) assert.equal(result[0].detailHighlights.length === 19, true) delete result[0].score delete result[0].labelHighlights delete result[0].detailHighlights const expectedResult = [{ label: "index.ts", detail: "browser/src/services/quickopen" }] assert.deepEqual(result, expectedResult) }) it("Correctly doesn't match.", async () => { const testString = "zzz" const testList = [ { label: "index.ts", detail: "browser/src/services/menu" }, { label: "index.ts", detail: "browser/src/services/quickopen" }, ] const result = filter(testList, testString) assert.deepEqual(result, []) }) it("Correctly matches split string in turn.", async () => { const testString = "index main" const testList = [ { label: "index.ts", detail: "browser/src/services/config" }, { label: "index.ts", detail: "browser/src/services/quickopen" }, { label: "main.ts", detail: "browser/src/services/menu" }, ] // Should return no results, since the first term should restrict the second // search to return no results. const result = filter(testList, testString) assert.deepEqual(result, []) }) it("Correctly sorts results for fuzzy match.", async () => { const testString = "aBE" const testList = [ { label: "BufferEditor.ts", detail: "packages/demo/src" }, { label: "BufferEditorContainer.ts", detail: "packages/demo/src" }, { label: "astBackedEditing.ts", detail: "packages/core/src" }, ] // All results match, but only the last has an exact match on aBE inside the file name. const result = filter(testList, testString) const be = result.find(r => r.label === "BufferEditor.ts") const bec = result.find(r => r.label === "BufferEditorContainer.ts") const abe = result.find(r => r.label === "astBackedEditing.ts") // Therefore it should score the highest. assert.equal(abe.score > be.score, true) assert.equal(abe.score > bec.score, true) // It should also be the first in the list assert.deepEqual(result[0], abe) }) it("Correctly sorts results for filtered search.", async () => { const testString = "buffer test oni" const testList = [ { label: "BufferEditor.ts", detail: "packages/demo/src" }, { label: "BufferEditorContainer.ts", detail: "packages/demo/src" }, { label: "BufferEditor.ts", detail: "packages/core/src" }, { label: "BufferEditor.ts", detail: "packages/core/test" }, { label: "BufferEditor.ts", detail: "packages/core/test/oni" }, ] const result = filter(testList, testString) // Should only match the last term const best = result.find(r => r.detail === "packages/core/test/oni") assert.deepEqual(result[0], best) assert.equal(result.length, 1) }) it("Correctly sorts results for shortest result on file name.", async () => { const testString = "main" const testList = [ { label: "main.tex", detail: "packages/core/src" }, { label: "main.tex", detail: "packages/core/test" }, { label: "main.tex", detail: "packages/core/test/oni" }, ] const result = filter(testList, testString) // Should prefer the short path const best = result.find(r => r.detail === "packages/core/src") const second = result.find(r => r.detail === "packages/core/test") const third = result.find(r => r.detail === "packages/core/test/oni") // Order should be as follows assert.deepEqual(result[0], best) assert.deepEqual(result[1], second) assert.deepEqual(result[2], third) }) it("Correctly sorts results for shortest result on path.", async () => { const testString = "somepath" const testList = [ { label: "fileA.ts", detail: "/some/path" }, { label: "fileB.ts", detail: "/some/path/longer" }, { label: "fileC.ts", detail: "packages/core/oni" }, ] const result = filter(testList, testString) // Should prefer the short path const best = result.find(r => r.label === "fileA.ts") const second = result.find(r => r.label === "fileB.ts") // Order should be as follows assert.deepEqual(result[0], best) assert.deepEqual(result[1], second) }) })
the_stack
import { expect } from 'chai'; import { inspect } from 'util'; import { JsonPointer, PathSegment } from '..'; const rand = (min: number, max: number): number => Math.random() * (max - min) + min; describe('JsonPointer', () => { const data0 = { has: 'data', arr: ['data', { nested: 'object with data' }, null], nested: { even: { further: 'hello' } }, }; type TestArr0 = [string, unknown]; // list paths in order so the .set method can work in reverse order const tests0: TestArr0[] = [ ['', data0], ['/has', data0.has], ['/arr', data0.arr], ['/arr/0', data0.arr[0]], ['/arr/1', data0.arr[1]], ['/arr/1/nested', (data0.arr[1] as Record<string, unknown>).nested], ['/arr/2', data0.arr[2]], ['/nested', data0.nested], ['/nested/even', data0.nested.even], ['/nested/even/further', data0.nested.even.further], ['/hasnot', undefined], ]; const data1 = { foo: 'bar', baz: [ 'qux', 'quux', { garply: { waldo: ['fred', 'plugh'] }, }, ], }; const tests1: TestArr0[] = [ ['', data1], ['/foo', data1.foo], ['/baz', data1.baz], ['/baz/0', data1.baz[0]], ['/baz/1', data1.baz[1]], ['/baz/2', data1.baz[2]], ['/baz/2/garply', (data1.baz[2] as { garply: unknown }).garply], [ '/baz/2/garply/waldo', ((data1.baz[2] as { garply: unknown }).garply as { waldo: string[] }) .waldo, ], [ '/baz/2/garply/waldo/0', ((data1.baz[2] as { garply: unknown }).garply as { waldo: string[] }) .waldo[0], ], [ '/baz/2/garply/waldo/1', ((data1.baz[2] as { garply: unknown }).garply as { waldo: string[] }) .waldo[1], ], ]; const tests1f: TestArr0[] = [ ['#', data1], ['#/foo', data1.foo], ['#/baz', data1.baz], ['#/baz/0', data1.baz[0]], ['#/baz/1', data1.baz[1]], ['#/baz/2', data1.baz[2]], ['#/baz/2/garply', (data1.baz[2] as { garply: unknown }).garply], [ '#/baz/2/garply/waldo', ((data1.baz[2] as { garply: unknown }).garply as { waldo: string[] }) .waldo, ], [ '#/baz/2/garply/waldo/0', ((data1.baz[2] as { garply: unknown }).garply as { waldo: string[] }) .waldo[0], ], [ '#/baz/2/garply/waldo/1', ((data1.baz[2] as { garply: unknown }).garply as { waldo: string[] }) .waldo[1], ], ]; describe('static .create()', () => { it('throws on undefined', () => { expect(() => JsonPointer.create(undefined as unknown as string)).to.throw( 'Invalid type: JSON Pointers are represented as strings.', ); }); it('succeeds when pointer is string', () => { expect(JsonPointer.create('')).to.be.a('object'); }); it('succeeds when pointer is PathSegment', () => { expect(JsonPointer.create([])).to.be.a('object'); }); }); describe('.ctor()', () => { it('throws on undefined', () => { expect(() => new JsonPointer(undefined as unknown as string)).to.throw( 'Invalid type: JSON Pointers are represented as strings.', ); }); it('succeeds when pointer is string', () => { expect(new JsonPointer('')).to.be.a('object'); }); it('succeeds when pointer is PathSegment', () => { expect(new JsonPointer([])).to.be.a('object'); }); }); describe('static .has()', () => { for (const [p, expected] of tests0) { it(`static .has(data, '${p}') = ${expected !== undefined}`, () => { expect(JsonPointer.has(data0, p)).to.be.eql(expected !== undefined); }); it(`static .has(data, '${JSON.stringify(JsonPointer.decode(p))}') = ${ expected !== undefined }`, () => { expect(JsonPointer.has(data0, JsonPointer.decode(p))).to.be.eql( expected !== undefined, ); }); it(`static .has(data, p'${p}') = ${expected !== undefined}`, () => { expect(JsonPointer.has(data0, new JsonPointer(p))).to.be.eql( expected !== undefined, ); }); } }); describe('.has()', () => { for (const [p, expected] of tests0) { it(`.has('${p}') = ${expected !== undefined}`, () => { const ptr = new JsonPointer(p); expect(ptr.has(data0)).to.be.eql(expected !== undefined); }); } }); describe('static .get()', () => { for (const [p, expected] of tests0) { it(`static .get(data, '${p}') = ${JSON.stringify(expected)}`, () => { expect(JsonPointer.get(data0, p)).to.be.eql(expected); }); it(`static .get(data, '${JSON.stringify( JsonPointer.decode(p), )}') = ${JSON.stringify(expected)}`, () => { expect(JsonPointer.get(data0, JsonPointer.decode(p))).to.be.eql( expected, ); }); it(`static .get(data, p'${p}') = ${JSON.stringify(expected)}`, () => { expect(JsonPointer.get(data0, new JsonPointer(p))).to.be.eql(expected); }); } }); describe('static .set() unforced', () => { const dataCopy0 = JSON.parse(JSON.stringify(data0)); const dataCopy1 = JSON.parse(JSON.stringify(data0)); const dataCopy2 = JSON.parse(JSON.stringify(data0)); for (const [p, expected] of tests0.reverse()) { const r = rand(1, 99999); it(`static .set(data, '${p}', ${r})`, () => { if (p === '') { expect(() => JsonPointer.set(dataCopy0, p, r)).to.throw( 'Cannot set the root object; assign it directly.', ); return; } JsonPointer.set(dataCopy0, p, r); if (expected === undefined) { expect(JsonPointer.get(dataCopy0, p)).to.be.eql(expected); } else { expect(JsonPointer.get(dataCopy0, p)).to.be.eql(r); } }); it(`static .set(data, ${JSON.stringify( JsonPointer.decode(p), )}, ${r})`, () => { if (p.length === 0) { expect(() => JsonPointer.set(dataCopy1, JsonPointer.decode(p), r), ).to.throw('Cannot set the root object; assign it directly.'); return; } JsonPointer.set(dataCopy1, JsonPointer.decode(p), r); if (expected === undefined) { expect(JsonPointer.get(dataCopy1, JsonPointer.decode(p))).to.be.eql( expected, ); } else { expect(JsonPointer.get(dataCopy1, JsonPointer.decode(p))).to.be.eql( r, ); } }); it(`static .set(data, p'${p}', ${r})`, () => { if (p === '') { expect(() => JsonPointer.set(dataCopy2, new JsonPointer(p), r), ).to.throw('Cannot set the root object; assign it directly.'); return; } JsonPointer.set(dataCopy2, new JsonPointer(p), r); if (expected === undefined) { expect(JsonPointer.get(dataCopy2, p)).to.be.eql(expected); } else { expect(JsonPointer.get(dataCopy2, p)).to.be.eql(r); } }); } it('throws on attempted prototype pollution', () => { const subject = { my: 'subject' }; expect(() => JsonPointer.set( subject, new JsonPointer('/__proto__/polluted'), "Yes! It's polluted", ), ).to.throw('Attempted prototype pollution disallowed.'); }); }); describe('static .unset()', () => { const dataCopy0 = JSON.parse(JSON.stringify(data0)); const dataCopy1 = JSON.parse(JSON.stringify(data0)); const dataCopy2 = JSON.parse(JSON.stringify(data0)); for (const [p] of tests0.reverse()) { it(`static .unset(data, '${p}')`, () => { if (p === '') { expect(() => JsonPointer.unset(dataCopy0, p)).to.throw( 'Cannot unset the root object; assign it directly.', ); return; } // values are changing! get it so we know what to expect const updatedExpected = JsonPointer.get(dataCopy0, p); expect(JsonPointer.unset(dataCopy0, p)).to.be.eql(updatedExpected); expect(JsonPointer.get(dataCopy0, p)).to.be.undefined; }); it(`static .unset(data, ${JSON.stringify( JsonPointer.decode(p), )})`, () => { if (p.length === 0) { expect(() => JsonPointer.unset(dataCopy1, JsonPointer.decode(p)), ).to.throw('Cannot unset the root object; assign it directly.'); return; } // values are changing! get it so we know what to expect const updatedExpected = JsonPointer.get(dataCopy1, p); expect(JsonPointer.unset(dataCopy1, JsonPointer.decode(p))).to.be.eql( updatedExpected, ); expect(JsonPointer.get(dataCopy1, JsonPointer.decode(p))).to.be .undefined; }); it(`static .unset(data, p'${p}')`, () => { if (p === '') { expect(() => JsonPointer.unset(dataCopy2, new JsonPointer(p)), ).to.throw('Cannot unset the root object; assign it directly.'); return; } // values are changing! get it so we know what to expect const updatedExpected = JsonPointer.get(dataCopy2, p); expect(JsonPointer.unset(dataCopy2, new JsonPointer(p))).to.be.eql( updatedExpected, ); expect(JsonPointer.get(dataCopy2, p)).to.be.undefined; }); } }); describe('static .visit()', () => { it(`static .visit(data)`, () => { const sequence: PathSegment[] = []; JsonPointer.visit(data1, (p, v) => { const path = JsonPointer.decode(p); if (path.length) { sequence.push(path[path.length - 1]); if (typeof v === 'string') { sequence.push(v); } } }); expect(sequence).to.eql([ 'foo', 'bar', 'baz', '0', 'qux', '1', 'quux', '2', 'garply', 'waldo', '0', 'fred', '1', 'plugh', ]); }); it(`static .visit(data) fragments`, () => { const sequence: PathSegment[] = []; JsonPointer.visit( data1, (p, v) => { const path = JsonPointer.decode(p); if (path.length) { sequence.push(path[path.length - 1]); if (typeof v === 'string') { sequence.push(v); } } }, true, ); expect(sequence).to.eql([ 'foo', 'bar', 'baz', '0', 'qux', '1', 'quux', '2', 'garply', 'waldo', '0', 'fred', '1', 'plugh', ]); }); const obj = { my: { obj: 'with nested data' } }; const objWithReferences: Record<string, unknown> = { your: { obj: { refers_to: obj } }, my: obj, }; objWithReferences.self = { nested: [objWithReferences, obj], }; it('handles references', () => { const pointers: Record<string, unknown> = {}; JsonPointer.visit(objWithReferences, (p, v) => { pointers[p] = v; }); console.log(inspect(pointers, false, 9)); }); }); describe('static .flatten()', () => { const data = { foo: 'bar', baz: [ 'qux', 'quux', { garply: { waldo: ['fred', 'plugh'] }, }, ], }; const obj = JsonPointer.flatten(data); const objf = JsonPointer.flatten(data, true); it('obj to # of items', () => { expect(Object.keys(obj).length).to.eql(tests1.length); }); for (const [p, expected] of tests1) { it(`obj['${p}'] === ${JSON.stringify(expected)}`, () => { expect(obj[p]).to.eql(expected); }); } for (const [p, expected] of tests1f) { it(`obj['${p}'] === ${JSON.stringify(expected)}`, () => { expect(objf[p]).to.eql(expected); }); } }); describe('static .map()', () => { const data = { foo: 'bar', baz: [ 'qux', 'quux', { garply: { waldo: ['fred', 'plugh'] }, }, ], }; const map = JsonPointer.map(data); const mapf = JsonPointer.map(data, true); it('map to # of items', () => { expect(Array.from(map.keys()).length).to.eql(tests1.length); }); for (const [p, expected] of tests1) { it(`map.get('${p}') === ${JSON.stringify(expected)}`, () => { expect(map.get(p)).to.eql(expected); }); } for (const [p, expected] of tests1f) { it(`map.get('${p}') === ${JSON.stringify(expected)}`, () => { expect(mapf.get(p)).to.eql(expected); }); } }); describe('static .decode()', () => { type Test = [string, string[]]; const tests: Test[] = [ ['', []], ['/foo', ['foo']], ['/foo/0', ['foo', '0']], ['/', ['']], ['/a~1b', ['a/b']], ['/c%d', ['c%d']], ['/e^f', ['e^f']], ['/g|h', ['g|h']], ['/i\\j', ['i\\j']], ['/k"l', ['k"l']], ['/ ', [' ']], ['/m~0n', ['m~n']], ['/foo/bar/baz', ['foo', 'bar', 'baz']], ['#/foo/bar/baz', ['foo', 'bar', 'baz']], ]; for (const [p, expected] of tests) { it(`.decode('${p}') = ${JSON.stringify(expected)}`, () => { expect(JsonPointer.decode(p)).to.be.eql(expected); }); } }); describe('.pointer property', () => { it('encodes pointer', () => { const p = new JsonPointer('/foo'); expect(p.pointer).to.eql('/foo'); expect(p.pointer).to.eql(p.pointer); }); it('encodes fragment', () => { const p = new JsonPointer('#/foo'); expect(p.pointer).to.eql('/foo'); expect(p.pointer).to.eql(p.pointer); expect(p.uriFragmentIdentifier).to.eql('#/foo'); }); }); describe('.relative method', () => { const doc = { foo: ['bar', 'baz'], highly: { nested: { objects: true, }, }, }; it('throws when relative pointer unspecified', () => { const p = new JsonPointer('/highly/nested/objects'); expect(() => p.rel(doc, undefined as unknown as string)).to.throw( 'Invalid type: Relative JSON Pointers are represented as strings.', ); }); it('throws when relative pointer empty', () => { const p = new JsonPointer('/highly/nested/objects'); expect(() => p.rel(doc, '')).to.throw( 'Invalid Relative JSON Pointer syntax. Relative pointer must begin with a non-negative integer, followed by either the number sign (#), or a JSON Pointer.', ); }); it('throws when relative pointer invalid [0](NaN)', () => { const p = new JsonPointer('/highly/nested/objects'); expect(() => p.rel(doc, 'b/z')).to.throw( 'Invalid Relative JSON Pointer syntax. Relative pointer must begin with a non-negative integer, followed by either the number sign (#), or a JSON Pointer.', ); }); it('throws when relative pointer invalid 1#/z', () => { const p = new JsonPointer('/highly/nested/objects'); expect(() => p.rel(doc, '1#/z')).to.throw( 'Invalid Relative JSON Pointer syntax. Relative pointer must begin with a non-negative integer, followed by either the number sign (#), or a JSON Pointer.', ); }); it('Spec examples 1', () => { const p = new JsonPointer('/foo/1'); expect(p.rel(doc, '0')).to.eql('baz'); expect(p.rel(doc, '1/0')).to.eql('bar'); expect(p.rel(doc, '2/highly/nested/objects')).to.eql(true); expect(p.rel(doc, '0#')).to.eql(1); expect(p.rel(doc, '1#')).to.eql('foo'); }); it('Spec examples 2', () => { const p = new JsonPointer('/highly/nested'); expect(p.rel(doc, '0/objects')).to.eql(true); expect(p.rel(doc, '1/nested/objects')).to.eql(true); expect(p.rel(doc, '2/foo/0')).to.eql('bar'); expect(p.rel(doc, '0#')).to.eql('nested'); expect(p.rel(doc, '1#')).to.eql('highly'); }); it('returns undefined when relative location cannot exist', () => { const p = new JsonPointer('/highly/nested/objects'); expect(p.rel(doc, '5/not-here')).to.be.undefined; }); }); describe('.rel method', () => { const doc = { foo: ['bar', 'baz'], highly: { nested: { objects: true, }, }, }; it('throws when relative pointer unspecified', () => { const p = new JsonPointer('/highly/nested/objects'); expect(() => p.relative(undefined as unknown as string)).to.throw( 'Invalid type: Relative JSON Pointers are represented as strings.', ); }); it('throws when relative pointer empty', () => { const p = new JsonPointer('/highly/nested/objects'); expect(() => p.relative('')).to.throw( 'Invalid Relative JSON Pointer syntax. Relative pointer must begin with a non-negative integer, followed by either the number sign (#), or a JSON Pointer.', ); }); it('throws when relative pointer invalid [0](NaN)', () => { const p = new JsonPointer('/highly/nested/objects'); expect(() => p.relative('b/z')).to.throw( 'Invalid Relative JSON Pointer syntax. Relative pointer must begin with a non-negative integer, followed by either the number sign (#), or a JSON Pointer.', ); }); it('throws when relative pointer invalid 1#/z', () => { const p = new JsonPointer('/highly/nested/objects'); expect(() => p.relative('1#/z')).to.throw( 'Invalid Relative JSON Pointer syntax. Relative pointer must begin with a non-negative integer, followed by either the number sign (#), or a JSON Pointer.', ); }); it('throws when relative pointer to name (#)', () => { const p = new JsonPointer('/highly/nested/objects'); expect(() => p.relative('1#')).to.throw( "We won't compile a pointer that will always return 'nested'. Use JsonPointer.rel(target, ptr) instead.", ); }); it('throws when relative location cannot exist', () => { const p = new JsonPointer('/highly/nested/objects'); expect(() => p.relative('5/not-here')).to.throw( 'Relative location does not exist.', ); }); it('Spec example from 1', () => { const p = new JsonPointer('/foo/1'); const q = p.relative('2/highly/nested/objects'); expect(q.get(doc)).to.eql(true); }); it('Spec example from 2', () => { const p = new JsonPointer('/highly/nested'); const q = p.relative('2/foo/0'); expect(q.get(doc)).to.eql('bar'); }); }); });
the_stack
declare module com { export module google { export module android { export module gms { export module dynamite { export module descriptors { export module com { export module google { export module firebase { export module perf { export class ModuleDescriptor { public static class: java.lang.Class<com.google.android.gms.dynamite.descriptors.com.google.firebase.perf.ModuleDescriptor>; public static MODULE_ID: string; public static MODULE_VERSION: number; public constructor(); } } } } } } } } } } } declare module com { export module google { export module firebase { export module perf { export class FirebasePerfRegistrar { public static class: java.lang.Class<com.google.firebase.perf.FirebasePerfRegistrar>; public constructor(); public getComponents(): java.util.List<com.google.firebase.components.Component<any>>; } } } } } declare module com { export module google { export module firebase { export module perf { export class FirebasePerformance { public static class: java.lang.Class<com.google.firebase.perf.FirebasePerformance>; public static MAX_TRACE_NAME_LENGTH: number; public setPerformanceCollectionEnabled(param0: boolean): void; public newHttpMetric(param0: string, param1: string): com.google.firebase.perf.metrics.HttpMetric; public newHttpMetric(param0: java.net.URL, param1: string): com.google.firebase.perf.metrics.HttpMetric; public static getInstance(): com.google.firebase.perf.FirebasePerformance; public isPerformanceCollectionEnabled(): boolean; public getAttributes(): java.util.Map<string,string>; public newTrace(param0: string): com.google.firebase.perf.metrics.Trace; public static startTrace(param0: string): com.google.firebase.perf.metrics.Trace; } export module FirebasePerformance { export class HttpMethod { public static class: java.lang.Class<com.google.firebase.perf.FirebasePerformance.HttpMethod>; /** * Constructs a new instance of the com.google.firebase.perf.FirebasePerformance$HttpMethod interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); public static HEAD: string; public static TRACE: string; public static DELETE: string; public static POST: string; public static GET: string; public static CONNECT: string; public static OPTIONS: string; public static PUT: string; public static PATCH: string; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class FeatureControl { public static class: java.lang.Class<com.google.firebase.perf.internal.FeatureControl>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class GaugeManager { public static class: java.lang.Class<com.google.firebase.perf.internal.GaugeManager>; } export module GaugeManager { export class zza { public static class: java.lang.Class<com.google.firebase.perf.internal.GaugeManager.zza>; } } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class RemoteConfigManager { public static class: java.lang.Class<com.google.firebase.perf.internal.RemoteConfigManager>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class SessionManager extends com.google.firebase.perf.internal.zzb { public static class: java.lang.Class<com.google.firebase.perf.internal.SessionManager>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zza { public static class: java.lang.Class<com.google.firebase.perf.internal.zza>; public onActivityDestroyed(param0: globalAndroid.app.Activity): void; public onActivitySaveInstanceState(param0: globalAndroid.app.Activity, param1: globalAndroid.os.Bundle): void; public onActivityPaused(param0: globalAndroid.app.Activity): void; public onActivityStarted(param0: globalAndroid.app.Activity): void; public onActivityResumed(param0: globalAndroid.app.Activity): void; public onActivityCreated(param0: globalAndroid.app.Activity, param1: globalAndroid.os.Bundle): void; public onActivityStopped(param0: globalAndroid.app.Activity): void; } export module zza { export class zza { public static class: java.lang.Class<com.google.firebase.perf.internal.zza.zza>; /** * Constructs a new instance of the com.google.firebase.perf.internal.zza$zza interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zza(param0: any /* com.google.android.gms.internal.firebase-perf.zzbt*/): void; }); public constructor(); } } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzb extends com.google.firebase.perf.internal.zza.zza { public static class: java.lang.Class<com.google.firebase.perf.internal.zzb>; public constructor(); public constructor(param0: any /* com.google.firebase.perf.internal.zza*/); } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzc { public static class: java.lang.Class<com.google.firebase.perf.internal.zzc>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzd extends com.google.firebase.perf.internal.zzr { public static class: java.lang.Class<com.google.firebase.perf.internal.zzd>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zze { public static class: java.lang.Class<com.google.firebase.perf.internal.zze>; public run(): void; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzf { public static class: java.lang.Class<com.google.firebase.perf.internal.zzf>; public run(): void; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzg { public static class: java.lang.Class<com.google.firebase.perf.internal.zzg>; public run(): void; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzh { public static class: java.lang.Class<com.google.firebase.perf.internal.zzh>; public run(): void; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzi extends com.google.firebase.perf.internal.zzr { public static class: java.lang.Class<com.google.firebase.perf.internal.zzi>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzj { public static class: java.lang.Class<com.google.firebase.perf.internal.zzj>; public run(): void; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzk extends com.google.firebase.perf.internal.zzr { public static class: java.lang.Class<com.google.firebase.perf.internal.zzk>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzl extends com.google.firebase.perf.internal.zzr { public static class: java.lang.Class<com.google.firebase.perf.internal.zzl>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzm { public static class: java.lang.Class<com.google.firebase.perf.internal.zzm>; public run(): void; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzn { public static class: java.lang.Class<com.google.firebase.perf.internal.zzn>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzo { public static class: java.lang.Class<com.google.firebase.perf.internal.zzo>; public run(): void; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzp { public static class: java.lang.Class<com.google.firebase.perf.internal.zzp>; public getProcessName(): string; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzq { public static class: java.lang.Class<com.google.firebase.perf.internal.zzq>; public static CREATOR: any /* globalAndroid.os.Parcelable.Creator<com.google.firebase.perf.internal.zzq>*/; public isExpired(): boolean; public describeContents(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export abstract class zzr { public static class: java.lang.Class<com.google.firebase.perf.internal.zzr>; public constructor(); } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzs { public static class: java.lang.Class<com.google.firebase.perf.internal.zzs>; public constructor(param0: globalAndroid.content.Context, param1: number, param2: number); } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzt extends java.lang.Object /* globalAndroid.os.Parcelable.Creator<com.google.firebase.perf.internal.zzq>*/ { public static class: java.lang.Class<com.google.firebase.perf.internal.zzt>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzu { public static class: java.lang.Class<com.google.firebase.perf.internal.zzu>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzv { public static class: java.lang.Class<com.google.firebase.perf.internal.zzv>; public static values(): any /* native.Array<com.google.firebase.perf.internal.zzv>*/; public toString(): string; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzx { public static class: java.lang.Class<com.google.firebase.perf.internal.zzx>; public onFailure(param0: java.lang.Exception): void; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzy { public static class: java.lang.Class<com.google.firebase.perf.internal.zzy>; public run(): void; } } } } } } declare module com { export module google { export module firebase { export module perf { export module internal { export class zzz { public static class: java.lang.Class<com.google.firebase.perf.internal.zzz>; /** * Constructs a new instance of the com.google.firebase.perf.internal.zzz interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zza(param0: any /* com.google.firebase.perf.internal.zzq*/): void; }); public constructor(); } } } } } } declare module com { export module google { export module firebase { export module perf { export module metrics { export class AddTrace { public static class: java.lang.Class<com.google.firebase.perf.metrics.AddTrace>; /** * Constructs a new instance of the com.google.firebase.perf.metrics.AddTrace interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { name(): string; enabled(): boolean; }); public constructor(); public name(): string; public enabled(): boolean; } } } } } } declare module com { export module google { export module firebase { export module perf { export module metrics { export class AppStartTrace { public static class: java.lang.Class<com.google.firebase.perf.metrics.AppStartTrace>; public onActivityPaused(param0: globalAndroid.app.Activity): void; public onActivityDestroyed(param0: globalAndroid.app.Activity): void; public onActivitySaveInstanceState(param0: globalAndroid.app.Activity, param1: globalAndroid.os.Bundle): void; public static setLauncherActivityOnCreateTime(param0: string): void; public onActivityStarted(param0: globalAndroid.app.Activity): void; public onActivityResumed(param0: globalAndroid.app.Activity): void; public static setLauncherActivityOnResumeTime(param0: string): void; public onActivityCreated(param0: globalAndroid.app.Activity, param1: globalAndroid.os.Bundle): void; public static setLauncherActivityOnStartTime(param0: string): void; public onActivityStopped(param0: globalAndroid.app.Activity): void; } export module AppStartTrace { export class zza { public static class: java.lang.Class<com.google.firebase.perf.metrics.AppStartTrace.zza>; public constructor(param0: com.google.firebase.perf.metrics.AppStartTrace); public run(): void; } } } } } } } declare module com { export module google { export module firebase { export module perf { export module metrics { export class HttpMetric { public static class: java.lang.Class<com.google.firebase.perf.metrics.HttpMetric>; public setResponseContentType(param0: string): void; public start(): void; public getAttributes(): java.util.Map<string,string>; public putAttribute(param0: string, param1: string): void; public removeAttribute(param0: string): void; public constructor(param0: java.net.URL, param1: string, param2: any /* com.google.firebase.perf.internal.zzc*/, param3: any /* com.google.android.gms.internal.firebase-perf.zzbg*/); public setRequestPayloadSize(param0: number): void; public setHttpResponseCode(param0: number): void; public stop(): void; public constructor(param0: string, param1: string, param2: any /* com.google.firebase.perf.internal.zzc*/, param3: any /* com.google.android.gms.internal.firebase-perf.zzbg*/); public getAttribute(param0: string): string; public setResponsePayloadSize(param0: number): void; } } } } } } declare module com { export module google { export module firebase { export module perf { export module metrics { export class Trace extends com.google.firebase.perf.internal.zzb implements com.google.firebase.perf.internal.zzz { public static class: java.lang.Class<com.google.firebase.perf.metrics.Trace>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.firebase.perf.metrics.Trace>; public constructor(); public incrementMetric(param0: string, param1: number): void; public describeContents(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public removeAttribute(param0: string): void; public constructor(param0: string, param1: any /* com.google.firebase.perf.internal.zzc*/, param2: any /* com.google.android.gms.internal.firebase-perf.zzax*/, param3: any /* com.google.firebase.perf.internal.zza*/); public stop(): void; public finalize(): void; public constructor(param0: any /* com.google.firebase.perf.internal.zza*/); public start(): void; public getAttributes(): java.util.Map<string,string>; public putAttribute(param0: string, param1: string): void; public getLongMetric(param0: string): number; public putMetric(param0: string, param1: number): void; public getAttribute(param0: string): string; } } } } } } declare module com { export module google { export module firebase { export module perf { export module metrics { export class zza { public static class: java.lang.Class<com.google.firebase.perf.metrics.zza>; public static CREATOR: any /* globalAndroid.os.Parcelable.Creator<com.google.firebase.perf.metrics.zza>*/; public describeContents(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: string); } } } } } } declare module com { export module google { export module firebase { export module perf { export module metrics { export class zzb extends java.lang.Object /* globalAndroid.os.Parcelable.Creator<com.google.firebase.perf.metrics.zza>*/ { public static class: java.lang.Class<com.google.firebase.perf.metrics.zzb>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module metrics { export class zzc extends globalAndroid.os.Parcelable.Creator<com.google.firebase.perf.metrics.Trace> { public static class: java.lang.Class<com.google.firebase.perf.metrics.zzc>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module metrics { export class zzd { public static class: java.lang.Class<com.google.firebase.perf.metrics.zzd>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module metrics { export class zze extends globalAndroid.os.Parcelable.Creator<com.google.firebase.perf.metrics.Trace> { public static class: java.lang.Class<com.google.firebase.perf.metrics.zze>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module network { export class FirebasePerfHttpClient { public static class: java.lang.Class<com.google.firebase.perf.network.FirebasePerfHttpClient>; public static execute(param0: org.apache.http.client.HttpClient, param1: org.apache.http.client.methods.HttpUriRequest, param2: org.apache.http.protocol.HttpContext): org.apache.http.HttpResponse; public static execute(param0: org.apache.http.client.HttpClient, param1: org.apache.http.client.methods.HttpUriRequest, param2: org.apache.http.client.ResponseHandler): any; public static execute(param0: org.apache.http.client.HttpClient, param1: org.apache.http.HttpHost, param2: org.apache.http.HttpRequest, param3: org.apache.http.client.ResponseHandler, param4: org.apache.http.protocol.HttpContext): any; public static execute(param0: org.apache.http.client.HttpClient, param1: org.apache.http.HttpHost, param2: org.apache.http.HttpRequest): org.apache.http.HttpResponse; public static execute(param0: org.apache.http.client.HttpClient, param1: org.apache.http.HttpHost, param2: org.apache.http.HttpRequest, param3: org.apache.http.protocol.HttpContext): org.apache.http.HttpResponse; public static execute(param0: org.apache.http.client.HttpClient, param1: org.apache.http.HttpHost, param2: org.apache.http.HttpRequest, param3: org.apache.http.client.ResponseHandler): any; public static execute(param0: org.apache.http.client.HttpClient, param1: org.apache.http.client.methods.HttpUriRequest): org.apache.http.HttpResponse; public static execute(param0: org.apache.http.client.HttpClient, param1: org.apache.http.client.methods.HttpUriRequest, param2: org.apache.http.client.ResponseHandler, param3: org.apache.http.protocol.HttpContext): any; } } } } } } declare module com { export module google { export module firebase { export module perf { export module network { export class FirebasePerfOkHttpClient { public static class: java.lang.Class<com.google.firebase.perf.network.FirebasePerfOkHttpClient>; public static execute(param0: okhttp3.Call): okhttp3.Response; public static enqueue(param0: okhttp3.Call, param1: okhttp3.Callback): void; } } } } } } declare module com { export module google { export module firebase { export module perf { export module network { export class FirebasePerfUrlConnection { public static class: java.lang.Class<com.google.firebase.perf.network.FirebasePerfUrlConnection>; public static getContent(param0: java.net.URL): any; public static instrument(param0: any): any; public static getContent(param0: java.net.URL, param1: native.Array<java.lang.Class>): any; public static openStream(param0: java.net.URL): java.io.InputStream; } } } } } } declare module com { export module google { export module firebase { export module perf { export module network { export class zza { public static class: java.lang.Class<com.google.firebase.perf.network.zza>; public constructor(param0: java.io.InputStream, param1: any /* com.google.android.gms.internal.firebase-perf.zzau*/, param2: any /* com.google.android.gms.internal.firebase-perf.zzbg*/); public read(): number; public skip(param0: number): number; public read(param0: native.Array<number>): number; public close(): void; public markSupported(): boolean; public mark(param0: number): void; public read(param0: native.Array<number>, param1: number, param2: number): number; public reset(): void; public available(): number; } } } } } } declare module com { export module google { export module firebase { export module perf { export module network { export class zzb { public static class: java.lang.Class<com.google.firebase.perf.network.zzb>; public getContentLength(): number; public equals(param0: any): boolean; public setRequestMethod(param0: string): void; public getContent(): any; public getRequestMethod(): string; public getContentEncoding(): string; public setDefaultUseCaches(param0: boolean): void; public usingProxy(): boolean; public disconnect(): void; public getOutputStream(): java.io.OutputStream; public getHeaderFieldLong(param0: string, param1: number): number; public getHeaderFieldKey(param0: number): string; public getHeaderField(param0: number): string; public getContent(param0: native.Array<java.lang.Class>): any; public setConnectTimeout(param0: number): void; public getDate(): number; public setInstanceFollowRedirects(param0: boolean): void; public setChunkedStreamingMode(param0: number): void; public getResponseMessage(): string; public addRequestProperty(param0: string, param1: string): void; public getHeaderField(param0: string): string; public connect(): void; public getConnectTimeout(): number; public getRequestProperty(param0: string): string; public toString(): string; public getPermission(): java.security.Permission; public getIfModifiedSince(): number; public setUseCaches(param0: boolean): void; public getDefaultUseCaches(): boolean; public getDoOutput(): boolean; public setAllowUserInteraction(param0: boolean): void; public setReadTimeout(param0: number): void; public getInstanceFollowRedirects(): boolean; public getHeaderFieldInt(param0: string, param1: number): number; public getResponseCode(): number; public hashCode(): number; public getUseCaches(): boolean; public getLastModified(): number; public getHeaderFieldDate(param0: string, param1: number): number; public getContentLengthLong(): number; public setFixedLengthStreamingMode(param0: number): void; public setDoOutput(param0: boolean): void; public getErrorStream(): java.io.InputStream; public getURL(): java.net.URL; public setDoInput(param0: boolean): void; public setIfModifiedSince(param0: number): void; public setRequestProperty(param0: string, param1: string): void; public getExpiration(): number; public getDoInput(): boolean; public getInputStream(): java.io.InputStream; public getHeaderFields(): java.util.Map<string,java.util.List<string>>; public getContentType(): string; public getAllowUserInteraction(): boolean; public getReadTimeout(): number; public getRequestProperties(): java.util.Map<string,java.util.List<string>>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module network { export class zzc { public static class: java.lang.Class<com.google.firebase.perf.network.zzc>; public constructor(param0: java.io.OutputStream, param1: any /* com.google.android.gms.internal.firebase-perf.zzau*/, param2: any /* com.google.android.gms.internal.firebase-perf.zzbg*/); public close(): void; public write(param0: number): void; public write(param0: native.Array<number>, param1: number, param2: number): void; public flush(): void; public write(param0: native.Array<number>): void; } } } } } } declare module com { export module google { export module firebase { export module perf { export module network { export class zzd { public static class: java.lang.Class<com.google.firebase.perf.network.zzd>; public getContentLength(): number; public equals(param0: any): boolean; public setRequestMethod(param0: string): void; public getContent(): any; public getRequestMethod(): string; public getContentEncoding(): string; public setDefaultUseCaches(param0: boolean): void; public usingProxy(): boolean; public disconnect(): void; public getOutputStream(): java.io.OutputStream; public getHeaderFieldLong(param0: string, param1: number): number; public getHeaderFieldKey(param0: number): string; public getHeaderField(param0: number): string; public getContent(param0: native.Array<java.lang.Class>): any; public setConnectTimeout(param0: number): void; public getDate(): number; public setInstanceFollowRedirects(param0: boolean): void; public setChunkedStreamingMode(param0: number): void; public getResponseMessage(): string; public addRequestProperty(param0: string, param1: string): void; public getHeaderField(param0: string): string; public connect(): void; public getConnectTimeout(): number; public getRequestProperty(param0: string): string; public toString(): string; public getPermission(): java.security.Permission; public getIfModifiedSince(): number; public setUseCaches(param0: boolean): void; public getDefaultUseCaches(): boolean; public getDoOutput(): boolean; public setAllowUserInteraction(param0: boolean): void; public setReadTimeout(param0: number): void; public getInstanceFollowRedirects(): boolean; public getHeaderFieldInt(param0: string, param1: number): number; public getResponseCode(): number; public hashCode(): number; public getUseCaches(): boolean; public getLastModified(): number; public getHeaderFieldDate(param0: string, param1: number): number; public getContentLengthLong(): number; public setFixedLengthStreamingMode(param0: number): void; public setDoOutput(param0: boolean): void; public constructor(param0: java.net.HttpURLConnection, param1: any /* com.google.android.gms.internal.firebase-perf.zzbg*/, param2: any /* com.google.android.gms.internal.firebase-perf.zzau*/); public getErrorStream(): java.io.InputStream; public getURL(): java.net.URL; public setDoInput(param0: boolean): void; public setIfModifiedSince(param0: number): void; public setRequestProperty(param0: string, param1: string): void; public getExpiration(): number; public getDoInput(): boolean; public getInputStream(): java.io.InputStream; public getHeaderFields(): java.util.Map<string,java.util.List<string>>; public getContentType(): string; public getAllowUserInteraction(): boolean; public getReadTimeout(): number; public getRequestProperties(): java.util.Map<string,java.util.List<string>>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module network { export class zze { public static class: java.lang.Class<com.google.firebase.perf.network.zze>; public getContentLength(): number; public setHostnameVerifier(param0: javax.net.ssl.HostnameVerifier): void; public equals(param0: any): boolean; public setRequestMethod(param0: string): void; public getContent(): any; public getRequestMethod(): string; public getContentEncoding(): string; public setDefaultUseCaches(param0: boolean): void; public usingProxy(): boolean; public getLocalCertificates(): native.Array<java.security.cert.Certificate>; public disconnect(): void; public getOutputStream(): java.io.OutputStream; public getHeaderFieldLong(param0: string, param1: number): number; public setSSLSocketFactory(param0: javax.net.ssl.SSLSocketFactory): void; public getHeaderFieldKey(param0: number): string; public getHeaderField(param0: number): string; public getServerCertificates(): native.Array<java.security.cert.Certificate>; public getContent(param0: native.Array<java.lang.Class>): any; public setConnectTimeout(param0: number): void; public getDate(): number; public setInstanceFollowRedirects(param0: boolean): void; public setChunkedStreamingMode(param0: number): void; public getResponseMessage(): string; public addRequestProperty(param0: string, param1: string): void; public getHeaderField(param0: string): string; public connect(): void; public getConnectTimeout(): number; public getRequestProperty(param0: string): string; public toString(): string; public getPermission(): java.security.Permission; public getIfModifiedSince(): number; public setUseCaches(param0: boolean): void; public getDefaultUseCaches(): boolean; public getPeerPrincipal(): java.security.Principal; public getDoOutput(): boolean; public setAllowUserInteraction(param0: boolean): void; public setReadTimeout(param0: number): void; public getSSLSocketFactory(): javax.net.ssl.SSLSocketFactory; public getInstanceFollowRedirects(): boolean; public getHeaderFieldInt(param0: string, param1: number): number; public getResponseCode(): number; public hashCode(): number; public getCipherSuite(): string; public getUseCaches(): boolean; public getLastModified(): number; public getHeaderFieldDate(param0: string, param1: number): number; public getContentLengthLong(): number; public setFixedLengthStreamingMode(param0: number): void; public setDoOutput(param0: boolean): void; public getErrorStream(): java.io.InputStream; public getURL(): java.net.URL; public setDoInput(param0: boolean): void; public setIfModifiedSince(param0: number): void; public setRequestProperty(param0: string, param1: string): void; public getLocalPrincipal(): java.security.Principal; public getExpiration(): number; public getDoInput(): boolean; public getInputStream(): java.io.InputStream; public getHostnameVerifier(): javax.net.ssl.HostnameVerifier; public getHeaderFields(): java.util.Map<string,java.util.List<string>>; public getContentType(): string; public getAllowUserInteraction(): boolean; public getReadTimeout(): number; public getRequestProperties(): java.util.Map<string,java.util.List<string>>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module network { export class zzf { public static class: java.lang.Class<com.google.firebase.perf.network.zzf>; public onResponse(param0: okhttp3.Call, param1: okhttp3.Response): void; public constructor(param0: okhttp3.Callback, param1: any /* com.google.firebase.perf.internal.zzc*/, param2: any /* com.google.android.gms.internal.firebase-perf.zzbg*/, param3: number); public onFailure(param0: okhttp3.Call, param1: java.io.IOException): void; } } } } } } declare module com { export module google { export module firebase { export module perf { export module network { export class zzg<T> extends org.apache.http.client.ResponseHandler<any> { public static class: java.lang.Class<com.google.firebase.perf.network.zzg<any>>; public constructor(param0: org.apache.http.client.ResponseHandler<any>, param1: any /* com.google.android.gms.internal.firebase-perf.zzbg*/, param2: any /* com.google.android.gms.internal.firebase-perf.zzau*/); public handleResponse(param0: org.apache.http.HttpResponse): any; } } } } } } declare module com { export module google { export module firebase { export module perf { export module network { export class zzh { public static class: java.lang.Class<com.google.firebase.perf.network.zzh>; } } } } } } declare module com { export module google { export module firebase { export module perf { export module provider { export class FirebasePerfProvider { public static class: java.lang.Class<com.google.firebase.perf.provider.FirebasePerfProvider>; public constructor(); public delete(param0: globalAndroid.net.Uri, param1: string, param2: native.Array<string>): number; public attachInfo(param0: globalAndroid.content.Context, param1: globalAndroid.content.pm.ProviderInfo): void; public query(param0: globalAndroid.net.Uri, param1: native.Array<string>, param2: string, param3: native.Array<string>, param4: string): globalAndroid.database.Cursor; public onCreate(): boolean; public getType(param0: globalAndroid.net.Uri): string; public update(param0: globalAndroid.net.Uri, param1: globalAndroid.content.ContentValues, param2: string, param3: native.Array<string>): number; public insert(param0: globalAndroid.net.Uri, param1: globalAndroid.content.ContentValues): globalAndroid.net.Uri; } } } } } } declare module com { export module google { export module firebase { export module perf { export class zza { public static class: java.lang.Class<com.google.firebase.perf.zza>; public create(param0: com.google.firebase.components.ComponentContainer): any; } } } } } //Generics information: //com.google.android.gms.internal.firebase-perf.zzaa:1 //com.google.android.gms.internal.firebase-perf.zzac:2 //com.google.android.gms.internal.firebase-perf.zzae:1 //com.google.android.gms.internal.firebase-perf.zzaf:1 //com.google.android.gms.internal.firebase-perf.zzai:1 //com.google.android.gms.internal.firebase-perf.zzdg:2 //com.google.android.gms.internal.firebase-perf.zzdh:1 //com.google.android.gms.internal.firebase-perf.zzdi:2 //com.google.android.gms.internal.firebase-perf.zzdk:1 //com.google.android.gms.internal.firebase-perf.zzef:1 //com.google.android.gms.internal.firebase-perf.zzek:1 //com.google.android.gms.internal.firebase-perf.zzem:1 //com.google.android.gms.internal.firebase-perf.zzep:2 //com.google.android.gms.internal.firebase-perf.zzep.zza:1 //com.google.android.gms.internal.firebase-perf.zzep.zzb:2 //com.google.android.gms.internal.firebase-perf.zzep.zzd:2 //com.google.android.gms.internal.firebase-perf.zzet:1 //com.google.android.gms.internal.firebase-perf.zzex:1 //com.google.android.gms.internal.firebase-perf.zzey:2 //com.google.android.gms.internal.firebase-perf.zzfd:1 //com.google.android.gms.internal.firebase-perf.zzfg:1 //com.google.android.gms.internal.firebase-perf.zzfr:2 //com.google.android.gms.internal.firebase-perf.zzfs:2 //com.google.android.gms.internal.firebase-perf.zzfu:2 //com.google.android.gms.internal.firebase-perf.zzgd:1 //com.google.android.gms.internal.firebase-perf.zzge:1 //com.google.android.gms.internal.firebase-perf.zzgk:1 //com.google.android.gms.internal.firebase-perf.zzgl:1 //com.google.android.gms.internal.firebase-perf.zzgn:1 //com.google.android.gms.internal.firebase-perf.zzgs:2 //com.google.android.gms.internal.firebase-perf.zzh:1 //com.google.android.gms.internal.firebase-perf.zzhf:2 //com.google.android.gms.internal.firebase-perf.zzj:1 //com.google.android.gms.internal.firebase-perf.zzl:1 //com.google.android.gms.internal.firebase-perf.zzm:1 //com.google.android.gms.internal.firebase-perf.zzp:1 //com.google.android.gms.internal.firebase-perf.zzq:1 //com.google.android.gms.internal.firebase-perf.zzr:1 //com.google.android.gms.internal.firebase-perf.zzs:1 //com.google.android.gms.internal.firebase-perf.zzt:1 //com.google.android.gms.internal.firebase-perf.zzu:1 //com.google.android.gms.internal.firebase-perf.zzv:2 //com.google.android.gms.internal.firebase-perf.zzx:1 //com.google.android.gms.internal.firebase-perf.zzy:2 //com.google.android.gms.internal.firebase-perf.zzz:2 //com.google.firebase.perf.network.zzg:1
the_stack
import { VirtualRepeat } from '../src/virtual-repeat'; import { ITestAppInterface } from './interfaces'; export type AsyncQueue = (func: (...args: any[]) => any) => void; export function createAssertionQueue(): AsyncQueue { let queue: Array<() => any> = []; let next = () => { if (queue.length) { setTimeout(() => { if (queue.length > 0) { let func = queue.shift(); func(); next(); } }, 16); } }; return (func: () => any) => { if (queue.push(func) === 1) { next(); } }; } /** * * @param extraHeight height of static content that contributes to overall heigh. Happen in case of table */ export function validateState(virtualRepeat: VirtualRepeat, viewModel: ITestAppInterface<any>, itemHeight: number, extraHeight?: number) { let views = virtualRepeat.viewSlot.children; let expectedHeight = viewModel.items.length * itemHeight; let topBufferHeight = virtualRepeat.topBufferEl.getBoundingClientRect().height; let bottomBufferHeight = virtualRepeat.bottomBufferEl.getBoundingClientRect().height; let renderedItemsHeight = views.length * itemHeight; expect(topBufferHeight + renderedItemsHeight + bottomBufferHeight).toBe( expectedHeight, `Top buffer (${topBufferHeight}) + items height (${renderedItemsHeight}) + bottom buffer (${bottomBufferHeight}) should have been correct` ); if (viewModel.items.length > views.length) { expect(topBufferHeight + bottomBufferHeight).toBeGreaterThan(0); } // validate contextual data for (let i = 0; i < views.length; i++) { const view = views[i]; const itemIndex = viewModel.items.indexOf(view.bindingContext.item); expect(views[i].bindingContext.item).toBe(viewModel.items[i], `view[${i}].bindingContext.item === items[${i}]`); let overrideContext = views[i].overrideContext; expect(overrideContext.parentOverrideContext.bindingContext).toBe(viewModel); expect(overrideContext.bindingContext).toBe(views[i].bindingContext); let first = i === 0; let last = i === viewModel.items.length - 1; let even = i % 2 === 0; expect(overrideContext.$index).toBe(i, `[item:${itemIndex} -- view:${i}]overrideContext.$index`); expect(overrideContext.$first).toBe(first, `[item:${itemIndex} -- view:${i}]overrideContext.$first`); expect(overrideContext.$last).toBe(last, `[item:${itemIndex} -- view:${i}]overrideContext.$last`); expect(overrideContext.$middle).toBe(!first && !last, `[item:${itemIndex} -- view:${i}]overrideContext.$middle`); expect(overrideContext.$odd).toBe(!even, `[item:${itemIndex} -- view:${i}]overrideContext.$odd`); expect(overrideContext.$even).toBe(even, `[item:${itemIndex} -- view:${i}]overrideContext.$even`); } } /** * Validate states of views of a virtual repeat, based on viewModel and number of items of it, together with height of each item */ export function validateScrolledState(virtualRepeat: VirtualRepeat, viewModel: ITestAppInterface<any>, itemHeight: number, extraTitle?: string) { let views = virtualRepeat.viewSlot.children; let expectedHeight = viewModel.items.length * itemHeight; let topBufferHeight = virtualRepeat.topBufferEl.getBoundingClientRect().height; let bottomBufferHeight = virtualRepeat.bottomBufferEl.getBoundingClientRect().height; let renderedItemsHeight = views.length * itemHeight; expect(topBufferHeight + renderedItemsHeight + bottomBufferHeight).toBe( expectedHeight, `${extraTitle ? `${extraTitle} + ` : '' }Top buffer (${topBufferHeight}) + items height (${renderedItemsHeight}) + bottom buffer (${bottomBufferHeight}) should have been correct` ); if (viewModel.items.length > views.length) { expect(topBufferHeight + bottomBufferHeight).toBeGreaterThan(0); } if (!Array.isArray(viewModel.items) || viewModel.items.length < 0) { expect(virtualRepeat.$first).toBe(0, `${extraTitle}repeat._first === 0 <when 0 | null | undefined>`); expect(virtualRepeat.viewCount()).toBe(0, `${extraTitle}items.length === 0 | null | undefined`); return; } // validate contextual data let startingLoc = viewModel.items && viewModel.items.length > 0 ? viewModel.items.indexOf(views[0].bindingContext.item) : 0; // let i = 0; // let ii = Math.min(viewModel.items.length - startingLoc, views.length); for (let i = startingLoc; i < views.length; i++) { // thanks to @reinholdk for the following line // it correctly handles view index & itemIndex for assertion let itemIndex = startingLoc + i; expect(views[i].bindingContext.item).toBe(viewModel.items[itemIndex], `view[${i}].bindingContext.item === items[${itemIndex}]`); // expect(views[i].bindingContext.item).toBe(viewModel.items[i], `view(${i}).bindingContext.item`); let overrideContext = views[i].overrideContext; expect(overrideContext.parentOverrideContext.bindingContext).toBe(viewModel, 'parentOverrideContext.bindingContext === viewModel'); expect(overrideContext.bindingContext).toBe(views[i].bindingContext, `overrideContext sync`); // let first = i === 0; // let last = i === viewModel.items.length - 1; // let even = i % 2 === 0; // expect(overrideContext.$index).toBe(i); let first = itemIndex === 0; let last = itemIndex === viewModel.items.length - 1; let even = itemIndex % 2 === 0; expect(overrideContext.$index).toBe(itemIndex, `[item:${itemIndex} -- view:${i}]overrideContext.$index`); expect(overrideContext.$first).toBe(first, `[item:${itemIndex} -- view:${i}]overrideContext.$first`); expect(overrideContext.$last).toBe(last, `[item:${itemIndex} -- view:${i}]overrideContext.$last`); expect(overrideContext.$middle).toBe(!first && !last, `[item:${itemIndex} -- view:${i}]overrideContext.$middle`); expect(overrideContext.$odd).toBe(!even, `[item:${itemIndex} -- view:${i}]overrideContext.$odd`); expect(overrideContext.$even).toBe(even, `[item:${itemIndex} -- view:${i}]overrideContext.$even`); } } /** * Manually dispatch a scroll event and validate scrolled state of virtual repeat * * Programatically set `scrollTop` of element specified with `elementSelector` query string * (or `#scrollContainer` by default) to be equal with its `scrollHeight` */ export function validateScroll(virtualRepeat: VirtualRepeat, viewModel: any, itemHeight: number, element: Element, done: Function): void { let event = new Event('scroll'); element.scrollTop = element.scrollHeight; element.dispatchEvent(event); window.setTimeout(() => { window.requestAnimationFrame(() => { validateScrolledState(virtualRepeat, viewModel, itemHeight); done(); }); }); } export function scrollRepeat(virtualRepeat: VirtualRepeat, dest: 'start' | 'end' | number): void { const scroller = virtualRepeat.getScroller(); scroller.scrollTop = dest === 'start' ? 0 : dest === 'end' ? scroller.scrollHeight : dest; } /** * Scroll a virtual repeat scroller element to top */ export async function scrollToStart(virtualRepeat: VirtualRepeat, insuranceTime = 5): Promise<void> { virtualRepeat.getScroller().scrollTop = 0; await ensureScrolled(insuranceTime); } /** * Scroll a virtual repeat scroller element to bottom */ export async function scrollToEnd(virtualRepeat: VirtualRepeat, insuranceTime = 5): Promise<void> { let element = virtualRepeat.scrollerEl; element.scrollTop = element.scrollHeight; createScrollEvent(element); await ensureScrolled(insuranceTime); } export async function scrollToIndex(virtualRepeat: VirtualRepeat, itemIndex: number): Promise<void> { let element = virtualRepeat.scrollerEl; element.scrollTop = virtualRepeat.itemHeight * (itemIndex + 1); createScrollEvent(element); await ensureScrolled(); } /** * Wait for a small time for repeat to finish processing. * * Default to 10 */ export async function ensureScrolled(time: number = 10): Promise<void> { await waitForNextFrame(); await waitForTimeout(time); } export function waitForTimeout(time = 1): Promise<void> { return new Promise(r => setTimeout(r, time)); } export function waitForNextFrame(): Promise<void> { return new Promise(r => requestAnimationFrame(() => r())); } export async function waitForFrames(count = 1): Promise<void> { while (count --) { await waitForNextFrame(); } } export function createScrollEvent(target: EventTarget): void { target.dispatchEvent(new Event('scroll')); } const kebabCaseLookup: Record<string, string> = {}; const kebabCase = (input: string): string => { // benchmark: http://jsben.ch/v7K9T let value = kebabCaseLookup[input]; if (value !== undefined) { return value; } value = ''; let first = true; let char: string, lower: string; for (let i = 0, ii = input.length; i < ii; ++i) { char = input.charAt(i); lower = char.toLowerCase(); value = value + (first ? lower : (char !== lower ? `-${lower}` : lower)); first = false; } return kebabCaseLookup[input] = value; }; const eventCmds = { delegate: 1, capture: 1, call: 1 }; /** * jsx with aurelia binding command friendly version of h */ export const h = (name: string, attrs: Record<string, string> | null, ...children: (Node | string | (Node | string)[])[]) => { const el = name === 'shadow-root' ? document.createDocumentFragment() : document.createElement(name === 'let$' ? 'let' : name); if (attrs !== null) { let value: string | string[] | object; let len: number; for (const attr in attrs) { value = attrs[attr]; // if attr is class or its alias // split up by splace and add to element via classList API if (attr === 'class' || attr === 'className' || attr === 'cls') { value = value === undefined || value === null ? [] : Array.isArray(value) ? value : ('' + value).split(' '); (el as Element).classList.add(...value as string[]); } else if (attr === 'style') { if (typeof value === 'object') { Object.keys(value).forEach(styleKey => { const styleValue = value[styleKey]; (el as HTMLElement).style[styleKey] = typeof styleValue === 'number' ? styleValue + 'px' : styleValue; }); } else if (typeof value === 'string') { (el as HTMLElement).style.cssText = value; } else { throw new Error('Invalid style value. Expected string/object, received: ' + typeof value); } } // for attributes with matching properties, simply assign // other if special attribute like data, or ones start with _ // assign as well else if (attr in el || attr === 'data' || attr[0] === '_') { el[attr] = value; } // if it's an asElement attribute, camel case it else if (attr === 'asElement') { (el as Element).setAttribute('as-element', value); } // ortherwise do fallback check else { // is it an event handler? if (attr[0] === 'o' && attr[1] === 'n' && !attr.endsWith('$')) { const decoded = kebabCase(attr.slice(2)); const parts = decoded.split('-'); if (parts.length > 1) { const lastPart = parts[parts.length - 1]; const cmd = eventCmds[lastPart] ? lastPart : 'trigger'; (el as Element).setAttribute(`${parts.slice(0, -1).join('-')}.${cmd}`, value); } else { (el as Element).setAttribute(`${parts[0]}.trigger`, value); } } else { const len = attr.length; const parts = attr.split('$'); if (parts.length === 1) { (el as Element).setAttribute(kebabCase(attr), value); } else { if (parts[parts.length - 1] === '') { parts[parts.length - 1] = 'bind'; } (el as Element).setAttribute(parts.map(kebabCase).join('.'), value); } } } } } const appender = (el instanceof HTMLTemplateElement) ? el.content : el; for (const child of children) { if (child === null || child === undefined) { continue; } if (Array.isArray(child)) { for (const child_child of child) { if (child_child instanceof Node) { if (isFragment(child_child) && !isFragment(appender)) { if (!appender.shadowRoot) { appender.attachShadow({ mode: 'open' }); } appender.shadowRoot.appendChild(child_child); } else { appender.appendChild(child_child); } } else { appender.appendChild(document.createTextNode('' + child_child)); } } } else { if (child instanceof Node) { if (isFragment(child) && !isFragment(appender)) { if (!appender.shadowRoot) { appender.attachShadow({ mode: 'open' }); } appender.shadowRoot.appendChild(child); } else { appender.appendChild(child); } } else { appender.appendChild(document.createTextNode('' + child)); } } } return el; }; const isFragment = (node: Node): node is DocumentFragment => node.nodeType === Node.DOCUMENT_FRAGMENT_NODE; /** * Based on repet comment anchor/top/bot buffer elements * count the number of active elements (or views) a repeat has */ export const getRepeatActiveViewCount = (repeat: VirtualRepeat): number => { let count = 0; let curr = repeat.templateStrategy.getFirstElement(repeat.topBufferEl, repeat.bottomBufferEl); while (curr !== null) { count++; curr = curr.nextElementSibling; if (curr === repeat.bottomBufferEl) { break; } } return count; };
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/secretsMappers"; import * as Parameters from "../models/parameters"; import { KeyVaultManagementClientContext } from "../keyVaultManagementClientContext"; /** Class representing a Secrets. */ export class Secrets { private readonly client: KeyVaultManagementClientContext; /** * Create a Secrets. * @param {KeyVaultManagementClientContext} client Reference to the service client. */ constructor(client: KeyVaultManagementClientContext) { this.client = client; } /** * Create or update a secret in a key vault in the specified subscription. NOTE: This API is * intended for internal use in ARM deployments. Users should use the data-plane REST service for * interaction with vault secrets. * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param vaultName Name of the vault * @param secretName Name of the secret * @param parameters Parameters to create or update the secret * @param [options] The optional parameters * @returns Promise<Models.SecretsCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, vaultName: string, secretName: string, parameters: Models.SecretCreateOrUpdateParameters, options?: msRest.RequestOptionsBase): Promise<Models.SecretsCreateOrUpdateResponse>; /** * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param vaultName Name of the vault * @param secretName Name of the secret * @param parameters Parameters to create or update the secret * @param callback The callback */ createOrUpdate(resourceGroupName: string, vaultName: string, secretName: string, parameters: Models.SecretCreateOrUpdateParameters, callback: msRest.ServiceCallback<Models.Secret>): void; /** * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param vaultName Name of the vault * @param secretName Name of the secret * @param parameters Parameters to create or update the secret * @param options The optional parameters * @param callback The callback */ createOrUpdate(resourceGroupName: string, vaultName: string, secretName: string, parameters: Models.SecretCreateOrUpdateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Secret>): void; createOrUpdate(resourceGroupName: string, vaultName: string, secretName: string, parameters: Models.SecretCreateOrUpdateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Secret>, callback?: msRest.ServiceCallback<Models.Secret>): Promise<Models.SecretsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, vaultName, secretName, parameters, options }, createOrUpdateOperationSpec, callback) as Promise<Models.SecretsCreateOrUpdateResponse>; } /** * Update a secret in the specified subscription. NOTE: This API is intended for internal use in * ARM deployments. Users should use the data-plane REST service for interaction with vault * secrets. * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param vaultName Name of the vault * @param secretName Name of the secret * @param parameters Parameters to patch the secret * @param [options] The optional parameters * @returns Promise<Models.SecretsUpdateResponse> */ update(resourceGroupName: string, vaultName: string, secretName: string, parameters: Models.SecretPatchParameters, options?: msRest.RequestOptionsBase): Promise<Models.SecretsUpdateResponse>; /** * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param vaultName Name of the vault * @param secretName Name of the secret * @param parameters Parameters to patch the secret * @param callback The callback */ update(resourceGroupName: string, vaultName: string, secretName: string, parameters: Models.SecretPatchParameters, callback: msRest.ServiceCallback<Models.Secret>): void; /** * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param vaultName Name of the vault * @param secretName Name of the secret * @param parameters Parameters to patch the secret * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, vaultName: string, secretName: string, parameters: Models.SecretPatchParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Secret>): void; update(resourceGroupName: string, vaultName: string, secretName: string, parameters: Models.SecretPatchParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Secret>, callback?: msRest.ServiceCallback<Models.Secret>): Promise<Models.SecretsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, vaultName, secretName, parameters, options }, updateOperationSpec, callback) as Promise<Models.SecretsUpdateResponse>; } /** * Gets the specified secret. NOTE: This API is intended for internal use in ARM deployments. * Users should use the data-plane REST service for interaction with vault secrets. * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param vaultName The name of the vault. * @param secretName The name of the secret. * @param [options] The optional parameters * @returns Promise<Models.SecretsGetResponse> */ get(resourceGroupName: string, vaultName: string, secretName: string, options?: msRest.RequestOptionsBase): Promise<Models.SecretsGetResponse>; /** * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param vaultName The name of the vault. * @param secretName The name of the secret. * @param callback The callback */ get(resourceGroupName: string, vaultName: string, secretName: string, callback: msRest.ServiceCallback<Models.Secret>): void; /** * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param vaultName The name of the vault. * @param secretName The name of the secret. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, vaultName: string, secretName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Secret>): void; get(resourceGroupName: string, vaultName: string, secretName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Secret>, callback?: msRest.ServiceCallback<Models.Secret>): Promise<Models.SecretsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, vaultName, secretName, options }, getOperationSpec, callback) as Promise<Models.SecretsGetResponse>; } /** * The List operation gets information about the secrets in a vault. NOTE: This API is intended * for internal use in ARM deployments. Users should use the data-plane REST service for * interaction with vault secrets. * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param vaultName The name of the vault. * @param [options] The optional parameters * @returns Promise<Models.SecretsListResponse> */ list(resourceGroupName: string, vaultName: string, options?: Models.SecretsListOptionalParams): Promise<Models.SecretsListResponse>; /** * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param vaultName The name of the vault. * @param callback The callback */ list(resourceGroupName: string, vaultName: string, callback: msRest.ServiceCallback<Models.SecretListResult>): void; /** * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param vaultName The name of the vault. * @param options The optional parameters * @param callback The callback */ list(resourceGroupName: string, vaultName: string, options: Models.SecretsListOptionalParams, callback: msRest.ServiceCallback<Models.SecretListResult>): void; list(resourceGroupName: string, vaultName: string, options?: Models.SecretsListOptionalParams | msRest.ServiceCallback<Models.SecretListResult>, callback?: msRest.ServiceCallback<Models.SecretListResult>): Promise<Models.SecretsListResponse> { return this.client.sendOperationRequest( { resourceGroupName, vaultName, options }, listOperationSpec, callback) as Promise<Models.SecretsListResponse>; } /** * The List operation gets information about the secrets in a vault. NOTE: This API is intended * for internal use in ARM deployments. Users should use the data-plane REST service for * interaction with vault secrets. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.SecretsListNextResponse> */ listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.SecretsListNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.SecretListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretListResult>): void; listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretListResult>, callback?: msRest.ServiceCallback<Models.SecretListResult>): Promise<Models.SecretsListNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback) as Promise<Models.SecretsListNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/secrets/{secretName}", urlParameters: [ Parameters.resourceGroupName, Parameters.vaultName0, Parameters.secretName0, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.SecretCreateOrUpdateParameters, required: true } }, responses: { 200: { bodyMapper: Mappers.Secret }, 201: { bodyMapper: Mappers.Secret }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/secrets/{secretName}", urlParameters: [ Parameters.resourceGroupName, Parameters.vaultName0, Parameters.secretName0, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.SecretPatchParameters, required: true } }, responses: { 200: { bodyMapper: Mappers.Secret }, 201: { bodyMapper: Mappers.Secret }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/secrets/{secretName}", urlParameters: [ Parameters.resourceGroupName, Parameters.vaultName1, Parameters.secretName1, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Secret }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/secrets", urlParameters: [ Parameters.resourceGroupName, Parameters.vaultName1, Parameters.subscriptionId ], queryParameters: [ Parameters.top, Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SecretListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SecretListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import React, { useCallback, useState, useEffect, useMemo } from 'react' import './index.less' import { Tooltip, Dropdown, Menu, message } from 'antd' import { hash, handleTwoSideSymbol, addList, addCodeBlock, addLink, addTable, addPhoto } from '../utils' import { BoldOutlined, ItalicOutlined, StrikethroughOutlined, OrderedListOutlined, UnorderedListOutlined, CarryOutOutlined, LinkOutlined, TableOutlined, PictureOutlined, LeftOutlined, RightOutlined, BulbOutlined, CodeOutlined, EllipsisOutlined, DownloadOutlined, UploadOutlined, ExpandOutlined, InsertRowRightOutlined, InsertRowLeftOutlined, MenuOutlined, } from '@ant-design/icons' import { ModeType, CodeBlockType, StateType } from '../types' import { CODELANGUAGE } from '../const' const { Item, ItemGroup } = Menu interface PropsType { state: StateType; dispatch: React.Dispatch<{ type: string, payload?: any }>; value: string; setValue: Function; editElement: any; } const NavBar: React.FC<PropsType> = ({ editElement, setValue, value, state, dispatch }) => { const [codeHighLightTheme, setCodeHighLightTheme] = useState('railscasts') // 当前代码高亮的主题 const [markdownTheme, setMarkdownTheme] = useState('maize') // 当前markdown的主题 // 代码块的列表元素 const codeBlockMenu = ( <Menu onClick={({ key }) => addCodeBlock(editElement.current, setValue, value, key)}> <ItemGroup title="代码块语言" className="item-group-list-container"> { CODELANGUAGE.map(({ key, language }: CodeBlockType) => <Item key={key}>{ language }</Item>) } </ItemGroup> </Menu> ) // 选择代码高亮主题 const selectCodeHighLightTheme = useCallback(({ key }) => { dispatch({ type: 'toggleLoading', payload: true }) setCodeHighLightTheme(key) }, []) // 代码高亮选择菜单 const codeHighLightMenu = useMemo(() => ( <Menu onClick={selectCodeHighLightTheme}> <ItemGroup title="代码高亮主题" className="item-group-list-container code-highlight-theme-menu"> <Item key="github" className={`${codeHighLightTheme === 'github' && 'active'}`}>github</Item> <Item key="railscasts" className={`${codeHighLightTheme === 'railscasts' && 'active'}`}>railscasts</Item> <Item key="androidstudio" className={`${codeHighLightTheme === 'androidstudio' && 'active'}`}>androidstudio</Item> <Item key="dracula" className={`${codeHighLightTheme === 'dracula' && 'active'}`}>dracula</Item> <Item key="atom-one-dark" className={`${codeHighLightTheme === 'atom-one-dark' && 'active'}`}>atom-one-dark</Item> <Item key="atom-one-light" className={`${codeHighLightTheme === 'atom-one-light' && 'active'}`}>atom-one-light</Item> <Item key="monokai-sublime" className={`${codeHighLightTheme === 'monokai-sublime' && 'active'}`}>monokai-sublime</Item> <Item key="tomorrow" className={`${codeHighLightTheme === 'tomorrow' && 'active'}`}>tomorrow</Item> <Item key="solarized-dark" className={`${codeHighLightTheme === 'solarized-dark' && 'active'}`}>solarized-dark</Item> <Item key="solarized-light" className={`${codeHighLightTheme === 'solarized-light' && 'active'}`}>solarized-light</Item> <Item key="color-brewer" className={`${codeHighLightTheme === 'color-brewer' && 'active'}`}>color-brewer</Item> <Item key="zenburn" className={`${codeHighLightTheme === 'zenburn' && 'active'}`}>zenburn</Item> <Item key="agate" className={`${codeHighLightTheme === 'agate' && 'active'}`}>agate</Item> </ItemGroup> </Menu> ), [selectCodeHighLightTheme]) // 选择markdown主题 const selectMarkdownTheme = ({ key } : { key: string }) => { dispatch({ type: 'toggleLoading', payload: true }) setMarkdownTheme(key) } // markdown主题选择菜单 const markdownThemeMenu = useMemo(() => ( <Menu onClick={selectMarkdownTheme}> <ItemGroup title="markdown主题" className="item-group-list-container markdown-theme-menu"> <Item key="github" className={`${markdownTheme === 'github' && 'active'}`}>github</Item> <Item key="maize" className={`${markdownTheme === 'maize' && 'active'}`}>maize</Item> </ItemGroup> </Menu> ), [selectMarkdownTheme]) // 控制「更多」中的按钮的点击 const handleMoreFunction = useCallback(({ key }) => { switch(key) { case 'importMd': importMd(); break; case 'exportMd': exportMd(); break; } }, []) // 导出md文件 const exportMd = () => { if(!Blob || !URL) return message.error('浏览器不支持导出md文件,请更换浏览器再试'); if(!value) return message.warning('当前内容为空,无需导出'); let blob = new Blob([value]) let a = document.createElement('a') let downloadURL = URL.createObjectURL(blob) a.href = downloadURL a.download = `${hash()}.md` a.click() URL.revokeObjectURL(downloadURL); } // 导入md文件 const importMd = () => { if(!FileReader) return message.error('浏览器不支持导入md文件,请更换浏览器再试'); let input = document.createElement('input'); input.type = 'file' input.accept = '.md' input.click() input.addEventListener('change', () => { let files = input.files as FileList if(!files.length) return; let reader = new FileReader() reader.readAsText(files[0]) reader.onload = () => { setValue(reader.result as string) message.success('导入成功') } }) } const modeTabClick = (newMode: ModeType) => { dispatch({ type: 'toggleMode', payload: state.mode === newMode ? ModeType.NORMAL : newMode, }) dispatch({ type: 'toggleTOC', payload: false }); } // 更多菜单 const moreMenu = useMemo(() => ( <Menu onClick={handleMoreFunction}> <Item key="importMd"> <UploadOutlined /> 导入md </Item> <Item key="exportMd"> <DownloadOutlined /> 导出md </Item> </Menu> ), [handleMoreFunction]) // 切换代码高亮主题 useEffect(() => { let head = document.head let oldLink = head.getElementsByClassName('highlightjs-style-link') if(oldLink.length) head.removeChild(oldLink[0]) let newLink = document.createElement('link') newLink.setAttribute('rel', 'stylesheet') newLink.setAttribute('type', 'text/css') newLink.setAttribute('class', 'highlightjs-style-link') newLink.setAttribute('href', `https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.7.2/styles/${codeHighLightTheme}.min.css`) newLink.onload = () => dispatch({ type: 'toggleLoading', payload: false }); newLink.onerror = () => { dispatch({ type: 'toggleLoading', payload: false }); message.error('主题获取失败,请稍后重试或尝试其它主题') } head.appendChild(newLink) }, [codeHighLightTheme]) // 切换markdown样式主题 useEffect(() => { let head = document.head let oldLink = head.getElementsByClassName('markdownTheme-style-link') if(oldLink.length) head.removeChild(oldLink[0]) let newLink = document.createElement('link') newLink.setAttribute('rel', 'stylesheet') newLink.setAttribute('type', 'text/css') newLink.setAttribute('class', 'markdownTheme-style-link') newLink.setAttribute('href', `https://lpyexplore.gitee.io/taobao_staticweb/css/theme/${markdownTheme}.css`) newLink.onload = () => dispatch({ type: 'toggleLoading', payload: false }); newLink.onerror = () => { dispatch({ type: 'toggleLoading', payload: false }); message.error('主题获取失败,请稍后重试或尝试其它主题') } head.appendChild(newLink) }, [markdownTheme]) return ( <nav className="__markdown-editor-reactjs-nav-bar"> <Tooltip title='加粗' arrowPointAtCenter> <BoldOutlined className="item" onClick={() => handleTwoSideSymbol(editElement.current, setValue, value, '**', '加粗字体')}/> </Tooltip> <Tooltip title='斜体' arrowPointAtCenter> <ItalicOutlined className="item" onClick={() => handleTwoSideSymbol(editElement.current, setValue, value, '*', '倾斜字体')}/> </Tooltip> <Tooltip title='删除线' arrowPointAtCenter> <StrikethroughOutlined className="item" onClick={() => handleTwoSideSymbol(editElement.current, setValue, value, '~~', '删除文本')}/> </Tooltip> <Tooltip title='有序列表' arrowPointAtCenter> <OrderedListOutlined className="item" onClick={() => addList(editElement.current, setValue, value, '1.', '有序列表')}/> </Tooltip> <Tooltip title='无序列表' arrowPointAtCenter> <UnorderedListOutlined className="item" onClick={() => addList(editElement.current, setValue, value, '-', '无序列表')}/> </Tooltip> <Tooltip title='任务列表' arrowPointAtCenter> <CarryOutOutlined className="item" onClick={() => addList(editElement.current, setValue, value, '- [x]', '任务列表')}/> </Tooltip> <Dropdown overlay={codeBlockMenu} placement="bottomCenter" arrow > <span className="item code" style={{ fontSize: 12 }}> <LeftOutlined />/<RightOutlined/> </span> </Dropdown> <Tooltip title='超链接' arrowPointAtCenter> <LinkOutlined className="item" onClick={() => addLink(editElement.current, setValue, value)}/> </Tooltip> <Tooltip title='表格' arrowPointAtCenter> <TableOutlined className="item" onClick={() => addTable(editElement.current, setValue, value)}/> </Tooltip> <Tooltip title='图片' arrowPointAtCenter> <PictureOutlined className="item" onClick={() => addPhoto(editElement.current, setValue, value)}/> </Tooltip> <Dropdown overlay={markdownThemeMenu} placement="bottomCenter" arrow > <BulbOutlined className="item"/> </Dropdown> <Dropdown overlay={codeHighLightMenu} placement="bottomCenter" arrow > <CodeOutlined className="item"/> </Dropdown> <Dropdown overlay={moreMenu} placement="bottomCenter" arrow > <EllipsisOutlined className="item"/> </Dropdown> <section className="right"> <Tooltip title='目录' arrowPointAtCenter> <MenuOutlined className={`item ${state.showTOC ? 'active' : ''}`} onClick={() => dispatch({ type: 'toggleTOC' })} /> </Tooltip> <Tooltip title='仅编辑' arrowPointAtCenter> <InsertRowRightOutlined className={`item ${state.mode === ModeType.EDIT ? 'active' : ''}`} onClick={() => modeTabClick(ModeType.EDIT)} /> </Tooltip> <Tooltip title='仅预览' arrowPointAtCenter> <InsertRowLeftOutlined className={`item ${state.mode === ModeType.PREVIEW ? 'active' : ''}`} onClick={() => modeTabClick(ModeType.PREVIEW)} /> </Tooltip> <Tooltip title='进入全屏' arrowPointAtCenter> <ExpandOutlined className={`item ${state.mode === ModeType.EXHIBITION ? 'active' : ''}`} onClick={() => modeTabClick(ModeType.EXHIBITION)} /> </Tooltip> </section> </nav> ) } export default NavBar
the_stack
import React, { useEffect } from "react"; import {makeStyles, Theme, createStyles, Divider, Hidden, LinearProgress} from "@material-ui/core"; import MediaGridList from "./MediaGridList"; import MediaFolders from "./MediaFolders"; import { FolderNode } from "./MediaFolder"; import MediasToolbar from "./MediasToolbar"; import intl from 'react-intl-universal'; import MediasBreadCrumbs from "./MediasBreadCrumbs"; import MediasBatchActions from "./MediasBatchActions"; import { IMedia } from "Base/Model/IMedia"; import { useLazyQuery, useMutation, useQuery } from "@apollo/react-hooks"; import { MUTATION_ADD_FOLDER, MUTATION_REMOVE_FOLDER, MUTATION_REMOVE_MEDIAS, MUTATION_UPDATE_FOLDER, MUTATION_UPDATE_MEDIA, QUERY_FOLDERS, QUERY_MEDIAS } from "./MediaGQLs"; import { ID } from "rx-drag/models/baseTypes"; import { useShowAppoloError } from "Store/Helpers/useInfoError"; import { toggle, batchRemove, remove } from "rx-drag/utils/ArrayHelper"; import { cloneObject } from "rx-drag/utils/cloneObject"; const useStyles = makeStyles((theme: Theme) => createStyles({ root: { flex: 1, display:'flex', flexFlow:'row', }, square:{ borderRadius:'0', }, left:{ flex:1, display:'flex', flexFlow:'column', }, toolbar:{ minHeight:theme.spacing(7), display:'flex', flexFlow:'row', alignItems:'center', flexWrap: 'wrap', paddingRight: '0', }, right:{ width:'260px', flexShrink:0, display:'flex', flexFlow:'column', }, mediasGrid:{ flex:1, display:'flex', flexFlow:'column', //padding:theme.spacing(0, 2, 2, 2), }, folderTitle:{ padding:theme.spacing(2) , minHeight:theme.spacing(7), display:'flex', alignItems: 'center', fontWeight: 500, fontSize: '1.1rem', position: 'relative', }, }), ); function makeupParent(folders?:Array<FolderNode>, parent?:FolderNode){ folders && folders.forEach(folder=>{ folder.parent = parent; makeupParent(folder.children, folder) }) return folders?folders:[]; } function getByIdFromTree(id:ID, folders?:Array<FolderNode>):FolderNode|undefined{ if(folders){ for(var i = 0; i < folders.length; i++){ if(folders[i].id === id){ return folders[i]; } let searchedChild = getByIdFromTree(id, folders[i].children); if(searchedChild){ return searchedChild; } } } return undefined; } export default function MediasContent( props:{ single?:boolean, onSelectedChange?:(medias:Array<IMedia>)=>void } ){ const {single, onSelectedChange} = props; const classes = useStyles(); const [folderLoading, setFolderLoading] = React.useState<boolean|string>(false); const [draggedFolder, setDraggedFolder] = React.useState<FolderNode|undefined>(); const [draggedMedia, setDraggedMedia] = React.useState<IMedia|undefined>(); const [folders, setFolders] = React.useState<Array<FolderNode>>([]); const [selectedFolder, setSelectedFolder] = React.useState('root'); const [gridLoading, setGridLoading] = React.useState(false); const [medias, setMedias] = React.useState<Array<IMedia>>([]); const [selectedMedias, setSelectedMedias] = React.useState<Array<IMedia>>([]); const [pageNumber, setPageNumber] = React.useState(0); const [hasData, setHasData] = React.useState(true); const [batchActionLoading, setBatchActionLoading] = React.useState(false); const { loading, error:queryFolderError, data:folderData } = useQuery(QUERY_FOLDERS, {fetchPolicy:'no-cache'}); const [excuteQuery, { loading:queryLoading, error:queryError, data:mediaData, refetch }] = useLazyQuery(QUERY_MEDIAS, { variables: { first:20, page:pageNumber + 1}, notifyOnNetworkStatusChange: true, fetchPolicy:'no-cache' }); const [addFolder, {error:addFolderError}] = useMutation(MUTATION_ADD_FOLDER, { onCompleted:(data)=>{ setFolderLoading(false); let newFolder = data?.addMediaFolder; if(!newFolder){ return; } setSelectedFolder(newFolder?.id || 'root'); const parent = getByIdFromTree(newFolder?.parent?.id, folders); newFolder.editing = true; newFolder.parent = parent; if(parent){ parent.children = parent.children ? [...parent.children, newFolder] : [newFolder]; setFolders([...folders]) }else{ setFolders([...folders, newFolder]); } } } ); const [updateFolder, {error:updateFolderError}] = useMutation(MUTATION_UPDATE_FOLDER,{ onCompleted:(data)=>{ setFolderLoading(false); }}); const [removeFolder, {error:removeFolderError}] = useMutation(MUTATION_REMOVE_FOLDER,{ onCompleted:(data)=>{ setFolderLoading(false); }}); const [updateMedia, {error:updateMediaError}] = useMutation(MUTATION_UPDATE_MEDIA,{ onCompleted:(data)=>{ setFolderLoading(false); }}); const [removeMedias, {error:removeMediasError}] = useMutation(MUTATION_REMOVE_MEDIAS,{ onCompleted:(data)=>{ setBatchActionLoading(false); }}); useEffect(()=>{ setGridLoading(queryLoading); }, [queryLoading]) const selectedFolderNode = getByIdFromTree(selectedFolder, folders); const error = queryFolderError || queryError || addFolderError || updateFolderError || removeFolderError || updateMediaError || removeMediasError; useShowAppoloError(error); useEffect(()=>{ setFolderLoading(loading); },[loading]) useEffect(()=>{ if(folderData){ const queriedFolders:Array<FolderNode> = makeupParent(cloneObject((folderData && folderData['mediaFoldersTree'])||[])); setFolders(queriedFolders) } },[folderData]) useEffect(()=>{ setMedias([...medias, ...(mediaData?.medias?.data||[])]) setHasData(mediaData?.medias?.paginatorInfo?.hasMorePages); // eslint-disable-next-line react-hooks/exhaustive-deps },[mediaData]) useEffect(() => { setGridLoading(true); setPageNumber(0); setMedias([]); setSelectedMedias([]); excuteQuery({variables: { first:20, page:pageNumber + 1}}); // eslint-disable-next-line react-hooks/exhaustive-deps },[pageNumber, selectedFolder]); useEffect(() => { onSelectedChange && onSelectedChange([...selectedMedias]); // eslint-disable-next-line react-hooks/exhaustive-deps },[selectedMedias]); const handleScrollToEnd = ()=>{ if(!gridLoading && hasData){ setGridLoading(true); refetch && refetch({ first:20, page:pageNumber + 1}); } } const handleAddFolder = (parent?:FolderNode)=>{ setFolderLoading(true) addFolder({variables:{parentId:parent?.id}}); } const handleFolderNameChange = (name:string, folder:FolderNode, fromGrid?:boolean)=>{ fromGrid ? setFolderLoading(folder.id) : setFolderLoading(true) folder.name = name; updateFolder({variables:{folder:{id:folder.id, name:folder.name, parentId:folder.parent?.id}}}); } const handleRemoveFolder = (folder:FolderNode, fromGrid?:boolean)=>{ const parentFolder = folder.parent; setFolderLoading(true) if(selectedFolder === folder.id){ setSelectedFolder('root'); } removeFolder({variables:{id:folder.id}}) if(!parentFolder){ remove(folder, folders) } else{ remove(folder, parentFolder.children) } } const handleMoveToFolderTo = (folder:FolderNode, targetFolder:FolderNode|undefined, fromGrid?:boolean)=>{ const parentFolder = folder.parent; fromGrid ? setFolderLoading(targetFolder ? targetFolder.id : true) : setFolderLoading(true) if(selectedFolder === folder.id){ setSelectedFolder('root'); } updateFolder({variables:{folder:{id:folder.id, name:folder.name, parentId:targetFolder?.id}}}); if(parentFolder){ remove(folder, parentFolder.children) } else{ remove(folder, folders) } folder.parent = undefined; if(targetFolder){ targetFolder.children = targetFolder?.children? [...targetFolder?.children, folder] : [folder] folder.parent = targetFolder; } else{ folders.push(folder) } } const handelMoveMediaTo = (media:IMedia, targetFolder:FolderNode|undefined, fromGrid?:boolean)=>{ if(targetFolder?.id === selectedFolder || (!targetFolder && selectedFolder==='root')){ return } fromGrid ? setFolderLoading(targetFolder ? targetFolder.id : true) : setFolderLoading(true); updateMedia({variables:{media:{id:media.id, title:media.title, folderId:targetFolder?.id}}}); remove(media, medias); setMedias([...medias]); } const handeRemoveMedia = (media:IMedia)=>{ remove(media, medias); remove(media, selectedMedias); setMedias([...medias]); setSelectedMedias([...selectedMedias]); } const handleToggleSelectMedia = (media:IMedia)=>{ if(single){ if(selectedMedias.length > 0 && media === selectedMedias[0]){ setSelectedMedias([]) }else{ setSelectedMedias([media]); } }else{ toggle(media, selectedMedias); setSelectedMedias([...selectedMedias]); } } const handleRemoveSelected = ()=>{ setBatchActionLoading(true) removeMedias({variables:{ids:selectedMedias.map((media)=>{return media.id})}}) batchRemove(selectedMedias, medias) setSelectedMedias([]) setMedias([...medias]) } return ( <div className={classes.root}> <div className = {classes.left}> <div className ={classes.toolbar}> { selectedMedias.length > 0 ? <MediasBatchActions selectedMedias = {selectedMedias} onClearSelected = {()=>setSelectedMedias([])} onRemoveSelected = {handleRemoveSelected} /> : <MediasToolbar /> } </div> <Divider></Divider> <MediasBreadCrumbs selectedFolder = {selectedFolder} selectedFolderNode = {selectedFolderNode} onSelect={setSelectedFolder} /> {batchActionLoading && <LinearProgress />} <div className ={classes.mediasGrid}> <MediaGridList loading={gridLoading} folderLoading = {folderLoading} draggedFolder = {draggedFolder} draggedMedia = {draggedMedia} folder = {selectedFolderNode} folders = {selectedFolderNode? selectedFolderNode.children : folders} medias = {medias} selectedMedias = {selectedMedias} onScrollToEnd = {handleScrollToEnd} onSelect = {(folder)=>{ setSelectedFolder(folder); }} onFolderNameChange = {(name, folder)=>handleFolderNameChange(name, folder, true)} onRemoveFolder = {(folder)=>handleRemoveFolder(folder, true)} onMoveFolderTo = {(folder, targetFolder)=>handleMoveToFolderTo(folder, targetFolder, true)} onMoveMediaTo = {(media, folder)=>handelMoveMediaTo(media, folder, true)} onRemoveMedia = {handeRemoveMedia} onDragFolder = {setDraggedFolder} onMediaDragStart = {setDraggedMedia} onMediaDragEnd = {()=>setDraggedMedia(undefined)} onToggleSelectMedia = {handleToggleSelectMedia} ></MediaGridList> </div> </div> <Divider orientation="vertical" flexItem /> <Hidden mdDown> <div className = {classes.right}> <div className = {classes.folderTitle}> {intl.get('folder')} </div> <Divider></Divider> { (folderLoading === true) && <LinearProgress /> } <MediaFolders draggedFolder = {draggedFolder} draggedMedia = {draggedMedia} folders = {folders} selectedFolder={selectedFolder} onSelect = {(folder)=>{ setSelectedFolder(folder); }} onAddFolder = {handleAddFolder} onFolderNameChange = {handleFolderNameChange} onRemoveFolder = {handleRemoveFolder} onMoveFolderTo = {handleMoveToFolderTo} onMoveMediaTo = {handelMoveMediaTo} onDragFolder = {setDraggedFolder} /> </div> </Hidden> </div> ) }
the_stack
import * as React from "react"; import * as auth from "./auth"; import * as core from "./core"; import * as data from "./data"; import * as sui from "./sui"; import * as simulator from "./simulator"; import * as screenshot from "./screenshot"; import * as qr from "./qr"; import { fireClickOnEnter } from "./util"; import { Modal, ModalAction } from "../../react-common/components/controls/Modal"; import { Share, ShareData } from "../../react-common/components/share/Share"; type ISettingsProps = pxt.editor.ISettingsProps; export enum ShareMode { Code, Url, Editor, Simulator } export interface ShareEditorProps extends ISettingsProps { loading?: boolean; } // This Component overrides shouldComponentUpdate, be sure to update that if the state is updated export interface ShareEditorState { mode?: ShareMode; pubId?: string; visible?: boolean; sharingError?: Error; loading?: boolean; projectName?: string; projectNameChanged?: boolean; thumbnails?: boolean; screenshotUri?: string; recordError?: string; qrCodeUri?: string; qrCodeExpanded?: boolean; title?: string; } export class ShareEditor extends auth.Component<ShareEditorProps, ShareEditorState> { private loanedSimulator: HTMLElement; private _gifEncoder: screenshot.GifEncoder; constructor(props: ShareEditorProps) { super(props); this.state = { pubId: undefined, visible: false, screenshotUri: undefined, recordError: undefined, title: undefined } this.hide = this.hide.bind(this); this.setAdvancedMode = this.setAdvancedMode.bind(this); this.handleProjectNameChange = this.handleProjectNameChange.bind(this); this.restartSimulator = this.restartSimulator.bind(this); this.handleCreateGitHubRepository = this.handleCreateGitHubRepository.bind(this); } hide() { if (this.state.qrCodeExpanded) { pxt.tickEvent('share.qrtoggle'); const { qrCodeExpanded } = this.state; this.setState({ qrCodeExpanded: !qrCodeExpanded }); return; } if (this._gifEncoder) { this._gifEncoder.cancel(); this._gifEncoder = undefined; } if (this.loanedSimulator) { simulator.driver.unloanSimulator(); this.loanedSimulator = undefined; simulator.driver.stopRecording(); } this.setState({ visible: false, screenshotUri: undefined, projectName: undefined, projectNameChanged: false, recordError: undefined, qrCodeUri: undefined, title: undefined }); } show(title?: string) { const { header } = this.props.parent.state; if (!header) return; // TODO investigate why edge does not render well // upon hiding dialog, the screen does not redraw properly const thumbnails = pxt.appTarget.cloud && pxt.appTarget.cloud.thumbnails && (pxt.appTarget.appTheme.simScreenshot || pxt.appTarget.appTheme.simGif); if (thumbnails) { this.loanedSimulator = simulator.driver.loanSimulator(); } this.setState({ thumbnails, visible: true, mode: ShareMode.Code, pubId: undefined, sharingError: undefined, screenshotUri: undefined, qrCodeUri: undefined, qrCodeExpanded: false, title, projectName: header.name }, thumbnails ? (() => this.props.parent.startSimulator()) : undefined); } UNSAFE_componentWillReceiveProps(newProps: ShareEditorProps) { const newState: ShareEditorState = {} if (!this.state.projectNameChanged && newProps.parent.state.projectName != this.state.projectName) { newState.projectName = newProps.parent.state.projectName; } if (newProps.loading != this.state.loading) { newState.loading = newProps.loading; } if (Object.keys(newState).length > 0) { this.setState(newState); } } shouldComponentUpdate(nextProps: ShareEditorProps, nextState: ShareEditorState, nextContext: any): boolean { return this.state.visible != nextState.visible || this.state.mode != nextState.mode || this.state.pubId != nextState.pubId || this.state.sharingError !== nextState.sharingError || this.state.projectName != nextState.projectName || this.state.projectNameChanged != nextState.projectNameChanged || this.state.loading != nextState.loading || this.state.screenshotUri != nextState.screenshotUri || this.state.qrCodeUri != nextState.qrCodeUri || this.state.qrCodeExpanded != nextState.qrCodeExpanded || this.state.title != nextState.title ; } private setAdvancedMode(mode: ShareMode) { this.setState({ mode: mode }); } handleProjectNameChange(name: string) { this.setState({ projectName: name, projectNameChanged: true }); } restartSimulator() { pxt.tickEvent('share.restart', undefined, { interactiveConsent: true }); this.props.parent.restartSimulator(); } screenshotAsync = () => { pxt.tickEvent("share.takescreenshot", { view: 'computer', collapsedTo: '' + !this.props.parent.state.collapseEditorTools }, { interactiveConsent: true }); return this.props.parent.requestScreenshotAsync() .then(img => { if (img) { this.setState({ screenshotUri: img }); } else { this.setState({ recordError: lf("Oops, screenshot failed. Please try again.") }); } }); } private loadEncoderAsync(): Promise<screenshot.GifEncoder> { if (this._gifEncoder) return Promise.resolve(this._gifEncoder); return screenshot.loadGifEncoderAsync() .then(encoder => this._gifEncoder = encoder); } gifRecord = async () => { pxt.tickEvent("share.gifrecord", { view: 'computer', collapsedTo: '' + !this.props.parent.state.collapseEditorTools }, { interactiveConsent: true }); try { const encoder = await this.loadEncoderAsync(); if (!encoder) { this.setState({ recordError: lf("Oops, gif encoder could not load. Please try again.") }); } else { encoder.start(); const gifwidth = pxt.appTarget.appTheme.simGifWidth || 160; simulator.driver.startRecording(gifwidth); } } catch (e: any) { pxt.reportException(e); this.setState({ recordError: lf("Oops, gif recording failed. Please try again.") }); if (this._gifEncoder) { this._gifEncoder.cancel(); } } } gifRender = async (): Promise<string> => { pxt.debug(`render gif`) simulator.driver.stopRecording(); if (!this._gifEncoder) return undefined; this.props.parent.stopSimulator(); let uri = await this._gifEncoder.renderAsync(); pxt.log(`gif: ${uri ? uri.length : 0} chars`) const maxSize = pxt.appTarget.appTheme.simScreenshotMaxUriLength; let recordError: string = undefined; if (uri) { if (maxSize && uri.length > maxSize) { pxt.tickEvent(`gif.toobig`, { size: uri.length }); uri = undefined; recordError = lf("Gif is too big, try recording a shorter time."); } else pxt.tickEvent(`gif.ok`, { size: uri.length }); } // give a breather to the browser to render the gif pxt.Util.delay(1000).then(() => this.props.parent.startSimulator()); return uri; } gifAddFrame = (dataUri?: ImageData, delay?: number) => { if (this._gifEncoder) return this._gifEncoder.addFrame(dataUri, delay); return false; } handleCreateGitHubRepository() { pxt.tickEvent("share.github.create", undefined, { interactiveConsent: true }); this.hide(); this.props.parent.createGitHubRepositoryAsync(); } protected async getShareUrl(pubId: string, persistent?: boolean) { const targetTheme = pxt.appTarget.appTheme; const header = this.props.parent.state.header; let shareData: ShareData = { url: "", embed: {} }; let shareUrl = (persistent ? targetTheme.homeUrl : targetTheme.shareUrl) || "https://makecode.com/"; if (!/\/$/.test(shareUrl)) shareUrl += '/'; let rootUrl = targetTheme.embedUrl if (!/\/$/.test(rootUrl)) rootUrl += '/'; const verPrefix = pxt.webConfig.verprefix || ''; if (header) { shareData.url = `${shareUrl}${pubId}`; shareData.embed.code = pxt.docs.codeEmbedUrl(`${rootUrl}${verPrefix}`, pubId); shareData.embed.editor = pxt.docs.embedUrl(`${rootUrl}${verPrefix}`, "pub", pubId); shareData.embed.url = `${rootUrl}${verPrefix}#pub:${pubId}`; let padding = '81.97%'; // TODO: parts aspect ratio let simulatorRunString = `${verPrefix}---run`; if (pxt.webConfig.runUrl) { if (pxt.webConfig.isStatic) { simulatorRunString = pxt.webConfig.runUrl; } else { // Always use live, not /beta etc. simulatorRunString = pxt.webConfig.runUrl.replace(pxt.webConfig.relprefix, "/---") } } if (pxt.appTarget.simulator) padding = (100 / pxt.appTarget.simulator.aspectRatio).toPrecision(4) + '%'; const runUrl = rootUrl + simulatorRunString.replace(/^\//, ''); shareData.embed.simulator = pxt.docs.runUrl(runUrl, padding, pubId); } if (targetTheme.qrCode) { shareData.qr = await qr.renderAsync(`${shareUrl}${pubId}`); } return shareData; } renderCore() { const { parent } = this.props; const { visible, projectName: newProjectName, title, screenshotUri } = this.state; const { simScreenshot, simGif } = pxt.appTarget.appTheme; const hasIdentity = auth.hasIdentity() && this.isLoggedIn(); const light = !!pxt.options.light; const thumbnails = pxt.appTarget.cloud && pxt.appTarget.cloud.thumbnails && (simScreenshot || simGif); const screenshotAsync = async () => await this.props.parent.requestScreenshotAsync(); const publishAsync = async (name: string, screenshotUri?: string, forceAnonymous?: boolean) => { pxt.tickEvent("menu.embed.publish", undefined, { interactiveConsent: true }); if (name && parent.state.projectName != name) { await parent.updateHeaderNameAsync(name); } try { const persistentPublish = hasIdentity && !forceAnonymous; const id = (persistentPublish ? await parent.persistentPublishAsync(screenshotUri) : await parent.anonymousPublishAsync(screenshotUri)); return await this.getShareUrl(id, persistentPublish); } catch (e) { pxt.tickEvent("menu.embed.error", { code: (e as any).statusCode }) return { url: "", embed: {}, error: e } as ShareData } } return visible ? <Modal title={lf("Share Project")} fullscreen={simScreenshot || simGif} className="sharedialog" parentElement={document.getElementById("root") || undefined} onClose={this.hide}> <Share projectName={newProjectName} screenshotUri={screenshotUri} showShareDropdown={hasIdentity} screenshotAsync={simScreenshot ? screenshotAsync : undefined} gifRecordAsync={!light && simGif ? this.gifRecord : undefined} gifRenderAsync={!light && simGif ? this.gifRender : undefined} gifAddFrame={!light && simGif ? this.gifAddFrame : undefined} publishAsync={publishAsync} registerSimulatorMsgHandler={thumbnails ? parent.pushScreenshotHandler : undefined} unregisterSimulatorMsgHandler={thumbnails ? parent.popScreenshotHandler : undefined} /> </Modal> : <></> } componentDidUpdate() { const container = document.getElementById("shareLoanedSimulator"); if (container && this.loanedSimulator && !this.loanedSimulator.parentNode) { container.appendChild(this.loanedSimulator); } const { screenshotUri, visible } = this.state; const targetTheme = pxt.appTarget.appTheme; if (visible && this.loanedSimulator && targetTheme.simScreenshot && !screenshotUri) { this.screenshotAsync().then(() => this.forceUpdate()); } } }
the_stack
import GlueCore, { Glue42Core } from "@glue42/core"; import GlueWeb, { Glue42Web, Glue42WebFactoryFunction } from "@glue42/web"; import { GlueClientControlName, GlueWebPlatformControlName, GlueWebPlatformStreamName, GlueWebPlatformWorkspacesStreamName, GlueWorkspaceFrameClientControlName } from "../common/constants"; import { BridgeOperation, ControlMessage, InternalPlatformConfig, LibDomains } from "../common/types"; import { PortsBridge } from "../connection/portsBridge"; import { generate } from "shortid"; import { SessionStorageController } from "./session"; import logger from "../shared/logger"; import { PromisePlus } from "../shared/promisePlus"; import { waitFor } from "../shared/utils"; import { UnsubscribeFunction } from "callback-registry"; import { FrameSessionData } from "../libs/workspaces/types"; export class GlueController { private _systemGlue!: Glue42Core.GlueCore; private _clientGlue!: Glue42Web.API; private _systemStream: Glue42Core.Interop.Stream | undefined; private _workspacesStream: Glue42Core.Interop.Stream | undefined; private _platformClientWindowId!: string; constructor( private readonly portsBridge: PortsBridge, private readonly sessionStorage: SessionStorageController ) { } public get clientGlue(): Glue42Web.API { return this._clientGlue; } public get platformWindowId(): string { return this._platformClientWindowId.slice(); } public async start(config: InternalPlatformConfig): Promise<void> { this._systemGlue = await this.initSystemGlue(config.glue); logger.setLogger(this._systemGlue.logger); } public async initClientGlue(config?: Glue42Web.Config, factory?: Glue42WebFactoryFunction, isWorkspaceFrame?: boolean): Promise<Glue42Web.API> { const port = await this.portsBridge.createInternalClient(); this.registerClientWindow(isWorkspaceFrame); const webConfig = { application: "Platform", gateway: { webPlatform: { port, windowId: this.platformWindowId } } }; const c = Object.assign({}, config, webConfig); this._clientGlue = factory ? await factory(c) : await GlueWeb(c) as any; return this._clientGlue; } public async createPlatformSystemMethod(handler: (args: ControlMessage, caller: Glue42Web.Interop.Instance, success: (args?: ControlMessage) => void, error: (error?: string | object) => void) => void): Promise<void> { await this.createMethodAsync(GlueWebPlatformControlName, handler); } public async createPlatformSystemStream(): Promise<void> { this._systemStream = await this.createStream(GlueWebPlatformStreamName); } public async createWorkspacesStream(): Promise<void> { this._workspacesStream = await this.createStream(GlueWebPlatformWorkspacesStreamName); } public async createWorkspacesEventsReceiver(callback: (data: any) => void): Promise<void> { await this._systemGlue.interop.register("T42.Workspaces.Events", (args) => callback(args)); } public pushSystemMessage(domain: LibDomains, operation: string, data: any): void { if (!this._systemStream) { throw new Error(`Cannot push data to domain: ${domain}, because the system stream is not created`); } this._systemStream.push({ domain, operation, data }); } public pushWorkspacesMessage(data: any): void { if (!this._workspacesStream) { throw new Error("Cannot push data to domain: workspaces, because the workspaces stream is not created"); } this._workspacesStream.push({ data }); } public async callFrame<OutBound extends object, InBound>(operationDefinition: BridgeOperation, operationArguments: OutBound, windowId: string): Promise<InBound> { const messageData = { operation: operationDefinition.name, operationArguments }; const baseErrorMessage = `Internal Platform->Frame Communication Error. Attempted calling workspace frame: ${windowId} for operation ${operationDefinition.name} `; if (operationDefinition.dataDecoder) { const decodeResult = operationDefinition.dataDecoder.run(messageData.operationArguments); if (!decodeResult.ok) { throw new Error(`${baseErrorMessage} OutBound validation failed: ${JSON.stringify(decodeResult.error)}`); } } const result = await this.transmitMessage<InBound>(GlueWorkspaceFrameClientControlName, messageData, baseErrorMessage, { windowId }, { methodResponseTimeoutMs: 30000, waitTimeoutMs: 30000 }); if (operationDefinition.resultDecoder) { const decodeResult = operationDefinition.resultDecoder.run(result); if (!decodeResult.ok) { throw new Error(`${baseErrorMessage} Result validation failed: ${JSON.stringify(decodeResult.error)}`); } } return result; } public async callWindow<OutBound extends object, InBound>(operationDefinition: BridgeOperation, data: OutBound, windowId: string): Promise<InBound> { const operation = operationDefinition.name; const messageData = { domain: "windows", operation, data }; const baseErrorMessage = `Internal Platform->Window Communication Error. Attempted calling client window: ${windowId} for operation ${operation}. `; if (operationDefinition.dataDecoder) { const decodeResult = operationDefinition.dataDecoder.run(messageData.data); if (!decodeResult.ok) { throw new Error(`${baseErrorMessage} OutBound validation failed: ${JSON.stringify(decodeResult.error)}`); } } const result = await this.transmitMessage<InBound>(GlueClientControlName, messageData, baseErrorMessage, { windowId }, { methodResponseTimeoutMs: 30000, waitTimeoutMs: 30000 }); if (operationDefinition.resultDecoder) { const decodeResult = operationDefinition.resultDecoder.run(result); if (!decodeResult.ok) { throw new Error(`${baseErrorMessage} Result validation failed: ${JSON.stringify(decodeResult.error)}`); } } return result; } public async setInstanceStartContext(windowId: string, context: any): Promise<void> { const key = `___instance___${windowId}`; await this._systemGlue.contexts.set(key, context); } public setWindowStartContext(windowId: string, context: any): Promise<void> { return PromisePlus((resolve, reject) => { let unsub: () => void; const ready = waitFor(3, () => { resolve(); unsub(); }); const key = `___window___${windowId}`; this._clientGlue.contexts.subscribe(key, ready) .then((un) => { unsub = un; ready(); }); this._systemGlue.contexts.set(key, context).then(ready).catch(reject); }, 10000, `Timed out waiting to set the window context for: ${windowId}`); } public getServers(): Glue42Web.Interop.Instance[] { return this._clientGlue.interop.servers(); } public subscribeForServerAdded(callback: (server: Glue42Web.Interop.Instance) => void): UnsubscribeFunction { return this._clientGlue.interop.serverAdded(callback); } public subscribeForMethodAdded(callback: (method: Glue42Web.Interop.Method) => void): UnsubscribeFunction { return this._clientGlue.interop.methodAdded(callback); } public invokeMethod<T>(method: string | Glue42Web.Interop.MethodDefinition, argumentObj?: object, target?: Glue42Web.Interop.InstanceTarget, options?: Glue42Web.Interop.InvokeOptions, success?: Glue42Web.Interop.InvokeSuccessHandler<T>, error?: Glue42Web.Interop.InvokeErrorHandler): Promise<Glue42Web.Interop.InvocationResult<T>> { return this._clientGlue.interop.invoke(method, argumentObj, target, options, success, error); } private async initSystemGlue(config?: Glue42Web.Config): Promise<Glue42Core.GlueCore> { const port = await this.portsBridge.createInternalClient(); const logLevel = config?.systemLogger?.level ?? "info"; return await GlueCore({ application: "Platform", gateway: { webPlatform: { port } }, logger: logLevel }); } public setContext(name: string, data: any): Promise<void> { return this._systemGlue.contexts.set(name, data); } private registerClientWindow(isWorkspaceFrame?: boolean): void { if (isWorkspaceFrame) { const platformFrame = this.sessionStorage.getPlatformFrame(); this._platformClientWindowId = platformFrame ? platformFrame.windowId : generate(); if (!platformFrame) { const platformFrameData: FrameSessionData = { windowId: this._platformClientWindowId, active: true, isPlatform: true }; this.sessionStorage.saveFrameData(platformFrameData); } return; } const platformWindowData = this.sessionStorage.getWindowDataByName("Platform"); this._platformClientWindowId = platformWindowData ? platformWindowData.windowId : generate(); if (!platformWindowData) { this.sessionStorage.saveWindowData({ name: "Platform", windowId: this.platformWindowId }); } } private async createMethodAsync(name: string, handler: (args: any, caller: Glue42Web.Interop.Instance, success: (args?: any) => void, error: (error?: string | object) => void) => void): Promise<void> { await this._systemGlue.interop.registerAsync(name, handler); } private async createStream(name: string): Promise<Glue42Web.Interop.Stream> { return this._systemGlue.interop.createStream(name); } private async transmitMessage<T>(methodName: string, messageData: any, baseErrorMessage: string, target?: "best" | "all" | Glue42Core.Interop.Instance, options?: Glue42Core.Interop.InvokeOptions): Promise<T> { // eslint-disable-next-line @typescript-eslint/no-explicit-any let invocationResult: Glue42Core.Interop.InvocationResult<T>; try { invocationResult = await this._systemGlue.interop.invoke<T>(methodName, messageData, target, options); if (!invocationResult) { throw new Error(`${baseErrorMessage} Received unsupported result from the client - empty result`); } if (!Array.isArray(invocationResult.all_return_values) || invocationResult.all_return_values.length === 0) { throw new Error(`${baseErrorMessage} Received unsupported result from the client - empty values collection`); } } catch (error) { if (error && error.all_errors && error.all_errors.length) { // IMPORTANT: Do NOT change the `Inner message:` string, because it is used by other programs to extract the inner message of a communication error const invocationErrorMessage = error.all_errors[0].message; throw new Error(`${baseErrorMessage} -> Inner message: ${invocationErrorMessage}`); } // IMPORTANT: Do NOT change the `Inner message:` string, because it is used by other programs to extract the inner message of a communication error throw new Error(`${baseErrorMessage} -> Inner message: ${error.message}`); } return invocationResult.all_return_values[0].returned; } }
the_stack
import assert from 'assert'; import Type from '../type'; import Node, { SourceRange, NLAnnotationMap, AnnotationMap, AnnotationSpec, implAnnotationsToSource, nlAnnotationsToSource, } from './base'; import NodeVisitor from './visitor'; import { Value } from './values'; import { DeviceSelector } from './invocation'; import { BooleanExpression } from './boolean_expression'; import { PermissionFunction } from './permissions'; import { Dataset, FunctionDeclaration, TopLevelExecutableStatement } from './statement'; import { ClassDef } from './class_def'; import { FieldSlot, AbstractSlot, OldSlot } from './slots'; import * as Optimizer from '../optimize'; import TypeChecker from '../typecheck'; import convertToPermissionRule from './convert_to_permission_rule'; import SchemaRetriever from '../schema'; import { TokenStream } from '../new-syntax/tokenstream'; import List from '../utils/list'; /** * A collection of Statements from the same source file. * * It is somewhat organized for "easier" API handling, * and for backward compatibility with API users. * */ export abstract class Input extends Node { static ControlCommand : any; isControlCommand ! : boolean; static Program : any; isProgram ! : boolean; static Library : any; isLibrary ! : boolean; static PermissionRule : any; isPermissionRule ! : boolean; static DialogueState : any; isDialogueState ! : boolean; *iterateSlots() : Generator<OldSlot, void> { } *iterateSlots2() : Generator<DeviceSelector|AbstractSlot, void> { } optimize() : Input { return this; } abstract clone() : Input; /** * Typecheck this ThingTalk input. * * This is the main API to typecheck a ThingTalk input. * * @param schemas - schema retriever object to retrieve Thingpedia information * @param [getMeta=false] - retreive natural language metadata during typecheck */ abstract typecheck(schemas : SchemaRetriever, getMeta ?: boolean) : Promise<this>; } Input.prototype.isControlCommand = false; Input.prototype.isProgram = false; Input.prototype.isLibrary = false; Input.prototype.isPermissionRule = false; Input.prototype.isDialogueState = false; /** * An executable ThingTalk program (containing at least one executable * statement). * */ export class Program extends Input { classes : ClassDef[]; declarations : FunctionDeclaration[]; statements : TopLevelExecutableStatement[]; nl_annotations : NLAnnotationMap; impl_annotations : AnnotationMap; /** * Construct a new ThingTalk program. * * @param {Ast~SourceRange|null} location - the position of this node * in the source code * @param {Ast.ClassDef[]} classes - locally defined classes * @param {Ast.Statement.Declaration[]} declarations - declaration statements * @param {Ast.Statement[]} rules - executable statements (rules and commands) * @param {Ast.Value|null} principal - executor of this program * @param {Ast.Statement.OnInputChoice[]} - on input continuations of this program */ constructor(location : SourceRange|null, classes : ClassDef[], declarations : FunctionDeclaration[], statements : TopLevelExecutableStatement[], { nl, impl } : AnnotationSpec = {}) { super(location); assert(Array.isArray(classes)); this.classes = classes; assert(Array.isArray(declarations)); this.declarations = declarations; assert(Array.isArray(statements)); this.statements = statements; this.nl_annotations = nl || {}; this.impl_annotations = impl || {}; } /** * @deprecated */ get principal() : Value|null { return this.impl_annotations.executor || null; } toSource() : TokenStream { let input : TokenStream = List.concat( nlAnnotationsToSource(this.nl_annotations), implAnnotationsToSource(this.impl_annotations), '\n', ); for (const classdef of this.classes) input = List.concat(input, classdef.toSource(), '\n'); for (const decl of this.declarations) input = List.concat(input, decl.toSource(), '\n'); for (const stmt of this.statements) input = List.concat(input, stmt.toSource(), '\n'); return input; } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitProgram(this)) { for (const classdef of this.classes) classdef.visit(visitor); for (const decl of this.declarations) decl.visit(visitor); for (const rule of this.statements) rule.visit(visitor); } visitor.exit(this); } *iterateSlots() : Generator<OldSlot, void> { for (const decl of this.declarations) yield* decl.iterateSlots(); for (const rule of this.statements) yield* rule.iterateSlots(); } *iterateSlots2() : Generator<DeviceSelector|AbstractSlot, void> { if (this.principal) yield new FieldSlot(null, {}, new Type.Entity('tt:contact'), this.impl_annotations, 'program', 'executor'); for (const decl of this.declarations) yield* decl.iterateSlots2(); for (const rule of this.statements) yield* rule.iterateSlots2(); } clone() : Program { // clone annotations const nl : NLAnnotationMap = {}; Object.assign(nl, this.nl_annotations); const impl : AnnotationMap = {}; Object.assign(impl, this.impl_annotations); const annotations : AnnotationSpec = { nl, impl }; return new Program( this.location, this.classes.map((c) => c.clone()), this.declarations.map((d) => d.clone()), this.statements.map((s) => s.clone()), annotations); } optimize() : this { return Optimizer.optimizeProgram(this); } async typecheck(schemas : SchemaRetriever, getMeta = false) : Promise<this> { const typeChecker = new TypeChecker(schemas, getMeta); await typeChecker.typeCheckProgram(this); return this; } /** * Attempt to convert this program to an equivalent permission rule. * * @param principal - the principal to use as source * @param contactName - the display value for the principal * @return the new permission rule, or `null` if conversion failed */ convertToPermissionRule(principal : string, contactName : string|null) : PermissionRule|null { return convertToPermissionRule(this, principal, contactName); } } Program.prototype.isProgram = true; Input.Program = Program; /** * An ThingTalk program definining a permission control policy. * */ export class PermissionRule extends Input { principal : BooleanExpression; query : PermissionFunction; action : PermissionFunction; /** * Construct a new permission rule. * * @param {Ast~SourceRange|null} location - the position of this node * in the source code * @param {Ast.BooleanExpression} principal - the predicate selecting * the source of the program this rule is applicable to * @param {Ast.PermissionFunction} query - a permission function for the query part * @param {Ast.PermissionFunction} action - a permission function for the action part */ constructor(location : SourceRange|null, principal : BooleanExpression, query : PermissionFunction, action : PermissionFunction) { super(location); assert(principal instanceof BooleanExpression); this.principal = principal; assert(query instanceof PermissionFunction); this.query = query; assert(action instanceof PermissionFunction); this.action = action; } toSource() : TokenStream { let list : TokenStream = List.concat('$policy', '{', '\t+', '\n', this.principal.toSource(), ':'); if (this.query.isBuiltin) list = List.concat(list, 'now'); else list = List.concat(list, this.query.toSource()); list = List.concat(list, '=>', this.action.toSource(), ';', '\t-', '\n', '}'); return list; } optimize() : this { this.principal = this.principal.optimize(); this.query.optimize(); this.action.optimize(); return this; } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitPermissionRule(this)) { this.principal.visit(visitor); this.query.visit(visitor); this.action.visit(visitor); } visitor.exit(this); } *iterateSlots() : Generator<OldSlot, void> { yield* this.principal.iterateSlots(null, null, {}); const [,scope] = yield* this.query.iterateSlots({}); yield* this.action.iterateSlots(scope); } *iterateSlots2() : Generator<DeviceSelector|AbstractSlot, void> { yield* this.principal.iterateSlots2(null, null, {}); const [,scope] = yield* this.query.iterateSlots2({}); yield* this.action.iterateSlots2(scope); } clone() : PermissionRule { return new PermissionRule(this.location, this.principal.clone(), this.query.clone(), this.action.clone()); } async typecheck(schemas : SchemaRetriever, getMeta = false) : Promise<this> { const typeChecker = new TypeChecker(schemas, getMeta); await typeChecker.typeCheckPermissionRule(this); return this; } } PermissionRule.prototype.isPermissionRule = true; Input.PermissionRule = PermissionRule; /** * An ThingTalk input file containing a library of classes and datasets. * */ export class Library extends Input { classes : ClassDef[]; datasets : Dataset[]; /** * Construct a new ThingTalk library. * * @param {Ast~SourceRange|null} location - the position of this node * in the source code * @param {Ast.ClassDef[]} classes - classes defined in the library * @param {Ast.Dataset[]} datasets - datasets defined in the library */ constructor(location : SourceRange|null, classes : ClassDef[], datasets : Dataset[]) { super(location); assert(Array.isArray(classes)); this.classes = classes; assert(Array.isArray(datasets)); this.datasets = datasets; } toSource() : TokenStream { let input : TokenStream = List.Nil; for (const classdef of this.classes) input = List.concat(input, classdef.toSource(), '\n'); for (const dataset of this.datasets) input = List.concat(input, dataset.toSource(), '\n'); return input; } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitLibrary(this)) { for (const classdef of this.classes) classdef.visit(visitor); for (const dataset of this.datasets) dataset.visit(visitor); } visitor.exit(this); } *iterateSlots() : Generator<OldSlot, void> { for (const dataset of this.datasets) yield* dataset.iterateSlots(); } *iterateSlots2() : Generator<DeviceSelector|AbstractSlot, void> { for (const dataset of this.datasets) yield* dataset.iterateSlots2(); } clone() : Library { return new Library(this.location, this.classes.map((c) => c.clone()), this.datasets.map((d) => d.clone())); } optimize() : Library { for (const d of this.datasets) d.optimize(); return this; } async typecheck(schemas : SchemaRetriever, getMeta = false) : Promise<this> { const typeChecker = new TypeChecker(schemas, getMeta); await typeChecker.typeCheckLibrary(this); return this; } } Library.prototype.isLibrary = true; Input.Library = Library;
the_stack